file_id
int64 1
66.7k
| content
stringlengths 14
343k
| repo
stringlengths 6
92
| path
stringlengths 5
169
|
---|---|---|---|
65,960 | import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class GameF extends JFrame {
public GameF() {
Container contentPane = getContentPane();
final Panel panel = new Panel();
panel.setBackground(new Color(255, 182, 147));
contentPane.setBackground(new Color(255, 182, 147));
contentPane.add(panel);
setSize(560, 560);
setTitle("My Gobang");
setResizable(false);
panel.setCursor(new Cursor(Cursor.HAND_CURSOR));
JMenuBar menuBar=new JMenuBar();
JMenu menu=new JMenu("选项");
JMenuItem menuStart=new JMenuItem("开始游戏");
menuStart.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
panel.ResetGame();
panel.repaint();
}
});
JMenuItem menuExit =new JMenuItem("退出");
menuExit.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
menuBar.add(menu);
menu.add(menuStart);
menu.add(menuExit);
this.setJMenuBar(menuBar);
}
}
| Parksmith/gobang | 1.0/GameF.java |
65,961 | import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class EndFenestra {
private JFrame bufo;
private static JButton b6;
private static JButton b5;
public EndFenestra(String n,double k,int b) {
b6 = new JButton("最终基因型:"+b+" 适应度结果为:"+k+" 退出");
bufo=new JFrame(n);
bufo.setSize(400,400);
bufo.setLayout(new FlowLayout());
bufo.add(b6);
b6.setSize(150,50);
bufo.setBackground(Color.green);
bufo.setVisible(true);
bufo.setDefaultCloseOperation(bufo.EXIT_ON_CLOSE);
b6.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
bufo.dispose();
}
});
}
public EndFenestra(String n,String k) {
b6 = new JButton("退出");
b5 = new JButton(k);
bufo=new JFrame(n);
bufo.setSize(400,400);
bufo.setLayout(new FlowLayout());
bufo.add(b5);
bufo.add(b6);
b6.setSize(150,50);
bufo.setBackground(Color.green);
bufo.setVisible(true);
bufo.setDefaultCloseOperation(bufo.EXIT_ON_CLOSE);
b6.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
bufo.dispose();
}
});
}
}
| Luke-lujunxian/Amazing-animals | src/EndFenestra.java |
65,962 | package View;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.paint.Color;
import javafx.stage.StageStyle;
import java.io.IOException;
/**
* 邓鹏飞
* 登入界面
*/
public class Dialog extends window {
public Dialog() throws IOException {
root = FXMLLoader.load(getClass().getResource("Fxml/Dialog.fxml"));
Scene scene = new Scene(root, 450, 480);
scene.setFill(Color.TRANSPARENT);
setScene(scene);
initStyle(StageStyle.TRANSPARENT);
setResizable(false);
setTitle("We Chat");
move();
quit();
setIcon();
minimiser();
}
/**
* 退出
*/
@Override
public void quit() {
((Button) $("quit1")).setTooltip(new Tooltip("退出"));
((Button) $("quit1")).setOnAction(event -> {
close();
System.exit(0);
});
}
@Override
public void minimiser() {
((Button) $("minimiser1")).setTooltip(new Tooltip("最小化"));
((Button) $("minimiser1")).setOnAction(event -> {
setIconified(true);
});
}
/**
* 设置错误提示
* @param id
* @param Text
*/
public void setErrorTip(String id,String Text){
((Label) $(id)).setText(Text);
}
/**
* 重置错误提醒
*/
public void resetErrorTip(){
setErrorTip("accountError", "");
setErrorTip("passwordError", "");
}
/*
清除各种输入框
*/
public void clear(){
((TextField) $("UserName")).clear();
((PasswordField) $("Password")).clear();
}
public void clear(String id){
((TextField) $(id)).clear();
}
}
| sundial-dreams/WeChatClient | src/View/Dialog.java |
65,966 | package client;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import task.DBBean;
import java.io.*;
import java.net.*;
import java.sql.ResultSet;
import java.sql.SQLException;
/**@author lpm
*聊天室客户端主程序
*这是运行聊天室客户端程序的入口
*/
public class Client implements ActionListener{
private LogonPane logonPane;//登录界面
private ClientModel client;//客户端数据模型
private ClientUI clientUI;//客户端聊天界面
private JButton enterButton,exitButton,regstButton;//登录,注册按钮
/**
*登录容器,本程序的设计是将登录窗口和聊天窗口分别采用两个JFrame盛放
*当登录成功时,登录窗口隐藏,显示聊天容器,当意外断开连接时,再次显示
*登录窗口以便重新登录。所以有必要设置一个logonFrame指针。
*/
private JFrame logonFrame;
/**
*构造方法,用于创建登录界面
*/
public Client() {
logonFrame=new JFrame("登录");
//将登录界面各元素加入登录窗口
Container contentPane=logonFrame.getContentPane();
logonPane=new LogonPane();
regstButton=new JButton("注册");
enterButton=new JButton("登录");
exitButton=new JButton("退出");
logonPane.setRelatedButton(enterButton);
regstButton.addActionListener(this);//注册用户
enterButton.addActionListener(this);
exitButton.addActionListener(this);
JPanel controlPane=new JPanel();
controlPane.add(regstButton);
controlPane.add(enterButton);
controlPane.add(exitButton);
contentPane.add(logonPane,BorderLayout.CENTER);
contentPane.add(controlPane,BorderLayout.SOUTH);
}
/**
* Method main
*
*
* @param args
*
*/
public static void main(String[] args) {
// TODO: 在这添加你的代码
try{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}catch(Exception e){
e.printStackTrace();
}
createAndShowGUI();
}
/**
*按钮事件处理
*此事件源包括"登录"、"退出"两个按钮。
*/
@SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent e) {
// "登录"按钮的事件处理,此过程包括连接服务器,创建聊天界面以及各种异常处理
if(e.getSource()==enterButton){
String ip=logonPane.getIP();
String name=logonPane.getName();
String pwd=logonPane.getpsw();
if (isok(name,pwd)) {
int port;
//=============================
try{
port=logonPane.getPort();
}catch(NumberFormatException ne){
//非数字字符在端口一栏
JOptionPane.showMessageDialog(logonFrame,ne.getMessage());
return;
}
//=============================
try{
client=new ClientModel(ip,port); //创建一个客户端
}catch(java.net.UnknownHostException ue){ //ip地址出错
JOptionPane.showMessageDialog(logonFrame,"不可知的服务器:"+ue.getMessage());
return;
}catch(IOException ie){
JOptionPane.showMessageDialog(logonFrame,ie.getMessage());
return;
}
//===================用户名的处理
boolean valid;
try{
valid=client.validate(name);
}catch(IOException ie){
JOptionPane.showMessageDialog(logonFrame,"服务器连接已满,请稍后重试!");
return;
}
//=============================
if(!valid){
JOptionPane.showMessageDialog(logonFrame,"无效或已经被使用的名字:"+name);
return;
}else{
clientUI=new ClientUI(client){
protected void doWhenStop(){
JOptionPane.showMessageDialog(clientUI,"与服务器的连接中断,请重新登录。");
clientUI.dispose();
logonFrame.show();
}
};
clientUI.setTitle(client.name+" 的聊天室");
clientUI.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
clientUI.setLocationRelativeTo(logonFrame);
clientUI.show();
client.start();
logonFrame.dispose();
}
}else {
JOptionPane.showMessageDialog(logonFrame,"数据库验证时无效或已经被使用的名字:"+name);
}
}else if(e.getSource()==exitButton){
System.exit(1);
}else if (e.getSource()==regstButton) {
RegistPanel registPanel = new RegistPanel();
registPanel.setVisible(true);
registPanel.setSize(300, 200);
registPanel.show();
}
}
/**
*退出处理,加入一个选择对话框
*/
protected void exit(){
int option=JOptionPane.showConfirmDialog(logonFrame,"程序正连接到服务器上,您确定退出吗?",
"请您选择",JOptionPane.YES_NO_OPTION);
if(option==JOptionPane.YES_OPTION)
System.exit(0);
}
public static void createAndShowGUI(){
JFrame frame=new Client().logonFrame;
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.show();
}
private boolean isok(String name,String pwd) {
DBBean bean = new DBBean();
bean.init();
String sql = "select * from user where " +
"userName='"+name+"'";
ResultSet rs = bean.executeQuery(sql);
try {
if (rs.next()) {
String dbpwd = rs.getString("userPWD");
System.out.println("***************"+dbpwd);
if (pwd.equals(dbpwd)) {
return true;
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
| lipengming/communication | src/client/Client.java |
65,968 | import java.lang.Override;
import java.lang.Runnable;
import java.lang.System;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.Thread;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.util.ArrayList;
public class WifiServer{
private static ServerSocket servers;
private static boolean exit = false;
private static String saveFilesPath;
private static Socket connectSocket;
private static InputStream ipstream;
private static FileOutputStream fileopstream;
private static long fileSize = 0;
public static void main(String[] args){
saveFilesPath = "/home/fg607/WifiSharedFolder";
startSocketServer();
System.out.println("等待接收文件......(输入'exit'退出)");
String str;
InputStreamReader stdin = new InputStreamReader(System.in);//get console input
BufferedReader bufin = new BufferedReader(stdin);
while (!exit){
try {
str = bufin.readLine();
if(str.equals("exit")){
exit = true;
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(100);
System.exit(0);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}).start();
}else {
System.out.println("不能识别的命令!!!");
}
}catch (IOException e){
System.out.println("获取命令出错!!!");
}
}
try {
servers.close();
}catch (IOException e){
System.out.println("关闭服务异常!!!");
}
}
public static void startSocketServer(){
//create a new thread to start server
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
try {
if(servers == null){
servers = new ServerSocket(2008);
}
while(!exit)
{
try {
connectSocket = servers.accept();
new SocketThread(connectSocket).start();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("服务关闭!");
}
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("创建服务失败!!!");
}
}
}).start();
}
static class SocketThread extends Thread{
private Socket socket = null;
public SocketThread(Socket socket){
this.socket = socket;
}
public void run(){
//obtain translate filename and create the same file
int fileNumber = receiveFileNmber(socket);
if(fileNumber == -1 || fileNumber < 0){
return;
}
for(int i =0;i< fileNumber;i++){
File file = createFile(socket,saveFilesPath);
if(file == null)
return;
//notify custom to translate file
noticeReady(socket,"transmitready");
//start translating
receiveFileData(socket,file);
}
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("关闭端口异常");
}
}
}
public static int receiveFileNmber(Socket socket){
InputStream ipstream = null;
String receiveData;
int number ;
try {
ipstream = socket.getInputStream();
byte[] buffer = new byte[1024];
int temp = 0;
temp = ipstream.read(buffer);
if(temp!=-1){
receiveData = new String(buffer,0,temp);
return Integer.parseInt(receiveData);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return -1;
}
public static File createFile(Socket socket,String path){
InputStream ipstream = null;
File file = null;
String filename = null;
String receiveData;
try {
ipstream = socket.getInputStream();
byte[] buffer = new byte[1024];
int temp = 0;
temp = ipstream.read(buffer);
if(temp!=-1)
receiveData = new String(buffer,0,temp);
else
return file;
int flag = receiveData.indexOf("$#$",0);
filename = receiveData.substring(0, flag);
fileSize = Long.decode(receiveData.substring(flag+3));
String filepath = path+"/"+filename;
File folder = new File(path);
if(!folder.exists())
folder.mkdir();
file = new File(filepath);
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("网络异常,文件接受失败!!!");
}
return file;
}
public static void noticeReady(Socket socket,String msg){
OutputStream opstream = null;
try {
opstream = socket.getOutputStream();
opstream.write(msg.getBytes());
opstream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void receiveFileData(Socket socket,File file){
String fileName = file.getName();
try {
ipstream = socket.getInputStream();
fileopstream = new FileOutputStream(file);
byte[] buffer = new byte[1024*1024];
int temp = 0;
System.out.println("********************************");
String str = "正在接收文件" + fileName + "...........";
System.out.println(str);
System.out.println("--------------------------------");
int receiveSize = 0;
while((temp= ipstream.read(buffer))!= -1){
fileopstream.write(buffer, 0, temp);
receiveSize += temp;
if(receiveSize == fileSize){
break;
}
}
if(receiveSize != fileSize){
deleteFile(file);
str = "网络出现异常,文件接收失败!";
System.out.println(str);
System.out.println("********************************");
System.out.println("等待接收文件......(输入'exit'退出)");
return;
}
fileopstream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
deleteFile(file);
String str = "网络出现异常,文件接收失败!";
System.out.println(str);
System.out.println("********************************");
System.out.println("等待接收文件......(输入'exit'退出)");
return;
}
String str = fileName +"接收完毕!";
System.out.println(str);
System.out.println("********************************");
System.out.println("等待接收文件......(输入'exit'退出)");
}
public static void deleteFile(File file){
if(file.exists()){
file.delete();
}
}
}
| fg607/WiFi-ShareFile | java/WifiServer.java |
65,969 | import java.util.Scanner;
class Player {
private String[][] mapInfo; // 用于存放地图信息
private Scanner keyboard = new Scanner(System.in); // 用于接收用户输入
private Scanner userXY; // 用于从用户输入中读取用户座标
public Player(Maze maze){
mapInfo = maze.getMap();
}
public void play(){
while(true){
System.out.print("Enter a cell (row and colum; zeros to exit): ");
// 读取一行用户输入
String userInput = keyboard.nextLine();
// 读取用户座标
userXY = new Scanner(userInput);
int x = 0; int y = 0;
// 读取用户座标 x
// 当用户座标 x 不存在时跳出本循环
if (userXY.hasNextInt()) {
x = userXY.nextInt();
} else {
continue;
}
// 读取用户座标 y
// 当用户座标 y 不存在时跳出本循环
if (userXY.hasNextInt()) {
y = userXY.nextInt();
} else {
continue;
}
// Play
if (isQuit(x, y)) {
// 退出
System.out.println("Goodbye");
userXY.close();
keyboard.close();
break;
} else if (isOverflow(x, y)) {
// 溢出
System.out.println("(" + x + ", " + y + ") is out of the maze");
userXY.close();
} else if (isTreasure(x, y)) {
// 获得宝箱
System.out.println("(" + x + ", " + y + ") is a treasure");
userXY.close();
} else if (isObstacle(x, y)) {
// 撞墙
System.out.println("(" + x + ", " + y + ") is within an obstacle");
userXY.close();
} else {
// 空格子
System.out.println("(" + x + ", " + y + ") is an empty cell");
userXY.close();
}
}
}
// 判断是否为退出信号
private boolean isQuit(int x, int y){
if (x == 0 && y == 0){
return true;
} else {
return false;
}
}
// 判断是否溢出
private boolean isOverflow(int x, int y){
if ((x <= 0) || (y <= 0) || (x >= mapInfo.length-1) || (y >= mapInfo[0].length-1)) {
return true;
} else {
return false;
}
}
// 判断是否得到宝箱
private boolean isTreasure(int x, int y){
if ("$".equals(mapInfo[x][y])){
return true;
} else {
return false;
}
}
// 判断是否撞墙
private boolean isObstacle(int x, int y){
if ("*".equals(mapInfo[x][y])){
return true;
} else {
return false;
}
}
} | mogeko/hw01_partI | src/Player.java |
65,972 | package panel;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import com.mxxy.game.base.Panel;
import com.mxxy.game.event.PanelEvent;
import com.mxxy.game.handler.AbstractPanelHandler;
import com.mxxy.game.ui.Announcer;
import com.mxxy.game.utils.Constant;
import com.mxxy.game.utils.RuntimeUtil;
/**
* HomePager (主页)
* @author ZAB
* 邮箱 :[email protected]
*/
@SuppressWarnings("rawtypes")
final public class HomePager extends AbstractPanelHandler{
public static boolean isfrist;
@Override
public void init(PanelEvent evt) {
super.init(evt);
System.out.println("HomePager"+panel);
if(!isfrist)
showAnnouncer();
isfrist=true;
}
@Override
protected void initView() {
}
/**
* 进入游戏
*/
public void enter(ActionEvent e){
Panel openHeadPet = uihelp.getPanel(e);
showHide(openHeadPet);
}
/**
* 注册用户
*/
public void register(ActionEvent e){
Panel dlg = uihelp.getPanel("RegistUser");
uihelp.showPanel(dlg);
}
/**
* 游戏主页
*/
private Announcer pager;
public void web(ActionEvent e){
showAnnouncer();
}
/**
* 报幕
*/
public void showAnnouncer(){
pager=new Announcer();
Thread thread=new Thread(pager);
thread.start();
panel.add(pager,0);
pager.setBounds(0, 0, Constant.WINDOW_WIDTH, Constant.WINDOW_HEIGHT);
pager.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
panel.remove(pager);
pager.setStop(false);
pager=null;
}
});
}
/**
* 游戏充值
*/
public void pay(ActionEvent e){
RuntimeUtil.exec("cmd /c start www.baidu.com");
}
/**
* 点击梦幻西游LOGO
* @param e
*/
public void logo(ActionEvent e){
RuntimeUtil.exec("cmd /c start www.baidu.com");
}
/**
* 退出
*/
public void exit(ActionEvent e){
application.exitGame();
}
}
| tommyadan/mxxy | script/HomePager.java |
65,973 | package Day31;
import java.util.Scanner;
public class Product {
//成员变量
static String[] names = {"iPhoneXS", "华为 Mate 20 Pro", "小米X", "Vivo NEX", "Oppo Find"};
static double[] price = {8999, 5399, 2399, 4399, 3999};
static int[] numbers = {50, 20, 80, 120, 90};
public static void main(String[] args) {
/*
*-------------------
* 1. 商品列表
* 2. 商品录入
* 3. 商品查询
* 4. 统计信息
* 5. 退出
*-------------------
* 选择: > 1
* ....
*/
//死循环显示菜单
outer:
while (true) {
//显示菜单,并获得选择的值
int c = menu();
//判断c的值
switch (c) {
case 1: f1(); break;
case 2: f2(); break;
case 3: f3(); break;
case 4: f4(); break;
case 5: break outer;
}
}
}
private static int menu() {
System.out.println("-------------------");
System.out.println("1. 商品列表");
System.out.println("2. 商品录入");
System.out.println("3. 商品查询");
System.out.println("4. 统计信息");
System.out.println("5. 退出");
System.out.println("-------------------");
System.out.println("选择: > ");
return new Scanner(System.in).nextInt();
}
private static void f1() {
//逐行打印出商品名称,价格和数量
for (int i = 0; i < names.length; i++) {
String n = names[i];
double p = price[i];
int b = numbers[i];
System.out.println((i+ 1) + " " + n + ", 价格 " + p + ", 数量 " + b);
}
}
private static void f2() {
for (int i = 0; i <= names.length; i++) {
System.out.println("录入第" + (i+1) + "件商品:");
System.out.println("名称:");
String n = new Scanner(System.in).nextLine();
System.out.println("价格:");
double p = new Scanner(System.in).nextDouble();
System.out.println("数量:");
int b = new Scanner(System.in).nextInt();
names[i] = n;
price[i] = p;
numbers[i] = b;
}
//重新显示商品列表
f1();
}
private static void f3() {
System.out.println("请输入要查询的商品名称:");
String n = new Scanner(System.in).nextLine();
for (int i = 0; i < names.length; i++) {
if (n.equals(names[i])) {
String name = names[i];
double p = price[i];
int b = numbers[i];
System.out.println((i + 1) + "名称:" + name + ", 价格:" + p + ", 数量:" + b);
return;
}
}
//循环结束,所有商品都比较完,没有找到该商品。
System.out.println("没有找到该商品。");
}
private static void f4() {
//商品总价,单价总价,最高单价,最高总价
double spzj = 0;
double djzj = 0;
double zgdj = 0;
double zgzj = 0;
for (int i = 0; i < names.length; i++) {
spzj += price[i] * numbers[i];
djzj += price[i];
if (price[i] > zgdj) {
zgdj = price[i];
}
if (price[i] * numbers[i] > zgzj) {
zgzj = price[i] * numbers[i];
}
}
System.out.println("商品总价:" + spzj);
System.out.println("单价总价:" + djzj);
System.out.println("最高单价:" + zgdj);
System.out.println("最高总价:" + zgzj);
}
}
| geekqq/Java-Algo | Day31/Product.java |
65,974 | package UI;
import Controllers.LoginControllers;
import UI.Dialog.Tips;
import UI.Dialog.ExitTips;
import Utils.Db;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Objects;
public class LoginUI {
private static final Db db = new Db();
private static JFrame lFrame;
private static Container c;
private static final JLabel a1 = new JLabel("用户名");
private static final JTextField username = new JTextField();
private static final JLabel a2 = new JLabel("密 码");
private static final JPasswordField password = new JPasswordField();
private static final JButton okbtn = new JButton("登入");
private static final JButton cancelbtn = new JButton("退出");
private static final JButton dbcbtn = new JButton("数据库配置");
public static void create() {
lFrame = new Window().create("登入", 600, 200, 300, 220);
c = lFrame.getContentPane();
//设置一层相当于桌布的东西
c.setLayout(new BorderLayout());//布局管理器
//设置按下右上角X号后关闭
lFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//初始化--往窗体里放其他控件
init();
//设置窗体可见
lFrame.setVisible(true);
checksql();
}
public static void checksql() {
boolean dbstatus = db.check();
if (!dbstatus) {
new Tips().create("无法连接至数据库!\n程序即将退出。", "错误", 0);
System.exit(0);
}
}
public static void init() {
/*标题部分--North*/
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new FlowLayout());
titlePanel.add(new JLabel("学生管理系统"));
c.add(titlePanel, "North");
/*输入部分--Center*/
JPanel fieldPanel = new JPanel();
fieldPanel.setLayout(null);
a1.setBounds(50, 20, 50, 20);
a2.setBounds(50, 60, 50, 20);
fieldPanel.add(a1);
fieldPanel.add(a2);
username.setBounds(110, 20, 120, 20);
password.setBounds(110, 60, 120, 20);
fieldPanel.add(username);
password.setFont(new Font("宋体", Font.PLAIN, 18));
fieldPanel.add(password);
c.add(fieldPanel, "Center");
/*按钮部分--South*/
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
buttonPanel.add(okbtn);
buttonPanel.add(cancelbtn);
buttonPanel.add(dbcbtn);
c.add(buttonPanel, "South");
// 绑定按钮监听器
addActionListener(okbtn);
addActionListener(cancelbtn);
addActionListener(dbcbtn);
// 绑定输入框监听器
addKeyListener(username);
addKeyListener(password);
}
// 登入触发
private static void isLogin() {
LoginControllers lc = new LoginControllers();
Boolean status = lc.StartLogin(username.getText(), new String(password.getPassword()));
if (status) {
// 此处应销毁本窗口并创建Mange窗口
MangeUI mFrame = new MangeUI();
mFrame.create(); // 打开新界面
lFrame.dispose();
} else {
new Tips().create("登入失败:用户名或密码错误!", "错误", 0);
}
}
// 添加按钮监听器
private static void addActionListener(JButton btn) {
// 为按钮绑定监听器
btn.addActionListener(e -> {
// 对话框
if (Objects.equals(e.getActionCommand(), "登入")) {
if (username.getText().length() > 0 && new String(password.getPassword()).length() > 0) {
isLogin();
} else {
new Tips().create("登入失败:用户名和密码不能为空!", "错误", 0);
}
}
if (Objects.equals(e.getActionCommand(), "退出")) {
new ExitTips().Exit();
}
if (Objects.equals(e.getActionCommand(), "数据库配置")) {
lFrame.dispose();
new DbConfigUI().create();
}
});
}
// 添加按键监听器
private static void addKeyListener(JTextField text) {
text.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
super.keyTyped(e);
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
isLogin();
}
}
});
}
} | Kurokitu/StudentManage | src/UI/LoginUI.java |
65,975 | import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
/**
* @author Guoooozy
* @date 2019/12/11 - 15:49
* 该类是登录成功之后的frame
*/
public class AfterLogin extends JFrame implements ActionListener {
JButton jcun,jyu,jcatch,jtrans,jout;//存,余额,取,转,退出
JLabel jLabel;
public String order;
public AfterLogin(String order)
{
this.order=order;
jcun=new JButton("存钱");
jyu=new JButton("余额");
jcatch=new JButton("取钱");
jtrans=new JButton("转账");
jout=new JButton("退出");
//设置监听
jcun.addActionListener(this);
jout.addActionListener(this);
jtrans.addActionListener(this);
jcatch.addActionListener(this);
jyu.addActionListener(this);
jLabel=new JLabel("您好,欢迎使用网上银行系统");
jLabel.setFont(new java.awt.Font("Dialog",1,23));
this.setTitle("网上银行");//标题
this.setSize(510,500);//设置大小
this.setLocation(400,200);//设置位置
this.setLayout(null);
jcun.setBounds(10,270,80,60);
jcatch.setBounds(110,270,80,60);
jtrans.setBounds(210,270,80,60);
jyu.setBounds(310,270,80,60);
jout.setBounds(410,270,80,60);
jLabel.setBounds(100,120,300,50);
this.add(jcatch);
this.add(jcun);
this.add(jLabel);
this.add(jout);
this.add(jtrans);
this.add(jyu);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);//设置可关闭
this.setVisible(true);//设置可见
this.setResizable(false);//设置不可拉伸
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand()=="存钱")
{
new Save(this.order);
//this.setVisible(false);//设置不可见
}
else if(e.getActionCommand()=="取钱")
{
new Catch(this.order);
//this.setVisible(false);//设置不可见
}
else if(e.getActionCommand()=="转账")
{
new Transfer(this.order);
}
else if(e.getActionCommand()=="余额")
{
new Show(this.order);
}
else
{
System.exit(0);
}
}
}
| Guoooozy/184804163guozhuoying | src/AfterLogin.java |
65,976 | import java.sql.*;
public class OutsourcerView
{
public static String action = "/";
public static String focus = "style=\"background-color:#707070\" ";
public static String viewSearch(String formAction, String search, String limit, String offset, String sortBy, String sort, String myScript)
{
String searchHTML = setHTMLField(search);
String msg = viewHeader(myScript, "", formAction);
msg += "<form name=\"myForm\" id=\"myForm\" action=\"" + formAction + "\" method=\"post\">\n";
msg += "<table class=\"ostable\">\n";
msg += "<tr>\n";
msg += "<td colspan=\"4\"><input type=\"text\" id=\"search\" name=\"search\" size=\"100\" value=" + searchHTML +">\n";
msg += "<td width=\"20\"><b>Limit</b></td><td width=\"20\" align=\"left\"><select name=\"limit\">\n";
msg += "<option value=\"10\"";
if (limit.equals("10"))
msg += " selected";
msg += ">10</option>\n";
msg += "<option value=\"20\"";
if (limit.equals("20"))
msg += " selected";
msg += ">20</option>\n";
msg += "<option value=\"30\"";
if (limit.equals("30"))
msg += " selected";
msg += ">30</option>\n";
msg += "<option value=\"\"";
if (limit.equals(""))
msg += " selected";
msg += ">All</option>\n";
msg += "</select></td>\n";
msg += "<td align=\"left\"><button onclick=\"formSubmit(0)\">Search</button></td>\n";
msg += "</tr>\n";
msg += "<input type=\"hidden\" id=\"offset\" name=\"offset\" value=\"" + offset + "\">\n";
msg += "<input type=\"hidden\" id=\"sort_by\" name=\"sort_by\" value=\"" + sortBy + "\">\n";
msg += "<input type=\"hidden\" id=\"sort\" name=\"sort\" value=\"" + sort + "\">\n";
msg += "<input type=\"hidden\" id=\"action_type\" name=\"action_type\" value=\"\">\n";
msg += "<input type=\"hidden\" id=\"queueID\" name=\"queueID\" value=\"\">\n";
msg += "<input type=\"hidden\" id=\"queue_action\" name=\"queue_action\" value=\"\">\n";
msg += "<input type=\"hidden\" id=\"id\" name=\"id\" value=\"\">\n";
msg += "<input type=\"hidden\" id=\"description\" name=\"description\" value=\"\">\n";
msg += "<input type=\"hidden\" id=\"submit_form\" name=\"submit_form\" value=\"1\">\n";
msg += "</table>\n";
return msg;
}
public static String getHead(String myScript, String onLoad)
{
String tableBgColor= "#EE7600";
String fontColor = "#000080";
String borderColor = "#7A9DCC";
String msg = "<html><head>\n";
msg += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
msg += "<style type=\"text/css\">\n";
msg += "p{font-family:Arial, Helvetica, sans-serif}\n";
msg += "h1{font-family:Arial, Helvetica, sans-serif}\n";
msg += "h2{font-family:Arial, Helvetica, sans-serif}\n";
msg += "h3{font-family:Arial, Helvetica, sans-serif}\n";
msg += "h4{font-family:Arial, Helvetica, sans-serif}\n";
msg += "h5{font-family:Arial, Helvetica, sans-serif}\n";
msg += "a:link {color:" + fontColor + ";text-decoration:none;}\n";
msg += "a:visited {color:" + fontColor + ";text-decoration:none;}\n";
msg += "a:hover {color:#000000;text-decoration:none;}\n";
msg += "a:active {color:#000000;text-decoration:none;}\n";
msg += "a.m1:link {color:" + fontColor + ";text-decoration:none;}\n";
msg += "a.m1:visited {color:" + fontColor + ";text-decoration:none;}\n";
msg += "a.m1:hover {color:#FFFFFF;text-decoration:none;}\n";
msg += "a.m1:active {color:#FFFFFF;text-decoration:none;}\n";
msg += "a.m2:link {color:#FFFFFF;text-decoration:none;}\n";
msg += "a.m2:visited {color:#FFFFFF;text-decoration:none;}\n";
msg += "a.m2:hover {color:#FFFFFF;text-decoration:none;}\n";
msg += "a:m2:active {color:#FFFFFF;text-decoration:none;}\n";
msg += "table.ostable {font-family:Arial, Helvetica, sans-serif;font-size:12px;color:#333333;width:100%;border-width: 0px;border-collapse: collapse;}\n";
msg += "table.tftable {font-family:Arial, Helvetica, sans-serif;font-size:12px;color:#333333;width:100%;border-width: 1px;border-color: " + borderColor + ";border-collapse: collapse;}\n";
msg += "table.logintable {font-family:Arial, Helvetica, sans-serif;font-size:14px;color:#333333;border-width: 1px;border-color: " + borderColor + ";border-collapse: collapse;}\n";
msg += "table.logintable th {font-family:Arial, Helvetica, sans-serif;font-size:14px;color:#FF0000;}\n";
msg += "table.tftable th {font-family:Arial, Helvetica, sans-serif;font-size:12px;background-color:" + tableBgColor + ";border-width: 1px;padding: 8px;border-style: solid;border-color: " + borderColor + ";text-align:center;}\n";
msg += "table.tftable tr {background-color:#ffffff;}\n";
msg += "table.tftable td {font-family:Arial, Helvetica, sans-serif;font-size:12px;border-width: 1px;padding: 8px;border-style: solid;border-color: " + borderColor + ";}\n";
msg += "#table-wrapper {position:relative;}\n";
msg += "#table-scroll {height:250px;overflow:auto;margin-top:20px;}\n";
msg += "#table-wrapper table {width:100%;}\n";
msg += "</style>\n";
if (!myScript.equals(""))
{
msg += "<script type=\"text/javascript\">\n";
msg += myScript + "\n";
msg += "</script>\n";
}
msg += "</head>\n";
if (!onLoad.equals(""))
{
msg += "<body onload=\"" + onLoad + "\">\n";
}
else
{
msg += "<body>\n";
}
return msg;
}
public static String viewHeader(String myScript, String onLoad, String page)
{
String externalHighlight = "class=\"m1\" ";
String jobsHighlight = "class=\"m1\" ";
String queueHighlight = "class=\"m1\" ";
String scheduleHighlight = "class=\"m1\" ";
String environmentHighlight = "class=\"m1\" ";
String customHighlight = "class=\"m1\" ";
String highlight = "class=\"m2\" ";
if (page.equals("external"))
externalHighlight = highlight;
else if (page.equals("jobs"))
jobsHighlight = highlight;
else if (page.equals("queue"))
queueHighlight = highlight;
else if (page.equals("schedule"))
scheduleHighlight = highlight;
else if (page.equals("environment"))
environmentHighlight = highlight;
else if (page.equals("custom"))
customHighlight = highlight;
String msg = getHead(myScript, onLoad);
msg += "<table class=\"ostable\">\n";
msg += "<tr><td><h1><a href=\"/\">Oracle2GP</a></h1></td>\n";
msg += "<td align=\"right\"><h1><a href=\"/?action_type=logout\">退出</a></h1></td>\n";
msg += "</tr>\n";
msg += "</table>\n";
msg += "<table>\n";
msg += "<table class=\"tftable\">\n";
msg += "<tr>\n";
msg += "<th width=\"17%\"><a " + externalHighlight + "href=\"external\"><h3>数据源</h3></a></th>\n";
msg += "<th width=\"17%\"><a " + jobsHighlight + "href=\"jobs\"><h3>作业清单</h3></a></th>\n";
msg += "<th width=\"17%\"><a " + queueHighlight + "href=\"queue\"><h3>作业状态</h3></a></th>\n";
msg += "<th width=\"17%\"><a " + scheduleHighlight + "href=\"schedule\"><h3>调度模式</h3></a></th>\n";
msg += "<th width=\"17%\"><a " + customHighlight + "href=\"custom\"><h3>定制表</h3></a></th>\n";
msg += "<th width=\"17%\"><a " + environmentHighlight + "href=\"environment\"><h3>环境配置</h3></a></th>\n";
msg += "</tr>\n";
msg += "</table>\n";
return msg;
}
public static String viewFooter()
{
String msg = "</body></html>\n";
return msg;
}
public static String viewError(String errorMsg)
{
String msg = "<h1>Error</h1>";
msg += errorMsg;
return msg;
}
public static String viewMain()
{
String msg = viewHeader("", "", "");
msg += "<p><b><i>Oracle2GP</b></i> is an open source, which is supported by Mr.Jiang</br>\n";
msg += "</p>\n";
return msg;
}
public static String viewPageNotFound()
{
String msg = viewHeader("", "", "");
msg = "Page not found!";
return msg;
}
public static String viewResults(String limit, String offset, ResultSet rs) throws SQLException
{
try
{
int intLimit = 0;
int intOffset = 0;
if (!limit.equals(""))
{
intLimit = Integer.parseInt(limit);
intOffset = Integer.parseInt(offset);
}
String nextOffset = String.valueOf(intOffset + intLimit);
String previousOffset = String.valueOf(intOffset - intLimit);
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
int counter = 0;
String msg = "";
while (rs.next())
{
counter++;
for (int i=1; i<numberOfColumns+1; i++)
{
if (i==1)
{
msg += "<tr>";
}
msg += "<td>" + rs.getString(i) + "</td>\n";
}
msg += "</tr>\n";
}
msg += "</table>\n";
if (intOffset > 0)
{
msg += "<button onclick=\"formSubmit(" + previousOffset + ")\">Previous</button>\n";
}
if (counter >= intLimit && !limit.equals(""))
{
msg += "<button onclick=\"formSubmit(" + nextOffset + ")\">Next</button>\n";
}
msg += "</form>\n";
return msg;
}
catch (SQLException ex)
{
throw new SQLException(ex.getMessage());
}
}
public static String setHTMLField(String val)
{
if (val != null)
{
val = val.replace("\"", "'");
val = "\"" + val + "\"";
}
else
val = "\"\"";
return val;
}
public static String setHTMLTextArea(String val)
{
if (val != null)
{
val = val.replace("\"", "'");
}
return val;
}
} | MLikeWater/Oracle2GP | src/OutsourcerView.java |
65,980 | package src;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.util.Scanner;
public class hmfa {
// 关于
static void About() throws IOException, InvalidKeyException {
System.out.println("\nheStudio MFA Tool for Desktop\n");
System.out.println("仓库:https://gitee.com/hestudio/hmfa");
System.out.println("heStudio 博客:https://www.hestudio.org\n");
hmfa.main(null);
}
// 主要函数
public static void main(String[] aStrings) throws IOException, InvalidKeyException {
System.out.println("\nheStudio MFA Desktop\n");
System.out.println("1. 获取令牌\n2. 管理令牌\n3. 关于\n4. 退出\n");
System.out.print("选择操作:");
Scanner choose = new Scanner(System.in);
int choose_return = choose.nextInt();
if (choose_return == 1) {
Getkey.main(null);
} else if (choose_return == 2) {
Console.main(null);
} else if (choose_return == 3) {
hmfa.About();
} else if (choose_return == 4) {
System.exit(0);
} else {
System.err.println("输入错误!");
hmfa.main(null);
}
choose.close();
}
} | hestudio-community/hmfa | src/hmfa.java |
65,982 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
/**
* <p>
* Title: HappyChat聊天系统登录程序
* </p>
* <p>
* Description: 根据指定的服务器地址、用户名和密码登录聊天服务器 友情下载:http://www.codefans.net
* </p>
* <p>
* Copyright: Copyright (c) 2006
* </p>
* <p>
* Filename: Login.java
* </p>
*
* @author 刘志成
* @version 1.0
*/
public class Login extends JFrame implements ActionListener {
private static final long serialVersionUID = -8965773902056088264L;
private JPanel pnlLogin;
private JButton btnLogin, btnRegister, btnExit;
private JLabel lblServer, lblUserName, lblPassword, lblLogo;
private JTextField txtUserName, txtServer;
private JPasswordField pwdPassword;
private String strServerIp;
// 用于将窗口定位
private Dimension scrnsize;
private Toolkit toolkit = Toolkit.getDefaultToolkit();
/**
* 构造登陆窗体
*/
public Login() {
super("登录[HappyChat]聊天室");
pnlLogin = new JPanel();
this.getContentPane().add(pnlLogin);
lblServer = new JLabel("服务器(S):");
lblUserName = new JLabel("用户名(U):");
lblPassword = new JLabel("口 令(P):");
txtServer = new JTextField(20);
txtServer.setText("127.0.0.1");
txtUserName = new JTextField(20);
pwdPassword = new JPasswordField(20);
btnLogin = new JButton("登录(L)");
btnLogin.setToolTipText("登录到服务器");
btnLogin.setMnemonic('L');
btnRegister = new JButton("注册(R)");
btnRegister.setToolTipText("注册新用户");
btnRegister.setMnemonic('R');
btnExit = new JButton("退出(X)");
btnExit.setToolTipText("退出系统");
btnExit.setMnemonic('X');
/***********************************************************************
* 该布局采用手动布局 setBounds设置组件位置 * setFont设置字体、字型、字号 * setForeground设置文字的颜色
* * setBackground设置背景色 * setOpaque将背景设置为透明
*/
pnlLogin.setLayout(null); // 组件用手动布局
pnlLogin.setBackground(new Color(52, 130, 203));
lblServer.setBounds(50, 100, 100, 30);
txtServer.setBounds(150, 100, 120, 25);
lblUserName.setBounds(50, 130, 100, 30);
txtUserName.setBounds(150, 130, 120, 25);
lblPassword.setBounds(50, 160, 100, 30);
pwdPassword.setBounds(150, 160, 120, 25);
btnLogin.setBounds(50, 200, 80, 25);
btnRegister.setBounds(130, 200, 80, 25);
btnExit.setBounds(210, 200, 80, 25);
Font fontstr = new Font("宋体", Font.PLAIN, 12);
lblServer.setFont(fontstr);
txtServer.setFont(fontstr);
lblUserName.setFont(fontstr);
txtUserName.setFont(fontstr);
lblPassword.setFont(fontstr);
pwdPassword.setFont(fontstr);
btnLogin.setFont(fontstr);
btnRegister.setFont(fontstr);
btnExit.setFont(fontstr);
lblUserName.setForeground(Color.BLACK);
lblPassword.setForeground(Color.BLACK);
btnLogin.setBackground(Color.ORANGE);
btnRegister.setBackground(Color.ORANGE);
btnExit.setBackground(Color.ORANGE);
pnlLogin.add(lblServer);
pnlLogin.add(txtServer);
pnlLogin.add(lblUserName);
pnlLogin.add(txtUserName);
pnlLogin.add(lblPassword);
pnlLogin.add(pwdPassword);
pnlLogin.add(btnLogin);
pnlLogin.add(btnRegister);
pnlLogin.add(btnExit);
// 设置背景图片
Icon logo1 = new ImageIcon("images\\loginlogo.jpg");
lblLogo = new JLabel(logo1);
lblLogo.setBounds(0, 0, 340, 66);
pnlLogin.add(lblLogo);
// 设置登录窗口
setResizable(false);
setSize(340, 260);
setVisible(true);
scrnsize = toolkit.getScreenSize();
setLocation(scrnsize.width / 2 - this.getWidth() / 2, scrnsize.height / 2 - this.getHeight() / 2);
Image img = toolkit.getImage("images\\appico.jpg");
setIconImage(img);
// 三个按钮注册监听
btnLogin.addActionListener(this);
btnRegister.addActionListener(this);
btnExit.addActionListener(this);
} // 构造方法结束
/**
* 按钮监听响应
*/
@SuppressWarnings({ "deprecation", "static-access" })
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if (source.equals(btnLogin)) {
// 判断用户名和密码是否为空
if (txtUserName.getText().equals("") || pwdPassword.getText().equals("")) {
JOptionPane op1 = new JOptionPane();
op1.showMessageDialog(null, "用户名或密码不能为空");
} else {
strServerIp = txtServer.getText();
login();
}
}
if (source.equals(btnRegister)) {
strServerIp = txtServer.getText();
this.dispose();
new Register(strServerIp);
}
if (source == btnExit) {
System.exit(0);
}
} // actionPerformed()结束
/**
* 登录事件响应方法
*/
@SuppressWarnings("deprecation")
public void login() {
// 接受客户的详细资料
Customer data = new Customer();
data.custName = txtUserName.getText();
data.custPassword = pwdPassword.getText();
try {
// 连接到服务器
Socket toServer;
toServer = new Socket(strServerIp, 1001);
ObjectOutputStream streamToServer = new ObjectOutputStream(toServer.getOutputStream());
// 写客户详细资料到服务器socket
streamToServer.writeObject((Customer) data);
// 读来自服务器socket的登录状态
BufferedReader fromServer = new BufferedReader(new InputStreamReader(toServer.getInputStream()));
String status = fromServer.readLine();
if (status.equals("登录成功")) {
new ChatRoom((String) data.custName, strServerIp);
this.dispose();
// 关闭流对象
streamToServer.close();
fromServer.close();
toServer.close();
} else {
JOptionPane.showMessageDialog(null, status);
// 关闭流对象
streamToServer.close();
fromServer.close();
toServer.close();
}
} catch (ConnectException e1) {
JOptionPane.showMessageDialog(null, "未能建立到指定服务器的连接!");
} catch (InvalidClassException e2) {
JOptionPane.showMessageDialog(null, "类错误!");
} catch (NotSerializableException e3) {
JOptionPane.showMessageDialog(null, "对象未序列化!");
} catch (IOException e4) {
JOptionPane.showMessageDialog(null, "不能写入到指定服务器!");
}
} // login()结束
/**
* 启动登陆窗体
*
* @param args
*/
public static void main(String args[]) {
new Login();
}
} // Class Login结束
| shaweiwei/happy-chat | src/Login.java |
65,985 | package stone;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author lichengpeng
* @desc 词法分析器
* @date 2020/7/11
**/
public class Lexer {
// pattern = 空白 + (注释 or 字符串 or 标识符)
// 标识符 = (变量 or 逻辑运算符 or 比较运算符 or 标点符号)
public static String regexPat = "\\s*((//.*)|" + "([0-9]+)|" + "(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|" + "([A-Z_a-z][A-Z_a-z0-9]*)|" +
"<=|>=|==|&&|\\|\\||\\p{Punct})?";
private Pattern pattern = Pattern.compile(regexPat);
private ArrayList<Token> queue = new ArrayList<Token>();
private boolean hashMore;
private LineNumberReader reader;
public Lexer(Reader r) {
hashMore = true;
reader = new LineNumberReader(r);
}
// 读取下一个token,并从队列中删除
public Token read() throws ParseException {
if(fillQueue(0)) {
return queue.remove(0);
}else {
return Token.EOF;
}
}
// 读取第i个token
public Token peek(int i) throws ParseException {
if(fillQueue(i)) {
return queue.get(i);
}else {
return Token.EOF;
}
}
// 填充token队列
private boolean fillQueue(int i) throws ParseException {
while(i >= queue.size()) {
if(hashMore) {
readLine();
}else {
return false;
}
}
return true;
}
// 读取一行
protected void readLine() throws ParseException{
String line;
try {
line = reader.readLine();
}catch(IOException e) {
throw new ParseException(e);
}
if(line == null) {
hashMore = false;
return;
}
int lineNo = reader.getLineNumber();
Matcher matcher = pattern.matcher(line);
matcher.useTransparentBounds(true).useAnchoringBounds(false);
int pos = 0;
int endPos = line.length();
while(pos < endPos) {
matcher.region(pos, endPos);
if(matcher.lookingAt()) {
addToken(lineNo, matcher);
pos = matcher.end();
}else {
throw new ParseException("bad token at line: " + lineNo);
}
}
queue.add(new IdToken(lineNo, Token.EOL));
}
protected void addToken(int lineNo, Matcher matcher) {
/**
* java regex group example:
* Regex: ([a-zA-Z0-9]+)([\s]+)([a-zA-Z ]+)([\s]+)([0-9]+)
*
* String: "!* UserName10 John Smith 01123 *!"
*
* group(0): UserName10 John Smith 01123
* group(1): UserName10
* group(2):
* group(3): John Smith
* group(4):
* group(5): 01123
*
* Regex: \\s*((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct})?
* ((//.*)|([0-9]+)|(\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\")|([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(1)
* (//.*): group(2)
* ([0-9]+): group(3)
* (\"(\\\\\"|\\\\\\\\|\\\\n|[^\"])*\"): group(4)
* ([A-Z_a-z][A-Z_a-z0-9]*)|<=|>=|==|&&|\\|\\||\\p{Punct}): group(5)
*/
String m = matcher.group(1);
// 当是空格的时候,直接退出
if(m == null) {
return;
}
// 当是注释时,直接退出
if(matcher.group(2) != null) {
return;
}
Token token;
if(matcher.group(3) != null) { // 匹配数字
token = new NumToken(lineNo, Integer.parseInt(m));
}else if(matcher.group(4) != null) { // 匹配字符串
token = new StrToken(lineNo, toStringLiteral(m));
}else { // 匹配标识符
token = new IdToken(lineNo, m);
}
queue.add(token);
}
protected String toStringLiteral(String s) {
StringBuilder sb = new StringBuilder();
int len = s.length() - 1;
for(int i = 1; i < len; i ++) { // 这一步相当于是去掉首位字符啊,就是把双引号去掉的意思吧
char c = s.charAt(i);
if(c == '\\' && i + 1 < len) {
char c2 = s.charAt(++ i);
if(c2 == '\\' || c2 == '"') {
c = s.charAt(++ i);
}else if(c2 == 'n') {
++ i;
c = '\n';
}
}
sb.append(c);
}
return sb.toString();
}
}
| 2329408386/stone | src/stone/Lexer.java |
65,987 | package com.fengdu.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@EnableWebMvc
@ComponentScan(basePackages = { "com.fengdu.controller" }) // 必须存在 扫描的API Controller package name 也可以直接扫描class
public class SwaggerConfig {
// @Bean
// public Docket customDocket() {
// return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
// }
// private ApiInfo apiInfo() {
//// Contact contact = new Contact("天空", "https://gitee.com/WiliamWang/my-shop", "[email protected]");
//// return new ApiInfo("my-shop前台API接口", // 大标题 title
//// "my-shop前台API接口", // 小标题
//// "0.0.1", // 版本
//// "www.tianyanshenghuo.com", // termsOfServiceUrl
//// contact, // 作者
//// "my-shop", // 链接显示文字
//// "https://gitee.com/WiliamWang/my-shop"// 网站链接
//// );
// return new ApiInfoBuilder().title("RESTful API document").version("2.0")
// .contact(new Contact("tiankong", "https://gitee.com/WiliamWang/my-shop", "[email protected]")).build();
// }
/* @Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("RESTful API document").version("2.0")
.contact(new Contact("tiankong", "https://gitee.com/WiliamWang/my-shop", "[email protected]")).build();
}*/
/* @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/swagger/**").addResourceLocations("classpath:/static/swagger/");
}*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.fengdu.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring+Swagger2构建APP RESTful 接口 1.0")
.termsOfServiceUrl("https://gitee.com/WiliamWang/my-shop")
.contact("tiankong")
.version("2.0")
.build();
}
} | tiankong0310/my-shop | my-shop-config/src/main/java/com/fengdu/config/SwaggerConfig.java |
65,992 | /*
* LuoYing is a program used to make 3D RPG game.
* Copyright (c) 2014-2016 Huliqing <[email protected]>
*
* This file is part of LuoYing.
*
* LuoYing is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LuoYing is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with LuoYing. If not, see <http://www.gnu.org/licenses/>.
*/
package name.huliqing.luoying.object.entity;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
/**
* 非模型类型的场景实体,这类实体一般不需要有实际存在于场景中的可视模型,一般如各类环境效果:灯光、水体(Filter)、
* 物理环境、天空、相机、阴影渲染及各类Filter\Scene Processor
* @author huliqing
*/
public abstract class NonModelEntity extends AbstractEntity {
/**
* 这个物体作为所有不需要实际存在的Entity的Spatial用于
* {@link #getSpatial() } 方法的调用返回, 避免在调用getSpatial的时候返回null.
*/
protected final Node NULL_ROOT = new Node(getClass().getName());
@Override
protected Spatial initSpatial() {
return NULL_ROOT;
}
}
| huliqing/LuoYing | ly-kernel/src/name/huliqing/luoying/object/entity/NonModelEntity.java |
65,993 | /**
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.huawei.mlkit.sample.activity.imageseg;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.huawei.mlkit.sample.R;
import com.huawei.mlkit.sample.activity.BaseActivity;
import com.huawei.mlkit.sample.transactor.ImageTransactor;
import com.huawei.mlkit.sample.transactor.StillImageSegmentationTransactor;
import com.huawei.mlkit.sample.util.BitmapUtils;
import com.huawei.mlkit.sample.views.color.ColorSelector;
import com.huawei.mlkit.sample.views.overlay.GraphicOverlay;
import com.huawei.hms.mlsdk.imgseg.MLImageSegmentationSetting;
import java.util.Locale;
public class LoadPhotoActivity extends BaseActivity {
private static final String TAG = "LoadPhotoActivity";
private static final String[] CATEGORIES = {"背景", "人", "天空", "绿植", "食物", "猫狗", "建筑", "花朵", "水面", "沙滩", "山坡"};
private static final String[] CATEGORIES_EN = {"Background", "People", "Sky", "Plant", "Food", "Animal", "Architecture", "Flower", "Water", "Beach", "Hill"};
private Uri mImageUri;
private ImageView preview;
private static final int REQUEST_TAKE_PHOTOR = 1;
private static final int REQUEST_SLECT_IMAGE = 2;
private LinearLayout linearObjects;
private ImageTransactor imageTransactor;
private GraphicOverlay graphicOverlay;
private Bitmap originBitmap;
private int colorvalue = Color.GREEN;
private int imageMaxWidth;
private int imageMaxHeight;
private ColorSelector colorSelector;
private boolean isLandScape;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_load_photo);
this.preview = this.findViewById(R.id.image_preview);
this.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LoadPhotoActivity.this.finish();
}
});
this.initView();
this.isLandScape = (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE);
}
private void initView() {
this.linearObjects = this.findViewById(R.id.linear_objects);
final String[] categories;
if (this.isEngLanguage()) {
categories = LoadPhotoActivity.CATEGORIES_EN;
} else {
categories = LoadPhotoActivity.CATEGORIES;
}
for (int i = 0; i < categories.length; i++) {
View view = LayoutInflater.from(this.getApplicationContext()).inflate(R.layout.layout, this.linearObjects, false);
TextView textView = view.findViewById(R.id.text);
textView.setText(categories[i]);
this.linearObjects.addView(view);
final int index = i;
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MLImageSegmentationSetting setting = new MLImageSegmentationSetting.Factory().setAnalyzerType(MLImageSegmentationSetting.IMAGE_SEG).create();
StillImageSegmentationTransactor transactor = new StillImageSegmentationTransactor(setting, LoadPhotoActivity.this.originBitmap, LoadPhotoActivity.this.preview, index);
transactor.setColor(LoadPhotoActivity.this.colorvalue);
LoadPhotoActivity.this.imageTransactor = transactor;
LoadPhotoActivity.this.imageTransactor.process(LoadPhotoActivity.this.originBitmap, LoadPhotoActivity.this.graphicOverlay);
}
});
}
this.graphicOverlay = this.findViewById(R.id.previewOverlay);
// Color picker settings.
this.colorSelector = this.findViewById(R.id.color_selector);
this.colorSelector = this.findViewById(R.id.color_selector);
this.colorSelector.initData();
this.colorSelector.setColors(Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE, Color.WHITE);
this.colorSelector.setOnColorSelectorChangeListener(new ColorSelector.OnColorSelectorChangeListener() {
@Override
public void onColorChanged(ColorSelector picker, int color) {
LoadPhotoActivity.this.colorvalue = color;
}
@Override
public void onStartColorSelect(ColorSelector picker) {
}
@Override
public void onStopColorSelect(ColorSelector picker) {
}
});
this.colorSelector.post(new Runnable() {
@Override
public void run() {
LoadPhotoActivity.this.selectLocalImage();
}
});
}
private void selectLocalImage() {
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
this.startActivityForResult(intent, LoadPhotoActivity.REQUEST_SLECT_IMAGE);
}
public boolean isEngLanguage() {
Locale locale = Locale.getDefault();
if (locale != null) {
String strLan = locale.getLanguage();
return strLan != null && "en".equals(strLan);
}
return false;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(this.TAG, "requestCode:" + requestCode + " : " + resultCode);
if (requestCode == this.REQUEST_TAKE_PHOTOR && resultCode == Activity.RESULT_OK) {
this.loadImage();
} else if (requestCode == this.REQUEST_TAKE_PHOTOR && resultCode == Activity.RESULT_CANCELED) {
this.finish();
} else if (requestCode == this.REQUEST_SLECT_IMAGE && resultCode == Activity.RESULT_OK) {
if (data != null) {
this.mImageUri = data.getData();
}
this.loadImage();
} else if (requestCode == this.REQUEST_SLECT_IMAGE && resultCode == Activity.RESULT_CANCELED) {
this.finish();
}
}
private void loadImage() {
this.originBitmap = BitmapUtils.loadFromPath(LoadPhotoActivity.this, this.mImageUri, this.getMaxWidthOfImage(), this.getMaxHeightOfImage());
this.preview.setImageBitmap(this.originBitmap);
}
private int getMaxWidthOfImage() {
if (this.imageMaxWidth == 0) {
if (this.isLandScape) {
this.imageMaxWidth = ((View) this.preview.getParent()).getHeight();
} else {
this.imageMaxWidth = ((View) this.preview.getParent()).getWidth();
}
}
return this.imageMaxWidth;
}
private int getMaxHeightOfImage() {
if (this.imageMaxHeight == 0) {
if (this.isLandScape) {
this.imageMaxHeight = ((View) this.preview.getParent()).getWidth();
} else {
this.imageMaxHeight = ((View) this.preview.getParent()).getHeight();
}
}
return this.imageMaxHeight;
}
@Override
protected void onDestroy() {
super.onDestroy();
BitmapUtils.recycleBitmap(this.originBitmap);
this.mImageUri = null;
if (this.imageTransactor != null) {
this.imageTransactor.stop();
this.imageTransactor = null;
}
if (this.graphicOverlay != null) {
this.graphicOverlay.clear();
this.graphicOverlay = null;
}
}
public void onBackPressed(View view) {
this.finish();
}
}
| HMS-Core/hms-ml-demo | MLKit-Sample/module-vision/src/main/java/com/huawei/mlkit/sample/activity/imageseg/LoadPhotoActivity.java |
65,996 | package com.tencent.ttpic.filter.aifilter;
import java.util.ArrayList;
import java.util.List;
public enum NewEnhanceCategories
{
public static String CATEGORY_UNRECOGNIZED;
public static List<NewEnhanceCategories> newEnhanceTypes;
public String displayName;
public String fileName;
public String filterType;
public String serverLabel;
static
{
BABY = new NewEnhanceCategories("BABY", 2, "baby", "儿童", "儿童", "gaobai_bf.png");
CROWD = new NewEnhanceCategories("CROWD", 3, "crowd", "合影", "合影", "ziran_cam.png");
P_LANDSCAPE = new NewEnhanceCategories("P_LANDSCAPE", 4, "plandscape", "人像加风光", "人景", "eftWeiguang_bf.png");
P_FOOD = new NewEnhanceCategories("P_FOOD", 5, "personfood", "人像加美食", "用餐", "xinxian2_bf.png");
P_SPORTS = new NewEnhanceCategories("P_SPORTS", 6, "personsports", "人像加运动", "健身", "xuanlan2_bf.png");
LANDSCAPE = new NewEnhanceCategories("LANDSCAPE", 7, "landscape", "户外", "户外", "xuanlan2_bf.png");
BUILDING = new NewEnhanceCategories("BUILDING", 8, "building", "建筑", "建筑", "fengzhigu2_bf.png");
INDOOR = new NewEnhanceCategories("INDOOR", 9, "indoor", "室内", "室内", "musi_cam.png");
NIGHT = new NewEnhanceCategories("NIGHT", 10, "night", "夜景", "夜景", "xuanlan2_bf.png");
SKY = new NewEnhanceCategories("SKY", 11, "sky", "天空", "天空", "jidi_bf.png");
SPORTS = new NewEnhanceCategories("SPORTS", 12, "sports", "运动", "运动", "xuanlan2_bf.png");
DISHES = new NewEnhanceCategories("DISHES", 13, "fooddishes", "菜肴", "菜肴", "xinxian2_bf.png");
DESSERT = new NewEnhanceCategories("DESSERT", 14, "fooddessert", "甜点", "甜点", "tianpin2_bf.png");
BEVERAGE = new NewEnhanceCategories("BEVERAGE", 15, "fooddrink", "饮品", "饮品", "youge_cam.png");
MEAT = new NewEnhanceCategories("MEAT", 16, "foodmeat", "肉类", "肉类", "lengcui_bf.png");
WESTERN = new NewEnhanceCategories("WESTERN", 17, "foodwestern", "西餐", "西餐", "xican2_bf.png");
RESTAURANT = new NewEnhanceCategories("RESTAURANT", 18, "foodrestaurant", "餐厅", "餐厅", "xican2_bf.png");
STILL_OBJECT = new NewEnhanceCategories("STILL_OBJECT", 19, "object", "静物", "静物", "xican2_bf.png");
ANIMAL = new NewEnhanceCategories("ANIMAL", 20, "animal", "动物", "动物", "musi_cam.png");
PLANT = new NewEnhanceCategories("PLANT", 21, "plant", "植物", "植物", "tianpin2_bf.png");
COMMON = new NewEnhanceCategories("COMMON", 22, "other", "通用", "通用", "ziran_cam.png");
$VALUES = new NewEnhanceCategories[] { FEMALE, MALE, BABY, CROWD, P_LANDSCAPE, P_FOOD, P_SPORTS, LANDSCAPE, BUILDING, INDOOR, NIGHT, SKY, SPORTS, DISHES, DESSERT, BEVERAGE, MEAT, WESTERN, RESTAURANT, STILL_OBJECT, ANIMAL, PLANT, COMMON };
CATEGORY_UNRECOGNIZED = "通用";
newEnhanceTypes = new ArrayList();
newEnhanceTypes.add(FEMALE);
newEnhanceTypes.add(MALE);
newEnhanceTypes.add(BABY);
newEnhanceTypes.add(CROWD);
newEnhanceTypes.add(P_LANDSCAPE);
newEnhanceTypes.add(P_FOOD);
newEnhanceTypes.add(P_SPORTS);
newEnhanceTypes.add(LANDSCAPE);
newEnhanceTypes.add(BUILDING);
newEnhanceTypes.add(INDOOR);
newEnhanceTypes.add(NIGHT);
newEnhanceTypes.add(SKY);
newEnhanceTypes.add(SPORTS);
newEnhanceTypes.add(DISHES);
newEnhanceTypes.add(DESSERT);
newEnhanceTypes.add(BEVERAGE);
newEnhanceTypes.add(MEAT);
newEnhanceTypes.add(WESTERN);
newEnhanceTypes.add(RESTAURANT);
newEnhanceTypes.add(STILL_OBJECT);
newEnhanceTypes.add(ANIMAL);
newEnhanceTypes.add(PLANT);
newEnhanceTypes.add(COMMON);
}
private NewEnhanceCategories(String paramString1, String paramString2, String paramString3, String paramString4)
{
this.filterType = paramString1;
this.serverLabel = paramString2;
this.displayName = paramString3;
this.fileName = paramString4;
}
}
/* Location: L:\local\mybackup\temp\qq_apk\com.tencent.tim\classes12.jar
* Qualified Name: com.tencent.ttpic.filter.aifilter.NewEnhanceCategories
* JD-Core Version: 0.7.0.1
*/ | tsuzcx/qq_apk | com.tencent.tim/classes.jar/com/tencent/ttpic/filter/aifilter/NewEnhanceCategories.java |
65,997 | /*
* This file is part of the Meteor Client distribution (https://github.com/MeteorDevelopment/meteor-client).
* Copyright (c) Meteor Development.
*/
package meteordevelopment.meteorclient.systems.modules.world;
import meteordevelopment.meteorclient.settings.BoolSetting;
import meteordevelopment.meteorclient.settings.ColorSetting;
import meteordevelopment.meteorclient.settings.Setting;
import meteordevelopment.meteorclient.settings.SettingGroup;
import meteordevelopment.meteorclient.systems.modules.Categories;
import meteordevelopment.meteorclient.systems.modules.Module;
import meteordevelopment.meteorclient.utils.player.PlayerUtils;
import meteordevelopment.meteorclient.utils.render.color.SettingColor;
import net.minecraft.client.render.DimensionEffects;
import net.minecraft.util.math.Vec3d;
/**
* @author Walaryne
*/
public class Ambience extends Module {
private final SettingGroup sgSky = settings.createGroup("天空");
private final SettingGroup sgWorld = settings.createGroup("世界");
// Sky
public final Setting<Boolean> endSky = sgSky.add(new BoolSetting.Builder()
.name("末地天空")
.description("使天空像末地一样。")
.defaultValue(false)
.build()
);
public final Setting<Boolean> customSkyColor = sgSky.add(new BoolSetting.Builder()
.name("自定义天空颜色")
.description("是否应该改变天空的颜色。")
.defaultValue(false)
.build()
);
public final Setting<SettingColor> overworldSkyColor = sgSky.add(new ColorSetting.Builder()
.name("主世界天空颜色")
.description("主世界天空的颜色。")
.defaultValue(new SettingColor(0, 125, 255))
.visible(customSkyColor::get)
.build()
);
public final Setting<SettingColor> netherSkyColor = sgSky.add(new ColorSetting.Builder()
.name("下界天空颜色")
.description("下界天空的颜色。")
.defaultValue(new SettingColor(102, 0, 0))
.visible(customSkyColor::get)
.build()
);
public final Setting<SettingColor> endSkyColor = sgSky.add(new ColorSetting.Builder()
.name("末地天空颜色")
.description("末地天空的颜色。")
.defaultValue(new SettingColor(65, 30, 90))
.visible(customSkyColor::get)
.build()
);
public final Setting<Boolean> customCloudColor = sgSky.add(new BoolSetting.Builder()
.name("自定义云彩颜色")
.description("是否应该改变云彩的颜色。")
.defaultValue(false)
.build()
);
public final Setting<SettingColor> cloudColor = sgSky.add(new ColorSetting.Builder()
.name("云彩颜色")
.description("云彩的颜色。")
.defaultValue(new SettingColor(102, 0, 0))
.visible(customCloudColor::get)
.build()
);
public final Setting<Boolean> changeLightningColor = sgSky.add(new BoolSetting.Builder()
.name("自定义闪电颜色")
.description("是否应该改变闪电的颜色。")
.defaultValue(false)
.build()
);
public final Setting<SettingColor> lightningColor = sgSky.add(new ColorSetting.Builder()
.name("闪电颜色")
.description("闪电的颜色。")
.defaultValue(new SettingColor(102, 0, 0))
.visible(changeLightningColor::get)
.build()
);
// World
public final Setting<Boolean> customGrassColor = sgWorld.add(new BoolSetting.Builder()
.name("自定义草色")
.description("是否应该改变草的颜色。")
.defaultValue(false)
.onChanged(val -> reload())
.build()
);
public final Setting<SettingColor> grassColor = sgWorld.add(new ColorSetting.Builder()
.name("草色")
.description("草的颜色。")
.defaultValue(new SettingColor(102, 0, 0))
.visible(customGrassColor::get)
.onChanged(val -> reload())
.build()
);
public final Setting<Boolean> customFoliageColor = sgWorld.add(new BoolSetting.Builder()
.name("自定义树叶颜色")
.description("是否应该改变树叶的颜色。")
.defaultValue(false)
.onChanged(val -> reload())
.build()
);
public final Setting<SettingColor> foliageColor = sgWorld.add(new ColorSetting.Builder()
.name("树叶颜色")
.description("树叶的颜色。")
.defaultValue(new SettingColor(102, 0, 0))
.visible(customFoliageColor::get)
.onChanged(val -> reload())
.build()
);
public final Setting<Boolean> customWaterColor = sgWorld.add(new BoolSetting.Builder()
.name("自定义水色")
.description("是否应该改变水的颜色。")
.defaultValue(false)
.onChanged(val -> reload())
.build()
);
public final Setting<SettingColor> waterColor = sgWorld.add(new ColorSetting.Builder()
.name("水色")
.description("水的颜色。")
.defaultValue(new SettingColor(102, 0, 0))
.visible(customWaterColor::get)
.onChanged(val -> reload())
.build()
);
public final Setting<Boolean> customLavaColor = sgWorld.add(new BoolSetting.Builder()
.name("自定义岩浆颜色")
.description("是否应该改变岩浆的颜色。")
.defaultValue(false)
.onChanged(val -> reload())
.build()
);
public final Setting<SettingColor> lavaColor = sgWorld.add(new ColorSetting.Builder()
.name("岩浆颜色")
.description("岩浆的颜色。")
.defaultValue(new SettingColor(102, 0, 0))
.visible(customLavaColor::get)
.onChanged(val -> reload())
.build()
);
public Ambience() {
super(Categories.World, "氛围", "改变环境中各个部分的颜色。");
}
@Override
public void onActivate() {
reload();
}
@Override
public void onDeactivate() {
reload();
}
private void reload() {
if (mc.worldRenderer != null && isActive()) mc.worldRenderer.reload();
}
public static class Custom extends DimensionEffects {
public Custom() {
super(Float.NaN, true, DimensionEffects.SkyType.END, true, false);
}
@Override
public Vec3d adjustFogColor(Vec3d color, float sunHeight) {
return color.multiply(0.15000000596046448D);
}
@Override
public boolean useThickFog(int camX, int camY) {
return false;
}
@Override
public float[] getFogColorOverride(float skyAngle, float tickDelta) {
return null;
}
}
public SettingColor skyColor() {
switch (PlayerUtils.getDimension()) {
case Overworld -> {
return overworldSkyColor.get();
}
case Nether -> {
return netherSkyColor.get();
}
case End -> {
return endSkyColor.get();
}
}
return null;
}
}
| dingzhen-vape/MeteorCN | src/main/java/meteordevelopment/meteorclient/systems/modules/world/Ambience.java |
65,998 | package core;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import core.Flyer;
import core.World;
/** 天空 */
public class Sky extends Flyer {
public int y1;// 第二张图片的的y坐标
private static BufferedImage[] images;
/** 加载背景-图片 */
static {
images = new BufferedImage[4];
for (int i = 0; i < images.length; i++) {
images[i] = loadImage//
("shoot/audio_png/pictures&/sky/", "bg_" + i);
}
}
/** sky构造方法 */
public Sky() {
super(images[0].getWidth(), images[0].getHeight(), 0, 0, 1);
y1 = -this.height;
xSpeed = 0;
ySpeed = 1;
}
/** 天空移动 */
int index = 0;
public void step() {
index++;
if (index % 8 == 0) {
y1 += ySpeed;
y += ySpeed;
}
if (y >= height) {
y = -height;
}
if (y1 >= height) {
y1 = -height;
}
}
/** 根据当前游戏关卡,返回天空图片 */
public BufferedImage getImage() {
// System.out.println("天空返回图");
switch (World.gameLevel) {
case 1:
return images[1];
case 2:
return images[2];
case 3:
return images[3];
default:
// 游戏开始状态,返回此图片
return images[0];
}
}
@Override
public void paintObject(Graphics g) {
g.drawImage(getImage(), 0, y, null);
g.drawImage(getImage(), x, y1, null);
}
@Override
public boolean outOfBounds() {
return false;
}
}
| tu-jacktu/TuShoot | shoot/core/Sky.java |
66,001 | package com.mars.controller;
import com.mars.mongo.UserEntity;
import com.mars.service.UserMongoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@RestController
@RequestMapping
public class MongoController {
private final static Logger logger = LoggerFactory.getLogger(HelloController.class);
@Autowired
UserMongoService userMongoService;
@GetMapping(value = "/mongo/save")
public UserEntity save(HttpServletRequest request) throws IOException {
UserEntity user=new UserEntity();
user.setId(2l);
user.setUserName("小明");
user.setPassWord("fffooo123");
userMongoService.saveUser(user);
return user;
}
@GetMapping(value = "/mongo/find")
public UserEntity find(HttpServletRequest request) throws IOException {
UserEntity user = userMongoService.findUserByUserName("小明");
return user;
}
@GetMapping(value = "/mongo/update")
public UserEntity update(HttpServletRequest request) throws IOException {
UserEntity user=new UserEntity();
user.setId(2l);
user.setUserName("天空");
user.setPassWord("fffxxxx");
userMongoService.updateUser(user);
return user;
}
@GetMapping(value = "/mongo/delete")
public UserEntity delete(HttpServletRequest request) throws IOException {
userMongoService.deleteUserById(2l);
return new UserEntity();
}
}
| hu5675/multi-spring-boot | boot-web/src/main/java/com/mars/controller/MongoController.java |
66,005 | package com.cecilia;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
* @author HuangQiang
* @version 1.0
* @createTime 2019/11/13 - 11:27
*/
public abstract class FlyingObject {
public static final int LIFE = 1;
public static final int DEAD = 2;
public static final int REMOVE = 3;
protected int state = LIFE;
protected int width; //图片的宽
protected int height; //图片的高
protected int x; //x坐标
protected int y; //y坐标
/* 敌机使用的构造方法 */
public FlyingObject(int width, int height) {
this.width = width;
this.height = height;
Random rand = new Random();
this.x = rand.nextInt(PlayGame.WIDTH - this.width);
this.y = -this.height;
}
/* 天空、英雄机、子弹使用的构造方法 */
public FlyingObject(int width, int height, int x, int y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
}
/* 飞行物共有的飞行方法 */
public abstract void move();
public void paintObject(Graphics g) {
g.drawImage(getImage(), x, y, null);
}
public abstract BufferedImage getImage();
public boolean isLife() {
return state == LIFE;
}
public boolean isDead() {
return state == DEAD;
}
public boolean isREMOVE() {
return state == REMOVE;
}
public boolean outOfBounds() {
return y >= PlayGame.HEIGHT;
}
public boolean hit(FlyingObject obj) {
int x1 = this.x - obj.width;
int x2 = this.x + this.width;
int y1 = this.y - obj.height;
int y2 = this.y + obj.height;
int x = obj.x;
int y = obj.y;
return x1 < x && x < x2 && y1 < y && y < y2;
}
public void goDead() {
state = DEAD;
}
}
| myceciliababy/shootgame | src/com/cecilia/FlyingObject.java |
66,006 | package com.community.mua.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import com.community.mua.App;
import com.community.mua.R;
import com.community.mua.bean.LoveListBean;
import com.community.mua.bean.PetMarketBean;
import com.community.mua.bean.ChangeChatBgBean;
import com.community.mua.bean.PairBean;
import com.community.mua.bean.SplashSizeBean;
import com.community.mua.bean.UserBean;
import com.community.mua.common.Constants;
import com.community.mua.livedatas.LiveDataBus;
import com.community.mua.livedatas.LiveEvent;
import java.util.ArrayList;
import java.util.List;
public class SharedPreferUtil {
private static final String KEY_USER_BEAN = "key_user_bean";
private static final String KEY_TA_BEAN = "key_ta_bean";
private static final String KEY_PAIR_BEAN = "key_pair_bean";
private static final String KEY_BGM = "key_bgm";
private static final SharedPreferUtil ourInstance = new SharedPreferUtil();
private static final String KEY_COINS = "key_coins";
private static final String KEY_CHAT_BG = "key_chat_bg";
private static final String KEY_SOUND = "key_sound";
private static final String KEY_VIBRATE = "key_vibrate";
private static final String KEY_PET_FOODS = "key_pet_foods";
private static final String KEY_FEED_TIME = "key_feed_time";
private static final String KEY_LATITUDE = "key_latitude";
private static final String KEY_LONGITUDE = "key_longitude";
private static final String KEY_LOCATION_ADDRESS = "key_Location_address";
private static final String KEY_BATTERY_PROPERTY_CAPACITY = "key_property_capacity";
private static final String KEY_BATTERY_STATUS_CHARGING = "key_property_capacity_status_change";
private static final String KEY_SPLASH_SIZE = "key_splash_size";
private static final String KEY_BTN_SOUND = "key_btn_sound";
private static final String KEY_CHAT_FLOW = "key_chat_flow";
private static final String KEY_LAST_COLLECT_COINS_TIME = "key_last_collect_coins_time";
private static final String KEY_LAST_COIN_TIMER = "key_last_coin_timer";
private static final String KEY_TODAY_COLLECT_COINS_COUNTS = "key_today_collect_coins_counts";
private static final String KEY_LOVE_LIST = "key_love_list";
public static SharedPreferUtil getInstance() {
return ourInstance;
}
private SharedPreferUtil() {
}
private SharedPreferences mSharedPreference = App.getContext().getSharedPreferences("mua_config", Context.MODE_PRIVATE);
public void setUserBean(UserBean bean) {
mSharedPreference.edit().putString(KEY_USER_BEAN, GsonUtils.toJson(bean)).commit();
}
public UserBean getUserBean() {
String str = mSharedPreference.getString(KEY_USER_BEAN, "");
if (TextUtils.isEmpty(str)) {
return null;
}
return GsonUtils.toBean(str, UserBean.class);
}
public void setTaBean(UserBean bean) {
mSharedPreference.edit().putString(KEY_TA_BEAN, GsonUtils.toJson(bean)).commit();
}
public UserBean getTaBean() {
String str = mSharedPreference.getString(KEY_TA_BEAN, "");
if (TextUtils.isEmpty(str)) {
return null;
}
return GsonUtils.toBean(str, UserBean.class);
}
public void setPairBean(PairBean bean) {
mSharedPreference.edit().putString(KEY_PAIR_BEAN, GsonUtils.toJson(bean)).commit();
}
public PairBean getPairBean() {
String str = mSharedPreference.getString(KEY_PAIR_BEAN, "");
if (TextUtils.isEmpty(str)) {
return null;
}
return GsonUtils.toBean(str, PairBean.class);
}
public void setBgm(String bgm) {
mSharedPreference.edit().putString(KEY_BGM, bgm).commit();
}
public String getBgm() {
return mSharedPreference.getString(KEY_BGM, "");
}
public void addCoins(int count) {
int coins = getCoins();
coins += count;
mSharedPreference.edit().putInt(KEY_COINS, coins).commit();
LiveDataBus.get().with(Constants.COINS_UPDATE, LiveEvent.class).postValue(new LiveEvent());
}
public int getCoins() {
return mSharedPreference.getInt(KEY_COINS, 0);
}
public boolean payCoins(int count) {
int coins = getCoins();
if (coins == 0) {
return false;
}
coins -= count;
if (coins < 0) {
return false;
}
LiveDataBus.get().with(Constants.COINS_UPDATE, LiveEvent.class).postValue(new LiveEvent());
return mSharedPreference.edit().putInt(KEY_COINS, coins).commit();
}
public static List<ChangeChatBgBean> sBgBeans;
public static void initBgBeans() {
if (sBgBeans == null) {
sBgBeans = new ArrayList<>();
sBgBeans.add(new ChangeChatBgBean(R.drawable.stary, "天空的星星"));
sBgBeans.add(new ChangeChatBgBean(R.drawable.pop_cron, "爆米花"));
sBgBeans.add(new ChangeChatBgBean(R.drawable.sweetie, "甜甜的味道"));
sBgBeans.add(new ChangeChatBgBean(R.drawable.little_duck, "小黄鸭"));
sBgBeans.add(new ChangeChatBgBean(R.drawable.v_gesture, "比个✌"));
sBgBeans.add(new ChangeChatBgBean(R.drawable.sky, "天空"));
sBgBeans.add(new ChangeChatBgBean(R.drawable.untitled, "无题"));
sBgBeans.add(new ChangeChatBgBean(R.drawable.frog, "一只小青蛙"));
sBgBeans.add(new ChangeChatBgBean(R.drawable.corner, "角"));
}
}
public static List<ChangeChatBgBean> getBgBeans() {
if (sBgBeans == null) {
initBgBeans();
}
return sBgBeans;
}
public void setChatBg(String name) {
mSharedPreference.edit().putString(KEY_CHAT_BG, name).commit();
}
public boolean isChatBgSelected(String name) {
String s = mSharedPreference.getString(KEY_CHAT_BG, "");
if (TextUtils.isEmpty(s)) {
return false;
}
return TextUtils.equals(s, name);
}
public int getChatBg() {
String s = mSharedPreference.getString(KEY_CHAT_BG, "");
if (sBgBeans == null || TextUtils.isEmpty(s)) {
return R.drawable.bg_main;
}
for (ChangeChatBgBean bgBean : sBgBeans) {
if (TextUtils.equals(bgBean.getTitle(), s)) {
return bgBean.getImg();
}
}
return R.drawable.bg_main;
}
public boolean getNotifySoundEnabled() {
return mSharedPreference.getBoolean(KEY_SOUND, true);
}
public void setNotifySoundEnabled(boolean b) {
mSharedPreference.edit().putBoolean(KEY_SOUND, b).commit();
}
public boolean getNotifyVibrateEnabled() {
return mSharedPreference.getBoolean(KEY_VIBRATE, true);
}
public void setNotifyVibrateEnabled(boolean b) {
mSharedPreference.edit().putBoolean(KEY_VIBRATE, b).commit();
}
public void setPetFoods(List<PetMarketBean> list) {
String str = GsonUtils.toJson(list);
mSharedPreference.edit().putString(KEY_PET_FOODS, str).commit();
}
public List<PetMarketBean> getPetFoods() {
String str = mSharedPreference.getString(KEY_PET_FOODS, "");
if (TextUtils.isEmpty(str)) {
return null;
}
return GsonUtils.toList(str, PetMarketBean.class);
}
public void clearCoins() {
mSharedPreference.edit().putInt(KEY_COINS, 0).commit();
}
// public void setLastFeedPetTime(long time) {
// mSharedPreference.edit().putLong(KEY_FEED_TIME, time).commit();
// }
//
// public long getLastFeedPetTime() {
// return mSharedPreference.getLong(KEY_FEED_TIME, 0);
// }
public void setLat(double lat) {
mSharedPreference.edit().putString(KEY_LATITUDE, lat + "").commit();
}
public String getLat() {
return mSharedPreference.getString(KEY_LATITUDE, "");
}
public void setLongitude(double longitude) {
mSharedPreference.edit().putString(KEY_LONGITUDE, longitude + "").commit();
}
public String getLongitude() {
return mSharedPreference.getString(KEY_LONGITUDE, "");
}
public void setLocationAdd(String address) {
mSharedPreference.edit().putString(KEY_LOCATION_ADDRESS, address).commit();
}
public String getLocationAdd() {
return mSharedPreference.getString(KEY_LOCATION_ADDRESS, "");
}
public void setBatteryManager(int currentLevel) {
mSharedPreference.edit().putString(KEY_BATTERY_PROPERTY_CAPACITY, currentLevel + "").commit();
}
public String getBatteryManager() {
return mSharedPreference.getString(KEY_BATTERY_PROPERTY_CAPACITY, "0");
}
public void setBatteryStatus(boolean status) {
mSharedPreference.edit().putBoolean(KEY_BATTERY_STATUS_CHARGING, status).commit();
}
public boolean getBatteryStatus() {
return mSharedPreference.getBoolean(KEY_BATTERY_STATUS_CHARGING, false);
}
public SplashSizeBean getSplashSize() {
String str = mSharedPreference.getString(KEY_SPLASH_SIZE, "");
if (TextUtils.isEmpty(str)) {
return null;
}
return GsonUtils.toBean(str, SplashSizeBean.class);
}
public void setSplashSize(SplashSizeBean bean) {
String str = GsonUtils.toJson(bean);
mSharedPreference.edit().putString(KEY_SPLASH_SIZE, str).commit();
}
public void setBtnSoundEnabled(boolean checked) {
mSharedPreference.edit().putBoolean(KEY_BTN_SOUND, checked).commit();
}
public boolean getBtnSoundEnabled() {
return mSharedPreference.getBoolean(KEY_BTN_SOUND, true);
}
public void setChatFlowEnabled(boolean checked) {
mSharedPreference.edit().putBoolean(KEY_CHAT_FLOW, checked).commit();
}
public boolean getChatFlowEnabled() {
return mSharedPreference.getBoolean(KEY_CHAT_FLOW, true);
}
public void setLastCollectCoinsTime(long time) {
mSharedPreference.edit().putLong(KEY_LAST_COLLECT_COINS_TIME, time).commit();
}
public long getLastCollectCoinsTime() {
return mSharedPreference.getLong(KEY_LAST_COLLECT_COINS_TIME, 0);
}
public int getTodayCollectCoinsCounts() {
return mSharedPreference.getInt(KEY_TODAY_COLLECT_COINS_COUNTS, 0);
}
public void setTodayCollectCoinsCounts(int i) {
mSharedPreference.edit().putInt(KEY_TODAY_COLLECT_COINS_COUNTS, i).commit();
}
public void setLastCoinTimerCount(int timerCount) {
mSharedPreference.edit().putInt(KEY_LAST_COIN_TIMER, timerCount).commit();
}
public int getLastCoinTimerCount() {
return mSharedPreference.getInt(KEY_LAST_COIN_TIMER, -1);
}
public void setLastFeedPetTime(long currentTimeMillis) {
PairBean pairBean = SharedPreferUtil.getInstance().getPairBean();
pairBean.setKittyStatusTime(currentTimeMillis);
SharedPreferUtil.getInstance().setPairBean(pairBean);
}
public long getLastFeedPetTime() {
PairBean pairBean = SharedPreferUtil.getInstance().getPairBean();
return pairBean.getKittyStatusTime();
}
public LoveListBean getDefaultLoveListBean(int pos){
if (pos == 0){
return new LoveListBean("一起看电影", "一起看一场走心电影叭");
}
if (pos == 1){
return new LoveListBean("一起做饭", "一房·两人·三餐·四季");
}
return new LoveListBean("写一封情书", "无声的话语,却格外打动人心");
}
public List<LoveListBean> getLoveList() {
String s = mSharedPreference.getString(KEY_LOVE_LIST, "");
if (TextUtils.isEmpty(s)) {
List<LoveListBean> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
list.add(getDefaultLoveListBean(i));
}
return list;
}
return GsonUtils.toList(s, LoveListBean.class);
}
public LoveListBean getLoveListBean(int pos) {
return getLoveList().get(pos);
}
public void setLoveList(int pos, LoveListBean bean) {
List<LoveListBean> list = getLoveList();
list.set(pos, bean);
mSharedPreference.edit().putString(KEY_LOVE_LIST, GsonUtils.toJson(list)).commit();
}
public void clearLoveListItem(int pos) {
List<LoveListBean> list = getLoveList();
list.set(pos, getDefaultLoveListBean(pos));
mSharedPreference.edit().putString(KEY_LOVE_LIST, GsonUtils.toJson(list)).commit();
}
}
| easemob/mua | app/src/main/java/com/community/mua/utils/SharedPreferUtil.java |
66,009 | // Copyright 2017 JanusGraph Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.janusgraph.example;
import com.google.common.base.Preconditions;
import org.janusgraph.core.EdgeLabel;
import org.janusgraph.core.Multiplicity;
import org.janusgraph.core.PropertyKey;
import org.janusgraph.core.JanusGraphFactory;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphTransaction;
import org.janusgraph.core.attribute.Geoshape;
import org.janusgraph.core.schema.ConsistencyModifier;
import org.janusgraph.core.schema.JanusGraphIndex;
import org.janusgraph.core.schema.JanusGraphManagement;
import org.janusgraph.graphdb.database.StandardJanusGraph;
import org.apache.tinkerpop.gremlin.process.traversal.Order;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
/**
* Example Graph factory that creates a {@link JanusGraph} based on roman mythology.
* Used in the documentation examples and tutorials.
*
* @author Marko A. Rodriguez (https://markorodriguez.com)
*/
public class GraphOfTheGodsFactory {
public static final String INDEX_NAME = "search";
private static final String ERR_NO_INDEXING_BACKEND =
"The indexing backend with name \"%s\" is not defined. Specify an existing indexing backend or " +
"use GraphOfTheGodsFactory.loadWithoutMixedIndex(graph,true) to load without the use of an " +
"indexing backend.";
public static JanusGraph create(final String directory) {
JanusGraphFactory.Builder config = JanusGraphFactory.build();
config.set("storage.backend", "berkeleyje");
config.set("storage.directory", directory);
config.set("index." + INDEX_NAME + ".backend", "elasticsearch");
JanusGraph graph = config.open();
GraphOfTheGodsFactory.load(graph);
return graph;
}
public static void loadWithoutMixedIndex(final JanusGraph graph, boolean uniqueNameCompositeIndex) {
load(graph, null, uniqueNameCompositeIndex);
}
public static void load(final JanusGraph graph) {
load(graph, INDEX_NAME, true);
}
private static boolean mixedIndexNullOrExists(StandardJanusGraph graph, String indexName) {
return indexName == null || graph.getIndexSerializer().containsIndex(indexName);
}
public static void load(final JanusGraph graph, String mixedIndexName, boolean uniqueNameCompositeIndex) {
if (graph instanceof StandardJanusGraph) {
Preconditions.checkState(mixedIndexNullOrExists((StandardJanusGraph)graph, mixedIndexName),
ERR_NO_INDEXING_BACKEND, mixedIndexName);
}
//**主要包含6种节点类型:**
//* location:位置(sky:天空,sea:海,tartarus:塔耳塔洛斯)
//* titan:巨人(saturn:罗马神话中的农神)
//* god:神(jupiter,neptune,pluto)
//* demigod:半神(hercules)
//* human:人类(alcmene)
//* monster:怪物(nemean,hydra,cerberus)
//**主要包含6中边类型:**
//* father:父亲
//* mother:母亲
//* brother:兄弟
//* battled:战斗
//* lives:生活在
//* pet:宠物
// Create Schema
JanusGraphManagement management = graph.openManagement();
// ===创建name属性; String、唯一CompositeIndex、锁机制保证name的强一致性
final PropertyKey name = management.makePropertyKey("name").dataType(String.class).make();
JanusGraphManagement.IndexBuilder nameIndexBuilder = management.buildIndex("name", Vertex.class).addKey(name);
if (uniqueNameCompositeIndex)
nameIndexBuilder.unique();
JanusGraphIndex nameIndex = nameIndexBuilder.buildCompositeIndex();
// 此处的LOCK,在name索引上添加了LOCK标识,标识这在并发修改相同的name属性时,必须通过锁机制(本地锁+分布式锁)保证并发修改;
management.setConsistency(nameIndex, ConsistencyModifier.LOCK);
// ===创建age属性;Integer、mixed index
final PropertyKey age = management.makePropertyKey("age").dataType(Integer.class).make();
if (null != mixedIndexName)
management.buildIndex("vertices", Vertex.class).addKey(age).buildMixedIndex(mixedIndexName);
// ===创建time属性
final PropertyKey time = management.makePropertyKey("time").dataType(Integer.class).make();
// ===创建reason属性
final PropertyKey reason = management.makePropertyKey("reason").dataType(String.class).make();
// ===创建place属性
final PropertyKey place = management.makePropertyKey("place").dataType(Geoshape.class).make();
// 为reason 和 place属性创建mixed index索引edges
if (null != mixedIndexName)
management.buildIndex("edges", Edge.class).addKey(reason).addKey(place).buildMixedIndex(mixedIndexName);
// 创建边类型:father, many to one
management.makeEdgeLabel("father").multiplicity(Multiplicity.MANY2ONE).make();
// 创建边类型:mother, many to one
management.makeEdgeLabel("mother").multiplicity(Multiplicity.MANY2ONE).make();
// 创建边类型:battled, 签名密匙为time:争斗次数,
EdgeLabel battled = management.makeEdgeLabel("battled").signature(time).make();
// 为battled边创建一个以顶点为中心的 中心索引(vertex-centric index),索引属性time; 双向索引,可以从 神->怪物 也可以 怪物->神
// 将查询节点对应的 battled 边时,可以使用这个vertex-centric索引,索引属性为 time;
// vertex-centric index为了解决大节点问题,一个节点存在过多的边!
management.buildEdgeIndex(battled, "battlesByTime", Direction.BOTH, Order.desc, time);
// 创建边类型:lives,签名密匙为reason
management.makeEdgeLabel("lives").signature(reason).make();
// 创建边类型:pet
management.makeEdgeLabel("pet").make();
// 创建边类型:brother
management.makeEdgeLabel("brother").make();
// 创建节点label
management.makeVertexLabel("titan").make();
management.makeVertexLabel("location").make();
management.makeVertexLabel("god").make();
management.makeVertexLabel("demigod").make();
management.makeVertexLabel("human").make();
management.makeVertexLabel("monster").make();
// 提交!! 上述schema的创建!
management.commit();
// ======= 开始插入数据!=======
JanusGraphTransaction tx = graph.newTransaction();
// 插入节点
Vertex saturn = tx.addVertex(T.label, "titan", "name", "saturn", "age", 10000);
Vertex sky = tx.addVertex(T.label, "location", "name", "sky");
Vertex sea = tx.addVertex(T.label, "location", "name", "sea");
Vertex jupiter = tx.addVertex(T.label, "god", "name", "jupiter", "age", 5000);
Vertex neptune = tx.addVertex(T.label, "god", "name", "neptune", "age", 4500);
Vertex hercules = tx.addVertex(T.label, "demigod", "name", "hercules", "age", 30);
Vertex alcmene = tx.addVertex(T.label, "human", "name", "alcmene", "age", 45);
Vertex pluto = tx.addVertex(T.label, "god", "name", "pluto", "age", 4000);
Vertex nemean = tx.addVertex(T.label, "monster", "name", "nemean");
Vertex hydra = tx.addVertex(T.label, "monster", "name", "hydra");
Vertex cerberus = tx.addVertex(T.label, "monster", "name", "cerberus");
Vertex tartarus = tx.addVertex(T.label, "location", "name", "tartarus");
// 插入边数据
jupiter.addEdge("father", saturn);
jupiter.addEdge("lives", sky, "reason", "loves fresh breezes");
jupiter.addEdge("brother", neptune);
jupiter.addEdge("brother", pluto);
neptune.addEdge("lives", sea).property("reason", "loves waves");
neptune.addEdge("brother", jupiter);
neptune.addEdge("brother", pluto);
hercules.addEdge("father", jupiter);
hercules.addEdge("mother", alcmene);
hercules.addEdge("battled", nemean, "time", 1, "place", Geoshape.point(38.1f, 23.7f));
hercules.addEdge("battled", hydra, "time", 2, "place", Geoshape.point(37.7f, 23.9f));
hercules.addEdge("battled", cerberus, "time", 12, "place", Geoshape.point(39f, 22f));
pluto.addEdge("brother", jupiter);
pluto.addEdge("brother", neptune);
pluto.addEdge("lives", tartarus, "reason", "no fear of death");
pluto.addEdge("pet", cerberus);
cerberus.addEdge("lives", tartarus);
// 提交事务,持久化提交的数据到磁盘
tx.commit();
}
/**
* Calls {@link JanusGraphFactory#open(String)}, passing the JanusGraph configuration file path
* which must be the sole element in the {@code args} array, then calls
* {@link #load(org.janusgraph.core.JanusGraph)} on the opened graph,
* then calls {@link org.janusgraph.core.JanusGraph#close()}
* and returns.
* <p>
* This method may call {@link System#exit(int)} if it encounters an error, such as
* failure to parse its arguments. Only use this method when executing main from
* a command line. Use one of the other methods on this class ({@link #create(String)}
* or {@link #load(org.janusgraph.core.JanusGraph)}) when calling from
* an enclosing application.
*
* @param args a singleton array containing a path to a JanusGraph config properties file
*/
public static void main(String args[]) {
if (null == args || 1 != args.length) {
System.err.println("Usage: GraphOfTheGodsFactory <janusgraph-config-file>");
System.exit(1);
}
JanusGraph g = JanusGraphFactory.open(args[0]);
load(g);
g.close();
}
}
| yoylee/janusgraph-source-article | janusgraph-core/src/main/java/org/janusgraph/example/GraphOfTheGodsFactory.java |
66,010 | package com.dimple.entity;
import com.dimple.utils.BaseEntity;
import lombok.Data;
import java.io.Serializable;
/**
* 问题表(Question)实体类
*
* @author makejava
* @since 2019-05-01 11:39:03
*/
@Data
public class Question extends BaseEntity {
private static final long serialVersionUID = 850681683013092951L;
private Integer id;
//问题类型:1表示单选,2表示多选,3表示天空,4表示判断,5表示问答
private String type;
//题干
private String title;
//A选项答案
private String optionA;
//B选项答案
private String optionB;
//C选项答案
private String optionC;
//D选项答案
private String optionD;
//答案
private String answer;
//解析
private String analyse;
//分值
private Double score;
//该题的最终得分
private Double finalScore;
//单选或者多选的选中(修改试题的正确答案回显)
private String optionAChecked;
private String optionBChecked;
private String optionCChecked;
private String optionDChecked;
//判断题的选中
private String judgeAnswer1;//正确
private String judgeAnswer0;//错误
//学生的答案(查看 详情和考试过程中的)
private String textAnswerStu;
private String optionACheckedStu;
private String optionBCheckedStu;
private String optionCCheckedStu;
private String optionDCheckedStu;
private String judgeAnswer1Stu;//正确
private String judgeAnswer0Stu;//错误
} | martin-chips/online_exam_system | src/main/java/com/dimple/entity/Question.java |
66,011 | package com.guoxiaoxing.phoenix.core;
import android.app.Activity;
import android.graphics.Color;
import android.os.Environment;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import com.guoxiaoxing.phoenix.core.listener.Starter;
import com.guoxiaoxing.phoenix.core.model.MediaEntity;
import com.guoxiaoxing.phoenix.core.model.MimeType;
import com.guoxiaoxing.phoenix.core.util.ReflectUtils;
import java.util.ArrayList;
import java.util.List;
/**
* For more information, you can visit https://github.com/guoxiaoxing or contact me by
* [email protected].
*
* @author guoxiaoxing
* @since 2017/8/14 上午9:47
*/
public class PhoenixOption implements Parcelable {
//功能 - 选择图片/视频/音频
public static final int TYPE_PICK_MEDIA = 0x000001;
//功能 - 拍照
public static final int TYPE_TAKE_PICTURE = 0x000002;
//功能 - 预览
public static final int TYPE_BROWSER_PICTURE = 0x000003;
//主题颜色 - 默认
public static final int THEME_DEFAULT = Color.parseColor("#333333");
//主题 - 中国红主题
public static final int THEME_RED = Color.parseColor("#FF4040");
//主题 - 青春橙主题
public static final int THEME_ORANGE = Color.parseColor("#FF571A");
//主题 - 天空蓝主题
public static final int THEME_BLUE = Color.parseColor("#538EEB");
//选择列表显示的文件类型,全部:MimeType.ofAll()、图片:MimeType.ofImage()、视频:MimeType.ofVideo(),音频:MimeType.ofAudio()
private int fileType = MimeType.ofImage();
//是否显示拍照按钮
private boolean enableCamera = false;
//主题样式,有默认样式、大风车样式、车牛样式、弹个车样式,可定制
private int theme = THEME_DEFAULT;
//最大选择张数,默认为0,表示不限制
private int maxPickNumber = 0;
//最小选择张数,默认为0,表示不限制
private int minPickNumber = 0;
//显示多少秒以内的视频
private int videoFilterTime;
//显示多少kb以下的图片/视频,默认为0,表示不限制
private int mediaFilterSize;
//视频秒数录制 默认10s
private int recordVideoTime = 10;
//图片选择界面每行图片个数
private int spanCount = 4;
//选择列表图片宽度
private int thumbnailWidth = 160;
//选择列表图片高度
private int thumbnailHeight = 160;
//选择列表点击动画效果
private boolean enableAnimation = true;
//是否显示gif图片
private boolean enableGif;
//是否开启点击预览
private boolean enablePreview = true;
//是否开启数字显示模式
private boolean pickNumberMode;
//是否开启点击声音
private boolean enableClickSound = true;
//预览图片时,是否增强左右滑动图片体验
private boolean previewEggs = true;
//是否开启压缩
private boolean enableCompress;
//视频压缩阈值(多少kb以下的视频不进行压缩,默认2048kb)
private int compressVideoFilterSize = 2048;
//图片压缩阈值(多少kb以下的图片不进行压缩,默认1024kb)
private int compressPictureFilterSize = 1024;
//已选择的数据、图片/视频/音频预览的数据
private List<MediaEntity> pickedMediaList = new ArrayList<>();
//拍照、视频的保存地址
private String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
public PhoenixOption() {
}
public int getFileType() {
return fileType;
}
public boolean isEnableCamera() {
return enableCamera;
}
public int getTheme() {
return theme;
}
public int getMaxPickNumber() {
return maxPickNumber;
}
public int getMinPickNumber() {
return minPickNumber;
}
public int getVideoFilterTime() {
return videoFilterTime;
}
public int getMediaFilterSize() {
return mediaFilterSize;
}
public int getRecordVideoTime() {
return recordVideoTime;
}
public int getSpanCount() {
return spanCount;
}
public int getThumbnailWidth() {
return thumbnailWidth;
}
public int getThumbnailHeight() {
return thumbnailHeight;
}
public boolean isEnableAnimation() {
return enableAnimation;
}
public boolean isEnableGif() {
return enableGif;
}
public boolean isEnablePreview() {
return enablePreview;
}
public boolean isPickNumberMode() {
return pickNumberMode;
}
public boolean isEnableClickSound() {
return enableClickSound;
}
public boolean isPreviewEggs() {
return previewEggs;
}
public boolean isEnableCompress() {
return enableCompress;
}
public int getCompressVideoFilterSize() {
return compressVideoFilterSize;
}
public int getCompressPictureFilterSize() {
return compressPictureFilterSize;
}
public List<MediaEntity> getPickedMediaList() {
return pickedMediaList;
}
public String getSavePath() {
return savePath;
}
public PhoenixOption fileType(int val) {
fileType = val;
return this;
}
public PhoenixOption enableCamera(boolean val) {
enableCamera = val;
return this;
}
public PhoenixOption theme(int val) {
theme = val;
return this;
}
public PhoenixOption maxPickNumber(int val) {
maxPickNumber = val;
return this;
}
public PhoenixOption minPickNumber(int val) {
minPickNumber = val;
return this;
}
public PhoenixOption videoFilterTime(int val) {
videoFilterTime = val;
return this;
}
public PhoenixOption mediaFilterSize(int val) {
mediaFilterSize = val;
return this;
}
public PhoenixOption recordVideoTime(int val) {
recordVideoTime = val;
return this;
}
public PhoenixOption spanCount(int val) {
spanCount = val;
return this;
}
public PhoenixOption thumbnailWidth(int val) {
thumbnailWidth = val;
return this;
}
public PhoenixOption thumbnailHeight(int val) {
thumbnailHeight = val;
return this;
}
public PhoenixOption enableAnimation(boolean val) {
enableAnimation = val;
return this;
}
public PhoenixOption enableGif(boolean val) {
enableGif = val;
return this;
}
public PhoenixOption enablePreview(boolean val) {
enablePreview = val;
return this;
}
public PhoenixOption pickNumberMode(boolean val) {
pickNumberMode = val;
return this;
}
public PhoenixOption enableClickSound(boolean val) {
enableClickSound = val;
return this;
}
public PhoenixOption previewEggs(boolean val) {
previewEggs = val;
return this;
}
public PhoenixOption pickedMediaList(List<MediaEntity> val) {
pickedMediaList = val;
return this;
}
public PhoenixOption enableCompress(boolean val) {
enableCompress = val;
return this;
}
public PhoenixOption compressVideoFilterSize(int val) {
compressVideoFilterSize = val;
return this;
}
public PhoenixOption compressPictureFilterSize(int val) {
compressPictureFilterSize = val;
return this;
}
public PhoenixOption savePath(String val) {
savePath = val;
return this;
}
public void start(Fragment fragment, int type, int requestCode) {
Starter starter = ReflectUtils.loadStarter(ReflectUtils.Phoenix);
if (starter != null) {
starter.start(fragment, this, type, requestCode);
}
}
public void start(Activity activity, int type, int requestCode) {
Starter starter = ReflectUtils.loadStarter(ReflectUtils.Phoenix);
if (starter != null) {
starter.start(activity, this, type, requestCode);
}
}
public void start(Fragment fragment, int type, String futureAction) {
Starter starter = ReflectUtils.loadStarter(ReflectUtils.Phoenix);
if (starter != null) {
starter.start(fragment, this, type, futureAction);
}
}
public void start(Activity activity, int type, String futureAction) {
Starter starter = ReflectUtils.loadStarter(ReflectUtils.Phoenix);
if (starter != null) {
starter.start(activity, this, type, futureAction);
}
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.fileType);
dest.writeByte(this.enableCamera ? (byte) 1 : (byte) 0);
dest.writeInt(this.theme);
dest.writeInt(this.maxPickNumber);
dest.writeInt(this.minPickNumber);
dest.writeInt(this.videoFilterTime);
dest.writeInt(this.mediaFilterSize);
dest.writeInt(this.recordVideoTime);
dest.writeInt(this.spanCount);
dest.writeInt(this.thumbnailWidth);
dest.writeInt(this.thumbnailHeight);
dest.writeByte(this.enableAnimation ? (byte) 1 : (byte) 0);
dest.writeByte(this.enableGif ? (byte) 1 : (byte) 0);
dest.writeByte(this.enablePreview ? (byte) 1 : (byte) 0);
dest.writeByte(this.pickNumberMode ? (byte) 1 : (byte) 0);
dest.writeByte(this.enableClickSound ? (byte) 1 : (byte) 0);
dest.writeByte(this.previewEggs ? (byte) 1 : (byte) 0);
dest.writeByte(this.enableCompress ? (byte) 1 : (byte) 0);
dest.writeInt(this.compressVideoFilterSize);
dest.writeInt(this.compressPictureFilterSize);
dest.writeTypedList(this.pickedMediaList);
dest.writeString(this.savePath);
}
protected PhoenixOption(Parcel in) {
this.fileType = in.readInt();
this.enableCamera = in.readByte() != 0;
this.theme = in.readInt();
this.maxPickNumber = in.readInt();
this.minPickNumber = in.readInt();
this.videoFilterTime = in.readInt();
this.mediaFilterSize = in.readInt();
this.recordVideoTime = in.readInt();
this.spanCount = in.readInt();
this.thumbnailWidth = in.readInt();
this.thumbnailHeight = in.readInt();
this.enableAnimation = in.readByte() != 0;
this.enableGif = in.readByte() != 0;
this.enablePreview = in.readByte() != 0;
this.pickNumberMode = in.readByte() != 0;
this.enableClickSound = in.readByte() != 0;
this.previewEggs = in.readByte() != 0;
this.enableCompress = in.readByte() != 0;
this.compressVideoFilterSize = in.readInt();
this.compressPictureFilterSize = in.readInt();
this.pickedMediaList = in.createTypedArrayList(MediaEntity.CREATOR);
this.savePath = in.readString();
}
public static final Creator<PhoenixOption> CREATOR = new Creator<PhoenixOption>() {
@Override
public PhoenixOption createFromParcel(Parcel source) {
return new PhoenixOption(source);
}
@Override
public PhoenixOption[] newArray(int size) {
return new PhoenixOption[size];
}
};
}
| sucese/phoenix | phoenix-core/src/main/java/com/guoxiaoxing/phoenix/core/PhoenixOption.java |
66,012 | package com.heaven7.ve.colorgap;
import java.util.List;
/**
* the raw script item. like
* <pre>
* String[][] rawScriptTable =
[["empty","30%",0,"天空",""],
["character","1",0,"",""],
["churchIn","40%",1,"植物,花艺",""],
["dinner","30%",0,"","装饰"]]
* </pre>
* one item correspond a logic-sentence. <br><br>
* Created by heaven7 on 2018/4/11 0011.
*/
@Deprecated
public class RawScriptItem {
/** the event, often is file dir */
private String event;
/** percent of whole plaids (30 means 30%) */
private int percentage;
/** the air-shot count */
private int airShotCount;
/** 定场镜头tags比较重要 */
private List<String> firstShotTags;
/** the important tags */
private List<String> importantTags;
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public int getPercentage() {
return percentage;
}
public void setPercentage(int percentage) {
this.percentage = percentage;
}
public int getAirShotCount() {
return airShotCount;
}
public void setAirShotCount(int airShotCount) {
this.airShotCount = airShotCount;
}
public List<String> getFirstShotTags() {
return firstShotTags;
}
public void setFirstShotTags(List<String> firstShotTags) {
this.firstShotTags = firstShotTags;
}
public List<String> getImportantTags() {
return importantTags;
}
public void setImportantTags(List<String> importantTags) {
this.importantTags = importantTags;
}
}
| LightSun/research-institute | java/ffmpeg-merge-video/src/main/java/com/heaven7/ve/colorgap/RawScriptItem.java |
66,013 | package com.xaaolaf.opencvdemo.secondsight.filters.curve;
/**
* Created by xupingwei on 2017/6/23.
* 该滤镜的效果可增加阴影和高光之间的对比度,并使图像的色调偏于冷淡。
* 另外,天空、水面以及着色将被着重强调,常用语地表图像
*/
public class ProviaCurveFilter extends CurveFilter {
public ProviaCurveFilter() {
super(
new double[]{0, 255}, //vValIn
new double[]{0, 255}, //vValOut
new double[]{0, 59, 202, 255}, //rValIn
new double[]{0, 54, 210, 255}, //rValOut
new double[]{0, 27, 196, 255}, //gValIn
new double[]{0, 21, 207, 255}, //gValOut
new double[]{0, 35, 205, 255}, //bValIn
new double[]{0, 25, 227, 255} //bValOut
);
}
}
| xupingwei/OpenCVDemo | app/src/main/java/com/xaaolaf/opencvdemo/secondsight/filters/curve/ProviaCurveFilter.java |
66,014 | package SorketTest;
import org.junit.Test;
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* 实现TCP网络编程
* 例子2:客户端发送文件给服务器,服务器保存在本地并发送反馈信息
*/
public class TCPTest2 {
//服务器
@Test
public void server(){
ServerSocket serverSocket=null;
Socket socket=null;
InputStream inputStream=null;
FileOutputStream fileOutputStream=null;
OutputStream out=null;
try {
serverSocket=new ServerSocket(8870);
socket=serverSocket.accept();
inputStream = socket.getInputStream();
fileOutputStream=new FileOutputStream("D:\\java\\IDEACommunity-Project\\javaSE\\Notes\\src\\SorketTest\\天空(接收).jpg");
byte[] b=new byte[512];
int readCount=0;
while ((readCount=inputStream.read(b))!=-1){
fileOutputStream.write(b,0,readCount);
}
System.out.println("文件已接收。");
//反馈接受信息
out=socket.getOutputStream();
out.write("来自服务端的消息:图片已经收到,很好看。".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fileOutputStream!=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//客户端
@Test
public void client(){
Socket socket=null;
OutputStream out=null;
FileInputStream f=null;
InputStream inputStream=null;
ByteArrayOutputStream byteArrayOutputStream=null;
try {
//(1)
socket=new Socket(InetAddress.getLoopbackAddress(),8870);
//(2)
out=socket.getOutputStream();
//(3)
f=new FileInputStream("D:\\java\\IDEACommunity-Project\\javaSE\\Notes\\src\\SorketTest\\天空.jpg");
//(4)
int readCount=0;
byte[] b=new byte[512];
while ((readCount=f.read(b))!=-1){
out.write(b,0,readCount);
}
//告诉服务器传输完成中断连接
socket.shutdownOutput();
//
System.out.println("文件传输完成。");
//将收到的信息打印在控制台
byteArrayOutputStream=new ByteArrayOutputStream();
inputStream=socket.getInputStream();
while((readCount=inputStream.read(b))!=-1){
byteArrayOutputStream.write(b,0,readCount);
}
System.out.println(byteArrayOutputStream);
} catch (IOException e) {
e.printStackTrace();
}finally {
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(f!=null){
try {
f.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(inputStream!=null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(byteArrayOutputStream!=null){
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
| xiaowansheng/JavaSENotes | src/SorketTest/TCPTest2.java |
66,017 | package org.mobiletrain.android37_materialdesigndemo.bean;
import java.util.List;
/**
* Created by Administrator on 2016-03-22.
*/
public class WarComment {
/**
* error : 0
* hotcommentList : []
* commentList : [{"commentId":"13263353","newsId":"8038621","userName":"军工第二八七","userId":"1149810","userImg":"http://image.mier123.com/uc_server/data/avatar/001/14/98/10_avatar_small.jpg","publishTime":"6小时前","laud":"0","content":"向百发百中导弹旅:官兵致敬。","loushu":"18","level":"6","militaryRank":"三级军士长","replys":[]},{"commentId":"13254159","newsId":"8038621","userName":"老玩童","userId":"377447","userImg":"http://wx.qlogo.cn/mmopen/MSibp3cbfuYVeSMeFudpPjmccmJd3kHgFhiaVXztzV2ZW4dGR8UiaLI1s8R7Ylw3rd9EODNOLJtsAA4gZ3L1IkLT4Odtm3TSCkN/0","publishTime":"11小时前","laud":"0","content":"平时如战时、战时如平时。","loushu":"17","level":"10","militaryRank":"中尉","replys":[]},{"commentId":"13252818","newsId":"8038621","userName":"156****0788","userId":"1241203","userImg":"http://image.mier123.com/api/images/pl_icon_default_head17.png","publishTime":"11小时前","laud":"0","content":"中国,好样的!","loushu":"16","level":"5","militaryRank":"四级军士长","replys":[]},{"commentId":"13249358","newsId":"8038621","userName":"m1447422735","userId":"1077181","userImg":"http://image.mier123.com/api/images/pl_icon_default_head1.png","publishTime":"13小时前","laud":"0","content":"中国人民解放军是祖国的钢铁长城!","loushu":"15","level":"10","militaryRank":"中尉","replys":[]},{"commentId":"13248322","newsId":"8038621","userName":"云中鹤","userId":"463339","userImg":"http://wx.qlogo.cn/mmopen/Bl8QPWdo6c5aINnuBibk9wJXtYzpwW1wCrezcRPGYXS4oAQLoPwE3sYpE2XM4d4GzLza8D4egObKrsPR2PCJDgvjelUSEXYoy/0","publishTime":"14小时前","laud":"0","content":"强军才能强国。实现中国萝,必须强军.","loushu":"14","level":"12","militaryRank":"少校","replys":[]},{"commentId":"13247527","newsId":"8038621","userName":"★绿色的背影★","userId":"1022903","userImg":"http://image.mier123.com/api/images/pl_icon_default_head13.png","publishTime":"14小时前","laud":"0","content":"科技强军,刻苦训练的成果。","loushu":"13","level":"9","militaryRank":"少尉","replys":[]},{"commentId":"13246775","newsId":"8038621","userName":"歧哎","userId":"1103747","userImg":"http://q.qlogo.cn/qqapp/1103461621/FBB7CA627929D485E5AED058DB5BC477/40","publishTime":"15小时前","laud":"0","content":"打着谁了:狐狸吗:","loushu":"12","level":"7","militaryRank":"二级军士长","replys":[]},{"commentId":"13241773","newsId":"8038621","userName":"马踏飞燕@","userId":"934537","userImg":"http://image.mier123.com/api/images/pl_icon_default_head4.png","publishTime":"昨天 22:47","laud":"0","content":"就要让敌人胆寒!","loushu":"11","level":"10","militaryRank":"中尉","replys":[]},{"commentId":"13241704","newsId":"8038621","userName":"飞豹2","userId":"1170496","userImg":"http://wx.qlogo.cn/mmopen/kwibjIYBG1C8h1tay5x1kTqxLoVxjJOa4O9m3ohich7aibxHh0licRJAcibHsp8Bz1jLYyd3bCmILgZCJ6m4dPMwNT9IEbBuwaKicO/0","publishTime":"昨天 22:44","laud":"0","content":"牛!花了那么多钱建设的二炮部队必须体现实力。没有实力那里来的威慑,继续努力。","loushu":"10","level":"5","militaryRank":"四级军士长","replys":[]},{"commentId":"13240912","newsId":"8038621","userName":"150****7983","userId":"1224753","userImg":"http://image.mier123.com/api/images/pl_icon_default_head18.png","publishTime":"昨天 22:13","laud":"0","content":"在战斗中命中率有5分之一,不要闹笑话就可以了","loushu":"9","level":"5","militaryRank":"四级军士长","replys":[]},{"commentId":"13240037","newsId":"8038621","userName":"宝石12","userId":"1111818","userImg":"http://image.mier123.com/uc_server/data/avatar/001/11/18/18_avatar_small.jpg","publishTime":"昨天 21:45","laud":"1","content":"放到南海去!","loushu":"8","level":"8","militaryRank":"一级军士长","replys":[]},{"commentId":"13239155","newsId":"8038621","userName":"潘圆58","userId":"854763","userImg":"http://image.mier123.com/api/images/pl_icon_default_head5.png","publishTime":"昨天 21:17","laud":"0","content":"这是科学的进步,中国人的福音。","loushu":"7","level":"9","militaryRank":"少尉","replys":[]},{"commentId":"13238212","newsId":"8038621","userName":"Wǒ.9s.","userId":"1025215","userImg":"http://image.mier123.com/uc_server/data/avatar/001/02/52/15_avatar_small.jpg","publishTime":"昨天 20:46","laud":"0","content":"向人民子弟兵致敬!","loushu":"6","level":"8","militaryRank":"一级军士长","replys":[]},{"commentId":"13234715","newsId":"8038621","userName":"李玉庚","userId":"992415","userImg":"http://image.mier123.com/api/images/pl_icon_default_head12.png","publishTime":"昨天 19:01","laud":"0","content":"东风15钻地导弹发射百颗多能百发百中,这是解放军苦练基本功所处得叼的,赞","loushu":"5","level":"9","militaryRank":"少尉","replys":[]},{"commentId":"13232066","newsId":"8038621","userName":"张猛","userId":"343579","userImg":"http://image.mier123.com/uc_server/data/avatar/000/34/35/79_avatar_small.jpg","publishTime":"昨天 17:42","laud":"0","content":"北斗的贡献。","loushu":"4","level":"14","militaryRank":"上校","replys":[]},{"commentId":"13231900","newsId":"8038621","userName":"坚守40","userId":"1091653","userImg":"http://image.mier123.com/api/images/pl_icon_default_head24.png","publishTime":"昨天 17:34","laud":"0","content":"为了祖国的明天","loushu":"3","level":"9","militaryRank":"少尉","replys":[]},{"commentId":"13231637","newsId":"8038621","userName":"茅山居士","userId":"1172558","userImg":"http://image.mier123.com/uc_server/data/avatar/001/17/25/58_avatar_small.jpg","publishTime":"昨天 17:22","laud":"0","content":"用毛泽东思想武装起来的军队都是刚刚的。","loushu":"2","level":"6","militaryRank":"三级军士长","replys":[]},{"commentId":"13230842","newsId":"8038621","userName":"老刘北京","userId":"1160990","userImg":"http://image.mier123.com/uc_server/data/avatar/001/16/09/90_avatar_small.jpg","publishTime":"昨天 16:49","laud":"3","content":"向人民子弟兵致敬!","loushu":"1","level":"7","militaryRank":"二级军士长","replys":[]}]
*/
private String error;
private List<?> hotcommentList;
/**
* commentId : 13263353
* newsId : 8038621
* userName : 军工第二八七
* userId : 1149810
* userImg : http://image.mier123.com/uc_server/data/avatar/001/14/98/10_avatar_small.jpg
* publishTime : 6小时前
* laud : 0
* content : 向百发百中导弹旅:官兵致敬。
* loushu : 18
* level : 6
* militaryRank : 三级军士长
* replys : []
*/
private List<CommentListEntity> commentList;
public void setError(String error) {
this.error = error;
}
public void setHotcommentList(List<?> hotcommentList) {
this.hotcommentList = hotcommentList;
}
public void setCommentList(List<CommentListEntity> commentList) {
this.commentList = commentList;
}
public String getError() {
return error;
}
public List<?> getHotcommentList() {
return hotcommentList;
}
public List<CommentListEntity> getCommentList() {
return commentList;
}
public static class CommentListEntity {
private String commentId;
private String newsId;
private String userName;
private String userId;
private String userImg;
private String publishTime;
private String laud;
private String content;
private String loushu;
private String level;
private String militaryRank;
private List<?> replys;
public void setCommentId(String commentId) {
this.commentId = commentId;
}
public void setNewsId(String newsId) {
this.newsId = newsId;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setUserImg(String userImg) {
this.userImg = userImg;
}
public void setPublishTime(String publishTime) {
this.publishTime = publishTime;
}
public void setLaud(String laud) {
this.laud = laud;
}
public void setContent(String content) {
this.content = content;
}
public void setLoushu(String loushu) {
this.loushu = loushu;
}
public void setLevel(String level) {
this.level = level;
}
public void setMilitaryRank(String militaryRank) {
this.militaryRank = militaryRank;
}
public void setReplys(List<?> replys) {
this.replys = replys;
}
public String getCommentId() {
return commentId;
}
public String getNewsId() {
return newsId;
}
public String getUserName() {
return userName;
}
public String getUserId() {
return userId;
}
public String getUserImg() {
return userImg;
}
public String getPublishTime() {
return publishTime;
}
public String getLaud() {
return laud;
}
public String getContent() {
return content;
}
public String getLoushu() {
return loushu;
}
public String getLevel() {
return level;
}
public String getMilitaryRank() {
return militaryRank;
}
public List<?> getReplys() {
return replys;
}
}
}
| haegyeong/News | app/src/main/java/org/mobiletrain/android37_materialdesigndemo/bean/WarComment.java |
66,027 | package com.github.dcais.aggra.test;
import com.github.dcais.aggra.cons.HttpConstants;
import com.github.dcais.aggra.converter.StringConverter;
import com.github.dcais.aggra.request.DynamicRequest;
import com.github.dcais.aggra.test.request.TestRequest;
import com.github.dcais.aggra.test.request.TestRmiRequest;
import com.github.dcais.aggra.test.request.TestRmiRequest2;
import com.github.dcais.aggra.test.result.Result;
import com.github.dcais.aggra.test.result.ReturnInfo;
import com.github.dcais.aggra.test.result.UploadFileInfo;
import com.github.dcais.aggra.test.result.tabs.TopicTabsQueryView;
import com.github.dcais.aggra.test.result.tabs.TopicTabsView;
import com.google.gson.Gson;
import com.google.gson.internal.StringMap;
import com.google.gson.reflect.TypeToken;
import org.apache.http.Header;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.io.File;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
/**
*
*/
@Test
@ContextConfiguration(locations = {"classpath:spring_base.xml"})
public class TestMain extends AbstractTestNGSpringContextTests {
private static final Logger log = org.slf4j.LoggerFactory.getLogger(TestMain.class);
@Autowired
private TestRequest testRequest;
@Autowired
private TestRmiRequest testRmiRequest;
@Autowired
private TestRmiRequest2 testRmiRequest2;
@Autowired
DynamicRequest dynamicRequest;
@Autowired
StringConverter defaultStringConverter;
// @Autowired
// private Test2Request test2Request;
@Test
public void basicTest() {
String result = testRequest.basicTest("ab", "cd", "中尉1", "XMLHttpRequest");
Gson gson = new Gson();
ReturnInfo r = gson.fromJson(result, new TypeToken<ReturnInfo>() {
}.getType());
Assert.assertNotNull(r);
Assert.assertEquals(r.getHeaders().get("Content-Type".toLowerCase()), "text/plain");
Assert.assertEquals(r.getHeaders().get("Method-Head-1".toLowerCase()), "MethodHead1");
Assert.assertEquals(r.getHeaders().get("Method-Head-2".toLowerCase()), "MethodHead2");
Assert.assertEquals(r.getHeaders().get("X-Requested-With".toLowerCase()), "XMLHttpRequest");
Assert.assertEquals(r.getParam().get("p1"), "ab");
Assert.assertEquals(r.getParam().get("p2"), null);
Assert.assertEquals(r.getParam().get("like"), "中尉1");
log.info(result);
}
@Test
public void headersTest() {
List<Header> heads = new ArrayList<>();
ReturnInfo returnInfo = testRequest.headerTest(heads);
boolean found = false;
for (Map.Entry<String,String> entry : returnInfo.getHeaders().entrySet() ) {
log.info(entry.getKey() + ":" + entry.getValue());
//一个Header的值
if (TestRequest.TEST_HEADER_NAME.equals(entry.getKey()) && TestRequest.TEST_HEADER_VALUE.equals(entry.getValue())) {
found = true;
}
}
Assert.assertTrue(found);
}
@Test
public void testReturnVoid() {
String para1 = "ab";
String para2 = "cd";
testRequest.testReturnVoid("ab", "cd", "中尉1", "XMLHttpRequest");
Map<String, Object> complexPara = new HashMap<String, Object>();
complexPara.put("p1", para1);
complexPara.put("p2", para2);
String str = testRequest.testReturnVoidWithSigleParams(complexPara, "中尉1", "XMLHttpRequest");
}
@Test
public void objectResultTest() {
ReturnInfo r = testRequest.objectResultTest("点赞");
Assert.assertNotNull(r);
Assert.assertEquals(r.getHeaders().get("Content-Type".toLowerCase()), "text/plain");
Assert.assertEquals(r.getHeaders().get("Method-Head-1".toLowerCase()), "MethodHead1");
Assert.assertEquals(r.getHeaders().get("Method-Head-2".toLowerCase()), "MethodHead2");
Assert.assertEquals(r.getParam().get("like"), "点赞");
log.info(defaultStringConverter.toString(r));
Assert.assertNotNull(r);
}
@Test
public void testPostBody() {
TopicTabsView ttv = new TopicTabsView();
ttv.setTitle("票提1");
TopicTabsQueryView queryView = new TopicTabsQueryView();
queryView.setCategoryId(1001l);
queryView.setIsHot("N");
ttv.setQuery(queryView);
String result = testRequest.postRequestBody(ttv);
log.info(result);
Gson gson = new Gson();
ReturnInfo r = gson.fromJson(result, ReturnInfo.class);
Assert.assertNotNull(r);
Assert.assertEquals(r.getHeaders().get("Content-Type".toLowerCase()), "application/json");
StringMap body = (StringMap) r.getBody();
Assert.assertEquals(body.get("title"), "票提1");
StringMap query = (StringMap) body.get("query");
Assert.assertEquals(query.get("isHot"), "N");
Double categoryId = (Double) query.get("categoryId");
Assert.assertTrue(categoryId.equals(new Double(1001)));
}
@Test
public void headParam() {
String headValue = "sqHeadsValue";
Assert.assertTrue(testRequest.headerParam0(headValue).contains(headValue), "False");
Map<Object, Object> heads = new HashMap<>();
heads.put(HttpConstants.HEAD_KEY_CONTENT_TYPE, HttpConstants.CONTENT_TYPE_TXT_PLAIN);
heads.put("sqHeads1", "sqHeadsValue1");
heads.put("sqHeads2", 1);
heads.put(1000, new Date());
Assert.assertTrue(testRequest.headerParam1(heads).contains(headValue), "False");
}
@Test
public void testQueryStringget() {
testRequest.queryStringGet("aa");
}
@Test
public void testQueryStringPost() {
testRequest.queryStringPost("aa");
}
@Test
public void testQueryStringBodyPost() {
testRequest.queryStringBodyPost("{\"key\":\"sqmall\"}");
}
@Test
public void testResultStringPost() {
Result<String> res = testRequest.resultStringTestPost(true, "hello");
}
@Test(groups = {"manual"})
public void testUrlPropValFill() {
testRmiRequest.urlWithVariablePlaceHold("aa");
}
@Test(groups = {"manual"})
public void testUrlPropValFill2NonVal() {
boolean ok = false;
try {
testRmiRequest2.urlWithNoneExistVariablePlaceHold(null, 1002);
} catch (Exception e) {
if (e.getMessage().contains("Could not resolve placeholder 'non.val'")) {
ok = true;
return;
}
throw e;
}
throw new RuntimeException("No Exception expect happens!");
}
// @Test(groups = {"manual"})
// public void noStringConvertPresent(){
// boolean ok = false;
// try {
// testRmiRequest2.noStringConvertre(null, 1002);
// }catch (Exception e){
// if(e.getMessage().contains(MethodProxy.NO_STRCVT_EXCEP_MSG)){
// ok = true;
// return;
// }
// throw e;
// }
// throw new RuntimeException("No Exception expect happens!");
//
// }
@Test
public void postMultipart() {
String result = testRequest.postMultipart("pv值1", "pv2");
log.info(result);
Gson gson = new Gson();
ReturnInfo r = gson.fromJson(result, ReturnInfo.class);
Assert.assertNotNull(r);
Assert.assertEquals(r.getHeaders().get("Content-Type".toLowerCase()), "application/x-www-form-urlencoded");
StringMap body = (StringMap) r.getBody();
Assert.assertEquals(body.get("p1"), "pv值1");
Assert.assertEquals(body.get("p2"), "pv2");
}
@Test
public void voidResult() {
testRequest.voidResult("pv1", "pv2");
}
@Test
public void voidTimeout2S() {
try {
ReturnInfo r = testRequest.timeout2S("aaa");
} catch (Exception e) {
log.info("", e);
ReturnInfo r = testRequest.timeout30S("aaa");
Gson gson = new Gson();
log.info("successed:" + gson.toJson(r));
}
}
@Test
public void testLog() {
testRequest.logTest("" + HttpConstants.LMCC_UNKNOW, "" + HttpConstants.LMCC_UNKNOW);
testRequest.logTest1("" + HttpConstants.LMCC_ALL, "" + HttpConstants.LMCC_UNKNOW);
testRequest.logTest2("" + HttpConstants.LMCC_UNKNOW, "" + "-90");
testRequest.logTest3("" + HttpConstants.LMCC_UNKNOW, "" + HttpConstants.LMCC_UNKNOW);
testRequest.logTest4("" + "0", "" + HttpConstants.LMCC_UNKNOW);
testRequest.logTest5("" + "3", "" + "3");
testRequest.logTest6("" + HttpConstants.LMCC_UNKNOW, "" + HttpConstants.LMCC_UNKNOW);
testRequest.logTest7("" + "0", "" + "0");
}
@Test
public void voidTimeout10S() {
ReturnInfo r = testRequest.timeout10S("aaa");
}
@Test
public void voidTimeout30S() {
ReturnInfo r = testRequest.timeout30S("aaa");
}
@Test
public void voidTimeout30S2() {
try {
ReturnInfo r = testRequest.timeout30S2("aaa", 2000, 2000);
} catch (Exception e) {
log.info("", e);
ReturnInfo r = testRequest.timeout30S2("aaa", 30000, 2000);
Gson gson = new Gson();
log.info("successed:" + gson.toJson(r));
}
}
// @Test
// public void multiTargetTest(){
// String r = test2Request.postMultipart("pv1","pv2");
// log.info(r);
// }
@Test
public void testFileUpload() throws Exception {
String[] fileName = {"logback.xml", "中文测试文件.txt", "linux.jpg", "google.png"};
File[] files = {new File(URLDecoder.decode(ClassLoader.getSystemResource(fileName[0]).getFile(), StandardCharsets.UTF_8.name())),
new File(URLDecoder.decode(ClassLoader.getSystemResource(fileName[1]).getFile(), StandardCharsets.UTF_8.name())),
new File(URLDecoder.decode(ClassLoader.getSystemResource(fileName[2]).getFile(), StandardCharsets.UTF_8.name())),
new File(URLDecoder.decode(ClassLoader.getSystemResource(fileName[3]).getFile(), StandardCharsets.UTF_8.name()))
};
List<UploadFileInfo> result = testRequest.fileTest("lala啦", files[0], files[0], files[1], files[2], files[3]);
int count = 0;
for (UploadFileInfo uploadFileInfo : result) {
if (TestRequest.GIVE_FILENAME.equals(uploadFileInfo.getFieldname())) {
continue;
}
for (int i = 0; i < files.length; i++) {
if (files[i].getName().equals(uploadFileInfo.getOriginalname())) {
//验证文件大小
Assert.assertEquals(uploadFileInfo.getSize().longValue(), files[i].length());
log.info(files[i].getName() + " OK!");
count++;
}
}
}
Assert.assertEquals(fileName.length, count); //验证文件名个数
}
@Test
public void testExpress() {
System.out.print(testRmiRequest.expressInfo("http://www.kuaidi100.com/query?type=shentong&postid=3346342356872", 3000, 3000, null));
}
// @Test
// public void testKdn(){
// String param = "RequestData=%7B%27OrderCode%27%3A%27%27%2C%27ShipperCode%27%3A%27ANE%27%2C%27LogisticCode%27%3A%2730000086155462%27%7D&EBusinessID=1263883&DataType=2&DataSign=NDc5YWY2MDFkMDIyYWUxZTRhNDBlZjA0MWRmODk2YzY%3D&RequestType=1002";
// log.info("ExpressBirdResult:getResultByApi=======request: "+param);
// Map<String,String> headers=new HashMap<>();
// headers.put("Content-Type", "application/x-www-form-urlencoded");
// String str = dynamicRequest.commonPostRequest("http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx",param,headers);
// }
@Test
public void thirdPost() {
testRequest.headerParam0("0");
testRequest.headerParam0("0");
testRequest.headerParam0("0");
}
@Test
public void testParamOrder4Get() {
String res = testRequest.paramOrder4get("1", "2");
System.out.println(res);
Map<String, Object> paras = new HashMap();
paras.put("p3", "3");
paras.put("p5", "5");
paras.put("p6", "6");
paras.put("p8", "8");
res = testRequest.paramOrder4get("1", "2", paras);
System.out.println(res);
}
}
| dcais/aggra | src/test/java/com/github/dcais/aggra/test/TestMain.java |
66,028 | package com.tyrael.kharazim.web.controller.user;
import com.tyrael.kharazim.application.base.auth.AuthUser;
import com.tyrael.kharazim.application.system.dto.file.UploadFileVO;
import com.tyrael.kharazim.application.system.service.FileService;
import com.tyrael.kharazim.application.user.domain.Role;
import com.tyrael.kharazim.application.user.dto.user.request.AddUserRequest;
import com.tyrael.kharazim.application.user.dto.user.request.ChangePasswordRequest;
import com.tyrael.kharazim.application.user.dto.user.request.ModifyUserRequest;
import com.tyrael.kharazim.application.user.dto.user.request.PageUserRequest;
import com.tyrael.kharazim.application.user.enums.EnableStatusEnum;
import com.tyrael.kharazim.application.user.enums.UserCertificateTypeEnum;
import com.tyrael.kharazim.application.user.enums.UserGenderEnum;
import com.tyrael.kharazim.application.user.mapper.RoleMapper;
import com.tyrael.kharazim.common.dto.Pair;
import com.tyrael.kharazim.common.dto.Pairs;
import com.tyrael.kharazim.mock.MockMultipartFile;
import com.tyrael.kharazim.web.controller.BaseControllerTest;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.ByteArrayInputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static com.tyrael.kharazim.application.user.enums.UserGenderEnum.FEMALE;
import static com.tyrael.kharazim.application.user.enums.UserGenderEnum.MALE;
/**
* @author Tyrael Archangel
* @since 2023/12/27
*/
@Slf4j
class UserControllerTest extends BaseControllerTest<UserController> {
@Autowired
private RoleMapper roleMapper;
@Autowired
private FileService fileService;
UserControllerTest() {
super(UserController.class);
}
@Test
void get() {
super.performWhenCall(mockController.getById(1L));
}
@Test
void page() {
PageUserRequest pageUserRequest = new PageUserRequest();
pageUserRequest.setKeywords("admin");
pageUserRequest.setStatus(EnableStatusEnum.ENABLED);
super.performWhenCall(mockController.page(pageUserRequest));
}
@Test
@SuppressWarnings("all")
void add() throws Exception {
List<Role> roles = roleMapper.listAll();
Map<String, Role> roleMap = roles.stream()
.collect(Collectors.toMap(Role::getName, e -> e));
List<Hero> heroes = new ArrayList<>(heroes());
Collections.shuffle(heroes);
Pairs<String, String> heroAvatars = heroAvatars();
Map<String, String> heroAvatarMap = heroAvatars.stream()
.collect(Collectors.toMap(Pair::left, Pair::right));
for (Hero hero : heroes) {
Role role = roleMap.get(hero.getRole());
AddUserRequest addUserRequest = new AddUserRequest();
addUserRequest.setName(hero.getName());
addUserRequest.setNickName(hero.getNickName());
addUserRequest.setGender(hero.getGender());
addUserRequest.setPhone("13812341234");
String avatarUrl = heroAvatarMap.get(hero.getName());
if (StringUtils.isNotBlank(avatarUrl)) {
try {
String fileId = uploadAvatar(hero.getName(), avatarUrl);
addUserRequest.setAvatar(fileId);
} catch (Exception e) {
log.error("get hero avatar error: " + e.getMessage(), e);
}
}
addUserRequest.setCertificateType(UserCertificateTypeEnum.ID_CARD);
addUserRequest.setCertificateCode("510823202308010001");
addUserRequest.setRoleId(role.getId());
addUserRequest.setRemark(hero.getRemark());
addUserRequest.setBirthday(hero.getRelease());
super.performWhenCall(mockController.add(addUserRequest));
}
}
private List<Hero> heroes() {
return List.of(
new Hero("Artanis", "阿塔尼斯", "斗士", MALE, "2015-10-27", "达拉姆的大主教"),
new Hero("Chen", "陈", "斗士", MALE, "2014-09-09", "传奇酒仙"),
new Hero("D.Va", "D.Va", "斗士", FEMALE, "2017-05-16", "MEKA驾驶员"),
new Hero("Deathwing", "死亡之翼", "斗士", MALE, "2019-12-03", "灭世者"),
new Hero("Dehaka", "德哈卡", "斗士", MALE, "2016-03-29", "原始虫群首领"),
new Hero("Gazlowe", "加兹鲁维", "斗士", MALE, "2014-01-01", "棘齿城老板"),
new Hero("Hogger", "霍格", "斗士", MALE, "2020-12-01", "艾尔文森林的祸患"),
new Hero("Imperius", "英普瑞斯", "斗士", MALE, "2019-01-08", "勇气大天使"),
new Hero("Leoric", "李奥瑞克", "斗士", MALE, "2015-07-21", "骷髅王"),
new Hero("Malthael", "马萨伊尔", "斗士", MALE, "2017-06-13", "死亡化身"),
new Hero("Ragnaros", "拉格纳罗斯", "斗士", MALE, "2016-12-14", "炎魔之王"),
new Hero("Rexxar", "雷克萨", "斗士", MALE, "2015-09-08", "部落的勇士"),
new Hero("Sonya", "桑娅", "斗士", FEMALE, "2014-03-13", "迷途野蛮人"),
new Hero("Thrall", "萨尔", "斗士", MALE, "2015-01-13", "部落大酋长"),
new Hero("Varian", "瓦里安", "斗士", MALE, "2016-11-15", "联盟的至高王"),
new Hero("Xul", "祖尔", "斗士", MALE, "2016-03-01", "神秘的死灵法师"),
new Hero("Yrel", "伊瑞尔", "斗士", MALE, "2018-06-12", "希望之光"),
new Hero("Alexstrasza", "阿莱克丝塔萨", "治疗者", FEMALE, "2017-11-14", "生命缚誓者"),
new Hero("Ana", "安娜", "治疗者", FEMALE, "2017-09-26", "老练的狙击手"),
new Hero("Anduin", "安度因", "治疗者", MALE, "2019-04-30", "暴风城国王"),
new Hero("Auriel", "奥莉尔", "治疗者", FEMALE, "2016-08-09", "希望大天使"),
new Hero("Brightwing", "光明之翼", "治疗者", FEMALE, "2014-04-15", "精灵龙"),
new Hero("Deckard", "迪卡德", "治疗者", MALE, "2018-04-24", "赫拉迪姆最后一人"),
new Hero("Kharazim", "卡拉辛姆", "治疗者", MALE, "2015-08-18", "梵罗达尼武僧"),
new Hero("Li Li", "丽丽", "治疗者", FEMALE, "2014-04-15", "世界行者"),
new Hero("Lt. Morales", "莫拉莉斯中尉", "治疗者", FEMALE, "2015-10-06", "战地医疗兵"),
new Hero("Lúcio", "卢西奥", "治疗者", MALE, "2017-02-14", "自由战士DJ"),
new Hero("Malfurion", "玛法里奥", "治疗者", MALE, "2014-03-13", "大德鲁伊"),
new Hero("Rehgar", "雷加尔", "治疗者", MALE, "2014-07-22", "大地之环萨满"),
new Hero("Stukov", "斯托科夫", "治疗者", MALE, "2017-07-11", "被感染的中将"),
new Hero("Tyrande", "泰兰德", "治疗者", FEMALE, "2014-03-13", "艾露恩的高阶女祭司"),
new Hero("Uther", "乌瑟尔", "治疗者", MALE, "2014-03-13", "光明使者"),
new Hero("Whitemane", "怀特迈恩", "治疗者", FEMALE, "2018-08-07", "大检察官"),
new Hero("Alarak", "阿拉纳克", "近刺", MALE, "2016-09-13", "塔达林的高阶领主"),
new Hero("Illidan", "伊利丹", "近刺", MALE, "2014-03-13", "背叛者"),
new Hero("Kerrigan", "凯瑞甘", "近刺", FEMALE, "2014-03-13", "刀锋女王"),
new Hero("Maiev", "玛维", "近刺", FEMALE, "2018-02-06", "守望者"),
new Hero("Murky", "奔波尔霸", "近刺", FEMALE, "2014-05-22", "鱼人宝宝"),
new Hero("Qhira", "琪拉", "近刺", FEMALE, "2019-08-06", "伊莱西亚赏金猎人"),
new Hero("Samuro", "萨穆罗", "近刺", MALE, "2016-10-18", "剑圣"),
new Hero("The Butcher", "屠夫", "近刺", MALE, "2015-06-30", "血肉雕刻者"),
new Hero("Valeera", "瓦莉拉", "近刺", FEMALE, "2017-01-24", "无冕者之影"),
new Hero("Zeratul", "泽拉图", "近刺", MALE, "2014-03-13", "黑暗教长"),
new Hero("Azmodan", "阿兹莫丹", "远刺", MALE, "2014-10-14", "罪恶之王"),
new Hero("Cassia", "卡西娅", "远刺", FEMALE, "2017-04-04", "亚马逊战争仕女"),
new Hero("Chromie", "克罗米", "远刺", FEMALE, "2016-05-17", "时光守护者"),
new Hero("Falstad", "弗斯塔德", "远刺", MALE, "2014-01-01", "蛮锤领主"),
new Hero("Fenix", "菲尼克斯", "远刺", MALE, "2018-03-27", "圣堂武士管理者"),
new Hero("Gall", "加尔", "远刺", MALE, "2015-11-17", "暮光之锤的酋长"),
new Hero("Genji", "源氏", "远刺", MALE, "2017-04-25", "半机械忍者"),
new Hero("Greymane", "格雷迈恩", "远刺", MALE, "2016-01-12", "狼人之王"),
new Hero("Gul'dan", "古尔丹", "远刺", MALE, "2016-07-12", "黑暗的化身"),
new Hero("Hanzo", "半藏", "远刺", MALE, "2017-12-12", "刺客大师"),
new Hero("Jaina", "吉安娜", "远刺", FEMALE, "2014-12-02", "大法师"),
new Hero("Junkrat", "狂鼠", "远刺", MALE, "2017-10-17", "渣客爆破手"),
new Hero("Kael'thas", "凯尔萨斯", "远刺", MALE, "2015-05-12", "太阳之王"),
new Hero("Kel'Thuzad", "克尔苏加德", "远刺", MALE, "2017-09-05", "纳克萨玛斯的大巫妖"),
new Hero("Li-Ming", "李敏", "远刺", FEMALE, "2016-02-02", "狂热的魔法师"),
new Hero("Lunara", "露娜拉", "远刺", FEMALE, "2015-12-15", "塞纳留斯的长女"),
new Hero("Mephisto", "墨菲斯托", "远刺", MALE, "2018-09-04", "憎恨之王"),
new Hero("Nazeebo", "纳兹波", "远刺", MALE, "2014-03-13", "异端巫医"),
new Hero("Nova", "诺娃", "远刺", FEMALE, "2014-03-13", "帝国幽灵特工"),
new Hero("Orphea", "奥菲娅", "远刺", FEMALE, "2018-11-13", "乌鸦庭继承人"),
new Hero("Probius", "普罗比斯", "远刺", MALE, "2017-03-14", "充满好奇心的探机"),
new Hero("Raynor", "雷诺", "远刺", MALE, "2014-03-13", "起义军指挥官"),
new Hero("Sgt. Hammer", "重锤军士", "远刺", FEMALE, "2014-03-13", "攻城坦克驾驶员"),
new Hero("Sylvanas", "希尔瓦娜斯", "远刺", FEMALE, "2015-03-24", "女妖之王"),
new Hero("Tassadar", "塔萨达尔", "远刺", MALE, "2014-01-01", "圣堂救世主"),
new Hero("Tracer", "猎空", "远刺", MALE, "2016-04-19", "守望先锋特工"),
new Hero("Tychus", "泰凯斯", "远刺", MALE, "2014-03-18", "臭名昭著的罪犯"),
new Hero("Valla", "维拉", "远刺", FEMALE, "2014-03-13", "猎魔人"),
new Hero("Zagara", "扎加拉", "远刺", FEMALE, "2014-06-25", "虫群之母"),
new Hero("Zul'jin", "祖尔金", "远刺", MALE, "2017-01-04", "阿曼尼督军"),
new Hero("Abathur", "阿巴瑟", "支援者", MALE, "2014-03-13", "进化大师"),
new Hero("Medivh", "麦迪文", "支援者", FEMALE, "2016-06-14", "最后的守护者"),
new Hero("The Lost Vikings", "失落的维京人", "支援者", MALE, "2015-02-10", "麻烦三人组"),
new Hero("Zarya", "查莉娅", "支援者", MALE, "2016-09-27", "俄罗斯卫士"),
new Hero("Anub'arak", "阿努巴拉克", "坦克", MALE, "2014-10-07", "叛变的国王"),
new Hero("Arthas", "阿尔萨斯", "坦克", MALE, "2014-03-13", "巫妖王"),
new Hero("Blaze", "布雷泽", "坦克", MALE, "2018-01-09", "精英火蝠"),
new Hero("Cho", "古", "坦克", MALE, "2015-11-17", "暮光之锤的酋长"),
new Hero("Diablo", "迪亚波罗", "坦克", MALE, "2014-03-13", "恐惧之王"),
new Hero("E.T.C.", "精英牛头人酋长", "坦克", MALE, "2014-01-01", "摇滚教父"),
new Hero("Garrosh", "加尔鲁什", "坦克", MALE, "2017-08-08", "地狱咆哮之子"),
new Hero("Johanna", "乔汉娜", "坦克", MALE, "2015-06-02", "萨卡兰姆圣教军"),
new Hero("Mal'Ganis", "玛尔加尼斯", "坦克", MALE, "2018-10-16", "纳斯雷兹姆领主"),
new Hero("Mei", "美", "坦克", FEMALE, "2020-06-23", "爱冒险的气象学家"),
new Hero("Muradin", "穆拉丁", "坦克", MALE, "2014-03-13", "山丘之王"),
new Hero("Stitches", "缝合怪", "坦克", MALE, "2014-01-01", "夜色镇的梦魇"),
new Hero("Tyrael", "泰瑞尔", "坦克", MALE, "2014-03-13", "正义天使"));
}
private Pairs<String, String> heroAvatars() {
return new Pairs<String, String>()
.append("Hogger", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/hogger/circleIcon.png")
.append("Mei", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/mei/circleIcon.png")
.append("Deathwing", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/deathwing/circleIcon.png")
.append("Qhira", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/qhira/circleIcon.png")
.append("Anduin", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/anduin/circleIcon.png")
.append("Imperius", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/imperius/circleIcon.png")
.append("Orphea", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/orphea/circleIcon.png")
.append("Mal'Ganis", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/malganis/circleIcon.png")
.append("Mephisto", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/mephisto/circleIcon.png")
.append("Whitemane", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/whitemane/circleIcon.png")
.append("Yrel", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/yrel/circleIcon.png")
.append("Deckard", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/deckard/circleIcon.png")
.append("Fenix", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/fenix/circleIcon.png")
.append("Maiev", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/maiev/circleIcon.png")
.append("Blaze", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/blaze/circleIcon.png")
.append("Hanzo", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/hanzo/circleIcon.png")
.append("Alexstrasza", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/alexstrasza/circleIcon.png")
.append("Junkrat", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/junkrat/circleIcon.png")
.append("Ana", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/ana/circleIcon.png")
.append("Kel'Thuzad", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/kelthuzad/circleIcon.png")
.append("Garrosh", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/garrosh/circleIcon.png")
.append("Stukov", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/stukov/circleIcon.png")
.append("Malthael", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/malthael/circleIcon.png")
.append("D.Va", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/dva/circleIcon.png")
.append("Genji", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/genji/circleIcon.png")
.append("Cassia", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/cassia/circleIcon.png")
.append("Probius", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/probius/circleIcon.png")
.append("Lúcio", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/lucio/circleIcon.png")
.append("Valeera", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/valeera/circleIcon.png")
.append("Zul'jin", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/zuljin/circleIcon.png")
.append("Ragnaros", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/ragnaros/circleIcon.png")
.append("Varian", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/varian/circleIcon.png")
.append("Samuro", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/samuro/circleIcon.png")
.append("Zarya", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/zarya/circleIcon.png")
.append("Alarak", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/alarak/circleIcon.png")
.append("Auriel", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/auriel/circleIcon.png")
.append("Gul'dan", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/guldan/circleIcon.png")
.append("Medivh", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/medivh/circleIcon.png")
.append("Chromie", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/chromie/circleIcon.png")
.append("Tracer", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/tracer/circleIcon.png")
.append("Dehaka", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/dehaka/circleIcon.png")
.append("Xul", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/xul/circleIcon.png")
.append("Li-Ming", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/li-ming/circleIcon.png")
.append("Greymane", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/greymane/circleIcon.png")
.append("Lunara", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/lunara/circleIcon.png")
.append("Cho", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/cho/circleIcon.png")
.append("Gall", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/gall/circleIcon.png")
.append("Artanis", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/artanis/circleIcon.png")
.append("Lt. Morales", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/lt-morales/circleIcon.png")
.append("Rexxar", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/rexxar/circleIcon.png")
.append("Kharazim", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/kharazim/circleIcon.png")
.append("Leoric", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/leoric/circleIcon.png")
.append("The Butcher", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/the-butcher/circleIcon.png")
.append("Johanna", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/johanna/circleIcon.png")
.append("Kael'thas", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/kaelthas/circleIcon.png")
.append("Sylvanas", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/sylvanas/circleIcon.png")
.append("The Lost Vikings", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/the-lost-vikings/circleIcon.png")
.append("Thrall", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/thrall/circleIcon.png")
.append("Jaina", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/jaina/circleIcon.png")
.append("Azmodan", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/azmodan/circleIcon.png")
.append("Anub'arak", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/anubarak/circleIcon.png")
.append("Chen", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/chen/circleIcon.png")
.append("Rehgar", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/rehgar/circleIcon.png")
.append("Zagara", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/zagara/circleIcon.png")
.append("Murky", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/murky/circleIcon.png")
.append("Brightwing", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/brightwing/circleIcon.png")
.append("Li Li", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/li-li/circleIcon.png")
.append("Tychus", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/tychus/circleIcon.png")
.append("Abathur", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/abathur/circleIcon.png")
.append("Arthas", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/arthas/circleIcon.png")
.append("Diablo", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/diablo/circleIcon.png")
.append("Illidan", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/illidan/circleIcon.png")
.append("Kerrigan", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/kerrigan/circleIcon.png")
.append("Malfurion", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/malfurion/circleIcon.png")
.append("Muradin", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/muradin/circleIcon.png")
.append("Nazeebo", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/nazeebo/circleIcon.png")
.append("Nova", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/nova/circleIcon.png")
.append("Raynor", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/raynor/circleIcon.png")
.append("Sgt. Hammer", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/sgt-hammer/circleIcon.png")
.append("Sonya", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/sonya/circleIcon.png")
.append("Tyrael", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/tyrael/circleIcon.png")
.append("Tyrande", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/tyrande/circleIcon.png")
.append("Uther", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/uther/circleIcon.png")
.append("Valla", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/valla/circleIcon.png")
.append("Zeratul", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/zeratul/circleIcon.png")
.append("E.T.C.", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/etc/circleIcon.png")
.append("Falstad", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/falstad/circleIcon.png")
.append("Gazlowe", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/gazlowe/circleIcon.png")
.append("Stitches", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/stitches/circleIcon.png")
.append("Tassadar", "https://static.heroesofthestorm.com/gd/6f704aac5aa2f1cfad17ee130347fb3b/heroes/tassadar/circleIcon.png");
}
private String uploadAvatar(String heroName, String url) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
HttpResponse<byte[]> httpResponse = HttpClient.newHttpClient()
.send(request, HttpResponse.BodyHandlers.ofByteArray());
byte[] body = httpResponse.body();
UploadFileVO uploadFileVO = new UploadFileVO();
uploadFileVO.setFileName(heroName + ".png");
uploadFileVO.setFile(new MockMultipartFile(heroName, new ByteArrayInputStream(body)));
return fileService.upload(uploadFileVO, super.mockAdmin()).getFileId();
}
@Test
void modify() {
ModifyUserRequest modifyUserRequest = new ModifyUserRequest();
modifyUserRequest.setId(0L);
modifyUserRequest.setNickName("超级管理员");
modifyUserRequest.setEnglishName("admin");
modifyUserRequest.setGender(MALE);
modifyUserRequest.setRemark("admin");
modifyUserRequest.setBirthday(LocalDate.of(2023, Month.AUGUST, 1));
super.performWhenCall(mockController.modify(null, modifyUserRequest));
}
@Test
void changePassword() {
ChangePasswordRequest changePasswordRequest = new ChangePasswordRequest();
changePasswordRequest.setNewPassword("123456789");
changePasswordRequest.setOldPassword("123456");
AuthUser authUser = new AuthUser();
authUser.setId(1L);
authUser.setSuperAdmin(true);
authUser.setName("admin");
authUser.setNickName("超级管理员");
super.performWhenCall(mockController.changePassword(authUser, changePasswordRequest));
}
@Test
void resetPassword() {
super.performWhenCall(mockController.resetPassword(super.mockAdmin(), 3L));
}
@Getter
private static class Hero {
private final String name;
private final String nickName;
private final String role;
private final UserGenderEnum gender;
private final LocalDate release;
private final String remark;
Hero(String name, String nickName, String role, UserGenderEnum gender, String release, String remark) {
this.name = name;
this.nickName = nickName;
this.role = role;
this.gender = gender;
this.release = LocalDate.parse(release, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
this.remark = remark;
}
}
}
| Tyrael-Archangel/kharazim | kharazim-application/src/test/java/com/tyrael/kharazim/web/controller/user/UserControllerTest.java |
66,030 | /*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.view;
import android.graphics.Rect;
import android.util.ArrayMap;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* The algorithm 算法 used for finding the next focusable view in a given direction
* from a view that currently has focus.
*/
public class FocusFinder {
private static final ThreadLocal<FocusFinder> tlFocusFinder =
new ThreadLocal<FocusFinder>() {
@Override
protected FocusFinder initialValue() {
return new FocusFinder();
}
};
/**
* Get the focus finder for this thread.
*/
public static FocusFinder getInstance() {
return tlFocusFinder.get();
}
final Rect mFocusedRect = new Rect();
final Rect mOtherRect = new Rect();
final Rect mBestCandidateRect = new Rect();
final SequentialFocusComparator mSequentialFocusComparator = new SequentialFocusComparator(); // 连续的
private final ArrayList<View> mTempList = new ArrayList<View>();
// enforce thread local access
private FocusFinder() {}
/**
* Find the next view to take focus in root's descendants, starting from the view
* that currently is focused.
* @param root Contains focused. Cannot be null.
* @param focused Has focus now.
* @param direction Direction to look.
* @return The next focusable view, or null if none exists.
*/
public final View findNextFocus(ViewGroup root, View focused, int direction) {
return findNextFocus(root, focused, null, direction);
}
/**
* Find the next view to take focus in root's descendants, searching from
* a particular rectangle in root's coordinates.
* @param root Contains focusedRect. Cannot be null.
* @param focusedRect The starting point of the search.
* @param direction Direction to look.
* @return The next focusable view, or null if none exists.
*/
public View findNextFocusFromRect(ViewGroup root, Rect focusedRect, int direction) {
mFocusedRect.set(focusedRect);
return findNextFocus(root, null, mFocusedRect, direction);
}
private View findNextFocus(ViewGroup root, View focused, Rect focusedRect, int direction) {
View next = null;
if (focused != null) {
next = findNextUserSpecifiedFocus(root, focused, direction);
}
if (next != null) {
return next;
}
ArrayList<View> focusables = mTempList;
try {
focusables.clear();
root.addFocusables(focusables, direction);
if (!focusables.isEmpty()) {
next = findNextFocus(root, focused, focusedRect, direction, focusables);
}
} finally {
focusables.clear();
}
return next;
}
private View findNextUserSpecifiedFocus(ViewGroup root, View focused, int direction) {
// check for user specified next focus
View userSetNextFocus = focused.findUserSetNextFocus(root, direction);
if (userSetNextFocus != null && userSetNextFocus.isFocusable()
&& (!userSetNextFocus.isInTouchMode()
|| userSetNextFocus.isFocusableInTouchMode())) {
return userSetNextFocus;
}
return null;
}
private View findNextFocus(ViewGroup root, View focused, Rect focusedRect,
int direction, ArrayList<View> focusables) {
if (focused != null) {
if (focusedRect == null) {
focusedRect = mFocusedRect;
}
// fill in interesting rect from focused
focused.getFocusedRect(focusedRect);
root.offsetDescendantRectToMyCoords(focused, focusedRect);
} else {
if (focusedRect == null) {
focusedRect = mFocusedRect;
// make up a rect at top left or bottom right of root
switch (direction) {
case View.FOCUS_RIGHT:
case View.FOCUS_DOWN:
setFocusTopLeft(root, focusedRect);
break;
case View.FOCUS_FORWARD:
if (root.isLayoutRtl()) {
setFocusBottomRight(root, focusedRect);
} else {
setFocusTopLeft(root, focusedRect);
}
break;
case View.FOCUS_LEFT:
case View.FOCUS_UP:
setFocusBottomRight(root, focusedRect);
break;
case View.FOCUS_BACKWARD:
if (root.isLayoutRtl()) {
setFocusTopLeft(root, focusedRect);
} else {
setFocusBottomRight(root, focusedRect);
break;
}
}
}
}
switch (direction) {
case View.FOCUS_FORWARD:
case View.FOCUS_BACKWARD:
return findNextFocusInRelativeDirection(focusables, root, focused, focusedRect,
direction);
case View.FOCUS_UP:
case View.FOCUS_DOWN:
case View.FOCUS_LEFT:
case View.FOCUS_RIGHT:
return findNextFocusInAbsoluteDirection(focusables, root, focused,
focusedRect, direction);
default:
throw new IllegalArgumentException("Unknown direction: " + direction);
}
}
private View findNextFocusInRelativeDirection(ArrayList<View> focusables, ViewGroup root,
View focused, Rect focusedRect, int direction) {
try {
// Note: This sort is stable.
mSequentialFocusComparator.setRoot(root);
mSequentialFocusComparator.setIsLayoutRtl(root.isLayoutRtl());
mSequentialFocusComparator.setFocusables(focusables);
Collections.sort(focusables, mSequentialFocusComparator);
} finally {
mSequentialFocusComparator.recycle();
}
final int count = focusables.size();
switch (direction) {
case View.FOCUS_FORWARD:
return getNextFocusable(focused, focusables, count);
case View.FOCUS_BACKWARD:
return getPreviousFocusable(focused, focusables, count);
}
return focusables.get(count - 1);
}
private void setFocusBottomRight(ViewGroup root, Rect focusedRect) {
final int rootBottom = root.getScrollY() + root.getHeight();
final int rootRight = root.getScrollX() + root.getWidth();
focusedRect.set(rootRight, rootBottom, rootRight, rootBottom);
}
private void setFocusTopLeft(ViewGroup root, Rect focusedRect) {
final int rootTop = root.getScrollY();
final int rootLeft = root.getScrollX();
focusedRect.set(rootLeft, rootTop, rootLeft, rootTop);
}
View findNextFocusInAbsoluteDirection(ArrayList<View> focusables, ViewGroup root, View focused,
Rect focusedRect, int direction) {
// initialize the best candidate 候选人 to something impossible
// (so the first plausible 似是而非的 似合理的 似乎可信的 view will become the best choice)
mBestCandidateRect.set(focusedRect);
switch(direction) {
case View.FOCUS_LEFT:
mBestCandidateRect.offset(focusedRect.width() + 1, 0);
break;
case View.FOCUS_RIGHT:
mBestCandidateRect.offset(-(focusedRect.width() + 1), 0);
break;
case View.FOCUS_UP:
mBestCandidateRect.offset(0, focusedRect.height() + 1);
break;
case View.FOCUS_DOWN:
mBestCandidateRect.offset(0, -(focusedRect.height() + 1));
}
View closest = null;
int numFocusables = focusables.size();
for (int i = 0; i < numFocusables; i++) {
View focusable = focusables.get(i);
// only interested in other non-root views
if (focusable == focused || focusable == root) continue;
// get focus bounds of other view in same coordinate system
focusable.getFocusedRect(mOtherRect);
root.offsetDescendantRectToMyCoords(focusable, mOtherRect);
if (isBetterCandidate(direction, focusedRect, mOtherRect, mBestCandidateRect)) {
mBestCandidateRect.set(mOtherRect);
closest = focusable;
}
}
return closest;
}
private static View getNextFocusable(View focused, ArrayList<View> focusables, int count) {
if (focused != null) {
int position = focusables.lastIndexOf(focused);
if (position >= 0 && position + 1 < count) {
return focusables.get(position + 1);
}
}
if (!focusables.isEmpty()) {
return focusables.get(0);
}
return null;
}
private static View getPreviousFocusable(View focused, ArrayList<View> focusables, int count) {
if (focused != null) {
int position = focusables.indexOf(focused);
if (position > 0) {
return focusables.get(position - 1);
}
}
if (!focusables.isEmpty()) {
return focusables.get(count - 1);
}
return null;
}
/**
* Is rect1 a better candidate than rect2 for a focus search in a particular
* direction from a source rect? This is the core routine 程序 that determines
* the order of focus searching.
* @param direction the direction (up, down, left, right)
* @param source The source we are searching from
* @param rect1 The candidate rectangle
* @param rect2 The current best candidate.
* @return Whether the candidate is the new best.
*/
boolean isBetterCandidate(int direction, Rect source, Rect rect1, Rect rect2) {
// to be a better candidate, need to at least be a candidate in the first
// place :)
if (!isCandidate(source, rect1, direction)) {
return false;
}
// we know that rect1 is a candidate.. if rect2 is not a candidate,
// rect1 is better
if (!isCandidate(source, rect2, direction)) {
return true;
}
// if rect1 is better by beam, it wins
if (beamBeats(direction, source, rect1, rect2)) {
return true;
}
// if rect2 is better, then rect1 cant' be :)
if (beamBeats(direction, source, rect2, rect1)) {
return false;
}
// otherwise, do fudge-tastic 胡说 精彩的 comparison of the major and minor axis
return (getWeightedDistanceFor(
majorAxisDistance(direction, source, rect1),
minorAxisDistance(direction, source, rect1))
< getWeightedDistanceFor(
majorAxisDistance(direction, source, rect2),
minorAxisDistance(direction, source, rect2)));
}
/**
* One rectangle may be another candidate than another by virtue . 美德;优点;贞操;功效 of being
* exclusively 唯一地;专有地;排外地 in the beam of the source rect.
* @return Whether rect1 is a better candidate than rect2 by virtue of it being in src's
* beam
*/
boolean beamBeats(int direction, Rect source, Rect rect1, Rect rect2) {
final boolean rect1InSrcBeam = beamsOverlap(direction, source, rect1);
final boolean rect2InSrcBeam = beamsOverlap(direction, source, rect2);
//// TODO: 2017/8/29
// if rect1 isn't exclusively 唯一地;专有地; in the src beam, it doesn't win
if (rect2InSrcBeam || !rect1InSrcBeam) {
return false;
}
// we know rect1 is in the beam, and rect2 is not
// if rect1 is to the direction of, and rect2 is not, rect1 wins.
// for example, for direction left, if rect1 is to the left of the source
// and rect2 is below, then we always prefer the in beam rect1, since rect2
// could be reached by going down.
//// TODO: 2017/8/29
if (!isToDirectionOf(direction, source, rect2)) {
return true;
}
// for horizontal directions, being exclusively in beam always wins
if ((direction == View.FOCUS_LEFT || direction == View.FOCUS_RIGHT)) {
return true;
}
// for vertical directions, beams only beat up to a point:
// now, as long as rect2 isn't completely closer, rect1 wins
// e.g for direction down, completely closer means for rect2's top
// edge to be closer to the source's top edge than rect1's bottom edge.
return (majorAxisDistance(direction, source, rect1)
< majorAxisDistanceToFarEdge(direction, source, rect2));
}
/**
* Fudge-factor 容差系数 opportunity 机会 : how to calculate distance given major and minor
* axis distances. Warning: this fudge factor is finely tuned 精密调整 , be sure to
* run all focus tests if you dare tweak 敢调整 it.
*/
int getWeightedDistanceFor(int majorAxisDistance, int minorAxisDistance) {
return 13 * majorAxisDistance * majorAxisDistance
+ minorAxisDistance * minorAxisDistance;
}
/**
* Is destRect a candidate for the next focus given the direction? This
* checks whether the dest is at least partially 部分地 to the direction of (e.g left of)
* from source.
*
* Includes an edge case for an empty rect (which is used in some cases when
* searching from a point on the screen).
*/
boolean isCandidate(Rect srcRect, Rect destRect, int direction) {
switch (direction) {
case View.FOCUS_LEFT:
return (srcRect.right > destRect.right || srcRect.left >= destRect.right)
&& srcRect.left > destRect.left;
case View.FOCUS_RIGHT:
return (srcRect.left < destRect.left || srcRect.right <= destRect.left)
&& srcRect.right < destRect.right;
case View.FOCUS_UP:
return (srcRect.bottom > destRect.bottom || srcRect.top >= destRect.bottom)
&& srcRect.top > destRect.top;
case View.FOCUS_DOWN:
return (srcRect.top < destRect.top || srcRect.bottom <= destRect.top)
&& srcRect.bottom < destRect.bottom;
}
throw new IllegalArgumentException("direction must be one of "
+ "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}.");
}
/**
* Do the "beams [计量] 秤杆 " w.r.t with regard to 的缩写,意思是"关于".常用于email,网络聊天,短消息等等场合.也可以不加点,直接用wrt.
* the given direction's axis of rect1 and rect2 overlap 重叠 ?
* @param direction the direction (up, down, left, right)
* @param rect1 The first rectangle
* @param rect2 The second rectangle
* @return whether the beams overlap
*/
boolean beamsOverlap(int direction, Rect rect1, Rect rect2) {
switch (direction) {
case View.FOCUS_LEFT:
case View.FOCUS_RIGHT:
//// TODO: 2017/8/29
return (rect2.bottom >= rect1.top) && (rect2.top <= rect1.bottom);
case View.FOCUS_UP:
case View.FOCUS_DOWN:
return (rect2.right >= rect1.left) && (rect2.left <= rect1.right);
}
throw new IllegalArgumentException("direction must be one of "
+ "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}.");
}
/**
* e.g for left, is 'to left of'
*/
boolean isToDirectionOf(int direction, Rect src, Rect dest) {
switch (direction) {
case View.FOCUS_LEFT:
return src.left >= dest.right;
case View.FOCUS_RIGHT:
return src.right <= dest.left;
case View.FOCUS_UP:
return src.top >= dest.bottom;
case View.FOCUS_DOWN:
return src.bottom <= dest.top;
}
throw new IllegalArgumentException("direction must be one of "
+ "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}.");
}
/**
* @return The distance from the edge furthest in the given direction
* of source to the edge nearest in the given direction of dest. If the
* dest is not in the direction from source, return 0.
*/
static int majorAxisDistance(int direction, Rect source, Rect dest) {
return Math.max(0, majorAxisDistanceRaw(direction, source, dest));
}
static int majorAxisDistanceRaw(int direction, Rect source, Rect dest) {
switch (direction) {
case View.FOCUS_LEFT:
return source.left - dest.right;
case View.FOCUS_RIGHT:
return dest.left - source.right;
case View.FOCUS_UP:
return source.top - dest.bottom;
case View.FOCUS_DOWN:
return dest.top - source.bottom;
}
throw new IllegalArgumentException("direction must be one of "
+ "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}.");
}
/**
* @return The distance along the major axis w.r.t the direction from the
* edge of source to the far edge of dest. If the
* dest is not in the direction from source, return 1 (to break ties with
* {@link #majorAxisDistance}).
*/
static int majorAxisDistanceToFarEdge(int direction, Rect source, Rect dest) {
return Math.max(1, majorAxisDistanceToFarEdgeRaw(direction, source, dest));
}
static int majorAxisDistanceToFarEdgeRaw(int direction, Rect source, Rect dest) {
switch (direction) {
case View.FOCUS_LEFT:
return source.left - dest.left;
case View.FOCUS_RIGHT:
return dest.right - source.right;
case View.FOCUS_UP:
return source.top - dest.top;
case View.FOCUS_DOWN:
return dest.bottom - source.bottom;
}
throw new IllegalArgumentException("direction must be one of "
+ "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}.");
}
/**
* Find the distance on the minor axis w.r.t the direction to the nearest
* edge of the destination rectangle.
* @param direction the direction (up, down, left, right)
* @param source The source rect.
* @param dest The destination rect.
* @return The distance.
*/
static int minorAxisDistance(int direction, Rect source, Rect dest) {
switch (direction) {
case View.FOCUS_LEFT:
case View.FOCUS_RIGHT:
// the distance between the center verticals
return Math.abs(
((source.top + source.height() / 2) -
((dest.top + dest.height() / 2))));
case View.FOCUS_UP:
case View.FOCUS_DOWN:
// the distance between the center horizontals
return Math.abs(
((source.left + source.width() / 2) -
((dest.left + dest.width() / 2))));
}
throw new IllegalArgumentException("direction must be one of "
+ "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}.");
}
/**
* Find the nearest touchable view to the specified view.
*
* @param root The root of the tree in which to search
* @param x X coordinate from which to start the search
* @param y Y coordinate from which to start the search
* @param direction Direction to look
* @param deltas Offset from the <x, y> to the edge of the nearest view. Note that this array
* may already be populated with values.
* @return The nearest touchable view, or null if none exists.
*/
public View findNearestTouchable(ViewGroup root, int x, int y, int direction, int[] deltas) {
ArrayList<View> touchables = root.getTouchables();
int minDistance = Integer.MAX_VALUE;
View closest = null;
int numTouchables = touchables.size();
int edgeSlop = ViewConfiguration.get(root.mContext).getScaledEdgeSlop();
Rect closestBounds = new Rect();
Rect touchableBounds = mOtherRect;
for (int i = 0; i < numTouchables; i++) {
View touchable = touchables.get(i);
// get visible bounds of other view in same coordinate system
touchable.getDrawingRect(touchableBounds);
root.offsetRectBetweenParentAndChild(touchable, touchableBounds, true, true);
if (!isTouchCandidate(x, y, touchableBounds, direction)) {
continue;
}
int distance = Integer.MAX_VALUE;
switch (direction) {
case View.FOCUS_LEFT:
distance = x - touchableBounds.right + 1;
break;
case View.FOCUS_RIGHT:
distance = touchableBounds.left;
break;
case View.FOCUS_UP:
distance = y - touchableBounds.bottom + 1;
break;
case View.FOCUS_DOWN:
distance = touchableBounds.top;
break;
}
if (distance < edgeSlop) {
// Give preference to innermost views
if (closest == null ||
closestBounds.contains(touchableBounds) ||
(!touchableBounds.contains(closestBounds) && distance < minDistance)) {
minDistance = distance;
closest = touchable;
closestBounds.set(touchableBounds);
switch (direction) {
case View.FOCUS_LEFT:
deltas[0] = -distance;
break;
case View.FOCUS_RIGHT:
deltas[0] = distance;
break;
case View.FOCUS_UP:
deltas[1] = -distance;
break;
case View.FOCUS_DOWN:
deltas[1] = distance;
break;
}
}
}
}
return closest;
}
/**
* Is destRect a candidate for the next touch given the direction?
*/
private boolean isTouchCandidate(int x, int y, Rect destRect, int direction) {
switch (direction) {
case View.FOCUS_LEFT:
return destRect.left <= x && destRect.top <= y && y <= destRect.bottom;
case View.FOCUS_RIGHT:
return destRect.left >= x && destRect.top <= y && y <= destRect.bottom;
case View.FOCUS_UP:
return destRect.top <= y && destRect.left <= x && x <= destRect.right;
case View.FOCUS_DOWN:
return destRect.top >= y && destRect.left <= x && x <= destRect.right;
}
throw new IllegalArgumentException("direction must be one of "
+ "{FOCUS_UP, FOCUS_DOWN, FOCUS_LEFT, FOCUS_RIGHT}.");
}
private static final boolean isValidId(final int id) {
return id != 0 && id != View.NO_ID;
}
/**
* Sorts views according to their visual layout and geometry 几何结构 for default tab order.
* If views are part of a focus chain (nextFocusForwardId), then they are all grouped
* together. The head of the chain is used to determine the order of the chain and is
* first in the order and the tail of the chain is the last in the order. The views
* in the middle of the chain can be arbitrary order.
* This is used for sequential focus traversal.
*/
//// TODO: 2017/8/28
private static final class SequentialFocusComparator implements Comparator<View> {
private final Rect mFirstRect = new Rect();
private final Rect mSecondRect = new Rect();
private ViewGroup mRoot;
private boolean mIsLayoutRtl;
private final SparseArray<View> mFocusables = new SparseArray<View>();
private final SparseBooleanArray mIsConnectedTo = new SparseBooleanArray();
private final ArrayMap<View, View> mHeadsOfChains = new ArrayMap<View, View>();
public void recycle() {
mRoot = null;
mFocusables.clear();
mHeadsOfChains.clear();
mIsConnectedTo.clear();
}
public void setRoot(ViewGroup root) {
mRoot = root;
}
public void setIsLayoutRtl(boolean b) {
mIsLayoutRtl = b;
}
public void setFocusables(ArrayList<View> focusables) {
for (int i = focusables.size() - 1; i >= 0; i--) {
final View view = focusables.get(i);
final int id = view.getId();
if (isValidId(id)) {
mFocusables.put(id, view);
}
final int nextId = view.getNextFocusForwardId();
if (isValidId(nextId)) {
mIsConnectedTo.put(nextId, true);
}
}
for (int i = focusables.size() - 1; i >= 0; i--) {
final View view = focusables.get(i);
final int nextId = view.getNextFocusForwardId();
if (isValidId(nextId) && !mIsConnectedTo.get(view.getId())) {
setHeadOfChain(view);
}
}
}
private void setHeadOfChain(View head) {
for (View view = head; view != null; view = mFocusables.get(view.getNextFocusForwardId())) {
final View otherHead = mHeadsOfChains.get(view);
if (otherHead != null) {
if (otherHead == head) {
return; // This view has already had its head set properly
}
// A hydra 九头蛇 -- multi-headed focus chain (e.g. A->C and B->C)
// Use the one we've already chosen instead and reset this chain.
view = head;
head = otherHead;
}
mHeadsOfChains.put(view, head);
}
}
public int compare(View first, View second) {
if (first == second) {
return 0;
}
// Order between views within a chain is immaterial 非物质的;无形的;不重要的;非实质的 -- next/previous is
// within a chain is handled elsewhere.
View firstHead = mHeadsOfChains.get(first);
View secondHead = mHeadsOfChains.get(second);
if (firstHead == secondHead && firstHead != null) {
if (first == firstHead) {
return -1; // first is the head, it should be first
} else if (second == firstHead) {
return 1; // second is the head, it should be first
} else if (isValidId(first.getNextFocusForwardId())) {
return -1; // first is not the end of the chain
} else {
return 1; // first is end of chain
}
}
if (firstHead != null) {
first = firstHead;
}
if (secondHead != null) {
second = secondHead;
}
// First see if they belong to the same focus chain.
getRect(first, mFirstRect);
getRect(second, mSecondRect);
if (mFirstRect.top < mSecondRect.top) {
return -1;
} else if (mFirstRect.top > mSecondRect.top) {
return 1;
} else if (mFirstRect.left < mSecondRect.left) {
return mIsLayoutRtl ? 1 : -1;
} else if (mFirstRect.left > mSecondRect.left) {
return mIsLayoutRtl ? -1 : 1;
} else if (mFirstRect.bottom < mSecondRect.bottom) {
return -1;
} else if (mFirstRect.bottom > mSecondRect.bottom) {
return 1;
} else if (mFirstRect.right < mSecondRect.right) {
return mIsLayoutRtl ? 1 : -1;
} else if (mFirstRect.right > mSecondRect.right) {
return mIsLayoutRtl ? -1 : 1;
} else {
// The view are distinct but completely coincident so we consider
// them equal for our purposes. Since the sort is stable, this
// means that the views will retain their layout order relative to one another.
return 0;
}
}
private void getRect(View view, Rect rect) {
view.getDrawingRect(rect);
mRoot.offsetDescendantRectToMyCoords(view, rect);
}
}
}
| fengyunmars/android-24 | android/view/FocusFinder.java |
66,032 | package com.lizixuan.component;
import com.lizixuan.listener.ActionDoneListener;
import com.lizixuan.mysqloperation.BookManageJDBC;
import com.lizixuan.mysqloperation.DeleteBookJDBC;
import com.lizixuan.mysqloperation.SearchBookJDBC;
import com.lizixuan.util.PathUtils;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Vector;
public class AboutMe extends Box {
JFrame jf = null;
final int WIDTH = 1200;
final int HEIGHT = 600;
public AboutMe(JFrame jf) throws IOException {
// 垂直布局
super(BoxLayout.Y_AXIS);
//组装视图
this.jf = jf;
// 设置背景图片
BackGroundPanel bgPanel = new BackGroundPanel(ImageIO.read(new File(PathUtils.getRealPath("aboutme.png"))));
bgPanel.setBounds(0, 0, WIDTH, HEIGHT);
// 垂直布局
Box vBox = Box.createVerticalBox();
Box zBox = Box.createHorizontalBox();
JLabel zLabel = new JLabel("致 谢");
zLabel.setFont(new java.awt.Font("等线", 1, 30));
zBox.add(zLabel);
// 致谢内容
Box contentBox = Box.createHorizontalBox();
JLabel contentLabel = new JLabel("总结:");
JTextArea contentArea = new JTextArea(7,15);
contentArea.setText("\n\n\n\n总的来说这次的还算顺利吧,其中个人感觉比较困难的地方就属于是修改\n" +
"内容了,完成修改内容不单单需要根据ID查找到还需要更新数据,从数据\n" +
"库中传出内容的时候也是费很大的功夫,在这里感谢一下我的学长“北鱼不\n" +
"该在戴溪打怪”。再也没有非常难的地方,哦对了,登录验证那里,由于的\n" +
"技术不太精湛用了非常愚蠢的办法,但是还是成功的验证了数据库里面的帐\n" +
"号和密码!");
contentLabel.setFont(new java.awt.Font("等线", 1, 16));
contentArea.setOpaque(false);
contentArea.setEditable(false);
contentBox.add(contentLabel);
contentBox.add(contentArea);
// 作者
Box authorBox = Box.createHorizontalBox();
JLabel authorLabel = new JLabel("作者:");
JTextField authorField = new JTextField(15);
authorLabel.setFont(new java.awt.Font("等线", 1, 16));
authorField.setText("致敬(vx:lixuanzi99313)");
authorField.setBorder(null);
authorField.setOpaque(false);
authorField.setEditable(false);
authorBox.add(authorLabel);
authorBox.add(authorField);
// 鸣谢所有人员
Box thankBox = Box.createVerticalBox();
// 再次感谢一下成员提供的帮助和支持
Box titleBox = Box.createHorizontalBox();
JLabel titleLabel = new JLabel("再次感谢以下成员提供的帮助和支持");
titleLabel.setFont(new java.awt.Font("等线", 1, 18));
titleBox.add(titleLabel);
Box biliBox = Box.createHorizontalBox();
JTextField biliField = new JTextField();
JTextField urlBiliField = new JTextField();
biliField.setText("java教程 深入浅出讲解java的图形化界面编程");
urlBiliField.setText("https://www.bilibili.com/video/av839084699/");
biliField.setFont(new java.awt.Font("等线", 1, 15));
biliField.setBorder(null);
biliField.setOpaque(false);
biliField.setEditable(false);
urlBiliField.setFont(new java.awt.Font("等线", 1, 15));
urlBiliField.setBorder(null);
urlBiliField.setOpaque(false);
urlBiliField.setEditable(false);
biliBox.add(biliField);
biliBox.add(Box.createHorizontalStrut(15));
biliBox.add(urlBiliField);
// 特别鸣谢
Box specialBox = Box.createHorizontalBox();
JLabel specialLabel =new JLabel("特别鸣谢");
JTextField specialField = new JTextField();
specialLabel.setFont(new java.awt.Font("等线", 1, 15));
specialField.setText("北鱼不该在戴溪打怪");
specialField.setFont(new java.awt.Font("等线", 1, 15));
specialField.setBorder(null);
specialField.setOpaque(false);
specialField.setEditable(false);
specialBox.add(specialLabel);
specialBox.add(Box.createHorizontalStrut(255));
specialBox.add(specialField);
// 小组成员
Box groupBox = Box.createHorizontalBox();
JLabel groupLabel =new JLabel("小组成员");
JTextField groupField = new JTextField();
groupLabel.setFont(new java.awt.Font("等线", 1, 15));
groupField.setText("积云雨(啥也不干)、浮世(就聊过一次天)");
groupField.setFont(new java.awt.Font("等线", 1, 15));
groupField.setBorder(null);
groupField.setOpaque(false);
groupField.setEditable(false);
groupBox.add(groupLabel);
groupBox.add(Box.createHorizontalStrut(255));
groupBox.add(groupField);
// 其他致谢
Box otherBox = Box.createHorizontalBox();
JLabel otherLabel =new JLabel("其他致谢(听了我好多废话^_^)");
JTextArea otherField = new JTextArea();
otherLabel.setFont(new java.awt.Font("等线", 1, 15));
otherField.setText("陶陶\n\n"+"来日可期\n\n"+"仅我可见\n\n"+"胡说艺术家\n\n"+"城隔玖梦\n\n");
otherField.setFont(new java.awt.Font("等线", 1, 15));
otherField.setBorder(null);
otherField.setOpaque(false);
otherField.setEditable(false);
otherBox.add(otherLabel);
otherBox.add(Box.createHorizontalStrut(95));
otherBox.add(otherField);
thankBox.add(titleBox);
thankBox.add(Box.createVerticalStrut(30));
thankBox.add(biliBox);
thankBox.add(Box.createVerticalStrut(20));
thankBox.add(specialBox);
thankBox.add(Box.createVerticalStrut(20));
thankBox.add(groupBox);
thankBox.add(Box.createVerticalStrut(20));
thankBox.add(otherBox);
vBox.add(Box.createVerticalStrut(40));
vBox.add(zLabel); // 添加致谢二字
vBox.add(Box.createVerticalStrut(40));
/*vBox.add(contentBox); // 添加致谢内容
vBox.add(Box.createVerticalStrut(20));*/
vBox.add(authorBox);
vBox.add(Box.createVerticalStrut(50));
vBox.add(thankBox);
bgPanel.add(vBox);
this.add(bgPanel);
}
}
| lixuanzi/LibraryMansgementSystem | src/com/lizixuan/component/AboutMe.java |
66,035 | package offer;
import java.util.Arrays;
/**
* @author suruomo
* @date 2020/7/22 16:09
* @description:剑指offer 11 旋转数字的最小数字
* 输入一个递增排序的数组的一个旋转,输出旋转数组的最小元素。
* 例如,数组 [3,4,5,1,2] 为 [1,2,3,4,5] 的一个旋转,该数组的最小值为1。
*/
public class MinArray {
public static void main(String[] args) {
int[] numbers={3,4,5,1,2};
System.out.println(minArray(numbers));
}
/**
* 胡说八道法
* @param numbers
* @return
*/
private static int minArray(int[] numbers) {
int n=numbers.length;
Arrays.sort(numbers);
return numbers[0];
}
/**
* 二分法
* @param numbers
* @return
*/
private static int minArray1(int[] numbers){
int low = 0;
int high = numbers.length - 1;
while (low < high) {
int pivot = low + (high - low) / 2;
if (numbers[pivot] < numbers[high]) {
high = pivot;
} else if (numbers[pivot] > numbers[high]) {
low = pivot + 1;
} else {
//由于可能的重复元素存在,只缩小一部分
high -= 1;
}
}
return numbers[low];
}
}
| suruomo/Java-LeetCode | src/main/java/offer/MinArray.java |
66,036 | package com.silencefly96.base;
import android.content.Context;
import android.view.View;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.run.utils.base.BaseFragment;
import com.run.utils.base.BaseMultiRecyclerAdapter;
import com.run.utils.base.ThreeLayerListHelper;
import com.run.utils.base.ViewHolder;
import com.silencefly96.base.bean.Character;
import com.silencefly96.base.bean.Monster;
import com.silencefly96.base.bean.People;
import java.util.ArrayList;
import java.util.List;
public class MultiListFragment extends BaseFragment {
private RecyclerView multiList;
private List<Object> datas = new ArrayList<>();
private List<People> peoples = new ArrayList<>();
private List<Character> characters = new ArrayList<>();
private List<Monster> monsters = new ArrayList<>();
@Override
public int bindLayout() {
return R.layout.fragment_multi;
}
@Override
public void initView(View view) {
multiList = $(R.id.recycler);
}
@Override
public void initData() {
peoples.add(new People("man"));
peoples.add(new People("woman"));
characters.add(new Character("man", 0, "小智", "12" ,"真新镇"));
characters.add(new Character("woman", 0, "小霞", "12" ,"华蓝道馆"));
characters.add(new Character("man", 0, "小刚", "14" ,"尼比道馆"));
monsters.add(new Monster("皮卡丘", "小智", "电系"));
monsters.add(new Monster("妙蛙种子", "小智", "草系"));
monsters.add(new Monster("妙蛙种子", "小智", "水系"));
monsters.add(new Monster("可达鸭", "小霞", "念力系"));
monsters.add(new Monster("海星星", "小霞", "水系"));
monsters.add(new Monster("太阳珊瑚", "小霞", "水系"));
monsters.add(new Monster("大岩蛇", "小刚", "石系"));
monsters.add(new Monster("超音蝠", "小刚", "飞行系"));
monsters.add(new Monster("胡说树", "小刚", "石系"));
datas.addAll(peoples);
}
@Override
public void doBusiness(Context mContext) {
multiList.setLayoutManager(new LinearLayoutManager(mActivity));
multiList.addItemDecoration(new DividerItemDecoration(mActivity, DividerItemDecoration.VERTICAL));
final BaseMultiRecyclerAdapter adapter = new BaseMultiRecyclerAdapter(datas) {
@Override
public int getItemViewType(int position) {
Object item = datas.get(position);
if (item instanceof People) return 0;
if (item instanceof Character) return 1;
if (item instanceof Monster) return 2;
return 0;
}
@Override
public int convertType(int viewType) {
switch (viewType){
case 0:
return R.layout.item_people_list;
case 1:
return R.layout.item_data_list;
case 2:
return R.layout.item_monster_list;
default:
}
return R.layout.item_people_list;
}
@Override
public void convertView(ViewHolder viewHolder, Object itemObj, int viewType) {
switch (viewType){
case 0:
viewHolder.setText(R.id.people_sex, ((People)itemObj).getSex());
break;
case 1:
viewHolder.setText(R.id.order, ((Character)itemObj).getOrder() + "");
viewHolder.setText(R.id.name, ((Character)itemObj).getName());
viewHolder.setText(R.id.old, ((Character)itemObj).getOld());
viewHolder.setText(R.id.sex, ((Character)itemObj).getSex());
viewHolder.setText(R.id.from, ((Character)itemObj).getFrom());
final String say = "我叫" + ((Character)itemObj).getName() + "请多关照!";
viewHolder.setOnClickListener(R.id.name, view -> showToast(say));
break;
case 2:
viewHolder.setText(R.id.monster_name, ((Monster)itemObj).getName());
viewHolder.setText(R.id.monster_belong, ((Monster)itemObj).getBelong());
viewHolder.setText(R.id.monster_property, ((Monster)itemObj).getProperty());
break;
default:
}
}
};
//注意使用viewholder注册点击事件,第一项无点击效果,即点击事件在第一项中注册
adapter.setOnItemClickListener((view, itemObj, position) -> {
//方法一,直接数据操作,只能展开一项数据
ThreeLayerListHelper.sortDatas(datas, itemObj, peoples, characters, monsters);
//方法二,通过节点形式增删数据,能展开多项
//ThreeLayerListHelper.sortDatasByNode(datas, itemObj, peoples, characters, monsters);
//做一些其他操作 - 例如:第三项Monster提示语
if (itemObj instanceof Monster){
showToast("这是" + ((Monster)itemObj).getBelong()
+ "的" + ((Monster)itemObj).getName());
}
adapter.notifyDataSetChanged();
});
multiList.setAdapter(adapter);
}
}
| silencefly96/Utils | app/src/main/java/com/silencefly96/base/MultiListFragment.java |
66,038 | package xy.com.view5;
import android.animation.ObjectAnimator;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private MyListView listView;
private MyAdapter myAdapter;
private List<String> data = new ArrayList<String>();
private int lastVisibleItemPosition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (MyListView) findViewById(R.id.listView);
listView.setEmptyView(findViewById(R.id.textView));
// testData();
myAdapter = new MyAdapter(MainActivity.this, data);
listView.setAdapter(myAdapter);
//从第十一个开始显示,这个显示的是item
// listView.setSelection(10);
//没反应,第一个参数是以px作单位的
// listView.smoothScrollBy(1,100);
//没反应,参数是以px作单位的
// listView.smoothScrollByOffset(2);
//没反应
// listView.smoothScrollToPosition(5);
/**
* 滑动监听
*/
listView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("TAG", "触摸时操作");
break;
case MotionEvent.ACTION_MOVE:
Log.d("TAG", "移动时操作");
break;
case MotionEvent.ACTION_UP:
Log.d("TAG", "离开时操作");
break;
}
return false;
}
});
/**
* 滑动监听
*/
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
switch (scrollState) {
case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
Log.d("TAG", "滑动停止时");
break;
case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
Log.d("TAG", "正在滚动");
break;
case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
Log.d("TAG", "手指抛动");
break;
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
Log.d("TAG", "滚动");
if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount > 0) {
Log.d("TAG", "滚动到了最后一行");
}
if (firstVisibleItem > lastVisibleItemPosition) {
Log.d("TAG", "上滑");
} else if (firstVisibleItem < lastVisibleItemPosition) {
Log.d("TAG", "下滑");
}
lastVisibleItemPosition = firstVisibleItem;
Log.d("TAG", "可视区域第一个Item的id" + listView.getFirstVisiblePosition());
Log.d("TAG", "可视区域最后一个Item的id" + listView.getLastVisiblePosition());
}
});
}
/**
* 测试数据
*/
private void testData() {
for (int i = 0; i < 40; i++) {
data.add("" + i);
}
}
public void onClick(View view) {
listView.smoothScrollToPosition(0);
Snackbar.make(view, "正儿八经", 1000).setAction("胡说八道", new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "增加一项", Toast.LENGTH_LONG).show();
data.add("new");
myAdapter.notifyDataSetChanged();
}
}).show();
}
//最低滑动距离
private int mTouchSlop;
private int direction;
private float mFirst, mCurrentY;
private boolean mShow = true;
View.OnTouchListener myTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mFirst = event.getY();
break;
case MotionEvent.ACTION_MOVE:
mCurrentY = event.getY();
if (mCurrentY - mFirst > mTouchSlop) {
direction = 0;//down
} else if (mFirst - mCurrentY > mTouchSlop) {
direction = 1;//up
}
if (direction == 1) {
if (mShow) {
toolbarAnim(0);//hide
mShow = !mShow;
}
} else if (direction == 0) {
if (!mShow) {
toolbarAnim(1);//hide
mShow = !mShow;
}
}
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
};
private ObjectAnimator mAnimator;
private void toolbarAnim(int flag) {
if (mAnimator!= null && mAnimator.isRunning()){
mAnimator.cancel();
}
if (flag==0){
// mAnimator=ObjectAnimator.ofFloat()
}
}
}
| xieyang94/Study | view5/src/main/java/xy/com/view5/MainActivity.java |
66,039 | /*
* Copyright 2002-2019 the original author or authors.
*
* 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
*
* 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 org.springframework.beans.factory.support;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import org.apache.commons.logging.Log;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyAccessorUtils;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.InjectionPoint;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
import org.springframework.beans.factory.config.AutowiredPropertyMarker;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.DependencyDescriptor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.TypedStringValue;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.NamedThreadLocal;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.PriorityOrdered;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.MethodCallback;
import org.springframework.util.StringUtils;
/**
* Abstract bean factory superclass that implements default bean creation,
* with the full capabilities specified by the {@link RootBeanDefinition} class.
* Implements the {@link org.springframework.beans.factory.config.AutowireCapableBeanFactory}
* interface in addition to AbstractBeanFactory's {@link #createBean} method.
*
* <p>Provides bean creation (with constructor resolution), property population,
* wiring (including autowiring), and initialization. Handles runtime bean
* references, resolves managed collections, calls initialization methods, etc.
* Supports autowiring constructors, properties by name, and properties by type.
*
* <p>The main template method to be implemented by subclasses is
* {@link #resolveDependency(DependencyDescriptor, String, Set, TypeConverter)},
* used for autowiring by type. In case of a factory which is capable of searching
* its bean definitions, matching beans will typically be implemented through such
* a search. For other factory styles, simplified matching algorithms can be implemented.
*
* <p>Note that this class does <i>not</i> assume or implement bean definition
* registry capabilities. See {@link DefaultListableBeanFactory} for an implementation
* of the {@link org.springframework.beans.factory.ListableBeanFactory} and
* {@link BeanDefinitionRegistry} interfaces, which represent the API and SPI
* view of such a factory, respectively.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Rob Harrop
* @author Mark Fisher
* @author Costin Leau
* @author Chris Beams
* @author Sam Brannen
* @author Phillip Webb
* @see RootBeanDefinition
* @see DefaultListableBeanFactory
* @see BeanDefinitionRegistry
* @since 13.02.2004
*/
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory
implements AutowireCapableBeanFactory {
/**
* Strategy for creating bean instances.
*/
private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
/**
* Resolver strategy for method parameter names.
*/
@Nullable
private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer();
/**
* Whether to automatically try to resolve circular references between beans.
*/
private boolean allowCircularReferences = true;
/**
* Whether to resort to injecting a raw bean instance in case of circular reference,
* even if the injected bean eventually got wrapped.
*/
private boolean allowRawInjectionDespiteWrapping = false;
/**
* Dependency types to ignore on dependency check and autowire, as Set of
* Class objects: for example, String. Default is none.
*/
private final Set<Class<?>> ignoredDependencyTypes = new HashSet<>();
/**
* Dependency interfaces to ignore on dependency check and autowire, as Set of
* Class objects. By default, only the BeanFactory interface is ignored.
*/
private final Set<Class<?>> ignoredDependencyInterfaces = new HashSet<>();
/**
* The name of the currently created bean, for implicit dependency registration
* on getBean etc invocations triggered from a user-specified Supplier callback.
*/
private final NamedThreadLocal<String> currentlyCreatedBean = new NamedThreadLocal<>("Currently created bean");
/**
* Cache of unfinished FactoryBean instances: FactoryBean name to BeanWrapper.
*/
private final ConcurrentMap<String, BeanWrapper> factoryBeanInstanceCache = new ConcurrentHashMap<>();
/**
* Cache of candidate factory methods per factory class.
*/
private final ConcurrentMap<Class<?>, Method[]> factoryMethodCandidateCache = new ConcurrentHashMap<>();
/**
* Cache of filtered PropertyDescriptors: bean Class to PropertyDescriptor array.
*/
private final ConcurrentMap<Class<?>, PropertyDescriptor[]> filteredPropertyDescriptorsCache =
new ConcurrentHashMap<>();
/**
* Create a new AbstractAutowireCapableBeanFactory.
*/
public AbstractAutowireCapableBeanFactory() {
super();
ignoreDependencyInterface(BeanNameAware.class);
ignoreDependencyInterface(BeanFactoryAware.class);
ignoreDependencyInterface(BeanClassLoaderAware.class);
}
/**
* Create a new AbstractAutowireCapableBeanFactory with the given parent.
*
* @param parentBeanFactory parent bean factory, or {@code null} if none
*/
public AbstractAutowireCapableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
this();
setParentBeanFactory(parentBeanFactory);
}
/**
* Set the instantiation strategy to use for creating bean instances.
* Default is CglibSubclassingInstantiationStrategy.
*
* @see CglibSubclassingInstantiationStrategy
*/
public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
this.instantiationStrategy = instantiationStrategy;
}
/**
* Return the instantiation strategy to use for creating bean instances.
*/
protected InstantiationStrategy getInstantiationStrategy() {
return this.instantiationStrategy;
}
/**
* Set the ParameterNameDiscoverer to use for resolving method parameter
* names if needed (e.g. for constructor names).
* <p>Default is a {@link DefaultParameterNameDiscoverer}.
*/
public void setParameterNameDiscoverer(@Nullable ParameterNameDiscoverer parameterNameDiscoverer) {
this.parameterNameDiscoverer = parameterNameDiscoverer;
}
/**
* Return the ParameterNameDiscoverer to use for resolving method parameter
* names if needed.
*/
@Nullable
protected ParameterNameDiscoverer getParameterNameDiscoverer() {
return this.parameterNameDiscoverer;
}
/**
* Set whether to allow circular references between beans - and automatically
* try to resolve them.
* <p>Note that circular reference resolution means that one of the involved beans
* will receive a reference to another bean that is not fully initialized yet.
* This can lead to subtle and not-so-subtle side effects on initialization;
* it does work fine for many scenarios, though.
* <p>Default is "true". Turn this off to throw an exception when encountering
* a circular reference, disallowing them completely.
* <p><b>NOTE:</b> It is generally recommended to not rely on circular references
* between your beans. Refactor your application logic to have the two beans
* involved delegate to a third bean that encapsulates their common logic.
*/
public void setAllowCircularReferences(boolean allowCircularReferences) {
this.allowCircularReferences = allowCircularReferences;
}
/**
* Set whether to allow the raw injection of a bean instance into some other
* bean's property, despite the injected bean eventually getting wrapped
* (for example, through AOP auto-proxying).
* <p>This will only be used as a last resort in case of a circular reference
* that cannot be resolved otherwise: essentially, preferring a raw instance
* getting injected over a failure of the entire bean wiring process.
* <p>Default is "false", as of Spring 2.0. Turn this on to allow for non-wrapped
* raw beans injected into some of your references, which was Spring 1.2's
* (arguably unclean) default behavior.
* <p><b>NOTE:</b> It is generally recommended to not rely on circular references
* between your beans, in particular with auto-proxying involved.
*
* @see #setAllowCircularReferences
*/
public void setAllowRawInjectionDespiteWrapping(boolean allowRawInjectionDespiteWrapping) {
this.allowRawInjectionDespiteWrapping = allowRawInjectionDespiteWrapping;
}
/**
* Ignore the given dependency type for autowiring:
* for example, String. Default is none.
*/
public void ignoreDependencyType(Class<?> type) {
this.ignoredDependencyTypes.add(type);
}
/**
* Ignore the given dependency interface for autowiring.
* <p>This will typically be used by application contexts to register
* dependencies that are resolved in other ways, like BeanFactory through
* BeanFactoryAware or ApplicationContext through ApplicationContextAware.
* <p>By default, only the BeanFactoryAware interface is ignored.
* For further types to ignore, invoke this method for each type.
*
* @see org.springframework.beans.factory.BeanFactoryAware
* @see org.springframework.context.ApplicationContextAware
*/
public void ignoreDependencyInterface(Class<?> ifc) {
this.ignoredDependencyInterfaces.add(ifc);
}
@Override
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
super.copyConfigurationFrom(otherFactory);
if (otherFactory instanceof AbstractAutowireCapableBeanFactory) {
AbstractAutowireCapableBeanFactory otherAutowireFactory =
(AbstractAutowireCapableBeanFactory) otherFactory;
this.instantiationStrategy = otherAutowireFactory.instantiationStrategy;
this.allowCircularReferences = otherAutowireFactory.allowCircularReferences;
this.ignoredDependencyTypes.addAll(otherAutowireFactory.ignoredDependencyTypes);
this.ignoredDependencyInterfaces.addAll(otherAutowireFactory.ignoredDependencyInterfaces);
}
}
//-------------------------------------------------------------------------
// Typical methods for creating and populating external bean instances
//-------------------------------------------------------------------------
@Override
@SuppressWarnings("unchecked")
public <T> T createBean(Class<T> beanClass) throws BeansException {
// Use prototype bean definition, to avoid registering bean as dependent bean.
RootBeanDefinition bd = new RootBeanDefinition(beanClass);
bd.setScope(SCOPE_PROTOTYPE);
bd.allowCaching = ClassUtils.isCacheSafe(beanClass, getBeanClassLoader());
return (T) createBean(beanClass.getName(), bd, null);
}
@Override
public void autowireBean(Object existingBean) {
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
RootBeanDefinition bd = new RootBeanDefinition(ClassUtils.getUserClass(existingBean));
bd.setScope(SCOPE_PROTOTYPE);
bd.allowCaching = ClassUtils.isCacheSafe(bd.getBeanClass(), getBeanClassLoader());
BeanWrapper bw = new BeanWrapperImpl(existingBean);
initBeanWrapper(bw);
populateBean(bd.getBeanClass().getName(), bd, bw);
}
@Override
public Object configureBean(Object existingBean, String beanName) throws BeansException {
markBeanAsCreated(beanName);
BeanDefinition mbd = getMergedBeanDefinition(beanName);
RootBeanDefinition bd = null;
if (mbd instanceof RootBeanDefinition) {
RootBeanDefinition rbd = (RootBeanDefinition) mbd;
bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
}
if (bd == null) {
bd = new RootBeanDefinition(mbd);
}
if (!bd.isPrototype()) {
bd.setScope(SCOPE_PROTOTYPE);
bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
}
BeanWrapper bw = new BeanWrapperImpl(existingBean);
initBeanWrapper(bw);
populateBean(beanName, bd, bw);
return initializeBean(beanName, existingBean, bd);
}
//-------------------------------------------------------------------------
// Specialized methods for fine-grained control over the bean lifecycle
//-------------------------------------------------------------------------
@Override
public Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
bd.setScope(SCOPE_PROTOTYPE);
return createBean(beanClass.getName(), bd, null);
}
@Override
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
bd.setScope(SCOPE_PROTOTYPE);
if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
} else {
Object bean;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
bean = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(bd, null, parent),
getAccessControlContext());
} else {
bean = getInstantiationStrategy().instantiate(bd, null, parent);
}
populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean));
return bean;
}
}
@Override
public void autowireBeanProperties(Object existingBean, int autowireMode, boolean dependencyCheck)
throws BeansException {
if (autowireMode == AUTOWIRE_CONSTRUCTOR) {
throw new IllegalArgumentException("AUTOWIRE_CONSTRUCTOR not supported for existing bean instance");
}
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
RootBeanDefinition bd =
new RootBeanDefinition(ClassUtils.getUserClass(existingBean), autowireMode, dependencyCheck);
bd.setScope(SCOPE_PROTOTYPE);
BeanWrapper bw = new BeanWrapperImpl(existingBean);
initBeanWrapper(bw);
populateBean(bd.getBeanClass().getName(), bd, bw);
}
@Override
public void applyBeanPropertyValues(Object existingBean, String beanName) throws BeansException {
markBeanAsCreated(beanName);
BeanDefinition bd = getMergedBeanDefinition(beanName);
BeanWrapper bw = new BeanWrapperImpl(existingBean);
initBeanWrapper(bw);
applyPropertyValues(beanName, bd, bw, bd.getPropertyValues());
}
@Override
public Object initializeBean(Object existingBean, String beanName) {
return initializeBean(beanName, existingBean, null);
}
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
@Override
public void destroyBean(Object existingBean) {
new DisposableBeanAdapter(existingBean, getBeanPostProcessors(), getAccessControlContext()).destroy();
}
//-------------------------------------------------------------------------
// Delegate methods for resolving injection points
//-------------------------------------------------------------------------
@Override
public Object resolveBeanByName(String name, DependencyDescriptor descriptor) {
InjectionPoint previousInjectionPoint = ConstructorResolver.setCurrentInjectionPoint(descriptor);
try {
return getBean(name, descriptor.getDependencyType());
} finally {
ConstructorResolver.setCurrentInjectionPoint(previousInjectionPoint);
}
}
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName) throws BeansException {
return resolveDependency(descriptor, requestingBeanName, null, null);
}
//---------------------------------------------------------------------
// Implementation of relevant AbstractBeanFactory template methods
//---------------------------------------------------------------------
/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
*
* @see #doCreateBean
*/
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {
if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
// Prepare method overrides.
try {
mbdToUse.prepareMethodOverrides();
} catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}
try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
//第一次调用bean的后置处理器------aop
//主要判断该bd要不要生成对象 如果要生成对象就把该beanName放入map中 后面会做aop代理
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
} catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
} catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
} catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}
/**
* Actually create the specified bean. Pre-creation processing has already happened
* at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
* <p>Differentiates between default bean instantiation, use of a
* factory method, and autowiring a constructor.
*
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a new instance of the bean
* @throws BeanCreationException if the bean could not be created
* @see #instantiateBean
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
*/
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
// Instantiate the bean.
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
//判断该对象有没有被创建 有 就删除 返回
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//实例化bean 半成品 推断构造方法 第二次后置处理
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//第三次调用后置处理器 合并
//通过后置处理器来应用合并之后的bd
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
} catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
//判断是否允许循环依赖 单例 allowCircularReferences默认为true
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
//第四次调用后置处理器====需要判断是否aop
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
// Initialize the bean instance.
Object exposedObject = bean;
try {
//填充属性 也就是我们常说的自动注入
//里面会有第五次第六次的bena后置处理器的调用
populateBean(beanName, mbd, instanceWrapper);
//初始化spring
//里面会有第七次 第八次bean的后置处理器的调用
exposedObject = initializeBean(beanName, exposedObject, mbd);
} catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
} else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
} else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
// Register bean as disposable.
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
} catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
@Override
@Nullable
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
Class<?> targetType = determineTargetType(beanName, mbd, typesToMatch);
// Apply SmartInstantiationAwareBeanPostProcessors to predict the
// eventual type after a before-instantiation shortcut.
if (targetType != null && !mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
boolean matchingOnlyFactoryBean = typesToMatch.length == 1 && typesToMatch[0] == FactoryBean.class;
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
Class<?> predicted = ibp.predictBeanType(targetType, beanName);
if (predicted != null &&
(!matchingOnlyFactoryBean || FactoryBean.class.isAssignableFrom(predicted))) {
return predicted;
}
}
}
}
return targetType;
}
/**
* Determine the target type for the given bean definition.
*
* @param beanName the name of the bean (for error handling purposes)
* @param mbd the merged bean definition for the bean
* @param typesToMatch the types to match in case of internal type matching purposes
* (also signals that the returned {@code Class} will never be exposed to application code)
* @return the type for the bean if determinable, or {@code null} otherwise
*/
@Nullable
protected Class<?> determineTargetType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
Class<?> targetType = mbd.getTargetType();
if (targetType == null) {
targetType = (mbd.getFactoryMethodName() != null ?
getTypeForFactoryMethod(beanName, mbd, typesToMatch) :
resolveBeanClass(mbd, beanName, typesToMatch));
if (ObjectUtils.isEmpty(typesToMatch) || getTempClassLoader() == null) {
mbd.resolvedTargetType = targetType;
}
}
return targetType;
}
/**
* Determine the target type for the given bean definition which is based on
* a factory method. Only called if there is no singleton instance registered
* for the target bean already.
* <p>This implementation determines the type matching {@link #createBean}'s
* different creation strategies. As far as possible, we'll perform static
* type checking to avoid creation of the target bean.
*
* @param beanName the name of the bean (for error handling purposes)
* @param mbd the merged bean definition for the bean
* @param typesToMatch the types to match in case of internal type matching purposes
* (also signals that the returned {@code Class} will never be exposed to application code)
* @return the type for the bean if determinable, or {@code null} otherwise
* @see #createBean
*/
@Nullable
protected Class<?> getTypeForFactoryMethod(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
ResolvableType cachedReturnType = mbd.factoryMethodReturnType;
if (cachedReturnType != null) {
return cachedReturnType.resolve();
}
Class<?> commonType = null;
Method uniqueCandidate = mbd.factoryMethodToIntrospect;
if (uniqueCandidate == null) {
Class<?> factoryClass;
boolean isStatic = true;
String factoryBeanName = mbd.getFactoryBeanName();
if (factoryBeanName != null) {
if (factoryBeanName.equals(beanName)) {
throw new BeanDefinitionStoreException(mbd.getResourceDescription(), beanName,
"factory-bean reference points back to the same bean definition");
}
// Check declared factory method return type on factory class.
factoryClass = getType(factoryBeanName);
isStatic = false;
} else {
// Check declared factory method return type on bean class.
factoryClass = resolveBeanClass(mbd, beanName, typesToMatch);
}
if (factoryClass == null) {
return null;
}
factoryClass = ClassUtils.getUserClass(factoryClass);
// If all factory methods have the same return type, return that type.
// Can't clearly figure out exact method due to type converting / autowiring!
int minNrOfArgs =
(mbd.hasConstructorArgumentValues() ? mbd.getConstructorArgumentValues().getArgumentCount() : 0);
Method[] candidates = this.factoryMethodCandidateCache.computeIfAbsent(factoryClass,
clazz -> ReflectionUtils.getUniqueDeclaredMethods(clazz, ReflectionUtils.USER_DECLARED_METHODS));
for (Method candidate : candidates) {
if (Modifier.isStatic(candidate.getModifiers()) == isStatic && mbd.isFactoryMethod(candidate) &&
candidate.getParameterCount() >= minNrOfArgs) {
// Declared type variables to inspect?
if (candidate.getTypeParameters().length > 0) {
try {
// Fully resolve parameter names and argument values.
Class<?>[] paramTypes = candidate.getParameterTypes();
String[] paramNames = null;
ParameterNameDiscoverer pnd = getParameterNameDiscoverer();
if (pnd != null) {
paramNames = pnd.getParameterNames(candidate);
}
ConstructorArgumentValues cav = mbd.getConstructorArgumentValues();
Set<ConstructorArgumentValues.ValueHolder> usedValueHolders = new HashSet<>(paramTypes.length);
Object[] args = new Object[paramTypes.length];
for (int i = 0; i < args.length; i++) {
ConstructorArgumentValues.ValueHolder valueHolder = cav.getArgumentValue(
i, paramTypes[i], (paramNames != null ? paramNames[i] : null), usedValueHolders);
if (valueHolder == null) {
valueHolder = cav.getGenericArgumentValue(null, null, usedValueHolders);
}
if (valueHolder != null) {
args[i] = valueHolder.getValue();
usedValueHolders.add(valueHolder);
}
}
Class<?> returnType = AutowireUtils.resolveReturnTypeForFactoryMethod(
candidate, args, getBeanClassLoader());
uniqueCandidate = (commonType == null && returnType == candidate.getReturnType() ?
candidate : null);
commonType = ClassUtils.determineCommonAncestor(returnType, commonType);
if (commonType == null) {
// Ambiguous return types found: return null to indicate "not determinable".
return null;
}
} catch (Throwable ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to resolve generic return type for factory method: " + ex);
}
}
} else {
uniqueCandidate = (commonType == null ? candidate : null);
commonType = ClassUtils.determineCommonAncestor(candidate.getReturnType(), commonType);
if (commonType == null) {
// Ambiguous return types found: return null to indicate "not determinable".
return null;
}
}
}
}
mbd.factoryMethodToIntrospect = uniqueCandidate;
if (commonType == null) {
return null;
}
}
// Common return type found: all factory methods return same type. For a non-parameterized
// unique candidate, cache the full type declaration context of the target factory method.
cachedReturnType = (uniqueCandidate != null ?
ResolvableType.forMethodReturnType(uniqueCandidate) : ResolvableType.forClass(commonType));
mbd.factoryMethodReturnType = cachedReturnType;
return cachedReturnType.resolve();
}
/**
* This implementation attempts to query the FactoryBean's generic parameter metadata
* if present to determine the object type. If not present, i.e. the FactoryBean is
* declared as a raw type, checks the FactoryBean's {@code getObjectType} method
* on a plain instance of the FactoryBean, without bean properties applied yet.
* If this doesn't return a type yet, and {@code allowInit} is {@code true} a
* full creation of the FactoryBean is used as fallback (through delegation to the
* superclass's implementation).
* <p>The shortcut check for a FactoryBean is only applied in case of a singleton
* FactoryBean. If the FactoryBean instance itself is not kept as singleton,
* it will be fully created to check the type of its exposed object.
*/
@Override
protected ResolvableType getTypeForFactoryBean(String beanName, RootBeanDefinition mbd, boolean allowInit) {
// Check if the bean definition itself has defined the type with an attribute
ResolvableType result = getTypeForFactoryBeanFromAttributes(mbd);
if (result != ResolvableType.NONE) {
return result;
}
ResolvableType beanType =
(mbd.hasBeanClass() ? ResolvableType.forClass(mbd.getBeanClass()) : ResolvableType.NONE);
// For instance supplied beans try the target type and bean class
if (mbd.getInstanceSupplier() != null) {
result = getFactoryBeanGeneric(mbd.targetType);
if (result.resolve() != null) {
return result;
}
result = getFactoryBeanGeneric(beanType);
if (result.resolve() != null) {
return result;
}
}
// Consider factory methods
String factoryBeanName = mbd.getFactoryBeanName();
String factoryMethodName = mbd.getFactoryMethodName();
// Scan the factory bean methods
if (factoryBeanName != null) {
if (factoryMethodName != null) {
// Try to obtain the FactoryBean's object type from its factory method
// declaration without instantiating the containing bean at all.
BeanDefinition factoryBeanDefinition = getBeanDefinition(factoryBeanName);
Class<?> factoryBeanClass;
if (factoryBeanDefinition instanceof AbstractBeanDefinition &&
((AbstractBeanDefinition) factoryBeanDefinition).hasBeanClass()) {
factoryBeanClass = ((AbstractBeanDefinition) factoryBeanDefinition).getBeanClass();
} else {
RootBeanDefinition fbmbd = getMergedBeanDefinition(factoryBeanName, factoryBeanDefinition);
factoryBeanClass = determineTargetType(factoryBeanName, fbmbd);
}
if (factoryBeanClass != null) {
result = getTypeForFactoryBeanFromMethod(factoryBeanClass, factoryMethodName);
if (result.resolve() != null) {
return result;
}
}
}
// If not resolvable above and the referenced factory bean doesn't exist yet,
// exit here - we don't want to force the creation of another bean just to
// obtain a FactoryBean's object type...
if (!isBeanEligibleForMetadataCaching(factoryBeanName)) {
return ResolvableType.NONE;
}
}
// If we're allowed, we can create the factory bean and call getObjectType() early
if (allowInit) {
FactoryBean<?> factoryBean = (mbd.isSingleton() ?
getSingletonFactoryBeanForTypeCheck(beanName, mbd) :
getNonSingletonFactoryBeanForTypeCheck(beanName, mbd));
if (factoryBean != null) {
// Try to obtain the FactoryBean's object type from this early stage of the instance.
Class<?> type = getTypeForFactoryBean(factoryBean);
if (type != null) {
return ResolvableType.forClass(type);
}
// No type found for shortcut FactoryBean instance:
// fall back to full creation of the FactoryBean instance.
return super.getTypeForFactoryBean(beanName, mbd, true);
}
}
if (factoryBeanName == null && mbd.hasBeanClass() && factoryMethodName != null) {
// No early bean instantiation possible: determine FactoryBean's type from
// static factory method signature or from class inheritance hierarchy...
return getTypeForFactoryBeanFromMethod(mbd.getBeanClass(), factoryMethodName);
}
result = getFactoryBeanGeneric(beanType);
if (result.resolve() != null) {
return result;
}
return ResolvableType.NONE;
}
private ResolvableType getFactoryBeanGeneric(@Nullable ResolvableType type) {
if (type == null) {
return ResolvableType.NONE;
}
return type.as(FactoryBean.class).getGeneric();
}
/**
* Introspect the factory method signatures on the given bean class,
* trying to find a common {@code FactoryBean} object type declared there.
*
* @param beanClass the bean class to find the factory method on
* @param factoryMethodName the name of the factory method
* @return the common {@code FactoryBean} object type, or {@code null} if none
*/
private ResolvableType getTypeForFactoryBeanFromMethod(Class<?> beanClass, String factoryMethodName) {
// CGLIB subclass methods hide generic parameters; look at the original user class.
Class<?> factoryBeanClass = ClassUtils.getUserClass(beanClass);
FactoryBeanMethodTypeFinder finder = new FactoryBeanMethodTypeFinder(factoryMethodName);
ReflectionUtils.doWithMethods(factoryBeanClass, finder, ReflectionUtils.USER_DECLARED_METHODS);
return finder.getResult();
}
/**
* This implementation attempts to query the FactoryBean's generic parameter metadata
* if present to determine the object type. If not present, i.e. the FactoryBean is
* declared as a raw type, checks the FactoryBean's {@code getObjectType} method
* on a plain instance of the FactoryBean, without bean properties applied yet.
* If this doesn't return a type yet, a full creation of the FactoryBean is
* used as fallback (through delegation to the superclass's implementation).
* <p>The shortcut check for a FactoryBean is only applied in case of a singleton
* FactoryBean. If the FactoryBean instance itself is not kept as singleton,
* it will be fully created to check the type of its exposed object.
*/
@Override
@Deprecated
@Nullable
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
return getTypeForFactoryBean(beanName, mbd, true).resolve();
}
/**
* Obtain a reference for early access to the specified bean,
* typically for the purpose of resolving a circular reference.
*
* @param beanName the name of the bean (for error handling purposes)
* @param mbd the merged bean definition for the bean
* @param bean the raw bean instance
* @return the object to expose as bean reference
*/
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
//这个方法内容比较少,但是很复杂,因为是对后置处理器的调用
//关于后置处理器笔者其实要说话很多很多
//现在市面上可见的资料或者书籍对后置处理器的说法笔者一般都不苟同
//我在B站上传过一个4个小时的视频,其中对spring后置处理器做了详细的分析
//也提出了一些自己的理解和主流理解不同的地方,有兴趣同学可以去看看
//其实简单说--这个方法作用主要是为了来处理aop的;
//当然还有其他功能,但是一般的读者最熟悉的就是aop
//这里我说明一下,aop的原理或者流程有很多书籍说到过
//但是笔者今天亲测了,现在市面可见的资料和书籍对aop的说法都不全
//很多资料提到aop是在spring bean的生命周期里面填充属性之后的代理周期完成的
//而这个代理周期甚至是在执行生命周期回调方法之后的一个周期
//那么问题来了?什么叫spring生命周期回调方法周期呢?
// 首先spring bean生命周期和spring生命周期回调方法周期是两个概念
//spring生命周期回调方法是spring bean生命周期的一部分、或者说一个周期
//简单理解就是spring bean的生命的某个过程会去执行spring的生命周期的回调方法
//比如你在某个bean的方法上面写一个加@PostConstruct的方法(一般称bean初始化方法)
//那么这个方法会在spring实例化一个对象之后,填充属性之后执行这个加注解的方法
//我这里叫做spring 生命周期回调方法的生命周期,不是我胡说,有官方文档可以参考的
//在执行完spring生命周期回调方法的生命周期之后才会执行代理生命周期
//在代理这个生命周期当中如果有需要会完成aop的功能
//以上是现在主流的说法,也是一般书籍或者“某些大师”的说法
//但是在循环引用的时候就不一样了,循环引用的情况下这个周期这里就完成了aop的代理
//这个周期严格意义上是在填充属性之前(填充属性也是一个生命周期阶段)
//填充属性的周期甚至在生命周期回调方法之前,更在代理这个周期之前了
//简单来说主流说法代理的生命周期比如在第8个周期或者第八步吧
//但是笔者这里得出的结论,如果一个bean是循环引用的则代理的周期可能在第3步就完成了
//那么为什么需要在第三步就完成呢?
//试想一下A、B两个类,现在对A类做aop处理,也就是需要对A代理
/** 不考虑循环引用 spring 先实例化A,然后走生命周期确实在第8个周期完成的代理
关于这个结论可以去看b站我讲的spring aop源码分析
但是如果是循环依赖就会有问题
比如spring 实例化A 然后发现需要注入B这个时候A还没有走到8步
还没有完成代理,发觉需要注入B,便去创建B,创建B的时候
发觉需要注入A,于是创建A,创建的过程中通过getSingleton
得到了a对象,注意是对象,一个没有完成代理的对象
然后把这个a注入给B?这样做合适吗?注入的a根本没有aop功能;显然不合适
因为b中注入的a需要是一个代理对象
而这个时候a存在第二个map中;不是一个代理对象;
于是我在第二个map中就不能单纯的存一个对象,需要存一个工厂
这个工厂在特殊的时候需要对a对象做改变,比如这里说的代理(需要aop功能的情况)
这也是三个map存在的必要性,不知道读者能不能get到点
*/
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
//---------------------------------------------------------------------
// Implementation methods
//---------------------------------------------------------------------
/**
* Obtain a "shortcut" singleton FactoryBean instance to use for a
* {@code getObjectType()} call, without full initialization of the FactoryBean.
*
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return the FactoryBean instance, or {@code null} to indicate
* that we couldn't obtain a shortcut FactoryBean instance
*/
@Nullable
private FactoryBean<?> getSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
synchronized (getSingletonMutex()) {
BeanWrapper bw = this.factoryBeanInstanceCache.get(beanName);
if (bw != null) {
return (FactoryBean<?>) bw.getWrappedInstance();
}
Object beanInstance = getSingleton(beanName, false);
if (beanInstance instanceof FactoryBean) {
return (FactoryBean<?>) beanInstance;
}
if (isSingletonCurrentlyInCreation(beanName) ||
(mbd.getFactoryBeanName() != null && isSingletonCurrentlyInCreation(mbd.getFactoryBeanName()))) {
return null;
}
Object instance;
try {
// Mark this bean as currently in creation, even if just partially.
beforeSingletonCreation(beanName);
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
instance = resolveBeforeInstantiation(beanName, mbd);
if (instance == null) {
bw = createBeanInstance(beanName, mbd, null);
instance = bw.getWrappedInstance();
}
} catch (UnsatisfiedDependencyException ex) {
// Don't swallow, probably misconfiguration...
throw ex;
} catch (BeanCreationException ex) {
// Instantiation failure, maybe too early...
if (logger.isDebugEnabled()) {
logger.debug("Bean creation exception on singleton FactoryBean type check: " + ex);
}
onSuppressedException(ex);
return null;
} finally {
// Finished partial creation of this bean.
afterSingletonCreation(beanName);
}
FactoryBean<?> fb = getFactoryBean(beanName, instance);
if (bw != null) {
this.factoryBeanInstanceCache.put(beanName, bw);
}
return fb;
}
}
/**
* Obtain a "shortcut" non-singleton FactoryBean instance to use for a
* {@code getObjectType()} call, without full initialization of the FactoryBean.
*
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return the FactoryBean instance, or {@code null} to indicate
* that we couldn't obtain a shortcut FactoryBean instance
*/
@Nullable
private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
if (isPrototypeCurrentlyInCreation(beanName)) {
return null;
}
Object instance;
try {
// Mark this bean as currently in creation, even if just partially.
beforePrototypeCreation(beanName);
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
instance = resolveBeforeInstantiation(beanName, mbd);
if (instance == null) {
BeanWrapper bw = createBeanInstance(beanName, mbd, null);
instance = bw.getWrappedInstance();
}
} catch (UnsatisfiedDependencyException ex) {
// Don't swallow, probably misconfiguration...
throw ex;
} catch (BeanCreationException ex) {
// Instantiation failure, maybe too early...
if (logger.isDebugEnabled()) {
logger.debug("Bean creation exception on non-singleton FactoryBean type check: " + ex);
}
onSuppressedException(ex);
return null;
} finally {
// Finished partial creation of this bean.
afterPrototypeCreation(beanName);
}
return getFactoryBean(beanName, instance);
}
/**
* Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
* invoking their {@code postProcessMergedBeanDefinition} methods.
*
* @param mbd the merged bean definition for the bean
* @param beanType the actual type of the managed bean instance
* @param beanName the name of the bean
* @see MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition
*/
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}
/**
* Apply before-instantiation post-processors, resolving whether there is a
* before-instantiation shortcut for the specified bean.
*
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return the shortcut-determined bean instance, or {@code null} if none
*/
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
/**
* Apply InstantiationAwareBeanPostProcessors to the specified bean definition
* (by class and name), invoking their {@code postProcessBeforeInstantiation} methods.
* <p>Any returned object will be used as the bean instead of actually instantiating
* the target bean. A {@code null} return value from the post-processor will
* result in the target bean being instantiated.
*
* @param beanClass the class of the bean to be instantiated
* @param beanName the name of the bean
* @return the bean object to use instead of a default instance of the target bean, or {@code null}
* @see InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
*/
@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
/**
* Create a new instance for the specified bean, using an appropriate instantiation strategy:
* factory method, constructor autowiring, or simple instantiation.
*
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a BeanWrapper for the new instance
* @see #obtainFromSupplier
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
* @see #instantiateBean
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//@Configuration 该注解的类中的@bean方法 bd中会存在factoryMethodName 用该方法创建对象
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
// Shortcut when re-creating the same bean...
//判断构造方法有没有被解析 默认没有
boolean resolved = false;
//需不需要被注入
boolean autowireNecessary = false;
if (args == null) {
//创建对象的快捷方式 为什么会有这么个玩意?
//因为在原型的情况下 就不需要在去解析构造方法了
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
} else {
return instantiateBean(beanName, mbd);
}
}
// Candidate constructors for autowiring?
//第二次调用bean的后置处理器---推断多少构造方法找出有质疑的构造方法
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}
/**
* Obtain a bean instance from the given supplier.
*
* @param instanceSupplier the configured supplier
* @param beanName the corresponding bean name
* @return a BeanWrapper for the new instance
* @see #getObjectForBeanInstance
* @since 5.0
*/
protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) {
Object instance;
String outerBean = this.currentlyCreatedBean.get();
this.currentlyCreatedBean.set(beanName);
try {
instance = instanceSupplier.get();
} finally {
if (outerBean != null) {
this.currentlyCreatedBean.set(outerBean);
} else {
this.currentlyCreatedBean.remove();
}
}
if (instance == null) {
instance = new NullBean();
}
BeanWrapper bw = new BeanWrapperImpl(instance);
initBeanWrapper(bw);
return bw;
}
/**
* Overridden in order to implicitly register the currently created bean as
* dependent on further beans getting programmatically retrieved during a
* {@link Supplier} callback.
*
* @see #obtainFromSupplier
* @since 5.0
*/
@Override
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
String currentlyCreatedBean = this.currentlyCreatedBean.get();
if (currentlyCreatedBean != null) {
registerDependentBean(beanName, currentlyCreatedBean);
}
return super.getObjectForBeanInstance(beanInstance, name, beanName, mbd);
}
/**
* Determine candidate constructors to use for the given bean, checking all registered
* {@link SmartInstantiationAwareBeanPostProcessor SmartInstantiationAwareBeanPostProcessors}.
*
* @param beanClass the raw class of the bean
* @param beanName the name of the bean
* @return the candidate constructors, or {@code null} if none specified
* @throws org.springframework.beans.BeansException in case of errors
* @see org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors
*/
@Nullable
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}
/**
* Instantiate the given bean using its default constructor.
*
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return a BeanWrapper for the new instance
*/
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
} else {
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
} catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
/**
* Instantiate the bean using a named factory method. The method may be static, if the
* mbd parameter specifies a class, rather than a factoryBean, or an instance variable
* on a factory object itself configured using Dependency Injection.
*
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param explicitArgs argument values passed in programmatically via the getBean method,
* or {@code null} if none (-> use constructor argument values from bean definition)
* @return a BeanWrapper for the new instance
* @see #getBean(String, Object[])
*/
protected BeanWrapper instantiateUsingFactoryMethod(
String beanName, RootBeanDefinition mbd, @Nullable Object[] explicitArgs) {
return new ConstructorResolver(this).instantiateUsingFactoryMethod(beanName, mbd, explicitArgs);
}
/**
* "autowire constructor" (with constructor arguments by type) behavior.
* Also applied if explicit constructor argument values are specified,
* matching all remaining arguments with beans from the bean factory.
* <p>This corresponds to constructor injection: In this mode, a Spring
* bean factory is able to host components that expect constructor-based
* dependency resolution.
*
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param ctors the chosen candidate constructors
* @param explicitArgs argument values passed in programmatically via the getBean method,
* or {@code null} if none (-> use constructor argument values from bean definition)
* @return a BeanWrapper for the new instance
*/
protected BeanWrapper autowireConstructor(
String beanName, RootBeanDefinition mbd, @Nullable Constructor<?>[] ctors, @Nullable Object[] explicitArgs) {
return new ConstructorResolver(this).autowireConstructor(beanName, mbd, ctors, explicitArgs);
}
/**
* Populate the bean instance in the given BeanWrapper with the property values
* from the bean definition.
*
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param bw the BeanWrapper with bean instance
*/
@SuppressWarnings("deprecation") // for postProcessPropertyValues
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
} else {
// Skip property population phase for null instance.
return;
}
}
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
//判断是否要属性注入
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
//找到
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}
if (pvs != null) {
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
/**
* Fill in any missing property values with references to
* other beans in this factory if autowire is set to "byName".
*
* @param beanName the name of the bean we're wiring up.
* Useful for debugging messages; not used functionally.
* @param mbd bean definition to update through autowiring
* @param bw the BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
registerDependentBean(propertyName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
} else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
/**
* Abstract method defining "autowire by type" (bean properties by type) behavior.
* <p>This is like PicoContainer default, in which there must be exactly one bean
* of the property type in the bean factory. This makes bean factories simple to
* configure for small namespaces, but doesn't work as well as standard Spring
* behavior for bigger applications.
*
* @param beanName the name of the bean to autowire by type
* @param mbd the merged bean definition to update through autowiring
* @param bw the BeanWrapper from which we can obtain information about the bean
* @param pvs the PropertyValues to register wired objects with
*/
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
//
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is a unsatisfied, non-simple property.
if (Object.class != pd.getPropertyType()) {
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
registerDependentBean(autowiredBeanName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
}
} catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
/**
* Return an array of non-simple bean properties that are unsatisfied.
* These are probably unsatisfied references to other beans in the
* factory. Does not include simple properties like primitives or Strings.
*
* @param mbd the merged bean definition the bean was created with
* @param bw the BeanWrapper the bean was created with
* @return an array of bean property names
* @see org.springframework.beans.BeanUtils#isSimpleProperty
*/
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
Set<String> result = new TreeSet<>();
PropertyValues pvs = mbd.getPropertyValues();
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
result.add(pd.getName());
}
}
return StringUtils.toStringArray(result);
}
/**
* Extract a filtered set of PropertyDescriptors from the given BeanWrapper,
* excluding ignored dependency types or properties defined on ignored dependency interfaces.
*
* @param bw the BeanWrapper the bean was created with
* @param cache whether to cache filtered PropertyDescriptors for the given bean Class
* @return the filtered PropertyDescriptors
* @see #isExcludedFromDependencyCheck
* @see #filterPropertyDescriptorsForDependencyCheck(org.springframework.beans.BeanWrapper)
*/
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw, boolean cache) {
PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
if (filtered == null) {
filtered = filterPropertyDescriptorsForDependencyCheck(bw);
if (cache) {
PropertyDescriptor[] existing =
this.filteredPropertyDescriptorsCache.putIfAbsent(bw.getWrappedClass(), filtered);
if (existing != null) {
filtered = existing;
}
}
}
return filtered;
}
/**
* Extract a filtered set of PropertyDescriptors from the given BeanWrapper,
* excluding ignored dependency types or properties defined on ignored dependency interfaces.
*
* @param bw the BeanWrapper the bean was created with
* @return the filtered PropertyDescriptors
* @see #isExcludedFromDependencyCheck
*/
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw) {
List<PropertyDescriptor> pds = new ArrayList<>(Arrays.asList(bw.getPropertyDescriptors()));
pds.removeIf(this::isExcludedFromDependencyCheck);
return pds.toArray(new PropertyDescriptor[0]);
}
/**
* Determine whether the given bean property is excluded from dependency checks.
* <p>This implementation excludes properties defined by CGLIB and
* properties whose type matches an ignored dependency type or which
* are defined by an ignored dependency interface.
*
* @param pd the PropertyDescriptor of the bean property
* @return whether the bean property is excluded
* @see #ignoreDependencyType(Class)
* @see #ignoreDependencyInterface(Class)
*/
protected boolean isExcludedFromDependencyCheck(PropertyDescriptor pd) {
return (AutowireUtils.isExcludedFromDependencyCheck(pd) ||
this.ignoredDependencyTypes.contains(pd.getPropertyType()) ||
AutowireUtils.isSetterDefinedInInterface(pd, this.ignoredDependencyInterfaces));
}
/**
* Perform a dependency check that all properties exposed have been set,
* if desired. Dependency checks can be objects (collaborating beans),
* simple (primitives and String), or all (both).
*
* @param beanName the name of the bean
* @param mbd the merged bean definition the bean was created with
* @param pds the relevant property descriptors for the target bean
* @param pvs the property values to be applied to the bean
* @see #isExcludedFromDependencyCheck(java.beans.PropertyDescriptor)
*/
protected void checkDependencies(
String beanName, AbstractBeanDefinition mbd, PropertyDescriptor[] pds, @Nullable PropertyValues pvs)
throws UnsatisfiedDependencyException {
int dependencyCheck = mbd.getDependencyCheck();
for (PropertyDescriptor pd : pds) {
if (pd.getWriteMethod() != null && (pvs == null || !pvs.contains(pd.getName()))) {
boolean isSimple = BeanUtils.isSimpleProperty(pd.getPropertyType());
boolean unsatisfied = (dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_ALL) ||
(isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_SIMPLE) ||
(!isSimple && dependencyCheck == AbstractBeanDefinition.DEPENDENCY_CHECK_OBJECTS);
if (unsatisfied) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, pd.getName(),
"Set this property value or disable dependency checking for this bean.");
}
}
}
}
/**
* Apply the given property values, resolving any runtime references
* to other beans in this bean factory. Must use deep copy, so we
* don't permanently modify this property.
*
* @param beanName the bean name passed for better exception information
* @param mbd the merged bean definition
* @param bw the BeanWrapper wrapping the target object
* @param pvs the new property values
*/
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs.isEmpty()) {
return;
}
if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}
MutablePropertyValues mpvs = null;
List<PropertyValue> original;
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
bw.setPropertyValues(mpvs);
return;
} catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
original = mpvs.getPropertyValueList();
} else {
original = Arrays.asList(pvs.getPropertyValues());
}
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);
// Create a deep copy, resolving any references for values.
List<PropertyValue> deepCopy = new ArrayList<>(original.size());
boolean resolveNecessary = false;
for (PropertyValue pv : original) {
if (pv.isConverted()) {
deepCopy.add(pv);
} else {
String propertyName = pv.getName();
Object originalValue = pv.getValue();
if (originalValue == AutowiredPropertyMarker.INSTANCE) {
Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
if (writeMethod == null) {
throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
}
originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
}
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// Possibly store converted value in merged bean definition,
// in order to avoid re-conversion for every created bean instance.
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
} else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
} else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}
// Set our (possibly massaged) deep copy.
try {
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
} catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
/**
* Convert the given value for the specified target property.
*/
@Nullable
private Object convertForProperty(
@Nullable Object value, String propertyName, BeanWrapper bw, TypeConverter converter) {
if (converter instanceof BeanWrapperImpl) {
return ((BeanWrapperImpl) converter).convertForProperty(value, propertyName);
} else {
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
return converter.convertIfNecessary(value, pd.getPropertyType(), methodParam);
}
}
/**
* Initialize the given bean instance, applying factory callbacks
* as well as init methods and bean post processors.
* <p>Called from {@link #createBean} for traditionally defined beans,
* and from {@link #initializeBean} for existing bean instances.
*
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @return the initialized bean instance (potentially wrapped)
* @see BeanNameAware
* @see BeanClassLoaderAware
* @see BeanFactoryAware
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #invokeInitMethods
* @see #applyBeanPostProcessorsAfterInitialization
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
} else {
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
invokeInitMethods(beanName, wrappedBean, mbd);
} catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
*
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the merged bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @throws Throwable if thrown by init methods or by the invocation process
* @see #invokeCustomInitMethod
*/
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
} catch (PrivilegedActionException pae) {
throw pae.getException();
}
} else {
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
/**
* Invoke the specified custom init method on the given bean.
* Called by invokeInitMethods.
* <p>Can be overridden in subclasses for custom resolution of init
* methods with arguments.
*
* @see #invokeInitMethods
*/
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
String initMethodName = mbd.getInitMethodName();
Assert.state(initMethodName != null, "No init method set");
Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));
if (initMethod == null) {
if (mbd.isEnforceInitMethod()) {
throw new BeanDefinitionValidationException("Could not find an init method named '" +
initMethodName + "' on bean with name '" + beanName + "'");
} else {
if (logger.isTraceEnabled()) {
logger.trace("No default init method named '" + initMethodName +
"' found on bean with name '" + beanName + "'");
}
// Ignore non-existent default lifecycle methods.
return;
}
}
if (logger.isTraceEnabled()) {
logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'");
}
Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(methodToInvoke);
return null;
});
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
methodToInvoke.invoke(bean), getAccessControlContext());
} catch (PrivilegedActionException pae) {
InvocationTargetException ex = (InvocationTargetException) pae.getException();
throw ex.getTargetException();
}
} else {
try {
ReflectionUtils.makeAccessible(methodToInvoke);
methodToInvoke.invoke(bean);
} catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
/**
* Applies the {@code postProcessAfterInitialization} callback of all
* registered BeanPostProcessors, giving them a chance to post-process the
* object obtained from FactoryBeans (for example, to auto-proxy them).
*
* @see #applyBeanPostProcessorsAfterInitialization
*/
@Override
protected Object postProcessObjectFromFactoryBean(Object object, String beanName) {
return applyBeanPostProcessorsAfterInitialization(object, beanName);
}
/**
* Overridden to clear FactoryBean instance cache as well.
*/
@Override
protected void removeSingleton(String beanName) {
synchronized (getSingletonMutex()) {
super.removeSingleton(beanName);
this.factoryBeanInstanceCache.remove(beanName);
}
}
/**
* Overridden to clear FactoryBean instance cache as well.
*/
@Override
protected void clearSingletonCache() {
synchronized (getSingletonMutex()) {
super.clearSingletonCache();
this.factoryBeanInstanceCache.clear();
}
}
/**
* Expose the logger to collaborating delegates.
*
* @since 5.0.7
*/
Log getLogger() {
return logger;
}
/**
* Special DependencyDescriptor variant for Spring's good old autowire="byType" mode.
* Always optional; never considering the parameter name for choosing a primary candidate.
*/
@SuppressWarnings("serial")
private static class AutowireByTypeDependencyDescriptor extends DependencyDescriptor {
public AutowireByTypeDependencyDescriptor(MethodParameter methodParameter, boolean eager) {
super(methodParameter, false, eager);
}
@Override
public String getDependencyName() {
return null;
}
}
/**
* {@link MethodCallback} used to find {@link FactoryBean} type information.
*/
private static class FactoryBeanMethodTypeFinder implements MethodCallback {
private final String factoryMethodName;
private ResolvableType result = ResolvableType.NONE;
FactoryBeanMethodTypeFinder(String factoryMethodName) {
this.factoryMethodName = factoryMethodName;
}
@Override
public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
if (isFactoryBeanMethod(method)) {
ResolvableType returnType = ResolvableType.forMethodReturnType(method);
ResolvableType candidate = returnType.as(FactoryBean.class).getGeneric();
if (this.result == ResolvableType.NONE) {
this.result = candidate;
} else {
Class<?> resolvedResult = this.result.resolve();
Class<?> commonAncestor = ClassUtils.determineCommonAncestor(candidate.resolve(), resolvedResult);
if (!ObjectUtils.nullSafeEquals(resolvedResult, commonAncestor)) {
this.result = ResolvableType.forClass(commonAncestor);
}
}
}
}
private boolean isFactoryBeanMethod(Method method) {
return (method.getName().equals(this.factoryMethodName) &&
FactoryBean.class.isAssignableFrom(method.getReturnType()));
}
ResolvableType getResult() {
Class<?> resolved = this.result.resolve();
boolean foundResult = resolved != null && resolved != Object.class;
return (foundResult ? this.result : ResolvableType.NONE);
}
}
}
| Hxx1221/spring-framework-5.x | spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java |
66,043 | package com.cskaoyan._02method._02define;
/**
* * 3. 定义一个方法用于判断一个正整数的奇偶性,要求:
* * 1. 奇数方法返回false
* * 2. 偶数方法返回true
*
* @author Common-zhou
* @since 2024-03-01 15:52
*/
public class Demo4 {
// [修饰符列表] 返回值类型 方法名(形参列表){
// // 方法体。 也就是方法的具体逻辑
// }
// 词典搜索一下。
// ChatGPT
// 要清晰,明了的表明自己的需求。
// 1.现在,我是一个Java程序员。 我需要你帮我取一个方法的名字。这个方法的主要正作用是判断一个正整数的奇偶性。
// 2.现在,我想写一个代码。 代码的主要作用是判断正整数的奇偶性。偶数返回true, 奇数返回false。使用Java代码。
// 最好帮我写成一个 public static 的方法。 方法的名字叫做isNumberEven
// ChatGPT 有一定的概率出错。 一本正经的胡说八道。 要能区分出来它说的是对是错。
public static boolean isNumberEven(int numer) {
if (numer % 2 == 0) {
return true;
}
return false;
}
}
| YZY-YYH/wangdao58th | 01-JavaSE/01_code/java58/src/com/cskaoyan/_02method/_02define/Demo4.java |
66,050 | package com.bin23.simplevideo.entity;
import java.util.List;
public class VideoBean {
/**
* date : 1606870800000
* nextPublishTime : 1606957200000
* adExist : false
* dialog : null
* topIssue : null
* total : 0
* nextPageUrl : http://baobab.kaiyanapp.com/api/v4/tabs/selected?date=1606698000000&num=2&page=2
* refreshCount : 0
* count : 15
* itemList : [{"data":{"date":1606870800000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225498&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/1163c79742996c7315be2105b14a1b94.png?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":{"fileSizeStr":"3.53MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/3c6d9321d68a7145f299990fd5648fe4.mp4"},"id":225498,"descriptionPgc":"","recall_source":null,"ad":false,"author":{"shield":{"itemId":1027,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/27c223e61df5b647d061e41ee995e8f6.jpeg?imageMogr2/quality/60/format/jpg","link":"","description":"分享创意广告短视频","videoNum":951,"follow":{"itemId":1027,"itemType":"author","followed":false},"recSort":0,"name":"这些广告超有梗","ifPgc":true,"latestReleaseTime":1606839239000,"id":1027,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/748/?title=%E8%BF%99%E4%BA%9B%E5%B9%BF%E5%91%8A%E8%B6%85%E6%9C%89%E6%A2%97","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/9056413cfeffaf0c841d894390aa8e08.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/ff0f6d0ad5f4b6211a3f746aaaffd916.jpeg?imageMogr2/quality/60/format/jpg","name":"这些广告超有梗","communityIndex":0,"id":748,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/140/?title=%E6%90%9E%E7%AC%91","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f787d5053443499e8d787911cd8b3876.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f2b803d3c383bba5a3888b2709160b6e.jpeg?imageMogr2/quality/60/format/jpg","name":"搞笑","communityIndex":0,"id":140,"adTrack":null,"desc":"哈哈哈哈哈哈哈哈","newestEndTime":null},{"actionUrl":"eyepetizer://tag/766/?title=%E8%84%91%E6%B4%9E%E5%B9%BF%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/7c46ad04ff913b87915615c78d226a40.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/0d6ab7ed49de67eab89ada4f65353e8c.jpeg?imageMogr2/quality/60/format/jpg","name":"脑洞广告","communityIndex":0,"id":766,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/16/?title=%E5%B9%BF%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/e41e74fe73882b552de00d95d56748d2.jpeg?imageMogr2/quality/60","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/3054658dbd559ac42c4c282e9cab7a32.jpeg?imageMogr2/quality/100","name":"广告","communityIndex":0,"id":16,"adTrack":null,"desc":"为广告人的精彩创意点赞","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225498","raw":"http://www.eyepetizer.net/detail.html?vid=225498"},"campaign":null,"idx":0,"slogan":"","shareAdTrack":null,"releaseTime":1606839239000,"description":"这是一则来自瑞典智慧财产管理局广告。广告讲述了以「制假买假」的形式向人们展示了不良商家。睁眼瞎牌墨镜,烫头皮直发夹,过敏反应香水,这些名字听了就让人觉得搞笑。From Swedish Intellectual Property Office","remark":"我就不信,戴墨镜不是为了装","title":"你一本正经胡说八道卖东西的样子,让我上瘾","recallSource":null,"duration":120,"library":"DAILY","descriptionEditor":"这是一则来自瑞典智慧财产管理局广告。广告讲述了以「制假买假」的形式向人们展示了不良商家。睁眼瞎牌墨镜,烫头皮直发夹,过敏反应香水,这些名字听了就让人觉得搞笑。From Swedish Intellectual Property Office","provider":{"name":"投稿","icon":"","alias":"PGC2"},"titlePgc":"","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":7,"replyCount":2,"realCollectionCount":32,"collectionCount":52},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"广告","thumbPlayUrl":"","resourceType":"video","promotion":null},"adIndex":-1,"tag":"0","id":0,"type":"video","trackingData":null},{"data":{"date":1606870800000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225525&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/6fecd965b82be9477319d128570eb05e.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/6fecd965b82be9477319d128570eb05e.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/9be04e4207d16d763958f5b8055c672c.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/6fecd965b82be9477319d128570eb05e.jpeg?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":null,"id":225525,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":2161,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/f4a9aba1c6857ee0cefcdc5aee0a1fc9.png?imageMogr2/quality/60/format/jpg","link":"","description":"技术与审美结合,探索视觉的无限可能","videoNum":982,"follow":{"itemId":2161,"itemType":"author","followed":false},"recSort":0,"name":"开眼创意精选","ifPgc":true,"latestReleaseTime":1606871634000,"id":2161,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/744/?title=%E6%AF%8F%E6%97%A5%E5%88%9B%E6%84%8F%E7%81%B5%E6%84%9F","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/bc2479c09cd15cb93b69d82e5f21c3fc.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/bc2479c09cd15cb93b69d82e5f21c3fc.png?imageMogr2/quality/60/format/jpg","name":"每日创意灵感","communityIndex":0,"id":744,"adTrack":null,"desc":"技术与审美结合,探索视觉的无限可能","newestEndTime":null},{"actionUrl":"eyepetizer://tag/520/?title=%E5%A4%A7%E8%87%AA%E7%84%B6","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/4f8c478d7753f65e4ec3407b3d055edf.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/036745f32252000f3b91efc21aafcaf1.jpeg?imageMogr2/quality/100","name":"大自然","communityIndex":0,"id":520,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/362/?title=%E9%9D%9E%E6%B4%B2","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/1e4cf584b2df92cd7982884c61766a3a.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"https://i.ytimg.com/vi/O3cBZ5X-eGw/maxresdefault.jpg","name":"非洲","communityIndex":0,"id":362,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/284/?title=%E5%86%B2%E6%B5%AA","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/18728b75876336299dadccb8695dcff4.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/18728b75876336299dadccb8695dcff4.jpeg?imageMogr2/quality/60/format/jpg","name":"冲浪","communityIndex":0,"id":284,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/190/?title=%E5%AE%8F%E5%A4%A7","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/293eb0312d5ad76044f212950fdd676f.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/293eb0312d5ad76044f212950fdd676f.jpeg?imageMogr2/quality/60/format/jpg","name":"宏大","communityIndex":0,"id":190,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/52/?title=%E9%A3%8E%E5%85%89%E5%A4%A7%E7%89%87","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/e484dd6aa22ea3c2e604812b44f8c60c.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f333f225c9ccc78819120f3a888b2e7e.jpeg?imageMogr2/quality/60/format/jpg","name":"风光大片","communityIndex":0,"id":52,"adTrack":null,"desc":"","newestEndTime":null},{"actionUrl":"eyepetizer://tag/2/?title=%E5%88%9B%E6%84%8F","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/1b457058cf2b317304ff9f70543c040d.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/fdefdb34cbe3d2ac9964d306febe9025.jpeg?imageMogr2/quality/100","name":"创意","communityIndex":0,"id":2,"adTrack":null,"desc":"技术与审美结合,探索视觉的无限可能","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225525","raw":"http://www.eyepetizer.net/detail.html?vid=225525"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606871634000,"description":"狂野海岸(Wild Coast)是南非最偏远的海岸线之一,也是世界上最美丽的海滨风景所在地之一。本片记录了该地区美丽的花园海岸线风景以及现代文明造就的嬉皮士、冲浪者与科萨人并肩生活的场景。From MrBrynnorth","remark":null,"title":"南非:以乡土记忆,回应现代目光","recallSource":null,"duration":285,"library":"DAILY","descriptionEditor":"狂野海岸(Wild Coast)是南非最偏远的海岸线之一,也是世界上最美丽的海滨风景所在地之一。本片记录了该地区美丽的花园海岸线风景以及现代文明造就的嬉皮士、冲浪者与科萨人并肩生活的场景。From MrBrynnorth","provider":{"name":"YouTube","icon":"http://img.kaiyanapp.com/fa20228bc5b921e837156923a58713f6.png","alias":"youtube"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":0,"replyCount":2,"realCollectionCount":0,"collectionCount":20},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"创意","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"0","id":0,"type":"video","trackingData":null},{"data":{"date":1606870800000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224485&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/805f88e90aa9360b956a1cbd0e9b43db.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/805f88e90aa9360b956a1cbd0e9b43db.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/2e475a45a64a262a6e8ff482aeed91b0.png?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/805f88e90aa9360b956a1cbd0e9b43db.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":null,"id":224485,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":2170,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/482c741c06644f5566c7218096dbaf26.jpeg","link":"","description":"有趣的人永远不缺童心","videoNum":936,"follow":{"itemId":2170,"itemType":"author","followed":false},"recSort":0,"name":"开眼动画精选","ifPgc":true,"latestReleaseTime":1606871641000,"id":2170,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/14/?title=%E5%8A%A8%E7%94%BB%E6%A2%A6%E5%B7%A5%E5%8E%82","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/afb9e7d7f061d10ade5ebcb524dc8679.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f9eae3e0321fa1e99a7b38641b5536a2.jpeg?imageMogr2/quality/60/format/jpg","name":"动画梦工厂","communityIndex":0,"id":14,"adTrack":null,"desc":"有趣的人永远不缺童心","newestEndTime":null},{"actionUrl":"eyepetizer://tag/156/?title=%E6%AF%95%E4%B8%9A%E8%AE%BE%E8%AE%A1","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/ae2f80473a05cdea0bcdda4cca64fbe2.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/ae2f80473a05cdea0bcdda4cca64fbe2.jpeg?imageMogr2/quality/60/format/jpg","name":"毕业设计","communityIndex":0,"id":156,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/58/?title=2D","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/d2e80d6c05055caf669d1f69f4b4eac1.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/012a82e8d4547c33ff3861c82747a83e.jpeg?imageMogr2/quality/100","name":"2D","communityIndex":0,"id":58,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/74/?title=CG","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/fdac34e3c19adf85704b039126edef52.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/e2a1eec9efb7e7d0abca85bbdedc425b.jpeg?imageMogr2/quality/100","name":"CG","communityIndex":0,"id":74,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/1023/?title=%E5%8A%A8%E7%94%BB","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/349cbd33cdf71fc74d5e9c7a00b444fd.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/208aa67386c045497389f015ae28dd29.jpeg?imageMogr2/quality/60/format/jpg","name":"动画","communityIndex":0,"id":1023,"adTrack":null,"desc":"有趣的人永远不缺童心","newestEndTime":null},{"actionUrl":"eyepetizer://tag/530/?title=%E4%BA%BA%E7%94%9F","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/a57744110ddbaa1e99d148a01c1b1bd8.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/a57744110ddbaa1e99d148a01c1b1bd8.jpeg?imageMogr2/quality/60/format/jpg","name":"人生","communityIndex":0,"id":530,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/92/?title=%E8%B6%85%E7%8E%B0%E5%AE%9E","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/16acd1adf55e68599a12ea7811859b68.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f27c0aebc383b65f3e47af443f0a07ce.jpeg?imageMogr2/quality/100","name":"超现实","communityIndex":0,"id":92,"adTrack":null,"desc":null,"newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=224485&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=224485"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606871641000,"description":"冲突的色彩、不合比例的人型,这则动画短片以一种抽象而细微的方式,展现了生活中的的恐惧、不安和焦虑感。作者希望通过此片告诉大家精神病人所经历的一切。From Inger Bierma","remark":null,"title":"焦虑是一种老鼠,它会飞","recallSource":null,"duration":270,"library":"DAILY","descriptionEditor":"冲突的色彩、不合比例的人型,这则动画短片以一种抽象而细微的方式,展现了生活中的的恐惧、不安和焦虑感。作者希望通过此片告诉大家精神病人所经历的一切。From Inger Bierma","provider":{"name":"Vimeo","icon":"http://img.kaiyanapp.com/c3ad630be461cbb081649c9e21d6cbe3.png","alias":"vimeo"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":0,"replyCount":2,"realCollectionCount":20,"collectionCount":20},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[{"width":1280,"name":"高清","urlList":[{"size":19946718,"name":"aliyun","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224485&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid="},{"size":19946718,"name":"ucloud","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224485&resourceType=video&editionType=high&source=ucloud&playUrlType=url_oss&udid="}],"type":"high","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224485&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid=","height":720}],"ifLimitVideo":false,"category":"动画","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"0","id":0,"type":"video","trackingData":null},{"data":{"date":1606870800000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225438&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/86938db63bfa109ea788918cbe45828d.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/86938db63bfa109ea788918cbe45828d.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/7f543b4d7058c3f6ee9e87d129ee92fc.jpeg?imageMogr2/quality/60/format/jpg","homepage":null},"videoPosterBean":{"fileSizeStr":"3.94MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/d07d620e288e4307a188a1747994717d.mp4"},"id":225438,"descriptionPgc":"高中毕业生占有兵,湖北襄樊人,2000年来到广东东莞打工,并开始用相机拍摄工友们的打工生活。20年来,他拍下了150万张照片,记录了流水线两侧的年轻女工,逐渐被自动化机器替代的过程。凭借这些照片,他从保安队长一路逆袭,成为国内各大摄影节的宠儿。11月,一条来到东莞市长安镇,和他聊了聊如此长情和疯狂的创作。","recall_source":null,"ad":false,"author":{"shield":{"itemId":170,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/b1f252f2a97e014f6de7e65709c5eedd.png?imageMogr2/quality/60/format/jpg","link":"","description":"所有未在美中度过的生活,都是被浪费了。","videoNum":1846,"follow":{"itemId":170,"itemType":"author","followed":false},"recSort":0,"name":"一条","ifPgc":true,"latestReleaseTime":1606762104000,"id":170,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/743/?title=%E8%AE%B0%E5%BD%95%E7%B2%BE%E9%80%89","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/a082f44b88e78daaf19fa4e1a2faaa5a.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/a082f44b88e78daaf19fa4e1a2faaa5a.jpeg?imageMogr2/quality/60/format/jpg","name":"记录精选","communityIndex":0,"id":743,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/136/?title=%E6%B8%A9%E6%83%85","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/0bc1dc78c631eae017ee69418303adc5.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/0bc1dc78c631eae017ee69418303adc5.jpeg?imageMogr2/quality/100","name":"温情","communityIndex":0,"id":136,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/534/?title=%E4%BA%BA%E6%96%87","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/5d6ee9241a0e2196bc1754b35f6f15e5.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/16b60131c2bc0885683ce7ee6ac75b52.jpeg?imageMogr2/quality/100","name":"人文","communityIndex":0,"id":534,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/24/?title=%E8%AE%B0%E5%BD%95","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/c3984cad49455e01637347e0c8f6a37d.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/fd76dab1411e07f0dcf45309720134f9.jpeg?imageMogr2/quality/100","name":"记录","communityIndex":0,"id":24,"adTrack":null,"desc":"告诉他们为什么与众不同","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225438","raw":"http://www.eyepetizer.net/detail.html?vid=225438"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606762104000,"description":"高中毕业生占有兵,湖北襄樊人,2000年来到广东东莞打工,并开始用相机拍摄工友们的打工生活。20年来,他拍下了150万张照片,记录了流水线两侧的年轻女工,逐渐被自动化机器替代的过程。凭借这些照片,他从保安队长一路逆袭,成为国内各大摄影节的宠儿。11月,一条来到东莞市长安镇,和他聊了聊如此长情和疯狂的创作。","remark":"","title":"中国第一代打工人的私密生活","recallSource":null,"duration":327,"library":"DAILY","descriptionEditor":"","provider":{"name":"PGC","icon":"","alias":"PGC"},"titlePgc":"中国第一代打工人的私密生活","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":31,"replyCount":5,"realCollectionCount":81,"collectionCount":188},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"记录","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"0","id":0,"type":"video","trackingData":null},{"data":{"date":1606870800000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225375&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/3b772e14f32b933693022845408e1253.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/3b772e14f32b933693022845408e1253.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/9ca986d927e6e497971c9a53ee963531.png?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/3b772e14f32b933693022845408e1253.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":null,"id":225375,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":2172,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/8581b06aa17c7dbe8970e4c27bbdbd98.png?imageMogr2/quality/60/format/jpg","link":"","description":"用一个好故事,描绘生活的不可思议","videoNum":558,"follow":{"itemId":2172,"itemType":"author","followed":false},"recSort":0,"name":"开眼剧情精选","ifPgc":true,"latestReleaseTime":1606871643000,"id":2172,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/1032/?title=%E7%BB%99%E4%BD%A0%E8%AE%B2%E4%B8%AA%E5%A5%BD%E6%95%85%E4%BA%8B","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/d471080a9de44e8fbaa4850887273332.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/33a2b832b7583dd9781f9fd40ad7617e.jpeg?imageMogr2/quality/60/format/jpg","name":"给你讲个好故事","communityIndex":0,"id":1032,"adTrack":null,"desc":"每周末更新,关注听开眼给你讲故事。","newestEndTime":null},{"actionUrl":"eyepetizer://tag/126/?title=%E9%87%8D%E5%8F%A3","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/c4da77041e6f10650b2d2d3902f27442.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/c4da77041e6f10650b2d2d3902f27442.jpeg?imageMogr2/quality/60/format/jpg","name":"重口","communityIndex":0,"id":126,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/196/?title=%E6%B8%85%E6%96%B0","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/9824ae7d052ca22de0a29e09d10364d8.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/9824ae7d052ca22de0a29e09d10364d8.jpeg?imageMogr2/quality/60/format/jpg","name":"清新","communityIndex":0,"id":196,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/150/?title=%E9%9D%92%E6%98%A5","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/34d33f611dbfe38e4d00cd4ab43212e7.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/58e3e0ec1e583a6debcc0f80d16c86fe.jpeg?imageMogr2/quality/100","name":"青春","communityIndex":0,"id":150,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/12/?title=%E5%89%A7%E6%83%85","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/945fa937f0955b31224314a4eeef59b8.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/945fa937f0955b31224314a4eeef59b8.jpeg?imageMogr2/quality/100","name":"剧情","communityIndex":0,"id":12,"adTrack":null,"desc":"用一个好故事,描绘生活的不可思议","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225375","raw":"http://www.eyepetizer.net/detail.html?vid=225375"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606871643000,"description":"这则短片的主人公 Ada 是一个 24 岁的普通女孩,虽然她在网上自称是性和爱的专家,但在现实生活中缺乏自信、恐惧社交,甚至不敢跟有好感的健身教练说话。当她给自己定了个目标要决心做到时,事情好像朝着奇怪的方向发展了......From Carlota Oms","remark":null,"title":"画面清新故事重口,这个胖女孩不简单","recallSource":null,"duration":562,"library":"DAILY","descriptionEditor":"这则短片的主人公 Ada 是一个 24 岁的普通女孩,虽然她在网上自称是性和爱的专家,但在现实生活中缺乏自信、恐惧社交,甚至不敢跟有好感的健身教练说话。当她给自己定了个目标要决心做到时,事情好像朝着奇怪的方向发展了......From Carlota Oms","provider":{"name":"Vimeo","icon":"http://img.kaiyanapp.com/c3ad630be461cbb081649c9e21d6cbe3.png","alias":"vimeo"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":0,"replyCount":2,"realCollectionCount":10,"collectionCount":10},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[{"width":1280,"name":"高清","urlList":[{"size":57016703,"name":"aliyun","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225375&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid="},{"size":57016703,"name":"ucloud","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225375&resourceType=video&editionType=high&source=ucloud&playUrlType=url_oss&udid="}],"type":"high","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225375&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid=","height":720}],"ifLimitVideo":false,"category":"剧情","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"0","id":0,"type":"video","trackingData":null},{"data":{"dataType":"TextFooter","actionUrl":"eyepetizer://feed?issueIndex=1","text":"查看往期编辑精选","adTrack":null,"font":"normal"},"adIndex":-1,"tag":null,"id":0,"type":"textFooter","trackingData":null},{"data":{"footer":null,"dataType":"ItemCollection","count":5,"header":{"cover":"http://img.kaiyanapp.com/e023e23ab6b75f5ca65bf9b66df4b6ed.png?imageMogr2/quality/60/format/jpg","rightText":null,"labelList":[{"actionUrl":null,"text":""}],"subTitle":null,"textAlign":"middle","subTitleFont":null,"actionUrl":"eyepetizer://webview/?title=%E5%85%A8%E6%96%B0%E6%83%85%E6%84%9F%E6%97%85%E8%A1%8C%E7%BA%AA%E5%AE%9E%E7%BB%BC%E8%89%BA&url=http%3A%2F%2Fwww.eyepetizer.net%2Fvideos_article.html%3Fnid%3D540%26shareable%3Dtrue","id":540,"label":{"text":"","detail":null,"card":""},"title":null,"font":"normal"},"itemList":[{"data":{"date":1606835273000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225541&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/fc765eaf34f6bb4875d026f5421d3dc8.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/fc765eaf34f6bb4875d026f5421d3dc8.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/1d68f34f9469b7d3b3b198c8f6e8e225.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/8e414720f2055fc1d1b53504ceaaa120.jpeg?imageMogr2/quality/60/format/jpg"},"videoPosterBean":null,"id":225541,"descriptionPgc":"","recall_source":null,"ad":false,"author":{"shield":{"itemId":5379,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/a502f1c280a80a9f9e705315afb588a0.png?imageMogr2/quality/60/format/jpg","link":"","description":"情感旅行纪实综艺《出逃两日又如何》 11月26日起腾讯视频独播","videoNum":6,"follow":{"itemId":5379,"itemType":"author","followed":false},"recSort":0,"name":"出逃两日又如何","ifPgc":true,"latestReleaseTime":1606835273000,"id":5379,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225541","raw":"http://www.eyepetizer.net/detail.html?vid=225541"},"campaign":null,"idx":0,"slogan":"","shareAdTrack":null,"releaseTime":1606835273000,"description":"11月3日中午12点来腾讯视频一起来看沈梦辰和李斯丹妮到底是真闺蜜还是塑料姐妹花?","remark":null,"title":"出逃两日又如何闺蜜组人物宣传片","recallSource":null,"duration":90,"library":"NONE","descriptionEditor":"11月3日中午12点来腾讯视频一起来看沈梦辰和李斯丹妮到底是真闺蜜还是塑料姐妹花?","provider":{"name":"腾讯","icon":"http://img.kaiyanapp.com/def8a8aa0971f93973280f7f75c772c4.png","alias":"qq"},"titlePgc":"","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":0,"replyCount":1,"realCollectionCount":0,"collectionCount":19},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"旅行","thumbPlayUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl/1606835095928_cfa08978.mp4?vid=225541&source=aliyun","resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null},{"data":{"date":1606209376000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224232&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/958c344b627d45a2104f6fee05367fdd.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/958c344b627d45a2104f6fee05367fdd.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/edb28a26d1ab5107a1b8eb42090e8d3d.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/958c344b627d45a2104f6fee05367fdd.jpeg?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":null,"id":224232,"descriptionPgc":"","recall_source":null,"ad":false,"author":{"shield":{"itemId":5379,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/a502f1c280a80a9f9e705315afb588a0.png?imageMogr2/quality/60/format/jpg","link":"","description":"情感旅行纪实综艺《出逃两日又如何》 11月26日起腾讯视频独播","videoNum":6,"follow":{"itemId":5379,"itemType":"author","followed":false},"recSort":0,"name":"出逃两日又如何","ifPgc":true,"latestReleaseTime":1606835273000,"id":5379,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=224232&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=224232"},"campaign":null,"idx":0,"slogan":"","shareAdTrack":null,"releaseTime":1606209376000,"description":"从爱情走向婚姻,你是否被生活改造了?让我们一起跟着张歆艺和袁弘一起探寻有关爱情,有关婚姻以及有关自我的真谛。","remark":null,"title":"出逃两日又如何夫妻组人物宣传片","recallSource":null,"duration":0,"library":"DEFAULT","descriptionEditor":"从爱情走向婚姻,你是否被生活改造了?让我们一起跟着张歆艺和袁弘一起探寻有关爱情,有关婚姻以及有关自我的真谛。","provider":{"name":"腾讯","icon":"http://img.kaiyanapp.com/def8a8aa0971f93973280f7f75c772c4.png","alias":"qq"},"titlePgc":"","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":444,"replyCount":11,"realCollectionCount":57,"collectionCount":752},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"旅行","thumbPlayUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl/1606209332776_b2d6c613.mp4?vid=224232&source=aliyun","resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null},{"data":{"date":1606209979000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224235&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/5128adacb25d4d8d6f634c10feb5d520.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/5128adacb25d4d8d6f634c10feb5d520.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/aad391d9f8488e333a67f336aa2118a6.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/db13de304e04ceda64aad1e2435cf5fc.jpeg?imageMogr2/quality/60/format/jpg"},"videoPosterBean":null,"id":224235,"descriptionPgc":"","recall_source":null,"ad":false,"author":{"shield":{"itemId":5379,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/a502f1c280a80a9f9e705315afb588a0.png?imageMogr2/quality/60/format/jpg","link":"","description":"情感旅行纪实综艺《出逃两日又如何》 11月26日起腾讯视频独播","videoNum":6,"follow":{"itemId":5379,"itemType":"author","followed":false},"recSort":0,"name":"出逃两日又如何","ifPgc":true,"latestReleaseTime":1606835273000,"id":5379,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=224235&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=224235"},"campaign":null,"idx":0,"slogan":"","shareAdTrack":null,"releaseTime":1606209979000,"description":"我们常常以为惊喜会藏在远方山水间,其实它就在每一个共同经历的瞬间。跟随张歆艺和袁弘,李斯丹妮和沈梦辰,杨立新和杨玏,白举纲和白日梦症候群 DDS 乐队一起逃离日常,和最爱的人重新相遇。","remark":null,"title":"出逃两日又如何亲密关系宣传片","recallSource":null,"duration":146,"library":"DEFAULT","descriptionEditor":"我们常常以为惊喜会藏在远方山水间,其实它就在每一个共同经历的瞬间。跟随张歆艺和袁弘,李斯丹妮和沈梦辰,杨立新和杨玏,白举纲和白日梦症候群 DDS 乐队一起逃离日常,和最爱的人重新相遇。","provider":{"name":"腾讯","icon":"http://img.kaiyanapp.com/def8a8aa0971f93973280f7f75c772c4.png","alias":"qq"},"titlePgc":"","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":451,"replyCount":13,"realCollectionCount":25,"collectionCount":634},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"旅行","thumbPlayUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl/1606209955581_b22d173a.mp4?vid=224235&source=aliyun","resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null},{"data":{"date":1606212527000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224236&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/5442d94a4f4a14bb55d62c0203285f92.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/5442d94a4f4a14bb55d62c0203285f92.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/71d0d49735b31f7955108d2b490b7d3e.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/65dd8564ffe065a9289e812ea23b4108.jpeg?imageMogr2/quality/60/format/jpg"},"videoPosterBean":null,"id":224236,"descriptionPgc":"","recall_source":null,"ad":false,"author":{"shield":{"itemId":5379,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/a502f1c280a80a9f9e705315afb588a0.png?imageMogr2/quality/60/format/jpg","link":"","description":"情感旅行纪实综艺《出逃两日又如何》 11月26日起腾讯视频独播","videoNum":6,"follow":{"itemId":5379,"itemType":"author","followed":false},"recSort":0,"name":"出逃两日又如何","ifPgc":true,"latestReleaseTime":1606835273000,"id":5379,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=224236&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=224236"},"campaign":null,"idx":0,"slogan":"","shareAdTrack":null,"releaseTime":1606212527000,"description":"《出逃两日又如何》邀请了四组身处不同亲密关系中的嘉宾,共同踏上一段自驾旅程,在荒野和高山之间,相处两日。他们将会在亲密相处中碰撞出怎样令人意想不到的情感对话和旅行灵感呢?","remark":"","title":"出逃两日又如何内容向宣传片","recallSource":null,"duration":90,"library":"DEFAULT","descriptionEditor":"《出逃两日又如何》邀请了四组身处不同亲密关系中的嘉宾,共同踏上一段自驾旅程,在荒野和高山之间,相处两日。他们将会在亲密相处中碰撞出怎样令人意想不到的情感对话和旅行灵感呢?","provider":{"name":"腾讯","icon":"http://img.kaiyanapp.com/def8a8aa0971f93973280f7f75c772c4.png","alias":"qq"},"titlePgc":"","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":259,"replyCount":14,"realCollectionCount":25,"collectionCount":618},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[{"width":1920,"name":"高清","urlList":[{"size":13894224,"name":"aliyun","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224236&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid="},{"size":13894224,"name":"ucloud","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224236&resourceType=video&editionType=high&source=ucloud&playUrlType=url_oss&udid="}],"type":"high","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224236&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid=","height":1080}],"ifLimitVideo":false,"category":"旅行","thumbPlayUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl/1606210234788_6837e2a3.mp4?vid=224236&source=aliyun","resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null},{"data":{"date":1606209124000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224230&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/e10e4f0ee18175c2ebff84118b1a2e8f.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/e10e4f0ee18175c2ebff84118b1a2e8f.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/b7d0f03d96bfa8678fff4f17896ee260.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/e10e4f0ee18175c2ebff84118b1a2e8f.jpeg?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":null,"id":224230,"descriptionPgc":"","recall_source":null,"ad":false,"author":{"shield":{"itemId":5379,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/a502f1c280a80a9f9e705315afb588a0.png?imageMogr2/quality/60/format/jpg","link":"","description":"情感旅行纪实综艺《出逃两日又如何》 11月26日起腾讯视频独播","videoNum":6,"follow":{"itemId":5379,"itemType":"author","followed":false},"recSort":0,"name":"出逃两日又如何","ifPgc":true,"latestReleaseTime":1606835273000,"id":5379,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=224230&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=224230"},"campaign":null,"idx":0,"slogan":"","shareAdTrack":null,"releaseTime":1606209124000,"description":"11月26日起,我们将和张歆艺和袁弘、李斯丹妮和沈梦辰、杨立新和杨玏还有白举纲和白日梦症候群DDS乐队一起在腾冲、大理、沙溪和香格里拉出逃两日,共同创造一段美好回忆。","remark":null,"title":"出逃两日又如何旅行向宣传片","recallSource":null,"duration":85,"library":"NONE","descriptionEditor":"11月26日起,我们将和张歆艺和袁弘、李斯丹妮和沈梦辰、杨立新和杨玏还有白举纲和白日梦症候群DDS乐队一起在腾冲、大理、沙溪和香格里拉出逃两日,共同创造一段美好回忆。","provider":{"name":"腾讯","icon":"http://img.kaiyanapp.com/def8a8aa0971f93973280f7f75c772c4.png","alias":"qq"},"titlePgc":"","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":272,"replyCount":10,"realCollectionCount":31,"collectionCount":633},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"旅行","thumbPlayUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl/1606208995905_51f96bf3.mp4?vid=224230&source=aliyun","resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null}],"adTrack":[]},"adIndex":-1,"tag":null,"id":0,"type":"videoCollectionWithCover","trackingData":null},{"data":{"dataType":"TextHeader","text":"- Dec. 01, Brunch -","adTrack":null,"font":"lobster"},"adIndex":-1,"tag":"1","id":0,"type":"textHeader","trackingData":null},{"data":{"date":1606784400000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224775&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/25627f22da43a5cb4c098a0fc81a43aa.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/25627f22da43a5cb4c098a0fc81a43aa.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/b90fcb7e6fa52b2361e22d9cfe902621.png?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/25627f22da43a5cb4c098a0fc81a43aa.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":{"fileSizeStr":"2.78MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/35c67ed5a9260ca98dc042ee86c7678a.mp4"},"id":224775,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":2007,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/8bf284aed36f12ea874defb29c790af9.png?imageMogr2/quality/60/format/jpg","link":"","description":"开眼搞笑精选","videoNum":396,"follow":{"itemId":2007,"itemType":"author","followed":false},"recSort":0,"name":"开眼搞笑精选","ifPgc":true,"latestReleaseTime":1606784400000,"id":2007,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/516/?title=%E6%81%B6%E6%90%9E","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f884134104430c3fe511147e93ea914f.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f884134104430c3fe511147e93ea914f.jpeg?imageMogr2/quality/100","name":"恶搞","communityIndex":0,"id":516,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/504/?title=%E7%AC%91cry","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/3d3cb19d13cc16e8c3c2eddb12284fa3.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/177986653f12273f6d55edafe856ffe3.jpeg?imageMogr2/quality/100","name":"笑cry","communityIndex":0,"id":504,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/168/?title=%E8%AE%BD%E5%88%BA","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/a3de18fb448aa41a140f1901130c380a.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/d536b9c09b2681630afcc92222599f0e.jpeg?imageMogr2/quality/100","name":"讽刺","communityIndex":0,"id":168,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/170/?title=%E5%B9%BD%E9%BB%98","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/8164ded95cfde8c5f42acf243c6ca3e6.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/8164ded95cfde8c5f42acf243c6ca3e6.jpeg?imageMogr2/quality/60/format/jpg","name":"幽默","communityIndex":0,"id":170,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/140/?title=%E6%90%9E%E7%AC%91","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f787d5053443499e8d787911cd8b3876.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f2b803d3c383bba5a3888b2709160b6e.jpeg?imageMogr2/quality/60/format/jpg","name":"搞笑","communityIndex":0,"id":140,"adTrack":null,"desc":"哈哈哈哈哈哈哈哈","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=224775","raw":"http://www.eyepetizer.net/detail.html?vid=224775"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606784400000,"description":"这是一则德国讽刺恶搞短片。你是否经常感到压抑,生活社交不自信,懂王药片来帮您!无论生活有什么不如意,一片懂王自信药,您就都懂了!From extra 3","remark":"","title":"讽刺懂王的最佳方式,是给他做条假广告","recallSource":null,"duration":137,"library":"DAILY","descriptionEditor":"这是一则德国讽刺恶搞短片。你是否经常感到压抑,生活社交不自信,懂王药片来帮您!无论生活有什么不如意,一片懂王自信药,您就都懂了!From extra 3","provider":{"name":"YouTube","icon":"http://img.kaiyanapp.com/fa20228bc5b921e837156923a58713f6.png","alias":"youtube"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":1129,"replyCount":7,"realCollectionCount":262,"collectionCount":1101},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[{"width":1280,"name":"高清","urlList":[{"size":14981707,"name":"aliyun","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224775&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid="},{"size":14981707,"name":"ucloud","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224775&resourceType=video&editionType=high&source=ucloud&playUrlType=url_oss&udid="}],"type":"high","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224775&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid=","height":720}],"ifLimitVideo":false,"category":"搞笑","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"1","id":0,"type":"video","trackingData":null},{"data":{"date":1606784400000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=217199&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/92e829e42f15ffe0b973b66921ea67d3.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/92e829e42f15ffe0b973b66921ea67d3.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/a5678d35c0109ee0179eeecc93f02008.png?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/92e829e42f15ffe0b973b66921ea67d3.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":{"fileSizeStr":"2.51MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/4d008f500d9d1e1a8c20895b872dbe61.mp4"},"id":217199,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":2166,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/a2fc6d32ac0b4f2842fb3d545d06f09b.jpeg","link":"","description":"告诉他们为什么与众不同","videoNum":342,"follow":{"itemId":2166,"itemType":"author","followed":false},"recSort":0,"name":"开眼记录精选","ifPgc":true,"latestReleaseTime":1606784436000,"id":2166,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/44/?title=5%20%E5%88%86%E9%92%9F%E6%96%B0%E7%9F%A5","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f2e7359e81e217782f32cc3d482b3284.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f2e7359e81e217782f32cc3d482b3284.jpeg?imageMogr2/quality/60/format/jpg","name":"5 分钟新知","communityIndex":0,"id":44,"adTrack":null,"desc":"大千世界,总有你不知道的","newestEndTime":null},{"actionUrl":"eyepetizer://tag/864/?title=%E4%BA%BA%E6%96%87%E7%A4%BE%E7%A7%91","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/5a24f441d4842d417b67470d71b01fb7.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/5a24f441d4842d417b67470d71b01fb7.png?imageMogr2/quality/60/format/jpg","name":"人文社科","communityIndex":0,"id":864,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/689/?title=%E5%81%A5%E5%BA%B7","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/34df9f86a9898ca037dc24c2f51c9f86.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/34df9f86a9898ca037dc24c2f51c9f86.jpeg?imageMogr2/quality/60/format/jpg","name":"健康","communityIndex":0,"id":689,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/534/?title=%E4%BA%BA%E6%96%87","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/5d6ee9241a0e2196bc1754b35f6f15e5.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/16b60131c2bc0885683ce7ee6ac75b52.jpeg?imageMogr2/quality/100","name":"人文","communityIndex":0,"id":534,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/702/?title=%E4%BA%BA%E7%89%A9","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/9101692746a60cd7360838bf394703c1.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/9101692746a60cd7360838bf394703c1.jpeg?imageMogr2/quality/60/format/jpg","name":"人物","communityIndex":0,"id":702,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/580/?title=%E4%BA%BA%E6%80%A7","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/de2c7c29deec1a0e8383a1ee295d9747.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/de2c7c29deec1a0e8383a1ee295d9747.jpeg?imageMogr2/quality/100","name":"人性","communityIndex":0,"id":580,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/530/?title=%E4%BA%BA%E7%94%9F","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/a57744110ddbaa1e99d148a01c1b1bd8.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/a57744110ddbaa1e99d148a01c1b1bd8.jpeg?imageMogr2/quality/60/format/jpg","name":"人生","communityIndex":0,"id":530,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/24/?title=%E8%AE%B0%E5%BD%95","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/c3984cad49455e01637347e0c8f6a37d.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/fd76dab1411e07f0dcf45309720134f9.jpeg?imageMogr2/quality/100","name":"记录","communityIndex":0,"id":24,"adTrack":null,"desc":"告诉他们为什么与众不同","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=217199&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=217199"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606784436000,"description":"如果有机会,你会问 HIV 携带者什么问题?一位 HIV 携带者回答了陌生人各样的问题。他在感染 HIV 后审视生命,决定为 HIV 携带者发声。目前,抗病毒药物在全球大范围普及,艾滋病已经成为一种「慢性病」。根据联合国认证的「U=U」理论,当 HIV 感染者体内的病毒载量连续六个月以上处于检测不出的水平时,HIV 就不会通过性接触传播。疾病并不可怕,真正可怕的是社会的偏见。疾病与性道德无关,这是我们的态度。From Jubilee","remark":"","title":"我是 HIV+,想问什么都可以","recallSource":null,"duration":481,"library":"DAILY","descriptionEditor":"如果有机会,你会问 HIV 携带者什么问题?一位 HIV 携带者回答了陌生人各样的问题。他在感染 HIV 后审视生命,决定为 HIV 携带者发声。目前,抗病毒药物在全球大范围普及,艾滋病已经成为一种「慢性病」。根据联合国认证的「U=U」理论,当 HIV 感染者体内的病毒载量连续六个月以上处于检测不出的水平时,HIV 就不会通过性接触传播。疾病并不可怕,真正可怕的是社会的偏见。疾病与性道德无关,这是我们的态度。From Jubilee","provider":{"name":"YouTube","icon":"http://img.kaiyanapp.com/fa20228bc5b921e837156923a58713f6.png","alias":"youtube"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":252,"replyCount":7,"realCollectionCount":202,"collectionCount":787},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[{"width":1280,"name":"高清","urlList":[{"size":36012046,"name":"aliyun","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=217199&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid="},{"size":36012046,"name":"ucloud","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=217199&resourceType=video&editionType=high&source=ucloud&playUrlType=url_oss&udid="}],"type":"high","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=217199&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid=","height":720}],"ifLimitVideo":false,"category":"记录","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"1","id":0,"type":"video","trackingData":null},{"data":{"date":1606784400000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224109&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/6e2f2284a23e0f2bda1fc9f8a740e34e.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/6e2f2284a23e0f2bda1fc9f8a740e34e.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/7206420ab8bae9858812ce4ebd703247.png?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/6e2f2284a23e0f2bda1fc9f8a740e34e.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":{"fileSizeStr":"2.12MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/ef1e4d72fa74d168c57478844ed6b5b7.mp4"},"id":224109,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":2162,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/98beab66d3885a139b54f21e91817c4f.jpeg","link":"","description":"为广告人的精彩创意点赞","videoNum":1443,"follow":{"itemId":2162,"itemType":"author","followed":false},"recSort":0,"name":"开眼广告精选","ifPgc":true,"latestReleaseTime":1606784454000,"id":2162,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/748/?title=%E8%BF%99%E4%BA%9B%E5%B9%BF%E5%91%8A%E8%B6%85%E6%9C%89%E6%A2%97","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/9056413cfeffaf0c841d894390aa8e08.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/ff0f6d0ad5f4b6211a3f746aaaffd916.jpeg?imageMogr2/quality/60/format/jpg","name":"这些广告超有梗","communityIndex":0,"id":748,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/758/?title=%E6%AC%A7%E7%BE%8E%E5%B9%BF%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/4347ee94f8ae98a86f2913db3b8638f3.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/8494d3626c41f8e8cb6316767cc0f573.jpeg?imageMogr2/quality/60/format/jpg","name":"欧美广告","communityIndex":0,"id":758,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/760/?title=%E5%81%9A%E6%A2%A6%E9%83%BD%E4%BC%9A%E7%AC%91%E9%86%92%E7%9A%84%E5%B9%BF%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/a7c61f4ff77e31ed2a24ee265184f8cb.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/ed1de432dca0a8e1fee20696980329fe.jpeg?imageMogr2/quality/60/format/jpg","name":"做梦都会笑醒的广告","communityIndex":0,"id":760,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/222/?title=%E4%BA%BA%E5%A3%B0","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/138ec1aca3bcda71fe5bd8fd26f1e828.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/138ec1aca3bcda71fe5bd8fd26f1e828.jpeg?imageMogr2/quality/60/format/jpg","name":"人声","communityIndex":0,"id":222,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/170/?title=%E5%B9%BD%E9%BB%98","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/8164ded95cfde8c5f42acf243c6ca3e6.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/8164ded95cfde8c5f42acf243c6ca3e6.jpeg?imageMogr2/quality/60/format/jpg","name":"幽默","communityIndex":0,"id":170,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/140/?title=%E6%90%9E%E7%AC%91","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f787d5053443499e8d787911cd8b3876.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f2b803d3c383bba5a3888b2709160b6e.jpeg?imageMogr2/quality/60/format/jpg","name":"搞笑","communityIndex":0,"id":140,"adTrack":null,"desc":"哈哈哈哈哈哈哈哈","newestEndTime":null},{"actionUrl":"eyepetizer://tag/120/?title=%E9%BB%91%E8%89%B2%E5%B9%BD%E9%BB%98","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/56b14178e460bff91a6104590799b7d6.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f787d5053443499e8d787911cd8b3876.jpeg?imageMogr2/quality/100","name":"黑色幽默","communityIndex":0,"id":120,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/16/?title=%E5%B9%BF%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/e41e74fe73882b552de00d95d56748d2.jpeg?imageMogr2/quality/60","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/3054658dbd559ac42c4c282e9cab7a32.jpeg?imageMogr2/quality/100","name":"广告","communityIndex":0,"id":16,"adTrack":null,"desc":"为广告人的精彩创意点赞","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=224109&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=224109"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606784454000,"description":"英国家庭用纸品牌 Plenty 打破圣诞广告走温馨风格的惯例,推出了这支名为「Xmess 一团糟」的宣传片。圣诞节看似热闹温馨的场景,却处处隐藏着婴儿吐奶、葡萄酒洒在身上、做好的火鸡翻倒等等「灾难」发生,幸好有爱、有 Plenty......From Plenty UK","remark":null,"title":"圣诞广告看够了,但这反套路的还可以","recallSource":null,"duration":96,"library":"DAILY","descriptionEditor":"英国家庭用纸品牌 Plenty 打破圣诞广告走温馨风格的惯例,推出了这支名为「Xmess 一团糟」的宣传片。圣诞节看似热闹温馨的场景,却处处隐藏着婴儿吐奶、葡萄酒洒在身上、做好的火鸡翻倒等等「灾难」发生,幸好有爱、有 Plenty......From Plenty UK","provider":{"name":"YouTube","icon":"http://img.kaiyanapp.com/fa20228bc5b921e837156923a58713f6.png","alias":"youtube"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":93,"replyCount":3,"realCollectionCount":60,"collectionCount":303},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[{"width":1280,"name":"高清","urlList":[{"size":6126383,"name":"aliyun","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224109&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid="},{"size":6126383,"name":"ucloud","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224109&resourceType=video&editionType=high&source=ucloud&playUrlType=url_oss&udid="}],"type":"high","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224109&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid=","height":720}],"ifLimitVideo":false,"category":"广告","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"1","id":0,"type":"video","trackingData":null},{"data":{"date":1606784400000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=222938&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/81426886744cf06ac1fef2dc49266bda.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/81426886744cf06ac1fef2dc49266bda.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/d4836a0e68f76d5a5b3b91f1c53a1a94.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/81426886744cf06ac1fef2dc49266bda.jpeg?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":{"fileSizeStr":"4.83MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/b74e7caf48bc9b79d1a552d742f42293.mp4"},"id":222938,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":5361,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/51744432e1309b9954f60789d665dd3e.jpeg?imageMogr2/quality/60/format/jpg","link":"","description":"我们会精选一些影视方面的视频,推荐给大家!","videoNum":50,"follow":{"itemId":5361,"itemType":"author","followed":false},"recSort":0,"name":"影视精选视频","ifPgc":true,"latestReleaseTime":1606840189000,"id":5361,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/796/?title=%E8%BF%B7%E5%BD%B1%E6%94%BE%E6%98%A0%E5%AE%A4","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/64f2b2ed039bd92c3be10d003d6041bf.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/56a8818adb038c59ab04ffc781db2f50.jpeg?imageMogr2/quality/60/format/jpg","name":"迷影放映室","communityIndex":0,"id":796,"adTrack":null,"desc":"电影、剧集、戏剧抢先看","newestEndTime":null},{"actionUrl":"eyepetizer://tag/1025/?title=%E5%BD%B1%E8%A7%86","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/8a298964e7c9fc2ae16342832e36d88d.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/9d7fe42c1445031e4c8f2421b652a011.jpeg?imageMogr2/quality/60/format/jpg","name":"影视","communityIndex":0,"id":1025,"adTrack":null,"desc":"电影、剧集、戏剧抢先看","newestEndTime":null},{"actionUrl":"eyepetizer://tag/34/?title=%E6%B7%B7%E5%89%AA","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/ebf307197b634f30b2fa4eb867e908c1.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/ebf307197b634f30b2fa4eb867e908c1.jpeg?imageMogr2/quality/60/format/jpg","name":"混剪","communityIndex":0,"id":34,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/496/?title=%E8%87%B4%E6%95%AC","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f9d6f16db9ea2e894f8e5e2ee7071d99.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f9d6f16db9ea2e894f8e5e2ee7071d99.jpeg?imageMogr2/quality/60/format/jpg","name":"致敬","communityIndex":0,"id":496,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/506/?title=%E7%BB%8F%E5%85%B8","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/1e948eab70737d8beca9f52fce907ab5.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/1e948eab70737d8beca9f52fce907ab5.jpeg?imageMogr2/quality/60/format/jpg","name":"经典","communityIndex":0,"id":506,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/350/?title=%E6%97%A5%E6%9C%AC","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/0e118c56a85899055348d15120841ecf.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/0e118c56a85899055348d15120841ecf.jpeg?imageMogr2/quality/60/format/jpg","name":"日本","communityIndex":0,"id":350,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/122/?title=%E7%A7%91%E5%B9%BB","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/417a8466c670ccde688bb4b525ddf23d.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/114beec25470880881352171834ddf43.jpeg?imageMogr2/quality/60","name":"科幻","communityIndex":0,"id":122,"adTrack":null,"desc":null,"newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=222938&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=222938"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606784473000,"description":"「新世纪福音战士」主要讲述了在 2015 年少年少女们操控巨大泛用人形决战兵器「EVA」,与神秘敌人「使徒」之间的战斗故事。这部动画诞生于 90 年代,是许多人童年的回忆,现在看依然是神作。BGM:「残酷な天使のテーゼ」\u2014\u2014中川翔子. From The Beauty Of","remark":null,"title":"新世纪福音战士,「致命」的童年回忆杀","recallSource":null,"duration":259,"library":"DAILY","descriptionEditor":"「新世纪福音战士」主要讲述了在 2015 年少年少女们操控巨大泛用人形决战兵器「EVA」,与神秘敌人「使徒」之间的战斗故事。这部动画诞生于 90 年代,是许多人童年的回忆,现在看依然是神作。BGM:「残酷な天使のテーゼ」\u2014\u2014中川翔子. From The Beauty Of","provider":{"name":"YouTube","icon":"http://img.kaiyanapp.com/fa20228bc5b921e837156923a58713f6.png","alias":"youtube"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":132,"replyCount":7,"realCollectionCount":119,"collectionCount":265},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"影视","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"1","id":0,"type":"video","trackingData":null},{"data":{"date":1606784400000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225405&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/6bbb15245e13bac91b40c8fb050c3d59.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/6bbb15245e13bac91b40c8fb050c3d59.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/f8e545de8707f517343f5263765a9ee3.jpeg?imageMogr2/quality/60/format/jpg","homepage":null},"videoPosterBean":{"fileSizeStr":"3.8MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/0670b477d580699ac04a14a10d02b3b0.mp4"},"id":225405,"descriptionPgc":"2019 年 1~10 月间,我国新增艾滋病病毒感染 13.1 万例。这种病毒是如何在人群中传播的?当一个人面临较高的感染风险,他/她又有哪些自救措施?为了保护自己,我们又有哪些预防手段?","recall_source":null,"ad":false,"author":{"shield":{"itemId":2290,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/e13c3a9314113a35b007a82975f58f71.png?imageMogr2/quality/60/format/jpg","link":"","description":"回形针是你的当代生活说明书。","videoNum":160,"follow":{"itemId":2290,"itemType":"author","followed":false},"recSort":0,"name":"回形针PaperClip","ifPgc":true,"latestReleaseTime":1606747380000,"id":2290,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/44/?title=5%20%E5%88%86%E9%92%9F%E6%96%B0%E7%9F%A5","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f2e7359e81e217782f32cc3d482b3284.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f2e7359e81e217782f32cc3d482b3284.jpeg?imageMogr2/quality/60/format/jpg","name":"5 分钟新知","communityIndex":0,"id":44,"adTrack":null,"desc":"大千世界,总有你不知道的","newestEndTime":null},{"actionUrl":"eyepetizer://tag/1024/?title=%E7%A7%91%E6%8A%80","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/7e326064edc565ac6355921cfe4b3e46.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/810adad06df812462bb0e00501fa679c.png?imageMogr2/quality/60/format/jpg","name":"科技","communityIndex":0,"id":1024,"adTrack":null,"desc":"新知识与一切先进生产力","newestEndTime":null},{"actionUrl":"eyepetizer://tag/1040/?title=%E7%A7%91%E6%99%AE","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/86af95dab03ab8fac3342517e83b07bb.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/86af95dab03ab8fac3342517e83b07bb.jpeg?imageMogr2/quality/60/format/jpg","name":"科普","communityIndex":0,"id":1040,"adTrack":null,"desc":null,"newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225405","raw":"http://www.eyepetizer.net/detail.html?vid=225405"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606747380000,"description":"2019 年 1~10 月间,我国新增艾滋病病毒感染 13.1 万例。这种病毒是如何在人群中传播的?当一个人面临较高的感染风险,他/她又有哪些自救措施?为了保护自己,我们又有哪些预防手段?","remark":"","title":"HIV 自救指南","recallSource":null,"duration":486,"library":"DAILY","descriptionEditor":"","provider":{"name":"PGC","icon":"","alias":"PGC"},"titlePgc":"HIV 自救指南","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":647,"replyCount":11,"realCollectionCount":413,"collectionCount":1148},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"科技","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"1","id":0,"type":"video","trackingData":null},{"data":{"date":1606784400000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=224492&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/aa46d61c6c2c3c0b7466cf389ebcc3ad.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/aa46d61c6c2c3c0b7466cf389ebcc3ad.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/bef9d5538c4eb29d2e34648b37de2900.png?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/aa46d61c6c2c3c0b7466cf389ebcc3ad.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":{"fileSizeStr":"2.31MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/3345636a9eae5b73277df6e31b1abe78.mp4"},"id":224492,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":2161,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/f4a9aba1c6857ee0cefcdc5aee0a1fc9.png?imageMogr2/quality/60/format/jpg","link":"","description":"技术与审美结合,探索视觉的无限可能","videoNum":982,"follow":{"itemId":2161,"itemType":"author","followed":false},"recSort":0,"name":"开眼创意精选","ifPgc":true,"latestReleaseTime":1606871634000,"id":2161,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/744/?title=%E6%AF%8F%E6%97%A5%E5%88%9B%E6%84%8F%E7%81%B5%E6%84%9F","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/bc2479c09cd15cb93b69d82e5f21c3fc.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/bc2479c09cd15cb93b69d82e5f21c3fc.png?imageMogr2/quality/60/format/jpg","name":"每日创意灵感","communityIndex":0,"id":744,"adTrack":null,"desc":"技术与审美结合,探索视觉的无限可能","newestEndTime":null},{"actionUrl":"eyepetizer://tag/1115/?title=%E5%85%89%E5%BD%B1","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/b50ab9edc704883e4c8b7060154735b4.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/b50ab9edc704883e4c8b7060154735b4.jpeg?imageMogr2/quality/60/format/jpg","name":"光影","communityIndex":0,"id":1115,"adTrack":null,"desc":"记录你拍下的光与影","newestEndTime":null},{"actionUrl":"eyepetizer://tag/675/?title=%E6%91%84%E5%BD%B1%E8%89%BA%E6%9C%AF","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/c2f92f2aa503674c0e344d565e7f406b.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/c2f92f2aa503674c0e344d565e7f406b.jpeg?imageMogr2/quality/60/format/jpg","name":"摄影艺术","communityIndex":0,"id":675,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/532/?title=%E7%94%9F%E5%91%BD","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/687fd94bc3708365a213ecba55a3751d.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/4150858bb1b67cbc26d70c86cf130933.jpeg?imageMogr2/quality/100","name":"生命","communityIndex":0,"id":532,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/520/?title=%E5%A4%A7%E8%87%AA%E7%84%B6","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/4f8c478d7753f65e4ec3407b3d055edf.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/036745f32252000f3b91efc21aafcaf1.jpeg?imageMogr2/quality/100","name":"大自然","communityIndex":0,"id":520,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/208/?title=%E5%99%A8%E4%B9%90","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f5b284ad6d9bd5812f7336983ed9e908.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f5b284ad6d9bd5812f7336983ed9e908.png?imageMogr2/quality/60/format/jpg","name":"器乐","communityIndex":0,"id":208,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/190/?title=%E5%AE%8F%E5%A4%A7","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/293eb0312d5ad76044f212950fdd676f.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/293eb0312d5ad76044f212950fdd676f.jpeg?imageMogr2/quality/60/format/jpg","name":"宏大","communityIndex":0,"id":190,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/76/?title=%E9%BB%91%E7%99%BD","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f91b71f98bea65a3330ab6aac290eeb8.jpeg?imageMogr2/quality/60","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f91b71f98bea65a3330ab6aac290eeb8.jpeg?imageMogr2/quality/60","name":"黑白","communityIndex":0,"id":76,"adTrack":null,"desc":"定格黑白,聚焦光影,记录片刻和永恒","newestEndTime":null},{"actionUrl":"eyepetizer://tag/2/?title=%E5%88%9B%E6%84%8F","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/1b457058cf2b317304ff9f70543c040d.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/fdefdb34cbe3d2ac9964d306febe9025.jpeg?imageMogr2/quality/100","name":"创意","communityIndex":0,"id":2,"adTrack":null,"desc":"技术与审美结合,探索视觉的无限可能","newestEndTime":null},{"actionUrl":"eyepetizer://tag/94/?title=%E5%AE%9E%E9%AA%8C%E6%80%A7","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/e1a1a2b35f6916636594fe6bff4c5050.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/4aae1da4cea59eb15007e8d306c6eaea.jpeg?imageMogr2/quality/100","name":"实验性","communityIndex":0,"id":94,"adTrack":null,"desc":null,"newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=224492&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=224492"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606784474000,"description":"这则短片名为「荒野」,摄影师用黑白色调记录了大自然,加上对高级质感的光影和宏大背景音效的利用,呈现出了有如塔尔科夫斯基电影一般的绝美画面。From Ivan Maria Friedman","remark":null,"title":"黑白光影变化,摄影真正的高级感","recallSource":null,"duration":223,"library":"DAILY","descriptionEditor":"这则短片名为「荒野」,摄影师用黑白色调记录了大自然,加上对高级质感的光影和宏大背景音效的利用,呈现出了有如塔尔科夫斯基电影一般的绝美画面。From Ivan Maria Friedman","provider":{"name":"Vimeo","icon":"http://img.kaiyanapp.com/c3ad630be461cbb081649c9e21d6cbe3.png","alias":"vimeo"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":204,"replyCount":1,"realCollectionCount":242,"collectionCount":554},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"创意","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":"1","id":0,"type":"video","trackingData":null},{"data":{"footer":null,"dataType":"ItemCollection","count":5,"header":{"textAlign":"left","subTitleFont":null,"actionUrl":"eyepetizer://pgcs/all","description":"看到啦 / 影视精选视频 / PENTATONIX 阿卡贝拉人声乐团","label":null,"title":"热门作者 / 精选分类关注推荐","cover":"http://img.kaiyanapp.com/2d5b6990c04ec7a21d77779eabed7b3f.png","rightText":null,"labelList":null,"subTitle":null,"iconList":["http://img.kaiyanapp.com/5d73b3baa9c66c73f735a708a567513f.png?imageMogr2/quality/60/format/jpg","http://img.kaiyanapp.com/51744432e1309b9954f60789d665dd3e.jpeg?imageMogr2/quality/60/format/jpg","http://img.kaiyanapp.com/ccc2d6a2c43ec975fe2bda155a15c55a.jpeg?imageMogr2/quality/60/format/jpg"],"id":0,"font":"bold"},"itemList":[{"data":{"date":1606867767000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225428&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/e215999c38bbd9cb5ed2e6dd696b073d.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/e215999c38bbd9cb5ed2e6dd696b073d.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/c2d7ddab3015caf2a8d300509c18370c.jpeg?imageMogr2/quality/60/format/jpg","homepage":null},"videoPosterBean":null,"id":225428,"descriptionPgc":"比利时皇家美术馆坐落于首都布鲁塞尔,百米之外便是布鲁塞尔王宫,在这其中收藏着比利时以及欧洲各国中世纪以来的各类名画,具有极高的参观艺术价值。比利时皇家美术馆的藏品中,主要以大量的弗拉芒油画为主,其中有勃鲁盖尔、勃伦朗、雅各布·乔登斯等等名人们的作品,特别是在美术馆为荣的\u201c鲁本斯\u201d厅内,拥有着超过20幅的鲁本斯油画。除此之外,镇馆之宝,雅克-路易·大卫创作的著名油画《马拉之死》也藏于其中。\n","recall_source":null,"ad":false,"author":{"shield":{"itemId":1988,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/5d73b3baa9c66c73f735a708a567513f.png?imageMogr2/quality/60/format/jpg","link":"","description":"旅行短视频APP\"看到啦\",看到旅行的新鲜感/随心动,随手拍。\n真实的旅行短视频、定制好玩的旅行线路、制作创意的旅行短片、分享难忘的旅行点滴。","videoNum":125,"follow":{"itemId":1988,"itemType":"author","followed":false},"recSort":0,"name":"看到啦","ifPgc":true,"latestReleaseTime":1606867767000,"id":1988,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/10/?title=%E8%B7%9F%E7%9D%80%E5%BC%80%E7%9C%BC%E7%9C%8B%E4%B8%96%E7%95%8C","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/7ea328a893aa1f092b9328a53494a267.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/50dab5468ecd2dbe5eb99dab5d608a0a.jpeg?imageMogr2/quality/60/format/jpg","name":"跟着开眼看世界","communityIndex":14,"id":10,"adTrack":null,"desc":"去你想去的地方,发现世界的美","newestEndTime":null},{"actionUrl":"eyepetizer://tag/1019/?title=%E6%97%85%E8%A1%8C","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/67b5aa7b489b33e7894e04d293e9b01f.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/67b5aa7b489b33e7894e04d293e9b01f.jpeg?imageMogr2/quality/60/format/jpg","name":"旅行","communityIndex":0,"id":1019,"adTrack":null,"desc":"世界这么大,总有你的目的地","newestEndTime":null},{"actionUrl":"eyepetizer://tag/1456/?title=%E6%94%B6%E9%9B%86%E5%85%A8%E4%B8%96%E7%95%8C%E7%9A%84%E5%8D%9A%E7%89%A9%E9%A6%86","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/c6e84f23f52ccc489c0f70b9537355c9.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/c6e84f23f52ccc489c0f70b9537355c9.jpeg?imageMogr2/quality/60/format/jpg","name":"收集全世界的博物馆","communityIndex":5,"id":1456,"adTrack":null,"desc":"看见城市,看见世界","newestEndTime":null},{"actionUrl":"eyepetizer://tag/891/?title=%E7%94%A8%E6%97%85%E8%A1%8C%E7%A9%BF%E8%B6%8A%E7%94%9F%E6%B4%BB","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/79b9f964320f3942cf13205a45cd3419.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/79b9f964320f3942cf13205a45cd3419.jpeg?imageMogr2/quality/60/format/jpg","name":"用旅行穿越生活","communityIndex":0,"id":891,"adTrack":null,"desc":"没有哪种幸福可以胜过旅行的自由。因为仅仅活着是不够的,还应当穿越生活。","newestEndTime":null},{"actionUrl":"eyepetizer://tag/683/?title=%E8%89%BA%E6%9C%AF","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/7f4b28deb406f7e6b78d4f70c5bec99b.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/52560bde4d8415af5944c93298c09ca4.jpeg?imageMogr2/quality/60/format/jpg","name":"艺术","communityIndex":15,"id":683,"adTrack":null,"desc":"用形象纪录\u201c我思\u201d","newestEndTime":null},{"actionUrl":"eyepetizer://tag/370/?title=%E6%AC%A7%E6%B4%B2","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/e5f917d0a272dd19672e7c67e44084d2.png?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/e5f917d0a272dd19672e7c67e44084d2.png?imageMogr2/quality/60/format/jpg","name":"欧洲","communityIndex":0,"id":370,"adTrack":null,"desc":null,"newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225428","raw":"http://www.eyepetizer.net/detail.html?vid=225428"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606867767000,"description":"比利时皇家美术馆坐落于首都布鲁塞尔,百米之外便是布鲁塞尔王宫,在这其中收藏着比利时以及欧洲各国中世纪以来的各类名画,具有极高的参观艺术价值。比利时皇家美术馆的藏品中,主要以大量的弗拉芒油画为主,其中有勃鲁盖尔、勃伦朗、雅各布·乔登斯等等名人们的作品,特别是在美术馆为荣的\u201c鲁本斯\u201d厅内,拥有着超过20幅的鲁本斯油画。除此之外,镇馆之宝,雅克-路易·大卫创作的著名油画《马拉之死》也藏于其中。\n","remark":"","title":"比利时法兰德斯艺术之旅:比利时皇家美术馆","recallSource":null,"duration":243,"library":"DEFAULT","descriptionEditor":"","provider":{"name":"PGC","icon":"","alias":"PGC"},"titlePgc":"比利时法兰德斯艺术之旅:比利时皇家美术馆","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":0,"replyCount":0,"realCollectionCount":0,"collectionCount":0},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"旅行","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null},{"data":{"date":1606840189000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225530&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/97e4bf7d1f3c1e93b082f5ac97c60a2c.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/97e4bf7d1f3c1e93b082f5ac97c60a2c.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/4264d056c8704d46914d4eca781b1e96.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/97e4bf7d1f3c1e93b082f5ac97c60a2c.jpeg?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":null,"id":225530,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":5361,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/51744432e1309b9954f60789d665dd3e.jpeg?imageMogr2/quality/60/format/jpg","link":"","description":"我们会精选一些影视方面的视频,推荐给大家!","videoNum":50,"follow":{"itemId":5361,"itemType":"author","followed":false},"recSort":0,"name":"影视精选视频","ifPgc":true,"latestReleaseTime":1606840189000,"id":5361,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/796/?title=%E8%BF%B7%E5%BD%B1%E6%94%BE%E6%98%A0%E5%AE%A4","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/64f2b2ed039bd92c3be10d003d6041bf.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/56a8818adb038c59ab04ffc781db2f50.jpeg?imageMogr2/quality/60/format/jpg","name":"迷影放映室","communityIndex":0,"id":796,"adTrack":null,"desc":"电影、剧集、戏剧抢先看","newestEndTime":null},{"actionUrl":"eyepetizer://tag/777/?title=%E5%8A%A8%E7%94%BB%E7%94%B5%E5%BD%B1","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/ce96474453286a52f0e7ed9d16e1eaf4.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/ce96474453286a52f0e7ed9d16e1eaf4.jpeg?imageMogr2/quality/60/format/jpg","name":"动画电影","communityIndex":0,"id":777,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/793/?title=%E5%BD%B1%E8%A7%86%E9%A2%84%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/66a25db995c30f130c433b2422111541.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/528bbba3db1e6388c4a97edce734a743.jpeg?imageMogr2/quality/60/format/jpg","name":"影视预告","communityIndex":0,"id":793,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/570/?title=%E7%94%B5%E5%BD%B1%E7%9B%B8%E5%85%B3","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/bee7c0cd647345f911c10be60ffcde93.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/bee7c0cd647345f911c10be60ffcde93.jpeg?imageMogr2/quality/60/format/jpg","name":"电影相关","communityIndex":0,"id":570,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/420/?title=%E7%9A%AE%E5%85%8B%E6%96%AF","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/2efed73c9bc3e10b37eeb840003bd9cb.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/239aacd78b31bf01ce67a9cb8db0e911.jpeg?imageMogr2/quality/60","name":"皮克斯","communityIndex":0,"id":420,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/174/?title=%E6%B2%BB%E6%84%88","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/5417e0d8f72d7bb3f1cd69eb75b0759e.jpeg?imageMogr2/quality/60","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/5417e0d8f72d7bb3f1cd69eb75b0759e.jpeg?imageMogr2/quality/60","name":"治愈","communityIndex":0,"id":174,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/176/?title=%E6%84%9F%E4%BA%BA","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/8b4dbcea6462e9c54994a46c9670e8f0.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/8b4dbcea6462e9c54994a46c9670e8f0.jpeg?imageMogr2/quality/60/format/jpg","name":"感人","communityIndex":0,"id":176,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/136/?title=%E6%B8%A9%E6%83%85","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/0bc1dc78c631eae017ee69418303adc5.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/0bc1dc78c631eae017ee69418303adc5.jpeg?imageMogr2/quality/100","name":"温情","communityIndex":0,"id":136,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/1025/?title=%E5%BD%B1%E8%A7%86","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/8a298964e7c9fc2ae16342832e36d88d.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/9d7fe42c1445031e4c8f2421b652a011.jpeg?imageMogr2/quality/60/format/jpg","name":"影视","communityIndex":0,"id":1025,"adTrack":null,"desc":"电影、剧集、戏剧抢先看","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225530","raw":"http://www.eyepetizer.net/detail.html?vid=225530"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606840189000,"description":"皮克斯 2020 新作「心灵奇旅」将于 12 月 25 日在北美上线流媒体迪士尼 + 观看,中国内地于同日在院线上映。讲述了中学音乐老师 Gardner 灵魂与肉体分离后的奇幻旅程。From 迪士尼影業","remark":null,"title":"皮克斯年度感恩巨献「心灵奇旅」加长版预告","recallSource":null,"duration":121,"library":"DEFAULT","descriptionEditor":"皮克斯 2020 新作「心灵奇旅」将于 12 月 25 日在北美上线流媒体迪士尼 + 观看,中国内地于同日在院线上映。讲述了中学音乐老师 Gardner 灵魂与肉体分离后的奇幻旅程。From 迪士尼影業","provider":{"name":"YouTube","icon":"http://img.kaiyanapp.com/fa20228bc5b921e837156923a58713f6.png","alias":"youtube"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":0,"replyCount":0,"realCollectionCount":0,"collectionCount":6},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"影视","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null},{"data":{"date":1606839246000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225521&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/ca3ac651d3400930c8d7fa9b5ab12030.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/ca3ac651d3400930c8d7fa9b5ab12030.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/c2e2a4722ab15171f0b805ed7416e5c1.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/ca3ac651d3400930c8d7fa9b5ab12030.jpeg?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":null,"id":225521,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":461,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/ccc2d6a2c43ec975fe2bda155a15c55a.jpeg?imageMogr2/quality/60/format/jpg","link":"","description":"Pentatonix,简称PTX,来自美国德克萨斯州阿灵顿的纯人声乐团,The Sing-Off第三季的总冠军,由四名男生和一名女生成员组成。该团以完美的默契度所演唱的和声,足以媲美乐队伴奏的乐曲。同时,该组合的音乐领域极为丰富,包括摇滚乐、电子乐、雷鬼音乐、乡村音乐、朋克等,每一种风格的音乐作品在他们的演唱之下都富含新颖的内涵,使人产生耳目一新的感觉。并且该队打破了阿卡贝拉的固有传统,用人声涉足流行乐坛,引领了阿卡贝拉界的新潮流。","videoNum":69,"follow":{"itemId":461,"itemType":"author","followed":false},"recSort":0,"name":"PENTATONIX 阿卡贝拉人声乐团","ifPgc":true,"latestReleaseTime":1606839246000,"id":461,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/18/?title=%E9%9F%B3%E4%B9%90%E7%94%B5%E5%8F%B0","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/70e1bedfdff53729402f1998788c3ee9.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/a27b2660a5c84adaf5c9fc1ea8cc9946.jpeg?imageMogr2/quality/60/format/jpg","name":"音乐电台","communityIndex":0,"id":18,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/747/?title=MV","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/b5c23136dc7275281d8b92db9712a44c.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/1d0e241628cc279959a3c26c3a14ac87.jpeg?imageMogr2/quality/60/format/jpg","name":"MV","communityIndex":0,"id":747,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/212/?title=%E9%9F%B3%E4%B9%90%E7%BF%BB%E5%94%B1","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/3b89837ec5b95b2c4fdc9538434354b1.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/3b89837ec5b95b2c4fdc9538434354b1.jpeg?imageMogr2/quality/60/format/jpg","name":"音乐翻唱","communityIndex":0,"id":212,"adTrack":null,"desc":"为我们爱的音乐注入全新生命力","newestEndTime":null},{"actionUrl":"eyepetizer://tag/1018/?title=%E9%9F%B3%E4%B9%90","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/46b2ed7ccd3e241ff54a314faf2632b8.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/46b2ed7ccd3e241ff54a314faf2632b8.jpeg?imageMogr2/quality/60/format/jpg","name":"音乐","communityIndex":0,"id":1018,"adTrack":null,"desc":"用眼睛就能「听」的艺术","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225521","raw":"http://www.eyepetizer.net/detail.html?vid=225521"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606839246000,"description":"无伴奏人声合唱乐团 Pentatonix 最新音乐视频「Thank You」发布。提前预祝大家圣诞节快乐!","remark":null,"title":"阿卡贝拉乐团 Pentatonix「Thank You」","recallSource":null,"duration":251,"library":"DEFAULT","descriptionEditor":"无伴奏人声合唱乐团 Pentatonix 最新音乐视频「Thank You」发布。提前预祝大家圣诞节快乐!","provider":{"name":"YouTube","icon":"http://img.kaiyanapp.com/fa20228bc5b921e837156923a58713f6.png","alias":"youtube"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":7,"replyCount":0,"realCollectionCount":6,"collectionCount":6},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"音乐","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null},{"data":{"date":1606839241000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225509&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/d7799966c6378c97c822071dc9cd1781.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/d7799966c6378c97c822071dc9cd1781.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/7d4d6e25b49993f43a6b86f488eb046c.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/d7799966c6378c97c822071dc9cd1781.jpeg?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":null,"id":225509,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":817,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/b0c49e7fd388795f87d1c0c80e666882.jpeg?imageMogr2/quality/60/format/jpg","link":"","description":"MV 精选频道。","videoNum":2175,"follow":{"itemId":817,"itemType":"author","followed":false},"recSort":0,"name":"Music Video 精选","ifPgc":true,"latestReleaseTime":1606839241000,"id":817,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/18/?title=%E9%9F%B3%E4%B9%90%E7%94%B5%E5%8F%B0","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/70e1bedfdff53729402f1998788c3ee9.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/a27b2660a5c84adaf5c9fc1ea8cc9946.jpeg?imageMogr2/quality/60/format/jpg","name":"音乐电台","communityIndex":0,"id":18,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/747/?title=MV","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/b5c23136dc7275281d8b92db9712a44c.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/1d0e241628cc279959a3c26c3a14ac87.jpeg?imageMogr2/quality/60/format/jpg","name":"MV","communityIndex":0,"id":747,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/1018/?title=%E9%9F%B3%E4%B9%90","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/46b2ed7ccd3e241ff54a314faf2632b8.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/46b2ed7ccd3e241ff54a314faf2632b8.jpeg?imageMogr2/quality/60/format/jpg","name":"音乐","communityIndex":0,"id":1018,"adTrack":null,"desc":"用眼睛就能「听」的艺术","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225509","raw":"http://www.eyepetizer.net/detail.html?vid=225509"},"campaign":null,"idx":0,"slogan":"","shareAdTrack":null,"releaseTime":1606839241000,"description":"皮叔 Pitbull 联手 IAmChino & Papayo 新单「Se La Vi」官方 MV 发布。皮叔的说唱充满激情,MV 画面也十分性感!From Pitbull","remark":"","title":"皮叔 Pitbull 联手两位歌手发布新单「Se La Vi」","recallSource":null,"duration":256,"library":"DEFAULT","descriptionEditor":"皮叔 Pitbull 联手 IAmChino & Papayo 新单「Se La Vi」官方 MV 发布。皮叔的说唱充满激情,MV 画面也十分性感!From Pitbull","provider":{"name":"YouTube","icon":"http://img.kaiyanapp.com/fa20228bc5b921e837156923a58713f6.png","alias":"youtube"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":7,"replyCount":0,"realCollectionCount":0,"collectionCount":0},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"音乐","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null},{"data":{"date":1606839228000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225084&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/7778d3450e465fa11cfce616e7468e4b.jpeg?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/7778d3450e465fa11cfce616e7468e4b.jpeg?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/33a862a1581db262de9ac48016fbf7da.jpeg?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/7778d3450e465fa11cfce616e7468e4b.jpeg?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":null,"id":225084,"descriptionPgc":null,"recall_source":null,"ad":false,"author":{"shield":{"itemId":3451,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/dd692dae17fadf756b828d4e94a9d341.jpeg?imageMogr2/quality/60/format/jpg","link":"","description":"直击当下是一个追踪现实、记录当下的纪实平台,我们直击真人真事,将镜头对准社会焦点。","videoNum":553,"follow":{"itemId":3451,"itemType":"author","followed":false},"recSort":0,"name":"直击当下","ifPgc":true,"latestReleaseTime":1606839228000,"id":3451,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/743/?title=%E8%AE%B0%E5%BD%95%E7%B2%BE%E9%80%89","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/a082f44b88e78daaf19fa4e1a2faaa5a.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/a082f44b88e78daaf19fa4e1a2faaa5a.jpeg?imageMogr2/quality/60/format/jpg","name":"记录精选","communityIndex":0,"id":743,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/690/?title=%E9%85%92","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/59fb19667bf6674b71a40cfca05ee8dd.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/59fb19667bf6674b71a40cfca05ee8dd.jpeg?imageMogr2/quality/60/format/jpg","name":"酒","communityIndex":0,"id":690,"adTrack":null,"desc":null,"newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225084&resourceType=video&utm_campaign=routine&utm_medium=share&utm_source=weibo&uid=0","raw":"http://www.eyepetizer.net/detail.html?vid=225084"},"campaign":null,"idx":0,"slogan":null,"shareAdTrack":null,"releaseTime":1606839228000,"description":"不会品葡萄酒的你快看过来!From South China Morning Post","remark":"专业葡萄酒品酒指南,喝酒小白必看!","title":"专业葡萄酒品酒指南,品酒小白必看!","recallSource":null,"duration":106,"library":"DEFAULT","descriptionEditor":"不会品葡萄酒的你快看过来!From South China Morning Post","provider":{"name":"YouTube","icon":"http://img.kaiyanapp.com/fa20228bc5b921e837156923a58713f6.png","alias":"youtube"},"titlePgc":null,"adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":0,"replyCount":0,"realCollectionCount":6,"collectionCount":6},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[{"width":1280,"name":"高清","urlList":[{"size":15790391,"name":"aliyun","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225084&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid="},{"size":15790391,"name":"ucloud","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225084&resourceType=video&editionType=high&source=ucloud&playUrlType=url_oss&udid="}],"type":"high","url":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225084&resourceType=video&editionType=high&source=aliyun&playUrlType=url_oss&udid=","height":720}],"ifLimitVideo":false,"category":"记录","thumbPlayUrl":null,"resourceType":"video","promotion":null},"adIndex":-1,"tag":null,"id":0,"type":"video","trackingData":null}],"adTrack":null},"adIndex":-1,"tag":null,"id":0,"type":"videoCollectionOfFollow","trackingData":null}]
* lastStartId : 0
*/
private long date;
private long nextPublishTime;
private boolean adExist;
private String dialog;
private String topIssue;
private int total;
private String nextPageUrl;
private int refreshCount;
private int count;
private List<ItemListEntity> itemList;
private int lastStartId;
public void setDate(long date) {
this.date = date;
}
public void setNextPublishTime(long nextPublishTime) {
this.nextPublishTime = nextPublishTime;
}
public void setAdExist(boolean adExist) {
this.adExist = adExist;
}
public void setDialog(String dialog) {
this.dialog = dialog;
}
public void setTopIssue(String topIssue) {
this.topIssue = topIssue;
}
public void setTotal(int total) {
this.total = total;
}
public void setNextPageUrl(String nextPageUrl) {
this.nextPageUrl = nextPageUrl;
}
public void setRefreshCount(int refreshCount) {
this.refreshCount = refreshCount;
}
public void setCount(int count) {
this.count = count;
}
public void setItemList(List<ItemListEntity> itemList) {
this.itemList = itemList;
}
public void setLastStartId(int lastStartId) {
this.lastStartId = lastStartId;
}
public long getDate() {
return date;
}
public long getNextPublishTime() {
return nextPublishTime;
}
public boolean isAdExist() {
return adExist;
}
public String getDialog() {
return dialog;
}
public String getTopIssue() {
return topIssue;
}
public int getTotal() {
return total;
}
public String getNextPageUrl() {
return nextPageUrl;
}
public int getRefreshCount() {
return refreshCount;
}
public int getCount() {
return count;
}
public List<ItemListEntity> getItemList() {
return itemList;
}
public int getLastStartId() {
return lastStartId;
}
public class ItemListEntity {
/**
* data : {"date":1606870800000,"brandWebsiteInfo":null,"collected":false,"type":"NORMAL","favoriteAdTrack":null,"waterMarks":null,"playUrl":"http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225498&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=","cover":{"feed":"http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/1163c79742996c7315be2105b14a1b94.png?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"},"videoPosterBean":{"fileSizeStr":"3.53MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/3c6d9321d68a7145f299990fd5648fe4.mp4"},"id":225498,"descriptionPgc":"","recall_source":null,"ad":false,"author":{"shield":{"itemId":1027,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/27c223e61df5b647d061e41ee995e8f6.jpeg?imageMogr2/quality/60/format/jpg","link":"","description":"分享创意广告短视频","videoNum":951,"follow":{"itemId":1027,"itemType":"author","followed":false},"recSort":0,"name":"这些广告超有梗","ifPgc":true,"latestReleaseTime":1606839239000,"id":1027,"adTrack":null},"dataType":"VideoBeanForClient","playlists":null,"tags":[{"actionUrl":"eyepetizer://tag/748/?title=%E8%BF%99%E4%BA%9B%E5%B9%BF%E5%91%8A%E8%B6%85%E6%9C%89%E6%A2%97","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/9056413cfeffaf0c841d894390aa8e08.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/ff0f6d0ad5f4b6211a3f746aaaffd916.jpeg?imageMogr2/quality/60/format/jpg","name":"这些广告超有梗","communityIndex":0,"id":748,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/140/?title=%E6%90%9E%E7%AC%91","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f787d5053443499e8d787911cd8b3876.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f2b803d3c383bba5a3888b2709160b6e.jpeg?imageMogr2/quality/60/format/jpg","name":"搞笑","communityIndex":0,"id":140,"adTrack":null,"desc":"哈哈哈哈哈哈哈哈","newestEndTime":null},{"actionUrl":"eyepetizer://tag/766/?title=%E8%84%91%E6%B4%9E%E5%B9%BF%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/7c46ad04ff913b87915615c78d226a40.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/0d6ab7ed49de67eab89ada4f65353e8c.jpeg?imageMogr2/quality/60/format/jpg","name":"脑洞广告","communityIndex":0,"id":766,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/16/?title=%E5%B9%BF%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/e41e74fe73882b552de00d95d56748d2.jpeg?imageMogr2/quality/60","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/3054658dbd559ac42c4c282e9cab7a32.jpeg?imageMogr2/quality/100","name":"广告","communityIndex":0,"id":16,"adTrack":null,"desc":"为广告人的精彩创意点赞","newestEndTime":null}],"webAdTrack":null,"webUrl":{"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225498","raw":"http://www.eyepetizer.net/detail.html?vid=225498"},"campaign":null,"idx":0,"slogan":"","shareAdTrack":null,"releaseTime":1606839239000,"description":"这是一则来自瑞典智慧财产管理局广告。广告讲述了以「制假买假」的形式向人们展示了不良商家。睁眼瞎牌墨镜,烫头皮直发夹,过敏反应香水,这些名字听了就让人觉得搞笑。From Swedish Intellectual Property Office","remark":"我就不信,戴墨镜不是为了装","title":"你一本正经胡说八道卖东西的样子,让我上瘾","recallSource":null,"duration":120,"library":"DAILY","descriptionEditor":"这是一则来自瑞典智慧财产管理局广告。广告讲述了以「制假买假」的形式向人们展示了不良商家。睁眼瞎牌墨镜,烫头皮直发夹,过敏反应香水,这些名字听了就让人觉得搞笑。From Swedish Intellectual Property Office","provider":{"name":"投稿","icon":"","alias":"PGC2"},"titlePgc":"","adTrack":[],"subtitles":[],"src":null,"searchWeight":0,"consumption":{"shareCount":7,"replyCount":2,"realCollectionCount":32,"collectionCount":52},"reallyCollected":false,"label":null,"played":false,"labelList":[],"lastViewTime":null,"playInfo":[],"ifLimitVideo":false,"category":"广告","thumbPlayUrl":"","resourceType":"video","promotion":null}
* adIndex : -1
* tag : 0
* id : 0
* type : video
* trackingData : null
*/
private DataEntity data;
private int adIndex;
private String tag;
private int id;
private String type;
private String trackingData;
public void setData(DataEntity data) {
this.data = data;
}
public void setAdIndex(int adIndex) {
this.adIndex = adIndex;
}
public void setTag(String tag) {
this.tag = tag;
}
public void setId(int id) {
this.id = id;
}
public void setType(String type) {
this.type = type;
}
public void setTrackingData(String trackingData) {
this.trackingData = trackingData;
}
public DataEntity getData() {
return data;
}
public int getAdIndex() {
return adIndex;
}
public String getTag() {
return tag;
}
public int getId() {
return id;
}
public String getType() {
return type;
}
public String getTrackingData() {
return trackingData;
}
public class DataEntity {
/**
* date : 1606870800000
* brandWebsiteInfo : null
* collected : false
* type : NORMAL
* favoriteAdTrack : null
* waterMarks : null
* playUrl : http://baobab.kaiyanapp.com/api/v1/playUrl?vid=225498&resourceType=video&editionType=default&source=aliyun&playUrlType=url_oss&udid=
* cover : {"feed":"http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageMogr2/quality/60/format/jpg","detail":"http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageMogr2/quality/60/format/jpg","sharing":null,"blurred":"http://img.kaiyanapp.com/1163c79742996c7315be2105b14a1b94.png?imageMogr2/quality/60/format/jpg","homepage":"http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim"}
* videoPosterBean : {"fileSizeStr":"3.53MB","scale":0.725,"url":"http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/3c6d9321d68a7145f299990fd5648fe4.mp4"}
* id : 225498
* descriptionPgc :
* recall_source : null
* ad : false
* author : {"shield":{"itemId":1027,"itemType":"author","shielded":false},"expert":false,"approvedNotReadyVideoCount":0,"icon":"http://img.kaiyanapp.com/27c223e61df5b647d061e41ee995e8f6.jpeg?imageMogr2/quality/60/format/jpg","link":"","description":"分享创意广告短视频","videoNum":951,"follow":{"itemId":1027,"itemType":"author","followed":false},"recSort":0,"name":"这些广告超有梗","ifPgc":true,"latestReleaseTime":1606839239000,"id":1027,"adTrack":null}
* dataType : VideoBeanForClient
* playlists : null
* tags : [{"actionUrl":"eyepetizer://tag/748/?title=%E8%BF%99%E4%BA%9B%E5%B9%BF%E5%91%8A%E8%B6%85%E6%9C%89%E6%A2%97","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/9056413cfeffaf0c841d894390aa8e08.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"IMPORTANT","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/ff0f6d0ad5f4b6211a3f746aaaffd916.jpeg?imageMogr2/quality/60/format/jpg","name":"这些广告超有梗","communityIndex":0,"id":748,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/140/?title=%E6%90%9E%E7%AC%91","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/f787d5053443499e8d787911cd8b3876.jpeg?imageMogr2/quality/100","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/f2b803d3c383bba5a3888b2709160b6e.jpeg?imageMogr2/quality/60/format/jpg","name":"搞笑","communityIndex":0,"id":140,"adTrack":null,"desc":"哈哈哈哈哈哈哈哈","newestEndTime":null},{"actionUrl":"eyepetizer://tag/766/?title=%E8%84%91%E6%B4%9E%E5%B9%BF%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/7c46ad04ff913b87915615c78d226a40.jpeg?imageMogr2/quality/60/format/jpg","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/0d6ab7ed49de67eab89ada4f65353e8c.jpeg?imageMogr2/quality/60/format/jpg","name":"脑洞广告","communityIndex":0,"id":766,"adTrack":null,"desc":null,"newestEndTime":null},{"actionUrl":"eyepetizer://tag/16/?title=%E5%B9%BF%E5%91%8A","childTagList":null,"bgPicture":"http://img.kaiyanapp.com/e41e74fe73882b552de00d95d56748d2.jpeg?imageMogr2/quality/60","haveReward":false,"childTagIdList":null,"tagRecType":"NORMAL","ifNewest":false,"headerImage":"http://img.kaiyanapp.com/3054658dbd559ac42c4c282e9cab7a32.jpeg?imageMogr2/quality/100","name":"广告","communityIndex":0,"id":16,"adTrack":null,"desc":"为广告人的精彩创意点赞","newestEndTime":null}]
* webAdTrack : null
* webUrl : {"forWeibo":"http://www.eyepetizer.net/detail.html?vid=225498","raw":"http://www.eyepetizer.net/detail.html?vid=225498"}
* campaign : null
* idx : 0
* slogan :
* shareAdTrack : null
* releaseTime : 1606839239000
* description : 这是一则来自瑞典智慧财产管理局广告。广告讲述了以「制假买假」的形式向人们展示了不良商家。睁眼瞎牌墨镜,烫头皮直发夹,过敏反应香水,这些名字听了就让人觉得搞笑。From Swedish Intellectual Property Office
* remark : 我就不信,戴墨镜不是为了装
* title : 你一本正经胡说八道卖东西的样子,让我上瘾
* recallSource : null
* duration : 120
* library : DAILY
* descriptionEditor : 这是一则来自瑞典智慧财产管理局广告。广告讲述了以「制假买假」的形式向人们展示了不良商家。睁眼瞎牌墨镜,烫头皮直发夹,过敏反应香水,这些名字听了就让人觉得搞笑。From Swedish Intellectual Property Office
* provider : {"name":"投稿","icon":"","alias":"PGC2"}
* titlePgc :
* adTrack : []
* subtitles : []
* src : null
* searchWeight : 0
* consumption : {"shareCount":7,"replyCount":2,"realCollectionCount":32,"collectionCount":52}
* reallyCollected : false
* label : null
* played : false
* labelList : []
* lastViewTime : null
* playInfo : []
* ifLimitVideo : false
* category : 广告
* thumbPlayUrl :
* resourceType : video
* promotion : null
*/
private long date;
private String brandWebsiteInfo;
private boolean collected;
private String type;
private String favoriteAdTrack;
private String waterMarks;
private String playUrl;
private CoverEntity cover;
private VideoPosterBeanEntity videoPosterBean;
private int id;
private String descriptionPgc;
private String recall_source;
private boolean ad;
private AuthorEntity author;
private String dataType;
private String playlists;
private List<TagsEntity> tags;
private String webAdTrack;
private WebUrlEntity webUrl;
private String campaign;
private int idx;
private String slogan;
private String shareAdTrack;
private long releaseTime;
private String description;
private String remark;
private String title;
private String recallSource;
private int duration;
private String library;
private String descriptionEditor;
private ProviderEntity provider;
private String titlePgc;
private List<?> adTrack;
private List<?> subtitles;
private String src;
private int searchWeight;
private ConsumptionEntity consumption;
private boolean reallyCollected;
private String label;
private boolean played;
private List<?> labelList;
private String lastViewTime;
private List<?> playInfo;
private boolean ifLimitVideo;
private String category;
private String thumbPlayUrl;
private String resourceType;
private String promotion;
public void setDate(long date) {
this.date = date;
}
public void setBrandWebsiteInfo(String brandWebsiteInfo) {
this.brandWebsiteInfo = brandWebsiteInfo;
}
public void setCollected(boolean collected) {
this.collected = collected;
}
public void setType(String type) {
this.type = type;
}
public void setFavoriteAdTrack(String favoriteAdTrack) {
this.favoriteAdTrack = favoriteAdTrack;
}
public void setWaterMarks(String waterMarks) {
this.waterMarks = waterMarks;
}
public void setPlayUrl(String playUrl) {
this.playUrl = playUrl;
}
public void setCover(CoverEntity cover) {
this.cover = cover;
}
public void setVideoPosterBean(VideoPosterBeanEntity videoPosterBean) {
this.videoPosterBean = videoPosterBean;
}
public void setId(int id) {
this.id = id;
}
public void setDescriptionPgc(String descriptionPgc) {
this.descriptionPgc = descriptionPgc;
}
public void setRecall_source(String recall_source) {
this.recall_source = recall_source;
}
public void setAd(boolean ad) {
this.ad = ad;
}
public void setAuthor(AuthorEntity author) {
this.author = author;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public void setPlaylists(String playlists) {
this.playlists = playlists;
}
public void setTags(List<TagsEntity> tags) {
this.tags = tags;
}
public void setWebAdTrack(String webAdTrack) {
this.webAdTrack = webAdTrack;
}
public void setWebUrl(WebUrlEntity webUrl) {
this.webUrl = webUrl;
}
public void setCampaign(String campaign) {
this.campaign = campaign;
}
public void setIdx(int idx) {
this.idx = idx;
}
public void setSlogan(String slogan) {
this.slogan = slogan;
}
public void setShareAdTrack(String shareAdTrack) {
this.shareAdTrack = shareAdTrack;
}
public void setReleaseTime(long releaseTime) {
this.releaseTime = releaseTime;
}
public void setDescription(String description) {
this.description = description;
}
public void setRemark(String remark) {
this.remark = remark;
}
public void setTitle(String title) {
this.title = title;
}
public void setRecallSource(String recallSource) {
this.recallSource = recallSource;
}
public void setDuration(int duration) {
this.duration = duration;
}
public void setLibrary(String library) {
this.library = library;
}
public void setDescriptionEditor(String descriptionEditor) {
this.descriptionEditor = descriptionEditor;
}
public void setProvider(ProviderEntity provider) {
this.provider = provider;
}
public void setTitlePgc(String titlePgc) {
this.titlePgc = titlePgc;
}
public void setAdTrack(List<?> adTrack) {
this.adTrack = adTrack;
}
public void setSubtitles(List<?> subtitles) {
this.subtitles = subtitles;
}
public void setSrc(String src) {
this.src = src;
}
public void setSearchWeight(int searchWeight) {
this.searchWeight = searchWeight;
}
public void setConsumption(ConsumptionEntity consumption) {
this.consumption = consumption;
}
public void setReallyCollected(boolean reallyCollected) {
this.reallyCollected = reallyCollected;
}
public void setLabel(String label) {
this.label = label;
}
public void setPlayed(boolean played) {
this.played = played;
}
public void setLabelList(List<?> labelList) {
this.labelList = labelList;
}
public void setLastViewTime(String lastViewTime) {
this.lastViewTime = lastViewTime;
}
public void setPlayInfo(List<?> playInfo) {
this.playInfo = playInfo;
}
public void setIfLimitVideo(boolean ifLimitVideo) {
this.ifLimitVideo = ifLimitVideo;
}
public void setCategory(String category) {
this.category = category;
}
public void setThumbPlayUrl(String thumbPlayUrl) {
this.thumbPlayUrl = thumbPlayUrl;
}
public void setResourceType(String resourceType) {
this.resourceType = resourceType;
}
public void setPromotion(String promotion) {
this.promotion = promotion;
}
public long getDate() {
return date;
}
public String getBrandWebsiteInfo() {
return brandWebsiteInfo;
}
public boolean isCollected() {
return collected;
}
public String getType() {
return type;
}
public String getFavoriteAdTrack() {
return favoriteAdTrack;
}
public String getWaterMarks() {
return waterMarks;
}
public String getPlayUrl() {
return playUrl;
}
public CoverEntity getCover() {
return cover;
}
public VideoPosterBeanEntity getVideoPosterBean() {
return videoPosterBean;
}
public int getId() {
return id;
}
public String getDescriptionPgc() {
return descriptionPgc;
}
public String getRecall_source() {
return recall_source;
}
public boolean isAd() {
return ad;
}
public AuthorEntity getAuthor() {
return author;
}
public String getDataType() {
return dataType;
}
public String getPlaylists() {
return playlists;
}
public List<TagsEntity> getTags() {
return tags;
}
public String getWebAdTrack() {
return webAdTrack;
}
public WebUrlEntity getWebUrl() {
return webUrl;
}
public String getCampaign() {
return campaign;
}
public int getIdx() {
return idx;
}
public String getSlogan() {
return slogan;
}
public String getShareAdTrack() {
return shareAdTrack;
}
public long getReleaseTime() {
return releaseTime;
}
public String getDescription() {
return description;
}
public String getRemark() {
return remark;
}
public String getTitle() {
return title;
}
public String getRecallSource() {
return recallSource;
}
public int getDuration() {
return duration;
}
public String getLibrary() {
return library;
}
public String getDescriptionEditor() {
return descriptionEditor;
}
public ProviderEntity getProvider() {
return provider;
}
public String getTitlePgc() {
return titlePgc;
}
public List<?> getAdTrack() {
return adTrack;
}
public List<?> getSubtitles() {
return subtitles;
}
public String getSrc() {
return src;
}
public int getSearchWeight() {
return searchWeight;
}
public ConsumptionEntity getConsumption() {
return consumption;
}
public boolean isReallyCollected() {
return reallyCollected;
}
public String getLabel() {
return label;
}
public boolean isPlayed() {
return played;
}
public List<?> getLabelList() {
return labelList;
}
public String getLastViewTime() {
return lastViewTime;
}
public List<?> getPlayInfo() {
return playInfo;
}
public boolean isIfLimitVideo() {
return ifLimitVideo;
}
public String getCategory() {
return category;
}
public String getThumbPlayUrl() {
return thumbPlayUrl;
}
public String getResourceType() {
return resourceType;
}
public String getPromotion() {
return promotion;
}
public class CoverEntity {
/**
* feed : http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageMogr2/quality/60/format/jpg
* detail : http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageMogr2/quality/60/format/jpg
* sharing : null
* blurred : http://img.kaiyanapp.com/1163c79742996c7315be2105b14a1b94.png?imageMogr2/quality/60/format/jpg
* homepage : http://img.kaiyanapp.com/69570ac9d84d2d156c4dada1a757375d.png?imageView2/1/w/720/h/560/format/jpg/q/75|watermark/1/image/aHR0cDovL2ltZy5rYWl5YW5hcHAuY29tL2JsYWNrXzMwLnBuZw==/dissolve/100/gravity/Center/dx/0/dy/0|imageslim
*/
private String feed;
private String detail;
private String sharing;
private String blurred;
private String homepage;
public void setFeed(String feed) {
this.feed = feed;
}
public void setDetail(String detail) {
this.detail = detail;
}
public void setSharing(String sharing) {
this.sharing = sharing;
}
public void setBlurred(String blurred) {
this.blurred = blurred;
}
public void setHomepage(String homepage) {
this.homepage = homepage;
}
public String getFeed() {
return feed;
}
public String getDetail() {
return detail;
}
public String getSharing() {
return sharing;
}
public String getBlurred() {
return blurred;
}
public String getHomepage() {
return homepage;
}
}
public class VideoPosterBeanEntity {
/**
* fileSizeStr : 3.53MB
* scale : 0.725
* url : http://eyepetizer-videos.oss-cn-beijing.aliyuncs.com/video_poster_share/3c6d9321d68a7145f299990fd5648fe4.mp4
*/
private String fileSizeStr;
private double scale;
private String url;
public void setFileSizeStr(String fileSizeStr) {
this.fileSizeStr = fileSizeStr;
}
public void setScale(double scale) {
this.scale = scale;
}
public void setUrl(String url) {
this.url = url;
}
public String getFileSizeStr() {
return fileSizeStr;
}
public double getScale() {
return scale;
}
public String getUrl() {
return url;
}
}
public class AuthorEntity {
/**
* shield : {"itemId":1027,"itemType":"author","shielded":false}
* expert : false
* approvedNotReadyVideoCount : 0
* icon : http://img.kaiyanapp.com/27c223e61df5b647d061e41ee995e8f6.jpeg?imageMogr2/quality/60/format/jpg
* link :
* description : 分享创意广告短视频
* videoNum : 951
* follow : {"itemId":1027,"itemType":"author","followed":false}
* recSort : 0
* name : 这些广告超有梗
* ifPgc : true
* latestReleaseTime : 1606839239000
* id : 1027
* adTrack : null
*/
private ShieldEntity shield;
private boolean expert;
private int approvedNotReadyVideoCount;
private String icon;
private String link;
private String description;
private int videoNum;
private FollowEntity follow;
private int recSort;
private String name;
private boolean ifPgc;
private long latestReleaseTime;
private int id;
private String adTrack;
public void setShield(ShieldEntity shield) {
this.shield = shield;
}
public void setExpert(boolean expert) {
this.expert = expert;
}
public void setApprovedNotReadyVideoCount(int approvedNotReadyVideoCount) {
this.approvedNotReadyVideoCount = approvedNotReadyVideoCount;
}
public void setIcon(String icon) {
this.icon = icon;
}
public void setLink(String link) {
this.link = link;
}
public void setDescription(String description) {
this.description = description;
}
public void setVideoNum(int videoNum) {
this.videoNum = videoNum;
}
public void setFollow(FollowEntity follow) {
this.follow = follow;
}
public void setRecSort(int recSort) {
this.recSort = recSort;
}
public void setName(String name) {
this.name = name;
}
public void setIfPgc(boolean ifPgc) {
this.ifPgc = ifPgc;
}
public void setLatestReleaseTime(long latestReleaseTime) {
this.latestReleaseTime = latestReleaseTime;
}
public void setId(int id) {
this.id = id;
}
public void setAdTrack(String adTrack) {
this.adTrack = adTrack;
}
public ShieldEntity getShield() {
return shield;
}
public boolean isExpert() {
return expert;
}
public int getApprovedNotReadyVideoCount() {
return approvedNotReadyVideoCount;
}
public String getIcon() {
return icon;
}
public String getLink() {
return link;
}
public String getDescription() {
return description;
}
public int getVideoNum() {
return videoNum;
}
public FollowEntity getFollow() {
return follow;
}
public int getRecSort() {
return recSort;
}
public String getName() {
return name;
}
public boolean isIfPgc() {
return ifPgc;
}
public long getLatestReleaseTime() {
return latestReleaseTime;
}
public int getId() {
return id;
}
public String getAdTrack() {
return adTrack;
}
public class ShieldEntity {
/**
* itemId : 1027
* itemType : author
* shielded : false
*/
private int itemId;
private String itemType;
private boolean shielded;
public void setItemId(int itemId) {
this.itemId = itemId;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public void setShielded(boolean shielded) {
this.shielded = shielded;
}
public int getItemId() {
return itemId;
}
public String getItemType() {
return itemType;
}
public boolean isShielded() {
return shielded;
}
}
public class FollowEntity {
/**
* itemId : 1027
* itemType : author
* followed : false
*/
private int itemId;
private String itemType;
private boolean followed;
public void setItemId(int itemId) {
this.itemId = itemId;
}
public void setItemType(String itemType) {
this.itemType = itemType;
}
public void setFollowed(boolean followed) {
this.followed = followed;
}
public int getItemId() {
return itemId;
}
public String getItemType() {
return itemType;
}
public boolean isFollowed() {
return followed;
}
}
}
public class TagsEntity {
/**
* actionUrl : eyepetizer://tag/748/?title=%E8%BF%99%E4%BA%9B%E5%B9%BF%E5%91%8A%E8%B6%85%E6%9C%89%E6%A2%97
* childTagList : null
* bgPicture : http://img.kaiyanapp.com/9056413cfeffaf0c841d894390aa8e08.jpeg?imageMogr2/quality/60/format/jpg
* haveReward : false
* childTagIdList : null
* tagRecType : IMPORTANT
* ifNewest : false
* headerImage : http://img.kaiyanapp.com/ff0f6d0ad5f4b6211a3f746aaaffd916.jpeg?imageMogr2/quality/60/format/jpg
* name : 这些广告超有梗
* communityIndex : 0
* id : 748
* adTrack : null
* desc : null
* newestEndTime : null
*/
private String actionUrl;
private String childTagList;
private String bgPicture;
private boolean haveReward;
private String childTagIdList;
private String tagRecType;
private boolean ifNewest;
private String headerImage;
private String name;
private int communityIndex;
private int id;
private String adTrack;
private String desc;
private String newestEndTime;
public void setActionUrl(String actionUrl) {
this.actionUrl = actionUrl;
}
public void setChildTagList(String childTagList) {
this.childTagList = childTagList;
}
public void setBgPicture(String bgPicture) {
this.bgPicture = bgPicture;
}
public void setHaveReward(boolean haveReward) {
this.haveReward = haveReward;
}
public void setChildTagIdList(String childTagIdList) {
this.childTagIdList = childTagIdList;
}
public void setTagRecType(String tagRecType) {
this.tagRecType = tagRecType;
}
public void setIfNewest(boolean ifNewest) {
this.ifNewest = ifNewest;
}
public void setHeaderImage(String headerImage) {
this.headerImage = headerImage;
}
public void setName(String name) {
this.name = name;
}
public void setCommunityIndex(int communityIndex) {
this.communityIndex = communityIndex;
}
public void setId(int id) {
this.id = id;
}
public void setAdTrack(String adTrack) {
this.adTrack = adTrack;
}
public void setDesc(String desc) {
this.desc = desc;
}
public void setNewestEndTime(String newestEndTime) {
this.newestEndTime = newestEndTime;
}
public String getActionUrl() {
return actionUrl;
}
public String getChildTagList() {
return childTagList;
}
public String getBgPicture() {
return bgPicture;
}
public boolean isHaveReward() {
return haveReward;
}
public String getChildTagIdList() {
return childTagIdList;
}
public String getTagRecType() {
return tagRecType;
}
public boolean isIfNewest() {
return ifNewest;
}
public String getHeaderImage() {
return headerImage;
}
public String getName() {
return name;
}
public int getCommunityIndex() {
return communityIndex;
}
public int getId() {
return id;
}
public String getAdTrack() {
return adTrack;
}
public String getDesc() {
return desc;
}
public String getNewestEndTime() {
return newestEndTime;
}
}
public class WebUrlEntity {
/**
* forWeibo : http://www.eyepetizer.net/detail.html?vid=225498
* raw : http://www.eyepetizer.net/detail.html?vid=225498
*/
private String forWeibo;
private String raw;
public void setForWeibo(String forWeibo) {
this.forWeibo = forWeibo;
}
public void setRaw(String raw) {
this.raw = raw;
}
public String getForWeibo() {
return forWeibo;
}
public String getRaw() {
return raw;
}
}
public class ProviderEntity {
/**
* name : 投稿
* icon :
* alias : PGC2
*/
private String name;
private String icon;
private String alias;
public void setName(String name) {
this.name = name;
}
public void setIcon(String icon) {
this.icon = icon;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getName() {
return name;
}
public String getIcon() {
return icon;
}
public String getAlias() {
return alias;
}
}
public class ConsumptionEntity {
/**
* shareCount : 7
* replyCount : 2
* realCollectionCount : 32
* collectionCount : 52
*/
private int shareCount;
private int replyCount;
private int realCollectionCount;
private int collectionCount;
public void setShareCount(int shareCount) {
this.shareCount = shareCount;
}
public void setReplyCount(int replyCount) {
this.replyCount = replyCount;
}
public void setRealCollectionCount(int realCollectionCount) {
this.realCollectionCount = realCollectionCount;
}
public void setCollectionCount(int collectionCount) {
this.collectionCount = collectionCount;
}
public int getShareCount() {
return shareCount;
}
public int getReplyCount() {
return replyCount;
}
public int getRealCollectionCount() {
return realCollectionCount;
}
public int getCollectionCount() {
return collectionCount;
}
}
}
}
}
| god23bin/RoadOfLearning_Android | SimpleVideo/app/src/main/java/com/bin23/simplevideo/entity/VideoBean.java |
66,051 | package com.example.lenovo.kuaikan.discover;
import java.util.List;
/**
* Created by Zhanglibin on 2017/4/5.
*/
public class BeanRecomm {
/**
* code : 200
* data : {"infos":[{"action_type":0,"item_type":1,"action":"","title":"新版轮播图","banners":[{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":1055,"pic":"http://f2.kkmh.com/image/170406/657xpped6.webp","type":2,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"月令馆","id":1166,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":22526,"pic":"http://f2.kkmh.com/image/170403/ssm8pd6j1.webp","type":3,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"这里有只小鹊仙","id":1152,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":0,"pic":"http://f2.kkmh.com/image/170406/axseq4j4t.webp","type":1,"target_package_name":"","hybrid_url":"","target_web_url":"http://www.kuaikanmanhua.com/gamecenter/game_13.html?v=0405 ","target_title":"龙之谷","id":1167,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":23262,"pic":"http://f2.kkmh.com/image/170331/o6o46784d.webp","type":3,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"愚人节 剧透猜真假","id":1134,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":1013,"pic":"http://f2.kkmh.com/image/170331/42f8ky4v2.webp","type":2,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"天真有邪","id":1127,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":22804,"pic":"http://f2.kkmh.com/image/170329/shc14j2b7.webp","type":3,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"就喜欢你看不惯我又干不掉我的样子","id":1118,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":445,"pic":"http://f2.kkmh.com/image/170327/acyio3h5k.webp","type":2,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"大师兄","id":1096,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":966,"pic":"http://f2.kkmh.com/image/170324/ect8754xa.webp","type":2,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"松松兔","id":1081,"request_id":"1-1491471717776","good_alias":"","chapter_count":9}]},{"action_type":0,"item_type":13,"action":"","title":"排行榜","banners":[{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":0,"pic":"http://f2.kkmh.com/image/161212/6kfvsdwj9.webp","type":18,"target_package_name":"","hybrid_url":"rank-week.html","target_web_url":"http://www.kuaikanmanhua.com/webapp/rank/rank-week.html","target_title":"每周点击排行榜","id":736,"request_id":"-1","good_alias":"","chapter_count":4},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":0,"pic":"http://f2.kkmh.com/image/161212/f14ssn2je.webp","type":18,"target_package_name":"","hybrid_url":"rank-new.html","target_web_url":"http://www.kuaikanmanhua.com/webapp/rank/rank-new.html","target_title":"新作榜","id":738,"request_id":"-1","good_alias":"","chapter_count":4},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":0,"pic":"http://f2.kkmh.com/image/161212/0snhnafbc.webp","type":18,"target_package_name":"","hybrid_url":"rank-over.html","target_web_url":"http://www.kuaikanmanhua.com/webapp/rank/rank-over.html","target_title":"完结榜","id":737,"request_id":"-1","good_alias":"","chapter_count":4},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":2,"pic":"http://f2.kkmh.com/image/161212/z90t6ho93.webp","type":17,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"分类","id":739,"request_id":"-1","good_alias":"","chapter_count":4}]},{"action_type":10,"item_type":14,"more_flag":true,"topics":[{"label_color":"#3750ff","description":"史上第一四海八荒现代都市妖怪新解构大系一本正经的胡说八道脑洞大开子不语怪力乱神但鉴古有志怪发明神道之不诬故知无不语怪医可乱神是也,爱你哟。【授权/每周六更新 责编:Zaku】","target_id":1070,"pic":"http://f2.kkmh.com/image/170331/35lcqfrsi.webp","type":2,"title":"怪医乱神","recommended_text":"跟我一起去寻妖吧!","likes_count":136432,"label_text":"奇幻","comments_count":25534,"label_text_color":"#ffffff","category":["奇幻","爆笑"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170122/haspj22wi.webp-w180.w","grade":1,"nickname":"物语谁说","reg_type":"author","id":31244040},"label_id":25},{"label_color":"#1e4691","description":"深爱的女友惨遭不幸,面对罪犯时,他却因害怕什么都不敢做······受到周遭嘲讽及媒体压迫的他,复仇之心,与日俱增······\r\n","target_id":1060,"pic":"http://f2.kkmh.com/image/170324/p730jq0js.webp","type":2,"title":"蟑螂","recommended_text":"我,绝不做废柴","likes_count":54834,"label_text":"悬疑","comments_count":1355,"label_text_color":"#ffffff","category":["剧情"],"user":{"pub_feed":0,"avatar_url":"","grade":1,"nickname":"Jogeumsan","reg_type":"author","id":37514008},"label_id":32},{"label_color":"#cc6ac7","description":"Z018年,一种可怕的寄生植物迅速席卷了全球各个角落。它们寄生于人体内生长,以人类为养分疯狂繁殖。宿主被吸干后,并不会立刻死亡,而会被寄生植物控所控制!人类不敌,被迫躲入了5座高塔\u2026\u2026【18劲动漫授权/制作人:摩西 更新时间:每周一 周四更新 快看责编:大萌】","target_id":1063,"pic":"http://f2.kkmh.com/image/170330/tlb9yugko.webp","type":2,"title":"寄食者","recommended_text":"寄生植物席卷人类世界!","likes_count":97898,"label_text":"热血","comments_count":2349,"label_text_color":"#ffffff","category":["奇幻","少年"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170117/vh1ttwo02.webp-w180.w","grade":1,"nickname":"18劲动漫","reg_type":"author","id":30629618},"label_id":42},{"label_color":"#6e68ff","description":"灾难题材漫画!倾城大雨,导致城市被淹。一夜之间,全城的鱼类竟然全部都异变成了吃人怪?在这场灾难中的幸存者生命岌岌可危,是否真的有人可以逃出这座城市?【独家/每周一,周五更新 责编:半石】","target_id":1045,"pic":"http://f2.kkmh.com/image/170320/on3ece0hb.webp","type":2,"title":"鱼变","recommended_text":"鱼怪围城,绝命逃亡","likes_count":1352847,"label_text":"剧情","comments_count":41884,"label_text_color":"#ffffff","category":["剧情"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170302/bwl5fuhcg.webp-w180.w","grade":1,"nickname":"小策君","reg_type":"author","id":36409899},"label_id":17}],"guide_text":"","action":"topic_new/discovery_module_list/213","style":1,"title":"极致少年漫"},{"action_type":0,"item_type":7,"action":"","title":"0211电商活动","banners":[{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":0,"pic":"http://f2.kkmh.com/image/170405/7rgonoq97.webp","type":1,"target_package_name":"","hybrid_url":"","target_web_url":"http://app.kkmh.com/iosoran0405","target_title":"","id":1119,"request_id":"-1","good_alias":"","chapter_count":1}]},{"action_type":10,"item_type":3,"more_flag":true,"topics":[{"label_color":"#ff7300","description":"患有中二病的逍遥门大师兄,带领着门下师弟师妹降妖除魔,修炼成仙的爆笑日常合集!超级下饭哦!【每周六更新 责编:凹凸慢】","target_id":445,"pic":"http://f2.kkmh.com/image/150806/s9sq4o31n.jpg","type":2,"title":"我家大师兄脑子有坑","recommended_text":"搞笑 修仙 剧情","likes_count":0,"label_text":"爆笑","comments_count":0,"label_text_color":"#ffffff","category":["奇幻","爆笑"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/150707/5tmlijkd0.jpg-w180.webp","grade":1,"nickname":"剧象漫画","reg_type":"author","id":1059889},"label_id":5},{"label_color":"#ff7300","description":"白领解压必备!神经病的画风,神经病的反转结局,你绝对会爱上这部作品!\r\n\r\n【独家/连载中 责编:牛奶】\r\n\r\n","target_id":121,"pic":"http://f2.kkmh.com/image/150609/cwb7j0zxk.jpg","type":2,"title":"正港奇片漫画","recommended_text":"神经病 搞笑 反转","likes_count":0,"label_text":"爆笑","comments_count":0,"label_text_color":"#ffffff","category":["爆笑"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/150423/drwux4bsf.jpg-w180.webp","grade":1,"nickname":"正港奇片","reg_type":"weibo","id":46},"label_id":5},{"label_color":"#ff7300","description":"超人气偶像尹深,经常因为\u201c脑残\u201d行为在网络上招黑,智商常年不在线,犯着各种蠢萌的小错,粉丝却越来越多\u2026\u2026人气偶像、明星组合、新人团体、各色娱乐圈人物纷纷登场,讲述偶像们爆笑逗比的日常与进阶之路!【授权/每周五更新 责编:大萌】","target_id":523,"pic":"http://f2.kkmh.com/image/161220/ozfo5e0bo.webp","type":2,"title":"头条都是他","recommended_text":"装逼 偶像 搞笑","likes_count":0,"label_text":"爆笑","comments_count":0,"label_text_color":"#ffffff","category":["日常","爆笑"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/150829/9rjo49xh8.jpg-w180.webp","grade":1,"nickname":"幽·灵(良筑良作)","reg_type":"weibo","id":31},"label_id":5}],"guide_text":"","action":"topic_new/discovery_module_list/216","style":2,"title":"轻松欢乐逗"},{"action_type":10,"item_type":14,"more_flag":true,"topics":[{"label_color":"#ff73b9","description":"少女与\u201c少女\u201d的羁绊,涤荡心灵的日常与\u201c非日常\u201d。【作者:日更计划/叽菇 作品责编:杰罗 日更计划授权/每月1日、11日、21日更新 快看漫画责编:漠漠】","target_id":996,"pic":"http://f2.kkmh.com/image/170103/7vec6ibok.webp","type":2,"title":"少女消失之前","recommended_text":"少女与\u201c少女\u201d的羁绊","likes_count":334828,"label_text":"百合","comments_count":6508,"label_text_color":"#ffffff","category":["奇幻","百合"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/161229/52ju2701z.webp-w180.w","grade":1,"nickname":"日更计划","reg_type":"author","id":28963270},"label_id":30},{"label_color":"#ff73b9","description":"重逢的两人身体交换,小心翼翼守护着秘密的同时,也查询着曾经不解的事情的真相\u2026\u2026【完结,责编:哑铃lynn】","target_id":788,"pic":"http://f2.kkmh.com/image/170105/x52v6pq11.webp","type":2,"title":"百合零距离","recommended_text":"互换身体,守护彼此的秘密","likes_count":3538224,"label_text":"百合","comments_count":64824,"label_text_color":"#ffffff","category":["完结","百合"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/160428/xizmge36y.webp-w180.w","grade":1,"nickname":"吉太","reg_type":"author","id":8735383},"label_id":30},{"label_color":"#ff7300","description":"生活在你我身边的萌娘 不管你有没有发现 但是她们已经在入侵你们的世界了!【出品:微漫画,总监制:天空,编绘:萌尽,制作人:古吉 不定期更新 责编:zaku】","target_id":670,"pic":"http://f2.kkmh.com/image/151231/hlmop1ofh.webp","type":2,"title":"萌尽的萌娘","recommended_text":"万物皆可萌,万物皆是女朋友!","likes_count":2042051,"label_text":"爆笑","comments_count":34499,"label_text_color":"#ffffff","category":["爆笑"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/151230/vqrie5we9.webp-w180.w","grade":1,"nickname":"微漫画合集","reg_type":"author","id":5574462},"label_id":5},{"label_color":"#b400fa","description":"给你1000万,换你的女朋友!你会愿意吗?纯真少女惨被欠债男友出卖,沦为总裁的玩物,身体与灵魂的全面沦陷,情欲都市的十字路口,她又该何去何从呢?\r\n《密会情人》漫画作者---柯小最新力作,灵与肉交织的虐爱狂想曲,2月2日,准点上架。\r\n【独家/双周更 责编:吴半石】","target_id":1017,"pic":"http://f2.kkmh.com/image/170216/08iair7wp.webp","type":2,"title":"恶魔式情调","recommended_text":"被男友出卖,又遇恶魔总裁?","likes_count":3489588,"label_text":"都市","comments_count":174101,"label_text_color":"#ffffff","category":["都市"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/160616/81rwrli9c.webp-w180.w","grade":1,"nickname":"柯小","reg_type":"author","id":14776286},"label_id":11}],"guide_text":"","action":"topic_new/discovery_module_list/215","style":2,"title":"男生福利站"},{"action_type":10,"item_type":15,"more_flag":true,"topics":[{"label_color":"#1e4691","description":"在百年鬼宅里拍摄还原鬼宅历史的电影是什么体验?!少女金小伊随着剧组入住这座神秘的月令馆后,一系列剧本之外的灵异事件竟陆续发生!黑夜已经到来,在历史中模糊了的悲剧,正在古宅真实重演!【独家/每周一更新 责编:33】","target_id":1055,"pic":"http://f2.kkmh.com/image/170317/u7vfbkarg.webp","type":2,"title":"月令馆神秘事件","recommended_text":"古宅里的历史悲剧,再次上演","likes_count":0,"label_text":"悬疑","comments_count":0,"label_text_color":"#ffffff","category":["剧情","灵异"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170317/mauf4ammw.webp-w180.w","grade":1,"nickname":"Maharo/Daum webtoon","reg_type":"author","id":37132892},"label_id":32},{"label_color":"#1e4691","description":"她出现之处,定有该死之人。传言只要她跟你说话或对你做奇怪的动作,不久后那个人就会必死无疑\u2026\u2026环环相扣的反转剧情,绝对让你忍不住去看下去!【独家/每周六更新 责编:33】","target_id":698,"pic":"http://f2.kkmh.com/image/170117/y8b04anfg.webp","type":2,"title":"西街44号","recommended_text":"世间本无地狱,地狱自在人心","likes_count":0,"label_text":"悬疑","comments_count":0,"label_text_color":"#ffffff","category":["灵异"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/160127/tkk3z2hmq.webp-w180.w","grade":1,"nickname":"笑水轩动漫","reg_type":"author","id":2914040},"label_id":32},{"label_color":"#5397d6","description":"短篇合集,讲述一场自来水污染导致人类出现的奇奇怪怪的疾病。细思极恐,高能慎入!看作者的脑洞能有多大!【责编:拉面】","target_id":699,"pic":"http://f2.kkmh.com/image/170122/zbyfi7n6d.webp","type":2,"title":"自来水之污","recommended_text":"细思极恐的故事在此集结","likes_count":0,"label_text":"脑洞","comments_count":0,"label_text_color":"#ffffff","category":["灵异"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/160530/744atwg2u.webp-w180.w","grade":1,"nickname":"潇潇潇潇如","reg_type":"author","id":6021212},"label_id":26}],"guide_text":"","action":"topic_new/discovery_module_list/157","style":2,"title":"烧脑故事"},{"action_type":10,"item_type":14,"more_flag":true,"topics":[{"label_color":"#6e68ff","description":"出轨俱乐部,人们在这里互相掩护偷情、共享伴侣。作品思想前卫大胆,家暴、婚内出轨、开放式婚姻...紧张刺激又不断反转的剧情让人欲罢不能!一辈子这么长,你会只爱一个人么?全平台关注量TOP3热作!2016年度掀起前所未有的超火爆讨论度,不可错过的伦理大作!\r\n 【第一季完结 责编:半石】","target_id":782,"pic":"http://f2.kkmh.com/image/170104/gio7ngxkf.webp","type":2,"title":"密会情人\u2014\u2014出轨俱乐部","recommended_text":"如果出轨成为一种习惯....","likes_count":51106979,"label_text":"剧情","comments_count":1220314,"label_text_color":"#ffffff","category":["成人","都市"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/160425/yaac9x7b3.webp-w180.w","grade":1,"nickname":"柯小(主笔)+快看漫画团队","reg_type":"author","id":10881293},"label_id":17},{"label_color":"#3750ff","description":"一场人为的高考成绩替换,两个女孩的命运彻底反转!十六年后,成绩垫底的她成为了受人尊敬的教师,成绩优异的她却成为社会底层的loser!悲惨大妈重返高三化身漂亮御姐,决意扭转被替换的人生【独家/完结 责编:哑铃lynn】","target_id":804,"pic":"http://f2.kkmh.com/image/160519/rnockahwm.webp","type":2,"title":"被替换的人生","recommended_text":"化身御姐,悲惨大妈重返高三","likes_count":4969315,"label_text":"奇幻","comments_count":112666,"label_text_color":"#ffffff","category":["奇幻","完结"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/160519/t7c00kaf0.webp-w180.w","grade":1,"nickname":"handsome king&快看漫画","reg_type":"author","id":12805361},"label_id":25},{"label_color":"#6e68ff","description":"快看总榜热度第一名!现象级超经典作品,在整容游戏App上美化自己的照片,现实中脸就会跟着变美!但每一次改变都要付出相应的代价,可能会伤害你的朋友、恋人、家人!这样的App你愿意使用吗?连载一年长期霸榜TOP3,亿万超火爆热度,新人必看! \r\n【独家/第一季完结 责编:33 】","target_id":544,"pic":"http://f2.kkmh.com/image/160808/18g8lnopi.webp","type":2,"title":"整容游戏","recommended_text":"为了变美,你愿意付出什么?","likes_count":30810292,"label_text":"剧情","comments_count":1832461,"label_text_color":"#ffffff","category":["奇幻","完结"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/150918/jdla02iby.jpg-w180.webp","grade":1,"nickname":"金丘","reg_type":"author","id":2967943},"label_id":17},{"label_color":"#3750ff","description":"花花公子遭受爱情诅咒,每晚7点都要变成小孩子?偶然遇到的失忆少女也有这种情况?如何才能解除诅咒呢?看两人联手找到诅咒原因!【独家,完结/责编:Zaku】\r\n","target_id":888,"pic":"http://f2.kkmh.com/image/160801/8yh7ubse3.webp","type":2,"title":"计时7点","recommended_text":"身体变小,头脑还是花花公子!","likes_count":3966084,"label_text":"奇幻","comments_count":44020,"label_text_color":"#ffffff","category":["奇幻","剧情"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/160801/1844k4iq7.webp-w180.w","grade":1,"nickname":" KOOM","reg_type":"author","id":19436620},"label_id":25}],"guide_text":"","action":"topic_new/discovery_module_list/190","style":2,"title":"情感都市"},{"action_type":10,"item_type":4,"more_flag":true,"topics":[{"label_color":"#3750ff","description":"千年树妖裟椤独自活到现世,成了\u201c不停\u201d甜品店的老板娘。她的店里会来很多奇怪的客人,每个客人都会喝她的浮生茶,给她说一个自己的故事,那是妖怪们荡气回肠的爱恨情仇\u2026\u2026【授权/每周五更新 责编:凹凸慢】\r\n ","target_id":745,"pic":"http://f2.kkmh.com/image/161214/n0ciklmyn.webp","type":2,"title":"浮生物语","recommended_text":"治愈 古风 神话","likes_count":0,"label_text":"奇幻","comments_count":0,"label_text_color":"#ffffff","category":["奇幻","古风"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/160608/sjete42dz.webp-w180.w","grade":1,"nickname":"元气工场","reg_type":"author","id":14113284},"label_id":25},{"label_color":"#f05523","description":"虐心宫廷复仇大作!深闺中不谙世事的少女,被凶残暴戾的皇帝带入后宫。与深宫中的女人们明争暗斗,历经九死一生,最终蜕变成掌权女皇!【独家/每周二更新,责编:牛奶】","target_id":940,"pic":"http://f2.kkmh.com/image/170122/b3u82uzhp.webp","type":2,"title":"芍药挽歌·冰霜花","recommended_text":"宫斗 古风 阴谋","likes_count":0,"label_text":"宫斗","comments_count":0,"label_text_color":"#ffffff","category":["古风"],"user":{"pub_feed":0,"avatar_url":"","grade":1,"nickname":"隼艺 / Daum Webtoon","reg_type":"author","id":23835673},"label_id":37},{"label_color":"#6e68ff","description":"绝美桃花妖痴心守护小萝莉,人妖殊途,两人历经磨难。由一段剪不断理还乱的暧昧感情,引出了关于医术、爱情、友情以及前世今生的旷世奇缘!【独家/每周四更新,责编:Zaku】","target_id":785,"pic":"http://f2.kkmh.com/image/161220/meiczq4h1.webp","type":2,"title":"桃花灼","recommended_text":"百合 妖怪 恋情","likes_count":0,"label_text":"剧情","comments_count":0,"label_text_color":"#ffffff","category":["古风","百合"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/160816/gjgohgk8x.webp-w180.w","grade":1,"nickname":"星空社","reg_type":"author","id":10978521},"label_id":17},{"label_color":"#ffaf14","description":"聪慧霸气的掌门之女,青楼偶遇潇洒爱撩的名门公子,本以为是良缘缔结,却不想是孽缘交织······此情应是长相守,你若无\u201c情\u201d我便休。爆笑与虐心并存的古风恋爱,画风超唯美!【独家/每周六更新 责编:半石】","target_id":927,"pic":"http://f2.kkmh.com/image/161220/0347s8oiy.webp","type":2,"title":"盛世清曲","recommended_text":"武侠 恋爱 恩仇","likes_count":0,"label_text":"励志","comments_count":0,"label_text_color":"#ffffff","category":["古风"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170109/abo05u7cc.webp-w180.w","grade":1,"nickname":"小球(主笔)+快看漫画团队","reg_type":"author","id":29971071},"label_id":39},{"label_color":"#6e68ff","description":"惨遭灭门的习武女医师,偶遇撩人的文弱小书生,一同追凶的途中爱恋萌发。水墨渲染的绝美画风,高甜高虐的古风恋爱!【独家/每周四更新 责编:林早上】","target_id":924,"pic":"http://f2.kkmh.com/image/161220/b07zecf0l.webp","type":2,"title":"远山千霖","recommended_text":"复仇 江湖 爱情","likes_count":0,"label_text":"剧情","comments_count":0,"label_text_color":"#ffffff","category":["剧情","古风"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/150421/sb1j0bq5k.jpg-w180.webp","grade":1,"nickname":"宣哲","reg_type":"weibo","id":9},"label_id":17},{"label_color":"#f05523","description":"云剑山庄的大小姐陆望心与皇子夏侯佑相爱,并以身相许,不料,登基后的夏侯佑竟把陆望心打入冷宫,并满门抄斩,绝望的陆望心却意外穿越回16岁,重获新生的陆望心从此踏上了复仇之路\u2026\u2026【独家/每周五更新 责编:33】","target_id":834,"pic":"http://f2.kkmh.com/image/161220/3312n1ujs.webp","type":2,"title":"君与望心","recommended_text":"恋爱 复仇 武侠","likes_count":0,"label_text":"宫斗","comments_count":0,"label_text_color":"#ffffff","category":["恋爱","古风"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/160526/tftou7pvt.webp-w180.w","grade":1,"nickname":"左小翎/夏天岛+大仙/夏天岛","reg_type":"author","id":13219143},"label_id":37}],"guide_text":"","action":"topic_new/discovery_module_list/147","style":2,"title":"古风侠情"},{"action_type":10,"item_type":4,"more_flag":true,"topics":[{"label_color":"#10beaa","description":"因特殊原因,江雪从小到大就不停地转校读书。这一年夏天,他遇到了改变她的男主角夏至,同时也遇到了对她一往情深的石海天。一个关于青春、梦想、篮球的故事开始了。【独家/完结,责编:哑铃】","target_id":953,"pic":"http://f2.kkmh.com/image/161223/qqz4onflu.webp","type":2,"title":"青空之夏","recommended_text":"篮球 梦想 恋爱","likes_count":0,"label_text":"青春","comments_count":0,"label_text_color":"#ffffff","category":["恋爱","校园"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/160229/rahxbk9g8.webp-w180.w","grade":1,"nickname":"北巷","reg_type":"author","id":3182172},"label_id":41},{"label_color":"#ff7300","description":"一对面瘫兄妹的变装日常。男子力爆表的霸道妹妹,和少女心满满的女装癖哥哥,这对互换兄妹身份毫无压力的双胞胎,会有怎样默契和搞笑的日常?【独家/完结 责编:Nico】","target_id":368,"pic":"http://f2.kkmh.com/image/161222/mpcfv91js.webp","type":2,"title":"变装兄妹","recommended_text":"兄妹 变装 爆笑","likes_count":0,"label_text":"爆笑","comments_count":0,"label_text_color":"#ffffff","category":["日常","完结"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/150707/dux1ctqhq.jpg-w180.webp","grade":1,"nickname":"毛虫","reg_type":"author","id":1062227},"label_id":5},{"label_color":"#fa6499","description":"曾获得第十届金龙奖幽默漫画奖,伟大的安妮成名作。根据安妮和其男友王小明从相识到相爱的一系列真人真事改编。当女神经病遇上冷酷死鱼眼的男主,会产生什么样的化学物质?!绝对爆笑的治愈系漫画,最无节操的恋爱指南!【独家/第二季完结】","target_id":8,"pic":"http://f2.kkmh.com/image/161212/xexop46qw.webp","type":2,"title":"安妮和王小明","recommended_text":"日常 搞笑 爱情","likes_count":0,"label_text":"恋爱","comments_count":0,"label_text_color":"#ffffff","category":["日常","恋爱"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/150421/vly25fgfb.jpg-w180.webp","grade":1,"nickname":"伟大的安妮","reg_type":"weibo","id":16},"label_id":15},{"label_color":"#ff7300","description":"超级怕鬼却要去当阎王是一种怎样的体验?使徒子全新搞怪力作,跟着胆小的阎王丫头,与各界神魔鬼怪过招。一惊一乍地练胆,还能爆笑不止,这部绝对能满足你!【授权/完结 责编:牛奶】\r\n","target_id":848,"pic":"http://f2.kkmh.com/image/170122/8afic3cwt.webp","type":2,"title":"阎王不高兴","recommended_text":"使徒子 女阎王 爆笑","likes_count":0,"label_text":"爆笑","comments_count":0,"label_text_color":"#ffffff","category":["爆笑","完结"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/150421/i26y7dz2t.jpg-w180.webp","grade":1,"nickname":"使徒子","reg_type":"weibo","id":6},"label_id":5},{"label_color":"#1e4691","description":"黑暗小巷的尽头,有一家生意冷淡的照明商店,每天都有奇怪的人进出。老板对于他们的来访一点都不惊讶,却警告一个常来店里买灯泡的女孩,小心那些奇怪的人······这些人身上到底发生了什么?【完结/独家 责编:吴半石】","target_id":1004,"pic":"http://f2.kkmh.com/image/170123/sziw811d3.webp","type":2,"title":"照明商店","recommended_text":"恐怖 悬疑 感动","likes_count":0,"label_text":"悬疑","comments_count":0,"label_text_color":"#ffffff","category":["灵异"],"user":{"pub_feed":0,"avatar_url":"","grade":1,"nickname":"姜草/Daum Webtoon","reg_type":"author","id":30271902},"label_id":32},{"label_color":"#6e68ff","description":"大龄丑男一觉醒来,竟变火辣美女,这真的不是做梦吗?虽说有些小羞耻,但终于能抛弃不堪的过往,开始全新的人生!【美蓝漫画授权/完结】","target_id":318,"pic":"http://f2.kkmh.com/image/170210/pfahorv31.webp","type":2,"title":"丑男变美女","recommended_text":"性转 福利 宅男","likes_count":0,"label_text":"剧情","comments_count":0,"label_text_color":"#ffffff","category":["恋爱","完结"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/150521/dxmcha507.jpg-w180.webp","grade":1,"nickname":"美蓝漫画","reg_type":"author","id":565296},"label_id":17}],"guide_text":"","action":"topic_new/discovery_module_list/130","style":2,"title":"完结佳作"},{"action_type":10,"item_type":17,"more_flag":true,"topics":[{"label_color":"#3750ff","description":"你相信世界上有这么一种能力吗?只要点击手机上的\u201c反转\u201d按钮,就可以改变别人的人生,然而代价却是\u2026\u2026当女主播何希得到了这颗夏娃的苹果时,等待她的究竟是重生还是毁灭?【独家/每周日更新 责编:半石】","target_id":1015,"pic":"http://f2.kkmh.com/image/170123/iulm17nwf.webp","type":2,"title":"反转现实","recommended_text":"改变人生的机会,这次你会用什么代价来交换?","likes_count":3641559,"label_text":"奇幻","comments_count":50455,"label_text_color":"#ffffff","category":["奇幻","都市"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170123/gqobgrx6m.webp-w180.w","grade":1,"nickname":"天极焉加+快看漫画团队","reg_type":"author","id":31447947},"label_id":25},{"label_color":"#3750ff","description":"弱者顺应命运,强者操控命运。叶继铭从高高在上的跨国企业总裁一下子变成了露宿街头的流浪汉,面对未婚妻和好友的背叛,他面临人生的重大抉择。【独家/每周三更新 责编:Zaku】","target_id":1025,"pic":"http://f2.kkmh.com/image/170203/epijwnqh2.webp","type":2,"title":"命理师","recommended_text":"早知我是大天狗,还当什么CEO?","likes_count":625933,"label_text":"奇幻","comments_count":8997,"label_text_color":"#ffffff","category":["奇幻","少年"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170124/hxc12a8vs.webp-w180.w","grade":1,"nickname":" 上官画蓉","reg_type":"author","id":31541018},"label_id":25},{"label_color":"#3750ff","description":"魔都是一个物欲横流,光怪陆离的超级都市,在这里,充斥着形形色色的人,除了人,还有各色奇异的生物也都伪装其中,他们在这座不夜城,每天都上演着神奇诡异的的故事,也许下一刻,它就在你身边发生。【独家/每周三更新 责编:Zaku】","target_id":1024,"pic":"http://f2.kkmh.com/image/170125/ul4gfzp8s.webp","type":2,"title":"魔都诡事","recommended_text":"你敢在魔都的夜晚独自前行吗?","likes_count":1914657,"label_text":"奇幻","comments_count":28701,"label_text_color":"#ffffff","category":["奇幻"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170124/x2reh5pbd.webp-w180.w","grade":1,"nickname":"红石/漫采文化","reg_type":"author","id":31540596},"label_id":25}],"guide_text":"","action":"topic_new/discovery_module_list/204","style":2,"title":"帮你找漫画"},{"action_type":10,"item_type":4,"more_flag":true,"topics":[{"label_color":"#fa6499","description":"身高180+的软妹恋上169的冰山总裁。谁说女追男隔层纱?女巨人的甜虐追爱史,扑倒冰山总裁不是梦!独特的设定,和其他充满套路的总裁漫不一样,看完第一话就停不下来!都市浪漫轻喜剧神作!【独家/每周六更新 责编:M】","target_id":835,"pic":"http://f2.kkmh.com/image/161220/pyx64xw5p.webp","type":2,"title":"女巨人也要谈恋爱","recommended_text":"身高差 搞笑 恋爱","likes_count":0,"label_text":"恋爱","comments_count":0,"label_text_color":"#ffffff","category":["恋爱","剧情"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/160526/qc9qlzmdl.webp-w180.w","grade":1,"nickname":"清英","reg_type":"author","id":13230382},"label_id":15},{"label_color":"#b400fa","description":"关于职场的都市浪漫故事,萧艾艾醉酒后意外与高中学生会长\u201c同床共枕\u201d,而他竟是公司总裁,暗中帮助职场中屡屡受挫的她。腹黑霸道总裁与倔强单纯女职员,职场与情场波折却浪漫的故事。【独家/每周四更新 责编:林早上】","target_id":869,"pic":"http://f2.kkmh.com/image/161220/7mgt7gpdl.webp","type":2,"title":"与爱有关","recommended_text":"霸道总裁 恋爱 狗血","likes_count":0,"label_text":"都市","comments_count":0,"label_text_color":"#ffffff","category":["恋爱","剧情"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/150713/wmvmn02ny.jpg-w180.webp","grade":1,"nickname":"空枣","reg_type":"author","id":1085041},"label_id":11},{"label_color":"#ff7300","description":"女主是金刚芭比,浑身长满肌肉,却有着天使脸庞和柔弱的少女情怀。完全颠覆所有传统少女漫!肌肉女倒追高冷男神,各种梗都令人喷饭!如果你想找一部既可以看帅哥,又让你笑到停不下来的漫画,请一定要看哦!!\r\n【独家/每周四更新 责编:思宇 】","target_id":554,"pic":"http://f2.kkmh.com/image/161220/fb3316jil.webp","type":2,"title":"你好!!筋肉女","recommended_text":"女汉子 搞笑 恋爱","likes_count":0,"label_text":"爆笑","comments_count":0,"label_text_color":"#ffffff","category":["爆笑"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/160803/emiox3v5r.webp-w180.w","grade":1,"nickname":"天极焉加","reg_type":"author","id":3117656},"label_id":5},{"label_color":"#bbc23a","description":"高富帅暖男捡到只性别不明的软萌小狐狸。成年后,小狐狸为爱变身亭亭玉立的少女与他再续前缘。绝对萌翻你的治愈养成系,超甜!超萌!超虐狗!【独家/每周一更新 责编:33】","target_id":711,"pic":"http://f2.kkmh.com/image/161212/p7p48tawz.webp","type":2,"title":"捡到只小狐狸","recommended_text":"萝莉 狐妖 爱情","likes_count":0,"label_text":"治愈","comments_count":0,"label_text_color":"#ffffff","category":["恋爱","奇幻"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/160203/sz37z2mh6.webp-w180.w","grade":1,"nickname":"通幽/夏天岛+叨叨君/夏天岛","reg_type":"author","id":6957622},"label_id":23},{"label_color":"#fa6499","description":"武力值MAX的道场继承人\u2014\u2014向小满,为了追男神,决定江湖洗手,转校做一个安安静静的柔弱女子。而未曾想到的是,踏入校园第一天,男神还没追到,却因超凡的战斗力,被学校不良少年误认为男神。究竟小满能否成为男神心中的理想型,顺利转变现有的画风呢?【独家/每周四更新 责编:33】","target_id":991,"pic":"http://f2.kkmh.com/image/161226/th1gzi9gn.webp","type":2,"title":"当校霸爱上学霸","recommended_text":"恋爱 校园 女扮男装","likes_count":0,"label_text":"恋爱","comments_count":0,"label_text_color":"#ffffff","category":["恋爱","校园"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/161226/qcezbh4i7.webp-w180.w","grade":1,"nickname":"灿灿 /夏天岛","reg_type":"author","id":28863310},"label_id":15},{"label_color":"#fa6499","description":"少女蔚莱无意中捡到了一台可以拍摄到未来的神秘相机,却发现只对暗恋的学长有作用,\u201c你的未来里,会有我吗?\u201d少女这样想着,举起了相机\u2026\u2026【独家/每周六更新 责编:33】","target_id":932,"pic":"http://f2.kkmh.com/image/161212/efivog5dg.webp","type":2,"title":"也许,未来","recommended_text":"穿越 爱情 剧情","likes_count":0,"label_text":"恋爱","comments_count":0,"label_text_color":"#ffffff","category":["恋爱","奇幻","校园"],"user":{"pub_feed":1,"avatar_url":"http://f2.kkmh.com/image/150421/05zf9r5db.jpg-w180.webp","grade":1,"nickname":"bless","reg_type":"weibo","id":102033},"label_id":15}],"guide_text":"","action":"topic_new/discovery_module_list/129","style":2,"title":"在这秀恩爱"}]}
* message : ok
*/
private int code;
private DataBean data;
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public static class DataBean {
private List<InfosBean> infos;
public List<InfosBean> getInfos() {
return infos;
}
public void setInfos(List<InfosBean> infos) {
this.infos = infos;
}
public static class InfosBean {
/**
* action_type : 0
* item_type : 1
* action :
* title : 新版轮播图
* banners : [{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":1055,"pic":"http://f2.kkmh.com/image/170406/657xpped6.webp","type":2,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"月令馆","id":1166,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":22526,"pic":"http://f2.kkmh.com/image/170403/ssm8pd6j1.webp","type":3,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"这里有只小鹊仙","id":1152,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":0,"pic":"http://f2.kkmh.com/image/170406/axseq4j4t.webp","type":1,"target_package_name":"","hybrid_url":"","target_web_url":"http://www.kuaikanmanhua.com/gamecenter/game_13.html?v=0405 ","target_title":"龙之谷","id":1167,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":23262,"pic":"http://f2.kkmh.com/image/170331/o6o46784d.webp","type":3,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"愚人节 剧透猜真假","id":1134,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":1013,"pic":"http://f2.kkmh.com/image/170331/42f8ky4v2.webp","type":2,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"天真有邪","id":1127,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":22804,"pic":"http://f2.kkmh.com/image/170329/shc14j2b7.webp","type":3,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"就喜欢你看不惯我又干不掉我的样子","id":1118,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":445,"pic":"http://f2.kkmh.com/image/170327/acyio3h5k.webp","type":2,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"大师兄","id":1096,"request_id":"1-1491471717776","good_alias":"","chapter_count":9},{"target_app_url":"","good_price":"","sub_title":"","special_list_url":"","target_id":966,"pic":"http://f2.kkmh.com/image/170324/ect8754xa.webp","type":2,"target_package_name":"","hybrid_url":"","target_web_url":"","target_title":"松松兔","id":1081,"request_id":"1-1491471717776","good_alias":"","chapter_count":9}]
* more_flag : true
* topics : [{"label_color":"#3750ff","description":"史上第一四海八荒现代都市妖怪新解构大系一本正经的胡说八道脑洞大开子不语怪力乱神但鉴古有志怪发明神道之不诬故知无不语怪医可乱神是也,爱你哟。【授权/每周六更新 责编:Zaku】","target_id":1070,"pic":"http://f2.kkmh.com/image/170331/35lcqfrsi.webp","type":2,"title":"怪医乱神","recommended_text":"跟我一起去寻妖吧!","likes_count":136432,"label_text":"奇幻","comments_count":25534,"label_text_color":"#ffffff","category":["奇幻","爆笑"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170122/haspj22wi.webp-w180.w","grade":1,"nickname":"物语谁说","reg_type":"author","id":31244040},"label_id":25},{"label_color":"#1e4691","description":"深爱的女友惨遭不幸,面对罪犯时,他却因害怕什么都不敢做······受到周遭嘲讽及媒体压迫的他,复仇之心,与日俱增······\r\n","target_id":1060,"pic":"http://f2.kkmh.com/image/170324/p730jq0js.webp","type":2,"title":"蟑螂","recommended_text":"我,绝不做废柴","likes_count":54834,"label_text":"悬疑","comments_count":1355,"label_text_color":"#ffffff","category":["剧情"],"user":{"pub_feed":0,"avatar_url":"","grade":1,"nickname":"Jogeumsan","reg_type":"author","id":37514008},"label_id":32},{"label_color":"#cc6ac7","description":"Z018年,一种可怕的寄生植物迅速席卷了全球各个角落。它们寄生于人体内生长,以人类为养分疯狂繁殖。宿主被吸干后,并不会立刻死亡,而会被寄生植物控所控制!人类不敌,被迫躲入了5座高塔\u2026\u2026【18劲动漫授权/制作人:摩西 更新时间:每周一 周四更新 快看责编:大萌】","target_id":1063,"pic":"http://f2.kkmh.com/image/170330/tlb9yugko.webp","type":2,"title":"寄食者","recommended_text":"寄生植物席卷人类世界!","likes_count":97898,"label_text":"热血","comments_count":2349,"label_text_color":"#ffffff","category":["奇幻","少年"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170117/vh1ttwo02.webp-w180.w","grade":1,"nickname":"18劲动漫","reg_type":"author","id":30629618},"label_id":42},{"label_color":"#6e68ff","description":"灾难题材漫画!倾城大雨,导致城市被淹。一夜之间,全城的鱼类竟然全部都异变成了吃人怪?在这场灾难中的幸存者生命岌岌可危,是否真的有人可以逃出这座城市?【独家/每周一,周五更新 责编:半石】","target_id":1045,"pic":"http://f2.kkmh.com/image/170320/on3ece0hb.webp","type":2,"title":"鱼变","recommended_text":"鱼怪围城,绝命逃亡","likes_count":1352847,"label_text":"剧情","comments_count":41884,"label_text_color":"#ffffff","category":["剧情"],"user":{"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170302/bwl5fuhcg.webp-w180.w","grade":1,"nickname":"小策君","reg_type":"author","id":36409899},"label_id":17}]
* guide_text :
* style : 1
*/
private int action_type;
private int item_type;
private String action;
private String title;
private boolean more_flag;
private String guide_text;
private int style;
private List<BannersBean> banners;
private List<TopicsBean> topics;
public int getAction_type() {
return action_type;
}
public void setAction_type(int action_type) {
this.action_type = action_type;
}
public int getItem_type() {
return item_type;
}
public void setItem_type(int item_type) {
this.item_type = item_type;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isMore_flag() {
return more_flag;
}
public void setMore_flag(boolean more_flag) {
this.more_flag = more_flag;
}
public String getGuide_text() {
return guide_text;
}
public void setGuide_text(String guide_text) {
this.guide_text = guide_text;
}
public int getStyle() {
return style;
}
public void setStyle(int style) {
this.style = style;
}
public List<BannersBean> getBanners() {
return banners;
}
public void setBanners(List<BannersBean> banners) {
this.banners = banners;
}
public List<TopicsBean> getTopics() {
return topics;
}
public void setTopics(List<TopicsBean> topics) {
this.topics = topics;
}
public static class BannersBean {
/**
* target_app_url :
* good_price :
* sub_title :
* special_list_url :
* target_id : 1055
* pic : http://f2.kkmh.com/image/170406/657xpped6.webp
* type : 2
* target_package_name :
* hybrid_url :
* target_web_url :
* target_title : 月令馆
* id : 1166
* request_id : 1-1491471717776
* good_alias :
* chapter_count : 9
*/
private String target_app_url;
private String good_price;
private String sub_title;
private String special_list_url;
private int target_id;
private String pic;
private int type;
private String target_package_name;
private String hybrid_url;
private String target_web_url;
private String target_title;
private int id;
private String request_id;
private String good_alias;
private int chapter_count;
public String getTarget_app_url() {
return target_app_url;
}
public void setTarget_app_url(String target_app_url) {
this.target_app_url = target_app_url;
}
public String getGood_price() {
return good_price;
}
public void setGood_price(String good_price) {
this.good_price = good_price;
}
public String getSub_title() {
return sub_title;
}
public void setSub_title(String sub_title) {
this.sub_title = sub_title;
}
public String getSpecial_list_url() {
return special_list_url;
}
public void setSpecial_list_url(String special_list_url) {
this.special_list_url = special_list_url;
}
public int getTarget_id() {
return target_id;
}
public void setTarget_id(int target_id) {
this.target_id = target_id;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getTarget_package_name() {
return target_package_name;
}
public void setTarget_package_name(String target_package_name) {
this.target_package_name = target_package_name;
}
public String getHybrid_url() {
return hybrid_url;
}
public void setHybrid_url(String hybrid_url) {
this.hybrid_url = hybrid_url;
}
public String getTarget_web_url() {
return target_web_url;
}
public void setTarget_web_url(String target_web_url) {
this.target_web_url = target_web_url;
}
public String getTarget_title() {
return target_title;
}
public void setTarget_title(String target_title) {
this.target_title = target_title;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRequest_id() {
return request_id;
}
public void setRequest_id(String request_id) {
this.request_id = request_id;
}
public String getGood_alias() {
return good_alias;
}
public void setGood_alias(String good_alias) {
this.good_alias = good_alias;
}
public int getChapter_count() {
return chapter_count;
}
public void setChapter_count(int chapter_count) {
this.chapter_count = chapter_count;
}
}
public static class TopicsBean {
/**
* label_color : #3750ff
* description : 史上第一四海八荒现代都市妖怪新解构大系一本正经的胡说八道脑洞大开子不语怪力乱神但鉴古有志怪发明神道之不诬故知无不语怪医可乱神是也,爱你哟。【授权/每周六更新 责编:Zaku】
* target_id : 1070
* pic : http://f2.kkmh.com/image/170331/35lcqfrsi.webp
* type : 2
* title : 怪医乱神
* recommended_text : 跟我一起去寻妖吧!
* likes_count : 136432
* label_text : 奇幻
* comments_count : 25534
* label_text_color : #ffffff
* category : ["奇幻","爆笑"]
* user : {"pub_feed":0,"avatar_url":"http://f2.kkmh.com/image/170122/haspj22wi.webp-w180.w","grade":1,"nickname":"物语谁说","reg_type":"author","id":31244040}
* label_id : 25
*/
private String label_color;
private String description;
private int target_id;
private String pic;
private int type;
private String title;
private String recommended_text;
private int likes_count;
private String label_text;
private int comments_count;
private String label_text_color;
private UserBean user;
private int label_id;
private List<String> category;
public String getLabel_color() {
return label_color;
}
public void setLabel_color(String label_color) {
this.label_color = label_color;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getTarget_id() {
return target_id;
}
public void setTarget_id(int target_id) {
this.target_id = target_id;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getRecommended_text() {
return recommended_text;
}
public void setRecommended_text(String recommended_text) {
this.recommended_text = recommended_text;
}
public int getLikes_count() {
return likes_count;
}
public void setLikes_count(int likes_count) {
this.likes_count = likes_count;
}
public String getLabel_text() {
return label_text;
}
public void setLabel_text(String label_text) {
this.label_text = label_text;
}
public int getComments_count() {
return comments_count;
}
public void setComments_count(int comments_count) {
this.comments_count = comments_count;
}
public String getLabel_text_color() {
return label_text_color;
}
public void setLabel_text_color(String label_text_color) {
this.label_text_color = label_text_color;
}
public UserBean getUser() {
return user;
}
public void setUser(UserBean user) {
this.user = user;
}
public int getLabel_id() {
return label_id;
}
public void setLabel_id(int label_id) {
this.label_id = label_id;
}
public List<String> getCategory() {
return category;
}
public void setCategory(List<String> category) {
this.category = category;
}
public static class UserBean {
/**
* pub_feed : 0
* avatar_url : http://f2.kkmh.com/image/170122/haspj22wi.webp-w180.w
* grade : 1
* nickname : 物语谁说
* reg_type : author
* id : 31244040
*/
private int pub_feed;
private String avatar_url;
private int grade;
private String nickname;
private String reg_type;
private int id;
public int getPub_feed() {
return pub_feed;
}
public void setPub_feed(int pub_feed) {
this.pub_feed = pub_feed;
}
public String getAvatar_url() {
return avatar_url;
}
public void setAvatar_url(String avatar_url) {
this.avatar_url = avatar_url;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getReg_type() {
return reg_type;
}
public void setReg_type(String reg_type) {
this.reg_type = reg_type;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
}
}
}
}
| Xianicai/Image | app/src/main/java/com/example/lenovo/kuaikan/discover/BeanRecomm.java |
66,054 | package com.mrathena.redis;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mrathena.spring.redis.serializer.CustomFastJsonRedisSerializer;
import com.mrathena.spring.redis.serializer.CustomKryoRedisSerializer;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @author mrathena on 2019/8/2 16:34
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:spring.redis.standalone.xml")
public class RedisStandaloneTest {
private static final String K = "key";
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
private ValueOperations<String, Object> stringObjectValueOperations;
private ValueOperations<String, String> stringStringValueOperations;
private Data data;
private List<Data> dataList;
private Set<Data> dataSet;
private Map<String, Data> dataMap;
@Before
public void beforeSerialize() {
// ValueOperations
stringObjectValueOperations = redisTemplate.opsForValue();
stringStringValueOperations = stringRedisTemplate.opsForValue();
// 数据
Data data = new Data("s", new O("u", "n"), null, (byte) 1, (short) 2, 3, 4L, 1.1F, 1.2D, 'a', true, (byte) 5, (short) 6, 7, 8L, 2.3F, 2.2D, 'B', true);
Data data2 =
new Data("s", new O("u2", "n2"), null, (byte) 2, (short) 3, 4, 5L, 2.2F, 3.3D, 'b', true, (byte) 6, (short) 7, 8, 9L, 4.4F, 5.5D, 'C', false);
Data data3 =
new Data("s", new O("u3", "n3"), null, (byte) 3, (short) 4, 5, 6L, 3.3F, 4.4D, 'c', true, (byte) 7, (short) 8, 9, 10L, 5.5F, 6.6D, 'D', false);
this.data = data;
List<Data> dataList = new LinkedList<>();
dataList.add(data);
dataList.add(data3);
this.dataList = dataList;
Set<Data> dataSet = new HashSet<>();
dataSet.add(data2);
dataSet.add(data3);
this.dataSet = dataSet;
Map<String, Data> dataMap = new HashMap<>(4);
dataMap.put("我是谁", data);
dataMap.put("我管你", data2);
this.dataMap = dataMap;
}
@Test
public void test() throws JsonProcessingException {
stringObjectValueOperations.set(K, new Date(), 10000, TimeUnit.MILLISECONDS);
System.out.println(stringStringValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K));
stringStringValueOperations.set(K, "a");
System.out.println(stringStringValueOperations.get(K));
}
@Test
public void JdkSerializationRedisSerializer() {
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
stringObjectValueOperations.set(K, 123);
// stringObjectValueOperations.increment(K);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, "你好啊");
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringStringValueOperations.get(K));
stringObjectValueOperations.set(K, data);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataList);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataSet);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataMap);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringStringValueOperations.get(K));
// org.springframework.data.redis.serializer.JdkSerializationRedisSerializer
// 反序列化时不需要提供类型信息
// 强制需要实现序列化,直接看redis不太方便,据说占的空间会大一点,反序列化为String后,乱七八糟的,还挺长 TODO 尝试看redis中能否获取size
// 不支持自增自减操作
}
@Test
public void StringRedisSerializer() {
// RedisTemplate默认序列化器为org.springframework.data.redis.serializer.JdkSerializationRedisSerializer
// Bean配置了默认序列化器为org.springframework.data.redis.serializer.StringRedisSerializer
stringObjectValueOperations.set(K, "你好啊");
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringStringValueOperations.set(K, "0.0,明显我不好啊!!!");
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, "1");
stringObjectValueOperations.increment(K);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringStringValueOperations.get(K));
// org.springframework.data.redis.serializer.StringRedisSerializer
// 支持自增自减操作
// 只支持String类型,用起来并不方便,需要手动把value转成string,不然set和get都会类转换异常
// RedisTemplate和StringRedisTemplate数据是互通的,想想也是通的,网上都是胡说八道
// 不过互通不代表能互用,用StringRedisTemplate存的数据用RedisTemplate取可能报错,因为序列化反序列化的机制不同
}
@Test
public void GenericToStringSerializer() {
// GenericToStringSerializer<Data> DataGenericToStringSerializer = new GenericToStringSerializer<>(Data.class);
// DataGenericToStringSerializer.setTypeConverter(new TypeConverter(););
// 需要实现org.springframework.beans.TypeConverter类型的类型转换器,用于把Data和String互相转换
// redisTemplate.setValueSerializer(DataGenericToStringSerializer);
// stringObjectValueOperations.set(K, data);
// System.out.println(stringObjectValueOperations.get(K));
// org.springframework.data.redis.serializer.GenericToStringSerializer
// GenericToStringSerializer,可自行实现普通类型和String的互相转换,一般几乎不会使用把
}
@Test
public void GenericJackson2JsonRedisSerializer() {
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
stringObjectValueOperations.set(K, 123);
stringObjectValueOperations.increment(K);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, "你好啊");
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
stringStringValueOperations.set(K, "我不好");
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, data);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataList);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataSet);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataMap);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
// org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer
// 支持自增自减操作
// 序列化为json,而且包含数据类型,可直接强制转换类型,非常方便,强烈推荐
// {"@class":"com.mrathena.redis.Data","name":{"@class":"com.mrathena.redis.Name","Dataname":"u","nickname":"n"},"age":20,"sex":true}
}
@Test
public void Jackson2JsonRedisSerializer() {
Jackson2JsonRedisSerializer<Object> objectJackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
objectJackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 如果没有ObjectMapper,反序列化的时候会报错,LinkedHashMap不能转化成Data
redisTemplate.setValueSerializer(objectJackson2JsonRedisSerializer);
stringObjectValueOperations.set(K, 123);
stringObjectValueOperations.increment(K);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, "你好啊");
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, data);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataList);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataSet);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataMap);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
// org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer
// 支持自增自减操作
// 序列化为json,但是感觉不太合理,包含数据类型,可直接强制转换类型,也算方便
// ["com.mrathena.redis.Data",{"name":["com.mrathena.redis.Name",{"Dataname":"u","nickname":"n"}],"age":20,"sex":true}]
}
@Test
public void FastJsonRedisSerializer() {
FastJsonRedisSerializer<Object> objectFastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// 开启FastJson的AutoType,可以给Json中写入class信息
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
fastJsonConfig.setSerializerFeatures(SerializerFeature.WriteMapNullValue, SerializerFeature.WriteClassName);
objectFastJsonRedisSerializer.setFastJsonConfig(fastJsonConfig);
// 如果没有SerializerFeature.WriteMapNullValue,序列化后的json中没有值为null的字段
redisTemplate.setValueSerializer(objectFastJsonRedisSerializer);
stringObjectValueOperations.set(K, 123);
stringObjectValueOperations.increment(K);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, "你好啊");
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, data);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataList);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataSet);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataMap);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
// com.alibaba.fastjson.support.spring.FastJsonRedisSerializer
// 支持自增自减操作
// 默认会去掉值为null的字段(可以设置支持),默认不支持AutoType(可以设置支持)
// 默认反序列化后的类型为JsonObject和JsonArray,不能直接到JavaBean(开启AutoType后可以)
// 序列化结果不是标准JSON
}
@Test
public void CustomerFastJsonRedisSerializer() {
redisTemplate.setValueSerializer(new CustomFastJsonRedisSerializer<>(Object.class));
stringObjectValueOperations.set(K, 123);
stringObjectValueOperations.increment(K);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, "你好啊");
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, data);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataList);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
List<Data> dDataList = (List<Data>) stringObjectValueOperations.get(K);
System.out.println(dDataList);
System.out.println();
stringObjectValueOperations.set(K, dataSet);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataMap);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
// com.mrathena.spring.redis.serializer.CustomFastJsonRedisSerializer
// 支持自增自减操作
// 默认会去掉值为null的字段(可以设置支持),默认不支持AutoType(可以设置支持)
// 默认反序列化后的类型为JsonObject和JsonArray,不能直接到JavaBean(开启AutoType后可以)
// 序列化结果不是标准JSON
}
@Test
public void KryoRedisSerializer() {
//
}
@Test
public void CustomKryoRedisSerializer() {
redisTemplate.setValueSerializer(new CustomKryoRedisSerializer<>(Object.class));
stringObjectValueOperations.set(K, "你好啊");
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, data);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataList);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataSet);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
System.out.println();
stringObjectValueOperations.set(K, dataMap);
System.out.println(stringObjectValueOperations.get(K));
System.out.println(stringObjectValueOperations.get(K).getClass());
System.out.println(stringStringValueOperations.get(K));
// com.mrathena.spring.redis.serializer.CustomKryoRedisSerializer
// 不支持自增自减操作
// 序列化后不便查看,但据说占用空间很小
// list等集合不支持
}
}
| mrathena/spring.redis | src/test/java/com/mrathena/redis/RedisStandaloneTest.java |
66,055 | package Feng;
public class Scene
{
Human grandpa;
Human seventhCalabasher;
Bogy snakeWoman;
Bogy scorpion;
PurpleGourd purpleGourd;
Scene()
{
grandpa = new Human("爷爷", 50);
seventhCalabasher = new Human("七娃", 100);
snakeWoman = new Bogy("蛇精", 100, 10);
scorpion = new Bogy("蝎子精", 100, 10);
purpleGourd = new PurpleGourd(seventhCalabasher);
}
public void Play()
{
purpleGourd.Glitter();
seventhCalabasher.Speak2("妈妈,爸爸,,,我在哪啊?", null);
purpleGourd.Release(seventhCalabasher);
purpleGourd.Glitter();
seventhCalabasher.Speak2("妈妈!", snakeWoman);
snakeWoman.Hug(seventhCalabasher);
snakeWoman.Speak2("诶~乖孩子", seventhCalabasher);
scorpion.Laugh();
seventhCalabasher.Speak2("妈妈~", snakeWoman);
snakeWoman.Speak2("好宝贝儿", seventhCalabasher);
snakeWoman.Kiss(seventhCalabasher);
grandpa.Speak2("孩子啊,你糊涂了,怎么跟妖怪打得火热啊,嗯?",
seventhCalabasher);
snakeWoman.Speak2("乖孩子,你看看这老头儿,你认得他吗?",
seventhCalabasher);
seventhCalabasher.Move(grandpa);
seventhCalabasher.Speak2("从来没有见过", snakeWoman);
grandpa.Speak2("孩子,我是你爷爷啊", seventhCalabasher);
seventhCalabasher.Speak2("你胡说,真不害羞", grandpa);
grandpa.Grieve();
seventhCalabasher.Move(snakeWoman);
seventhCalabasher.Speak2("妈妈,我是你的好宝贝儿", snakeWoman);
snakeWoman.Speak2("oh~真是个乖孩子", seventhCalabasher);
snakeWoman.Laugh();
scorpion.Laugh();
grandpa.Cry();
snakeWoman.Speak2("孩子,这个老头儿带了一帮蛮小子在这里捣乱,你说该怎么办呢,啊?",
seventhCalabasher);
seventhCalabasher.RollTheEyes();
seventhCalabasher.Speak2("妈,这宝贝可神了,威力无穷。我用它来收拾这帮蛮小子,给爸爸妈妈出气",
snakeWoman);
purpleGourd.Glitter();
snakeWoman.Speak2("oh,太好了,好宝贝儿", seventhCalabasher);
scorpion.Speak2("好!", seventhCalabasher);
snakeWoman.Laugh();
scorpion.Laugh();
}
public static void main(String[] args) throws Exception
{
Scene sce = new Scene();
sce.Play();
}
}
| jwork-2021-attic/jw01-DDDDDebugger | hw02/191220021/src/Feng/Scene.java |
66,056 | package mc.bape.module.other;
import mc.bape.values.Mode;
import mc.bape.values.Option;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import org.lwjgl.input.Keyboard;
import mc.bape.module.ModuleType;
import mc.bape.module.Module;
import mc.bape.utils.Helper;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.common.gameevent.PlayerEvent;
import org.lwjgl.input.Keyboard;
import java.util.Random;
import static org.lwjgl.input.Keyboard.KEY_P;
public class AutoL extends Module {
private int counter = 0;
private boolean warnAlready = false;
static String[] LMessages = {
"Subscribe to James_Tylor on youtube and discover BapeClient!",
"Hahaha I have a good client. Try BapeClient NOW!",
"Wanna get some good cheats? Try BapeClient!",
"You look so sad without cheats, try BapeClient with me!",
"Get good. Get BapeClient!",
"Don't even look at me without BapeClient.",
"You play like shit, why not try BapeClient?",
"You poor thing without BapeClient.",
"Get out of my face without BapeClient.",
"Hey! Wise up! Don't waste your time without BapeClient.",
"Must be a Vape User.",
"Don't push me around.",
"Ghost bypasses? Must be a Vape user.",
"I am not insulting you. I am describing you.",
"I'm not perfect, but I confess natural, how about you?",
"You say I envy you? Don't be ridiculous, go buy BapeClient.",
"To hear you speak, the kind of intelligence that Vape users have..",
"You haven't evolved, imagine still using Vape.",
"How do I dare to touch you, a Vape like you..",
"The prices of everything, are more and more cheap. (Like the shitty clients that you use)",
"Knowing that you are not happy, I feel at ease.",
"You should look into buying a client, I'd recommend BapeClient.",
"Here are your tickets to the Juice WRLD concert",
"She's got a body that won't quit and a brain that won't start.",
"Go ahead, tell them everything you know. It'll only take 10 seconds.",
"Well that was easy, must be a Vape user.",
"Are you that poor to not be able to afford BapeClient? How sad.",
"HvH is important? Well I guess so since I just broke your aura.",
"You're the type of guy to place 3rd in a 1v1 race",
"What client? Vape v4???",
"Your IQ Is so low you shouldn't be on the internet you fucking troglodyte",
"You probably clicked the wrong button on the Minecraft Installation screen.",
"This game can't be fun for someone so shit, uninstall already no one likes you.",
"It must be hard knowing that you're a mistake...",
"How's it feel with a shitty client?",
"Probably has MVP+ rank and fanboys this server..",
"Yes we totally skid bypasses, that's probably the reason we have the best bypasses whenever we update.",
"Simon doesn't fucking care lol.",
"Dumbass doesn't even have BapeClient.. --> BapeClient Dot XYZ",
"Stop playing on this shitty server and get BapeClient lmao.",
"Thor called, he wants his dox back.",
"L bozo",
"using a suck client",
"L",
"Play minecraft without skill",
"stupid bi7ch",
"have a lot of nerve",
"are out of your mind",
"Drop dead",
"don’t give me your shoot",
"no more excuses",
"pain in the ass",
"asshole",
"bastard",
"now you are going to die",
"REST IN PISS, FOREVER MISS",
"I WARNED YOU...",
"NOOB L2P G3T R3KT",
"failed at your 1337 h4x0r skillz",
"TRIED SO HARD AND GOT SO FAR, BUT IN THE END, YOU ARE STILL SUCK!",
"HACKER! ENJOY BAN!",
", GET BETTER HAX NEXT TIME XD",
"HAVE FUN TRYING TO RESTORE YOUR ITEMS :D",
", You are an idiot! HA HA HA HA HA HA HA",
"Time to get banned!",
"#MakeHackGreatAgain",
"suck L",
", you suck",
"too bad, HA HA HA HA HA",
"IS TOO LATE NOW",
"is hacking!",
"cheater",
", Your skill has been filtered",
"WATCHDOG IS DEAD, AND YOU KILLED HIM",
"give you up",
"let you down",
"run around and desert you",
"make you cry",
"say goodbye!",
"tell the lie and hurt you",
"deep in the dark you needn't the light",
"upload this video to your youtube!",
"TOO LATE",
"silly bi7ch",
"Bad operation",
"using suck hacks"
};
static String[] LMessagesCN = {
"我现在在这埋汰你呢小老弟",
"你个没速度的小废物",
"我好象你爸爸似的你难道自己不清楚现在的情况吗",
"然后你完全没有力量你明白你的扣字垃圾吗小废物",
"我好象你爸爸似的你是不了解情况怎么的呢",
"你为什么在这里耀武扬威的",
"现在了解什么情况你完全垃圾似的知道了吗",
"你好象垃圾似的你怎么和我对抗呢",
"嘻嘻嘻嘻你能出来告诉我吗",
"你完全没有速度你明白什么情况吗垃圾似的出来找揍",
"你自己好象我儿子似的只能污蔑我还是想怎么样吗",
"我就是你父亲似的随便殴打你一个完全没什么力量的儿子",
"父亲我随便殴打你这样的事实情况了啊儿子",
"我现在不是随便殴打你吗自闭青年",
"你自己现在不了解情况还是怎么的",
"自闭症儿童开始殴打你登峰造极的爸爸了啊",
"我怎么感觉你和我的自闭儿子似的反抗爸爸",
"儿子你现在自己怎么反抗的爸爸的你知不知道什么情况啊",
"现在的你看见你爹的各种速度害怕了还是怎么的",
"爸爸随意的打的你了啊你清楚事实吗",
"你还想无力地反抗我还是怎么啊弟弟",
"你自己不了解情况还是怎么的你完全垃圾似的",
"嘻嘻嘻你的b脸呢", "你妈给你b脸你装你妈b里去了呢",
"你好像完完全全不清楚情况",
"你没有发现你根本不是爹爹的对手吗",
"爹爹我随随便便干翻你母亲",
"你个狗儿子只有畏畏缩缩的滚了",
"你现在是不是坐在电脑前手心出汗呢",
"你是不是紧张了呢你是不是语无伦次了呢",
"你现在能做的只有乱敲键盘满怀恐惧地向我暗示你内心的恐惧呢",
"你没有发现现在就像一个跳梁小丑一样取悦我吗"
, "我随随便便殴打你殴打你个自闭东西",
"为什么为什么动不动操你妈傻逼",
"这是你翻来覆去的词汇呢",
"小朋友拿出你的实力来可好",
"你没有发现你根本不是爹爹的对手吗",
"你是不是死皮赖脸的给我上啊",
"死了妈的小伙子啊",
"你别在无济于事的给你爸爸我死皮赖脸的上了",
"你就是死皮赖脸的小伙子是不是这样你快回答我",
"你是个啥啊你个死了妈的小伙子你就是个小废物啊",
"小伙子你八仙过海的赶来狐假虎威地狗你爹爹我呢",
"你是不是垃圾狗篮子啊你告诉大家你是不是啊",
"你是不是大言不惭地吹嘘啊垃圾狗篮子呢",
"你怎么了啊是不是畏惧你爸爸我了啊",
"你个狗篮子是不是啊小伙子你妈死了",
"你承不承认你是个耀武扬威半身不遂的垃圾狗篮子啊",
"你赶紧的跟上啊", "是不是没有办法提高你的速度了",
"自己是不是已经感觉无能为力了啊",
"是不是没有速度焦头烂额了啊",
"你是不是知道你自己要输给你登峰造极的爸爸我了啊",
"你是不是没有自知之明了啊",
"你觉得你要输给你登峰造极的爸爸我啊你开始不是风风火火的吗",
"你干什么啊墨迹什么啊你什么自闭症速度啊",
"你难道不应该用强大到令人退缩的词汇来攻击我吗",
"弟弟你怎么词穷了啊",
"窝囊废东西是不是啊小伙子",
"你还大言不惭地吹嘘你的速度是不是啊",
"你有什么资本吹嘘",
"你无人问津的速度啊你一五一十的告诉你爸爸我啊",
"你是不是悬心吊胆的以为你可以赢过你登峰造极的爸爸我啊",
"我看你沾沾自喜的样子你是不是以为你可以胜利啊",
"小伙子你是不是窝囊废弟弟啊",
"你是不是家喻户晓的耀武扬威的不可一世的窝囊废啊",
"你怎么成了一个瓮中之鳖啊",
"你是不是疯疯癫癫无法自拔了啊",
"窝囊废东西是不是妄自尊大啊",
"你为什么怎么用你哩哩啦啦的言语攻击你登峰造极的爸爸我啊",
"你是不是想用你婆婆妈妈的词汇击败你老老实实的爹爹我啊",
"你是不是开始沾沾自喜了啊",
"你是不是以为你可以击败登峰造极的爸爸我啊",
"你现在是不是觉得莫名其妙的啊",
"为什么你爹打字速度这么快啊",
"你是不是畏惧你爹爹的速度了啊",
"你是不是对这些词汇一窍不通啊",
"你是不是什么都不懂啊",
"你怎么唯唯诺诺的了啊",
"你是不是畏惧我了啊",
"窝囊废东西你是不是苟延残喘了啊",
"你是不是汗流浃背了啊是不是气喘吁吁了啊",
"垃圾狗篮子跟上你爹爹我的节奏啊好不好啊",
"快用你三三两两的词汇攻击我",
"你一个井底之蛙怎么可能知道天比你个子高地比你脸皮厚嘛",
"老老实实的当你的窝囊废去啊",
"你干什么啊三番五次的攻击你爸爸我啊",
"你怎么还纹丝不动啊",
"你是又聋又瞎的吗",
"你是不明不白的吗",
"我叫你去老老实实的当窝囊废啊你迷迷糊糊的吗",
"你是不是听不懂你爹爹说的话啊",
"你爹爹我叫你去当窝囊废啊",
"你干什么啊是不是开始恼羞成怒了啊",
"怎么还不去老老实实地当你的窝囊废啊",
"怎么还在我面前耀武扬威的啊",
"你是不是想继续用你那断断续续的言语证明你的窝囊废啊",
"你再怎么样都是无济于事的小老弟你了解不了解啊",
"小老弟你就是个独一无二的窝囊废啊",
"你是不是不可一世的窝囊废啊",
"你为什么唧唧喳喳的啊",
"快用你断断续续的言语攻击我啊",
"你要是没有能力攻击我你就别在这婆婆妈妈的好不好啊崽种东西",
"你是不是窝囊废东西啊你告诉我啊",
"你用你稀稀拉拉支离破碎的言语攻击我啊",
"你怎么三番五次地污蔑你爹爹我啊",
"你是不是以为你有那一点零零散散的言语就可以击败我啊",
"你小心你爹爹我大义灭亲啊",
"你赶紧滚啊小老弟别提心吊胆的啊",
"爹爹我不会吃了你的啊",
"你干什么啊还纹丝不动是不是啊",
"赶紧从地球上消失啊",
"为什么还唧唧歪歪哩哩啦啦叽叽喳喳叭叭叭叭的啊",
"你是不是不想滚啊",
"你怎么莫名其妙地就不滚了啊",
"你是不是开始肆无忌惮了啊",
"你爹爹我见识多了别在狗狗妈妈了好吗", "你好象垃圾似的你有什么脾气你告诉大家知道了吗", "你认为就你这点词汇能把我打倒在这小小的网络世界中吗", "你就是幻想反抗你爸爸我还是怎么啊弟弟似的",
"你自己清楚明白你根本就是垃圾似的怎么的呢", "我残酷殴打你这样的事实情况你好象不清楚", "残酷地殴打你这样的恶霸事实你自己告诉我呢", "为什么没有速度你告诉你爸爸我", "为什么窝囊废你告诉你爸爸我啊",
"窝囊废东西你还不滚啊", "你恶心了你爸爸我你明不明白啊", "你自己好象没有水平但是不了解情况怎么的呢", "我现在和你随便开始你怎么不承认你自己垃圾东西", "我觉得我就是你爸爸还是怎么啊出来告诉我似的",
"你自己好象不清楚了解情况还是怎么的告诉大家埃", "但是你这样的垃圾速度清楚了解情况还是怎么的殴打我埃", "我随便的殴打你这样的垃圾似的好象们有反抗把", "我觉得你完全没有实力反抗爹的速度你怎么不知道啊",
"我觉得你就是个废品你自己好像没有文化了解吗", "我觉得你是废品你怎么反抗我的速度呢孩子", "你了解吗你知道吗你清楚吗明白吗晓得吗", "你真以为就凭你那毫无逻辑残缺不齐的词能带给你所谓的优越感和胜利感吗",
"你的词汇就是艹B艹妈这样下流的吗", "你不就是个张口闭口艹B艹妈满脑子想着艹B艹妈的自闭玩意吗", "你为什么那么语无伦次那么没有逻辑", "你就是完全没什么文化水平似的垃圾废物弟弟",
"我随便殴打你这样的事实儿子你的言语行动都装作不清楚似的", "你这个垃圾速度和我继续的对抗呢对吗", "你真的以为你能称霸这键盘界吗", "你完全垃圾似的没有水平怎么反抗我", "你告诉在场的各位啊",
"我随便殴打你的事实不能进行唠嗑怎么的告诉我呢啊", "我不认为你这个垃圾似的能够开始唠嗑怎么的", "马上出来告诉大家可以了吗你完全垃圾似的知道吗", "我就是你爸爸这样的事实你自己好象不清楚",
"我随便殴打你这样的事实情况你自己告诉我还是怎么", "我好象你爸爸似的小老弟你是不清楚事实还是怎么的怎么就没有点速度呢", "你知道吗殴打你这个弱智垃圾完全不需要什么水平",
"你自己好象没有水平似不了解情况怎么的", "你严重的没有水平似的你晓得啊", "你自己没有速度开始逃避我?你是怎么的啊", "你就是不能反抗你父亲我还是怎么的啊速度滚出来告诉我啊",
"我不明白什么了啊我觉得好象我是你爸爸了呢", "火葬场打电话问你妈要几分熟啊你回答啊", "马上狗肉节了你为什么不给你家里人安顿好避难所还出来打游戏啊你回答啊", "你是根本没长脑子还是脑子发霉啊你回答啊",
"你赶紧回到你妈生殖器里重新改造重新做狗啊", "你这个畏畏缩缩的小老弟赶紧滚啊", "你话那么多怎么不坐你妈坟头跟她慢慢唠嗑", "你爹爹我反手赏你亲亲妈妈一个不侧漏的骨灰盒",
"我就是养条狗在键盘上放个屁的速度都比你手速快", "别喷粪好吗再喷你脑子就空了你知道吗", "爸爸一把剔骨刀插你妈脑门上一脚踹过去给你妈头盖骨撬开现在你狗娘脑浆子都蹦上九霄云外了你知道吗",
"我用jb把你狗娘脑袋抽傻了现在你妈逢人就吹嘘她被男性生殖器干成了脑震荡你清楚吗", "大爹徒手撕开你狗娘的大屁眼子再找来你亲爹把他脑袋塞进去让你妈的屎橛子替你爹补充一下生物能量你明白吗",
"不要那种威胁的语气跟我对话行不行啊", "你以为你骂几句傻逼就无人能匹敌了吗", "你不要那么风趣幽默好吗", "你有没有发现你bb的都是一堆废话", "我完全可以无视你那垃圾语言",
"我估计你无法抵挡我这洪水般的词汇", "你已经无力回天", "你只能乱敲键盘", "你告诉我你内心在哭泣而且无力回天是不是的", "你怎么不好好考虑一下你到底有没有那个实力跟我抗衡",
"跟个残废人墨迹半天有多无聊你知道吗", "别再用你那三言两语支离破碎的词语来攻击我好吗", "你不觉得你这稀稀拉拉的词汇太没杀伤力了吗", "就你这窝囊废样子你还想揍倒我吗", "你现在痴人说梦异想天开了吧",
"你怎么到现在都不理解我揍你的意图呢", "你太废物为什么为什么我总有忍不住揍你的冲动", "你现在是不是在思索着该怎么回答我呢", "你一五一十的告诉我行不", "你是不是被我打击的无法言语了呢",
"是不是在失望的深渊里面痛苦的无法自拔", "你认为你就这么跟我说几句话旧能跟你大哥我抗衡了吗", "我都不想再打击你这个没有力气的弟弟了", "跟你这么说简直就是在侮辱我的曼巴狂蛇键盘",
"你以为就你这点词汇能把我打倒在这虚拟的网络世界中吗", "你以为你能称霸这键盘界吗", "你是不是就连打句我草你妈你都没有勇气按下回车吗", "还在那摇摆不定失去重心是吗",
"双眼涣散的你看到了你爹爹我对你洪水般的攻击吗", "你那鬼哭狼嚎的语言在我眼里是多么地不堪一击", "大哥我随意践踏你的自尊和人格", "你还能用你那零零碎碎的语言反击我么",
"你说话好吗我求你了提升一下你的蛤蟆速度啊", "你还要继续发扬你那厚颜无耻的精神吗", "你回去抱着你妈一起痛哭好吗", "只有你妈能给你安慰了行吗", "你看看你那有气无力的挣扎",
"你是不是要跪下求我停止攻击了呢", "看好你爹爹是如何用华丽的词汇来教育你的啊", "你感到前所未有的恐惧了吗", "你的心是否正在因为畏惧你爹爹的速度而没命地跳动", "弟弟你是畏惧我了吗",
"你还不快滚蛋吗", "你可以继续用你那支离破碎的语言和不要脸的功夫继续和我对话", "可是你觉得你还有什么呢", "你就是一个废物你懂吗", "你那毫无逻辑残缺不齐的词真的能带给你快乐和胜利感吗",
"你是不是想气急败坏的冲到现实来找我呢", "用你那残缺发抖的双手来揍我吗", "你只能撕破你第n层脸皮来求我绕了你", "继续找借口来逃避我吧", "你现在内心哭泣了是吗", "对你对话使我感到了一种莫名的耻辱",
"我不想再和残废人墨迹了你懂吗", "你为什么连最基本的词汇都忘的一干二净了呢", "你是在紧张吗", "你空白的大脑偶尔也思考这复杂的局势", "你还想着凭借你那点词汇赢过我吗", "你现在是什么处境呢",
"你是不是希望让你爹爹手下留情呢", "你是不是在想要怎么回答我", "你为什么哑巴了呢", "你为什么不敢打字了呢", "你为什么一跟我说话就开始结结巴巴反反复复的呢", "你为什么还要垂死挣扎呢",
"你是不是跟我说一句话要经过大脑半天的思考才敢发出来", "你怎么窝囊废到前无古人后无来者的地步了", "你真的无药可救了你知道吗", "你为什么要在我面前红红火火班门弄斧的",
"你为什么要当着我的面唧唧歪歪结结巴巴的", "你就没有一颗羞耻之心吗", "你那平平淡淡的语言难以抵挡我", "我真的想给你一次毁灭性的打击", "你的无知只是我脚下的一堆凌土你知道不",
"你记住以后不要再用你那粗俗的语言来攻击我就像让你爹爹我来定格你的人品", "你不要见到我就一副闻风丧胆的样子", "你蹲厕所去看看你那窝囊废形象", "我真的不知道要能拿什么词语来形容你这个弟弟",
"你在你大哥我面前是永远抬不起头的你知道不知道啊弟弟", "你那点词汇那么的不堪一击", "你还想用你那不堪的语言来激起我的怒火", "我简直不屑与你废话你清楚明白吗", "你以后不要在我面前装了好吗",
"没有一点点实力还在我面前耀武扬威的你不觉得丢脸吗", "你何来的自信跟我抗衡啊。", "你那些流离失所的语言早就已经被我攻击的支离破碎", "你还要我挥洒着这些语言来跟你描述我淋漓尽致的语言么",
"你自己告诉你大哥我你那弱小的身躯能承受住我那犀利的语言么", "什么什么什么你这个垃圾", "怎么怎么怎么你这个废物", "为什么为什么为什么你要用那么低贱而庸俗的语言来跟我抗衡呢你告诉我呢",
"你这个乱七八糟的玩意你告诉我好不好", "你就这么束手待毙颠三倒四的等着我来收拾你是吗", "我平平常常的扣字速度轻轻松松就能把你攻击得一塌糊涂", "你还能怎么样", "你难道还想继续在我这展示自己有多丢脸吗",
"丢脸好玩吗好意思吗", "死了妈的你到底行不行啊", "我的语言对你来说已经无关紧要", "因为你早就被我揍的全身麻木了是不", "你从开始就根本不敢回击我是不是的", "你一开始的反击只是你的本能是不是的",
"要不要让我停止你的苟延残喘", "在键盘上无奈地敲出“我错了”好吗", "你那点零零星星的词汇", "你的希望是不是就来自于你那偶然的灵光一现", "你有什么资格再来跟我对话", "我不是什么所谓的大手",
"但是我在你眼里永远是神圣而不可侵犯的你知道吗", "看着你那可悲可笑的滑稽样我心底产生了一种悲痛感", "你到底是怎么长大的", "我真想去问候一下你妈", "到底是怎么把你这酒囊饭袋生出来的",
"登峰造极出类拔萃无人能敌的世纪窝囊废", "你回去再修炼几十年再跟我来对抗吧", "现在你没有这个能力", "你不知道爸爸我的速度可以完全吧你抹杀了啊你怎么和我相提并论了阿",
"你气急败坏的窝囊废怎么和我絮叨了啊你怎么按么恬不知耻了啊", "你松松垮垮的词汇怎么和我匹敌的阿", "你不知道自己恨窝囊废阿", "你现在的词汇怎么那么窝囊废了啊", "小老弟你怎么回事儿啊",
"你气急败坏的和我絮叨你那不要脸的词了阿", "还厚颜无耻的跑到我面前吹嘘你的实力是多么的强悍", "你难道就真的不知道羞耻二字怎写吗", "拿着几年前百度上已经开始传的沸沸扬扬的泛滥词汇",
"在你这段七拼八凑的泛滥词汇里我怎么就丝毫看不出其中的含义", "我现在用登峰造极的完全可以抹杀你的自尊心了你难道还不知道阿", "你现在的速度可以说的狗急跳墙的速度了你还怎么和我媲美的阿",
"为什么你老是用你那三三两两的杀伤力来挑战我登峰造极的水平", "你以为你狗刨式的打字方法就能够击败我出神入化的水平", "不要以为你是东方不败", "其实你就是酒囊饭袋",
"你只有你那蜗牛般的速度和你那唧唧歪歪的词汇", "你告诉我你为什么在这里耀武扬威", "你认为你那恶心的词汇可以伤到你爸爸我", "你是不是就这点本事", "为什么没有速度你告诉你爸爸我",
"为什么窝囊废你告诉你爸爸我啊", "窝囊废东西你还不滚", "你恶心了你爸爸我", "你为什么在这里耀武扬威", "为什么在这里唧唧喳喳", "你为什么为什么语无伦次", "你告诉你爸爸我告诉我为什么",
"你这样苟活于世", "是不是给你祖上添光彩了呢", "你看看你那可怜的我装什么了", "您倒是告诉我呢", "我装什么都比你装b好", "你是不是不知道你有多难堪呢",
"是不是要你妈妈我把你打的一败涂地你才知道你地下有多厚呢", "现在窝囊废我告诉你", "我替你感到悲哀你知道么", "你气急败坏的说你要灭我", "你怎么灭啊小老弟", "滚回你妈妈子宫去深造几年再来和我抗衡",
"你耀武扬威做什么阿", "你横行霸道干什么阿", "你这窝囊东西", "你这瘠薄东西", "你这废物东西", "我见识多了", "别在爹爹妈妈了好吗", "以后见了我十米开外就要给我跪下知道没有",
"别老用你那窝囊废", "耀武扬威这个字眼浑浑噩噩活一辈子", "就你这个样子的太给中国十几亿人口丢脸了", "你的语言不彳亍你需要学习需要教育", "我真的真的为你妈妈感觉到非常地伤心",
"你不要总是和我耀武扬威的好不好啊", "你也不要在用那杂乱无章的语言和我说话好不好啊", "你告诉告诉我你到底怎么了", "你有牌面吗当然没有", "你拿什么跟我玩哦", "你拿什么跟我玩呢",
"你没有能力跟上爹的飞一般的速度", "你告诉我你妈妈怎么把你带到地球上的呢", "你告诉我你爸爸怎么了啊", "你告诉我你妈妈怎么了啊", "你妈妈死了你知不知道", "你爸爸也死了你知不知道",
"你爸爸妈妈死了你还有心情上网", "你为什么这么不孝", "你告诉告诉我可以嘛", "你为什么不告诉我呢", "你说话可以嘛", "你是害怕了吗", "你是退缩了吗", "你为什么不拿出你的词语驳回我的理论呢",
"你可怕了是嘛为什么呢", "我小手哦你为什么怕我呢", "你为什么不说话呢", "孩子别装逼了还是嘛", "在跟我装b我把你妈比撕烂了塞你嘴里哦", "你是不是在哭泣哦", "我知道你哭了",
"你现在都泪流满面了是嘛", "你告诉告诉我", "你是公是母是雌是雄呢", "我是你亲爹么你告诉我", "爹知道你激动了", "你为什么激动呢", "你是紧张了么", "你是遇见了爸爸我紧张了么",
"你为什么会遇见爸爸我呢", "因为爹是打狗专家呢", "爹为什么要打狗呢", "因为你是狗呢", "你为什么是狗呢", "因为你妈妈没把你教好呢", "为什么没把你教好呢", "因为你妈妈忙着卖B了",
"你妈妈为什么忙着卖B呢", "因为要挣钱养活你呢", "你妈妈为什么要养活你", "为什么要养你这只畜生呢", "为什么把你养大你不好好做人", "而跑去做狗呢?回家问你妈妈去", "这么多为什么因为",
"你知道究竟是为什么呢", "是因为你这条狗惹的祸呢", "你难道还不知错么", "为什么还坚持呢", "你坚持的理由在哪", "为什么还不变回原形呢", "孩子你知道了么,还是做人好呢",
"做一个低调的网络人物才能受到别人的尊重", "我知道你怕我了呢嘻嘻", "你为什么要怕我呢", "你可不可以不怕我呢", "我不想骄傲使人退步发生在爹身上呢", "你手心为什么出汗呢", "你键盘为什么会湿了呢",
"你为什么会有这种现象呢", "你真的紧张了是么", "你有感觉到冷么", "你在发抖么", "你放松一点好不好啊", "你爹爹我很仁慈的", "你别让感觉到你是在逃避我好么", "我不想离开你呢你知道吗",
"从你身上爹找到无穷的自信了呢", "你给爹点激情吧", "你让我知道你的速度也是多么多么快", "语言是多么多么丰富吧", "你为什么这么这么巴拉巴拉的逃避我呢", "你给个解释听听好么",
"我真的不想被别人议论成我是在欺负你", "你为什么哭呢", "你让我看到你的眼泪了", "你能成熟点好么", "你竟然还装不知道你在这样无力地打击我", "你觉得你有速度还是怎么的你可以出来和我抵抗吗",
"觉得你完全没有速度你明白的还是怎么的你可以出来吗", "我觉得你完全没有水平你明白的还是怎么的你可以出来吗", "你可以出来和我抵抗的吗还是怎么的你告诉我的可以吗",
"你难道不知道你就是没有速度垃圾吗你告诉我的呢", "你难道不知道你就是没有速度的垃圾吗你出来的呢", "你完全没有速度和蜗牛龟龟似的你明白的还是怎么的啊", "你难道不知道你就是没有速度的垃圾吗你告诉我的呢",
"你难道不知道你就是完全没有速度的垃圾吗你告诉我的可以", "你麻痹的是不是可会造谣我了可有意思了呢小伙子", "纹丝不动对不对了啊是不是动不动窝囊废了啊", "你现在能不能登峰造极了啊你马上的开始啊",
"你个小屁孩子你马上的和我比速度啊你行不行", "你现在能不能登峰造极了啊你马上的开始啊", "你现在嬉皮笑脸的干什么啊", "你这样什么意思啊", "你现在是不是气急败坏咬牙切齿了呢",
"你现在能接你父亲我华丽又神圣的语言吗", "你现在开始和你父亲我唠嗑了吗", "你现在开始欺负爹爹了是吗", "你现在开始大逆不道了是吗", "你这坨只能被人踩在脚底下的烂泥你知道了吗",
"你不知道你父亲我的唠嗑是出神入化的吗", "你现在什么东西你和你父亲我叫嚷什么了啊", "你完全的不懂你现在的速度了是不是呢", "你完全不知道你是什么词汇你奶奶孙子脱口而出",
"我有没有懂不懂速度你自己不清楚吗", "你语无伦次你妈妈个b啊你个大垃圾", "你完全完全你妈妈个老篮子东西", "你难道完全的不清你是什么东西了是不是呢",
"你难道不觉得你现在没道路没技术没水平没战斗力没杀伤力吗。", "你没有可以挑战我的词汇了是吗小老弟", "你现在要是有一点攻击力我都服你了啊", "你完全的不能跟我抗衡你知道吗小伙子",
"你现在配有资格让我挑战你吗", "你完全的不行了你的词汇丝毫没杀伤力", "你现在衡量什么东西啊", "你完全没有能力你自己清楚了吗", "你完全的不能跟我的等级相提并论你知道吗", "你完全的不行什么东西了啊",
"你现在完全不能你奶奶个腿儿啊", "你还相提并论了吗", "你完全没速度什么战斗力大逆不道的话你都比什么攻击了啊", "你完全的不了解你是什么东西的速度了", "你现在叫花子似的说什么戳穿啊",
"你现在癞皮狗似的你说什么速度等级啊", "你完全的不知道你的处女膜是怎么破的", "你噶骄什么呢你篮子又干嘛呢你想升级是吗", "你完全的不了解你现在是不是完全的没速度",
"你是不是完全的不懂你的等级和我的等级有多大的差距了是不是呢", "你完全的不了解我的等级有多高你就挑战我和我抗衡了是不是呢", "你现在什么东西你和我嗷嗷什么东西了啊.", "你衡量你奶奶孙子啊",
"我现在的速度完全都可以挑战你那0杀伤力的蛤蟆速度了", "你是垃圾的你自己不清楚吗", "你说什么东西呢啊", "你完全的不知道你爷爷都不是我对手你又了解知道吗", "你是不是完全不知道呢",
"你现在完全没速度了啊", "你爷爷你妈妈个b啊", "你个垃圾你了解你奶奶孙子啊", "你完全不晓得我是不是很厉害的等级挑战你那蜗牛的速度了是不是呢", "你现在速度什么东西了啊", "我是你父亲你知道吗",
"你谈什么垃圾速度啊", "你还跟我操你妈你是什么东西呢", "你以为你登峰造极了是吧", "你以为我不是你父亲了是吧", "你就是完全的蛤蟆速度我跟上你了", "你速度你妈妈个b啊你个垃圾",
"你还完全你自己草你妈你自己清楚了吗", "我是你父亲你还登峰造极了", "你清楚你妈妈个b", "你完全了就你妈妈个b", "你张口闭口奶奶孙子啊", "你现在开始说些什么东西大逆不道的话", "你自己不清楚吗",
"你是不是完全的又没有词汇了呢", "你是不是头脑一片混乱了", "你是不是想抄袭我的高级词汇了呢", "你开始说些什么东西你自己不清楚吗", "你就想完全地逃避我你知道了吗",
"你快告诉我你是不是因为没有速度而沉默呢", "你就是不是又开始你那个泛滥了", "小朋友你现在和我说些什么乱七八糟的话啊", "我看你的老词汇要养到多少岁才能有点战斗力", "是不是呢回答我",
"你完全不清楚事实", "你的词汇已经很落伍了", "你现在是不是完全的不清楚了", "你为什么现在完全跟不上我的速度了", "你是大脑不清晰了还是欲言又止了", "你那词汇到底是百度呢还是搜狗呢",
"你现在是不是气急败坏地苦苦搜寻所谓的词汇了是不是呢", "你是不是完全的不知道你多搞笑是不是呢", "我的唠嗑那么牛比怎么是废物呢不是吗", "你就知道幻想吧", "你是不是完全的不行了呢",
"你是不是没速度加没词汇啊", "你选迮繁荣什么都不是你什么废物似的", "你是不是很喜欢你那个词汇呢你是不是完全的跟不上我的速度了", "你是不是很喜欢呆驴一样的速度了", "不要扯开话题和你父亲我唠嗑啊",
"你是不是完全的登峰造极的窝囊废了呢", "你是不是完全的不清楚你是什么东西了是不是呢", "你自己半身不遂了呢你清楚了吗", "是不是完全的不清楚你说不上话了是不是呢", "你现在大逆不道的话太多了你知道了吗",
"你是不是词汇找到了呢", "是不是呢你告诉我呢你完全的不清楚了", "你是不是这样的呢你告诉我呢", "能不能告诉我你现在是个什么东西了啊", "你想让我告诉你什么东西你自己说啊",
"哈哈你的词汇是什么处女膜的呢", "你就告诉你我完全速度一五一十的揍一年了啊", "你这个速度你是在散步呢吗", "我的速度是完全的揍你你自己不知道了吗", "你什么三三两两什么东西乱七八糟的啊",
"你就告诉我你是不是很喜欢抄袭呢是不是的", "我抄袭什么的下列啊你个垃圾似的你清楚了吗", "你选杂开始大逆不道的话越来越多了你知道了吗", "你刚刚看到你那些编造的话语都是什么东西了啊弟弟你可真能幻想啊",
"你现在怎么跟我抗衡你还关呢", "你是不是完全的没有词汇了还是在想怎么找词汇呢", "你现在不清楚我词汇什么东西了啊", "你是个什么半身不遂的东西啊", "你是不是整一个弟弟东西啊",
"你不行了你老了你知道吗", "你跟不上我的速度是不是吧", "完全什么东西你个弟弟你妈妈个b啊", "你什么东西你自己不清楚吗", "你自己没词汇对不对啊", "你妈死了是不是", "你妈死了知道不",
"你鬼哭狼嚎叫妈妈呢", "你丢弃了这个半死不活的妈妈啊", "放心我会一五一十告诉你妈", "然后你开始给我反抗好吗", "你没有一点速度啊你没什么实力怎么和我抗衡",
"你开始死皮赖脸的耀武扬威了呢你看谁给你脸了", "是谁给你的勇气啊你告诉我", "你这个速度简直就是蜗牛啊", "我在侮辱你呢", "你没什么脾气啊", "还在那嘻嘻哈哈什么呢", "你气急败坏什么呢",
"是不是恼羞成怒了", "你照照镜子看看你这个人模狗样的好吗", "你难道不知道吗", "你就是我的手下败将", "小老弟给我反抗", "我给你机会反抗", "你什么窝囊废自己窝囊废你比比叨叨什么啊",
"你开始怀疑爸爸开软件了", "嘻嘻嘻嘻弟弟开始造谣你爹开软件了哈", "你继续造谣你爸爸", "你再怎么造谣我我还是你野爹啊", "野爹就是外面操翻你妈了然后不负责了你知道吗", "你是不是狗啊",
"你就是一条废狗啊", "这你清清楚楚的啊", "我正在随随便便殴打你这个二哈呢你知道吗", "你没有一点速度还在这丢人现眼呢", "你妈生你干什么玩意", "自己垃圾还瞎扒拉啥词汇啊",
"滚吧死垃圾没速度还在这你在侮辱你爹的啊", "你是不是气急败坏", "你是不是恨不得冲过来一拳打倒我啊", "你为什么不拿出你的词语驳回我的理论呢", "你难道完全忘记了你是什么东西了是不是呢",
"你难道不觉得你的词汇", "支离破碎零零散散流离失所无家可归", "没有道理没有技术没有水平没战斗力没杀伤力吗", "你完全的没速度的词汇能挑战我是吗", "你现在能有一点攻击力我都服你了啊",
"你完全的不能跟我抗衡你知道吗小伙子", "你现在配有资格让我挑战你吗", "你完全没速度什么战斗力大逆不道的话你都比什么攻击了啊", "你完全的不了解你是什么东西的速度了你现在叫花子似的说什么戳穿啊",
"你现在癞皮狗似的你瞎扯什么速度等级啊", "你完全不知道你的处女膜是怎么破的你瞎叫什么呢", "你个篮子在干嘛呢你想升级是吗", "你完全不了解情况你现在完全没速度",
"你是不是完全的不懂你的等级和我的等级有多大的差距是不是呢", "你完全的不了解我的等级有多高你就挑战我和我抗衡了是不是呢", "你现在什么东西你跟我嗷嗷叫什么东西了啊",
"你就是完全的速度还跟我完全比你那没用的速度了是不是呢", "你现在速度什么东西了啊我是你爹爹你知道了吗", "你谈什么垃圾速度啊你还完全的跟我处女膜什么呢", "你以为你登峰造极了是吧",
"你就是完全没有速度你跟上我了吗", "你速度你妈妈个b啊你个小垃圾", "你还完全不清楚你现在自己草你自己妈你自己知道了吗", "我是你亲亲爹爹你还以为自己登峰造极了",
"你清楚你妈妈个b啊你完全了就你妈妈个b啊你生你奶奶孙子啊", "你是不是完全的登峰造极的窝囊废了呢", "你是不是完全的不清楚你是什么东西了是不是呢", "你自己半身不遂了你清楚了吗",
"是不是完全的不清楚你说不上了是不是呢", "你现在大逆不道的话很多你知道了吗", "你是不不是词汇找到了呢是不是完全的不清楚", "你说跟不上你自己不清楚吗", "是不是呢你告诉我呢",
"你完全不清楚了你是不是这样的呢你告诉我呢", "你还知道词汇了呢你是不是这样你告诉我", "你想让我告诉你什么东西你自己说啊", "哈哈你的词汇是什么处女膜的呢你", "我完全速度一五一十的揍你一年了啊",
"你以为你三三两两的词汇能把我按在地上暴打呢", "我的速度是把你吊起来打你自己不知道吗", "你那些都是什么三三两两什么叽叽喳喳什么乱七八糟的东西啊",
"你就告诉我你是不是很喜欢抄袭呢是不是呢我抄袭什么的词汇啊", "你个垃圾似的你清楚了吗", "你那杂交词汇变得越来越多了你知道吗", "你刚刚看道袍你超次什么东西了啊你可真能幻想啊",
"你现在怎么跟我抗衡你还关呢我现在怎么不行了啊", "你拼死拼活拼不过我一五一十的速度啊", "你是不是完全的没有词汇了还是在想怎么找词汇呢", "你现在不清楚我词汇是什么东西了啊",
"你回答我你现在是不是个半身不遂的东西啊", "你现在怎么了呢你是不是完全的弟弟啊", "你不行了你老了你知道吗", "你跟不上我的速度吧", "你什么东西你个弟弟你妈妈个b啊", "你什么东西你自己不清楚啊",
"你自己没有一点词汇对不对啊", "你就是二愣子似的你还说什么啊弟弟", "你一个二愣子弄出这么多话题弟弟你好好想想把", "没速度就不要恶心你爸爸我你明白吗", "你爸爸我的速度揍你足够了你知道吗",
"你就是二愣子似的你还说什么啊弟弟", "你一个二愣子弄出这么多话题弟弟", "你好好想想把你怎么提升速度", "我觉得你完全没速度你自己清楚你那拖拉机速度", "我觉得你完全没速度你弟弟噶哈你自己清楚垃圾啊",
"我草你妈你这样语无伦次的bb什么东西", "你就是狗你知道不知道啊", "我草你妈的你干什么三三两两的啊弟弟你自己垃圾啊", "小家伙你自己马上出来跟我唠嗑可以么篮子似的呢啊",
"你这样的人我瞧不起你阿你自己没发现还是怎么的啊", "你自己就是个拖拉机似的你还跟我近乎的哈巴狗啊", "你自己就是个拖拉机跟我套近乎的小家伙什么哈巴狗啊", "你自己充其量严格二愣子弟弟啊你还完事瞧不起我啊",
"你自己没有战斗力你别跟我扯淡可以吗.你完全没有战斗力啊", "你自己随便拖拉机你跟我套近乎的小家伙你哈巴狗的啊", "你自己没有战斗力你别跟我墨迹可以吗你完全没有战斗力啊",
"你一丁点战斗力都没有你还跟我抗衡是这样吗弟弟", "你的眼睛开始发昏了是不是啊", "你跟我墨迹啥啊你完全没有战斗力啊你了解吗", "你难道不觉得什么了吗你自己完全充其量篮子似的啊",
"你自己完全没有战斗力的呢啊", "你自己完全二愣子似的啊弟弟", "你完全废物啊是这样的情况吗", "你你自己完全拖拉机似的啊", "你充其量就是二愣子似的啊", "你现在完全没有速度了啊",
"你自己拖拉机似的啊你自己难道不清楚什么了吗", "你自己完全拖拉机似的啊我可瞧不起你这样的人啊", "你自己清楚什么了啊你自己完全拖拉机似的啊", "你自己没有战斗力你清楚了吗我可瞧不起你这样啊",
"你自己随便拖拉机你自己难道不清楚什么了吗", "你自己不清楚什么情况了吗你自己完全蜗牛似的啊", "你自己完全拖拉机似的啊你自己完全没有战斗力啊", "你自己没有战斗力你别跟我墨迹可以么篮子似的啊",
"你自己一个颤巍巍的小伙子你还和我墨迹什么了啊", "你自己充其量就是个二愣子似的啊你自己清楚了吗", "你自己现在整一个二愣子似的啊你难道不清楚什么了吗", "弟弟你自己完全没有速度似的难道不对吗废物啊",
"弟弟你自己现在好象我儿子似的你清楚什么了吗", "弟弟你自己蜗牛速度似的难道不对吗废物哈", "弟弟你自己没有战斗力似的你难道不清楚什么了吗", "弟弟你自己完全拖拉机似的啊这样你清楚情况了吗",
"弟弟你自己充其量篮子似的啊你完全没有战斗力啊", "弟弟你自己就是二愣子似的啊你自己没觉得了吗", "弟弟你自己就像拖拉机似的我可瞧不起你这样的人啊", "你现在完全二愣子似的啊你难道不清楚什么了吗",
"你自己充其量演个二愣子弟弟啊", "你完事你还瞧不起我啊是不是啊回答我啊", "你自己没有战斗力你别跟我墨迹可以吗你完全没有战斗力啊", "你一丁点战斗力都没有你还跟我抗是这样吗弟弟",
"你自己一个颤巍巍小伙子你跟我墨迹啥啊弟弟", "你自己没有战斗力你别跟我扯淡可以吗你自己废物啊", "你自己拖拉机似的啊你自己难道不清楚什么了吗", "你自己就是个拖拉机跟我套近乎的小家伙什么哈巴狗啊",
"你现在完全准备好和我唠嗑了是吗我可瞧不起你啊", "你现在自己是不是没有准备好了啊你自己清楚了吗", "你自己随便拖拉机你跟我套近乎的小家伙你哈巴狗的啊", "你现在自己没有战斗力啊是这样的情况吗小家伙",
"小家伙你自己马上出来跟我唠嗑可以么篮子似的呢啊", "你这样的人我瞧不起你啊你自己没发现还是怎么的啊", "你现在充其量没有战斗力你清楚这样的情况了吗", "我现在觉得你这样的速度完全不可以跟我对抗啊不是吗",
"你完全就是一个拖拉机啊你不知道我是你爸爸吗", "我可瞧不起你这样的啊你难道不清楚你是儿子了吗", "你难道不清楚什么了吗你自己完全拖拉机似的啊", "我可不喜欢搭理你这样的啊你自己完全清楚了啊",
"你一丁点战斗力的没有你还跟对抗是这样的呢吗", "你现在自己好象阿拉伯难民啊你难道不是这样的情况吗", "小弟弟我觉得你这样的速度完全不可以跟我对抗不是吗",
"你自己现在意大利的警犬似的你难道不是这样的情况了吗", "你现在是不是自己无能为力是不是", "你现在是不是无济于事了对不对", "你现在是不是大言不惭了是不是", "你现在是不是闻风丧胆了是不是",
"你现在是不是错字连篇大神对不对", "你现在是不是大言不惭哈巴狗没讲错吧", "你现在是不是无济于事是不是的", "小伙子你现在是不是无能为力对啊", "你怎么了窝囊废弟弟", "你自己窝囊废", "怎么窝囊废",
"什么窝囊废", "为什么窝囊废", "是不是窝囊废", "你回答爸爸的啊", "你干什么半身不遂", "你唧唧喳喳的有意思啊", "你干什么窝囊废弟弟", "什么什么窝囊废", "你耀武扬威什么啊",
"有意思啊", "小伙子你什么东西", "你胡说八道什么", "你自己是不是窝囊废", "怎么了窝囊废似的", "你完全窝囊废", "你知道吗窝囊废", "你知道什么了啊", "你自己是不是窝囊废",
"草你妈窝囊废", "你怎么了啊窝囊废", "你干什么耀武扬威啊", "你半身不遂窝囊废啊", "你怎么了啊", "你回答爸爸我啊", "你怎么了啊窝囊废", "你干什么沉默的啊", "怎么了窝囊废啊",
"是不是唧唧喳喳的", "为什么窝囊废的", "弟弟你是不是窝囊废的", "告诉爸爸好不好窝囊废", "三三两两窝囊废的", "稀稀拉拉窝囊废的", "小伙子你干什么耀武扬威", "你个杂交东西",
"你大言不惭什么呢哈巴狗", "你干什么窝囊废小伙子", "你个半身不遂的小伙子", "我草你妈的有意思了对不对", "你是不是哈巴狗东西啊神经病", "为什么没有速度你告诉你爸爸我",
"为什么窝囊废你告诉你爸爸我啊", "窝囊废东西你还不滚", "你恶心了你爸爸我", "你为什么在这里耀武扬威", "为什么在这里唧唧喳喳", "为什么在这里汪汪汪地狗叫", "为什么为什么为什么我草你妈的",
"你为什么为什么语无伦次", "你告诉你爸爸我", "告诉我为什么", "你告诉我你什么东西", "你耀武扬威的什么东西", "你是不是没有速度", "没有速度你装什么B攻击我",
"你告诉我你哪来的自信与勇气拿着这点词汇来攻击我", "怎么不告诉我啊我告诉你啊你赶紧告诉我啊", "你是个什么东西啊,你是不是小垃圾啊", "你为什么不告诉我你是个小垃圾呢", "回答我啊弟弟",
"我現在在這埋汰妳呢小老弟", "妳個沒速度的小廢物", "我好象妳爸爸似的妳難道自己不清楚現在的情況嗎", "然後妳完全沒有力量妳明白妳的扣字垃圾嗎小廢物", "我好象妳爸爸似的妳是不了解情況怎麽的呢",
"妳爲什麽在這裏耀武揚威的", "現在了解什麽情況妳完全垃圾似的知道了嗎", "妳好象垃圾似的妳怎麽和我對抗呢", "嘻嘻嘻嘻妳能出來告訴我嗎", "妳完全沒有速度妳明白什麽情況嗎垃圾似的出來找揍",
"妳自己好象我兒子似的只能汙蔑我還是想怎麽樣嗎", "我就是妳父親似的隨便毆打妳壹個完全沒什麽力量的兒子", "父親我隨便毆打妳這樣的事實情況了啊兒子", "我現在不是隨便毆打妳嗎自閉青年",
"妳自己現在不了解情況還是怎麽的", "自閉症兒童開始毆打妳登峰造極的爸爸了啊", "我怎麽感覺妳和我的自閉兒子似的反抗爸爸", "兒子妳現在自己怎麽反抗的爸爸的妳知不知道什麽情況啊",
"現在的妳看見妳爹的各種速度害怕了還是怎麽的", "爸爸隨意的打的妳了啊妳清楚事實嗎", "妳還想無力地反抗我還是怎麽啊弟弟", "妳自己不了解情況還是怎麽的妳完全垃圾似的", "嘻嘻嘻妳的b臉呢",
"妳媽給妳b臉妳裝妳媽b裏去了呢", "妳好像完完全全不清楚情況", "妳沒有發現妳根本不是爹爹的對手嗎", "爹爹我隨隨便便幹翻妳母親", "妳個狗兒子只有畏畏縮縮的滾了", "妳現在是不是坐在電腦前手心出汗呢",
"妳是不是緊張了呢妳是不是語無倫次了呢", "妳現在能做的只有亂敲鍵盤滿懷恐懼地向我暗示妳內心的恐懼呢", "妳沒有發現現在就像壹個跳梁小醜壹樣取悅我嗎", "我隨隨便便毆打妳毆打妳個自閉東西",
"爲什麽爲什麽動不動操妳媽傻逼", "這是妳翻來覆去的詞彙呢", "小朋友拿出妳的實力來可好", "妳沒有發現妳根本不是爹爹的對手嗎", "妳是不是死皮賴臉的給我上啊", "死了媽的小夥子啊",
"妳別在無濟于事的給妳爸爸我死皮賴臉的上了", "妳就是死皮賴臉的小夥子是不是這樣妳快回答我", "妳是個啥啊妳個死了媽的小夥子妳就是個小廢物啊", "小夥子妳八仙過海的趕來狐假虎威地狗妳爹爹我呢",
"妳是不是垃圾狗籃子啊妳告訴大家妳是不是啊", "妳是不是大言不慚地吹噓啊垃圾狗籃子呢", "妳怎麽了啊是不是畏懼妳爸爸我了啊", "妳個狗籃子是不是啊小夥子妳媽死了",
"妳承不承認妳是個耀武揚威半身不遂的垃圾狗籃子啊", "妳趕緊的跟上啊", "是不是沒有辦法提高妳的速度了", "自己是不是已經感覺無能爲力了啊", "是不是沒有速度焦頭爛額了啊",
"妳是不是知道妳自己要輸給妳登峰造極的爸爸我了啊", "妳是不是沒有自知之明了啊", "妳覺得妳要輸給妳登峰造極的爸爸我啊妳開始不是風風火火的嗎", "妳幹什麽啊墨迹什麽啊妳什麽自閉症速度啊",
"妳難道不應該用強大到令人退縮的詞彙來攻擊我嗎", "弟弟妳怎麽詞窮了啊", "窩囊廢東西是不是啊小夥子", "妳還大言不慚地吹噓妳的速度是不是啊", "妳有什麽資本吹噓",
"妳無人問津的速度啊妳壹五壹十的告訴妳爸爸我啊", "妳是不是懸心吊膽的以爲妳可以贏過妳登峰造極的爸爸我啊", "我看妳沾沾自喜的樣子妳是不是以爲妳可以勝利啊", "小夥子妳是不是窩囊廢弟弟啊",
"妳是不是家喻戶曉的耀武揚威的不可壹世的窩囊廢啊", "妳怎麽成了壹個甕中之鼈啊", "妳是不是瘋瘋癫癫無法自拔了啊", "窩囊廢東西是不是妄自尊大啊", "妳爲什麽怎麽用妳哩哩啦啦的言語攻擊妳登峰造極的爸爸我啊",
"妳是不是想用妳婆婆媽媽的詞彙擊敗妳老老實實的爹爹我啊", "妳是不是開始沾沾自喜了啊", "妳是不是以爲妳可以擊敗登峰造極的爸爸我啊", "妳現在是不是覺得莫名其妙的啊", "爲什麽妳爹打字速度這麽快啊",
"妳是不是畏懼妳爹爹的速度了啊", "妳是不是對這些詞彙壹竅不通啊", "妳是不是什麽都不懂啊"};
static String[] LMessagesFrancais = {
"Tu me fais chier.",
"T'es con, ou quoi?",
"Marche à l'ombre!",
"Casse-toi !",
"Ne me casse pas les couilles ?",
"fils de pute",
"On t'as bercé trop près du mur?",
"merde dans un bas de soie.",
"T'es rien qu'un ostie de gros cochon sale qui s'roule dans sa propre merde à la journée longue pis qu'y aime ça en plus!",
"trou de cul !",
"Va te faire foutre. Va te faire enculer.",
"emmerdeur",
"casse-pied",
"Merde!",
"Merde alors!",
"Bordel-de-merde!",
"Putain de merde!",
"Tu es une vraie merde.",
"Alors je te dis Merde pour ton examen de demain !"
};
static String[] LMessagesРусский = {
"Русский",
"сука блядь",
"Иди на хуй",
"ди на хуй",
"Какой позор!",
"Сука ! Блять!",
"Курицын сын!",
"чёрт возьми",
"Иди к чёрту",
"хуй:* твай матель",
"Ерунда! Чепуха! Вздор!",
"Круглый дурак! Дурак!",
"К чёрту!",
"Что за чёрт! Что за дьявол",
"Не выведи меня из себя!",
"Мне стыдно за тебя"
};
static String[] LMessagesGerman = {
"Mistkerl",
"Blödmann",
"Penner",
"Pisser",
"Widerling",
"Schwein",
"Hund",
"Schweine-hund",
"Affe",
"Ganove ",
"Dummschwätzer",
"Arschgeige",
"Grobian",
"Griesgram",
"Stinkmorchel",
"Stinkstiefel",
"Schweinebacke",
"Johnny Depp"
};
private Option<Boolean> autoL = new Option<Boolean>("AutoL","AutoL", false);
private Mode<Enum> mode = new Mode("Mode", "mode", (Enum[]) AutoL.AutoLmod.values(), (Enum) AutoL.AutoLmod.English);
public AutoL(){
super("AutoL", Keyboard.KEY_NONE, ModuleType.Other,"send obscenities when you press P");
this.addValues(this.mode);
Chinese="嘴臭模式";
}
static enum AutoLmod {
English,
Chinese,
Francais,
Russian,
German
}
@Override
public void enable() {
Helper.sendMessage("Press P to name-calling!");
}
@SubscribeEvent
public void keyInput(InputEvent.KeyInputEvent event) {
if(this.mode.getValue() == AutoLmod.English){
if (Keyboard.isKeyDown(KEY_P)) {
Random r = new Random();
mc.thePlayer.sendChatMessage(LMessages[r.nextInt(LMessages.length)]);
}
} else if (this.mode.getValue() == AutoLmod.Chinese){
if (Keyboard.isKeyDown(KEY_P)) {
Random r = new Random();
mc.thePlayer.sendChatMessage(LMessagesCN[r.nextInt(LMessagesCN.length)]);
}
}else if (this.mode.getValue() == AutoLmod.Francais){
if (Keyboard.isKeyDown(KEY_P)) {
Random r = new Random();
mc.thePlayer.sendChatMessage(LMessagesFrancais[r.nextInt(LMessagesFrancais.length)]);
}
}else if (this.mode.getValue() == AutoLmod.Russian){
if (Keyboard.isKeyDown(KEY_P)) {
Random r = new Random();
mc.thePlayer.sendChatMessage(LMessagesРусский[r.nextInt(LMessagesРусский.length)]);
}
}else if (this.mode.getValue() == AutoLmod.Russian){
if (Keyboard.isKeyDown(KEY_P)) {
Random r = new Random();
mc.thePlayer.sendChatMessage(LMessagesGerman[r.nextInt(LMessagesGerman.length)]);
}
}
}
}
| ImCzf233/Bape-Opensource | src/main/java/mc/bape/module/other/AutoL.java |
66,057 | package W01.S191220053;
import W01.S191220053.GlobalVariables.EntityType;
import W01.S191220053.GlobalVariables.GlobalClassType;
import W01.S191220053.GlobalVariables.MagicStatus;
import java.util.HashSet;
import W01.S191220053.GlobalVariables.BeingStatus;
import W01.S191220053.GlobalVariables.WeaponStatus;
public class Scene {
private static int num;
private static Being[] allmember;
private CalaBoy[] calaboy;
private Human oldman;
private Monster snake, scorpion, frog;
private Building stonecave;
public Scene(){
// 人物、建筑初始化
calaboy = new CalaBoy[8];
calaboy[7] = new CalaBoy(30, "SeventhBro", BeingStatus.alive);
calaboy[5] = new CalaBoy(30, "FifthBro", BeingStatus.alive);
calaboy[4] = new CalaBoy(30, "FourthBro", BeingStatus.alive);
oldman = new Human(20, "GrandPa", BeingStatus.alive);
snake = new Monster(40, "SnakeMadam", BeingStatus.alive);
scorpion = new Monster(50, "Scorpion", BeingStatus.alive);
frog = new Monster(10, "FrogScout", BeingStatus.panic);
stonecave = new Building(100, "StoneCave", BeingStatus.alive);
// 人物的武器以及特殊能力
calaboy[7].ObtainEntity(new Weapon("PurpleCalabash", EntityType.weapon, 5, 100, WeaponStatus.brandnew));
calaboy[5].ObtainEntity(new Magic("Water", EntityType.magic, 5, MagicStatus.normal));
calaboy[4].ObtainEntity(new Magic("Fire", EntityType.magic, 5, MagicStatus.normal));
calaboy[4].ObtainEntity(new Magic("Lighting", EntityType.magic, 5, MagicStatus.normal));
// 所有人物添加到全局变量组, 方便广播
allmember = new Being[20];
allmember[0] = calaboy[7];
allmember[1] = calaboy[5];
allmember[2] = calaboy[4];
allmember[3] = oldman;
allmember[4] = snake;
allmember[5] = scorpion;
allmember[6] = frog;
allmember[7] = stonecave;
num = 8;
}
public void Play(){
calaboy[4].Attack(stonecave, "Lighting");
frog.StatusTransition(BeingStatus.panic);
frog.SpeakTo(snake, "报!!!大王, 这帮蛮小子打进来了!!");
Being[] tempgroup = new Being[] {calaboy[4], calaboy[5]};
calaboy[7].GroupBroadCast(tempgroup, "你们这帮野小子, 敢来这胡闹, 我可对你们不客气了!");
calaboy[5].SpeakTo(calaboy[7], "弟弟,你怎么昏了头脑, 去帮两个妖精?");
calaboy[4].SpeakTo(calaboy[7], "弟弟, 你中邪了, 怎么跟妖精混在一起?");
calaboy[7].GroupBroadCast(tempgroup, "你们才是妖精呢, 我是妈妈的好宝贝. 谁敢欺负我的爸爸妈妈我就把它捏得粉碎");
oldman.SpeakTo(calaboy[7], "孩子你中邪了, 快醒醒.");
calaboy[7].SpeakTo(oldman, "你这老家伙, 再胡说八道我就要你好看!");
SpecialEntity fire = (SpecialEntity)calaboy[4].ExertEntity("Fire", null, GlobalClassType.None);
fire.Attack(calaboy[7]);
calaboy[7].BroadCast("收!!!");
calaboy[7].ExertEntity("PurpleCalabash", fire, GlobalClassType.SpecialEntity);
calaboy[4].Attack(calaboy[7], "Fire");
snake.SpeakTo(calaboy[7], "hahah, 你真行啊");
calaboy[5].SpeakTo(calaboy[4], "哥哥, 看我的");
SpecialEntity water = (SpecialEntity)calaboy[5].ExertEntity("Water", null, GlobalClassType.None);
calaboy[7].ExertEntity("PurpleCalabash", water, GlobalClassType.SpecialEntity);
calaboy[7].Brag("PurpleCalabash");
SpecialEntity lighting = (SpecialEntity)calaboy[4].ExertEntity("Lighting", null, GlobalClassType.None);
calaboy[7].ExertEntity("PurpleCalabash", lighting, GlobalClassType.SpecialEntity);
calaboy[7].ExertEntity("PurpleCalabash", calaboy[4], GlobalClassType.CalaBoy);
calaboy[7].ExertEntity("PurpleCalabash", calaboy[5], GlobalClassType.CalaBoy);
calaboy[5].SpeakTo(calaboy[4], "唉你这个混蛋!");
calaboy[4].SpeakTo(calaboy[5], "我今天要给你点颜色瞧瞧");
calaboy[5].Attack(calaboy[4], "Water");
fire = (SpecialEntity)calaboy[4].ExertEntity("Fire", null, GlobalClassType.None);
water = (SpecialEntity)calaboy[5].ExertEntity("Water", null, GlobalClassType.None);
fire.Attack(water);
water.Attack(fire);
calaboy[7].SpeakTo(snake, "哈哈哈, 妈, 你看他们都打起来了");
}
public static void BroadCastMessage(Being src, String message){
for (int iter = 0; iter < num; ++iter){
// 广播不发给自己
if (allmember[iter].UnitName() != src.UnitName())
allmember[iter].ReceiveDialog(message);
}
}
public static void GroupBroadCastMessage(Being[] target, String message){
HashSet<Being> set = new HashSet<Being>();
for (var iter : target)
set.add(iter);
for (int iter = 0; iter < num; ++iter)
if (set.contains(allmember[iter]))
allmember[iter].ReceiveDialog(message);
}
public static void main(String[] args) {
// P12 -《妖迷心窍》
// 3:28 ~ 3:38 : <序幕> 葫芦娃4、5娃打进妖精洞穴
// 3:57 ~ 4:30 : <中章> 人物对话演示(广播、组播)
// 4:30 ~ 5:57 : <高潮> 战斗演示
new Scene().Play();
}
}
| jwork-2021-attic/jw01-EnxIII | S191220053/Scene.java |
66,060 | import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//define
int a=0,a4=0,a100,a400;
String str="";
System.out.print("輸入西元年份:");
a=in.nextInt();
//process
a4=a%4;
a100=a%100;
a400=a%400;
if (a4==0&& !((a100==0)&&!(a400==0)))
str="閏年";
else
str="平年";
System.out.println("該年為 "+str);
}
} | Kalvin520/Java-Learning | Year.java |
66,062 | import java.io.*;
import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
while (true) {
System.out.println("GCログの場所を入力してください。 ");
String logfile = new Scanner(System.in).nextLine();
BufferedReader stream = new BufferedReader(new InputStreamReader(new FileInputStream(new File(logfile))));
String line = "";
boolean isG1GC = false;
int processed_lines = 0;
int stop_times = 0;
BigDecimal total_stop_time = new BigDecimal("0.0");
BigDecimal totaltime = new BigDecimal("0.0");
BigDecimal biggest = new BigDecimal("0.0");
//for skip header(jvminfo etc)
for (int i = 0; i < 3; i++) stream.readLine();
while ((line = stream.readLine()) != null) {
boolean isStopTime = true;
if (!isG1GC && line.contains("GC pause")) isG1GC = true;
if (isG1GC && !line.contains("GC pause")) isStopTime = false;
if (!line.contains("secs")) continue; //[GC concurrent-cleanup-start] etc
String sec = line.substring(line.lastIndexOf(",") + 1, line.lastIndexOf((" secs"))).trim();
System.out.println("Processed " + sec);
BigDecimal secb = new BigDecimal(sec);
totaltime = totaltime.add(secb);
if (isStopTime) {
total_stop_time = total_stop_time.add(secb);
if ((biggest.compareTo(secb)) == -1) biggest = secb;
}
++processed_lines;
if (isStopTime) ++stop_times;
}
stream.close();
System.out.println();
System.out.println("###############");
System.out.println("ログファイル名 = " + logfile);
System.out.println("合計GC処理時間 = " + totaltime.toString() + " sec");
System.out.println("合計停止時間 = " + total_stop_time.toString() + " sec");
System.out.println("最長停止時間 = " + biggest.toString() + " sec");
System.out.println("平均停止時間 = " + total_stop_time.divide(new BigDecimal(processed_lines), RoundingMode.HALF_UP) + "sec");
System.out.println("GC停止回数 = " + stop_times);
System.out.println("###############");
System.out.println();
System.out.println("CTRL+Cで停止します。");
}
}
}
| kawaemon/GCLogParser | Main.java |
66,063 | import java.util.Scanner;
public class Bmi {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 2; i++) { // 2人分の入力と計算を行うためのループ
System.out.println("身長(身長(例:160なら1.6など))を入力してください(" + i + "):");
double height = scanner.nextDouble();
System.out.println("体重を入力してください(" + i + "):");
double weight = scanner.nextDouble();
double bmi = calculateBMI(height, weight);
System.out.printf("1" + i + " のBMIは %.2f です。\n", bmi);
String message = interpretBMI(bmi);
System.out.println(message);
}
}
public static double calculateBMI(double height, double weight) {
return weight / (height * height);
}
public static String interpretBMI(double bmi) {
String category;
if (bmi < 18.5) {
category = "やせすぎ";
} else if (bmi >= 18.5 && bmi < 24.9) {
category = "平均的な体重";
} else if (bmi >= 24.9 && bmi < 29.9) {
category = "やや太り気味";
} else {
category = "肥満";
}
String message = "あなたのBMIは " + String.format("%.2f", bmi) + " の" + category + " です。\n";
if (category.equals("平均的な体重")) {
message += "健康的です。この状態を維持しましょう。";
} else {
message += "適正体重を目指すために、筋肉を付ける、運動するを心がけましょう。";
}
return message;
}
}
| sasa0307/command-ensyu | Bmi.java |
66,065 | package com.anemois;
import java.util.Scanner;
public class a004{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int x;
while(scanner.hasNext()){
x = scanner.nextInt();
if((x%4==0 && x%100 != 0) || x%400 == 0)
System.out.println("閏年");
else
System.out.println("平年");
}
scanner.close();
}
} | Anemois/ZeroJudge | a004.java |
66,066 | import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
class Data {
private String name;
private int english;
private int math;
public Data(String str, int e, int m) {
name = str;
english = e;
math = m;
}
public void writeData() {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("student.txt", true))) {
writer.write(name + " " + english + " " + math + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
public void show() {
System.out.println("姓名: " + name);
System.out.println("英文成績: " + english);
System.out.println("數學成績: " + math);
System.out.println("平均: " + calculateAverage());
System.out.println();
}
private double calculateAverage() {
return (english + math) / 2.0;
}
}
public class Ex10 {
public static void readData() {
try (BufferedReader reader = new BufferedReader(new FileReader("student.txt"))) {
String line;
while ((line = reader.readLine()) != null) {
String[] data = line.split(" ");
Data student = new Data(data[0], Integer.parseInt(data[1]), Integer.parseInt(data[2]));
student.show();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Data stu1 = new Data("Ariel", 92, 85);
Data stu2 = new Data("Fiona", 67, 89);
stu1.writeData();
stu2.writeData();
readData();
}
}
| 111B01529/chap14 | ex10.java |
66,068 | import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
public class sas {
public static void main(String[] args) {
// Scannerクラスのインスタンス化
Scanner stdIn = new Scanner(System.in);
// クラスの人数を入力してもらう
System.out.print("クラスの人数を入力して下さい:");
int num = Integer.parseInt(stdIn.nextLine());
// arrayList型の変数listを宣言し、空のarrayListを代入する
ArrayList<Integer> list = new ArrayList<>();
// クラスの人数分の年齢を入力してもらい、listに追加する
for(int i = 0;i < num; i++){
// 入力を促す文字列を表示する
System.out.print((i+1)+"人目の年齢を入力して下さい:");
// 入力してもらった年齢をリストに格納する
list.add (Integer.parseInt(stdIn.nextLine()));
}
// 年齢の合計を管理する変数sumを宣言し、0で初期化する
int sum = 0;
//listに格納されている年齢の平均を求める
for(int i = 0;i < num; i++){
// listの年齢を取り出し、sumの中に足していく
sum = sum + list.get(i);
}
//平均年齢を管理する変数aveを宣言し、平均年齢を計算し、代入する
double ave = (double)sum / num;
//平均年齢を表示する
System.out.println("クラスの平均年齢は、"+ave+"歳です。");
//---------------------------------------------------------------------//
// HashMap型の変数mapを宣言し、空のHashMapを代入する。
HashMap<String,Integer> map = new HashMap<>();
// キーとして先生の名前を、値としてその人の年齢をmapを格納する
map.put("江藤",34);
map.put("加藤",27);
map.put("佐藤",29);
map.put("伊藤",42);
map.put("後藤",38);
// 先生の平均年齢を計算するので、合計する為の変数sum2を宣言し、0で初期化する
int sum2 = 0;
// 拡張for文を用いて、各先生の名前と年齢を表示する
for(String name:map.keySet()){
// 合計に年齢を足し込む
sum2 += map.get(name);
// 先生の名前と年齢を表示する
System.out.println("名前:" + name + "先生 年齢:" + map.get(name));
}
//平均年齢を管理する変数aveを宣言し、平均年齢を計算し、代入する
double ave2 = (double)sum2 / map.size();
// 最後に平均年齢を計算し、表示する
System.out.println("先生の平均年齢は、"+ ave2 +"歳です。");
}
}
| l3Lqcky/java | sas.java |
66,069 | class M8_5 {
public static void main(String[] args) {
// 要素数が5のリストを作る。
int[] array = {1, 2, 3, 4, 5};
// 合計
int a = 0;
for (int i = 0; i < array.length ; i ++){
a += array[i];
}
// 合計を表示
System.out.println("合計値は" + a + "です。");
// 平均を表示
System.out.println("平均値は" + (a / array.length) + "です。");
}
}
| a000000000aaa000a0/1_1-7_3 | M8_5.java |
66,076 | package test;
import java.util.Scanner;
public class test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()) {
int year = scanner.nextInt();
if((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0)) {
System.out.println("閏年");
}else {
System.out.println("平年");
}
}
}
}
| gjlmotea/ZeroJudge | a004.java |
66,078 | import java.util.Scanner;
/**
* @File: ex32
* @Description: 2次平面上で旅行をするとき、そのプランが実行可能蚊どうかを判定してください
* @Input: ------
* N
* t1 x1 y1
* .
* tn xn yn
* ------
*/
public class ex32 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int preT = 0;
int preX = 0;
int preY = 0;
for (int i = 0; i < N; i++) {
int postT = sc.nextInt();
int postX = sc.nextInt();
int postY = sc.nextInt();
int dt = postT - preT;
int dist = Math.abs(postX - preX) + Math.abs(postY - preY);
if ((dt < dist) || ((dist - dt) % 2 != 0)) {
System.out.println("No");
return;
}
preT = postT;
preX = postX;
preY = postY;
}
System.out.println("Yes");
}
}
| NISHI3/java_2020 | ex32.java |
66,079 | import java.util.Scanner;
/**
* @File: ex20
* @Description: 2つの正整数a,bが与えられます。a,bの平均値をxとします。xの小数点以下を切り上げて得られる整数を出力してください。
* @Input:
* ------
* a b
* ------
*/
public class ex20 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.println((a + b + 1) / 2);
}
}
| NISHI3/java_2020 | ex20.java |
66,086 | import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//小红有n 个点,每个点的坐标为 (xi,yi),小红可以从一个点出发,平行于坐标轴移动,直到到达另一个点。比如从 (1,1)出发,可以到达 (1,3),(5,1),但无法直接到达(4,4),如果需要到达(4,4),需要增加一个点 (4,1)或者 (1,4)。
//小红想知道,最少需要增加几个点,才能使得任意两个点之间可以互相到达。
//输入描述:每行n个数用空格隔开。n(n <= 1000),表示方阵阶数为n。接下来是n行的数字输入有多个测试用例,每个测试用例第一行为一个整数
//n,表示方阵阶数,接下来n行,每行n个整数,表示方阵。
//输出描述:输出一个整数表示答案。
//示例1 输入 2 1 1 1 1 2 2 输出 1
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] arr = new int[n][n];
int[] x = new int[n];
int[] y = new int[n];
int count = 0;
for (int i = 0; i < n; i++) {
x[i] = 0;
y[i] = 0;
}
for (int i = 0; i < n; i++) {
int j = 0;
while (j < n) {
arr[i][j] = sc.nextInt();
x[i] += arr[i][j];
y[j] += arr[i][j];
j++;
}
}
for (int i = 0; i < n; i++) {
if (x[i] % 2 != 0) {
count++;
}
if (y[i] % 2 != 0) {
count++;
}
}
if (count == 0) {
System.out.println(0);
} else if (count == 2 || count == 4) {
System.out.println(1);
} else {
System.out.println(-1);
}
}
} | puppyooo/JavaCode | Main.java |
66,129 | package 第四场.石油采集;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* 链接:https://www.nowcoder.com/acm/contest/76/A
* 来源:牛客网
* <p>
* 题目描述
* 随着海上运输石油泄漏的问题,一个新的有利可图的行业正在诞生,那就是撇油行业。如今,在墨西哥湾漂浮的大量石油,吸引了许多商人的目光。这些商人们有一种特殊的飞机,可以一瓢略过整个海面20米乘10米这么大的长方形。(上下相邻或者左右相邻的格子,不能斜着来)当然,这要求一瓢撇过去的全部是油,如果一瓢里面有油有水的话,那就毫无意义了,资源完全无法利用。现在,商人想要知道,在这片区域中,他可以最多得到多少瓢油。
* <p>
* 地图是一个N×N的网络,每个格子表示10m×10m的正方形区域,每个区域都被标示上了是油还是水
* 输入描述:
* 测试输入包含多条测试数据
* 测试数据的第一行给出了测试数据的数目T(T<75)
* 每个测试样例都用数字N(N<50)来表示地图区域的大小,接下来N行,每行都有N个字符,其中符号’.’表示海面、符号’#’表示油面。
* 输出描述:
* 输出格式如下“Case X: M”(X从1开始),M是商人可以最多得到的油量。
* 示例1
* 输入
* 1
* 6
* ......
* .##...
* ......
* .#..#.
* .#..##
* ......
* 输出
* Case 1: 3
*/
/**
* 用一个二维数组记录每个位置往下和往右能取得的石油数,二维数组初始值-1
*/
public class Main {
static class MaxValue {
int down;
int right;
MaxValue() {
}
MaxValue(int down, int right) {
this.down = down;
this.right = right;
}
}
public static void main(String[] args) {
try {
System.setIn(new FileInputStream("input.txt"));
} catch (FileNotFoundException ignored) {
}
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for (int caseNo = 1; caseNo <= n; caseNo++) {
int graghSize = in.nextInt();
char[][] gragh = new char[graghSize][graghSize];
for (int i = 0; i < graghSize; i++) {
gragh[i] = in.next().toCharArray();
}
boolean[][] flag = new boolean[graghSize][graghSize];
MaxValue[][] values = new MaxValue[graghSize][graghSize];
int res = search(gragh, 0, 0, flag, values);
System.out.printf("Case %d: %d\n", caseNo, res);
}
in.close();
}
private static int search(char[][] gragh, int x, int y, boolean[][] flag, MaxValue[][] values) {
if (x == gragh.length) {
x = 0;
y += 1;
}
if (y == gragh.length) {
return 0;
}
// 已经被选中或者当前区域是水面
if (flag[x][y] || gragh[x][y] == '.') {
return search(gragh, x + 1, y, flag, values);
}
// 已经计算出结果
if (values[x][y] != null) {
return Math.max(values[x][y].down, values[x][y].right);
}
values[x][y] = new MaxValue(0, 0);
// 往右取
if (x + 1 < gragh.length && gragh[x + 1][y] == '#') {
flag[x + 1][y] = true;
values[x][y].right = 1 + search(gragh, x + 1, y, flag, values);
flag[x + 1][y] = false;
}
// 往下取
if (y + 1 < gragh.length && gragh[x][y + 1] == '#') {
flag[x][y + 1] = true;
values[x][y].down = 1 + search(gragh, x + 1, y, flag, values);
flag[x][y + 1] = false;
}
return Math.max(values[x][y].down, values[x][y].right);
}
}
| lxhao/algorithm | 牛客刷题/第四场/石油采集/Main.java |
66,132 | package com.lzw.beans;
import java.util.List;
/**
* 试卷类
*/
public class TestPaper {
/**
* id : cet4_20180601
* name : 2018年6月第一套英语四级真题
* listening : {"id":"cet4_20180601_listening","name":"2018年6月第一套英语四级真题-听力","news":[{"id":"cet4_20180601_listening_news_1","name":"News Report One","text":"A Message in a bottle sent out to sea by a New Hampshire man more than five decades ago was found 1,500 miles away and has been returned to his daughter. The long lost message was discovered by Clint Buffington of Utah while he was vacationing. Buffington says he found a soda bottle half buried in the sand that looked like it had been there since the beginning of time. The note inside the bottles said, \u201creturn to 419 Ocean Street and receive a reward of $150 from Richard and Tina Pierce, owners of the Beach comber motel.\u201d The motel was owned by the parents of Paula Pierce in 1960. Her father had written the note as a joke and had thrown it into the Atlantic Ocean. Buffington flew to New Hampshire to deliver the message to Paula Pierce. She held up to her father\u2019s promise giving Buffington that reward, but the biggest reward is the message in a bottle finding its way back home.","questions":[{"name":"question_1","title":"What is the news report mainly about?","answers":["The return of a bottled message to its owner's daughter.","A New Hampshire man's joke with friends on his wife.","A father's message for his daughter.","The history of a century-old motel."]},{"name":"question_2","title":"Why did Pollard Pearce give Clint Buffington the reward?","answers":["She wanted to show gratitude for his kindness.","She wanted to honor her father's promise.","She had been asked by her father to do so.","She was excited to see her father's handwriting."]}]},{"id":"cet4_20180601_listening_news_2","name":"News Report two","text":"Millions of bees have died in South Carolina during aerial insect spraying \noperations that were carried out to combat the Zika virus. The insect spraying \nover the weekend left more than 2 million bees dead on the spot in Dorchester \nCounty South Carolina, where four travel-related cases of Zika disease have been \nconfirmed in the area. Most of the deaths came from flower town bee farm, a \ncompany in Summer-ville that sells bees and honey products, Juanita Stanley who \nowns the company said the farm looks like it\u2019s been destroyed, the farm lost \nabout 2.5 million bees. Dorchester County officials apologized for the \naccidental mass killing of bees. Dorchester County is aware that some beekeepers \nin the area that was sprayed on Sunday lost their bee colonies. County Manager \nJason Ward said in a statement: I\u2019m not pleased that so many bees were killed.","questions":[{"name":"question_1","title":"Why was spraying operations carried out in Dorchester County","answers":["People were concerned about the number of bees.","Several cases of Zika disease had been identified.","Two million bees were infected with disease.","Zika virus had destroyed some bee farms."]},{"name":"question_2","title":"Why does the news reports say about flower town bee farm?","answers":["It apologized to its customers. ","It was forced to kill its bees.","It lost a huge stock of bees.","It lost 2.5 million dollars."]}]},{"id":"cet4_20180601_listening_news_3","name":"News Report Three","text":"The world\u2019s largest aircraft has taken to the skies for the first time. The \nAir-Lander 10 spent nearly two hours in the air, having taken off from \nCardington airfield in Bedfordshire. During its flight, it reached 3000 feet and \nperformed a series of gentle turns all over a safe area. The aircraft is massive \nas long as a football field and as tall as six double decker buses and capable \nof flying for up to five days. It was first developed for the U.S.government as \na long-range spy aircraft but was abandoned following budget cutbacks. The \naircraft cost 25 million pounds and can carry heavier loads than huge jet planes \nwhile also producing less noise and emitting less pollution. The makers believe \nit\u2019s the future of aircraft and one day we\u2019ll be using them to go places. But \nthere\u2019s still a long way to go. The air lander will need to have two hundred \nhours flying time before being allowed to fly by the Aviation Administration. If \nit passes though we can hope we\u2019ll all get some extra leg room.","questions":[{"name":"question_1","title":"What do we learn about the first flight of the Air-Lander 10?","answers":["It stayed in the air for about two hours.","It took off and landed on a football field.","It proved to be of high commercial value.","It made a series of sharp turns in the sky."]},{"name":"question_2","title":"What caused the U.S. government to abandon the Air-Lander 10 as a spy aircraft?","answers":["Engineering problems.","The air pollution it produced.","Inadequate funding.","The opposition from the military"]},{"name":"question_3","title":"What is the advantage of Air-Lander 10 over huge jet planes?","answers":["It uses the latest aviation technology.","It flies faster than a commercial jet.","It is a safer means of transportation.","It is more environmentally friendly."]}]}],"conversation":[{"id":"cet4_20180601_listening_conversation_1","name":"Conversation One","text":"M:Do you feel like going out tonight?\n\n\nW:Yeah, why not? We haven\u2019t been out for ages.\n\n\nM:What a shame. Well, there is a film about climate change. Does it sound \ngood to you?\n\n\nW:No, not really. It doesn\u2019t really appeal to me. What is it about? Just \nclimate change?\n\n\nM:I think it\u2019s about how climate change affects everyday life. I wonder how \nthey make it entertaining.\n\n\nW:Well, it sounds really awful. It\u2019s an important subject, I agree. But I\u2019m \nnot in the mood for anything depressing. What else is on?\n\n\nM:There\u2019s a Spanish Dance Festival.\n\n\nW:Oh, I love dance. That sounds really interesting.\n\n\nM:Apparently, it\u2019s absolutely brilliant. Let\u2019s see what it says in the \npaper,\u201cAnna Gomez leads in an exciting production of the great Spanish love \nstory, Carmen.\u201d\n\n\nW:OK, then what time is it on?\n\n\nM:At 7:30. Well, that\u2019s no good. We haven\u2019t got enough time to get there. Is \nthere anything else?\n\n\nM:There is a comedy special on.\n\n\nW: Where\u2019s it on? It\u2019s at the City Theatre. It\u2019s a charity comedy night with \nlots of different acts. It looks pretty good. The critic in the local papers \nsays it\u2019s the funniest thing he\u2019s ever seen. It says here Roger Whitehead is an \namazing host to a night of foreign performances.\n\n\nW: Emm...I\u2019m not keen on him. He\u2019s not very funny.\n\n\nM:Are you sure you fancy going out tonight? You\u2019re not very enthusiastic.\n\n\nW:Perhaps you\u2019re right. OK. Let\u2019s go see the dance. But tomorrow, not \ntonight.\n\n\nM: Great. I\u2019ll book the tickets online.","questions":[{"name":"question_1","title":"What does the woman think of climate change?","answers":["It seems a depressing topic.","It sounds quite alarming.","It has little impact on our daily life. ","It is getting more serious these days."]},{"name":"question_2","title":"Why did the speakers give up going to the Spanish Dance Festival tonight?","answers":["The man doesn't understand Spanish.","The woman doesn't really like dancing.","They don't want something too noisy.","They can't make it to the theatre in time."]},{"name":"question_3","title":"What does the critic say about the comedy performed at the City Theatre?","answers":["It would be more fun without Mr. Whitehead hosting.","It has too many acts to hold the audience's attention.","It is the most amusing show he has ever watched.","It is a show inappropriate for a night of charity."]},{"name":"question_4","title":"What does the woman decide to do tomorrow?","answers":["Watch a comedy. ","Go and see the dance.","Book the tickets online. ","See a film with the man."]}]},{"id":"cet4_20180601_listening_conversation_2","name":"Conversation Two","text":"W:Good morning, Mr. Lee. May I have a minute of your time?\n\n\nM:Sure, Catherine. What can I do for you?\n\n\nW:I\u2019m quite anxious about transferring over to your college. I\u2019m afraid I \nwon\u2019t fit in.\n\n\nM:Don\u2019t worry, Catherine. It\u2019s completely normal for you to be nervous about \ntransferring schools. This happens to many transfer students.\n\n\nW:Yes, I know, but I\u2019m younger than most of the students in my year. And that \nworries me a lot.\n\n\nM:Well, you may be the only younger one in your year, but you know, we have a \nlot of after-school activities you can join in. And so, this way you\u2019ll be able \nto meet new friends of different age groups.\n\n\nW:That\u2019s nice. I love games and hobby groups.\n\n\nM:I\u2019m sure you do. So you\u2019ll be just fine. Don\u2019t worry so much and try to \nmake the most of what we have on offer here. Also, remember that you can come to \nme anytime of the day if you need help.\n\n\nW:Thanks so much. I definitely feel better now. As a matter of fact, I\u2019ve \nalready contacted one of the girls who\u2019d be living in the same house as me and \nshe seemed really nice. I guess living on campus I\u2019ll have a chance to have a \ncloser circle of friends since we\u2019ll be living together.\n\n\nM:All students are very friendly with new arrivals. Let me check who would be \nliving with you in your flat. OK. There are Hannah, Kelly and Bree. Bree is also \na new student here like you. I\u2019m sure you two will have more to share with each \nother.","questions":[{"name":"question_1","title":"Why does Catherine feel anxious?","answers":["Most of her schoolmates are younger than she is.","She simply has no idea what school to transfer to.","There are too many activities for her to cope with.","She worries she won't fit in as a transfer student."]},{"name":"question_2","title":"What does Mr. Lee encourage Catherine to do?","answers":["Seek advice from senior students.","Pick up some meaningful hobbies.","Participate in after-school activities.","Look into what the school offers."]},{"name":"question_3","title":"What does Mr. Lee promise to do for Catherine?","answers":["Give her help whenever she needs it.","Accept her as a transfer student.","Find her accommodation on campus.","Introduce her to her roommates."]},{"name":"question_4","title":"What do we learn about Catherine\u2019s schoolmate Bree?","answers":["She has interests similar to Mr. Lee's.","She has become friends with Catherine.","She has chosen the major Catherine has.","She has just transferred to the college."]}]}],"passage":[{"id":"cet4_20180601_listening_passage_1","name":"Passage One","text":"Have you ever felt like you would do just about anything to satisfy your \nhunger? A new study in mice may help to explain why hunger can feel like such a \npowerful motivating force. In the study, researchers found that hunger \noutweighed other physical drives including fear, thirst and social needs to \ndetermine which feeling won out. The researchers did a series of \nexperiments.\n\n\nIn one experiment, the mice were both hungry and thirsty. When given the \nchoice of either eating food or drinking water, the mice went for the food the \nresearchers found. However, when the mice were well-fed but thirsty they opted \nto drink according to the study.\n\n\nThe second experiment meant to pit the mice\u2019s hunger against their fear. \nHungry mice were placed in a cage that had certain Fox centered areas and other \nplaces that smelled safer. In other words, not like an animal that could eat \nthem but also had food. It turned out that when the mice were hungry they \nventured into the unsafe areas for food. But when the mice were well-fed they \nstayed in areas of the cage that were considered safe. Hunger also outweighed \nthe mice\u2019s social needs, the researchers found. Mice are usually social animals \nand prefer to be in the company of other mice according to the study. When the \nmice were hungry they opted to leave the company of other mice to go get \nfood.","questions":[{"name":"question_1","title":"What is the researchers\u2019 purpose in carrying out the Su\u2019s experiments with mice?","answers":["To investigate how being overweight impacts on health.","To find out which physical drive is the most powerful.","To discover what most mice like to eat.","To determine what feelings mice have."]},{"name":"question_2","title":"In what circumstances do mice venture into unsafe areas?","answers":["When they are hungry.","When they are thirsty.","When they smell food.","When they want company."]},{"name":"question_3","title":"What is said about mice at the end of the passage?","answers":["They search for food in groups.","They are overweight when food is plenty.","They prefer to be with other mice.","They enjoy the company of other animals."]}]},{"id":"cet4_20180601_listening_passage_2","name":"Passage Two","text":"The United States has one of the best highway systems in the world. \nInterstate highways connect just about every large and mid-sized city in the \ncountry. Did you ever wonder why such a complete system of excellent roads \nexists? For an answer, you would have to go back to the early 1920s. In those \nyears just after World War I, the military wanted to build an American highway \nsystem for national defense. Such a system could if necessary move troops \nquickly from one area to another. It could also get people out of cities in \ndanger of being bombed, so-called roads of national importance were designated, \nbut they were mostly small country roads. In 1944 Congress passed a bill to \nupgrade the system but did not fund the plan right away. In the 1950s, the plan \nbegan to become a reality. Over 25 billion dollars was appropriated by Congress \nand construction began on about 40,000 miles of new roads. The idea was to \nconnect the new system to existing expressways and freeways. And though the \nsystem was built mostly to make car travel easier, defense was not forgotten. \nFor instance, highway overpasses had to be high enough to allow trailers \ncarrying military missiles to pass under them. By 1974, this system was mostly \ncompleted a few additional roads would come later. Quick and easy travel between \nall parts of the country was now possible.","questions":[{"name":"question_1","title":"What does the speaker say about the American highway system?","answers":["Its construction started before World War I.","Its construction cost more than $ 40 billion.","It is efficiently used for transport.","It is one of the best in the world."]},{"name":"question_2","title":"What was the original purpose of building a highway system?","answers":["To improve transportation in the countryside.","To move troops quickly from place to place.","To enable people to travel at a higher speed.","To speed up the transportation of goods."]},{"name":"question_3","title":"When was the interstate highway system mostly completed?","answers":["In the 1970s.","In the 1960s. ","In the 1950s. ","In the 1940s."]}]},{"id":"cet4_20180601_listening_passage_3","name":"Passage Three","text":"Texting while driving was listed as a major cause of road deaths among young \nAmericans back in 2013. A recent study said that 40 percent of American teens \nclaimed to have been in a car when the driver used a cell phone in a way that \nput people in danger. This sounds like a widespread disease but it\u2019s one that \ntechnology may now help to cure. T.J. Evert, a 20-year-old inventor, has come up \nwith a novel solution that could easily put texting drivers on notice. It\u2019s \ncalled Smart Wheel and it\u2019s designed to fit over the steering wheel of most \nstandard vehicles to track whether or not the driver has two hands on the wheel \nat all times. Evert\u2019s invention warns the drivers with a light and a sound when \nthey hold the wheel with one hand only. But as soon as they place the other hand \nback on the wheel the light turns back to green and the sound stops. It also \nwatches for what\u2019s called \u201cclose by hands\u201dwhere both hands are close together \nnear the top of the wheel, so the driver can type with both thumbs and drive at \nthe same time. All the data smart wheel collects is also sent to a connected \napp, so any parents who install smart wheel can keep track of the teen\u2019s driving \nhabits. If they try to remove or damage the cover, that\u2019s reported as well.","questions":[{"name":"question_1","title":"What is a major cause of road deaths among young Americans?","answers":["Chatting while driving. ","Messaging while driving.","Driving under age. ","Speeding on highways."]},{"name":"question_2","title":"What is Smart Wheel?","answers":["A gadget to hold a phone on the steering wheel.","A gadget to charge the phone in a car.","A device to control the speed of a vehicle.","A device to ensure people drive with both hands."]},{"name":"question_3","title":"What happens if the driver has one hand on the wheel?","answers":["The car keeps flashing its headlights.","The car slows down gradually to a halt.","They are alerted with a light and a sound.","They get a warning on their smart phone."]},{"name":"question_4","title":"How do parents keep track of their teen\u2019s driving habits?","answers":["Installing a camera. ","Using a connected app.","Checking their emails. ","Keeping a daily record."]}]}]}
* reading : {"id":"cet4_20180601_reading","name":"2018年6月第一套英语四级真题-阅读","section_a":{"id":"cet4_20180601_reading_section_a","text":"An office tower on Miller Street in Manchester is completely covered in solar panels. They are used to create some of the energy used by the insurance company inside. When the tower was first 26 in 1962, it was covered with thin square stones. These small square stones became a problem for the building and continued to fall off the face for 40 years until a major renovation was 27 . During this renovation the building s owners, CIS, 28 the solar panel company, Solarcentury. They agreed to cover the entire building in solar panels. In 2004, the completed CIS tower became Europe s largest 29 of vertical solar panels. A vertical solar project on such a large 30 has never been repeated since.Covering a skyscraper with solar panels had never been done before, and the CIS tower was chosen as one of the \"10 best green energy projects\". For a long time after this renovation project, it was the tallest building in the United Kingdom, but it was 31 overtaken by the Millbank Tower.Green buildings like this aren t 32 cost-efficient for the investor, but it does produce much less pollution than that caused by energy 33 through fossil fuels. As solar panels get 34 , the world is likely to see more skyscrapers covered in solar panels, collecting energy much like trees do. Imagine a world where building the tallest skyscraper wasn t a race of 35 , but rather one to collect the most solar energy.","words":["cheaper","cleaner","collection","competed","constructed","consulted","dimension","discovered","eventually","height","necessarily","production","range","scale","undertaken"]},"section_b":{"id":"cet4_20180601_reading_section_b","title":"Some College Students Are Angry That They Have to Pay to Do Their Homework","text":"A) Digital learning systems now charge students for access codes needed to complete coursework, take quizzes, and turn in homework. As universities go digital, students are complaining of a new hit to their finances that s replacing\u2014and sometimes joining\u2014expensive textbooks: pricey online access codes that are required to complete coursework and submit assignments.B) The codes\u2014which typically range in price from $ 80 to $ 155 per course\u2014give students online access to systems developed by education companies like McGraw Hill and Pearson. These companies, which long reaped big profits as textbook publishers, have boasted that their new online offerings, when pushed to students through universities they partner with, represent the future of the industry.\nC) But critics say the digital access codes represent the same profit-seeking ethos (观念) of the textbook business, and are even harder for students to opt out of. While they could once buy second-hand textbooks, or share copies with friends, the digital systems are essentially impossible to avoid.\nD) \"When we talk about the access code we see it as the new face of the textbook monopoly (垄断), a new way to lock students around this system,\" said Ethan Senack, the higher education advocate for the U.S. Public Interest Research Group, to BuzzFeed News. \"Rather than $250 (for a print textbook) you re paying $ 120,\" said Senack. \"But because it s all digital it eliminates the used book market and eliminates any sharing and because homework and tests are through an access code, it eliminates any ability to opt out.\"\nE) Sarina Harpet, a 19-year-old student at Virginia Tech, was faced with a tough dilemma when she first started college in 2015\u2014pay rent or pay to turn in her chemistry homework. She told BuzzFeed News that her freshman chemistry class required her to use Connect, a system provided by McGraw Hill where students can submit homework, take exams and track their grades. But the code to access the program cost $ 120\u2014a big sum for Harper, who had already put down $ 450 for textbooks, and had rent day approaching.\nF) She decided to wait for her next work-study paycheck, which was typically $ 150- $ 200, to pay for the code. She knew that her chemistry grade may take a dive as a result. \"It s a balancing act,\" she said. \"Can I really afford these access codes now?\" She didn t hand in her first two assignments for chemistry, which started her out in the class with a failing grade.\nG) The access codes may be another financial headache for students, but for textbook businesses, they re the future. McGraw Hill, which controls 21% of the higher education market, reported in March that its digital content sales exceeded print sales for the first time in 2015. The company said that 45% of its $ 140 million revenue in 2015 \"was derived from digital products.\"\nH) A Pearson spokesperson told BuzzFeed News that \"digital materials are less expensive and a good investment\" that offer new features, like audio texts, personalized knowledge checks and expert videos. Its digital course materials save students up to 60% compared to traditional printed textbooks, the company added. McGraw Hill didn t respond to a request for comment, but its CEO David Levin told the Financial Times in August that \"in higher education, the era of the printed textbook is now over.\"\nI) The textbook industry insists the online systems represent a better deal for students. \"These digital products aren t just mechanisms for students to submit homework, they offer all kinds of features,\" David Anderson, the executive director of higher education with the Association of American Publishers, told BuzzFeed News. \"It helps students understand in a way that you can t do with print homework assignments.\"\nJ) David Hunt, an associate professor in sociology at Augusta University, which has rolled out digital textbooks across its math and psychology departments, told BuzzFeed News that he understands the utility of using systems that require access codes. But he doesn t require his students to buy access to a learning program that controls the class assignments. \"I try to make things as inexpensive as possible,\" said Hunt, who uses free digital textbooks for his classes but designs his own curriculum. \"The online systems may make my life a lot easier but I feel like I m giving up control. The discussions are the things where my expertise can benefit the students most.\"\nK) A 20-year-old junior at Georgia Southern University told BuzzFeed News that she normally spends $ 500-$ 600 on access codes for class. In one case, the professor didn t require students to buy a textbook, just an access code to turn in homework. This year she said she spent $ 900 on access codes to books and programs. \"That s two months of rent,\" she said. \"You can t sell any of it back. With a traditional textbook you can sell it for $ 30 - $ 50 and that helps to pay for your new semester s books. With an access code, you re out of that money. \"\nL) Benjamin Wolverton, a 19-year-old student at the University of South Carolina, told BuzzFeed News that \"it s ridiculous that after paying tens of thousands in tuition we have to pay for all these access codes to do our homework.\" Many of the access codes he s purchased have been required simply to complete homework or quizzes. \"Often it s only 10% of your grade in class.\" he said. \"You re paying so much money for something that hardly affects your grade\u2014but if you didn t have it, it would affect your grades enough. It would be bad to start out at a B or C.\" Wolverton said he spent $ 500 on access codes for digital books and programs this semester.\nM) Harper, a poultry (家禽) science major, is taking chemistry again this year and had to buy a new access code to hand in her homework. She rented her economics and statistics textbooks for about $ 20 each. But her access codes for homework, which can t be rented or bought second-hand, were her most expensive purchases: $ 120 and $ 85.\nN) She still remembers the sting of her first experience skipping an assignment due to the high prices. \"We don t really have a missed assignment policy,\" she said. \"If you miss it, you just miss it. I just got zeros on a couple of first assignments. I managed to pull everything back up. But as a scared freshman looking at their grades, it s not fun.\"","questions":["A student s yearly expenses on access codes may amount to their rent for two months.","The online access codes may be seen as a way to tie the students to the digital system.","If a student takes a course again, they may have to buy a new access code to submit their assignments.","McGraw Hill accounts for over one-fifth of the market share of college textbooks.","Many traditional textbook publishers are now offering online digital products, which they believe will be the future of the publishing business.","One student complained that they now had to pay for access codes in addition to the high tuition.","Digital materials can cost students less than half the price of traditional printed books according to a publisher.","One student decided not to buy her access code until she received the pay for her part-time job.","Online systems may deprive teachers of opportunities to make the best use of their expertise for their students.","Digital access codes are criticized because they are profit-driven just like the textbook business."]},"section_c":[{"id":"cet4_20180601_reading_section_c_passage_1","name":"Passage One","text":"Losing your ability to think and remember is pretty scary. We know the risk of dementia (痴呆症) increases with age. But if you have memory slips, you probably needn t worry. There are pretty clear differences between signs of dementia and age-related memory loss.After age 50, it s quite common to have trouble remembering the names of people, places and things quickly, says Dr. Kirk Daffner of Brigham and Women s Hospital in Boston.\nThe brain ages just like the rest of the body. Certain parts shrink, especially areas in the brain that are important to learning, memory and planning. Changes in brain cells can affect communication between different regions of the brain. And blood flow can be reduced as blood vessels narrow.\nForgetting the name of an actor in a favorite movie, for example, is nothing to worry about. But if you forget the plot of the movie or don t remember even seeing it, that s far more concerning, Daffner says.\nWhen you forget entire experiences, he says, that s \"a red flag that something more serious may be involved.\" Forgetting how to operate a familiar object like a microwave oven, or forgetting how to drive to the house of a friend you ve visited many times before can also be signs of something going wrong.\nBut even then, Daffner says, people shouldn t panic. There are many things that can cause confusion and memory loss, including health problems like temporary stoppage of breathing during sleep, high blood pressure, or depression, as well as medications (药物) like antidepressants.\nYou don t have to figure this out on your own. Daffner suggests going to your doctor to check on medications, health problems and other issues that could be affecting memory. And the best defense against memory loss is to try to prevent it by building up your brain s cognitive (认知的) reserve, Daffner says.\n\"Read books, go to movies, take on new hobbies or activities that force one to think in novel ways,\" he says. In other words, keep your brain busy and working. And also get physically active, because exercise is a known brain booster.","questions":[{"name":"question_1","title":"Why does the author say that one needn t be concerned about memory slips?","answers":["Not all of them are symptoms of dementia.","They occur only among certain groups of people.","Not all of them are related to one s age.","They are quite common among fifty-year-olds."]},{"name":"question_2","title":"What happens as we become aged according to the passage?","answers":["Our interaction skills deteriorate.","Some parts of our brain stop functioning.","Communication within our brain weakens.","Our whole brain starts shrinking."]},{"name":"question_3","title":"Which memory-related symptom should people take seriously?","answers":["Totally forgetting how to do one s daily routines.","Inability to recall details of one s life experiences.","Failure to remember the names of movies or actors.","Occasionally confusing the addresses of one s friends."]},{"name":"question_4","title":"What should people do when signs of serious memory loss show up?","answers":["Check the brain s cognitive reserve. ","Stop medications affecting memory. ","Turn to a professional for assistance.","Exercise to improve their well-being."]},{"name":"question_5","title":"What is Dr. Daffner s advice for combating memory loss?","answers":["Having regular physical and mental checkups.","Taking medicine that helps boost one s brain.","Engaging in known memory repair activities.","Staying active both physically and mentally."]}]},{"id":"cet4_20180601_reading_section_c_passage_2","name":"Passage Two","text":"A letter written by Charles Darwin in 1875 has been returned to the Smithsonian \nInstitution Archives (档案馆) by the FBI after being stolen twice.\n\"We realized \nin the mid-1970s that it was missing,\" says Effie Kapsalis, head of the \nSmithsonian Insitution Archives. \"It was noted as missing and likely taken by an \nintern (实习生), from what the FBI is telling us. Word got out that it was missing \nwhen someone asked to see the letter for research purposes,\" and the intern put \nthe letter back. \"The intern likely took the letter again once nobody was \nwatching it.\"\nDecades passed. Finally, the FBI received a tip that the stolen \ndocument was located very close to Washington, D.C. Their art crime team \nrecovered the letter but were unable to press charges because the time of \nlimitations had ended. The FBI worked closely with the Archives to determine \nthat the letter was both authentic and definitely Smithsonian s property.\nThe \nletter was written by Darwin to thank an American geologist, Dr. Ferdinand \nVandeveer Hayden, for sending him copies of his research into the geology of the \nregion that would become Yellowstone National Park.\nThe letter is in fairly \ngood condition, in spite of being out of the care of trained museum staff for so \nlong. \"It was luckily in good shape,\" says Kapsalis, \"and we just have to do \nsome minor things in order to be able to unfold it. It has some glue on it that \nhas colored it slightly, but nothing that will prevent us from using it. After \nit is repaired, we will take digital photos of it and that will be available \nonline. One of our goals is to get items of high research value or interest to \nthe public online.\"\nIt would now be difficult for an intern, visitor or a \nthief to steal a document like this. \"Archiving practices have changed greatly \nsince the 1970s,\" says Kapsalis, \"and we keep our high value documents in a safe \nthat I don t even have access to.\"","questions":[{"name":"question_1","title":"What happened to Darwin s letter in the 1970s?","answers":["It was recovered by the FBI.","It was stolen more than once.","It was put in the archives for research purposes.","It was purchased by the Smithsonian Archives."]},{"name":"question_2","title":"What did the FBI do after the recovery of the letter?","answers":["They proved its authenticity. ","They kept it in a special safe.","They arrested the suspect immediately.","They pressed criminal charges in vain."]},{"name":"question_3","title":"What is Darwin s letter about?","answers":["The evolution of Yellowstone National Park.","His cooperation with an American geologist.","Some geological evidence supporting his theory.","His acknowledgement of help from a professional."]},{"name":"question_4","title":"What will the Smithsonian Institution Archives do with the letter according to \nKapsalis?","answers":["Reserve it for research purposes only. ","Turn it into an object of high interest.","Keep it a permanent secret. ","Make it available online."]},{"name":"question_5","title":"What has the past half century witnessed according to Kapsalis?","answers":["Growing interest in rare art objects.","Radical changes in archiving practices.","Recovery of various missing documents.","Increases in the value of museum exhibits."]}]}]}
* trans : {"id":"cet4_20180601_trans","name":"2018年6月第一套英语四级真题-翻译","title":"Directions: For this part, you are allowed 30 minutes to translate a passage from Chinese into English. You should write your answer on Answer Sheet 2.","text":"过去,乘飞机出行对大多数中国人来说是难以想象的。如今,随着经济的发展和生活水平的提高,越来越多的中国人包括许多农民和外出务工人员都能乘飞机出行。他们可以乘飞机到达所有大城市,还有很多城市也在筹建机场。航空服务不断改进,而且经常会有廉价机票。近年来,节假日期间选择乘飞机外出旅游的人数在不断增加。"}
* writing : {"id":"cet4_20180601_writing","name":"2018年6月第一套英语四级真题-写作","title":"Directions: For this part, you are allowed 30 minutes to write a short essay on the importance of reading ability and how to develop it. You should write at least 120 words but no more than 180 words."}
*/
private String id;
private String name;
private ListeningBean listening;
private ReadingBean reading;
private TransBean trans;
private WritingBean writing;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ListeningBean getListening() {
return listening;
}
public void setListening(ListeningBean listening) {
this.listening = listening;
}
public ReadingBean getReading() {
return reading;
}
public void setReading(ReadingBean reading) {
this.reading = reading;
}
public TransBean getTrans() {
return trans;
}
public void setTrans(TransBean trans) {
this.trans = trans;
}
public WritingBean getWriting() {
return writing;
}
public void setWriting(WritingBean writing) {
this.writing = writing;
}
public static class ListeningBean {
/**
* id : cet4_20180601_listening
* name : 2018年6月第一套英语四级真题-听力
* news : [{"id":"cet4_20180601_listening_news_1","name":"News Report One","text":"A Message in a bottle sent out to sea by a New Hampshire man more than five decades ago was found 1,500 miles away and has been returned to his daughter. The long lost message was discovered by Clint Buffington of Utah while he was vacationing. Buffington says he found a soda bottle half buried in the sand that looked like it had been there since the beginning of time. The note inside the bottles said, \u201creturn to 419 Ocean Street and receive a reward of $150 from Richard and Tina Pierce, owners of the Beach comber motel.\u201d The motel was owned by the parents of Paula Pierce in 1960. Her father had written the note as a joke and had thrown it into the Atlantic Ocean. Buffington flew to New Hampshire to deliver the message to Paula Pierce. She held up to her father\u2019s promise giving Buffington that reward, but the biggest reward is the message in a bottle finding its way back home.","questions":[{"name":"question_1","title":"What is the news report mainly about?","answers":["The return of a bottled message to its owner's daughter.","A New Hampshire man's joke with friends on his wife.","A father's message for his daughter.","The history of a century-old motel."]},{"name":"question_2","title":"Why did Pollard Pearce give Clint Buffington the reward?","answers":["She wanted to show gratitude for his kindness.","She wanted to honor her father's promise.","She had been asked by her father to do so.","She was excited to see her father's handwriting."]}]},{"id":"cet4_20180601_listening_news_2","name":"News Report two","text":"Millions of bees have died in South Carolina during aerial insect spraying \noperations that were carried out to combat the Zika virus. The insect spraying \nover the weekend left more than 2 million bees dead on the spot in Dorchester \nCounty South Carolina, where four travel-related cases of Zika disease have been \nconfirmed in the area. Most of the deaths came from flower town bee farm, a \ncompany in Summer-ville that sells bees and honey products, Juanita Stanley who \nowns the company said the farm looks like it\u2019s been destroyed, the farm lost \nabout 2.5 million bees. Dorchester County officials apologized for the \naccidental mass killing of bees. Dorchester County is aware that some beekeepers \nin the area that was sprayed on Sunday lost their bee colonies. County Manager \nJason Ward said in a statement: I\u2019m not pleased that so many bees were killed.","questions":[{"name":"question_1","title":"Why was spraying operations carried out in Dorchester County","answers":["People were concerned about the number of bees.","Several cases of Zika disease had been identified.","Two million bees were infected with disease.","Zika virus had destroyed some bee farms."]},{"name":"question_2","title":"Why does the news reports say about flower town bee farm?","answers":["It apologized to its customers. ","It was forced to kill its bees.","It lost a huge stock of bees.","It lost 2.5 million dollars."]}]},{"id":"cet4_20180601_listening_news_3","name":"News Report Three","text":"The world\u2019s largest aircraft has taken to the skies for the first time. The \nAir-Lander 10 spent nearly two hours in the air, having taken off from \nCardington airfield in Bedfordshire. During its flight, it reached 3000 feet and \nperformed a series of gentle turns all over a safe area. The aircraft is massive \nas long as a football field and as tall as six double decker buses and capable \nof flying for up to five days. It was first developed for the U.S.government as \na long-range spy aircraft but was abandoned following budget cutbacks. The \naircraft cost 25 million pounds and can carry heavier loads than huge jet planes \nwhile also producing less noise and emitting less pollution. The makers believe \nit\u2019s the future of aircraft and one day we\u2019ll be using them to go places. But \nthere\u2019s still a long way to go. The air lander will need to have two hundred \nhours flying time before being allowed to fly by the Aviation Administration. If \nit passes though we can hope we\u2019ll all get some extra leg room.","questions":[{"name":"question_1","title":"What do we learn about the first flight of the Air-Lander 10?","answers":["It stayed in the air for about two hours.","It took off and landed on a football field.","It proved to be of high commercial value.","It made a series of sharp turns in the sky."]},{"name":"question_2","title":"What caused the U.S. government to abandon the Air-Lander 10 as a spy aircraft?","answers":["Engineering problems.","The air pollution it produced.","Inadequate funding.","The opposition from the military"]},{"name":"question_3","title":"What is the advantage of Air-Lander 10 over huge jet planes?","answers":["It uses the latest aviation technology.","It flies faster than a commercial jet.","It is a safer means of transportation.","It is more environmentally friendly."]}]}]
* conversation : [{"id":"cet4_20180601_listening_conversation_1","name":"Conversation One","text":"M:Do you feel like going out tonight?\n\n\nW:Yeah, why not? We haven\u2019t been out for ages.\n\n\nM:What a shame. Well, there is a film about climate change. Does it sound \ngood to you?\n\n\nW:No, not really. It doesn\u2019t really appeal to me. What is it about? Just \nclimate change?\n\n\nM:I think it\u2019s about how climate change affects everyday life. I wonder how \nthey make it entertaining.\n\n\nW:Well, it sounds really awful. It\u2019s an important subject, I agree. But I\u2019m \nnot in the mood for anything depressing. What else is on?\n\n\nM:There\u2019s a Spanish Dance Festival.\n\n\nW:Oh, I love dance. That sounds really interesting.\n\n\nM:Apparently, it\u2019s absolutely brilliant. Let\u2019s see what it says in the \npaper,\u201cAnna Gomez leads in an exciting production of the great Spanish love \nstory, Carmen.\u201d\n\n\nW:OK, then what time is it on?\n\n\nM:At 7:30. Well, that\u2019s no good. We haven\u2019t got enough time to get there. Is \nthere anything else?\n\n\nM:There is a comedy special on.\n\n\nW: Where\u2019s it on? It\u2019s at the City Theatre. It\u2019s a charity comedy night with \nlots of different acts. It looks pretty good. The critic in the local papers \nsays it\u2019s the funniest thing he\u2019s ever seen. It says here Roger Whitehead is an \namazing host to a night of foreign performances.\n\n\nW: Emm...I\u2019m not keen on him. He\u2019s not very funny.\n\n\nM:Are you sure you fancy going out tonight? You\u2019re not very enthusiastic.\n\n\nW:Perhaps you\u2019re right. OK. Let\u2019s go see the dance. But tomorrow, not \ntonight.\n\n\nM: Great. I\u2019ll book the tickets online.","questions":[{"name":"question_1","title":"What does the woman think of climate change?","answers":["It seems a depressing topic.","It sounds quite alarming.","It has little impact on our daily life. ","It is getting more serious these days."]},{"name":"question_2","title":"Why did the speakers give up going to the Spanish Dance Festival tonight?","answers":["The man doesn't understand Spanish.","The woman doesn't really like dancing.","They don't want something too noisy.","They can't make it to the theatre in time."]},{"name":"question_3","title":"What does the critic say about the comedy performed at the City Theatre?","answers":["It would be more fun without Mr. Whitehead hosting.","It has too many acts to hold the audience's attention.","It is the most amusing show he has ever watched.","It is a show inappropriate for a night of charity."]},{"name":"question_4","title":"What does the woman decide to do tomorrow?","answers":["Watch a comedy. ","Go and see the dance.","Book the tickets online. ","See a film with the man."]}]},{"id":"cet4_20180601_listening_conversation_2","name":"Conversation Two","text":"W:Good morning, Mr. Lee. May I have a minute of your time?\n\n\nM:Sure, Catherine. What can I do for you?\n\n\nW:I\u2019m quite anxious about transferring over to your college. I\u2019m afraid I \nwon\u2019t fit in.\n\n\nM:Don\u2019t worry, Catherine. It\u2019s completely normal for you to be nervous about \ntransferring schools. This happens to many transfer students.\n\n\nW:Yes, I know, but I\u2019m younger than most of the students in my year. And that \nworries me a lot.\n\n\nM:Well, you may be the only younger one in your year, but you know, we have a \nlot of after-school activities you can join in. And so, this way you\u2019ll be able \nto meet new friends of different age groups.\n\n\nW:That\u2019s nice. I love games and hobby groups.\n\n\nM:I\u2019m sure you do. So you\u2019ll be just fine. Don\u2019t worry so much and try to \nmake the most of what we have on offer here. Also, remember that you can come to \nme anytime of the day if you need help.\n\n\nW:Thanks so much. I definitely feel better now. As a matter of fact, I\u2019ve \nalready contacted one of the girls who\u2019d be living in the same house as me and \nshe seemed really nice. I guess living on campus I\u2019ll have a chance to have a \ncloser circle of friends since we\u2019ll be living together.\n\n\nM:All students are very friendly with new arrivals. Let me check who would be \nliving with you in your flat. OK. There are Hannah, Kelly and Bree. Bree is also \na new student here like you. I\u2019m sure you two will have more to share with each \nother.","questions":[{"name":"question_1","title":"Why does Catherine feel anxious?","answers":["Most of her schoolmates are younger than she is.","She simply has no idea what school to transfer to.","There are too many activities for her to cope with.","She worries she won't fit in as a transfer student."]},{"name":"question_2","title":"What does Mr. Lee encourage Catherine to do?","answers":["Seek advice from senior students.","Pick up some meaningful hobbies.","Participate in after-school activities.","Look into what the school offers."]},{"name":"question_3","title":"What does Mr. Lee promise to do for Catherine?","answers":["Give her help whenever she needs it.","Accept her as a transfer student.","Find her accommodation on campus.","Introduce her to her roommates."]},{"name":"question_4","title":"What do we learn about Catherine\u2019s schoolmate Bree?","answers":["She has interests similar to Mr. Lee's.","She has become friends with Catherine.","She has chosen the major Catherine has.","She has just transferred to the college."]}]}]
* passage : [{"id":"cet4_20180601_listening_passage_1","name":"Passage One","text":"Have you ever felt like you would do just about anything to satisfy your \nhunger? A new study in mice may help to explain why hunger can feel like such a \npowerful motivating force. In the study, researchers found that hunger \noutweighed other physical drives including fear, thirst and social needs to \ndetermine which feeling won out. The researchers did a series of \nexperiments.\n\n\nIn one experiment, the mice were both hungry and thirsty. When given the \nchoice of either eating food or drinking water, the mice went for the food the \nresearchers found. However, when the mice were well-fed but thirsty they opted \nto drink according to the study.\n\n\nThe second experiment meant to pit the mice\u2019s hunger against their fear. \nHungry mice were placed in a cage that had certain Fox centered areas and other \nplaces that smelled safer. In other words, not like an animal that could eat \nthem but also had food. It turned out that when the mice were hungry they \nventured into the unsafe areas for food. But when the mice were well-fed they \nstayed in areas of the cage that were considered safe. Hunger also outweighed \nthe mice\u2019s social needs, the researchers found. Mice are usually social animals \nand prefer to be in the company of other mice according to the study. When the \nmice were hungry they opted to leave the company of other mice to go get \nfood.","questions":[{"name":"question_1","title":"What is the researchers\u2019 purpose in carrying out the Su\u2019s experiments with mice?","answers":["To investigate how being overweight impacts on health.","To find out which physical drive is the most powerful.","To discover what most mice like to eat.","To determine what feelings mice have."]},{"name":"question_2","title":"In what circumstances do mice venture into unsafe areas?","answers":["When they are hungry.","When they are thirsty.","When they smell food.","When they want company."]},{"name":"question_3","title":"What is said about mice at the end of the passage?","answers":["They search for food in groups.","They are overweight when food is plenty.","They prefer to be with other mice.","They enjoy the company of other animals."]}]},{"id":"cet4_20180601_listening_passage_2","name":"Passage Two","text":"The United States has one of the best highway systems in the world. \nInterstate highways connect just about every large and mid-sized city in the \ncountry. Did you ever wonder why such a complete system of excellent roads \nexists? For an answer, you would have to go back to the early 1920s. In those \nyears just after World War I, the military wanted to build an American highway \nsystem for national defense. Such a system could if necessary move troops \nquickly from one area to another. It could also get people out of cities in \ndanger of being bombed, so-called roads of national importance were designated, \nbut they were mostly small country roads. In 1944 Congress passed a bill to \nupgrade the system but did not fund the plan right away. In the 1950s, the plan \nbegan to become a reality. Over 25 billion dollars was appropriated by Congress \nand construction began on about 40,000 miles of new roads. The idea was to \nconnect the new system to existing expressways and freeways. And though the \nsystem was built mostly to make car travel easier, defense was not forgotten. \nFor instance, highway overpasses had to be high enough to allow trailers \ncarrying military missiles to pass under them. By 1974, this system was mostly \ncompleted a few additional roads would come later. Quick and easy travel between \nall parts of the country was now possible.","questions":[{"name":"question_1","title":"What does the speaker say about the American highway system?","answers":["Its construction started before World War I.","Its construction cost more than $ 40 billion.","It is efficiently used for transport.","It is one of the best in the world."]},{"name":"question_2","title":"What was the original purpose of building a highway system?","answers":["To improve transportation in the countryside.","To move troops quickly from place to place.","To enable people to travel at a higher speed.","To speed up the transportation of goods."]},{"name":"question_3","title":"When was the interstate highway system mostly completed?","answers":["In the 1970s.","In the 1960s. ","In the 1950s. ","In the 1940s."]}]},{"id":"cet4_20180601_listening_passage_3","name":"Passage Three","text":"Texting while driving was listed as a major cause of road deaths among young \nAmericans back in 2013. A recent study said that 40 percent of American teens \nclaimed to have been in a car when the driver used a cell phone in a way that \nput people in danger. This sounds like a widespread disease but it\u2019s one that \ntechnology may now help to cure. T.J. Evert, a 20-year-old inventor, has come up \nwith a novel solution that could easily put texting drivers on notice. It\u2019s \ncalled Smart Wheel and it\u2019s designed to fit over the steering wheel of most \nstandard vehicles to track whether or not the driver has two hands on the wheel \nat all times. Evert\u2019s invention warns the drivers with a light and a sound when \nthey hold the wheel with one hand only. But as soon as they place the other hand \nback on the wheel the light turns back to green and the sound stops. It also \nwatches for what\u2019s called \u201cclose by hands\u201dwhere both hands are close together \nnear the top of the wheel, so the driver can type with both thumbs and drive at \nthe same time. All the data smart wheel collects is also sent to a connected \napp, so any parents who install smart wheel can keep track of the teen\u2019s driving \nhabits. If they try to remove or damage the cover, that\u2019s reported as well.","questions":[{"name":"question_1","title":"What is a major cause of road deaths among young Americans?","answers":["Chatting while driving. ","Messaging while driving.","Driving under age. ","Speeding on highways."]},{"name":"question_2","title":"What is Smart Wheel?","answers":["A gadget to hold a phone on the steering wheel.","A gadget to charge the phone in a car.","A device to control the speed of a vehicle.","A device to ensure people drive with both hands."]},{"name":"question_3","title":"What happens if the driver has one hand on the wheel?","answers":["The car keeps flashing its headlights.","The car slows down gradually to a halt.","They are alerted with a light and a sound.","They get a warning on their smart phone."]},{"name":"question_4","title":"How do parents keep track of their teen\u2019s driving habits?","answers":["Installing a camera. ","Using a connected app.","Checking their emails. ","Keeping a daily record."]}]}]
*/
private String id;
private String name;
private List<NewsBean> news;
private List<ConversationBean> conversation;
private List<PassageBean> passage;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<NewsBean> getNews() {
return news;
}
public void setNews(List<NewsBean> news) {
this.news = news;
}
public List<ConversationBean> getConversation() {
return conversation;
}
public void setConversation(List<ConversationBean> conversation) {
this.conversation = conversation;
}
public List<PassageBean> getPassage() {
return passage;
}
public void setPassage(List<PassageBean> passage) {
this.passage = passage;
}
public static class NewsBean {
/**
* id : cet4_20180601_listening_news_1
* name : News Report One
* text : A Message in a bottle sent out to sea by a New Hampshire man more than five decades ago was found 1,500 miles away and has been returned to his daughter. The long lost message was discovered by Clint Buffington of Utah while he was vacationing. Buffington says he found a soda bottle half buried in the sand that looked like it had been there since the beginning of time. The note inside the bottles said, “return to 419 Ocean Street and receive a reward of $150 from Richard and Tina Pierce, owners of the Beach comber motel.” The motel was owned by the parents of Paula Pierce in 1960. Her father had written the note as a joke and had thrown it into the Atlantic Ocean. Buffington flew to New Hampshire to deliver the message to Paula Pierce. She held up to her father’s promise giving Buffington that reward, but the biggest reward is the message in a bottle finding its way back home.
* questions : [{"name":"question_1","title":"What is the news report mainly about?","answers":["The return of a bottled message to its owner's daughter.","A New Hampshire man's joke with friends on his wife.","A father's message for his daughter.","The history of a century-old motel."]},{"name":"question_2","title":"Why did Pollard Pearce give Clint Buffington the reward?","answers":["She wanted to show gratitude for his kindness.","She wanted to honor her father's promise.","She had been asked by her father to do so.","She was excited to see her father's handwriting."]}]
*/
private String id;
private String name;
private String text;
private List<QuestionsBean> questions;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<QuestionsBean> getQuestions() {
return questions;
}
public void setQuestions(List<QuestionsBean> questions) {
this.questions = questions;
}
public static class QuestionsBean {
/**
* name : question_1
* title : What is the news report mainly about?
* answers : ["The return of a bottled message to its owner's daughter.","A New Hampshire man's joke with friends on his wife.","A father's message for his daughter.","The history of a century-old motel."]
*/
private String name;
private String title;
private List<String> answers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getAnswers() {
return answers;
}
public void setAnswers(List<String> answers) {
this.answers = answers;
}
}
}
public static class ConversationBean {
/**
* id : cet4_20180601_listening_conversation_1
* name : Conversation One
* text : M:Do you feel like going out tonight?
W:Yeah, why not? We haven’t been out for ages.
M:What a shame. Well, there is a film about climate change. Does it sound
good to you?
W:No, not really. It doesn’t really appeal to me. What is it about? Just
climate change?
M:I think it’s about how climate change affects everyday life. I wonder how
they make it entertaining.
W:Well, it sounds really awful. It’s an important subject, I agree. But I’m
not in the mood for anything depressing. What else is on?
M:There’s a Spanish Dance Festival.
W:Oh, I love dance. That sounds really interesting.
M:Apparently, it’s absolutely brilliant. Let’s see what it says in the
paper,“Anna Gomez leads in an exciting production of the great Spanish love
story, Carmen.”
W:OK, then what time is it on?
M:At 7:30. Well, that’s no good. We haven’t got enough time to get there. Is
there anything else?
M:There is a comedy special on.
W: Where’s it on? It’s at the City Theatre. It’s a charity comedy night with
lots of different acts. It looks pretty good. The critic in the local papers
says it’s the funniest thing he’s ever seen. It says here Roger Whitehead is an
amazing host to a night of foreign performances.
W: Emm...I’m not keen on him. He’s not very funny.
M:Are you sure you fancy going out tonight? You’re not very enthusiastic.
W:Perhaps you’re right. OK. Let’s go see the dance. But tomorrow, not
tonight.
M: Great. I’ll book the tickets online.
* questions : [{"name":"question_1","title":"What does the woman think of climate change?","answers":["It seems a depressing topic.","It sounds quite alarming.","It has little impact on our daily life. ","It is getting more serious these days."]},{"name":"question_2","title":"Why did the speakers give up going to the Spanish Dance Festival tonight?","answers":["The man doesn't understand Spanish.","The woman doesn't really like dancing.","They don't want something too noisy.","They can't make it to the theatre in time."]},{"name":"question_3","title":"What does the critic say about the comedy performed at the City Theatre?","answers":["It would be more fun without Mr. Whitehead hosting.","It has too many acts to hold the audience's attention.","It is the most amusing show he has ever watched.","It is a show inappropriate for a night of charity."]},{"name":"question_4","title":"What does the woman decide to do tomorrow?","answers":["Watch a comedy. ","Go and see the dance.","Book the tickets online. ","See a film with the man."]}]
*/
private String id;
private String name;
private String text;
private List<QuestionsBeanX> questions;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<QuestionsBeanX> getQuestions() {
return questions;
}
public void setQuestions(List<QuestionsBeanX> questions) {
this.questions = questions;
}
public static class QuestionsBeanX {
/**
* name : question_1
* title : What does the woman think of climate change?
* answers : ["It seems a depressing topic.","It sounds quite alarming.","It has little impact on our daily life. ","It is getting more serious these days."]
*/
private String name;
private String title;
private List<String> answers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getAnswers() {
return answers;
}
public void setAnswers(List<String> answers) {
this.answers = answers;
}
}
}
public static class PassageBean {
/**
* id : cet4_20180601_listening_passage_1
* name : Passage One
* text : Have you ever felt like you would do just about anything to satisfy your
hunger? A new study in mice may help to explain why hunger can feel like such a
powerful motivating force. In the study, researchers found that hunger
outweighed other physical drives including fear, thirst and social needs to
determine which feeling won out. The researchers did a series of
experiments.
In one experiment, the mice were both hungry and thirsty. When given the
choice of either eating food or drinking water, the mice went for the food the
researchers found. However, when the mice were well-fed but thirsty they opted
to drink according to the study.
The second experiment meant to pit the mice’s hunger against their fear.
Hungry mice were placed in a cage that had certain Fox centered areas and other
places that smelled safer. In other words, not like an animal that could eat
them but also had food. It turned out that when the mice were hungry they
ventured into the unsafe areas for food. But when the mice were well-fed they
stayed in areas of the cage that were considered safe. Hunger also outweighed
the mice’s social needs, the researchers found. Mice are usually social animals
and prefer to be in the company of other mice according to the study. When the
mice were hungry they opted to leave the company of other mice to go get
food.
* questions : [{"name":"question_1","title":"What is the researchers\u2019 purpose in carrying out the Su\u2019s experiments with mice?","answers":["To investigate how being overweight impacts on health.","To find out which physical drive is the most powerful.","To discover what most mice like to eat.","To determine what feelings mice have."]},{"name":"question_2","title":"In what circumstances do mice venture into unsafe areas?","answers":["When they are hungry.","When they are thirsty.","When they smell food.","When they want company."]},{"name":"question_3","title":"What is said about mice at the end of the passage?","answers":["They search for food in groups.","They are overweight when food is plenty.","They prefer to be with other mice.","They enjoy the company of other animals."]}]
*/
private String id;
private String name;
private String text;
private List<QuestionsBeanXX> questions;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<QuestionsBeanXX> getQuestions() {
return questions;
}
public void setQuestions(List<QuestionsBeanXX> questions) {
this.questions = questions;
}
public static class QuestionsBeanXX {
/**
* name : question_1
* title : What is the researchers’ purpose in carrying out the Su’s experiments with mice?
* answers : ["To investigate how being overweight impacts on health.","To find out which physical drive is the most powerful.","To discover what most mice like to eat.","To determine what feelings mice have."]
*/
private String name;
private String title;
private List<String> answers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getAnswers() {
return answers;
}
public void setAnswers(List<String> answers) {
this.answers = answers;
}
}
}
}
public static class ReadingBean {
/**
* id : cet4_20180601_reading
* name : 2018年6月第一套英语四级真题-阅读
* section_a : {"id":"cet4_20180601_reading_section_a","text":"An office tower on Miller Street in Manchester is completely covered in solar panels. They are used to create some of the energy used by the insurance company inside. When the tower was first 26 in 1962, it was covered with thin square stones. These small square stones became a problem for the building and continued to fall off the face for 40 years until a major renovation was 27 . During this renovation the building s owners, CIS, 28 the solar panel company, Solarcentury. They agreed to cover the entire building in solar panels. In 2004, the completed CIS tower became Europe s largest 29 of vertical solar panels. A vertical solar project on such a large 30 has never been repeated since.Covering a skyscraper with solar panels had never been done before, and the CIS tower was chosen as one of the \"10 best green energy projects\". For a long time after this renovation project, it was the tallest building in the United Kingdom, but it was 31 overtaken by the Millbank Tower.Green buildings like this aren t 32 cost-efficient for the investor, but it does produce much less pollution than that caused by energy 33 through fossil fuels. As solar panels get 34 , the world is likely to see more skyscrapers covered in solar panels, collecting energy much like trees do. Imagine a world where building the tallest skyscraper wasn t a race of 35 , but rather one to collect the most solar energy.","words":["cheaper","cleaner","collection","competed","constructed","consulted","dimension","discovered","eventually","height","necessarily","production","range","scale","undertaken"]}
* section_b : {"id":"cet4_20180601_reading_section_b","title":"Some College Students Are Angry That They Have to Pay to Do Their Homework","text":"A) Digital learning systems now charge students for access codes needed to complete coursework, take quizzes, and turn in homework. As universities go digital, students are complaining of a new hit to their finances that s replacing\u2014and sometimes joining\u2014expensive textbooks: pricey online access codes that are required to complete coursework and submit assignments.B) The codes\u2014which typically range in price from $ 80 to $ 155 per course\u2014give students online access to systems developed by education companies like McGraw Hill and Pearson. These companies, which long reaped big profits as textbook publishers, have boasted that their new online offerings, when pushed to students through universities they partner with, represent the future of the industry.\nC) But critics say the digital access codes represent the same profit-seeking ethos (观念) of the textbook business, and are even harder for students to opt out of. While they could once buy second-hand textbooks, or share copies with friends, the digital systems are essentially impossible to avoid.\nD) \"When we talk about the access code we see it as the new face of the textbook monopoly (垄断), a new way to lock students around this system,\" said Ethan Senack, the higher education advocate for the U.S. Public Interest Research Group, to BuzzFeed News. \"Rather than $250 (for a print textbook) you re paying $ 120,\" said Senack. \"But because it s all digital it eliminates the used book market and eliminates any sharing and because homework and tests are through an access code, it eliminates any ability to opt out.\"\nE) Sarina Harpet, a 19-year-old student at Virginia Tech, was faced with a tough dilemma when she first started college in 2015\u2014pay rent or pay to turn in her chemistry homework. She told BuzzFeed News that her freshman chemistry class required her to use Connect, a system provided by McGraw Hill where students can submit homework, take exams and track their grades. But the code to access the program cost $ 120\u2014a big sum for Harper, who had already put down $ 450 for textbooks, and had rent day approaching.\nF) She decided to wait for her next work-study paycheck, which was typically $ 150- $ 200, to pay for the code. She knew that her chemistry grade may take a dive as a result. \"It s a balancing act,\" she said. \"Can I really afford these access codes now?\" She didn t hand in her first two assignments for chemistry, which started her out in the class with a failing grade.\nG) The access codes may be another financial headache for students, but for textbook businesses, they re the future. McGraw Hill, which controls 21% of the higher education market, reported in March that its digital content sales exceeded print sales for the first time in 2015. The company said that 45% of its $ 140 million revenue in 2015 \"was derived from digital products.\"\nH) A Pearson spokesperson told BuzzFeed News that \"digital materials are less expensive and a good investment\" that offer new features, like audio texts, personalized knowledge checks and expert videos. Its digital course materials save students up to 60% compared to traditional printed textbooks, the company added. McGraw Hill didn t respond to a request for comment, but its CEO David Levin told the Financial Times in August that \"in higher education, the era of the printed textbook is now over.\"\nI) The textbook industry insists the online systems represent a better deal for students. \"These digital products aren t just mechanisms for students to submit homework, they offer all kinds of features,\" David Anderson, the executive director of higher education with the Association of American Publishers, told BuzzFeed News. \"It helps students understand in a way that you can t do with print homework assignments.\"\nJ) David Hunt, an associate professor in sociology at Augusta University, which has rolled out digital textbooks across its math and psychology departments, told BuzzFeed News that he understands the utility of using systems that require access codes. But he doesn t require his students to buy access to a learning program that controls the class assignments. \"I try to make things as inexpensive as possible,\" said Hunt, who uses free digital textbooks for his classes but designs his own curriculum. \"The online systems may make my life a lot easier but I feel like I m giving up control. The discussions are the things where my expertise can benefit the students most.\"\nK) A 20-year-old junior at Georgia Southern University told BuzzFeed News that she normally spends $ 500-$ 600 on access codes for class. In one case, the professor didn t require students to buy a textbook, just an access code to turn in homework. This year she said she spent $ 900 on access codes to books and programs. \"That s two months of rent,\" she said. \"You can t sell any of it back. With a traditional textbook you can sell it for $ 30 - $ 50 and that helps to pay for your new semester s books. With an access code, you re out of that money. \"\nL) Benjamin Wolverton, a 19-year-old student at the University of South Carolina, told BuzzFeed News that \"it s ridiculous that after paying tens of thousands in tuition we have to pay for all these access codes to do our homework.\" Many of the access codes he s purchased have been required simply to complete homework or quizzes. \"Often it s only 10% of your grade in class.\" he said. \"You re paying so much money for something that hardly affects your grade\u2014but if you didn t have it, it would affect your grades enough. It would be bad to start out at a B or C.\" Wolverton said he spent $ 500 on access codes for digital books and programs this semester.\nM) Harper, a poultry (家禽) science major, is taking chemistry again this year and had to buy a new access code to hand in her homework. She rented her economics and statistics textbooks for about $ 20 each. But her access codes for homework, which can t be rented or bought second-hand, were her most expensive purchases: $ 120 and $ 85.\nN) She still remembers the sting of her first experience skipping an assignment due to the high prices. \"We don t really have a missed assignment policy,\" she said. \"If you miss it, you just miss it. I just got zeros on a couple of first assignments. I managed to pull everything back up. But as a scared freshman looking at their grades, it s not fun.\"","questions":["A student s yearly expenses on access codes may amount to their rent for two months.","The online access codes may be seen as a way to tie the students to the digital system.","If a student takes a course again, they may have to buy a new access code to submit their assignments.","McGraw Hill accounts for over one-fifth of the market share of college textbooks.","Many traditional textbook publishers are now offering online digital products, which they believe will be the future of the publishing business.","One student complained that they now had to pay for access codes in addition to the high tuition.","Digital materials can cost students less than half the price of traditional printed books according to a publisher.","One student decided not to buy her access code until she received the pay for her part-time job.","Online systems may deprive teachers of opportunities to make the best use of their expertise for their students.","Digital access codes are criticized because they are profit-driven just like the textbook business."]}
* section_c : [{"id":"cet4_20180601_reading_section_c_passage_1","name":"Passage One","text":"Losing your ability to think and remember is pretty scary. We know the risk of dementia (痴呆症) increases with age. But if you have memory slips, you probably needn t worry. There are pretty clear differences between signs of dementia and age-related memory loss.After age 50, it s quite common to have trouble remembering the names of people, places and things quickly, says Dr. Kirk Daffner of Brigham and Women s Hospital in Boston.\nThe brain ages just like the rest of the body. Certain parts shrink, especially areas in the brain that are important to learning, memory and planning. Changes in brain cells can affect communication between different regions of the brain. And blood flow can be reduced as blood vessels narrow.\nForgetting the name of an actor in a favorite movie, for example, is nothing to worry about. But if you forget the plot of the movie or don t remember even seeing it, that s far more concerning, Daffner says.\nWhen you forget entire experiences, he says, that s \"a red flag that something more serious may be involved.\" Forgetting how to operate a familiar object like a microwave oven, or forgetting how to drive to the house of a friend you ve visited many times before can also be signs of something going wrong.\nBut even then, Daffner says, people shouldn t panic. There are many things that can cause confusion and memory loss, including health problems like temporary stoppage of breathing during sleep, high blood pressure, or depression, as well as medications (药物) like antidepressants.\nYou don t have to figure this out on your own. Daffner suggests going to your doctor to check on medications, health problems and other issues that could be affecting memory. And the best defense against memory loss is to try to prevent it by building up your brain s cognitive (认知的) reserve, Daffner says.\n\"Read books, go to movies, take on new hobbies or activities that force one to think in novel ways,\" he says. In other words, keep your brain busy and working. And also get physically active, because exercise is a known brain booster.","questions":[{"name":"question_1","title":"Why does the author say that one needn t be concerned about memory slips?","answers":["Not all of them are symptoms of dementia.","They occur only among certain groups of people.","Not all of them are related to one s age.","They are quite common among fifty-year-olds."]},{"name":"question_2","title":"What happens as we become aged according to the passage?","answers":["Our interaction skills deteriorate.","Some parts of our brain stop functioning.","Communication within our brain weakens.","Our whole brain starts shrinking."]},{"name":"question_3","title":"Which memory-related symptom should people take seriously?","answers":["Totally forgetting how to do one s daily routines.","Inability to recall details of one s life experiences.","Failure to remember the names of movies or actors.","Occasionally confusing the addresses of one s friends."]},{"name":"question_4","title":"What should people do when signs of serious memory loss show up?","answers":["Check the brain s cognitive reserve. ","Stop medications affecting memory. ","Turn to a professional for assistance.","Exercise to improve their well-being."]},{"name":"question_5","title":"What is Dr. Daffner s advice for combating memory loss?","answers":["Having regular physical and mental checkups.","Taking medicine that helps boost one s brain.","Engaging in known memory repair activities.","Staying active both physically and mentally."]}]},{"id":"cet4_20180601_reading_section_c_passage_2","name":"Passage Two","text":"A letter written by Charles Darwin in 1875 has been returned to the Smithsonian \nInstitution Archives (档案馆) by the FBI after being stolen twice.\n\"We realized \nin the mid-1970s that it was missing,\" says Effie Kapsalis, head of the \nSmithsonian Insitution Archives. \"It was noted as missing and likely taken by an \nintern (实习生), from what the FBI is telling us. Word got out that it was missing \nwhen someone asked to see the letter for research purposes,\" and the intern put \nthe letter back. \"The intern likely took the letter again once nobody was \nwatching it.\"\nDecades passed. Finally, the FBI received a tip that the stolen \ndocument was located very close to Washington, D.C. Their art crime team \nrecovered the letter but were unable to press charges because the time of \nlimitations had ended. The FBI worked closely with the Archives to determine \nthat the letter was both authentic and definitely Smithsonian s property.\nThe \nletter was written by Darwin to thank an American geologist, Dr. Ferdinand \nVandeveer Hayden, for sending him copies of his research into the geology of the \nregion that would become Yellowstone National Park.\nThe letter is in fairly \ngood condition, in spite of being out of the care of trained museum staff for so \nlong. \"It was luckily in good shape,\" says Kapsalis, \"and we just have to do \nsome minor things in order to be able to unfold it. It has some glue on it that \nhas colored it slightly, but nothing that will prevent us from using it. After \nit is repaired, we will take digital photos of it and that will be available \nonline. One of our goals is to get items of high research value or interest to \nthe public online.\"\nIt would now be difficult for an intern, visitor or a \nthief to steal a document like this. \"Archiving practices have changed greatly \nsince the 1970s,\" says Kapsalis, \"and we keep our high value documents in a safe \nthat I don t even have access to.\"","questions":[{"name":"question_1","title":"What happened to Darwin s letter in the 1970s?","answers":["It was recovered by the FBI.","It was stolen more than once.","It was put in the archives for research purposes.","It was purchased by the Smithsonian Archives."]},{"name":"question_2","title":"What did the FBI do after the recovery of the letter?","answers":["They proved its authenticity. ","They kept it in a special safe.","They arrested the suspect immediately.","They pressed criminal charges in vain."]},{"name":"question_3","title":"What is Darwin s letter about?","answers":["The evolution of Yellowstone National Park.","His cooperation with an American geologist.","Some geological evidence supporting his theory.","His acknowledgement of help from a professional."]},{"name":"question_4","title":"What will the Smithsonian Institution Archives do with the letter according to \nKapsalis?","answers":["Reserve it for research purposes only. ","Turn it into an object of high interest.","Keep it a permanent secret. ","Make it available online."]},{"name":"question_5","title":"What has the past half century witnessed according to Kapsalis?","answers":["Growing interest in rare art objects.","Radical changes in archiving practices.","Recovery of various missing documents.","Increases in the value of museum exhibits."]}]}]
*/
private String id;
private String name;
private SectionABean section_a;
private SectionBBean section_b;
private List<SectionCBean> section_c;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public SectionABean getSection_a() {
return section_a;
}
public void setSection_a(SectionABean section_a) {
this.section_a = section_a;
}
public SectionBBean getSection_b() {
return section_b;
}
public void setSection_b(SectionBBean section_b) {
this.section_b = section_b;
}
public List<SectionCBean> getSection_c() {
return section_c;
}
public void setSection_c(List<SectionCBean> section_c) {
this.section_c = section_c;
}
public static class SectionABean {
/**
* id : cet4_20180601_reading_section_a
* text : An office tower on Miller Street in Manchester is completely covered in solar panels. They are used to create some of the energy used by the insurance company inside. When the tower was first 26 in 1962, it was covered with thin square stones. These small square stones became a problem for the building and continued to fall off the face for 40 years until a major renovation was 27 . During this renovation the building s owners, CIS, 28 the solar panel company, Solarcentury. They agreed to cover the entire building in solar panels. In 2004, the completed CIS tower became Europe s largest 29 of vertical solar panels. A vertical solar project on such a large 30 has never been repeated since.Covering a skyscraper with solar panels had never been done before, and the CIS tower was chosen as one of the "10 best green energy projects". For a long time after this renovation project, it was the tallest building in the United Kingdom, but it was 31 overtaken by the Millbank Tower.Green buildings like this aren t 32 cost-efficient for the investor, but it does produce much less pollution than that caused by energy 33 through fossil fuels. As solar panels get 34 , the world is likely to see more skyscrapers covered in solar panels, collecting energy much like trees do. Imagine a world where building the tallest skyscraper wasn t a race of 35 , but rather one to collect the most solar energy.
* words : ["cheaper","cleaner","collection","competed","constructed","consulted","dimension","discovered","eventually","height","necessarily","production","range","scale","undertaken"]
*/
private String id;
private String text;
private List<String> words;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<String> getWords() {
return words;
}
public void setWords(List<String> words) {
this.words = words;
}
}
public static class SectionBBean {
/**
* id : cet4_20180601_reading_section_b
* title : Some College Students Are Angry That They Have to Pay to Do Their Homework
* text : A) Digital learning systems now charge students for access codes needed to complete coursework, take quizzes, and turn in homework. As universities go digital, students are complaining of a new hit to their finances that s replacing—and sometimes joining—expensive textbooks: pricey online access codes that are required to complete coursework and submit assignments.B) The codes—which typically range in price from $ 80 to $ 155 per course—give students online access to systems developed by education companies like McGraw Hill and Pearson. These companies, which long reaped big profits as textbook publishers, have boasted that their new online offerings, when pushed to students through universities they partner with, represent the future of the industry.
C) But critics say the digital access codes represent the same profit-seeking ethos (观念) of the textbook business, and are even harder for students to opt out of. While they could once buy second-hand textbooks, or share copies with friends, the digital systems are essentially impossible to avoid.
D) "When we talk about the access code we see it as the new face of the textbook monopoly (垄断), a new way to lock students around this system," said Ethan Senack, the higher education advocate for the U.S. Public Interest Research Group, to BuzzFeed News. "Rather than $250 (for a print textbook) you re paying $ 120," said Senack. "But because it s all digital it eliminates the used book market and eliminates any sharing and because homework and tests are through an access code, it eliminates any ability to opt out."
E) Sarina Harpet, a 19-year-old student at Virginia Tech, was faced with a tough dilemma when she first started college in 2015—pay rent or pay to turn in her chemistry homework. She told BuzzFeed News that her freshman chemistry class required her to use Connect, a system provided by McGraw Hill where students can submit homework, take exams and track their grades. But the code to access the program cost $ 120—a big sum for Harper, who had already put down $ 450 for textbooks, and had rent day approaching.
F) She decided to wait for her next work-study paycheck, which was typically $ 150- $ 200, to pay for the code. She knew that her chemistry grade may take a dive as a result. "It s a balancing act," she said. "Can I really afford these access codes now?" She didn t hand in her first two assignments for chemistry, which started her out in the class with a failing grade.
G) The access codes may be another financial headache for students, but for textbook businesses, they re the future. McGraw Hill, which controls 21% of the higher education market, reported in March that its digital content sales exceeded print sales for the first time in 2015. The company said that 45% of its $ 140 million revenue in 2015 "was derived from digital products."
H) A Pearson spokesperson told BuzzFeed News that "digital materials are less expensive and a good investment" that offer new features, like audio texts, personalized knowledge checks and expert videos. Its digital course materials save students up to 60% compared to traditional printed textbooks, the company added. McGraw Hill didn t respond to a request for comment, but its CEO David Levin told the Financial Times in August that "in higher education, the era of the printed textbook is now over."
I) The textbook industry insists the online systems represent a better deal for students. "These digital products aren t just mechanisms for students to submit homework, they offer all kinds of features," David Anderson, the executive director of higher education with the Association of American Publishers, told BuzzFeed News. "It helps students understand in a way that you can t do with print homework assignments."
J) David Hunt, an associate professor in sociology at Augusta University, which has rolled out digital textbooks across its math and psychology departments, told BuzzFeed News that he understands the utility of using systems that require access codes. But he doesn t require his students to buy access to a learning program that controls the class assignments. "I try to make things as inexpensive as possible," said Hunt, who uses free digital textbooks for his classes but designs his own curriculum. "The online systems may make my life a lot easier but I feel like I m giving up control. The discussions are the things where my expertise can benefit the students most."
K) A 20-year-old junior at Georgia Southern University told BuzzFeed News that she normally spends $ 500-$ 600 on access codes for class. In one case, the professor didn t require students to buy a textbook, just an access code to turn in homework. This year she said she spent $ 900 on access codes to books and programs. "That s two months of rent," she said. "You can t sell any of it back. With a traditional textbook you can sell it for $ 30 - $ 50 and that helps to pay for your new semester s books. With an access code, you re out of that money. "
L) Benjamin Wolverton, a 19-year-old student at the University of South Carolina, told BuzzFeed News that "it s ridiculous that after paying tens of thousands in tuition we have to pay for all these access codes to do our homework." Many of the access codes he s purchased have been required simply to complete homework or quizzes. "Often it s only 10% of your grade in class." he said. "You re paying so much money for something that hardly affects your grade—but if you didn t have it, it would affect your grades enough. It would be bad to start out at a B or C." Wolverton said he spent $ 500 on access codes for digital books and programs this semester.
M) Harper, a poultry (家禽) science major, is taking chemistry again this year and had to buy a new access code to hand in her homework. She rented her economics and statistics textbooks for about $ 20 each. But her access codes for homework, which can t be rented or bought second-hand, were her most expensive purchases: $ 120 and $ 85.
N) She still remembers the sting of her first experience skipping an assignment due to the high prices. "We don t really have a missed assignment policy," she said. "If you miss it, you just miss it. I just got zeros on a couple of first assignments. I managed to pull everything back up. But as a scared freshman looking at their grades, it s not fun."
* questions : ["A student s yearly expenses on access codes may amount to their rent for two months.","The online access codes may be seen as a way to tie the students to the digital system.","If a student takes a course again, they may have to buy a new access code to submit their assignments.","McGraw Hill accounts for over one-fifth of the market share of college textbooks.","Many traditional textbook publishers are now offering online digital products, which they believe will be the future of the publishing business.","One student complained that they now had to pay for access codes in addition to the high tuition.","Digital materials can cost students less than half the price of traditional printed books according to a publisher.","One student decided not to buy her access code until she received the pay for her part-time job.","Online systems may deprive teachers of opportunities to make the best use of their expertise for their students.","Digital access codes are criticized because they are profit-driven just like the textbook business."]
*/
private String id;
private String title;
private String text;
private List<String> questions;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<String> getQuestions() {
return questions;
}
public void setQuestions(List<String> questions) {
this.questions = questions;
}
}
public static class SectionCBean {
/**
* id : cet4_20180601_reading_section_c_passage_1
* name : Passage One
* text : Losing your ability to think and remember is pretty scary. We know the risk of dementia (痴呆症) increases with age. But if you have memory slips, you probably needn t worry. There are pretty clear differences between signs of dementia and age-related memory loss.After age 50, it s quite common to have trouble remembering the names of people, places and things quickly, says Dr. Kirk Daffner of Brigham and Women s Hospital in Boston.
The brain ages just like the rest of the body. Certain parts shrink, especially areas in the brain that are important to learning, memory and planning. Changes in brain cells can affect communication between different regions of the brain. And blood flow can be reduced as blood vessels narrow.
Forgetting the name of an actor in a favorite movie, for example, is nothing to worry about. But if you forget the plot of the movie or don t remember even seeing it, that s far more concerning, Daffner says.
When you forget entire experiences, he says, that s "a red flag that something more serious may be involved." Forgetting how to operate a familiar object like a microwave oven, or forgetting how to drive to the house of a friend you ve visited many times before can also be signs of something going wrong.
But even then, Daffner says, people shouldn t panic. There are many things that can cause confusion and memory loss, including health problems like temporary stoppage of breathing during sleep, high blood pressure, or depression, as well as medications (药物) like antidepressants.
You don t have to figure this out on your own. Daffner suggests going to your doctor to check on medications, health problems and other issues that could be affecting memory. And the best defense against memory loss is to try to prevent it by building up your brain s cognitive (认知的) reserve, Daffner says.
"Read books, go to movies, take on new hobbies or activities that force one to think in novel ways," he says. In other words, keep your brain busy and working. And also get physically active, because exercise is a known brain booster.
* questions : [{"name":"question_1","title":"Why does the author say that one needn t be concerned about memory slips?","answers":["Not all of them are symptoms of dementia.","They occur only among certain groups of people.","Not all of them are related to one s age.","They are quite common among fifty-year-olds."]},{"name":"question_2","title":"What happens as we become aged according to the passage?","answers":["Our interaction skills deteriorate.","Some parts of our brain stop functioning.","Communication within our brain weakens.","Our whole brain starts shrinking."]},{"name":"question_3","title":"Which memory-related symptom should people take seriously?","answers":["Totally forgetting how to do one s daily routines.","Inability to recall details of one s life experiences.","Failure to remember the names of movies or actors.","Occasionally confusing the addresses of one s friends."]},{"name":"question_4","title":"What should people do when signs of serious memory loss show up?","answers":["Check the brain s cognitive reserve. ","Stop medications affecting memory. ","Turn to a professional for assistance.","Exercise to improve their well-being."]},{"name":"question_5","title":"What is Dr. Daffner s advice for combating memory loss?","answers":["Having regular physical and mental checkups.","Taking medicine that helps boost one s brain.","Engaging in known memory repair activities.","Staying active both physically and mentally."]}]
*/
private String id;
private String name;
private String text;
private List<QuestionsBeanXXX> questions;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public List<QuestionsBeanXXX> getQuestions() {
return questions;
}
public void setQuestions(List<QuestionsBeanXXX> questions) {
this.questions = questions;
}
public static class QuestionsBeanXXX {
/**
* name : question_1
* title : Why does the author say that one needn t be concerned about memory slips?
* answers : ["Not all of them are symptoms of dementia.","They occur only among certain groups of people.","Not all of them are related to one s age.","They are quite common among fifty-year-olds."]
*/
private String name;
private String title;
private List<String> answers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getAnswers() {
return answers;
}
public void setAnswers(List<String> answers) {
this.answers = answers;
}
}
}
}
public static class TransBean {
/**
* id : cet4_20180601_trans
* name : 2018年6月第一套英语四级真题-翻译
* title : Directions: For this part, you are allowed 30 minutes to translate a passage from Chinese into English. You should write your answer on Answer Sheet 2.
* text : 过去,乘飞机出行对大多数中国人来说是难以想象的。如今,随着经济的发展和生活水平的提高,越来越多的中国人包括许多农民和外出务工人员都能乘飞机出行。他们可以乘飞机到达所有大城市,还有很多城市也在筹建机场。航空服务不断改进,而且经常会有廉价机票。近年来,节假日期间选择乘飞机外出旅游的人数在不断增加。
*/
private String id;
private String name;
private String title;
private String text;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
public static class WritingBean {
/**
* id : cet4_20180601_writing
* name : 2018年6月第一套英语四级真题-写作
* title : Directions: For this part, you are allowed 30 minutes to write a short essay on the importance of reading ability and how to develop it. You should write at least 120 words but no more than 180 words.
*/
private String id;
private String name;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
}
| android-zongwei-li/EnglishExamSystem | app/src/main/java/com/lzw/beans/TestPaper.java |
66,135 | package com.blazers.jandan.model.news;
import android.databinding.BindingAdapter;
import android.net.Uri;
import com.facebook.drawee.view.SimpleDraweeView;
import java.util.Date;
import io.realm.RealmList;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
/**
* Created by blazers on 2016/12/7.
*/
public class NewsPost extends RealmObject {
/**
* id : 84360
* url : http://i.jandan.net/2016/12/07/newton-expensive-principia.html
* title : 初版初印:牛顿的《自然哲学的数学原理》即将拍卖
* content : <p><img src="http://tankr.net/s/small/1KBN.jpg" alt="初版初印:牛顿的《自然哲学的数学原理》即将拍卖" /></p>
* <p>炼金术师牛顿的《自然哲学的数学原理》是全世界最有影响力的书籍之一。它的初版初印本月将在纽约开拍,标价100万美元。</p>
* <p>2003年,一本据说曾属于詹姆士二世的《原理》进入了拍卖市场,这本用摩洛哥山羊皮装帧的善本拍出了250万美元的天价,标价为60万美元。如今,纽约克里斯蒂拍卖行拿到了这本书的初版初印,标价在100万到150万美元之间,业内估计此书将轻松成为有史以来最贵的善本之一。</p>
* <p>那么,它为何那么值钱呢?《原理》是现代科学领域最重要也是最具影响力的图书。它阐释了牛顿的万有引力理论,同时也是利用严谨的数学系统研究物理的开山之作。它成为了科学方法论和科学思维的标准。从1687年该书出版,到1916年爱因斯坦相对论的发表,在长达近230年的时间里,它一直都是物理研究的基石。</p>
* <p> “牛顿在当时做出的研究彻底改变了物理科学。这是物理的基本法,”皇家学会图书馆馆长Keith Moore说。</p>
* <p>它也是全球保有量最少的书籍版本之一。《原理》初版初印仅有约400册,其中约20%是“欧陆版”,为欧洲大陆的买家打造,它们跟英国本土销售的有细微区别。这次拍卖的书就是其中之一。</p>
* <p>Moore认为如此昂贵的标价得益于社会文化对科学越来越推崇,以及那些暴富的Geek们。</p>
* <p> “买这些珍贵善本的人可能都是那些搞互联网发财的人。如果你的钱来源自一个超级酷的算法,你可能想感谢一下牛顿的物理学。如果你手头有好几百万现金,为何不买一本初版初印的《原理》呢?你买不了吃亏,更买不了上当。”</p>
* <p> “它不仅见证了科学的历史和发展;它更是有史以来出版过的最伟大的书籍之一,”Moore补充说。</p>
* <p>英国皇家学会保有两本《原理》,包括它的“最珍贵的收藏”——牛顿的原始手稿。</p>
* <p><em>[<a target=_blank href="http://i.jandan.net/2016/12/07/newton-expensive-principia.html">许叔</a> via <a target=_blank rel="external" href="http://www.zmescience.com/science/news-science/newton-expensive-principia/">Quartz</a>]</em>zmescience</p>
* <p>
* date : 2016-12-07 16:00:57
* tags : [{"id":698,"slug":"%e8%87%b4%e5%af%8c%e4%bf%a1%e6%81%af","title":"致富信息","description":"","post_count":963}]
* author : {"id":587,"slug":"cedric","name":"许叔","first_name":"Cedric","last_name":"Hsu","nickname":"许叔","url":"http://weibo.com/cedrichsu","description":""}
* comments : [{"id":3341879,"name":"茶苯海明","url":"","date":"2016-12-07 16:09:20","content":"<p>第一版〈理论力学〉,比圣经更伟大的著作<\/p>\n","parent":0,"vote_positive":0,"vote_negative":0,"index":1}]
* comments_rank : [{"id":3341879,"name":"茶苯海明","url":"","date":"2016-12-07 16:09:20","content":"<p>第一版〈理论力学〉,比圣经更伟大的著作<\/p>\n","parent":0,"vote_positive":0,"vote_negative":0,"index":1}]
* comment_count : 1
* custom_fields : {"thumb_c":["http://tankr.net/s/custom/1KBN.jpg"]}
*/
public static final String ID = "id";
@PrimaryKey
public int id;
public int page;
public boolean favorite;
public Date favorite_time;
public String url;
public String title;
public String content;
public String date;
public NewsAuthor author;
public int comment_count;
public NewsCustomField custom_fields;
public RealmList<NewsTag> tags;
public RealmList<NewsComment> comments;
public RealmList<NewsCommentsRank> comments_rank;
public String tag() {
if (tags != null && tags.size() != 0) {
return tags.get(0).title;
}
return "";
}
@BindingAdapter({"post"})
public static void showImage(SimpleDraweeView simpleDraweeView, NewsPost posts) {
simpleDraweeView.setImageURI(Uri.parse(posts.custom_fields.thumb_c.get(0).getValue()));
}
}
| Blazers007/Jandan | app/src/main/java/com/blazers/jandan/model/news/NewsPost.java |
66,137 | package io.github.ljwlgl.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* @author zqgan
* @since 2018/9/1
* 日期时间处理相关类
**/
public class DateUtil {
public static final String YYYYMMDD = "yyyy-MM-dd";
public static final String YYYYMMDDHHMMSS = "yyyy-MM-dd HH:mm:ss";
public static final String YYYYMMDDHHMMSSSSS = "yyyy-MM-dd HH:mm:ss.SSS";
public static final String YYYYMMDDHHMM_CHINESE = "yyyy年MM月dd日HH点mm分";
public static final String YYYYMMDD_CHINESE = "yyyy年MM月dd日";
public static final String MMDD_CHINESE = "MM月dd日";
public static final long MILLISECONDS_FOR_ONE_MINUTE = 60 * 1000;
public static final long MILLISECONDS_FOR_ONE_HOUR = 60 * MILLISECONDS_FOR_ONE_MINUTE;
public static final long MILLISECONDS_FOR_ONE_DAY = 24 * MILLISECONDS_FOR_ONE_HOUR;
/**
* 获取当前日期,只包年月日
*/
public static Date getCurrentDate() {
Calendar c = Calendar.getInstance();
return stringToDate(dateToShortDateString(c.getTime()));
}
/**
* 比较两个时间是否是相同的天数
*/
public static boolean isSameDay(Date date1, Date date2) {
if (calcIntervalDays(date1, date2) == 0) {
return true;
} else {
return false;
}
}
/**
* 将Date转成Calendar
*/
public static Calendar toCalendar(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c;
}
/**
* 计算两个时间间隔的天数
*/
public static int calcIntervalDays(String dateStr1, String dateStr2) {
return calcIntervalDays(stringToDate(dateStr1), stringToDate(dateStr2));
}
/**
* 计算两个时间的间隔小时,只会整除
*/
public static int calcIntervalOurs(Date date1, Date date2) {
if (date2.after(date1)) {
return Long.valueOf((date2.getTime() - date1.getTime()) / (1000 * 60 * 60)).intValue();
} else if (date2.before(date1)) {
return Long.valueOf((date1.getTime() - date2.getTime()) / (1000 * 60 * 60)).intValue();
} else {
return 0;
}
}
/**
* 计算两个时间的间隔小时,只会整除
*/
public static int calcIntervalMinutes(Date date1, Date date2) {
if (date2.after(date1)) {
return Long.valueOf((date2.getTime() - date1.getTime()) / (1000 * 60)).intValue();
} else if (date2.before(date1)) {
return Long.valueOf((date1.getTime() - date2.getTime()) / (1000 * 60)).intValue();
} else {
return 0;
}
}
/**
* 计算两个时间的间隔天数
*/
public static int calcIntervalDays(Date date1, Date date2) {
if (date2.after(date1)) {
return Long.valueOf((date2.getTime() - date1.getTime()) / (1000 * 60 * 60 * 24)).intValue();
} else if (date2.before(date1)) {
return Long.valueOf((date1.getTime() - date2.getTime()) / (1000 * 60 * 60 * 24)).intValue();
} else {
return 0;
}
}
/**
* 返回日期对应的是星期几
*/
public static int dayOfWeek(Date date) {
Calendar ca = Calendar.getInstance();
ca.setTime(date);
int dayofWeek;
if (ca.get(Calendar.DAY_OF_WEEK) == 1) {
dayofWeek = 7;
} else {
dayofWeek = ca.get(Calendar.DAY_OF_WEEK) - 1;
}
return dayofWeek;
}
/**
* 获取今天的分钟数,如今天18:05,则返回1805
*/
public static int getTodayMinutes() {
Calendar ca = Calendar.getInstance();
int hours = ca.get(Calendar.HOUR_OF_DAY);
int minutes = ca.get(Calendar.MINUTE);
return hours * 60 + minutes;
}
/**
* 获取指定间隔天数的日期
*/
public static Date getIntervalDaysDate(Date time, int days) {
Calendar ca = Calendar.getInstance();
ca.setTime(time);
ca.add(Calendar.DATE, days);
return stringToDate(dateToShortDateString(ca.getTime()));
}
/**
* 获取间隔的几个小时,如需要获取之前的3小时,hours传-3
*/
public static Date getIntervalHourDate(Date time, int hours) {
Calendar ca = Calendar.getInstance();
ca.setTime(time);
ca.add(Calendar.HOUR, hours);
System.out.println(dateToString(ca.getTime(), YYYYMMDDHHMM_CHINESE));
return ca.getTime();
}
public static String dateToShortDateString(Date date) {
return dateToString(date, "yyyy-MM-dd");
}
public static String dateToString(Date date, String format) {
DateFormat dateFormat = new SimpleDateFormat(format);
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
try {
return dateFormat.format(date);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将String转成Date,默认时区东八区,TimeZone.getTimeZone("Asia/Shanghai")
*
* @param dateStr 含格式的时间字符串串
* @return Date
*/
public static Date stringToDate(String dateStr) {
SimpleDateFormat format = null;
if (dateStr.contains("/")) {
if (dateStr.contains(":") && dateStr.contains(" ")) {
format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
} else {
format = new SimpleDateFormat("yyyy/MM/dd");
}
} else if (dateStr.contains("-")) {
if (dateStr.contains(":") && dateStr.contains(" ")) {
format = new SimpleDateFormat(YYYYMMDDHHMMSS);
} else {
format = new SimpleDateFormat(YYYYMMDD);
}
} else if (dateStr.contains("年") && dateStr.contains("月") && dateStr.contains("日")) {
format = new SimpleDateFormat(YYYYMMDD_CHINESE);
} else if (!dateStr.contains("年") && dateStr.contains("月") && dateStr.contains("日")) {
format = new SimpleDateFormat(MMDD_CHINESE);
}
if (format == null) {
return null;
}
format.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
try {
return format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
/**
* 全站时间展示规范
* 1分钟内:刚刚
* 超过1分钟并在1小时内:某分钟前 (1分钟前)
* 超过1小时并在当日内:某小时前(1小时前)
* 昨天:昨天 + 小时分钟(昨天 08:30)
* 昨天之前并在当年内:某月某日 + 小时分钟(1月1日 08:30)
* 隔年:某年某月某日 + 小时分钟(2015年1月1日 08:30)
*/
public static String dateToVoString(Date date) {
Date now = new Date();
long deltaMilliSeconds = now.getTime() - date.getTime();
Calendar dateCalendar = toCalendar(date);
Calendar nowCalendar = toCalendar(now);
if (nowCalendar.get(Calendar.YEAR) == dateCalendar.get(Calendar.YEAR)) {
if (isSameDay(date, now)) {
if (deltaMilliSeconds < MILLISECONDS_FOR_ONE_MINUTE) {
return "刚刚";
} else if (deltaMilliSeconds < MILLISECONDS_FOR_ONE_HOUR) {
return String.format("%d分钟前", deltaMilliSeconds / MILLISECONDS_FOR_ONE_MINUTE);
} else if (deltaMilliSeconds < MILLISECONDS_FOR_ONE_DAY) {
return String.format("%d小时前", deltaMilliSeconds / MILLISECONDS_FOR_ONE_HOUR);
}
}
if (isSameDay(date, getIntervalDaysDate(now, -1))) {
return String.format("昨天 %d:%02d", dateCalendar.get(Calendar.HOUR_OF_DAY),
dateCalendar.get(Calendar.MINUTE));
} else {
return String.format("%d月%d日 %d:%02d", dateCalendar.get(Calendar.MONTH) + 1,
dateCalendar.get(Calendar.DAY_OF_MONTH),
dateCalendar.get(Calendar.HOUR_OF_DAY), dateCalendar.get(Calendar.MINUTE));
}
} else {
return String.format("%d年%d月%d日 %d:%02d", dateCalendar.get(Calendar.YEAR),
dateCalendar.get(Calendar.MONTH) + 1,
dateCalendar.get(Calendar.DAY_OF_MONTH), dateCalendar.get(Calendar.HOUR_OF_DAY),
dateCalendar.get(Calendar.MINUTE));
}
}
/**
* 获取指定日期百分百
*
* @param date
* @return
*/
public static Float getPercentage(Date date) {
if (date == null) date = new Date();
Integer day = getDay(date);
Integer month = getMonth(date);
Integer year = getYear(date);
Integer monthDays = getMonthLastDay(year, month);
return (float) day / (float) monthDays;
}
/**
* 获取年份
*
* @param date
* @return
*/
public static int getYear(Date date) {
if (date == null) date = new Date();
String year = new SimpleDateFormat("yyyy").format(date);
return Integer.parseInt(year);
}
/**
* 获取月份
*
* @param date
* @return
*/
public static int getMonth(Date date) {
String month = new SimpleDateFormat("MM").format(date);
return Integer.parseInt(month);
}
/**
* 获取日期
*
* @param date
* @return
*/
public static int getDay(Date date) {
String day = new SimpleDateFormat("dd").format(date);
return Integer.parseInt(day);
}
/**
* 获取某月的最后一天
*
* @param year
* @param month
* @return
*/
public static int getMonthLastDay(int year, int month) {
Calendar a = Calendar.getInstance();
a.set(Calendar.YEAR, year);
a.set(Calendar.MONTH, month - 1);
a.set(Calendar.DATE, 1);//把日期设置为当月第一天
a.roll(Calendar.DATE, -1);//日期回滚一天,也就是最后一天
int maxDate = a.get(Calendar.DATE);
return maxDate;
}
/**
* 获取某月的第一天
*
* @param year
* @param month
* @return
*/
public static int getMonthFirstDay(int year, int month) {
Calendar a = Calendar.getInstance();
a.set(Calendar.YEAR, year);
a.set(Calendar.MONTH, month);
a.set(Calendar.DATE, 1);//把日期设置为当月第一天
int maxDate = a.get(Calendar.DATE);
return maxDate;
}
/**
* 判断是否是闰年
*
* @param year
* @return
*/
public static boolean isLeap(int year) {
if (((year % 100 == 0) && year % 400 == 0) || ((year % 100 != 0) && year % 4 == 0))
return true;
else
return false;
}
/**
* 获取传入当日0点
*
* @param time
* @return
*/
public static Date startTime(Date time) {
if (time == null) time = new Date();
Calendar todayStart = Calendar.getInstance();
todayStart.setTime(time);
todayStart.set(Calendar.HOUR_OF_DAY, 0);
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
return todayStart.getTime();
}
/**
* 获取传入当日最后一刻
*
* @param time
* @return
*/
public static Date endTime(Date time) {
if (time == null) time = new Date();
Calendar todayStart = Calendar.getInstance();
todayStart.setTime(time);
todayStart.set(Calendar.HOUR_OF_DAY, 23);
todayStart.set(Calendar.MINUTE, 59);
todayStart.set(Calendar.SECOND, 59);
todayStart.set(Calendar.MILLISECOND, 999);
return todayStart.getTime();
}
}
| LJWLgl/CommonUtil | src/main/java/io/github/ljwlgl/util/DateUtil.java |
66,144 | package talex.zsw.baseproject.activity;
import android.content.Intent;
import android.os.Bundle;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import talex.zsw.baselibrary.BaseAppCompatActivity;
import talex.zsw.baselibrary.widget.RichText;
import talex.zsw.baseproject.R;
/**
* 项目名称: BaseProject
* 作者: 赵小白 email:[email protected]
* 日期: 2015-11-16-0016 13:24
* 修改人:
* 修改时间:
* 修改备注:
*/
public class RichTextActivity extends BaseAppCompatActivity implements RichText.OnImageClickListener
{
@Bind(R.id.mRichText) RichText mRichText;
@Override protected void initArgs(Intent intent)
{
}
@Override protected void initView(Bundle bundle)
{
setContentView(R.layout.activity_richtext);
ButterKnife.bind(this);
mRichText.setOnImageClickListener(this);
}
@Override protected void initData()
{
String content =
"<div id=\"section_show_post\"><div class=\"rbox_t\"></div><div class=\"rbox_c\"><div id=\"show_post_entry\" itemscope=\"\" itemtype=\"http://schema.org/Article\"><div class=\"entry-banner\"><a href=\"http://www.iplaysoft.com/windows10.html\"><img alt=\"微软最新 Windows 10 TH2 操作系统简体中文正式版官方原版 ISO 镜像下载+序列号\" src=\"http://ips.chotee.com/wp-content/uploads/2014/windows10/win10th2.jpg\" srcset=\"http://ips.chotee.com/wp-content/uploads/2014/windows10/win10th2.jpg 1x,http://ips.chotee.com/wp-content/uploads/2014/windows10/win10th2_2x.jpg 2x\" border=\"0\" width=\"680\" height=\"130\"></a></div><div class=\"entry-head\"><h2 class=\"entry-title\" itemprop=\"name\"><a href=\"http://www.iplaysoft.com/windows10.html\">微软最新 Windows 10 TH2 操作系统简体中文正式版官方原版 ISO 镜像下载+序列号</a></h2><div class=\"entry-cat\">\n" +
"<span class=\"entry-update-summary\">TH2 新版镜像发布 (版本1511)</span>[ <a href=\"http://www.iplaysoft.com/category/system\" rel=\"category tag\">系统工具</a> // <a href=\"http://www.iplaysoft.com/os/windows-platform\" rel=\"tag\">Windows</a>] [2015-11-16<meta itemprop=\"datePublished\" content=\"2015-11-16\">]</div></div><div class=\"entry-show-content\">\n" +
"<span itemprop=\"description\"><p>随着<a href=\"http://www.iplaysoft.com/tag/微软\" target=\"_blank\">微软</a>的不断努力开发完善 <strong>Windows 10</strong> 系统以及 <a href=\"http://www.iplaysoft.com/office2016.html\" target=\"_blank\">Office 2016</a> 办公软件。如今,这款最新一代的操作系统以及新版的<a href=\"http://www.iplaysoft.com/tag/办公\" target=\"_blank\">办公</a>软件均已经越来越多人用上了!</p><p>这里给大家提供最新的微软官方 <strong>Windows 10 TH2 系统正式版原版光盘镜像 ISO下载。</strong>新版系统增加了全新的 <a href=\"http://www.iplaysoft.com/microsoft-edge.html\" target=\"_blank\">Microsoft Edge 浏览器</a>。电脑上安装了已经激活的 <a href=\"http://www.iplaysoft.com/windows81.html\" target=\"_blank\">Win8</a> / Win7 用户,可以直接在免费线更新升级到最新正式版系统。当然,我们更加推荐你下载独立的 Windows 10 ISO 光盘<a href=\"http://www.iplaysoft.com/tag/镜像\" target=\"_blank\">镜像</a>进行全新安装(<a href=\"http://www.iplaysoft.com/clean-install-windows10-activate.html\" target=\"_blank\">教程</a>)……</p>\n" +
"</span><div class=\"entry-meta\">\n" +
"<a href=\"http://www.iplaysoft.com/windows10.html#comments\">评论:190条</a> | 围观:<span id=\"spn2216\">1,019,684</span>℃<script type=\"text/javascript\">strBatchView+=\"2216,\";</script> | 标签:<span itemprop=\"keywords\"><a href=\"http://www.iplaysoft.com/tag/iso\" rel=\"tag\">ISO</a> , <a href=\"http://www.iplaysoft.com/tag/windows\" rel=\"tag\">windows</a> , <a href=\"http://www.iplaysoft.com/tag/windows10\" rel=\"tag\">windows10</a> , <a href=\"http://www.iplaysoft.com/tag/%e5%8d%87%e7%ba%a7\" rel=\"tag\">升级</a> , <a href=\"http://www.iplaysoft.com/tag/%e5%be%ae%e8%bd%af\" rel=\"tag\">微软</a> , <a href=\"http://www.iplaysoft.com/tag/%e6%a1%8c%e9%9d%a2\" rel=\"tag\">桌面</a> , <a href=\"http://www.iplaysoft.com/tag/%e7%b3%bb%e7%bb%9f\" rel=\"tag\">系统</a> , <a href=\"http://www.iplaysoft.com/tag/%e8%a3%85%e6%9c%ba\" rel=\"tag\">装机</a> , <a href=\"http://www.iplaysoft.com/tag/%e9%95%9c%e5%83%8f\" rel=\"tag\">镜像</a></span></div></div></div><div id=\"show_post_side\" class=\"sidebar_bdad_list\" style=\"margin:-8px 0 0 8px;\"> <script type=\"text/javascript\">BAIDU_CLB_fillSlot('230916');\n" +
"\t\t\t\t\t\tvar bd_slot_code = shffleArray(new Array('230917','230918'));\n" +
"\t\t\t\t\t\tfor(var i=0;i<bd_slot_code.length;i++){BAIDU_CLB_fillSlot(bd_slot_code[i]);}</script> </div></div><div class=\"rbox_b\"></div></div>";
mRichText.setRichText(content);
}
@Override public void imageClicked(List<String> imageUrls, int position)
{
showToast("图片地址是:" + imageUrls);
}
}
| vivitale/BaseLibrary | app/src/main/java/talex/zsw/baseproject/activity/RichTextActivity.java |
66,145 | package hit.mapper;
import java.util.List;
import org.junit.Test;
import hit.po.Club;
import hit.po.ClubMember;
import hit.po.ClubMemberRequest;
import hit.po.Role;
public interface ClubMapper {
int deleteByPrimaryKey(Integer clubId);
int insert(Club record);
int insertSelective(Club record);
Club selectByPrimaryKey(Integer clubId);
int updateByPrimaryKeySelective(Club record);
int updateByPrimaryKey(Club record);
List<Integer> getRoleMenu(Integer roleId);
List<ClubMember> getMembershipByClubId(Integer club_id);
List<ClubMemberRequest> getMemberRequestByClubId(Integer club_id);
List<Role> getRolesByClubId(Integer club_id);
void deleteClubMember(ClubMember clubMember);
void addClubMember(ClubMember clubMember);
void deleteClubRequest(ClubMember clubMember);
Role getUserRoleInClub(ClubMember clubMember);
List<Club> getClubsByUser(Integer userId);
void updateUserClubScore(ClubMember clubMember);
Integer calcTotalRequest(Integer club_id);
/**
* @author 作者: 如今我已·剑指天涯
*创建时间:2016年4月16日下午8:00:42
*/
List<Club> queryAllClubs();
} | sunpeng1996/HackPKU | src/hit/mapper/ClubMapper.java |
66,146 | package hit.service;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import hit.po.School;
import hit.po.User;
/**
* 用户Service接口
* @author 作者: 如今我已·剑指天涯
* @Description:
*创建时间:2016年3月29日下午11:13:33
*/
@Component
public interface UserService {
//public User login(String password, String email);
public User selectByEmail(String email);
public String addUser(User user);
public void updateUser(User user);
public User login(String password, String email);
//通过schoolname得到school对象
public School findSchoolBySchoolName(String schoolname);
public User getUserById(Integer userId);
//在第一次注册后自动调用的方法
public User update(HttpServletRequest request, User user,
String username, String schoolname, String institute,
String major, String time, String phone, String sex,
String province, MultipartFile image, String scholar);
public void updateUserByEmail(User user);
/**
* @author 作者: 如今我已·剑指天涯
*创建时间:2016年4月16日下午8:46:07
*/
public void joinClub(Integer user_id, Integer clubId);
/**
*
* @author 作者: 如今我已·剑指天涯
* @Description:判断用户是否已经提交请求的方法
*创建时间:2016年4月16日下午9:58:34
*/
public Boolean judgeRequest(Integer user_id, Integer clubId);
public Boolean findPasswordByEmail(String email);
}
| sunpeng1996/HackPKU | src/hit/service/UserService.java |
66,147 | package hit.service;
import hit.po.Club;
import hit.po.ClubMember;
import hit.po.ClubMemberRequest;
import hit.po.Menu;
import hit.po.News;
import hit.po.Role;
import hit.po.RolePrivilege;
import hit.po.User;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component
public interface ClubService {
public Club getClubById(Integer club_id) ;
public List<ClubMember> getMembershipByClubId(Integer club_id);
public void updateClub(Club club);
public List<Role> getRoles(Integer club_id);
public List<Menu> getAlMenus();
public int addRole(Role role);
public List<Integer> getRoleMenu(Integer roleId);
public void addRolePrivileges(List<RolePrivilege> rolePrivileges);
public void updateRole(Role role,List<RolePrivilege> rolePrivileges) ;
public void deleteRole(Role role,Integer club_id);
public List<ClubMember> getClubMembership(Integer club_id);
public List<ClubMemberRequest> getClubMemberRequest(Integer club_id);
public void editUserRole(Integer user_id,Integer club_id,Integer role_id);
public void deleteClubMember(Integer user_id,Integer club_id,Integer role_id);
public void addClubMember(Integer user_id,Integer club_id,Integer role_id);
public Role getUserRoleInClub(Integer userId,Integer clubId);
public List<Club> getClubsByUser(Integer user_id);
public void rejectRequest(Integer user_id,Integer club_id);
public Integer calcTotalRequest(Integer club_id);
public Club createClub(HttpServletRequest request, Club club, String clubname, String description, Date setuptime,
User user, MultipartFile clubImage);
public Integer queryClubidByClubnameAndUserId(String clubname,
Integer userId);
public void bindUserAndClub(Club club2, User user);
public List<Club> getAllClubs();
/**
*
* @author 作者: 如今我已·剑指天涯
* @Description:发布新闻,新闻入库
*创建时间:2016年4月17日下午10:09:54
*/
public News addNews(String title, String blob, Integer user_id,
Integer club_id);
/**
* 通过一系列参数查询新闻id
* @author 作者: 如今我已·剑指天涯
*创建时间:2016年4月17日下午10:35:37
* @param date
*/
public Integer queryNewsIdByTitleAndUser(String title, Integer user_id,
Integer club_id);
}
| sunpeng1996/HackPKU | src/hit/service/ClubService.java |
66,148 | /***********************************************************
* @Description : 89.格雷编码
* https://leetcode-cn.com/problems/gray-code/
* @author : 梁山广(Liang Shan Guang)
* @date : 2020/1/31 22:01
* @email : [email protected]
***********************************************************/
package C14_位操作.T89_格雷编码;
import java.util.ArrayList;
import java.util.List;
/**
* Gray Code
* reflect-and-prefix method
* 时间复杂度O(2^n), 空间复杂度O(1)
*/
public class Solution {
public List<Integer> grayCode(int n) {
final int size = 1 << n;
List<Integer> result = new ArrayList<>(size);
result.add(0);
for (int i = 0; i < n; i++) {
final int highestBit = 1 << i;
// 要反着遍历, 才能对称
for (int j = result.size() - 1; j >= 0; j--)
{
result.add(highestBit | result.get(j));
}
}
return result;
}
}
| lsgwr/algorithms | Part7LeetCode/src/main/java/C14_位操作/T89_格雷编码/Solution.java |
66,150 | /**
* ClassName: Solution_89
* Data: 2020/7/30
* author: Oh_MyBug
* version: V1.0
*/
/*
89. 格雷编码
格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。
格雷编码序列必须以 0 开头。
示例 1:
输入: 2
输出: [0,1,3,2]
解释:
00 - 0
01 - 1
11 - 3
10 - 2
对于给定的 n,其格雷编码序列并不唯一。
例如,[0,2,3,1] 也是一个有效的格雷编码序列。
00 - 0
10 - 2
11 - 3
01 - 1
示例 2:
输入: 0
输出: [0]
解释: 我们定义格雷编码序列必须以 0 开头。
给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。
因此,当 n = 0 时,其格雷编码序列为 [0]。
*/
public class Solution_89 {
/*public List<Integer> grayCode(int n) {
}*/
}
| asdf2014/algorithm | Codes/oh-mybug/051-100/Solution_89.java |
66,151 | package tmnt.example.onedaily.bean.movie;
/**
* Created by tmnt on 2017/4/17.
*/
public class Director {
/**
* alt : https://movie.douban.com/celebrity/1009396/
* avatars : {"small":"https://img3.doubanio.com/img/celebrity/small/4451.jpg","large":"https://img3.doubanio.com/img/celebrity/large/4451.jpg","medium":"https://img3.doubanio.com/img/celebrity/medium/4451.jpg"}
* name : F·加里·格雷
* id : 1009396
*/
private String alt;
private Avatar avatars;
private String name;
private String id;
public String getAlt() {
return alt;
}
public void setAlt(String alt) {
this.alt = alt;
}
public Avatar getAvatars() {
return avatars;
}
public void setAvatars(Avatar avatars) {
this.avatars = avatars;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
| tmntduke/OneDaily | app/src/main/java/tmnt/example/onedaily/bean/movie/Director.java |
66,152 | //格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
//
// 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。
//
// 示例 1:
//
// 输入: 2
//输出: [0,1,3,2]
//解释:
//00 - 0
//01 - 1
//11 - 3
//10 - 2
//
//对于给定的 n,其格雷编码序列并不唯一。
//例如,[0,2,3,1] 也是一个有效的格雷编码序列。
//
//00 - 0
//10 - 2
//11 - 3
//01 - 1
//
// 示例 2:
//
// 输入: 0
//输出: [0]
//解释: 我们定义格雷编码序列必须以 0 开头。
// 给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。
// 因此,当 n = 0 时,其格雷编码序列为 [0]。
//
// Related Topics 回溯算法
package leetcode.editor.cn;
import java.util.ArrayList;
import java.util.List;
public class GrayCode_01 {
public static void main(String[] args) {
Solution solution = new GrayCode_01().new Solution();
solution.grayCode(3);
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> code = new ArrayList<Integer>();
code.add(0);
genCodes(code, n, 0, 1 << n);
return code;
}
public void genCodes(List<Integer> code, int n, int curr, int size) {
if (code.size() == size) {
System.out.println(code);
return;
}
for (int i = 0; i < n; i++) {
int mask = 1 << i;
int el = (curr ^ mask);
System.out.printf("%2d, %2d, %2d\n", curr, mask, el);
if (!code.contains(el)) {
code.add(el);
genCodes(code, n, el, size);
}
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | gdhucoder/Algorithms4 | leetcode/editor/cn/GrayCode_01.java |
66,153 | package learn.freq02;
import java.util.ArrayList;
//The gray code is a binary numeral system where two successive values differ in only one bit.
//
//Given a non-negative integer n representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.
//
//For example, given n = 2, return [0,1,3,2]. Its gray code sequence is:
//
//00 - 0
//01 - 1
//11 - 3
//10 - 2
//
//Note:
//For a given n, a gray code sequence is not uniquely defined.
//
//For example, [0,2,3,1] is also a valid gray code sequence according to the above definition.
//格雷码转换 输入二进制长度 输出 一条从头转到底的路径
//格雷码定义就是在二进制数字变换时候 不管你有多少bit 每次只能变一个 bit
//像上面的例子一样 如果是2位bit 那么一共就是2*2种=4种数字 你返回的结果一定要把四种数字的int值都返回 但是每2个之间最多变一位 bit
//比方说 n=4时候 需要返回16个数字 从0000开始 但是相邻数字 每次之变1 bit 。 返回一种顺序即可。
//00 - 0
//01 - 1
//11 - 3
//10 - 2
//
//Try one more example, n = 3:
//
//000 - 0
//001 - 1
//011 - 3
//010 - 2
//110 - 6
//111 - 7
//101 - 5
//100 - 4
//看出规律了么 n = 2: [0,1,3,2] and n=3: [0,1,3,2,6,7,5,4]
//前面是一样的 后面6754 就是 [2+4,3+4,1+4,0+4] 0132反过来2310 +4 (3-1)^2
//所以每次递归找出前一层然后再反过来 +(n-1)^2即可
public class GrayCode {
public ArrayList<Integer> grayCode(int n) {
ArrayList<Integer> result = new ArrayList<Integer>();
if (n == 0) { //递归的结束条件 0bit就是0 就这么规定
result.add(0);
return result;
}
ArrayList<Integer> preResult = grayCode(n - 1);
result.addAll(preResult);
//新加的部分把上一层结果反着加。
for (int i = preResult.size() - 1; i >= 0; i--) {
result.add(preResult.get(i) + (int) Math.pow(2, n - 1));
}
return result;
}
}
| duoan/leetcode-java | src/learn/freq02/GrayCode.java |
66,154 | package pp.arithmetic.leetcode;
import pp.arithmetic.Util;
import java.util.ArrayList;
import java.util.List;
/**
* Created by wangpeng on 2019-11-09.
* 89. 格雷编码
* <p>
* 格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
* <p>
* 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。格雷编码序列必须以 0 开头。
* <p>
* 示例 1:
* <p>
* 输入: 2
* 输出: [0,1,3,2]
* 解释:
* 00 - 0
* 01 - 1
* 11 - 3
* 10 - 2
* <p>
* 对于给定的 n,其格雷编码序列并不唯一。
* 例如,[0,2,3,1] 也是一个有效的格雷编码序列。
* <p>
* 00 - 0
* 10 - 2
* 11 - 3
* 01 - 1
* 示例 2:
* <p>
* 输入: 0
* 输出: [0]
* 解释: 我们定义格雷编码序列必须以 0 开头。
* 给定编码总位数为 n 的格雷编码序列,其长度为 2^n。当 n = 0 时,长度为 2^0 = 1。
* 因此,当 n = 0 时,其格雷编码序列为 [0]。
* <p>
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/gray-code
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
public class _89_grayCode {
public static void main(String[] args) {
_89_grayCode grayCode = new _89_grayCode();
Util.printList(grayCode.grayCode(2));
}
/**
* 解题思路:
*
* @param n
* @return
*/
public List<Integer> grayCode(int n) {
List<Integer> gray = new ArrayList<>();
gray.add(0); //初始化 n = 0 的解
for (int i = 0; i < n; i++) {
int add = 1 << i; //要加的数
//倒序遍历,并且加上一个值添加到结果中
for (int j = gray.size() - 1; j >= 0; j--) {
gray.add(gray.get(j) + add);
}
}
return gray;
}
}
| pphdsny/Leetcode-Java | src/pp/arithmetic/leetcode/_89_grayCode.java |
66,155 | #### [89. 格雷编码](https://leetcode-cn.com/problems/gray-code/) + 右移再异或,记忆性题目
难度:Median
### 解题思路
如题。
### 代码
```java
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> ans = new ArrayList<>();
// 因为格雷码长度是 2 的 n 次方
for (int i = 0; i < (1 << n); i++) {
// 通过除 2 后再异或即可完成编码过程
ans.add(i ^ (i >> 1));
}
return ans;
}
}
作者:Jasion_han
链接:https://leetcode-cn.com/problems/gray-code/solution/89ge-lei-bian-ma-you-yi-zai-yi-huo-ji-yi-xing-ti-m/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
```
| Jasion-han/Leetcode | Bit Manipulation/89. 格雷编码.java |
66,156 | /*
* @lc app=leetcode.cn id=89 lang=java
*
* [89] 格雷编码
*/
import java.util.ArrayList;
import java.util.List;
// @lc code=start
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < 1 << n; i++) {
ans.add(i ^ (i >> 1));
}
return ans;
}
}
// @lc code=end
| fireraccoon/leetcode-solutions | src/89.格雷编码.java |
66,157 | package keqing.gtqtcore.client.utils;
import keqing.gtqtcore.GTQTCore;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.*;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
public class TitleUtils {
public static final String DEFAULT_TITLE = "GregTech : Quantum Transition 格雷:量子跃迁 | ModPack Ver:" +GTQTCore.PACK+ " - GTQTCore Ver:"+GTQTCore.VERSION;
public static String currentTitle = null;
public static String TEST = "本整合包当前处于 内测 状态,不保证游戏完整性,仅供体验!";
public static void checkTitleState() {
if (currentTitle == null) {
return;
}
}
public static void setRandomTitle(String STATUE)
{
currentTitle = buildTitle(getrandom(),STATUE);
Display.setTitle(currentTitle);
}
/**
* 设置一言随机标题,可以在其他线程使用。
*
* @param state 当前状态
*/
public static void setRandomTitleSync(String state) {
currentTitle = buildTitle(getrandom(),state);
}
/**
* 设置一言随机标题,可以在其他线程使用。
*/
public static void setRandomTitleSync() {
currentTitle = buildTitle(getrandom(),null);
}
private static String getrandom() {
Random rand = new Random();
int randomNum = rand.nextInt(10);
return switch (randomNum) {
case 1 -> "风不来,树不动;船不摇,水不浑。";
case 2 -> "人生两件事:走路与识人。道曲难行,路直景稀。";
case 3 -> "供人以鱼,只解一餐;授人以渔,终身受用。";
case 4 -> "剑情絮,水梦烛。问其意,意中寻。";
case 5 -> "人经不住千言,树经不住千斧。早上好!";
case 6 -> "随时光而去的是红颜和青丝,与日俱增的是希望和信心。";
case 7 -> "莫将分付东邻子,回首长安佳丽地。";
case 8 -> "残巻生前能伴我,锦衣死后又归谁?";
case 9 -> "悄悄地你走了,正如你悄悄的来。";
default -> "珍爱身体,拒绝熬夜,别让生命戛然而止。";
};
}
public static String buildTitle(String RANDOM,String STATUE) {
//if(STATUE!=null)return String.format("%s | 加载状态:%s | %s",DEFAULT_TITLE,STATUE,TEST);
//return String.format("%s | GTQT官方交流QQ群:494136307 | %s",DEFAULT_TITLE,TEST);
if(STATUE!=null)return String.format("%s | 随机废话:%s | 加载状态:%s | %s",DEFAULT_TITLE,RANDOM,STATUE,TEST);
return String.format("%s | GTQT官方交流QQ群:1073091808 | 随机废话; %s | %s",DEFAULT_TITLE,RANDOM,TEST);
}
} | GTQT/GTQTcore | src/main/java/keqing/gtqtcore/client/utils/TitleUtils.java |
66,159 | /**
<p>The gray code is a binary numeral system where two successive values differ in only one bit.</p>
<p>Given a non-negative integer <em>n</em> representing the total number of bits in the code, print the sequence of gray code. A gray code sequence must begin with 0.</p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> 2
<strong>Output:</strong> <code>[0,1,3,2]</code>
<strong>Explanation:</strong>
00 - 0
01 - 1
11 - 3
10 - 2
For a given <em>n</em>, a gray code sequence may not be uniquely defined.
For example, [0,2,3,1] is also a valid gray code sequence.
00 - 0
10 - 2
11 - 3
01 - 1
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> 0
<strong>Output:</strong> <code>[0]
<strong>Explanation:</strong> We define the gray code sequence to begin with 0.
A gray code sequence of <em>n</em> has size = 2<sup>n</sup>, which for <em>n</em> = 0 the size is 2<sup>0</sup> = 1.
Therefore, for <em>n</em> = 0 the gray code sequence is [0].</code>
</pre>
<p>格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。</p>
<p>给定一个代表编码总位数的非负整数<em> n</em>,打印其格雷编码序列。格雷编码序列必须以 0 开头。</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> 2
<strong>输出:</strong> <code>[0,1,3,2]</code>
<strong>解释:</strong>
00 - 0
01 - 1
11 - 3
10 - 2
对于给定的 <em>n</em>,其格雷编码序列并不唯一。
例如,<code>[0,2,3,1]</code> 也是一个有效的格雷编码序列。
00 - 0
10 - 2
11 - 3
01 - 1</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> 0
<strong>输出:</strong> <code>[0]
<strong>解释:</strong> 我们定义</code>格雷编码序列必须以 0 开头。<code>
给定</code>编码总位数为<code> <em>n</em> 的格雷编码序列,其长度为 2<sup>n</sup></code>。<code>当 <em>n</em> = 0 时,长度为 2<sup>0</sup> = 1。
因此,当 <em>n</em> = 0 时,其格雷编码序列为 [0]。</code>
</pre>
<p>格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。</p>
<p>给定一个代表编码总位数的非负整数<em> n</em>,打印其格雷编码序列。格雷编码序列必须以 0 开头。</p>
<p><strong>示例 1:</strong></p>
<pre><strong>输入:</strong> 2
<strong>输出:</strong> <code>[0,1,3,2]</code>
<strong>解释:</strong>
00 - 0
01 - 1
11 - 3
10 - 2
对于给定的 <em>n</em>,其格雷编码序列并不唯一。
例如,<code>[0,2,3,1]</code> 也是一个有效的格雷编码序列。
00 - 0
10 - 2
11 - 3
01 - 1</pre>
<p><strong>示例 2:</strong></p>
<pre><strong>输入:</strong> 0
<strong>输出:</strong> <code>[0]
<strong>解释:</strong> 我们定义</code>格雷编码序列必须以 0 开头。<code>
给定</code>编码总位数为<code> <em>n</em> 的格雷编码序列,其长度为 2<sup>n</sup></code>。<code>当 <em>n</em> = 0 时,长度为 2<sup>0</sup> = 1。
因此,当 <em>n</em> = 0 时,其格雷编码序列为 [0]。</code>
</pre>
**/
class Solution {
public List<Integer> grayCode(int n) {
}
} | learningtheory/leetcode | java/89.Gray Code(格雷编码).java |
66,162 | package demo001_100;
import java.util.ArrayList;
import java.util.List;
/**
* @author:Sun Hongwei
* @2020/2/19 下午10:51
* File Description:格雷编码: 格雷编码是一个二进制数字系统,在该系统中,
* 两个连续的数值仅有一个位数的差异。
* 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。
* 格雷编码序列必须以 0 开头。
*
*镜像法:先统计完k位的所有编码后,将前面最高位填1,将所有数反过来遍历一遍,加起来即为k+1位的编码
*/
public class demo089 {
public List<Integer> grayCode(int n) {
List<Integer> result=new ArrayList<Integer>();
result.add(0);
int head=1;
for(int i=0;i<n;i++){
for (int j=result.size()-1;j>=0;j--){
result.add(head+result.get(j));
}
head=head<<1;
}
return result;
}
}
| sunhongwei815/my_leetcode_algorithm | demo001-100/demo089.java |
66,163 | package com.bottomlord.week_011;
import java.util.ArrayList;
import java.util.List;
public class LeetCode_89_1_格雷编码 {
public List<Integer> grayCode(int n) {
List<Integer> ans = new ArrayList<Integer>(){{add(0);}};
int head = 1;
for (int i = 0; i < n; i++) {
for (int j = ans.size() - 1; j >= 0; j--) {
ans.add(head + ans.get(j));
}
head <<= 1;
}
return ans;
}
}
| liveForExperience/LeetCodeStudy | src/main/java/com/bottomlord/week_011/LeetCode_89_1_格雷编码.java |
66,164 | package org.zj.anime.bean;
import java.util.Date;
public class Anime {
/**
* 妖精的尾巴连载至276集
* 2016-03-19更新 状态:待更中...
* 类型:日本动漫 热血 动作 神魔
* 发音:日语 地区:日本 年代:2009
* 角色:纳兹·多拉格尼尔 露西·哈特菲利亚
* 声优:大原沙耶香 羽多野涉 佐藤聪美
* 别名:妖精的尾巴第一季/妖精的尾巴第二季
* 剧情:少女露西一直希望能加入云集众多厉害魔法师的名为“妖精尾巴”的公会,在纳兹的引导下,露西终于得偿所愿,随后,露西跟纳兹、格雷、艾尔莎和哈比组成“最强!?”队伍,二男二女一猫的旅程就此展开……展开
*/
private int id;//id
private String name;
private String category;//分类 japan anime dimensional movie
private String version;
private String pic_link;//封面图片连接
private String type;//剧情
private String year;//年代
private String language;//语言
private String loca;//地区
private String role;//角色
private String voice_actor;//声优
private String alias;//别名
private String info;//信息
private String status;//状态
private Date createDate;
public Anime() {
}
@Override
public String toString() {
return "Anime{" +
"id=" + id +
", name='" + name + '\'' +
", category='" + category + '\'' +
", version='" + version + '\'' +
", pic_link='" + pic_link + '\'' +
", plot='" + type + '\'' +
", year='" + year + '\'' +
", language='" + language + '\'' +
", loca='" + loca + '\'' +
", role='" + role + '\'' +
", voice_actor='" + voice_actor + '\'' +
", alias='" + alias + '\'' +
", info='" + info + '\'' +
", status='" + status + '\'' +
", createDate=" + createDate +
'}';
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public Anime(int id, String category, String name, String version, String pic_link, String type, String year, String language, String loca, String role, String voice_actor, String alias, String info, String status, Date createDate) {
this.name=name;
this.id = id;
this.version=version;
this.category = category;
this.pic_link = pic_link;
this.type = type;
this.year = year;
this.language = language;
this.loca = loca;
this.role = role;
this.voice_actor = voice_actor;
this.alias = alias;
this.info = info;
this.status = status;
this.createDate=createDate;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getPic_link() {
return pic_link;
}
public void setPic_link(String pic_link) {
this.pic_link = pic_link;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getLoca() {
return loca;
}
public void setLoca(String loca) {
this.loca = loca;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getVoice_actor() {
return voice_actor;
}
public void setVoice_actor(String voice_actor) {
this.voice_actor = voice_actor;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
| zhangjunapk/anime | src/main/java/org/zj/anime/bean/Anime.java |
66,165 | package cn.qiyubing.algorithm.recursion;
/**
* 生成格雷码
*
* @author qiyubing
* @since 2019-05-12
*/
public class GrayCode {
public static void main(String[] args) {
String[] grayCodes = generate(3);
for (String grayCode : grayCodes) {
System.out.println(grayCode);
}
}
/**
* 递归生成格雷码
*
* @param n 格雷码位数
*/
private static String[] generate(int n) {
if (n == 1) {
return new String[]{"0", "1"};
} else {
// 获取n-1位格雷码的数组
String[] lastCodes = generate(n - 1);
String[] newCodes = new String[2 * lastCodes.length];
// 前半部分加"0"
for (int i = 0; i < lastCodes.length; i++) {
newCodes[i] = "0" + lastCodes[i];
}
// 后半部分加"1"
for (int i = 0; i < lastCodes.length; i++) {
newCodes[newCodes.length - 1 - i] = "1" + lastCodes[i];
}
return newCodes;
}
}
}
| yubinnng/algorithms | other/GrayCode.java |
66,166 | /*
* @lc app=leetcode.cn id=89 lang=java
*
* [89] 格雷编码
*/
// @lc code=start
class Solution {
public List<Integer> grayCode(int n) {
List<Integer> res = new ArrayList<>();
res.add(0);
int head = 1;
while (n > 0) {
for (int i = res.size() - 1; i >= 0; i--) {
res.add(res.get(i) + head);
}
head <<= 1;
n--;
}
return res;
}
}
// @lc code=end
| paterlisia/leetcode-solution | src/Java/practice/first-time/89.格雷编码.java |
66,167 | package chapter1.topic2;
import java.util.ArrayList;
import java.util.List;
/**
* @author donald
* @date 2022/01/08
*
* 89. 格雷编码
*
* n 位格雷码序列 是一个由 2n 个整数组成的序列,其中:
* - 每个整数都在范围 [0, 2n - 1] 内(含 0 和 2n - 1)
* - 第一个整数是 0
* - 一个整数在序列中出现 不超过一次
* - 每对 相邻 整数的二进制表示 恰好一位不同 ,且
* - 第一个 和 最后一个 整数的二进制表示 恰好一位不同
*
* 给你一个整数 n ,返回任一有效的 n 位格雷码序列 。
*
* 示例 1:
* 输入:n = 2
* 输出:[0,1,3,2]
* 解释:
* [0,1,3,2] 的二进制表示是 [00,01,11,10] 。
* - 00 和 01 有一位不同
* - 01 和 11 有一位不同
* - 11 和 10 有一位不同
* - 10 和 00 有一位不同
* [0,2,3,1] 也是一个有效的格雷码序列,其二进制表示是 [00,10,11,01] 。
* - 00 和 10 有一位不同
* - 10 和 11 有一位不同
* - 11 和 01 有一位不同
* - 01 和 00 有一位不同
*
*
* 示例 2:
* 输入:n = 1
* 输出:[0,1]
*/
public class LeetCode_89 {
public List<Integer> grayCode(int n) {
/**
关键是搞清楚格雷编码的生成过程, G(i) = i ^ (i/2);
如 n = 3:
G(0) = 000,
G(1) = 1 ^ 0 = 001 ^ 000 = 001
G(2) = 2 ^ 1 = 010 ^ 001 = 011
G(3) = 3 ^ 1 = 011 ^ 001 = 010
G(4) = 4 ^ 2 = 100 ^ 010 = 110
G(5) = 5 ^ 2 = 101 ^ 010 = 111
G(6) = 6 ^ 3 = 110 ^ 011 = 101
G(7) = 7 ^ 3 = 111 ^ 011 = 100
**/
List<Integer> ret = new ArrayList<>();
for(int i = 0; i < 1<<n; ++i)
ret.add(i ^ i>>1);
return ret;
}
}
| DonaldY/LeetCode-Practice | src/main/java/chapter1/topic2/LeetCode_89.java |
66,168 | package com.daybyday.bit;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: zhaomengyi
* @Date: 2023-02-23 09:40
* @Description:n 位格雷码序列 是一个由 2n 个整数组成的序列,其中:
* 每个整数都在范围 [0, 2n - 1] 内(含 0 和 2n - 1)
* 第一个整数是 0
* 一个整数在序列中出现 不超过一次
* 每对 相邻 整数的二进制表示 恰好一位不同 ,且
* 第一个 和 最后一个 整数的二进制表示 恰好一位不同
* 给你一个整数 n ,返回任一有效的 n 位格雷码序列 。
*/
public class LC0089_GrayCode {
public List<Integer> grayCode(int n) {
//数学结论:格雷编码的每个位置符合要求的数是 G(i) = i ^ (i >> 1)
List<Integer> ans = new ArrayList<Integer>();
ans.add(0);
for(int i = 1; i < 1 << n; i++){
ans.add(i ^ (i >> 1));
}
return ans;
}
}
| tjzhaomengyi/DataStructure-java | src/com/daybyday/bit/LC0089_GrayCode.java |
66,169 | package leetcode.editor.cn;
//格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
//
// 给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。
//
// 格雷编码序列必须以 0 开头。
//
//
//
// 示例 1:
//
// 输入: 2
//输出: [0,1,3,2]
//解释:
//00 - 0
//01 - 1
//11 - 3
//10 - 2
//
//对于给定的 n,其格雷编码序列并不唯一。
//例如,[0,2,3,1] 也是一个有效的格雷编码序列。
//
//00 - 0
//10 - 2
//11 - 3
//01 - 1
//
// 示例 2:
//
// 输入: 0
//输出: [0]
//解释: 我们定义格雷编码序列必须以 0 开头。
// 给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。
// 因此,当 n = 0 时,其格雷编码序列为 [0]。
//
// Related Topics 回溯算法
// 👍 261 👎 0
import java.util.ArrayList;
import java.util.List;
public class _89GrayCode {
public static void main(String[] args) {
Solution t = new _89GrayCode().new Solution();
}
/**
*
*/
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
/**
* 思路:每次新加入一位时,把之前的结果调转,前面加个1
* 如:00 01 11 10,再加一位时,前面四个不变,后四个为 110 111 101 100,刚好是前4个调转后前面加1
*/
public List<Integer> grayCode1(int n) {
List<Integer> answer = new ArrayList<>();
if (n <= 0) {
return answer;
}
answer.add(0);
int head = 1;
for (int i = 0; i < n; i++) {
for (int j = answer.size() - 1; j >= 0; j--) {
answer.add(head + answer.get(j));
}
// 每次左移一位,只有最高位是1
head <<= 1;
}
return answer;
}
public List<Integer> grayCode(int n) {
List<Integer> gray = new ArrayList<Integer>();
for (int binary = 0; binary < 1 << n; binary++) {
gray.add(binary ^ binary >> 1);
}
return gray;
}
}
//leetcode submit region end(Prohibit modification and deletion)
} | uestczhuhao/Algorithms | src/leetcode/editor/cn/_89GrayCode.java |
66,170 | package indi.simon.learning.leetcode.知识性的;
import java.util.ArrayList;
import java.util.List;
/**
* @author chenzhuo(zhiyue)
*/
public class Quiz1238_reviewed_格雷码 {
public static void main(String[] args) {
Quiz1238_reviewed_格雷码 quiz1238_reviewed格雷码 = new Quiz1238_reviewed_格雷码();
List<Integer> res = quiz1238_reviewed格雷码.circularPermutation(3, 2);
System.out.println(res);
}
public List<Integer> circularPermutation(int n, int start) {
List<Integer> ret = new ArrayList<Integer>();
ret.add(start);
for (int i = 1; i <= n; i++) {
int m = ret.size();
for (int j = m - 1; j >= 0; j--) {
ret.add(((ret.get(j) ^ start) | (1 << (i - 1))) ^ start);
}
}
return ret;
}
}
| BugsEverywhere/learning | leetcode/src/main/java/indi/simon/learning/leetcode/知识性的/Quiz1238_reviewed_格雷码.java |
66,171 | package bit_manipulation;
import java.util.ArrayList;
import java.util.List;
/**
* 89. 格雷编码
* n 位格雷码序列 是一个由 2n 个整数组成的序列,其中:
* 每个整数都在范围 [0, 2n - 1] 内(含 0 和 2n - 1)
* 第一个整数是 0
* 一个整数在序列中出现 不超过一次
* 每对 相邻 整数的二进制表示 恰好一位不同 ,且
* 第一个 和 最后一个 整数的二进制表示 恰好一位不同
* 给你一个整数 n ,返回任一有效的 n 位格雷码序列 。
*
* 示例 1:
* 输入:n = 2
* 输出:[0,1,3,2]
* 解释:
* [0,1,3,2] 的二进制表示是 [00,01,11,10] 。
* - 00 和 01 有一位不同
* - 01 和 11 有一位不同
* - 11 和 10 有一位不同
* - 10 和 00 有一位不同
* [0,2,3,1] 也是一个有效的格雷码序列,其二进制表示是 [00,10,11,01] 。
* - 00 和 10 有一位不同
* - 10 和 11 有一位不同
* - 11 和 01 有一位不同
* - 01 和 00 有一位不同
* 示例 2:
* 输入:n = 1
* 输出:[0,1]
*/
public class Problem_0089_GrayCode {
public static List<Integer> grayCode1(int n) {
List<Integer> ans = new ArrayList<>();
ans.add(0);
for (int i = 0; i < n; i++) {
int size = ans.size();
for (int j = size-1; j >= 0; j--) {
int t = ans.get(j) | (1 << i);
ans.add(t);
}
}
return ans;
}
public static List<Integer> grayCode2(int n) {
List<Integer> ans = new ArrayList<>();
for (int i = 0; i < (1<<n); i++) { //0~2^n-1
ans.add(i ^ (i>>1));
}
return ans;
}
public static void main(String[] args) {
System.out.println(grayCode1(2));
System.out.println(grayCode2(2));
}
}
| Joey-df/algorithm-structure | src/bit_manipulation/Problem_0089_GrayCode.java |
66,172 |
// 历史上有许多计算圆周率pai的公式,其中,格雷戈里和莱布尼茨发现了下面的公式:
// pai = 4*(1-1/3+1/5-1/7 ....)
// 参见【图1.png】
// 这个公式简单而优美,但美中不足,它收敛的太慢了。
// 如果我们四舍五入保留它的两位小数,那么:
// 累积1项是:4.00
// 累积2项是:2.67
// 累积3项是:3.47
// 。。。
// 请你写出它累积100项是多少(四舍五入到小数后两位)。
// 注意:只填写该小数本身,不要填写任何多余的说明或解释文字。
public class Main_2 {
public static void main(String[] args) {
double ans = 0;
for (int i = 0; i < 100; i++) {
ans += Math.pow(-1, i) * (1.0 / (2 * i + 1));
// 这里计算公式是 ((-1)^i)
// ______________————————
// _______________2*i+1
}
ans *= 4;
// 结果已经自然四舍五入了
System.out.printf("%.2f", ans); // 3.13
// System.out.println(ans); // 3.1315929035585537
}
}
| 1m188/algorithm | 蓝桥杯/第5届/个人赛省赛/Java大学A组/Main_2.java |
66,173 | package cn.xxt.listviewsample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
/**
* 自定义listview
* @author zhq
* @date 2018/6/8 上午11:33
*/
public class CustomItemActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_item);
ListView lvCustom = findViewById(R.id.lv_custom);
final String[] heros = {"女枪", "凯特琳", "风女", "女坦", "布隆", "璐璐",
"奶妈", "伊泽瑞尔", "维鲁斯", "卢锡安", "格雷福斯"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, R.layout.custom_item
, R.id.tv_content, heros);
lvCustom.setAdapter(adapter);
lvCustom.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(CustomItemActivity.this, "你选择了英雄:" + heros[position]
, Toast.LENGTH_SHORT).show();
}
});
}
}
| Martin-zhq/someexercise | listviewsample/src/main/java/cn/xxt/listviewsample/CustomItemActivity.java |
66,174 | package chapter1_exercise1to500.section2_exercise51to100;
import java.util.ArrayList;
import java.util.List;
/*
格雷编码是一个二进制数字系统,在该系统中,两个连续的数值仅有一个位数的差异。
给定一个代表编码总位数的非负整数 n,打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。
格雷编码序列必须以 0 开头。
示例 1:
输入: 2
输出: [0,1,3,2]
解释:
00 - 0
01 - 1
11 - 3
10 - 2
对于给定的 n,其格雷编码序列并不唯一。
例如,[0,2,3,1] 也是一个有效的格雷编码序列。
00 - 0
10 - 2
11 - 3
01 - 1
示例 2:
输入: 0
输出: [0]
解释: 我们定义格雷编码序列必须以 0 开头。
给定编码总位数为 n 的格雷编码序列,其长度为 2n。当 n = 0 时,长度为 20 = 1。
因此,当 n = 0 时,其格雷编码序列为 [0]。
* */
public class Ex89_GrayCode {
//以下算法击败91% -- --建议修改为用固定大小的静态数组实现,而不是使用java封装动态数组
public List<Integer> grayCode(int n) {
List<Integer>result=new ArrayList<>();
if(n==0){
result.add(0);
return result;
}
int base=1;
result.add(base-1);
result.add(base);
int lt=1;
while(lt<n){
base=(int)Math.pow(2,lt);
int size=result.size();
for(int i=size-1;i>=0;i--){
result.add(base+result.get(i));
}
lt++;
}
return result;
}
}
| AGUAN-RUN/LeetCode_Better_Best | src/chapter1_exercise1to500/section2_exercise51to100/Ex89_GrayCode.java |
66,175 | package DFS.格雷编码89;
import java.util.ArrayList;
import java.util.List;
/**
* 格雷编码是一个二进制数字系统,在该系统中,
* 两个连续的数值仅有一个位数的差异。
*
* 给定一个代表编码总位数的非负整数 n,
* 打印其格雷编码序列。即使有多个不同答案,你也只需要返回其中一种。
*
* 格雷编码序列必须以 0 开头。
*/
/**
* 动态规划找到规律
*/
public class Solution {
public List<Integer> grayCode(int n) {
List<Integer> result = new ArrayList<>();
result.add(0);
for(int i = 0;i<n;i++){
int size = result.size();
int tmp = 1<<i;
for(int j = 0;j<size;j++){
result.add(tmp+result.get(size-1-j));
}
}
return result;
}
}
| JILLXIA/2021leetcode | src/DFS/格雷编码89/Solution.java |
66,176 | /***** Lobxxx Translate Finished ******/
/*
* Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
/*
* (C) Copyright Taligent, Inc. 1996-1998 - All Rights Reserved
* (C) Copyright IBM Corp. 1996-1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
* materials are provided under terms of a License Agreement between Taligent
* and Sun. This technology is protected by multiple US and International
* patents. This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
* <p>
* (C)版权Taligent,Inc 1996-1998 - 保留所有权利(C)版权所有IBM Corp 1996-1998 - 保留所有权利
*
* 此源代码和文档的原始版本由IBM的全资子公司Taligent,Inc拥有版权和所有权。
* 这些资料根据Taligent和Sun之间的许可协议的条款提供此技术受多个美国和国际专利保护Taligent是Taligent的注册商标。Taligent是Taligent的注册商标。
*
*/
package java.util;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoField;
import sun.util.calendar.BaseCalendar;
import sun.util.calendar.CalendarDate;
import sun.util.calendar.CalendarSystem;
import sun.util.calendar.CalendarUtils;
import sun.util.calendar.Era;
import sun.util.calendar.Gregorian;
import sun.util.calendar.JulianCalendar;
import sun.util.calendar.ZoneInfo;
/**
* <code>GregorianCalendar</code> is a concrete subclass of
* <code>Calendar</code> and provides the standard calendar system
* used by most of the world.
*
* <p> <code>GregorianCalendar</code> is a hybrid calendar that
* supports both the Julian and Gregorian calendar systems with the
* support of a single discontinuity, which corresponds by default to
* the Gregorian date when the Gregorian calendar was instituted
* (October 15, 1582 in some countries, later in others). The cutover
* date may be changed by the caller by calling {@link
* #setGregorianChange(Date) setGregorianChange()}.
*
* <p>
* Historically, in those countries which adopted the Gregorian calendar first,
* October 4, 1582 (Julian) was thus followed by October 15, 1582 (Gregorian). This calendar models
* this correctly. Before the Gregorian cutover, <code>GregorianCalendar</code>
* implements the Julian calendar. The only difference between the Gregorian
* and the Julian calendar is the leap year rule. The Julian calendar specifies
* leap years every four years, whereas the Gregorian calendar omits century
* years which are not divisible by 400.
*
* <p>
* <code>GregorianCalendar</code> implements <em>proleptic</em> Gregorian and
* Julian calendars. That is, dates are computed by extrapolating the current
* rules indefinitely far backward and forward in time. As a result,
* <code>GregorianCalendar</code> may be used for all years to generate
* meaningful and consistent results. However, dates obtained using
* <code>GregorianCalendar</code> are historically accurate only from March 1, 4
* AD onward, when modern Julian calendar rules were adopted. Before this date,
* leap year rules were applied irregularly, and before 45 BC the Julian
* calendar did not even exist.
*
* <p>
* Prior to the institution of the Gregorian calendar, New Year's Day was
* March 25. To avoid confusion, this calendar always uses January 1. A manual
* adjustment may be made if desired for dates that are prior to the Gregorian
* changeover and which fall between January 1 and March 24.
*
* <h3><a name="week_and_year">Week Of Year and Week Year</a></h3>
*
* <p>Values calculated for the {@link Calendar#WEEK_OF_YEAR
* WEEK_OF_YEAR} field range from 1 to 53. The first week of a
* calendar year is the earliest seven day period starting on {@link
* Calendar#getFirstDayOfWeek() getFirstDayOfWeek()} that contains at
* least {@link Calendar#getMinimalDaysInFirstWeek()
* getMinimalDaysInFirstWeek()} days from that year. It thus depends
* on the values of {@code getMinimalDaysInFirstWeek()}, {@code
* getFirstDayOfWeek()}, and the day of the week of January 1. Weeks
* between week 1 of one year and week 1 of the following year
* (exclusive) are numbered sequentially from 2 to 52 or 53 (except
* for year(s) involved in the Julian-Gregorian transition).
*
* <p>The {@code getFirstDayOfWeek()} and {@code
* getMinimalDaysInFirstWeek()} values are initialized using
* locale-dependent resources when constructing a {@code
* GregorianCalendar}. <a name="iso8601_compatible_setting">The week
* determination is compatible</a> with the ISO 8601 standard when {@code
* getFirstDayOfWeek()} is {@code MONDAY} and {@code
* getMinimalDaysInFirstWeek()} is 4, which values are used in locales
* where the standard is preferred. These values can explicitly be set by
* calling {@link Calendar#setFirstDayOfWeek(int) setFirstDayOfWeek()} and
* {@link Calendar#setMinimalDaysInFirstWeek(int)
* setMinimalDaysInFirstWeek()}.
*
* <p>A <a name="week_year"><em>week year</em></a> is in sync with a
* {@code WEEK_OF_YEAR} cycle. All weeks between the first and last
* weeks (inclusive) have the same <em>week year</em> value.
* Therefore, the first and last days of a week year may have
* different calendar year values.
*
* <p>For example, January 1, 1998 is a Thursday. If {@code
* getFirstDayOfWeek()} is {@code MONDAY} and {@code
* getMinimalDaysInFirstWeek()} is 4 (ISO 8601 standard compatible
* setting), then week 1 of 1998 starts on December 29, 1997, and ends
* on January 4, 1998. The week year is 1998 for the last three days
* of calendar year 1997. If, however, {@code getFirstDayOfWeek()} is
* {@code SUNDAY}, then week 1 of 1998 starts on January 4, 1998, and
* ends on January 10, 1998; the first three days of 1998 then are
* part of week 53 of 1997 and their week year is 1997.
*
* <h4>Week Of Month</h4>
*
* <p>Values calculated for the <code>WEEK_OF_MONTH</code> field range from 0
* to 6. Week 1 of a month (the days with <code>WEEK_OF_MONTH =
* 1</code>) is the earliest set of at least
* <code>getMinimalDaysInFirstWeek()</code> contiguous days in that month,
* ending on the day before <code>getFirstDayOfWeek()</code>. Unlike
* week 1 of a year, week 1 of a month may be shorter than 7 days, need
* not start on <code>getFirstDayOfWeek()</code>, and will not include days of
* the previous month. Days of a month before week 1 have a
* <code>WEEK_OF_MONTH</code> of 0.
*
* <p>For example, if <code>getFirstDayOfWeek()</code> is <code>SUNDAY</code>
* and <code>getMinimalDaysInFirstWeek()</code> is 4, then the first week of
* January 1998 is Sunday, January 4 through Saturday, January 10. These days
* have a <code>WEEK_OF_MONTH</code> of 1. Thursday, January 1 through
* Saturday, January 3 have a <code>WEEK_OF_MONTH</code> of 0. If
* <code>getMinimalDaysInFirstWeek()</code> is changed to 3, then January 1
* through January 3 have a <code>WEEK_OF_MONTH</code> of 1.
*
* <h4>Default Fields Values</h4>
*
* <p>The <code>clear</code> method sets calendar field(s)
* undefined. <code>GregorianCalendar</code> uses the following
* default value for each calendar field if its value is undefined.
*
* <table cellpadding="0" cellspacing="3" border="0"
* summary="GregorianCalendar default field values"
* style="text-align: left; width: 66%;">
* <tbody>
* <tr>
* <th style="vertical-align: top; background-color: rgb(204, 204, 255);
* text-align: center;">Field<br>
* </th>
* <th style="vertical-align: top; background-color: rgb(204, 204, 255);
* text-align: center;">Default Value<br>
* </th>
* </tr>
* <tr>
* <td style="vertical-align: middle;">
* <code>ERA<br></code>
* </td>
* <td style="vertical-align: middle;">
* <code>AD<br></code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle; background-color: rgb(238, 238, 255);">
* <code>YEAR<br></code>
* </td>
* <td style="vertical-align: middle; background-color: rgb(238, 238, 255);">
* <code>1970<br></code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle;">
* <code>MONTH<br></code>
* </td>
* <td style="vertical-align: middle;">
* <code>JANUARY<br></code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: top; background-color: rgb(238, 238, 255);">
* <code>DAY_OF_MONTH<br></code>
* </td>
* <td style="vertical-align: top; background-color: rgb(238, 238, 255);">
* <code>1<br></code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle;">
* <code>DAY_OF_WEEK<br></code>
* </td>
* <td style="vertical-align: middle;">
* <code>the first day of week<br></code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: top; background-color: rgb(238, 238, 255);">
* <code>WEEK_OF_MONTH<br></code>
* </td>
* <td style="vertical-align: top; background-color: rgb(238, 238, 255);">
* <code>0<br></code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: top;">
* <code>DAY_OF_WEEK_IN_MONTH<br></code>
* </td>
* <td style="vertical-align: top;">
* <code>1<br></code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle; background-color: rgb(238, 238, 255);">
* <code>AM_PM<br></code>
* </td>
* <td style="vertical-align: middle; background-color: rgb(238, 238, 255);">
* <code>AM<br></code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle;">
* <code>HOUR, HOUR_OF_DAY, MINUTE, SECOND, MILLISECOND<br></code>
* </td>
* <td style="vertical-align: middle;">
* <code>0<br></code>
* </td>
* </tr>
* </tbody>
* </table>
* <br>Default values are not applicable for the fields not listed above.
*
* <p>
* <strong>Example:</strong>
* <blockquote>
* <pre>
* // get the supported ids for GMT-08:00 (Pacific Standard Time)
* String[] ids = TimeZone.getAvailableIDs(-8 * 60 * 60 * 1000);
* // if no ids were returned, something is wrong. get out.
* if (ids.length == 0)
* System.exit(0);
*
* // begin output
* System.out.println("Current Time");
*
* // create a Pacific Standard Time time zone
* SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000, ids[0]);
*
* // set up rules for Daylight Saving Time
* pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
* pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
*
* // create a GregorianCalendar with the Pacific Daylight time zone
* // and the current date and time
* Calendar calendar = new GregorianCalendar(pdt);
* Date trialTime = new Date();
* calendar.setTime(trialTime);
*
* // print out a bunch of interesting things
* System.out.println("ERA: " + calendar.get(Calendar.ERA));
* System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
* System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
* System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
* System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
* System.out.println("DATE: " + calendar.get(Calendar.DATE));
* System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
* System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
* System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
* System.out.println("DAY_OF_WEEK_IN_MONTH: "
* + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
* System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
* System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
* System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
* System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
* System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
* System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
* System.out.println("ZONE_OFFSET: "
* + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000)));
* System.out.println("DST_OFFSET: "
* + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000)));
* System.out.println("Current Time, with hour reset to 3");
* calendar.clear(Calendar.HOUR_OF_DAY); // so doesn't override
* calendar.set(Calendar.HOUR, 3);
* System.out.println("ERA: " + calendar.get(Calendar.ERA));
* System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
* System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
* System.out.println("WEEK_OF_YEAR: " + calendar.get(Calendar.WEEK_OF_YEAR));
* System.out.println("WEEK_OF_MONTH: " + calendar.get(Calendar.WEEK_OF_MONTH));
* System.out.println("DATE: " + calendar.get(Calendar.DATE));
* System.out.println("DAY_OF_MONTH: " + calendar.get(Calendar.DAY_OF_MONTH));
* System.out.println("DAY_OF_YEAR: " + calendar.get(Calendar.DAY_OF_YEAR));
* System.out.println("DAY_OF_WEEK: " + calendar.get(Calendar.DAY_OF_WEEK));
* System.out.println("DAY_OF_WEEK_IN_MONTH: "
* + calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH));
* System.out.println("AM_PM: " + calendar.get(Calendar.AM_PM));
* System.out.println("HOUR: " + calendar.get(Calendar.HOUR));
* System.out.println("HOUR_OF_DAY: " + calendar.get(Calendar.HOUR_OF_DAY));
* System.out.println("MINUTE: " + calendar.get(Calendar.MINUTE));
* System.out.println("SECOND: " + calendar.get(Calendar.SECOND));
* System.out.println("MILLISECOND: " + calendar.get(Calendar.MILLISECOND));
* System.out.println("ZONE_OFFSET: "
* + (calendar.get(Calendar.ZONE_OFFSET)/(60*60*1000))); // in hours
* System.out.println("DST_OFFSET: "
* + (calendar.get(Calendar.DST_OFFSET)/(60*60*1000))); // in hours
* </pre>
* </blockquote>
*
* <p>
* <code> GregorianCalendar </code>是<code> Calendar </code>的一个具体子类,提供了大多数世界使用的标准日历系统
*
* <p> <code> GregorianCalendar </code>是一个混合日历,支持Julian和Gregorian日历系统,并支持单个不连续,默认情况下对应于公历日历的公历日期(2010年1
* 0月15日) 1582在一些国家,后来在其他)割接日期可能会改变由调用者通过调用{@link #setGregorianChange(Date)setGregorianChange()}。
*
* <p>
* 历史上,在那些采用公历日历的国家中,1582年10月4日(朱利安)之后是1582年10月15日(Gregorian)。
* 这个日历模型正确在Gregorian切换之前,<code> GregorianCalendar </code>朱利安日历格里高利历和儒略历的唯一区别是闰年规则朱利安历法规定闰年每四年,而公历日历省略不能
* 被400整除的世纪年代。
* 历史上,在那些采用公历日历的国家中,1582年10月4日(朱利安)之后是1582年10月15日(Gregorian)。
*
* <p>
* <code> GregorianCalendar </code>实现<em> proleptian </em> Gregorian和Julian日历也就是说,通过无限远地向后和向前推断当前规则来计算日期
* 结果,<code> GregorianCalendar </code >可以用于所有年份以产生有意义的和一致的结果然而,使用<code> GregorianCalendar </code>获得的日期历史
* 上仅从公元4年3月1日起,当采用现代儒略历日历规则时准确在此日期之前,年规则被不规则地应用,在公元前45年,儒略历甚至不存在。
*
* <p>
* 在制定公历之前,元旦是3月25日为了避免混淆,这个日历总是使用1月1日。如果需要,可以在公历切换之前的日期,并且在1月1日和3月之间的日期进行手动调整24
*
* <h3> <a name=\"week_and_year\">年周年周</a> </h3>
*
* <p>为{@link日历#WEEK_OF_YEAR WEEK_OF_YEAR}字段计算的值范围从1到53一个日历年的第一周是从{@link Calendar#getFirstDayOfWeek()getFirstDayOfWeek()}
* 开始的最早的七天,其中包含至少{@link Calendar#getMinimalDaysInFirstWeek()getMinimalDaysInFirstWeek()}从那一年起它因此取决于{@code getMinimalDaysInFirstWeek()}
* ,{@code getFirstDayOfWeek()}的值和1月1日的星期几一年的第1周和下一年的第1周(不包括)之间的周数从2到52或53(从朱利安 - 格里高利转变中涉及的年份除外)。
*
* <p>构建{@code GregorianCalendar} <a name=\"iso8601_compatible_setting\">星期确定是兼容的时,使用与区域设置相关的资源来初始化{@code getFirstDayOfWeek()}
* 和{@code getMinimalDaysInFirstWeek当{@code getFirstDayOfWeek()}为{@code MONDAY}且{@code getMinimalDaysInFirstWeek()}
* 为4时,使用ISO 8601标准,其中的值在标准为首选的区域设置中使用这些值可以显式地通过调用{@link Calendar#setFirstDayOfWeek(int)setFirstDayOfWeek()}
* 和{@link Calendar#setMinimalDaysInFirstWeek(int)setMinimalDaysInFirstWeek()}。
*
* <p> <a name=\"week_year\"> <em>周年</em> </a>与{@code WEEK_OF_YEAR}周期同步第一周和最后一周之间的所有周都包含相同的<em>周年</em>值因
* 此,一周年的第一天和最后几天可能有不同的日历年值。
*
* <p>例如,1998年1月1日是星期四如果{@code getFirstDayOfWeek()}为{@code MONDAY},{@code getMinimalDaysInFirstWeek()}为4
* (ISO 8601标准兼容设置),则1998年第1周从1997年12月29日开始,到1998年1月4日结束1997年的最后三天的周年是1998年然而,{@code getFirstDayOfWeek()}
* 是{@code SUNDAY},那么第1周1998年1月4日开始,1998年1月10日结束; 1998年头三天是1997年第53周的一部分,其周年是1997年。
*
* <h4>每周几周</h4>
*
* <p>为<code> WEEK_OF_MONTH </code>字段计算的值范围为0到6个月的第1周(具有<code> WEEK_OF_MONTH = 1 </code>的天)是最早的一组,至少<code >
* getMinimalDaysInFirstWeek()</code>该月中的连续日期,结束于<code> getFirstDayOfWeek()</code>与一年中的第1周不同,一个月的第1周可能会
* 少于7天,从<code> getFirstDayOfWeek()</code>开始,并且不包括上一个月的天数。
* 第1周之前的某个月的天数有<code> WEEK_OF_MONTH </code>为0。
*
* <p>例如,如果<code> getFirstDayOfWeek()</code>是<code> SUNDAY </code>和<code> getMinimalDaysInFirstWeek()</code>
* 为4,那么1998年1月的第一周是星期天, 1月4日至1月10日星期六这些日子有<code> WEEK_OF_MONTH </code> 1月1日星期四至1月3日星期六的<code> WEEK_OF_M
* ONTH </code>为0如果<code> getMinimalDaysInFirstWeek / code>更改为3,则1月1日到1月3日的<code> WEEK_OF_MONTH </code>为
* 1。
*
* <h4>默认字段值</h4>
*
* <p> <code> clear </code>方法设置日历字段未定义<code> GregorianCalendar </code>如果每个日历字段的值未定义,则会对其使用以下默认值
*
* <table cellpadding ="0"cellspacing ="3"border ="0"summary ="GregorianCalendar default field values"
* style="text-align: left; width: 66%;">
* <tbody>
* <tr>
* <th style ="vertical-align:top; background-color:rgb(204,204,255); text-align:center;">字段<br>
* </th>
* <th style ="vertical-align:top; background-color:rgb(204,204,255); text-align:center;">默认值<br>
* </th>
* </tr>
* <tr>
* <td style="vertical-align: middle;">
* <code> ERA <br> </code>
* </td>
* <td style="vertical-align: middle;">
* <code> AD <br> </code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle; background-color: rgb(238, 238, 255);">
* <code> YEAR <br> </code>
* </td>
* <td style="vertical-align: middle; background-color: rgb(238, 238, 255);">
* <code> 1970 <br> </code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle;">
* <code> MONTH <br> </code>
* </td>
* <td style="vertical-align: middle;">
* <code> JANUARY <br> </code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: top; background-color: rgb(238, 238, 255);">
* <code> DAY_OF_MONTH <br> </code>
* </td>
* <td style="vertical-align: top; background-color: rgb(238, 238, 255);">
* <code> 1 <br> </code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle;">
* <code> DAY_OF_WEEK <br> </code>
* </td>
* <td style="vertical-align: middle;">
* <code>周的第一天<br> </code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: top; background-color: rgb(238, 238, 255);">
* <code> WEEK_OF_MONTH <br> </code>
* </td>
* <td style="vertical-align: top; background-color: rgb(238, 238, 255);">
* <code> 0 <br> </code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: top;">
* <code> DAY_OF_WEEK_IN_MONTH <br> </code>
* </td>
* <td style="vertical-align: top;">
* <code> 1 <br> </code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle; background-color: rgb(238, 238, 255);">
* <code> AM_PM <br> </code>
* </td>
* <td style="vertical-align: middle; background-color: rgb(238, 238, 255);">
* <code> AM <br> </code>
* </td>
* </tr>
* <tr>
* <td style="vertical-align: middle;">
* <code> HOUR,HOUR_OF_DAY,MINUTE,SECOND,MILLISECOND <br> </code>
* </td>
* <td style="vertical-align: middle;">
* <code> 0 <br> </code>
* </td>
* </tr>
* </tbody>
* </table>
* <br>默认值不适用于上面未列出的字段
*
* <p>
* <strong>示例:</strong>
* <blockquote>
* <pre>
* //获取GMT-08:00(太平洋标准时间)的支持的ID。
* String [] ids = TimeZonegetAvailableIDs(-8 * 60 * 60 * 1000); //如果没有返回ids,则会出错if(idslength == 0)Syste
* mexit(0);。
* //获取GMT-08:00(太平洋标准时间)的支持的ID。
*
* // begin output Systemoutprintln("Current Time");
*
* //创建太平洋标准时间时区SimpleTimeZone pdt = new SimpleTimeZone(-8 * 60 * 60 * 1000,ids [0]);
*
* //为夏令时设置规则pdtsetStartRule(CalendarAPRIL,1,CalendarSUNDAY,2 * 60 * 60 * 1000); pdtsetEndRule(Calendar
* OCTOBER,-1,CalendarSUNDAY,2 * 60 * 60 * 1000);。
*
* //创建一个带太平洋夏令时区域的GregorianCalendar //和当前日期和时间Calendar calendar = new GregorianCalendar(pdt); Date tria
* lTime = new Date(); calendarsetTime(trialTime);。
*
* println("HOUR:"+ calendarget(CalendarHOUR)); Systemoutprintln("HOUR_OF_DAY:"+ calendarget(CalendarHOU
* R_OF_DAY)); Systemoutprintln("MINUTE:"+ calendarget(CalendarMINUTE)); Systemoutprintln("SECOND:"+ cal
* endarget(CalendarSECOND)); Systemoutprintln("MILLISECOND:"+ calendarget(CalendarMILLISECOND)); System
* outprintln("ZONE_OFFSET:"+(calendarget(CalendarZONE_OFFSET)/(60 * 60 * 1000))); Systemoutprintln("DST
* _OFFSET:"+(calendarget(CalendarDST_OFFSET)/(60 * 60 * 1000)));。
*
* Systemoutprintln("当前时间,小时重置为3"); calendarclear(CalendarHOUR_OF_DAY); //所以不重写日历(CalendarHOUR,3); Syste
* moutprintln("ERA:"+ calendarget(CalendarERA)); Systemoutprintln("YEAR:"+ calendarget(CalendarYEAR));
* Systemoutprintln("MONTH:"+ calendarget(CalendarMONTH)); Systemoutprintln("WEEK_OF_YEAR:"+ calendarget
* (CalendarWEEK_OF_YEAR)); Systemoutprintln("WEEK_OF_MONTH:"+ calendarget(CalendarWEEK_OF_MONTH)); Syst
* emoutprintln("DATE:"+ calendarget(CalendarDATE)); Systemoutprintln("DAY_OF_MONTH:"+ calendarget(Calen
* darDAY_OF_MONTH)); Systemoutprintln("DAY_OF_YEAR:"+ calendarget(CalendarDAY_OF_YEAR)); Systemoutprint
* ln("DAY_OF_WEEK:"+ calendarget(CalendarDAY_OF_WEEK)); Systemoutprintln("DAY_OF_WEEK_IN_MONTH:"+ calen
* darget(CalendarDAY_OF_WEEK_IN_MONTH)); Systemoutprintln("AM_PM:"+ calendarget(CalendarAM_PM)); System
* outprintln("HOUR:"+ calendarget(CalendarHOUR)); Systemoutprintln("HOUR_OF_DAY:"+ calendarget(Calendar
* HOUR_OF_DAY)); Systemoutprintln("MINUTE:"+ calendarget(CalendarMINUTE)); Systemoutprintln("SECOND:"+
* calendarget(CalendarSECOND)); Systemoutprintln("MILLISECOND:"+ calendarget(CalendarMILLISECOND)); Sys
* temoutprintln("ZONE_OFFSET:"+(calendarget(CalendarZONE_OFFSET)/(60 * 60 * 1000))); //以小时为单位Systemoutp
* rintln("DST_OFFSET:"+(calendarget(CalendarDST_OFFSET)/(60 * 60 * 1000))); //以小时为单位。
* </pre>
* </blockquote>
*
*
* @see TimeZone
* @author David Goldsmith, Mark Davis, Chen-Lieh Huang, Alan Liu
* @since JDK1.1
*/
public class GregorianCalendar extends Calendar {
/*
* Implementation Notes
*
* The epoch is the number of days or milliseconds from some defined
* starting point. The epoch for java.util.Date is used here; that is,
* milliseconds from January 1, 1970 (Gregorian), midnight UTC. Other
* epochs which are used are January 1, year 1 (Gregorian), which is day 1
* of the Gregorian calendar, and December 30, year 0 (Gregorian), which is
* day 1 of the Julian calendar.
*
* We implement the proleptic Julian and Gregorian calendars. This means we
* implement the modern definition of the calendar even though the
* historical usage differs. For example, if the Gregorian change is set
* to new Date(Long.MIN_VALUE), we have a pure Gregorian calendar which
* labels dates preceding the invention of the Gregorian calendar in 1582 as
* if the calendar existed then.
*
* Likewise, with the Julian calendar, we assume a consistent
* 4-year leap year rule, even though the historical pattern of
* leap years is irregular, being every 3 years from 45 BCE
* through 9 BCE, then every 4 years from 8 CE onwards, with no
* leap years in-between. Thus date computations and functions
* such as isLeapYear() are not intended to be historically
* accurate.
* <p>
* 实现注释
*
* 时代是从某个定义的起始点开始的天数或毫秒数此处使用javautilDate的时期;即从1970年1月1日(格雷戈里安)到午夜UTC的毫秒数。
* 使用的其他时期是1月1日,第1年(格里高利亚),这是公历日历的第1天和12月30日,第0年(格里高利亚)是儒略历的第1天。
*
* 我们实现proleptian朱利安和格里高利历日历这意味着我们实现日历的现代定义,即使历史使用不同例如,如果格雷戈里亚改变设置为新的日期(LongMIN_VALUE),我们有一个纯粹的公历日历标记日期
* 之前在1582年的公历日历的发明,好像日历存在了。
*
* 同样,对于朱利安日历,我们假设一个连续的4年闰年规则,即使闰年的历史模式是不规则的,每3年从公元前45年至公元前9年,然后每4年从公元前8年,没有闰年之间因此日期计算和函数,如isLeapYear()不
* 打算历史上准确。
*
*/
//////////////////
// Class Variables
//////////////////
/**
* Value of the <code>ERA</code> field indicating
* the period before the common era (before Christ), also known as BCE.
* The sequence of years at the transition from <code>BC</code> to <code>AD</code> is
* ..., 2 BC, 1 BC, 1 AD, 2 AD,...
*
* <p>
* <code> ERA </code>字段的值指示在公共时代之前(在基督之前)的时期,也称为BCE从<code> BC </code>到<code> AD < / code>是,2 BC,1 BC,1
* AD,2 AD,。
*
*
* @see #ERA
*/
public static final int BC = 0;
/**
* Value of the {@link #ERA} field indicating
* the period before the common era, the same value as {@link #BC}.
*
* <p>
* 指示通用时代前的时间段的{@link #ERA}字段的值,与{@link #BC}
*
*
* @see #CE
*/
static final int BCE = 0;
/**
* Value of the <code>ERA</code> field indicating
* the common era (Anno Domini), also known as CE.
* The sequence of years at the transition from <code>BC</code> to <code>AD</code> is
* ..., 2 BC, 1 BC, 1 AD, 2 AD,...
*
* <p>
* 表示公共时代(Anno Domini)的<code> ERA </code>字段的值,也称为CE在从<code> BC </code>到<code> AD </code>是,2 BC,1 BC,1 AD
* ,2 AD,。
*
*
* @see #ERA
*/
public static final int AD = 1;
/**
* Value of the {@link #ERA} field indicating
* the common era, the same value as {@link #AD}.
*
* <p>
* 指示公共年龄的{@link #ERA}字段的值,与{@link #AD}的值相同
*
*
* @see #BCE
*/
static final int CE = 1;
private static final int EPOCH_OFFSET = 719163; // Fixed date of January 1, 1970 (Gregorian)
private static final int EPOCH_YEAR = 1970;
static final int MONTH_LENGTH[]
= {31,28,31,30,31,30,31,31,30,31,30,31}; // 0-based
static final int LEAP_MONTH_LENGTH[]
= {31,29,31,30,31,30,31,31,30,31,30,31}; // 0-based
// Useful millisecond constants. Although ONE_DAY and ONE_WEEK can fit
// into ints, they must be longs in order to prevent arithmetic overflow
// when performing (bug 4173516).
private static final int ONE_SECOND = 1000;
private static final int ONE_MINUTE = 60*ONE_SECOND;
private static final int ONE_HOUR = 60*ONE_MINUTE;
private static final long ONE_DAY = 24*ONE_HOUR;
private static final long ONE_WEEK = 7*ONE_DAY;
/*
* <pre>
* Greatest Least
* Field name Minimum Minimum Maximum Maximum
* ---------- ------- ------- ------- -------
* ERA 0 0 1 1
* YEAR 1 1 292269054 292278994
* MONTH 0 0 11 11
* WEEK_OF_YEAR 1 1 52* 53
* WEEK_OF_MONTH 0 0 4* 6
* DAY_OF_MONTH 1 1 28* 31
* DAY_OF_YEAR 1 1 365* 366
* DAY_OF_WEEK 1 1 7 7
* DAY_OF_WEEK_IN_MONTH -1 -1 4* 6
* AM_PM 0 0 1 1
* HOUR 0 0 11 11
* HOUR_OF_DAY 0 0 23 23
* MINUTE 0 0 59 59
* SECOND 0 0 59 59
* MILLISECOND 0 0 999 999
* ZONE_OFFSET -13:00 -13:00 14:00 14:00
* DST_OFFSET 0:00 0:00 0:20 2:00
* </pre>
* *: depends on the Gregorian change date
* <p>
* <pre>
* 最大最小字段名称最小最小最大最大---------- ------- ------- ------- ------- ERA 0 0 1 1年1 1 292269054 292278994 MONTH
* 0 0 11 11 WEEK_OF_YEAR 1 1 52 * 53 WEEK_OF_MONTH 0 0 4 * 6 DAY_OF_MONTH 1 1 28 * 31 DAY_OF_YEAR 1 1 3
* 65 * 366 DAY_OF_WEEK 1 1 7 7 DAY_OF_WEEK_IN_MONTH -1 -1 4 * 6 AM_PM 0 0 1 1 HOUR 0 0 11 11 HOUR_OF_DA
* Y 0 0 23 23 MINUTE 0 0 59 59 SECOND 0 0 59 59 MILLISECOND 0 0 999 999 ZONE_OFFSET -13:00 -13:00 14:00
* 14:00 DST_OFFSET 0:00 0:00 0:20 2:00。
* </pre>
* *:取决于公历变更日期
*
*/
static final int MIN_VALUES[] = {
BCE, // ERA
1, // YEAR
JANUARY, // MONTH
1, // WEEK_OF_YEAR
0, // WEEK_OF_MONTH
1, // DAY_OF_MONTH
1, // DAY_OF_YEAR
SUNDAY, // DAY_OF_WEEK
1, // DAY_OF_WEEK_IN_MONTH
AM, // AM_PM
0, // HOUR
0, // HOUR_OF_DAY
0, // MINUTE
0, // SECOND
0, // MILLISECOND
-13*ONE_HOUR, // ZONE_OFFSET (UNIX compatibility)
0 // DST_OFFSET
};
static final int LEAST_MAX_VALUES[] = {
CE, // ERA
292269054, // YEAR
DECEMBER, // MONTH
52, // WEEK_OF_YEAR
4, // WEEK_OF_MONTH
28, // DAY_OF_MONTH
365, // DAY_OF_YEAR
SATURDAY, // DAY_OF_WEEK
4, // DAY_OF_WEEK_IN
PM, // AM_PM
11, // HOUR
23, // HOUR_OF_DAY
59, // MINUTE
59, // SECOND
999, // MILLISECOND
14*ONE_HOUR, // ZONE_OFFSET
20*ONE_MINUTE // DST_OFFSET (historical least maximum)
};
static final int MAX_VALUES[] = {
CE, // ERA
292278994, // YEAR
DECEMBER, // MONTH
53, // WEEK_OF_YEAR
6, // WEEK_OF_MONTH
31, // DAY_OF_MONTH
366, // DAY_OF_YEAR
SATURDAY, // DAY_OF_WEEK
6, // DAY_OF_WEEK_IN
PM, // AM_PM
11, // HOUR
23, // HOUR_OF_DAY
59, // MINUTE
59, // SECOND
999, // MILLISECOND
14*ONE_HOUR, // ZONE_OFFSET
2*ONE_HOUR // DST_OFFSET (double summer time)
};
// Proclaim serialization compatibility with JDK 1.1
@SuppressWarnings("FieldNameHidesFieldInSuperclass")
static final long serialVersionUID = -8125100834729963327L;
// Reference to the sun.util.calendar.Gregorian instance (singleton).
private static final Gregorian gcal =
CalendarSystem.getGregorianCalendar();
// Reference to the JulianCalendar instance (singleton), set as needed. See
// getJulianCalendarSystem().
private static JulianCalendar jcal;
// JulianCalendar eras. See getJulianCalendarSystem().
private static Era[] jeras;
// The default value of gregorianCutover.
static final long DEFAULT_GREGORIAN_CUTOVER = -12219292800000L;
/////////////////////
// Instance Variables
/////////////////////
/**
* The point at which the Gregorian calendar rules are used, measured in
* milliseconds from the standard epoch. Default is October 15, 1582
* (Gregorian) 00:00:00 UTC or -12219292800000L. For this value, October 4,
* 1582 (Julian) is followed by October 15, 1582 (Gregorian). This
* corresponds to Julian day number 2299161.
* <p>
* 使用公历日历规则的点,以毫秒为单位从标准时期测量默认为1582年10月15日(格里高利亚)00:00:00 UTC或-12219292800000L对于此值,1582年10月4日(朱利安) 1582年
* 10月15日(格里高利亚)这对应于儒略日数2299161。
*
*
* @serial
*/
private long gregorianCutover = DEFAULT_GREGORIAN_CUTOVER;
/**
* The fixed date of the gregorianCutover.
* <p>
* gregorianCutover的固定日期
*
*/
private transient long gregorianCutoverDate =
(((DEFAULT_GREGORIAN_CUTOVER + 1)/ONE_DAY) - 1) + EPOCH_OFFSET; // == 577736
/**
* The normalized year of the gregorianCutover in Gregorian, with
* 0 representing 1 BCE, -1 representing 2 BCE, etc.
* <p>
* 格雷戈里亚的gregorianCutover的归一化年份,0代表1 BCE,-1代表2 BCE等
*
*/
private transient int gregorianCutoverYear = 1582;
/**
* The normalized year of the gregorianCutover in Julian, with 0
* representing 1 BCE, -1 representing 2 BCE, etc.
* <p>
* Julian中gregorianCutover的归一化年份,0代表1 BCE,-1代表2 BCE等
*
*/
private transient int gregorianCutoverYearJulian = 1582;
/**
* gdate always has a sun.util.calendar.Gregorian.Date instance to
* avoid overhead of creating it. The assumption is that most
* applications will need only Gregorian calendar calculations.
* <p>
* gdate总是有一个sunutilcalendarGregorianDate实例,以避免创建它的开销假设是大多数应用程序只需要Gregorian日历计算
*
*/
private transient BaseCalendar.Date gdate;
/**
* Reference to either gdate or a JulianCalendar.Date
* instance. After calling complete(), this value is guaranteed to
* be set.
* <p>
* 引用gdate或JulianCalendarDate实例调用complete()后,将保证设置此值
*
*/
private transient BaseCalendar.Date cdate;
/**
* The CalendarSystem used to calculate the date in cdate. After
* calling complete(), this value is guaranteed to be set and
* consistent with the cdate value.
* <p>
* 用于在cdate中计算日期的CalendarSystem在调用complete()之后,此值将保证设置并与cdate值一致
*
*/
private transient BaseCalendar calsys;
/**
* Temporary int[2] to get time zone offsets. zoneOffsets[0] gets
* the GMT offset value and zoneOffsets[1] gets the DST saving
* value.
* <p>
* 临时int [2]获取时区偏移zoneOffsets [0]获取GMT偏移值,zoneOffsets [1]获取DST保存值
*
*/
private transient int[] zoneOffsets;
/**
* Temporary storage for saving original fields[] values in
* non-lenient mode.
* <p>
* 用于在非宽松模式下保存原始字段[]值的临时存储
*
*/
private transient int[] originalFields;
///////////////
// Constructors
///////////////
/**
* Constructs a default <code>GregorianCalendar</code> using the current time
* in the default time zone with the default
* {@link Locale.Category#FORMAT FORMAT} locale.
* <p>
* 使用默认时区中的当前时间使用默认的{@link LocaleCategory#FORMAT FORMAT}语言环境构造默认<code> GregorianCalendar </code>
*
*/
public GregorianCalendar() {
this(TimeZone.getDefaultRef(), Locale.getDefault(Locale.Category.FORMAT));
setZoneShared(true);
}
/**
* Constructs a <code>GregorianCalendar</code> based on the current time
* in the given time zone with the default
* {@link Locale.Category#FORMAT FORMAT} locale.
*
* <p>
* 根据指定时区中的当前时间使用默认{@link LocaleCategory#FORMAT FORMAT}语言环境构造<code> GregorianCalendar </code>
*
*
* @param zone the given time zone.
*/
public GregorianCalendar(TimeZone zone) {
this(zone, Locale.getDefault(Locale.Category.FORMAT));
}
/**
* Constructs a <code>GregorianCalendar</code> based on the current time
* in the default time zone with the given locale.
*
* <p>
* 根据具有给定语言环境的默认时区中的当前时间构造<code> GregorianCalendar </code>
*
*
* @param aLocale the given locale.
*/
public GregorianCalendar(Locale aLocale) {
this(TimeZone.getDefaultRef(), aLocale);
setZoneShared(true);
}
/**
* Constructs a <code>GregorianCalendar</code> based on the current time
* in the given time zone with the given locale.
*
* <p>
* 根据给定时区中具有给定语言环境的当前时间构造一个<code> GregorianCalendar </code>
*
*
* @param zone the given time zone.
* @param aLocale the given locale.
*/
public GregorianCalendar(TimeZone zone, Locale aLocale) {
super(zone, aLocale);
gdate = (BaseCalendar.Date) gcal.newCalendarDate(zone);
setTimeInMillis(System.currentTimeMillis());
}
/**
* Constructs a <code>GregorianCalendar</code> with the given date set
* in the default time zone with the default locale.
*
* <p>
* 构造一个<code> GregorianCalendar </code>,其中默认时区中使用默认语言环境设置给定日期
*
*
* @param year the value used to set the <code>YEAR</code> calendar field in the calendar.
* @param month the value used to set the <code>MONTH</code> calendar field in the calendar.
* Month value is 0-based. e.g., 0 for January.
* @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar.
*/
public GregorianCalendar(int year, int month, int dayOfMonth) {
this(year, month, dayOfMonth, 0, 0, 0, 0);
}
/**
* Constructs a <code>GregorianCalendar</code> with the given date
* and time set for the default time zone with the default locale.
*
* <p>
* 构造具有为默认时区设置的给定日期和时间的<code> GregorianCalendar </code>,默认时区使用默认语言环境
*
*
* @param year the value used to set the <code>YEAR</code> calendar field in the calendar.
* @param month the value used to set the <code>MONTH</code> calendar field in the calendar.
* Month value is 0-based. e.g., 0 for January.
* @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar.
* @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field
* in the calendar.
* @param minute the value used to set the <code>MINUTE</code> calendar field
* in the calendar.
*/
public GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay,
int minute) {
this(year, month, dayOfMonth, hourOfDay, minute, 0, 0);
}
/**
* Constructs a GregorianCalendar with the given date
* and time set for the default time zone with the default locale.
*
* <p>
* 构造GregorianCalendar,使用默认语言环境为默认时区设置的给定日期和时间
*
*
* @param year the value used to set the <code>YEAR</code> calendar field in the calendar.
* @param month the value used to set the <code>MONTH</code> calendar field in the calendar.
* Month value is 0-based. e.g., 0 for January.
* @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar.
* @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field
* in the calendar.
* @param minute the value used to set the <code>MINUTE</code> calendar field
* in the calendar.
* @param second the value used to set the <code>SECOND</code> calendar field
* in the calendar.
*/
public GregorianCalendar(int year, int month, int dayOfMonth, int hourOfDay,
int minute, int second) {
this(year, month, dayOfMonth, hourOfDay, minute, second, 0);
}
/**
* Constructs a <code>GregorianCalendar</code> with the given date
* and time set for the default time zone with the default locale.
*
* <p>
* 构造具有为默认时区设置的给定日期和时间的<code> GregorianCalendar </code>,默认时区使用默认语言环境
*
*
* @param year the value used to set the <code>YEAR</code> calendar field in the calendar.
* @param month the value used to set the <code>MONTH</code> calendar field in the calendar.
* Month value is 0-based. e.g., 0 for January.
* @param dayOfMonth the value used to set the <code>DAY_OF_MONTH</code> calendar field in the calendar.
* @param hourOfDay the value used to set the <code>HOUR_OF_DAY</code> calendar field
* in the calendar.
* @param minute the value used to set the <code>MINUTE</code> calendar field
* in the calendar.
* @param second the value used to set the <code>SECOND</code> calendar field
* in the calendar.
* @param millis the value used to set the <code>MILLISECOND</code> calendar field
*/
GregorianCalendar(int year, int month, int dayOfMonth,
int hourOfDay, int minute, int second, int millis) {
super();
gdate = (BaseCalendar.Date) gcal.newCalendarDate(getZone());
this.set(YEAR, year);
this.set(MONTH, month);
this.set(DAY_OF_MONTH, dayOfMonth);
// Set AM_PM and HOUR here to set their stamp values before
// setting HOUR_OF_DAY (6178071).
if (hourOfDay >= 12 && hourOfDay <= 23) {
// If hourOfDay is a valid PM hour, set the correct PM values
// so that it won't throw an exception in case it's set to
// non-lenient later.
this.internalSet(AM_PM, PM);
this.internalSet(HOUR, hourOfDay - 12);
} else {
// The default value for AM_PM is AM.
// We don't care any out of range value here for leniency.
this.internalSet(HOUR, hourOfDay);
}
// The stamp values of AM_PM and HOUR must be COMPUTED. (6440854)
setFieldsComputed(HOUR_MASK|AM_PM_MASK);
this.set(HOUR_OF_DAY, hourOfDay);
this.set(MINUTE, minute);
this.set(SECOND, second);
// should be changed to set() when this constructor is made
// public.
this.internalSet(MILLISECOND, millis);
}
/**
* Constructs an empty GregorianCalendar.
*
* <p>
* 构造一个空的GregorianCalendar
*
*
* @param zone the given time zone
* @param aLocale the given locale
* @param flag the flag requesting an empty instance
*/
GregorianCalendar(TimeZone zone, Locale locale, boolean flag) {
super(zone, locale);
gdate = (BaseCalendar.Date) gcal.newCalendarDate(getZone());
}
/////////////////
// Public methods
/////////////////
/**
* Sets the <code>GregorianCalendar</code> change date. This is the point when the switch
* from Julian dates to Gregorian dates occurred. Default is October 15,
* 1582 (Gregorian). Previous to this, dates will be in the Julian calendar.
* <p>
* To obtain a pure Julian calendar, set the change date to
* <code>Date(Long.MAX_VALUE)</code>. To obtain a pure Gregorian calendar,
* set the change date to <code>Date(Long.MIN_VALUE)</code>.
*
* <p>
* 设置<code> GregorianCalendar </code>更改日期这是从Julian日期切换到Gregorian日期的时间点默认值是1582年10月15日(Gregorian)在此之前,日期
* 将在儒略历。
* <p>
* 要获取纯朱利安日历,请将更改日期设置为<code> Date(LongMAX_VALUE)</code>要获取纯Gregorian日历,请将更改日期设置为<code> Date(LongMIN_VALU
* E)</code>。
*
*
* @param date the given Gregorian cutover date.
*/
public void setGregorianChange(Date date) {
long cutoverTime = date.getTime();
if (cutoverTime == gregorianCutover) {
return;
}
// Before changing the cutover date, make sure to have the
// time of this calendar.
complete();
setGregorianChange(cutoverTime);
}
private void setGregorianChange(long cutoverTime) {
gregorianCutover = cutoverTime;
gregorianCutoverDate = CalendarUtils.floorDivide(cutoverTime, ONE_DAY)
+ EPOCH_OFFSET;
// To provide the "pure" Julian calendar as advertised.
// Strictly speaking, the last millisecond should be a
// Gregorian date. However, the API doc specifies that setting
// the cutover date to Long.MAX_VALUE will make this calendar
// a pure Julian calendar. (See 4167995)
if (cutoverTime == Long.MAX_VALUE) {
gregorianCutoverDate++;
}
BaseCalendar.Date d = getGregorianCutoverDate();
// Set the cutover year (in the Gregorian year numbering)
gregorianCutoverYear = d.getYear();
BaseCalendar julianCal = getJulianCalendarSystem();
d = (BaseCalendar.Date) julianCal.newCalendarDate(TimeZone.NO_TIMEZONE);
julianCal.getCalendarDateFromFixedDate(d, gregorianCutoverDate - 1);
gregorianCutoverYearJulian = d.getNormalizedYear();
if (time < gregorianCutover) {
// The field values are no longer valid under the new
// cutover date.
setUnnormalized();
}
}
/**
* Gets the Gregorian Calendar change date. This is the point when the
* switch from Julian dates to Gregorian dates occurred. Default is
* October 15, 1582 (Gregorian). Previous to this, dates will be in the Julian
* calendar.
*
* <p>
* 获取Gregorian日历更改日期这是从Julian日期切换到Gregorian日期的时间点缺省为1582年10月15日(Gregorian)在此之前,日期将在儒略历
*
*
* @return the Gregorian cutover date for this <code>GregorianCalendar</code> object.
*/
public final Date getGregorianChange() {
return new Date(gregorianCutover);
}
/**
* Determines if the given year is a leap year. Returns <code>true</code> if
* the given year is a leap year. To specify BC year numbers,
* <code>1 - year number</code> must be given. For example, year BC 4 is
* specified as -3.
*
* <p>
* 确定给定年份是否为闰年如果给定年份是闰年,则返回<code> true </code>若要指定BC年份数字,必须给定<code> 1年数字</code>例如,年BC 4被指定为-3
*
*
* @param year the given year.
* @return <code>true</code> if the given year is a leap year; <code>false</code> otherwise.
*/
public boolean isLeapYear(int year) {
if ((year & 3) != 0) {
return false;
}
if (year > gregorianCutoverYear) {
return (year%100 != 0) || (year%400 == 0); // Gregorian
}
if (year < gregorianCutoverYearJulian) {
return true; // Julian
}
boolean gregorian;
// If the given year is the Gregorian cutover year, we need to
// determine which calendar system to be applied to February in the year.
if (gregorianCutoverYear == gregorianCutoverYearJulian) {
BaseCalendar.Date d = getCalendarDate(gregorianCutoverDate); // Gregorian
gregorian = d.getMonth() < BaseCalendar.MARCH;
} else {
gregorian = year == gregorianCutoverYear;
}
return gregorian ? (year%100 != 0) || (year%400 == 0) : true;
}
/**
* Returns {@code "gregory"} as the calendar type.
*
* <p>
* 返回{@code"gregory"}作为日历类型
*
*
* @return {@code "gregory"}
* @since 1.8
*/
@Override
public String getCalendarType() {
return "gregory";
}
/**
* Compares this <code>GregorianCalendar</code> to the specified
* <code>Object</code>. The result is <code>true</code> if and
* only if the argument is a <code>GregorianCalendar</code> object
* that represents the same time value (millisecond offset from
* the <a href="Calendar.html#Epoch">Epoch</a>) under the same
* <code>Calendar</code> parameters and Gregorian change date as
* this object.
*
* <p>
* 将<code> GregorianCalendar </code>与指定的<code> Object </code>进行比较。
* 如果且仅当参数是<code> GregorianCalendar </code>对象时,结果是<code> true </code>表示与此对象相同的<code>日历</code>参数和公历变更日期下的
* 相同时间值(与<a href=\"Calendarhtml#Epoch\">时代</a>的毫秒偏移量)。
* 将<code> GregorianCalendar </code>与指定的<code> Object </code>进行比较。
*
*
* @param obj the object to compare with.
* @return <code>true</code> if this object is equal to <code>obj</code>;
* <code>false</code> otherwise.
* @see Calendar#compareTo(Calendar)
*/
@Override
public boolean equals(Object obj) {
return obj instanceof GregorianCalendar &&
super.equals(obj) &&
gregorianCutover == ((GregorianCalendar)obj).gregorianCutover;
}
/**
* Generates the hash code for this <code>GregorianCalendar</code> object.
* <p>
* 为此<code> GregorianCalendar </code>对象生成哈希码
*
*/
@Override
public int hashCode() {
return super.hashCode() ^ (int)gregorianCutoverDate;
}
/**
* Adds the specified (signed) amount of time to the given calendar field,
* based on the calendar's rules.
*
* <p><em>Add rule 1</em>. The value of <code>field</code>
* after the call minus the value of <code>field</code> before the
* call is <code>amount</code>, modulo any overflow that has occurred in
* <code>field</code>. Overflow occurs when a field value exceeds its
* range and, as a result, the next larger field is incremented or
* decremented and the field value is adjusted back into its range.</p>
*
* <p><em>Add rule 2</em>. If a smaller field is expected to be
* invariant, but it is impossible for it to be equal to its
* prior value because of changes in its minimum or maximum after
* <code>field</code> is changed, then its value is adjusted to be as close
* as possible to its expected value. A smaller field represents a
* smaller unit of time. <code>HOUR</code> is a smaller field than
* <code>DAY_OF_MONTH</code>. No adjustment is made to smaller fields
* that are not expected to be invariant. The calendar system
* determines what fields are expected to be invariant.</p>
*
* <p>
* 根据日历规则,将指定的(已签名)时间量添加到给定日历字段
*
* <p> <em>添加规则1 </em>调用之后<code>字段</code>的值减去调用之前<code>字段</code>的值<code> amount </code >,对在<code>字段中发生的任
* 何溢出进行取模</code>当字段值超过其范围时发生溢出,结果是下一个较大字段递增或递减,并且将字段值调回其范围</p>。
*
* <p> <em>添加规则2 </em>如果一个较小的字段预期是不变的,但是它不可能等于其之前的值,因为它的最小值或最大值之后的变化< / code>被改变,则其值被调整为尽可能接近其期望值较小的字段表示
* 较小的时间单位<code> HOUR </code>是比<code> DAY_OF_MONTH </code >不对预期不变的较小字段进行调整日历系统确定哪些字段预期是不变的</p>。
*
*
* @param field the calendar field.
* @param amount the amount of date or time to be added to the field.
* @exception IllegalArgumentException if <code>field</code> is
* <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown,
* or if any calendar fields have out-of-range values in
* non-lenient mode.
*/
@Override
public void add(int field, int amount) {
// If amount == 0, do nothing even the given field is out of
// range. This is tested by JCK.
if (amount == 0) {
return; // Do nothing!
}
if (field < 0 || field >= ZONE_OFFSET) {
throw new IllegalArgumentException();
}
// Sync the time and calendar fields.
complete();
if (field == YEAR) {
int year = internalGet(YEAR);
if (internalGetEra() == CE) {
year += amount;
if (year > 0) {
set(YEAR, year);
} else { // year <= 0
set(YEAR, 1 - year);
// if year == 0, you get 1 BCE.
set(ERA, BCE);
}
}
else { // era == BCE
year -= amount;
if (year > 0) {
set(YEAR, year);
} else { // year <= 0
set(YEAR, 1 - year);
// if year == 0, you get 1 CE
set(ERA, CE);
}
}
pinDayOfMonth();
} else if (field == MONTH) {
int month = internalGet(MONTH) + amount;
int year = internalGet(YEAR);
int y_amount;
if (month >= 0) {
y_amount = month/12;
} else {
y_amount = (month+1)/12 - 1;
}
if (y_amount != 0) {
if (internalGetEra() == CE) {
year += y_amount;
if (year > 0) {
set(YEAR, year);
} else { // year <= 0
set(YEAR, 1 - year);
// if year == 0, you get 1 BCE
set(ERA, BCE);
}
}
else { // era == BCE
year -= y_amount;
if (year > 0) {
set(YEAR, year);
} else { // year <= 0
set(YEAR, 1 - year);
// if year == 0, you get 1 CE
set(ERA, CE);
}
}
}
if (month >= 0) {
set(MONTH, month % 12);
} else {
// month < 0
month %= 12;
if (month < 0) {
month += 12;
}
set(MONTH, JANUARY + month);
}
pinDayOfMonth();
} else if (field == ERA) {
int era = internalGet(ERA) + amount;
if (era < 0) {
era = 0;
}
if (era > 1) {
era = 1;
}
set(ERA, era);
} else {
long delta = amount;
long timeOfDay = 0;
switch (field) {
// Handle the time fields here. Convert the given
// amount to milliseconds and call setTimeInMillis.
case HOUR:
case HOUR_OF_DAY:
delta *= 60 * 60 * 1000; // hours to minutes
break;
case MINUTE:
delta *= 60 * 1000; // minutes to seconds
break;
case SECOND:
delta *= 1000; // seconds to milliseconds
break;
case MILLISECOND:
break;
// Handle week, day and AM_PM fields which involves
// time zone offset change adjustment. Convert the
// given amount to the number of days.
case WEEK_OF_YEAR:
case WEEK_OF_MONTH:
case DAY_OF_WEEK_IN_MONTH:
delta *= 7;
break;
case DAY_OF_MONTH: // synonym of DATE
case DAY_OF_YEAR:
case DAY_OF_WEEK:
break;
case AM_PM:
// Convert the amount to the number of days (delta)
// and +12 or -12 hours (timeOfDay).
delta = amount / 2;
timeOfDay = 12 * (amount % 2);
break;
}
// The time fields don't require time zone offset change
// adjustment.
if (field >= HOUR) {
setTimeInMillis(time + delta);
return;
}
// The rest of the fields (week, day or AM_PM fields)
// require time zone offset (both GMT and DST) change
// adjustment.
// Translate the current time to the fixed date and time
// of the day.
long fd = getCurrentFixedDate();
timeOfDay += internalGet(HOUR_OF_DAY);
timeOfDay *= 60;
timeOfDay += internalGet(MINUTE);
timeOfDay *= 60;
timeOfDay += internalGet(SECOND);
timeOfDay *= 1000;
timeOfDay += internalGet(MILLISECOND);
if (timeOfDay >= ONE_DAY) {
fd++;
timeOfDay -= ONE_DAY;
} else if (timeOfDay < 0) {
fd--;
timeOfDay += ONE_DAY;
}
fd += delta; // fd is the expected fixed date after the calculation
int zoneOffset = internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET);
setTimeInMillis((fd - EPOCH_OFFSET) * ONE_DAY + timeOfDay - zoneOffset);
zoneOffset -= internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET);
// If the time zone offset has changed, then adjust the difference.
if (zoneOffset != 0) {
setTimeInMillis(time + zoneOffset);
long fd2 = getCurrentFixedDate();
// If the adjustment has changed the date, then take
// the previous one.
if (fd2 != fd) {
setTimeInMillis(time - zoneOffset);
}
}
}
}
/**
* Adds or subtracts (up/down) a single unit of time on the given time
* field without changing larger fields.
* <p>
* <em>Example</em>: Consider a <code>GregorianCalendar</code>
* originally set to December 31, 1999. Calling {@link #roll(int,boolean) roll(Calendar.MONTH, true)}
* sets the calendar to January 31, 1999. The <code>YEAR</code> field is unchanged
* because it is a larger field than <code>MONTH</code>.</p>
*
* <p>
* 在给定时间字段上添加或减少(上/下)单个时间单位,而不更改较大字段
* <p>
* <em>示例</em>:考虑最初设置为1999年12月31日的<code> GregorianCalendar </code>。
* 调用{@link #roll(int,boolean)roll(CalendarMONTH,true)}将日历设置为1月31日,1999 <code> YEAR </code>字段未更改,因为它是一个比
* <code> MONTH </code> </p>。
* <em>示例</em>:考虑最初设置为1999年12月31日的<code> GregorianCalendar </code>。
*
*
* @param up indicates if the value of the specified calendar field is to be
* rolled up or rolled down. Use <code>true</code> if rolling up, <code>false</code> otherwise.
* @exception IllegalArgumentException if <code>field</code> is
* <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown,
* or if any calendar fields have out-of-range values in
* non-lenient mode.
* @see #add(int,int)
* @see #set(int,int)
*/
@Override
public void roll(int field, boolean up) {
roll(field, up ? +1 : -1);
}
/**
* Adds a signed amount to the specified calendar field without changing larger fields.
* A negative roll amount means to subtract from field without changing
* larger fields. If the specified amount is 0, this method performs nothing.
*
* <p>This method calls {@link #complete()} before adding the
* amount so that all the calendar fields are normalized. If there
* is any calendar field having an out-of-range value in non-lenient mode, then an
* <code>IllegalArgumentException</code> is thrown.
*
* <p>
* <em>Example</em>: Consider a <code>GregorianCalendar</code>
* originally set to August 31, 1999. Calling <code>roll(Calendar.MONTH,
* 8)</code> sets the calendar to April 30, <strong>1999</strong>. Using a
* <code>GregorianCalendar</code>, the <code>DAY_OF_MONTH</code> field cannot
* be 31 in the month April. <code>DAY_OF_MONTH</code> is set to the closest possible
* value, 30. The <code>YEAR</code> field maintains the value of 1999 because it
* is a larger field than <code>MONTH</code>.
* <p>
* <em>Example</em>: Consider a <code>GregorianCalendar</code>
* originally set to Sunday June 6, 1999. Calling
* <code>roll(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to
* Tuesday June 1, 1999, whereas calling
* <code>add(Calendar.WEEK_OF_MONTH, -1)</code> sets the calendar to
* Sunday May 30, 1999. This is because the roll rule imposes an
* additional constraint: The <code>MONTH</code> must not change when the
* <code>WEEK_OF_MONTH</code> is rolled. Taken together with add rule 1,
* the resultant date must be between Tuesday June 1 and Saturday June
* 5. According to add rule 2, the <code>DAY_OF_WEEK</code>, an invariant
* when changing the <code>WEEK_OF_MONTH</code>, is set to Tuesday, the
* closest possible value to Sunday (where Sunday is the first day of the
* week).</p>
*
* <p>
* 将带符号的金额添加到指定的日历字段而不更改较大的字段负的滚动量意味着从字段中减去而不更改较大的字段如果指定的金额为0,则此方法不执行任何操作
*
* <p>此方法在添加金额之前调用{@link #complete()},以便所有日历字段均正常化如果在非宽松模式下有任何日历字段具有超出范围值,则<code > IllegalArgumentExcep
* tion </code>。
*
* <p>
* <em>示例</em>:考虑一个最初设置为1999年8月31日的<code> GregorianCalendar </code>。
* <call> <code> roll(CalendarMONTH,8)</code> 1999 </strong>使用<code> GregorianCalendar </code>,<code> DA
* Y_OF_MONTH </code>字段在四月中不能为31日<code> DAY_OF_MONTH </code>设置为尽可能接近的值30 <code> YEAR </code>字段保持1999的值,因
* 为它是一个比<code> MONTH </code>。
* <em>示例</em>:考虑一个最初设置为1999年8月31日的<code> GregorianCalendar </code>。
* <p>
* <em> </em>:考虑原来设置为1999年6月6日星期日的<code> GregorianCalendar </code>。
* 调用<code> roll(CalendarWEEK_OF_MONTH,-1)</code> 1999,而调用<code> add(CalendarWEEK_OF_MONTH,-1)</code>将日历
* 设置为1999年5月30日星期五这是因为滚动规则强加了一个附加约束:<code> MONTH </code>当<code> WEEK_OF_MONTH </code>滚动时与添加规则1一起,结果日期必须
* 在6月1日星期六至6月5日星期六之间。
* <em> </em>:考虑原来设置为1999年6月6日星期日的<code> GregorianCalendar </code>。
* 根据添加规则2,<code> DAY_OF_WEEK </code>当更改<code> WEEK_OF_MONTH </code>时,设置为星期二,最接近星期日的可能值(星期日是星期日的第一天)</p>
* 。
* <em> </em>:考虑原来设置为1999年6月6日星期日的<code> GregorianCalendar </code>。
*
*
* @param field the calendar field.
* @param amount the signed amount to add to <code>field</code>.
* @exception IllegalArgumentException if <code>field</code> is
* <code>ZONE_OFFSET</code>, <code>DST_OFFSET</code>, or unknown,
* or if any calendar fields have out-of-range values in
* non-lenient mode.
* @see #roll(int,boolean)
* @see #add(int,int)
* @see #set(int,int)
* @since 1.2
*/
@Override
public void roll(int field, int amount) {
// If amount == 0, do nothing even the given field is out of
// range. This is tested by JCK.
if (amount == 0) {
return;
}
if (field < 0 || field >= ZONE_OFFSET) {
throw new IllegalArgumentException();
}
// Sync the time and calendar fields.
complete();
int min = getMinimum(field);
int max = getMaximum(field);
switch (field) {
case AM_PM:
case ERA:
case YEAR:
case MINUTE:
case SECOND:
case MILLISECOND:
// These fields are handled simply, since they have fixed minima
// and maxima. The field DAY_OF_MONTH is almost as simple. Other
// fields are complicated, since the range within they must roll
// varies depending on the date.
break;
case HOUR:
case HOUR_OF_DAY:
{
int unit = max + 1; // 12 or 24 hours
int h = internalGet(field);
int nh = (h + amount) % unit;
if (nh < 0) {
nh += unit;
}
time += ONE_HOUR * (nh - h);
// The day might have changed, which could happen if
// the daylight saving time transition brings it to
// the next day, although it's very unlikely. But we
// have to make sure not to change the larger fields.
CalendarDate d = calsys.getCalendarDate(time, getZone());
if (internalGet(DAY_OF_MONTH) != d.getDayOfMonth()) {
d.setDate(internalGet(YEAR),
internalGet(MONTH) + 1,
internalGet(DAY_OF_MONTH));
if (field == HOUR) {
assert (internalGet(AM_PM) == PM);
d.addHours(+12); // restore PM
}
time = calsys.getTime(d);
}
int hourOfDay = d.getHours();
internalSet(field, hourOfDay % unit);
if (field == HOUR) {
internalSet(HOUR_OF_DAY, hourOfDay);
} else {
internalSet(AM_PM, hourOfDay / 12);
internalSet(HOUR, hourOfDay % 12);
}
// Time zone offset and/or daylight saving might have changed.
int zoneOffset = d.getZoneOffset();
int saving = d.getDaylightSaving();
internalSet(ZONE_OFFSET, zoneOffset - saving);
internalSet(DST_OFFSET, saving);
return;
}
case MONTH:
// Rolling the month involves both pinning the final value to [0, 11]
// and adjusting the DAY_OF_MONTH if necessary. We only adjust the
// DAY_OF_MONTH if, after updating the MONTH field, it is illegal.
// E.g., <jan31>.roll(MONTH, 1) -> <feb28> or <feb29>.
{
if (!isCutoverYear(cdate.getNormalizedYear())) {
int mon = (internalGet(MONTH) + amount) % 12;
if (mon < 0) {
mon += 12;
}
set(MONTH, mon);
// Keep the day of month in the range. We don't want to spill over
// into the next month; e.g., we don't want jan31 + 1 mo -> feb31 ->
// mar3.
int monthLen = monthLength(mon);
if (internalGet(DAY_OF_MONTH) > monthLen) {
set(DAY_OF_MONTH, monthLen);
}
} else {
// We need to take care of different lengths in
// year and month due to the cutover.
int yearLength = getActualMaximum(MONTH) + 1;
int mon = (internalGet(MONTH) + amount) % yearLength;
if (mon < 0) {
mon += yearLength;
}
set(MONTH, mon);
int monthLen = getActualMaximum(DAY_OF_MONTH);
if (internalGet(DAY_OF_MONTH) > monthLen) {
set(DAY_OF_MONTH, monthLen);
}
}
return;
}
case WEEK_OF_YEAR:
{
int y = cdate.getNormalizedYear();
max = getActualMaximum(WEEK_OF_YEAR);
set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK));
int woy = internalGet(WEEK_OF_YEAR);
int value = woy + amount;
if (!isCutoverYear(y)) {
int weekYear = getWeekYear();
if (weekYear == y) {
// If the new value is in between min and max
// (exclusive), then we can use the value.
if (value > min && value < max) {
set(WEEK_OF_YEAR, value);
return;
}
long fd = getCurrentFixedDate();
// Make sure that the min week has the current DAY_OF_WEEK
// in the calendar year
long day1 = fd - (7 * (woy - min));
if (calsys.getYearFromFixedDate(day1) != y) {
min++;
}
// Make sure the same thing for the max week
fd += 7 * (max - internalGet(WEEK_OF_YEAR));
if (calsys.getYearFromFixedDate(fd) != y) {
max--;
}
} else {
// When WEEK_OF_YEAR and YEAR are out of sync,
// adjust woy and amount to stay in the calendar year.
if (weekYear > y) {
if (amount < 0) {
amount++;
}
woy = max;
} else {
if (amount > 0) {
amount -= woy - max;
}
woy = min;
}
}
set(field, getRolledValue(woy, amount, min, max));
return;
}
// Handle cutover here.
long fd = getCurrentFixedDate();
BaseCalendar cal;
if (gregorianCutoverYear == gregorianCutoverYearJulian) {
cal = getCutoverCalendarSystem();
} else if (y == gregorianCutoverYear) {
cal = gcal;
} else {
cal = getJulianCalendarSystem();
}
long day1 = fd - (7 * (woy - min));
// Make sure that the min week has the current DAY_OF_WEEK
if (cal.getYearFromFixedDate(day1) != y) {
min++;
}
// Make sure the same thing for the max week
fd += 7 * (max - woy);
cal = (fd >= gregorianCutoverDate) ? gcal : getJulianCalendarSystem();
if (cal.getYearFromFixedDate(fd) != y) {
max--;
}
// value: the new WEEK_OF_YEAR which must be converted
// to month and day of month.
value = getRolledValue(woy, amount, min, max) - 1;
BaseCalendar.Date d = getCalendarDate(day1 + value * 7);
set(MONTH, d.getMonth() - 1);
set(DAY_OF_MONTH, d.getDayOfMonth());
return;
}
case WEEK_OF_MONTH:
{
boolean isCutoverYear = isCutoverYear(cdate.getNormalizedYear());
// dow: relative day of week from first day of week
int dow = internalGet(DAY_OF_WEEK) - getFirstDayOfWeek();
if (dow < 0) {
dow += 7;
}
long fd = getCurrentFixedDate();
long month1; // fixed date of the first day (usually 1) of the month
int monthLength; // actual month length
if (isCutoverYear) {
month1 = getFixedDateMonth1(cdate, fd);
monthLength = actualMonthLength();
} else {
month1 = fd - internalGet(DAY_OF_MONTH) + 1;
monthLength = calsys.getMonthLength(cdate);
}
// the first day of week of the month.
long monthDay1st = BaseCalendar.getDayOfWeekDateOnOrBefore(month1 + 6,
getFirstDayOfWeek());
// if the week has enough days to form a week, the
// week starts from the previous month.
if ((int)(monthDay1st - month1) >= getMinimalDaysInFirstWeek()) {
monthDay1st -= 7;
}
max = getActualMaximum(field);
// value: the new WEEK_OF_MONTH value
int value = getRolledValue(internalGet(field), amount, 1, max) - 1;
// nfd: fixed date of the rolled date
long nfd = monthDay1st + value * 7 + dow;
// Unlike WEEK_OF_YEAR, we need to change day of week if the
// nfd is out of the month.
if (nfd < month1) {
nfd = month1;
} else if (nfd >= (month1 + monthLength)) {
nfd = month1 + monthLength - 1;
}
int dayOfMonth;
if (isCutoverYear) {
// If we are in the cutover year, convert nfd to
// its calendar date and use dayOfMonth.
BaseCalendar.Date d = getCalendarDate(nfd);
dayOfMonth = d.getDayOfMonth();
} else {
dayOfMonth = (int)(nfd - month1) + 1;
}
set(DAY_OF_MONTH, dayOfMonth);
return;
}
case DAY_OF_MONTH:
{
if (!isCutoverYear(cdate.getNormalizedYear())) {
max = calsys.getMonthLength(cdate);
break;
}
// Cutover year handling
long fd = getCurrentFixedDate();
long month1 = getFixedDateMonth1(cdate, fd);
// It may not be a regular month. Convert the date and range to
// the relative values, perform the roll, and
// convert the result back to the rolled date.
int value = getRolledValue((int)(fd - month1), amount, 0, actualMonthLength() - 1);
BaseCalendar.Date d = getCalendarDate(month1 + value);
assert d.getMonth()-1 == internalGet(MONTH);
set(DAY_OF_MONTH, d.getDayOfMonth());
return;
}
case DAY_OF_YEAR:
{
max = getActualMaximum(field);
if (!isCutoverYear(cdate.getNormalizedYear())) {
break;
}
// Handle cutover here.
long fd = getCurrentFixedDate();
long jan1 = fd - internalGet(DAY_OF_YEAR) + 1;
int value = getRolledValue((int)(fd - jan1) + 1, amount, min, max);
BaseCalendar.Date d = getCalendarDate(jan1 + value - 1);
set(MONTH, d.getMonth() - 1);
set(DAY_OF_MONTH, d.getDayOfMonth());
return;
}
case DAY_OF_WEEK:
{
if (!isCutoverYear(cdate.getNormalizedYear())) {
// If the week of year is in the same year, we can
// just change DAY_OF_WEEK.
int weekOfYear = internalGet(WEEK_OF_YEAR);
if (weekOfYear > 1 && weekOfYear < 52) {
set(WEEK_OF_YEAR, weekOfYear); // update stamp[WEEK_OF_YEAR]
max = SATURDAY;
break;
}
}
// We need to handle it in a different way around year
// boundaries and in the cutover year. Note that
// changing era and year values violates the roll
// rule: not changing larger calendar fields...
amount %= 7;
if (amount == 0) {
return;
}
long fd = getCurrentFixedDate();
long dowFirst = BaseCalendar.getDayOfWeekDateOnOrBefore(fd, getFirstDayOfWeek());
fd += amount;
if (fd < dowFirst) {
fd += 7;
} else if (fd >= dowFirst + 7) {
fd -= 7;
}
BaseCalendar.Date d = getCalendarDate(fd);
set(ERA, (d.getNormalizedYear() <= 0 ? BCE : CE));
set(d.getYear(), d.getMonth() - 1, d.getDayOfMonth());
return;
}
case DAY_OF_WEEK_IN_MONTH:
{
min = 1; // after normalized, min should be 1.
if (!isCutoverYear(cdate.getNormalizedYear())) {
int dom = internalGet(DAY_OF_MONTH);
int monthLength = calsys.getMonthLength(cdate);
int lastDays = monthLength % 7;
max = monthLength / 7;
int x = (dom - 1) % 7;
if (x < lastDays) {
max++;
}
set(DAY_OF_WEEK, internalGet(DAY_OF_WEEK));
break;
}
// Cutover year handling
long fd = getCurrentFixedDate();
long month1 = getFixedDateMonth1(cdate, fd);
int monthLength = actualMonthLength();
int lastDays = monthLength % 7;
max = monthLength / 7;
int x = (int)(fd - month1) % 7;
if (x < lastDays) {
max++;
}
int value = getRolledValue(internalGet(field), amount, min, max) - 1;
fd = month1 + value * 7 + x;
BaseCalendar cal = (fd >= gregorianCutoverDate) ? gcal : getJulianCalendarSystem();
BaseCalendar.Date d = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE);
cal.getCalendarDateFromFixedDate(d, fd);
set(DAY_OF_MONTH, d.getDayOfMonth());
return;
}
}
set(field, getRolledValue(internalGet(field), amount, min, max));
}
/**
* Returns the minimum value for the given calendar field of this
* <code>GregorianCalendar</code> instance. The minimum value is
* defined as the smallest value returned by the {@link
* Calendar#get(int) get} method for any possible time value,
* taking into consideration the current values of the
* {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
* {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
* {@link #getGregorianChange() getGregorianChange} and
* {@link Calendar#getTimeZone() getTimeZone} methods.
*
* <p>
* 返回此<code> GregorianCalendar </code>实例的给定日历字段的最小值最小值被定义为{@link Calendar#get(int)get}方法为任何可能的时间值返回的最小值,
* 考虑{@link Calendar#getFirstDayOfWeek()getFirstDayOfWeek},{@link Calendar#getMinimalDaysInFirstWeek()getMinimalDaysInFirstWeek}
* ,{@link #getGregorianChange()getGregorianChange}和{@link Calendar#getTimeZone()getTimeZone}方法。
*
*
* @param field the calendar field.
* @return the minimum value for the given calendar field.
* @see #getMaximum(int)
* @see #getGreatestMinimum(int)
* @see #getLeastMaximum(int)
* @see #getActualMinimum(int)
* @see #getActualMaximum(int)
*/
@Override
public int getMinimum(int field) {
return MIN_VALUES[field];
}
/**
* Returns the maximum value for the given calendar field of this
* <code>GregorianCalendar</code> instance. The maximum value is
* defined as the largest value returned by the {@link
* Calendar#get(int) get} method for any possible time value,
* taking into consideration the current values of the
* {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
* {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
* {@link #getGregorianChange() getGregorianChange} and
* {@link Calendar#getTimeZone() getTimeZone} methods.
*
* <p>
* 返回此<code> GregorianCalendar </code>实例的给定日历字段的最大值最大值定义为对于任何可能的时间值,由{@link Calendar#get(int)get}方法返回的最大
* 值,考虑到{@link Calendar#getFirstDayOfWeek()getFirstDayOfWeek},{@link Calendar#getMinimalDaysInFirstWeek()getMinimalDaysInFirstWeek}
* ,{@link #getGregorianChange()getGregorianChange}和{@link Calendar#getTimeZone()getTimeZone}方法。
*
*
* @param field the calendar field.
* @return the maximum value for the given calendar field.
* @see #getMinimum(int)
* @see #getGreatestMinimum(int)
* @see #getLeastMaximum(int)
* @see #getActualMinimum(int)
* @see #getActualMaximum(int)
*/
@Override
public int getMaximum(int field) {
switch (field) {
case MONTH:
case DAY_OF_MONTH:
case DAY_OF_YEAR:
case WEEK_OF_YEAR:
case WEEK_OF_MONTH:
case DAY_OF_WEEK_IN_MONTH:
case YEAR:
{
// On or after Gregorian 200-3-1, Julian and Gregorian
// calendar dates are the same or Gregorian dates are
// larger (i.e., there is a "gap") after 300-3-1.
if (gregorianCutoverYear > 200) {
break;
}
// There might be "overlapping" dates.
GregorianCalendar gc = (GregorianCalendar) clone();
gc.setLenient(true);
gc.setTimeInMillis(gregorianCutover);
int v1 = gc.getActualMaximum(field);
gc.setTimeInMillis(gregorianCutover-1);
int v2 = gc.getActualMaximum(field);
return Math.max(MAX_VALUES[field], Math.max(v1, v2));
}
}
return MAX_VALUES[field];
}
/**
* Returns the highest minimum value for the given calendar field
* of this <code>GregorianCalendar</code> instance. The highest
* minimum value is defined as the largest value returned by
* {@link #getActualMinimum(int)} for any possible time value,
* taking into consideration the current values of the
* {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
* {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
* {@link #getGregorianChange() getGregorianChange} and
* {@link Calendar#getTimeZone() getTimeZone} methods.
*
* <p>
* 返回此<code> GregorianCalendar </code>实例的给定日历字段的最大最小值。
* 最大最小值被定义为对于任何可能的时间值,由{@link #getActualMinimum(int)}返回的最大值,考虑{@link Calendar#getFirstDayOfWeek()getFirstDayOfWeek}
* ,{@link Calendar#getMinimalDaysInFirstWeek()getMinimalDaysInFirstWeek},{@link #getGregorianChange()getGregorianChange}
* 和{@link Calendar#getTimeZone()getTimeZone}方法的当前值。
* 返回此<code> GregorianCalendar </code>实例的给定日历字段的最大最小值。
*
*
* @param field the calendar field.
* @return the highest minimum value for the given calendar field.
* @see #getMinimum(int)
* @see #getMaximum(int)
* @see #getLeastMaximum(int)
* @see #getActualMinimum(int)
* @see #getActualMaximum(int)
*/
@Override
public int getGreatestMinimum(int field) {
if (field == DAY_OF_MONTH) {
BaseCalendar.Date d = getGregorianCutoverDate();
long mon1 = getFixedDateMonth1(d, gregorianCutoverDate);
d = getCalendarDate(mon1);
return Math.max(MIN_VALUES[field], d.getDayOfMonth());
}
return MIN_VALUES[field];
}
/**
* Returns the lowest maximum value for the given calendar field
* of this <code>GregorianCalendar</code> instance. The lowest
* maximum value is defined as the smallest value returned by
* {@link #getActualMaximum(int)} for any possible time value,
* taking into consideration the current values of the
* {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
* {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
* {@link #getGregorianChange() getGregorianChange} and
* {@link Calendar#getTimeZone() getTimeZone} methods.
*
* <p>
* 返回此<code> GregorianCalendar </code>实例的给定日历字段的最小最大值最小的最大值定义为对于任何可能的时间值,由{@link #getActualMaximum(int)}
* 返回的最小值,考虑{@link Calendar#getFirstDayOfWeek()getFirstDayOfWeek},{@link Calendar#getMinimalDaysInFirstWeek()getMinimalDaysInFirstWeek}
* ,{@link #getGregorianChange()getGregorianChange}和{@link Calendar#getTimeZone()getTimeZone}方法的当前值。
*
*
* @param field the calendar field
* @return the lowest maximum value for the given calendar field.
* @see #getMinimum(int)
* @see #getMaximum(int)
* @see #getGreatestMinimum(int)
* @see #getActualMinimum(int)
* @see #getActualMaximum(int)
*/
@Override
public int getLeastMaximum(int field) {
switch (field) {
case MONTH:
case DAY_OF_MONTH:
case DAY_OF_YEAR:
case WEEK_OF_YEAR:
case WEEK_OF_MONTH:
case DAY_OF_WEEK_IN_MONTH:
case YEAR:
{
GregorianCalendar gc = (GregorianCalendar) clone();
gc.setLenient(true);
gc.setTimeInMillis(gregorianCutover);
int v1 = gc.getActualMaximum(field);
gc.setTimeInMillis(gregorianCutover-1);
int v2 = gc.getActualMaximum(field);
return Math.min(LEAST_MAX_VALUES[field], Math.min(v1, v2));
}
}
return LEAST_MAX_VALUES[field];
}
/**
* Returns the minimum value that this calendar field could have,
* taking into consideration the given time value and the current
* values of the
* {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
* {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
* {@link #getGregorianChange() getGregorianChange} and
* {@link Calendar#getTimeZone() getTimeZone} methods.
*
* <p>For example, if the Gregorian change date is January 10,
* 1970 and the date of this <code>GregorianCalendar</code> is
* January 20, 1970, the actual minimum value of the
* <code>DAY_OF_MONTH</code> field is 10 because the previous date
* of January 10, 1970 is December 27, 1996 (in the Julian
* calendar). Therefore, December 28, 1969 to January 9, 1970
* don't exist.
*
* <p>
* 考虑到给定时间值和{@link Calendar#getFirstDayOfWeek()getFirstDayOfWeek}的给定时间值和当前值,返回此日历字段可能具有的最小值,{@link Calendar#getMinimalDaysInFirstWeek()getMinimalDaysInFirstWeek}
* ,{@link# getGregorianChange()getGregorianChange}和{@link Calendar#getTimeZone()getTimeZone}方法。
*
* <p>例如,如果格雷戈里改变日期是1970年1月10日,并且<code> GregorianCalendar </code>的日期是1970年1月20日,则<code> DAY_OF_MONTH </code>
* 字段的实际最小值是10,因为1970年1月10日的前日是1996年12月27日(儒略历)因此,1969年12月28日到1970年1月9日不存在。
*
*
* @param field the calendar field
* @return the minimum of the given field for the time value of
* this <code>GregorianCalendar</code>
* @see #getMinimum(int)
* @see #getMaximum(int)
* @see #getGreatestMinimum(int)
* @see #getLeastMaximum(int)
* @see #getActualMaximum(int)
* @since 1.2
*/
@Override
public int getActualMinimum(int field) {
if (field == DAY_OF_MONTH) {
GregorianCalendar gc = getNormalizedCalendar();
int year = gc.cdate.getNormalizedYear();
if (year == gregorianCutoverYear || year == gregorianCutoverYearJulian) {
long month1 = getFixedDateMonth1(gc.cdate, gc.calsys.getFixedDate(gc.cdate));
BaseCalendar.Date d = getCalendarDate(month1);
return d.getDayOfMonth();
}
}
return getMinimum(field);
}
/**
* Returns the maximum value that this calendar field could have,
* taking into consideration the given time value and the current
* values of the
* {@link Calendar#getFirstDayOfWeek() getFirstDayOfWeek},
* {@link Calendar#getMinimalDaysInFirstWeek() getMinimalDaysInFirstWeek},
* {@link #getGregorianChange() getGregorianChange} and
* {@link Calendar#getTimeZone() getTimeZone} methods.
* For example, if the date of this instance is February 1, 2004,
* the actual maximum value of the <code>DAY_OF_MONTH</code> field
* is 29 because 2004 is a leap year, and if the date of this
* instance is February 1, 2005, it's 28.
*
* <p>This method calculates the maximum value of {@link
* Calendar#WEEK_OF_YEAR WEEK_OF_YEAR} based on the {@link
* Calendar#YEAR YEAR} (calendar year) value, not the <a
* href="#week_year">week year</a>. Call {@link
* #getWeeksInWeekYear()} to get the maximum value of {@code
* WEEK_OF_YEAR} in the week year of this {@code GregorianCalendar}.
*
* <p>
*
* <p>此方法根据{@link Calendar#YEAR YEAR}(日历年)值而不是<a href=\"#week_year\">周年</b>计算{@link日历#WEEK_OF_YEAR WEEK_OF_YEAR}
* 的最大值, a>调用{@link #getWeeksInWeekYear()}可获得此{@code GregorianCalendar}周年的{@code WEEK_OF_YEAR}最大值。
*
*
* @param field the calendar field
* @return the maximum of the given field for the time value of
* this <code>GregorianCalendar</code>
* @see #getMinimum(int)
* @see #getMaximum(int)
* @see #getGreatestMinimum(int)
* @see #getLeastMaximum(int)
* @see #getActualMinimum(int)
* @since 1.2
*/
@Override
public int getActualMaximum(int field) {
final int fieldsForFixedMax = ERA_MASK|DAY_OF_WEEK_MASK|HOUR_MASK|AM_PM_MASK|
HOUR_OF_DAY_MASK|MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK|
ZONE_OFFSET_MASK|DST_OFFSET_MASK;
if ((fieldsForFixedMax & (1<<field)) != 0) {
return getMaximum(field);
}
GregorianCalendar gc = getNormalizedCalendar();
BaseCalendar.Date date = gc.cdate;
BaseCalendar cal = gc.calsys;
int normalizedYear = date.getNormalizedYear();
int value = -1;
switch (field) {
case MONTH:
{
if (!gc.isCutoverYear(normalizedYear)) {
value = DECEMBER;
break;
}
// January 1 of the next year may or may not exist.
long nextJan1;
do {
nextJan1 = gcal.getFixedDate(++normalizedYear, BaseCalendar.JANUARY, 1, null);
} while (nextJan1 < gregorianCutoverDate);
BaseCalendar.Date d = (BaseCalendar.Date) date.clone();
cal.getCalendarDateFromFixedDate(d, nextJan1 - 1);
value = d.getMonth() - 1;
}
break;
case DAY_OF_MONTH:
{
value = cal.getMonthLength(date);
if (!gc.isCutoverYear(normalizedYear) || date.getDayOfMonth() == value) {
break;
}
// Handle cutover year.
long fd = gc.getCurrentFixedDate();
if (fd >= gregorianCutoverDate) {
break;
}
int monthLength = gc.actualMonthLength();
long monthEnd = gc.getFixedDateMonth1(gc.cdate, fd) + monthLength - 1;
// Convert the fixed date to its calendar date.
BaseCalendar.Date d = gc.getCalendarDate(monthEnd);
value = d.getDayOfMonth();
}
break;
case DAY_OF_YEAR:
{
if (!gc.isCutoverYear(normalizedYear)) {
value = cal.getYearLength(date);
break;
}
// Handle cutover year.
long jan1;
if (gregorianCutoverYear == gregorianCutoverYearJulian) {
BaseCalendar cocal = gc.getCutoverCalendarSystem();
jan1 = cocal.getFixedDate(normalizedYear, 1, 1, null);
} else if (normalizedYear == gregorianCutoverYearJulian) {
jan1 = cal.getFixedDate(normalizedYear, 1, 1, null);
} else {
jan1 = gregorianCutoverDate;
}
// January 1 of the next year may or may not exist.
long nextJan1 = gcal.getFixedDate(++normalizedYear, 1, 1, null);
if (nextJan1 < gregorianCutoverDate) {
nextJan1 = gregorianCutoverDate;
}
assert jan1 <= cal.getFixedDate(date.getNormalizedYear(), date.getMonth(),
date.getDayOfMonth(), date);
assert nextJan1 >= cal.getFixedDate(date.getNormalizedYear(), date.getMonth(),
date.getDayOfMonth(), date);
value = (int)(nextJan1 - jan1);
}
break;
case WEEK_OF_YEAR:
{
if (!gc.isCutoverYear(normalizedYear)) {
// Get the day of week of January 1 of the year
CalendarDate d = cal.newCalendarDate(TimeZone.NO_TIMEZONE);
d.setDate(date.getYear(), BaseCalendar.JANUARY, 1);
int dayOfWeek = cal.getDayOfWeek(d);
// Normalize the day of week with the firstDayOfWeek value
dayOfWeek -= getFirstDayOfWeek();
if (dayOfWeek < 0) {
dayOfWeek += 7;
}
value = 52;
int magic = dayOfWeek + getMinimalDaysInFirstWeek() - 1;
if ((magic == 6) ||
(date.isLeapYear() && (magic == 5 || magic == 12))) {
value++;
}
break;
}
if (gc == this) {
gc = (GregorianCalendar) gc.clone();
}
int maxDayOfYear = getActualMaximum(DAY_OF_YEAR);
gc.set(DAY_OF_YEAR, maxDayOfYear);
value = gc.get(WEEK_OF_YEAR);
if (internalGet(YEAR) != gc.getWeekYear()) {
gc.set(DAY_OF_YEAR, maxDayOfYear - 7);
value = gc.get(WEEK_OF_YEAR);
}
}
break;
case WEEK_OF_MONTH:
{
if (!gc.isCutoverYear(normalizedYear)) {
CalendarDate d = cal.newCalendarDate(null);
d.setDate(date.getYear(), date.getMonth(), 1);
int dayOfWeek = cal.getDayOfWeek(d);
int monthLength = cal.getMonthLength(d);
dayOfWeek -= getFirstDayOfWeek();
if (dayOfWeek < 0) {
dayOfWeek += 7;
}
int nDaysFirstWeek = 7 - dayOfWeek; // # of days in the first week
value = 3;
if (nDaysFirstWeek >= getMinimalDaysInFirstWeek()) {
value++;
}
monthLength -= nDaysFirstWeek + 7 * 3;
if (monthLength > 0) {
value++;
if (monthLength > 7) {
value++;
}
}
break;
}
// Cutover year handling
if (gc == this) {
gc = (GregorianCalendar) gc.clone();
}
int y = gc.internalGet(YEAR);
int m = gc.internalGet(MONTH);
do {
value = gc.get(WEEK_OF_MONTH);
gc.add(WEEK_OF_MONTH, +1);
} while (gc.get(YEAR) == y && gc.get(MONTH) == m);
}
break;
case DAY_OF_WEEK_IN_MONTH:
{
// may be in the Gregorian cutover month
int ndays, dow1;
int dow = date.getDayOfWeek();
if (!gc.isCutoverYear(normalizedYear)) {
BaseCalendar.Date d = (BaseCalendar.Date) date.clone();
ndays = cal.getMonthLength(d);
d.setDayOfMonth(1);
cal.normalize(d);
dow1 = d.getDayOfWeek();
} else {
// Let a cloned GregorianCalendar take care of the cutover cases.
if (gc == this) {
gc = (GregorianCalendar) clone();
}
ndays = gc.actualMonthLength();
gc.set(DAY_OF_MONTH, gc.getActualMinimum(DAY_OF_MONTH));
dow1 = gc.get(DAY_OF_WEEK);
}
int x = dow - dow1;
if (x < 0) {
x += 7;
}
ndays -= x;
value = (ndays + 6) / 7;
}
break;
case YEAR:
/* The year computation is no different, in principle, from the
* others, however, the range of possible maxima is large. In
* addition, the way we know we've exceeded the range is different.
* For these reasons, we use the special case code below to handle
* this field.
*
* The actual maxima for YEAR depend on the type of calendar:
*
* Gregorian = May 17, 292275056 BCE - Aug 17, 292278994 CE
* Julian = Dec 2, 292269055 BCE - Jan 3, 292272993 CE
* Hybrid = Dec 2, 292269055 BCE - Aug 17, 292278994 CE
*
* We know we've exceeded the maximum when either the month, date,
* time, or era changes in response to setting the year. We don't
* check for month, date, and time here because the year and era are
* sufficient to detect an invalid year setting. NOTE: If code is
* added to check the month and date in the future for some reason,
* Feb 29 must be allowed to shift to Mar 1 when setting the year.
* <p>
* 其他,然而,可能的最大值的范围是大此外,我们知道我们已经超过范围的方式是不同的由于这些原因,我们使用下面的特殊情况代码来处理这个字段
*
* YEAR的实际最大值取决于日历类型:
*
* Gregorian = May 17,292275056 BCE - Aug 17,292278994 CE Julian = Dec 2,292269055 BCE - Jan 3,2922
* 72993 CE Hybrid = Dec 2,292269055 BCE - Aug 17,292278994 CE。
*
* 我们知道当月,日期,时间或时代因为设置年份而发生变化时,我们已经超出了最大值。
* 我们在这里不检查月份,日期和时间,因为年份和时代足以检测到无效年设置注意:如果由于某种原因添加代码以检查未来的月份和日期,则在设置年份时,必须允许2月29日更改为3月1日。
*
*/
{
if (gc == this) {
gc = (GregorianCalendar) clone();
}
// Calculate the millisecond offset from the beginning
// of the year of this calendar and adjust the max
// year value if we are beyond the limit in the max
// year.
long current = gc.getYearOffsetInMillis();
if (gc.internalGetEra() == CE) {
gc.setTimeInMillis(Long.MAX_VALUE);
value = gc.get(YEAR);
long maxEnd = gc.getYearOffsetInMillis();
if (current > maxEnd) {
value--;
}
} else {
CalendarSystem mincal = gc.getTimeInMillis() >= gregorianCutover ?
gcal : getJulianCalendarSystem();
CalendarDate d = mincal.getCalendarDate(Long.MIN_VALUE, getZone());
long maxEnd = (cal.getDayOfYear(d) - 1) * 24 + d.getHours();
maxEnd *= 60;
maxEnd += d.getMinutes();
maxEnd *= 60;
maxEnd += d.getSeconds();
maxEnd *= 1000;
maxEnd += d.getMillis();
value = d.getYear();
if (value <= 0) {
assert mincal == gcal;
value = 1 - value;
}
if (current < maxEnd) {
value--;
}
}
}
break;
default:
throw new ArrayIndexOutOfBoundsException(field);
}
return value;
}
/**
* Returns the millisecond offset from the beginning of this
* year. This Calendar object must have been normalized.
* <p>
* 返回从今年开始的毫秒偏移量此Calendar对象必须已经过规范化
*
*/
private long getYearOffsetInMillis() {
long t = (internalGet(DAY_OF_YEAR) - 1) * 24;
t += internalGet(HOUR_OF_DAY);
t *= 60;
t += internalGet(MINUTE);
t *= 60;
t += internalGet(SECOND);
t *= 1000;
return t + internalGet(MILLISECOND) -
(internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET));
}
@Override
public Object clone()
{
GregorianCalendar other = (GregorianCalendar) super.clone();
other.gdate = (BaseCalendar.Date) gdate.clone();
if (cdate != null) {
if (cdate != gdate) {
other.cdate = (BaseCalendar.Date) cdate.clone();
} else {
other.cdate = other.gdate;
}
}
other.originalFields = null;
other.zoneOffsets = null;
return other;
}
@Override
public TimeZone getTimeZone() {
TimeZone zone = super.getTimeZone();
// To share the zone by CalendarDates
gdate.setZone(zone);
if (cdate != null && cdate != gdate) {
cdate.setZone(zone);
}
return zone;
}
@Override
public void setTimeZone(TimeZone zone) {
super.setTimeZone(zone);
// To share the zone by CalendarDates
gdate.setZone(zone);
if (cdate != null && cdate != gdate) {
cdate.setZone(zone);
}
}
/**
* Returns {@code true} indicating this {@code GregorianCalendar}
* supports week dates.
*
* <p>
* 返回{@code true}表示此{@code GregorianCalendar}支持星期日期
*
*
* @return {@code true} (always)
* @see #getWeekYear()
* @see #setWeekDate(int,int,int)
* @see #getWeeksInWeekYear()
* @since 1.7
*/
@Override
public final boolean isWeekDateSupported() {
return true;
}
/**
* Returns the <a href="#week_year">week year</a> represented by this
* {@code GregorianCalendar}. The dates in the weeks between 1 and the
* maximum week number of the week year have the same week year value
* that may be one year before or after the {@link Calendar#YEAR YEAR}
* (calendar year) value.
*
* <p>This method calls {@link Calendar#complete()} before
* calculating the week year.
*
* <p>
* 返回由此{@code GregorianCalendar}表示的<a href=\"#week_year\">周年</a> 1周与周年的最大周数之间的周数具有相同的周年值,可能是在{@link日历#YEAR YEAR}
* (日历年)值之前或之后的一年。
*
* <p>此方法在计算周年之前调用{@link Calendar#complete()}
*
*
* @return the week year represented by this {@code GregorianCalendar}.
* If the {@link Calendar#ERA ERA} value is {@link #BC}, the year is
* represented by 0 or a negative number: BC 1 is 0, BC 2
* is -1, BC 3 is -2, and so on.
* @throws IllegalArgumentException
* if any of the calendar fields is invalid in non-lenient mode.
* @see #isWeekDateSupported()
* @see #getWeeksInWeekYear()
* @see Calendar#getFirstDayOfWeek()
* @see Calendar#getMinimalDaysInFirstWeek()
* @since 1.7
*/
@Override
public int getWeekYear() {
int year = get(YEAR); // implicitly calls complete()
if (internalGetEra() == BCE) {
year = 1 - year;
}
// Fast path for the Gregorian calendar years that are never
// affected by the Julian-Gregorian transition
if (year > gregorianCutoverYear + 1) {
int weekOfYear = internalGet(WEEK_OF_YEAR);
if (internalGet(MONTH) == JANUARY) {
if (weekOfYear >= 52) {
--year;
}
} else {
if (weekOfYear == 1) {
++year;
}
}
return year;
}
// General (slow) path
int dayOfYear = internalGet(DAY_OF_YEAR);
int maxDayOfYear = getActualMaximum(DAY_OF_YEAR);
int minimalDays = getMinimalDaysInFirstWeek();
// Quickly check the possibility of year adjustments before
// cloning this GregorianCalendar.
if (dayOfYear > minimalDays && dayOfYear < (maxDayOfYear - 6)) {
return year;
}
// Create a clone to work on the calculation
GregorianCalendar cal = (GregorianCalendar) clone();
cal.setLenient(true);
// Use GMT so that intermediate date calculations won't
// affect the time of day fields.
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
// Go to the first day of the year, which is usually January 1.
cal.set(DAY_OF_YEAR, 1);
cal.complete();
// Get the first day of the first day-of-week in the year.
int delta = getFirstDayOfWeek() - cal.get(DAY_OF_WEEK);
if (delta != 0) {
if (delta < 0) {
delta += 7;
}
cal.add(DAY_OF_YEAR, delta);
}
int minDayOfYear = cal.get(DAY_OF_YEAR);
if (dayOfYear < minDayOfYear) {
if (minDayOfYear <= minimalDays) {
--year;
}
} else {
cal.set(YEAR, year + 1);
cal.set(DAY_OF_YEAR, 1);
cal.complete();
int del = getFirstDayOfWeek() - cal.get(DAY_OF_WEEK);
if (del != 0) {
if (del < 0) {
del += 7;
}
cal.add(DAY_OF_YEAR, del);
}
minDayOfYear = cal.get(DAY_OF_YEAR) - 1;
if (minDayOfYear == 0) {
minDayOfYear = 7;
}
if (minDayOfYear >= minimalDays) {
int days = maxDayOfYear - dayOfYear + 1;
if (days <= (7 - minDayOfYear)) {
++year;
}
}
}
return year;
}
/**
* Sets this {@code GregorianCalendar} to the date given by the
* date specifiers - <a href="#week_year">{@code weekYear}</a>,
* {@code weekOfYear}, and {@code dayOfWeek}. {@code weekOfYear}
* follows the <a href="#week_and_year">{@code WEEK_OF_YEAR}
* numbering</a>. The {@code dayOfWeek} value must be one of the
* {@link Calendar#DAY_OF_WEEK DAY_OF_WEEK} values: {@link
* Calendar#SUNDAY SUNDAY} to {@link Calendar#SATURDAY SATURDAY}.
*
* <p>Note that the numeric day-of-week representation differs from
* the ISO 8601 standard, and that the {@code weekOfYear}
* numbering is compatible with the standard when {@code
* getFirstDayOfWeek()} is {@code MONDAY} and {@code
* getMinimalDaysInFirstWeek()} is 4.
*
* <p>Unlike the {@code set} method, all of the calendar fields
* and the instant of time value are calculated upon return.
*
* <p>If {@code weekOfYear} is out of the valid week-of-year
* range in {@code weekYear}, the {@code weekYear}
* and {@code weekOfYear} values are adjusted in lenient
* mode, or an {@code IllegalArgumentException} is thrown in
* non-lenient mode.
*
* <p>
* 将此{@code GregorianCalendar}设置为日期说明符所指定的日期 - <a href=\"#week_year\"> {@code weekYear} </a>,{@code weekOfYear}
* 和{@code dayOfWeek} {@code weekOfYear}遵循<a href=\"#week_and_year\"> {@code WEEK_OF_YEAR}编号</a> {@code dayOfWeek}
* 值必须是{@link日历#DAY_OF_WEEK DAY_OF_WEEK}值之一:{@link Calendar# SUNDAY SUNDAY}到{@link日历#SATURDAY SATURDAY}。
*
* <p>请注意,星期几的表示与ISO 8601标准不同,{@code getFirstDayOfWeek()}为{@code MONDAY}时,{@code weekOfYear}编号与标准兼容, @c
* ode getMinimalDaysInFirstWeek()}是4。
*
* <p>与{@code set}方法不同,所有日历字段和时间值都会在返回时计算
*
* <p>如果{@code weekOfYear}在{@code weekYear}的有效星期范围之外,{@code weekYear}和{@code weekOfYear}值会在宽松模式下调整,或者{@code weekYear}
* 代码IllegalArgumentException}在非宽松模式中抛出。
*
*
* @param weekYear the week year
* @param weekOfYear the week number based on {@code weekYear}
* @param dayOfWeek the day of week value: one of the constants
* for the {@link #DAY_OF_WEEK DAY_OF_WEEK} field:
* {@link Calendar#SUNDAY SUNDAY}, ...,
* {@link Calendar#SATURDAY SATURDAY}.
* @exception IllegalArgumentException
* if any of the given date specifiers is invalid,
* or if any of the calendar fields are inconsistent
* with the given date specifiers in non-lenient mode
* @see GregorianCalendar#isWeekDateSupported()
* @see Calendar#getFirstDayOfWeek()
* @see Calendar#getMinimalDaysInFirstWeek()
* @since 1.7
*/
@Override
public void setWeekDate(int weekYear, int weekOfYear, int dayOfWeek) {
if (dayOfWeek < SUNDAY || dayOfWeek > SATURDAY) {
throw new IllegalArgumentException("invalid dayOfWeek: " + dayOfWeek);
}
// To avoid changing the time of day fields by date
// calculations, use a clone with the GMT time zone.
GregorianCalendar gc = (GregorianCalendar) clone();
gc.setLenient(true);
int era = gc.get(ERA);
gc.clear();
gc.setTimeZone(TimeZone.getTimeZone("GMT"));
gc.set(ERA, era);
gc.set(YEAR, weekYear);
gc.set(WEEK_OF_YEAR, 1);
gc.set(DAY_OF_WEEK, getFirstDayOfWeek());
int days = dayOfWeek - getFirstDayOfWeek();
if (days < 0) {
days += 7;
}
days += 7 * (weekOfYear - 1);
if (days != 0) {
gc.add(DAY_OF_YEAR, days);
} else {
gc.complete();
}
if (!isLenient() &&
(gc.getWeekYear() != weekYear
|| gc.internalGet(WEEK_OF_YEAR) != weekOfYear
|| gc.internalGet(DAY_OF_WEEK) != dayOfWeek)) {
throw new IllegalArgumentException();
}
set(ERA, gc.internalGet(ERA));
set(YEAR, gc.internalGet(YEAR));
set(MONTH, gc.internalGet(MONTH));
set(DAY_OF_MONTH, gc.internalGet(DAY_OF_MONTH));
// to avoid throwing an IllegalArgumentException in
// non-lenient, set WEEK_OF_YEAR internally
internalSet(WEEK_OF_YEAR, weekOfYear);
complete();
}
/**
* Returns the number of weeks in the <a href="#week_year">week year</a>
* represented by this {@code GregorianCalendar}.
*
* <p>For example, if this {@code GregorianCalendar}'s date is
* December 31, 2008 with <a href="#iso8601_compatible_setting">the ISO
* 8601 compatible setting</a>, this method will return 53 for the
* period: December 29, 2008 to January 3, 2010 while {@link
* #getActualMaximum(int) getActualMaximum(WEEK_OF_YEAR)} will return
* 52 for the period: December 31, 2007 to December 28, 2008.
*
* <p>
* 返回由此{@code GregorianCalendar}表示的<a href=\"#week_year\">周年</a>中的周数
*
* <p>例如,如果{@code GregorianCalendar}的日期为2008年12月31日并且使用<a href=\"#iso8601_compatible_setting\"> ISO 8601
* 兼容设置</a>,则此方法将在以下期间返回53: 2008年12月29日至2010年1月3日,而{@ link #getActualMaximum(int)getActualMaximum(WEEK_OF_YEAR)}
* 将在此期间返回52:2007年12月31日至2008年12月28日。
*
*
* @return the number of weeks in the week year.
* @see Calendar#WEEK_OF_YEAR
* @see #getWeekYear()
* @see #getActualMaximum(int)
* @since 1.7
*/
@Override
public int getWeeksInWeekYear() {
GregorianCalendar gc = getNormalizedCalendar();
int weekYear = gc.getWeekYear();
if (weekYear == gc.internalGet(YEAR)) {
return gc.getActualMaximum(WEEK_OF_YEAR);
}
// Use the 2nd week for calculating the max of WEEK_OF_YEAR
if (gc == this) {
gc = (GregorianCalendar) gc.clone();
}
gc.setWeekDate(weekYear, 2, internalGet(DAY_OF_WEEK));
return gc.getActualMaximum(WEEK_OF_YEAR);
}
/////////////////////////////
// Time => Fields computation
/////////////////////////////
/**
* The fixed date corresponding to gdate. If the value is
* Long.MIN_VALUE, the fixed date value is unknown. Currently,
* Julian calendar dates are not cached.
* <p>
* 与gdate对应的固定日期如果值为LongMIN_VALUE,则固定日期值为unknown目前,不对Julian日历日期进行缓存
*
*/
transient private long cachedFixedDate = Long.MIN_VALUE;
/**
* Converts the time value (millisecond offset from the <a
* href="Calendar.html#Epoch">Epoch</a>) to calendar field values.
* The time is <em>not</em>
* recomputed first; to recompute the time, then the fields, call the
* <code>complete</code> method.
*
* <p>
* 将时间值(与<a href=\"Calendarhtml#Epoch\">时代</a>的毫秒偏移量)转换为日历字段值首先重新计算时间<em> </em>;重新计算时间,然后是字段,调用<code> c
* omplete </code>方法。
*
*
* @see Calendar#complete
*/
@Override
protected void computeFields() {
int mask;
if (isPartiallyNormalized()) {
// Determine which calendar fields need to be computed.
mask = getSetStateFields();
int fieldMask = ~mask & ALL_FIELDS;
// We have to call computTime in case calsys == null in
// order to set calsys and cdate. (6263644)
if (fieldMask != 0 || calsys == null) {
mask |= computeFields(fieldMask,
mask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK));
assert mask == ALL_FIELDS;
}
} else {
mask = ALL_FIELDS;
computeFields(mask, 0);
}
// After computing all the fields, set the field state to `COMPUTED'.
setFieldsComputed(mask);
}
/**
* This computeFields implements the conversion from UTC
* (millisecond offset from the Epoch) to calendar
* field values. fieldMask specifies which fields to change the
* setting state to COMPUTED, although all fields are set to
* the correct values. This is required to fix 4685354.
*
* <p>
* 此computeFields实现从UTC(从Epoch的毫秒偏移)到日历字段值的转换fieldMask指定哪些字段将设置状态更改为COMPUTED,虽然所有字段都设置为正确的值这是需要修复的468535
* 4。
*
*
* @param fieldMask a bit mask to specify which fields to change
* the setting state.
* @param tzMask a bit mask to specify which time zone offset
* fields to be used for time calculations
* @return a new field mask that indicates what field values have
* actually been set.
*/
private int computeFields(int fieldMask, int tzMask) {
int zoneOffset = 0;
TimeZone tz = getZone();
if (zoneOffsets == null) {
zoneOffsets = new int[2];
}
if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) {
if (tz instanceof ZoneInfo) {
zoneOffset = ((ZoneInfo)tz).getOffsets(time, zoneOffsets);
} else {
zoneOffset = tz.getOffset(time);
zoneOffsets[0] = tz.getRawOffset();
zoneOffsets[1] = zoneOffset - zoneOffsets[0];
}
}
if (tzMask != 0) {
if (isFieldSet(tzMask, ZONE_OFFSET)) {
zoneOffsets[0] = internalGet(ZONE_OFFSET);
}
if (isFieldSet(tzMask, DST_OFFSET)) {
zoneOffsets[1] = internalGet(DST_OFFSET);
}
zoneOffset = zoneOffsets[0] + zoneOffsets[1];
}
// By computing time and zoneOffset separately, we can take
// the wider range of time+zoneOffset than the previous
// implementation.
long fixedDate = zoneOffset / ONE_DAY;
int timeOfDay = zoneOffset % (int)ONE_DAY;
fixedDate += time / ONE_DAY;
timeOfDay += (int) (time % ONE_DAY);
if (timeOfDay >= ONE_DAY) {
timeOfDay -= ONE_DAY;
++fixedDate;
} else {
while (timeOfDay < 0) {
timeOfDay += ONE_DAY;
--fixedDate;
}
}
fixedDate += EPOCH_OFFSET;
int era = CE;
int year;
if (fixedDate >= gregorianCutoverDate) {
// Handle Gregorian dates.
assert cachedFixedDate == Long.MIN_VALUE || gdate.isNormalized()
: "cache control: not normalized";
assert cachedFixedDate == Long.MIN_VALUE ||
gcal.getFixedDate(gdate.getNormalizedYear(),
gdate.getMonth(),
gdate.getDayOfMonth(), gdate)
== cachedFixedDate
: "cache control: inconsictency" +
", cachedFixedDate=" + cachedFixedDate +
", computed=" +
gcal.getFixedDate(gdate.getNormalizedYear(),
gdate.getMonth(),
gdate.getDayOfMonth(),
gdate) +
", date=" + gdate;
// See if we can use gdate to avoid date calculation.
if (fixedDate != cachedFixedDate) {
gcal.getCalendarDateFromFixedDate(gdate, fixedDate);
cachedFixedDate = fixedDate;
}
year = gdate.getYear();
if (year <= 0) {
year = 1 - year;
era = BCE;
}
calsys = gcal;
cdate = gdate;
assert cdate.getDayOfWeek() > 0 : "dow="+cdate.getDayOfWeek()+", date="+cdate;
} else {
// Handle Julian calendar dates.
calsys = getJulianCalendarSystem();
cdate = (BaseCalendar.Date) jcal.newCalendarDate(getZone());
jcal.getCalendarDateFromFixedDate(cdate, fixedDate);
Era e = cdate.getEra();
if (e == jeras[0]) {
era = BCE;
}
year = cdate.getYear();
}
// Always set the ERA and YEAR values.
internalSet(ERA, era);
internalSet(YEAR, year);
int mask = fieldMask | (ERA_MASK|YEAR_MASK);
int month = cdate.getMonth() - 1; // 0-based
int dayOfMonth = cdate.getDayOfMonth();
// Set the basic date fields.
if ((fieldMask & (MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK))
!= 0) {
internalSet(MONTH, month);
internalSet(DAY_OF_MONTH, dayOfMonth);
internalSet(DAY_OF_WEEK, cdate.getDayOfWeek());
mask |= MONTH_MASK|DAY_OF_MONTH_MASK|DAY_OF_WEEK_MASK;
}
if ((fieldMask & (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK
|MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK)) != 0) {
if (timeOfDay != 0) {
int hours = timeOfDay / ONE_HOUR;
internalSet(HOUR_OF_DAY, hours);
internalSet(AM_PM, hours / 12); // Assume AM == 0
internalSet(HOUR, hours % 12);
int r = timeOfDay % ONE_HOUR;
internalSet(MINUTE, r / ONE_MINUTE);
r %= ONE_MINUTE;
internalSet(SECOND, r / ONE_SECOND);
internalSet(MILLISECOND, r % ONE_SECOND);
} else {
internalSet(HOUR_OF_DAY, 0);
internalSet(AM_PM, AM);
internalSet(HOUR, 0);
internalSet(MINUTE, 0);
internalSet(SECOND, 0);
internalSet(MILLISECOND, 0);
}
mask |= (HOUR_OF_DAY_MASK|AM_PM_MASK|HOUR_MASK
|MINUTE_MASK|SECOND_MASK|MILLISECOND_MASK);
}
if ((fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) != 0) {
internalSet(ZONE_OFFSET, zoneOffsets[0]);
internalSet(DST_OFFSET, zoneOffsets[1]);
mask |= (ZONE_OFFSET_MASK|DST_OFFSET_MASK);
}
if ((fieldMask & (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK|WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK)) != 0) {
int normalizedYear = cdate.getNormalizedYear();
long fixedDateJan1 = calsys.getFixedDate(normalizedYear, 1, 1, cdate);
int dayOfYear = (int)(fixedDate - fixedDateJan1) + 1;
long fixedDateMonth1 = fixedDate - dayOfMonth + 1;
int cutoverGap = 0;
int cutoverYear = (calsys == gcal) ? gregorianCutoverYear : gregorianCutoverYearJulian;
int relativeDayOfMonth = dayOfMonth - 1;
// If we are in the cutover year, we need some special handling.
if (normalizedYear == cutoverYear) {
// Need to take care of the "missing" days.
if (gregorianCutoverYearJulian <= gregorianCutoverYear) {
// We need to find out where we are. The cutover
// gap could even be more than one year. (One
// year difference in ~48667 years.)
fixedDateJan1 = getFixedDateJan1(cdate, fixedDate);
if (fixedDate >= gregorianCutoverDate) {
fixedDateMonth1 = getFixedDateMonth1(cdate, fixedDate);
}
}
int realDayOfYear = (int)(fixedDate - fixedDateJan1) + 1;
cutoverGap = dayOfYear - realDayOfYear;
dayOfYear = realDayOfYear;
relativeDayOfMonth = (int)(fixedDate - fixedDateMonth1);
}
internalSet(DAY_OF_YEAR, dayOfYear);
internalSet(DAY_OF_WEEK_IN_MONTH, relativeDayOfMonth / 7 + 1);
int weekOfYear = getWeekNumber(fixedDateJan1, fixedDate);
// The spec is to calculate WEEK_OF_YEAR in the
// ISO8601-style. This creates problems, though.
if (weekOfYear == 0) {
// If the date belongs to the last week of the
// previous year, use the week number of "12/31" of
// the "previous" year. Again, if the previous year is
// the Gregorian cutover year, we need to take care of
// it. Usually the previous day of January 1 is
// December 31, which is not always true in
// GregorianCalendar.
long fixedDec31 = fixedDateJan1 - 1;
long prevJan1 = fixedDateJan1 - 365;
if (normalizedYear > (cutoverYear + 1)) {
if (CalendarUtils.isGregorianLeapYear(normalizedYear - 1)) {
--prevJan1;
}
} else if (normalizedYear <= gregorianCutoverYearJulian) {
if (CalendarUtils.isJulianLeapYear(normalizedYear - 1)) {
--prevJan1;
}
} else {
BaseCalendar calForJan1 = calsys;
//int prevYear = normalizedYear - 1;
int prevYear = getCalendarDate(fixedDec31).getNormalizedYear();
if (prevYear == gregorianCutoverYear) {
calForJan1 = getCutoverCalendarSystem();
if (calForJan1 == jcal) {
prevJan1 = calForJan1.getFixedDate(prevYear,
BaseCalendar.JANUARY,
1,
null);
} else {
prevJan1 = gregorianCutoverDate;
calForJan1 = gcal;
}
} else if (prevYear <= gregorianCutoverYearJulian) {
calForJan1 = getJulianCalendarSystem();
prevJan1 = calForJan1.getFixedDate(prevYear,
BaseCalendar.JANUARY,
1,
null);
}
}
weekOfYear = getWeekNumber(prevJan1, fixedDec31);
} else {
if (normalizedYear > gregorianCutoverYear ||
normalizedYear < (gregorianCutoverYearJulian - 1)) {
// Regular years
if (weekOfYear >= 52) {
long nextJan1 = fixedDateJan1 + 365;
if (cdate.isLeapYear()) {
nextJan1++;
}
long nextJan1st = BaseCalendar.getDayOfWeekDateOnOrBefore(nextJan1 + 6,
getFirstDayOfWeek());
int ndays = (int)(nextJan1st - nextJan1);
if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) {
// The first days forms a week in which the date is included.
weekOfYear = 1;
}
}
} else {
BaseCalendar calForJan1 = calsys;
int nextYear = normalizedYear + 1;
if (nextYear == (gregorianCutoverYearJulian + 1) &&
nextYear < gregorianCutoverYear) {
// In case the gap is more than one year.
nextYear = gregorianCutoverYear;
}
if (nextYear == gregorianCutoverYear) {
calForJan1 = getCutoverCalendarSystem();
}
long nextJan1;
if (nextYear > gregorianCutoverYear
|| gregorianCutoverYearJulian == gregorianCutoverYear
|| nextYear == gregorianCutoverYearJulian) {
nextJan1 = calForJan1.getFixedDate(nextYear,
BaseCalendar.JANUARY,
1,
null);
} else {
nextJan1 = gregorianCutoverDate;
calForJan1 = gcal;
}
long nextJan1st = BaseCalendar.getDayOfWeekDateOnOrBefore(nextJan1 + 6,
getFirstDayOfWeek());
int ndays = (int)(nextJan1st - nextJan1);
if (ndays >= getMinimalDaysInFirstWeek() && fixedDate >= (nextJan1st - 7)) {
// The first days forms a week in which the date is included.
weekOfYear = 1;
}
}
}
internalSet(WEEK_OF_YEAR, weekOfYear);
internalSet(WEEK_OF_MONTH, getWeekNumber(fixedDateMonth1, fixedDate));
mask |= (DAY_OF_YEAR_MASK|WEEK_OF_YEAR_MASK|WEEK_OF_MONTH_MASK|DAY_OF_WEEK_IN_MONTH_MASK);
}
return mask;
}
/**
* Returns the number of weeks in a period between fixedDay1 and
* fixedDate. The getFirstDayOfWeek-getMinimalDaysInFirstWeek rule
* is applied to calculate the number of weeks.
*
* <p>
* 返回在fixedDay1和fixedDate之间的周期内的周数getFirstDayOfWeek-getMinimalDaysInFirstWeek规则用于计算周数
*
*
* @param fixedDay1 the fixed date of the first day of the period
* @param fixedDate the fixed date of the last day of the period
* @return the number of weeks of the given period
*/
private int getWeekNumber(long fixedDay1, long fixedDate) {
// We can always use `gcal' since Julian and Gregorian are the
// same thing for this calculation.
long fixedDay1st = Gregorian.getDayOfWeekDateOnOrBefore(fixedDay1 + 6,
getFirstDayOfWeek());
int ndays = (int)(fixedDay1st - fixedDay1);
assert ndays <= 7;
if (ndays >= getMinimalDaysInFirstWeek()) {
fixedDay1st -= 7;
}
int normalizedDayOfPeriod = (int)(fixedDate - fixedDay1st);
if (normalizedDayOfPeriod >= 0) {
return normalizedDayOfPeriod / 7 + 1;
}
return CalendarUtils.floorDivide(normalizedDayOfPeriod, 7) + 1;
}
/**
* Converts calendar field values to the time value (millisecond
* offset from the <a href="Calendar.html#Epoch">Epoch</a>).
*
* <p>
* 将日历字段值转换为时间值(距离<a href=\"Calendarhtml#Epoch\">时代的毫秒偏移量</a>)
*
*
* @exception IllegalArgumentException if any calendar fields are invalid.
*/
@Override
protected void computeTime() {
// In non-lenient mode, perform brief checking of calendar
// fields which have been set externally. Through this
// checking, the field values are stored in originalFields[]
// to see if any of them are normalized later.
if (!isLenient()) {
if (originalFields == null) {
originalFields = new int[FIELD_COUNT];
}
for (int field = 0; field < FIELD_COUNT; field++) {
int value = internalGet(field);
if (isExternallySet(field)) {
// Quick validation for any out of range values
if (value < getMinimum(field) || value > getMaximum(field)) {
throw new IllegalArgumentException(getFieldName(field));
}
}
originalFields[field] = value;
}
}
// Let the super class determine which calendar fields to be
// used to calculate the time.
int fieldMask = selectFields();
// The year defaults to the epoch start. We don't check
// fieldMask for YEAR because YEAR is a mandatory field to
// determine the date.
int year = isSet(YEAR) ? internalGet(YEAR) : EPOCH_YEAR;
int era = internalGetEra();
if (era == BCE) {
year = 1 - year;
} else if (era != CE) {
// Even in lenient mode we disallow ERA values other than CE & BCE.
// (The same normalization rule as add()/roll() could be
// applied here in lenient mode. But this checking is kept
// unchanged for compatibility as of 1.5.)
throw new IllegalArgumentException("Invalid era");
}
// If year is 0 or negative, we need to set the ERA value later.
if (year <= 0 && !isSet(ERA)) {
fieldMask |= ERA_MASK;
setFieldsComputed(ERA_MASK);
}
// Calculate the time of day. We rely on the convention that
// an UNSET field has 0.
long timeOfDay = 0;
if (isFieldSet(fieldMask, HOUR_OF_DAY)) {
timeOfDay += (long) internalGet(HOUR_OF_DAY);
} else {
timeOfDay += internalGet(HOUR);
// The default value of AM_PM is 0 which designates AM.
if (isFieldSet(fieldMask, AM_PM)) {
timeOfDay += 12 * internalGet(AM_PM);
}
}
timeOfDay *= 60;
timeOfDay += internalGet(MINUTE);
timeOfDay *= 60;
timeOfDay += internalGet(SECOND);
timeOfDay *= 1000;
timeOfDay += internalGet(MILLISECOND);
// Convert the time of day to the number of days and the
// millisecond offset from midnight.
long fixedDate = timeOfDay / ONE_DAY;
timeOfDay %= ONE_DAY;
while (timeOfDay < 0) {
timeOfDay += ONE_DAY;
--fixedDate;
}
// Calculate the fixed date since January 1, 1 (Gregorian).
calculateFixedDate: {
long gfd, jfd;
if (year > gregorianCutoverYear && year > gregorianCutoverYearJulian) {
gfd = fixedDate + getFixedDate(gcal, year, fieldMask);
if (gfd >= gregorianCutoverDate) {
fixedDate = gfd;
break calculateFixedDate;
}
jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask);
} else if (year < gregorianCutoverYear && year < gregorianCutoverYearJulian) {
jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask);
if (jfd < gregorianCutoverDate) {
fixedDate = jfd;
break calculateFixedDate;
}
gfd = jfd;
} else {
jfd = fixedDate + getFixedDate(getJulianCalendarSystem(), year, fieldMask);
gfd = fixedDate + getFixedDate(gcal, year, fieldMask);
}
// Now we have to determine which calendar date it is.
// If the date is relative from the beginning of the year
// in the Julian calendar, then use jfd;
if (isFieldSet(fieldMask, DAY_OF_YEAR) || isFieldSet(fieldMask, WEEK_OF_YEAR)) {
if (gregorianCutoverYear == gregorianCutoverYearJulian) {
fixedDate = jfd;
break calculateFixedDate;
} else if (year == gregorianCutoverYear) {
fixedDate = gfd;
break calculateFixedDate;
}
}
if (gfd >= gregorianCutoverDate) {
if (jfd >= gregorianCutoverDate) {
fixedDate = gfd;
} else {
// The date is in an "overlapping" period. No way
// to disambiguate it. Determine it using the
// previous date calculation.
if (calsys == gcal || calsys == null) {
fixedDate = gfd;
} else {
fixedDate = jfd;
}
}
} else {
if (jfd < gregorianCutoverDate) {
fixedDate = jfd;
} else {
// The date is in a "missing" period.
if (!isLenient()) {
throw new IllegalArgumentException("the specified date doesn't exist");
}
// Take the Julian date for compatibility, which
// will produce a Gregorian date.
fixedDate = jfd;
}
}
}
// millis represents local wall-clock time in milliseconds.
long millis = (fixedDate - EPOCH_OFFSET) * ONE_DAY + timeOfDay;
// Compute the time zone offset and DST offset. There are two potential
// ambiguities here. We'll assume a 2:00 am (wall time) switchover time
// for discussion purposes here.
// 1. The transition into DST. Here, a designated time of 2:00 am - 2:59 am
// can be in standard or in DST depending. However, 2:00 am is an invalid
// representation (the representation jumps from 1:59:59 am Std to 3:00:00 am DST).
// We assume standard time.
// 2. The transition out of DST. Here, a designated time of 1:00 am - 1:59 am
// can be in standard or DST. Both are valid representations (the rep
// jumps from 1:59:59 DST to 1:00:00 Std).
// Again, we assume standard time.
// We use the TimeZone object, unless the user has explicitly set the ZONE_OFFSET
// or DST_OFFSET fields; then we use those fields.
TimeZone zone = getZone();
if (zoneOffsets == null) {
zoneOffsets = new int[2];
}
int tzMask = fieldMask & (ZONE_OFFSET_MASK|DST_OFFSET_MASK);
if (tzMask != (ZONE_OFFSET_MASK|DST_OFFSET_MASK)) {
if (zone instanceof ZoneInfo) {
((ZoneInfo)zone).getOffsetsByWall(millis, zoneOffsets);
} else {
int gmtOffset = isFieldSet(fieldMask, ZONE_OFFSET) ?
internalGet(ZONE_OFFSET) : zone.getRawOffset();
zone.getOffsets(millis - gmtOffset, zoneOffsets);
}
}
if (tzMask != 0) {
if (isFieldSet(tzMask, ZONE_OFFSET)) {
zoneOffsets[0] = internalGet(ZONE_OFFSET);
}
if (isFieldSet(tzMask, DST_OFFSET)) {
zoneOffsets[1] = internalGet(DST_OFFSET);
}
}
// Adjust the time zone offset values to get the UTC time.
millis -= zoneOffsets[0] + zoneOffsets[1];
// Set this calendar's time in milliseconds
time = millis;
int mask = computeFields(fieldMask | getSetStateFields(), tzMask);
if (!isLenient()) {
for (int field = 0; field < FIELD_COUNT; field++) {
if (!isExternallySet(field)) {
continue;
}
if (originalFields[field] != internalGet(field)) {
String s = originalFields[field] + " -> " + internalGet(field);
// Restore the original field values
System.arraycopy(originalFields, 0, fields, 0, fields.length);
throw new IllegalArgumentException(getFieldName(field) + ": " + s);
}
}
}
setFieldsNormalized(mask);
}
/**
* Computes the fixed date under either the Gregorian or the
* Julian calendar, using the given year and the specified calendar fields.
*
* <p>
* 使用给定年份和指定的日历字段计算格里高利历史或儒略历日历下的固定日期
*
*
* @param cal the CalendarSystem to be used for the date calculation
* @param year the normalized year number, with 0 indicating the
* year 1 BCE, -1 indicating 2 BCE, etc.
* @param fieldMask the calendar fields to be used for the date calculation
* @return the fixed date
* @see Calendar#selectFields
*/
private long getFixedDate(BaseCalendar cal, int year, int fieldMask) {
int month = JANUARY;
if (isFieldSet(fieldMask, MONTH)) {
// No need to check if MONTH has been set (no isSet(MONTH)
// call) since its unset value happens to be JANUARY (0).
month = internalGet(MONTH);
// If the month is out of range, adjust it into range
if (month > DECEMBER) {
year += month / 12;
month %= 12;
} else if (month < JANUARY) {
int[] rem = new int[1];
year += CalendarUtils.floorDivide(month, 12, rem);
month = rem[0];
}
}
// Get the fixed date since Jan 1, 1 (Gregorian). We are on
// the first day of either `month' or January in 'year'.
long fixedDate = cal.getFixedDate(year, month + 1, 1,
cal == gcal ? gdate : null);
if (isFieldSet(fieldMask, MONTH)) {
// Month-based calculations
if (isFieldSet(fieldMask, DAY_OF_MONTH)) {
// We are on the first day of the month. Just add the
// offset if DAY_OF_MONTH is set. If the isSet call
// returns false, that means DAY_OF_MONTH has been
// selected just because of the selected
// combination. We don't need to add any since the
// default value is the 1st.
if (isSet(DAY_OF_MONTH)) {
// To avoid underflow with DAY_OF_MONTH-1, add
// DAY_OF_MONTH, then subtract 1.
fixedDate += internalGet(DAY_OF_MONTH);
fixedDate--;
}
} else {
if (isFieldSet(fieldMask, WEEK_OF_MONTH)) {
long firstDayOfWeek = BaseCalendar.getDayOfWeekDateOnOrBefore(fixedDate + 6,
getFirstDayOfWeek());
// If we have enough days in the first week, then
// move to the previous week.
if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) {
firstDayOfWeek -= 7;
}
if (isFieldSet(fieldMask, DAY_OF_WEEK)) {
firstDayOfWeek = BaseCalendar.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6,
internalGet(DAY_OF_WEEK));
}
// In lenient mode, we treat days of the previous
// months as a part of the specified
// WEEK_OF_MONTH. See 4633646.
fixedDate = firstDayOfWeek + 7 * (internalGet(WEEK_OF_MONTH) - 1);
} else {
int dayOfWeek;
if (isFieldSet(fieldMask, DAY_OF_WEEK)) {
dayOfWeek = internalGet(DAY_OF_WEEK);
} else {
dayOfWeek = getFirstDayOfWeek();
}
// We are basing this on the day-of-week-in-month. The only
// trickiness occurs if the day-of-week-in-month is
// negative.
int dowim;
if (isFieldSet(fieldMask, DAY_OF_WEEK_IN_MONTH)) {
dowim = internalGet(DAY_OF_WEEK_IN_MONTH);
} else {
dowim = 1;
}
if (dowim >= 0) {
fixedDate = BaseCalendar.getDayOfWeekDateOnOrBefore(fixedDate + (7 * dowim) - 1,
dayOfWeek);
} else {
// Go to the first day of the next week of
// the specified week boundary.
int lastDate = monthLength(month, year) + (7 * (dowim + 1));
// Then, get the day of week date on or before the last date.
fixedDate = BaseCalendar.getDayOfWeekDateOnOrBefore(fixedDate + lastDate - 1,
dayOfWeek);
}
}
}
} else {
if (year == gregorianCutoverYear && cal == gcal
&& fixedDate < gregorianCutoverDate
&& gregorianCutoverYear != gregorianCutoverYearJulian) {
// January 1 of the year doesn't exist. Use
// gregorianCutoverDate as the first day of the
// year.
fixedDate = gregorianCutoverDate;
}
// We are on the first day of the year.
if (isFieldSet(fieldMask, DAY_OF_YEAR)) {
// Add the offset, then subtract 1. (Make sure to avoid underflow.)
fixedDate += internalGet(DAY_OF_YEAR);
fixedDate--;
} else {
long firstDayOfWeek = BaseCalendar.getDayOfWeekDateOnOrBefore(fixedDate + 6,
getFirstDayOfWeek());
// If we have enough days in the first week, then move
// to the previous week.
if ((firstDayOfWeek - fixedDate) >= getMinimalDaysInFirstWeek()) {
firstDayOfWeek -= 7;
}
if (isFieldSet(fieldMask, DAY_OF_WEEK)) {
int dayOfWeek = internalGet(DAY_OF_WEEK);
if (dayOfWeek != getFirstDayOfWeek()) {
firstDayOfWeek = BaseCalendar.getDayOfWeekDateOnOrBefore(firstDayOfWeek + 6,
dayOfWeek);
}
}
fixedDate = firstDayOfWeek + 7 * ((long)internalGet(WEEK_OF_YEAR) - 1);
}
}
return fixedDate;
}
/**
* Returns this object if it's normalized (all fields and time are
* in sync). Otherwise, a cloned object is returned after calling
* complete() in lenient mode.
* <p>
* 如果它被规范化(所有字段和时间都是同步的),则返回此对象。否则,在宽松模式下调用complete()后将返回一个克隆对象
*
*/
private GregorianCalendar getNormalizedCalendar() {
GregorianCalendar gc;
if (isFullyNormalized()) {
gc = this;
} else {
// Create a clone and normalize the calendar fields
gc = (GregorianCalendar) this.clone();
gc.setLenient(true);
gc.complete();
}
return gc;
}
/**
* Returns the Julian calendar system instance (singleton). 'jcal'
* and 'jeras' are set upon the return.
* <p>
* 返回Julian日历系统实例(单例)'jcal'和'jeras'在返回时设置
*
*/
private static synchronized BaseCalendar getJulianCalendarSystem() {
if (jcal == null) {
jcal = (JulianCalendar) CalendarSystem.forName("julian");
jeras = jcal.getEras();
}
return jcal;
}
/**
* Returns the calendar system for dates before the cutover date
* in the cutover year. If the cutover date is January 1, the
* method returns Gregorian. Otherwise, Julian.
* <p>
* 返回割接年份中割接日期之前的日历系统如果割接日期为1月1日,则该方法返回Gregorian否则,Julian
*
*/
private BaseCalendar getCutoverCalendarSystem() {
if (gregorianCutoverYearJulian < gregorianCutoverYear) {
return gcal;
}
return getJulianCalendarSystem();
}
/**
* Determines if the specified year (normalized) is the Gregorian
* cutover year. This object must have been normalized.
* <p>
* 确定指定年份(标准化)是否为格雷戈里切割年份此对象必须已经过规范化
*
*/
private boolean isCutoverYear(int normalizedYear) {
int cutoverYear = (calsys == gcal) ? gregorianCutoverYear : gregorianCutoverYearJulian;
return normalizedYear == cutoverYear;
}
/**
* Returns the fixed date of the first day of the year (usually
* January 1) before the specified date.
*
* <p>
* 返回指定日期之前一年中第一天(通常为1月1日)的固定日期
*
*
* @param date the date for which the first day of the year is
* calculated. The date has to be in the cut-over year (Gregorian
* or Julian).
* @param fixedDate the fixed date representation of the date
*/
private long getFixedDateJan1(BaseCalendar.Date date, long fixedDate) {
assert date.getNormalizedYear() == gregorianCutoverYear ||
date.getNormalizedYear() == gregorianCutoverYearJulian;
if (gregorianCutoverYear != gregorianCutoverYearJulian) {
if (fixedDate >= gregorianCutoverDate) {
// Dates before the cutover date don't exist
// in the same (Gregorian) year. So, no
// January 1 exists in the year. Use the
// cutover date as the first day of the year.
return gregorianCutoverDate;
}
}
// January 1 of the normalized year should exist.
BaseCalendar juliancal = getJulianCalendarSystem();
return juliancal.getFixedDate(date.getNormalizedYear(), BaseCalendar.JANUARY, 1, null);
}
/**
* Returns the fixed date of the first date of the month (usually
* the 1st of the month) before the specified date.
*
* <p>
* 返回指定日期之前的月份的第一个日期(通常为月份的第一天)的固定日期
*
*
* @param date the date for which the first day of the month is
* calculated. The date has to be in the cut-over year (Gregorian
* or Julian).
* @param fixedDate the fixed date representation of the date
*/
private long getFixedDateMonth1(BaseCalendar.Date date, long fixedDate) {
assert date.getNormalizedYear() == gregorianCutoverYear ||
date.getNormalizedYear() == gregorianCutoverYearJulian;
BaseCalendar.Date gCutover = getGregorianCutoverDate();
if (gCutover.getMonth() == BaseCalendar.JANUARY
&& gCutover.getDayOfMonth() == 1) {
// The cutover happened on January 1.
return fixedDate - date.getDayOfMonth() + 1;
}
long fixedDateMonth1;
// The cutover happened sometime during the year.
if (date.getMonth() == gCutover.getMonth()) {
// The cutover happened in the month.
BaseCalendar.Date jLastDate = getLastJulianDate();
if (gregorianCutoverYear == gregorianCutoverYearJulian
&& gCutover.getMonth() == jLastDate.getMonth()) {
// The "gap" fits in the same month.
fixedDateMonth1 = jcal.getFixedDate(date.getNormalizedYear(),
date.getMonth(),
1,
null);
} else {
// Use the cutover date as the first day of the month.
fixedDateMonth1 = gregorianCutoverDate;
}
} else {
// The cutover happened before the month.
fixedDateMonth1 = fixedDate - date.getDayOfMonth() + 1;
}
return fixedDateMonth1;
}
/**
* Returns a CalendarDate produced from the specified fixed date.
*
* <p>
* 返回从指定的固定日期生成的CalendarDate
*
*
* @param fd the fixed date
*/
private BaseCalendar.Date getCalendarDate(long fd) {
BaseCalendar cal = (fd >= gregorianCutoverDate) ? gcal : getJulianCalendarSystem();
BaseCalendar.Date d = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.NO_TIMEZONE);
cal.getCalendarDateFromFixedDate(d, fd);
return d;
}
/**
* Returns the Gregorian cutover date as a BaseCalendar.Date. The
* date is a Gregorian date.
* <p>
* 将Gregorian割接日期作为BaseCalendarDate返回日期是公历日期
*
*/
private BaseCalendar.Date getGregorianCutoverDate() {
return getCalendarDate(gregorianCutoverDate);
}
/**
* Returns the day before the Gregorian cutover date as a
* BaseCalendar.Date. The date is a Julian date.
* <p>
* 将Gregorian割接日期前一天作为BaseCalendarDate返回日期是Julian日期
*
*/
private BaseCalendar.Date getLastJulianDate() {
return getCalendarDate(gregorianCutoverDate - 1);
}
/**
* Returns the length of the specified month in the specified
* year. The year number must be normalized.
*
* <p>
* 返回指定年份中指定月份的长度必须对年份数进行归一化
*
*
* @see #isLeapYear(int)
*/
private int monthLength(int month, int year) {
return isLeapYear(year) ? LEAP_MONTH_LENGTH[month] : MONTH_LENGTH[month];
}
/**
* Returns the length of the specified month in the year provided
* by internalGet(YEAR).
*
* <p>
* 返回由internalGet(YEAR)提供的年份中指定月份的长度
*
*
* @see #isLeapYear(int)
*/
private int monthLength(int month) {
int year = internalGet(YEAR);
if (internalGetEra() == BCE) {
year = 1 - year;
}
return monthLength(month, year);
}
private int actualMonthLength() {
int year = cdate.getNormalizedYear();
if (year != gregorianCutoverYear && year != gregorianCutoverYearJulian) {
return calsys.getMonthLength(cdate);
}
BaseCalendar.Date date = (BaseCalendar.Date) cdate.clone();
long fd = calsys.getFixedDate(date);
long month1 = getFixedDateMonth1(date, fd);
long next1 = month1 + calsys.getMonthLength(date);
if (next1 < gregorianCutoverDate) {
return (int)(next1 - month1);
}
if (cdate != gdate) {
date = (BaseCalendar.Date) gcal.newCalendarDate(TimeZone.NO_TIMEZONE);
}
gcal.getCalendarDateFromFixedDate(date, next1);
next1 = getFixedDateMonth1(date, next1);
return (int)(next1 - month1);
}
/**
* Returns the length (in days) of the specified year. The year
* must be normalized.
* <p>
* 返回指定年份的长度(以天为单位)年份必须标准化
*
*/
private int yearLength(int year) {
return isLeapYear(year) ? 366 : 365;
}
/**
* Returns the length (in days) of the year provided by
* internalGet(YEAR).
* <p>
* 返回由internalGet(YEAR)提供的年份(以天为单位)
*
*/
private int yearLength() {
int year = internalGet(YEAR);
if (internalGetEra() == BCE) {
year = 1 - year;
}
return yearLength(year);
}
/**
* After adjustments such as add(MONTH), add(YEAR), we don't want the
* month to jump around. E.g., we don't want Jan 31 + 1 month to go to Mar
* 3, we want it to go to Feb 28. Adjustments which might run into this
* problem call this method to retain the proper month.
* <p>
* 调整后,如添加(MONTH),添加(YEAR),我们不想让月份跳到Eg,我们不想要1月31 + 1个月去3月3日,我们想要去2月28日可能会遇到此问题的调整将调用此方法以保留正确的月份
*
*/
private void pinDayOfMonth() {
int year = internalGet(YEAR);
int monthLen;
if (year > gregorianCutoverYear || year < gregorianCutoverYearJulian) {
monthLen = monthLength(internalGet(MONTH));
} else {
GregorianCalendar gc = getNormalizedCalendar();
monthLen = gc.getActualMaximum(DAY_OF_MONTH);
}
int dom = internalGet(DAY_OF_MONTH);
if (dom > monthLen) {
set(DAY_OF_MONTH, monthLen);
}
}
/**
* Returns the fixed date value of this object. The time value and
* calendar fields must be in synch.
* <p>
* 返回此对象的固定日期值时间值和日历字段必须同步
*
*/
private long getCurrentFixedDate() {
return (calsys == gcal) ? cachedFixedDate : calsys.getFixedDate(cdate);
}
/**
* Returns the new value after 'roll'ing the specified value and amount.
* <p>
* 在滚动指定的值和数量后返回新值
*
*/
private static int getRolledValue(int value, int amount, int min, int max) {
assert value >= min && value <= max;
int range = max - min + 1;
amount %= range;
int n = value + amount;
if (n > max) {
n -= range;
} else if (n < min) {
n += range;
}
assert n >= min && n <= max;
return n;
}
/**
* Returns the ERA. We need a special method for this because the
* default ERA is CE, but a zero (unset) ERA is BCE.
* <p>
* 返回ERA我们需要一个特殊的方法,因为默认ERA是CE,但零(未设置)ERA是BCE
*
*/
private int internalGetEra() {
return isSet(ERA) ? internalGet(ERA) : CE;
}
/**
* Updates internal state.
* <p>
* 更新内部状态
*
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
if (gdate == null) {
gdate = (BaseCalendar.Date) gcal.newCalendarDate(getZone());
cachedFixedDate = Long.MIN_VALUE;
}
setGregorianChange(gregorianCutover);
}
/**
* Converts this object to a {@code ZonedDateTime} that represents
* the same point on the time-line as this {@code GregorianCalendar}.
* <p>
* Since this object supports a Julian-Gregorian cutover date and
* {@code ZonedDateTime} does not, it is possible that the resulting year,
* month and day will have different values. The result will represent the
* correct date in the ISO calendar system, which will also be the same value
* for Modified Julian Days.
*
* <p>
* 将此对象转换为{@code ZonedDateTime},表示与此{@code GregorianCalendar}时间轴上的相同点
* <p>
* 由于此对象支持Julian-Gregorian割接日期,{@code ZonedDateTime}不支持,因此生成的年,月和日可能具有不同的值。
* 结果将表示ISO日历系统中的正确日期,这也将修改儒略日的值相同。
*
*
* @return a zoned date-time representing the same point on the time-line
* as this gregorian calendar
* @since 1.8
*/
public ZonedDateTime toZonedDateTime() {
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(getTimeInMillis()),
getTimeZone().toZoneId());
}
/**
* Obtains an instance of {@code GregorianCalendar} with the default locale
* from a {@code ZonedDateTime} object.
* <p>
* Since {@code ZonedDateTime} does not support a Julian-Gregorian cutover
* date and uses ISO calendar system, the return GregorianCalendar is a pure
* Gregorian calendar and uses ISO 8601 standard for week definitions,
* which has {@code MONDAY} as the {@link Calendar#getFirstDayOfWeek()
* FirstDayOfWeek} and {@code 4} as the value of the
* {@link Calendar#getMinimalDaysInFirstWeek() MinimalDaysInFirstWeek}.
* <p>
* {@code ZoneDateTime} can store points on the time-line further in the
* future and further in the past than {@code GregorianCalendar}. In this
* scenario, this method will throw an {@code IllegalArgumentException}
* exception.
*
* <p>
* 使用{@code ZonedDateTime}对象的默认语言区域获取{@code GregorianCalendar}的实例
* <p>
* 由于{@code ZonedDateTime}不支持Julian-Gregorian切换日期并使用ISO日历系统,因此返回GregorianCalendar是一个纯粹的公历,对于星期定义使用ISO 86
* 01标准,{@code MONDAY}作为{@link日历#getFirstDayOfWeek()FirstDayOfWeek}和{@code 4}作为{@link Calendar#getMinimalDaysInFirstWeek()MinimalDaysInFirstWeek}
* 的值。
*
* @param zdt the zoned date-time object to convert
* @return the gregorian calendar representing the same point on the
* time-line as the zoned date-time provided
* @exception NullPointerException if {@code zdt} is null
* @exception IllegalArgumentException if the zoned date-time is too
* large to represent as a {@code GregorianCalendar}
* @since 1.8
*/
public static GregorianCalendar from(ZonedDateTime zdt) {
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone(zdt.getZone()));
cal.setGregorianChange(new Date(Long.MIN_VALUE));
cal.setFirstDayOfWeek(MONDAY);
cal.setMinimalDaysInFirstWeek(4);
try {
cal.setTimeInMillis(Math.addExact(Math.multiplyExact(zdt.toEpochSecond(), 1000),
zdt.get(ChronoField.MILLI_OF_SECOND)));
} catch (ArithmeticException ex) {
throw new IllegalArgumentException(ex);
}
return cal;
}
}
| lobinary/Lobinary | JDK8Source/src/main/java/java/util/GregorianCalendar.java |
66,178 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.polardbx.rule;
import com.alibaba.polardbx.common.model.DBType;
import com.alibaba.polardbx.common.utils.Assert;
import com.alibaba.polardbx.common.utils.TStringUtil;
import com.alibaba.polardbx.config.ConfigDataMode;
import com.alibaba.polardbx.rule.Rule.RuleColumn;
import com.alibaba.polardbx.rule.exception.TddlRuleException;
import com.alibaba.polardbx.rule.impl.EnumerativeRule;
import com.alibaba.polardbx.rule.impl.ExtPartitionGroovyRule;
import com.alibaba.polardbx.rule.meta.RangeHash1Meta;
import com.alibaba.polardbx.rule.meta.ShardFunctionMeta;
import com.alibaba.polardbx.rule.model.AdvancedParameter;
import com.alibaba.polardbx.rule.model.AdvancedParameter.AtomIncreaseType;
import com.alibaba.polardbx.rule.utils.CalcParamsAttribute;
import com.alibaba.polardbx.rule.utils.CoverRuleProcessor;
import com.alibaba.polardbx.rule.utils.GroovyRuleShardFuncFinder;
import com.alibaba.polardbx.rule.utils.RuleUtils;
import com.alibaba.polardbx.rule.utils.ShardFunctionMetaUtils;
import com.alibaba.polardbx.rule.utils.SimpleRuleProcessor;
import com.alibaba.polardbx.rule.utils.sample.Samples;
import com.alibaba.polardbx.rule.virtualnode.DBTableMap;
import com.alibaba.polardbx.rule.virtualnode.TableSlotMap;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import static com.alibaba.polardbx.common.ddl.newengine.DdlConstants.MAX_TABLE_NAME_LENGTH_MYSQL_ALLOWS;
import static com.alibaba.polardbx.common.ddl.newengine.DdlConstants.RANDOM_SUFFIX_LENGTH_OF_PHYSICAL_TABLE_NAME;
/**
* 描述一个逻辑表怎样分库分表,允许指定逻辑表名和db/table的{@linkplain Rule}规则
* <p>
*
* @author linxuan
* @author jianghang 2013-11-4 下午5:33:51
* @since 5.0.0
*/
public class TableRule extends VirtualTableSupport implements VirtualTableRule {
/** =================================================== **/
/** == 原始的配置字符串 == **/
/**
* ===================================================
**/
protected String dbNamePattern; // item_{0000}_dbkey
protected String tbNamePattern; // item_{0000}
protected String[] dbRules; // rule配置字符串
protected String[] tbRules; // rule配置字符串
protected List<String> extraPackages; // 自定义用户包
protected boolean allowFullTableScan = false; // 是否允许全表扫描
/**
* 虚拟节点映射
*/
protected TableSlotMap tableSlotMap;
protected DBTableMap dbTableMap;
protected String tableSlotKeyFormat;
/**
* <pre>
* key: groupKey
* val: set of phy tb
* </pre>
*/
protected Map<String, Set<String>> staticTopology; // 静态拓扑,通过正常拓扑计算不出来的拓扑内容
/**
* ============ 运行时变量 =================
**/
protected List<Rule<String>> dbShardRules;
protected List<Rule<String>> tbShardRules;
/**
* {@link TableRule#shardColumns} will be used in {@link PushJoinRule#getShardColumnRef} for join pushdown,
* so that we MUST keep the order of names in {@link TableRule#shardColumns}
* following the law that db partition key in front of tb partition key.
* Anyone who is modifying {@link TableRule#buildShardColumns()} should keep this in mind
*/
protected List<String> shardColumns; // 分库分表字段, 对顺序有要求,分库键在前,分表键在后
protected List<String> upperShardColumns; // 大写的分库分表字段
protected List<String> dbPartitionKeys;
protected List<String> tbPartitionKeys;
/**
*
*/
protected Object outerContext;
protected CoverRuleProcessor coverRuleProcessor;
/**
* 是否是个广播表,optimizer模块需要用他来标记某个表是否需要进行复制
*/
protected boolean broadcast = false;
/**
* 相同的join group 应该具有相同的切分规则
*/
protected String joinGroup = null;
// 特殊规则优化
protected boolean simple = false;
protected int ruleDbCount;
protected int extDbCount;
protected int ruleTbCount;
protected int extTbCount;
protected boolean randomTableNamePatternEnabled = true;
protected String existingRandomSuffixForRecovery = null;
protected String tableNamePrefixForShadowTable = null;
protected final long version;
protected int isActiveTopologyInited;
/**
* <pre>
* SimpleRule类型的规则模板:
* 1. ((#{0},1,{1}#).longValue() % {2}).intdiv({3})
* 2. (#{0},1,{1}#.hashCode().abs().longValue() % {2}).intdiv({3})
*
* dbCount 是简单规则枚举的总分库数,
* tbCount 是简单规则枚举的总分表数;
*
* 在SimpleRule类型规则的表达式中,dbCount 与 tbCount 是直接通过正则表达式从简单规则表达式中提取出来,
* 因此,dbCount 与 tbCount 与 与真实的 库表数量不一定完全一致(例如,字符串枚举可能会有产生重复),
* (例如,
* 对于对映射规则、冷热规则,dbCount可能也不是真实的分库数
* )
* dbCount 与 tbCount 目前主要用在两个地方:
* (1)计算简单规则的路由计算,简单规则通过提取规则表达式的值,走JAVA而不是走Groovy来计算路由;
* (2)show create table 时回接分库分表数;
* (3)Join下推判断分库分表规则是否完全一致。
*
* 问题:dbCount、tbCount 与 acutalDbCount、actualTbCount 的区别:
* acutalDbCount 和 actualTbCount 是TDDL根据拆分规则的实际枚举数目,
*
* acutalDbCount 是实际的规则枚举的总分库数,
* actualTbCount 是实际的规则枚举的总分表数;
*
* 而 dbCount 和 tbCount 不是。
* --------------------------------
* 在非SimpleRule类型的表达式中,由于其分库分表数目是根据规则枚举结果算出来的,
* 所以,dbCount、tbCount 直接由 acutalDbCount、actualTbCount赋值,
* 总与acutalDbCount、actualTbCount 保持一致
*
*
* </pre>
*/
// SimpleRule 场景下 tbCount/dbCount 与真实的 库表数量不一致~
protected int tbCount;
protected int dbCount;
protected AtomIncreaseType partitionType;
protected String[] tbNames;
protected String[] dbNames;
protected boolean coverRule = false; // 规则是否可以被覆盖更新,默认false,对于noloop不断滚动的规则可以覆盖
protected Integer start;
protected Integer end;
protected String[] tbNamesOfExtraDb;
protected String[] dbNamesOfExtraDb;
/**
* <pre>
* 专用于保存直接调用groovy函数的非参数化的复杂规则(通常是非简单规则或时间类规则居多)的所使用的groovy拆分函数的类型
* , 这个参数主要用于判断拆分规则的等价判断
* </pre>
*/
// 分库用的Groovy函数
protected String dbGroovyShardMethodName;
// 分表用的Groovy函数
protected String tbGroovyShardMethodName;
/**
* 用于描述分库函数的元数据,dbShardFunctionMetaMap 保存的是XML规则的关于DB切分函数的元数据内容,
* dbShardFunctionMeta 由 dbShardFunctionMetaMap 反射生成
*/
protected Map<String, Object> dbShardFunctionMetaMap;
protected ShardFunctionMeta dbShardFunctionMeta;
/**
* 用于描述分库函数的元数据, tbShardFunctionMetaMap
* 保存的是XML规则的关于DB切分函数的元数据内容,tbShardFunctionMeta 由 tbShardFunctionMetaMap
* 反射生成
*/
protected Map<String, Object> tbShardFunctionMetaMap;
protected ShardFunctionMeta tbShardFunctionMeta;
// 从 actualTopology 里计算出来的实际分库分表数量,用于 SHOW CREATE TABLE
protected int actualTbCount; // 总分表数
protected int actualDbCount; // 总分库数
protected List<MappingRule> extPartitions;
protected Map<String, Set<MappingRule>> extDbKeyToMappingRules;
protected Map<String, Set<MappingRule>> extTbKeyToMappingRules;
protected Map<String, Set<String>> extTopology;
public TableRule() {
this.version = 0;
}
public TableRule(long version) {
this.version = version;
}
public long getVersion() {
return this.version;
}
@Override
public void doInit() {
// 初始化虚拟节点
if (tableSlotMap != null) {
tableSlotMap.setTableSlotKeyFormat(tableSlotKeyFormat);
tableSlotMap.setLogicTable(this.virtualTbName);
tableSlotMap.init();
}
if (dbTableMap != null) {
dbTableMap.setTableSlotKeyFormat(tableSlotKeyFormat);
dbTableMap.setLogicTable(this.virtualTbName);
dbTableMap.init();
}
if (outerContext == null) {
// // 初始化规则计算的上下文,这个非常重要
// outerContext = new HashMap<String, Object>();
// ((Map<String, Object>)
// outerContext).put(OuterContextAttribute.NEED_ROUTE_FOR_EXTRA_DB,
// this);
}
if (extPartitions != null) {
buildExtMapping();
}
// 处理一下占位符
replaceWithParam(this.dbRules, dbRuleParames != null ? dbRuleParames : ruleParames);
replaceWithParam(this.tbRules, tbRuleParames != null ? tbRuleParames : ruleParames);
// 构造一下Rule对象
String packagesStr = buildExtraPackagesStr(extraPackages);
if (dbShardRules == null) { // 如果未设置Rule对象,基于string生成rule对象
setDbShardRules(convertToRuleArray(dbRules,
dbNamePattern,
packagesStr,
dbTableMap,
tableSlotMap,
extDbKeyToMappingRules,
false));
}
if (tbShardRules == null) {
setTbShardRules(convertToRuleArray(tbRules,
tbNamePattern,
packagesStr,
dbTableMap,
tableSlotMap,
extTbKeyToMappingRules,
true));
}
if (tbShardRules == null || tbShardRules.size() == 0) {
if (this.tbNamePattern == null) {
// 表规则没有,tbKeyPattern为空
this.tbNamePattern = this.virtualTbName;
}
}
// 构造一下分区字段
buildShardColumns();
if (customTopology != null) {
// 依赖tb/db name,需要在init方法中计算
buildStaticTopology(customTopology);
}
SimpleRuleProcessor.process(this);
if (!isLazyInit()) {
// 基于rule计算一下拓扑结构
initActualTopology();
}
if (broadcast) {
if (!RuleUtils.isEmpty(dbShardRules) || !RuleUtils.isEmpty(tbShardRules)) {
throw new IllegalArgumentException("broadcast table not support shard rule");
}
}
if (dbShardFunctionMetaMap != null) {
dbShardFunctionMeta = getShardFunctionMetaObject(dbShardFunctionMetaMap);
dbShardFunctionMeta.initShardFuncionMeta(this);
}
if (tbShardFunctionMetaMap != null) {
tbShardFunctionMeta = getShardFunctionMetaObject(tbShardFunctionMetaMap);
tbShardFunctionMeta.initShardFuncionMeta(this);
}
GroovyRuleShardFuncFinder.process(this);
}
public boolean varifyTableShardFuncMetaInfo() {
List<String> shardColumns = getShardColumns();
if (shardColumns.size() == 1) {
String shardColumn = shardColumns.get(0);
ShardFunctionMeta dbShardFunctionMeta = getDbShardFunctionMeta();
ShardFunctionMeta tbShardFunctionMeta = getTbShardFunctionMeta();
if (dbShardFunctionMeta != null && tbShardFunctionMeta != null) {
String dbCreateTableFuncAndParams = dbShardFunctionMeta.buildCreateTablePartitionFunctionStr();
String tbCreateTableFuncAndParams = tbShardFunctionMeta.buildCreateTablePartitionFunctionStr();
if (!dbCreateTableFuncAndParams.equals(tbCreateTableFuncAndParams)) {
throw new TddlRuleException(
String.format("Not support to both different parition function on the same column `%s`",
shardColumn));
}
} else {
if (GroovyRuleShardFuncFinder.groovyDateMethodFunctionSet.contains(dbGroovyShardMethodName)
&& GroovyRuleShardFuncFinder.groovyDateMethodFunctionSet.contains(tbGroovyShardMethodName)) {
// 分库分表的拆分函数都是时间类的拆分函数
if (!dbGroovyShardMethodName.equalsIgnoreCase(tbGroovyShardMethodName)) {
// 如果分库函数与分表函数不一样,但拆分键一样,这样不允许建表
if (dbPartitionKeys.size() == 1 && tbPartitionKeys.size() == 1) {
String dbKey = dbPartitionKeys.get(0).toLowerCase();
String tbKey = tbPartitionKeys.get(0).toLowerCase();
if (dbKey.equalsIgnoreCase(tbKey)) {
throw new TddlRuleException(String.format(
"Not support to use two different db/tb shard functions on the same column `%s`",
shardColumn));
}
}
}
} else {
if (dbRules != null && tbRules != null) {
String dbShardInfoStr =
String.format("%s_%s", dbShardFunctionMeta != null, dbGroovyShardMethodName);
String tbShardInfoStr =
String.format("%s_%s", tbShardFunctionMeta != null, tbGroovyShardMethodName);
if (!dbShardInfoStr.equals(tbShardInfoStr)) {
throw new TddlRuleException(String.format(
"Not support to use two different db/tb shard functions on the same column `%s`",
shardColumn));
}
}
}
}
}
return true;
}
public ShardFunctionMeta getShardFunctionMetaObject(Map<String, Object> shardFuncMetaMap) {
String classUrl = null;
Class classObj = null;
ShardFunctionMeta shardFunctionMetaObj = null;
try {
classUrl = (String) shardFuncMetaMap.get(ShardFunctionMetaUtils.CLASS_URL);
if (classUrl == null) {
throw new IllegalArgumentException("shardFunctionMetaMap must contain property of class url.");
}
classUrl = RuleCompatibleHelper.compatibleShardFunctionMeta(classUrl);
classObj = Class.forName(classUrl);
shardFunctionMetaObj =
(ShardFunctionMeta) ShardFunctionMetaUtils.convertMapToShardFunctionMeta(shardFuncMetaMap,
classObj);
} catch (Throwable e) {
// DRDS模式下,忽略报错
logger.error(String.format("failed to build shardFunctionMeta, its tbNamePattern is %s, classUrl is %s",
tbNamePattern,
classUrl == null ? "null" : classUrl),
e);
}
return shardFunctionMetaObj;
}
public void initActualTopology() {
if (actualTopology != null) {
showTopology(false);
return; // 用户显式设置的优先
}
if (logger.isDebugEnabled()) {
logger.debug("Initializing topology of virtual table " + this.virtualTbName);
}
actualTopology = new TreeMap<String, Set<String>>();
actualTopologyOfExtraDb = new TreeMap<String, Set<String>>();
if (RuleUtils.isEmpty(dbShardRules) && RuleUtils.isEmpty(tbShardRules)) {
// 啥规则都没有
// 该表没有做任何拆分
Set<String> tbs = new TreeSet<String>();
tbs.add(this.tbNamePattern);
actualTopology.put(this.dbNamePattern, tbs);
if (ConfigDataMode.isFastMock()) {
dbCount = 1;
tbCount = 1;
}
} else if (RuleUtils.isEmpty(dbShardRules)) {
// 没有库规则
// 该表分表不分库
Set<String> tbs = new TreeSet<String>();
for (Rule<String> tbRule : tbShardRules) {
tbs.addAll(vbvRule(tbRule, getEnumerates(tbRule), null));
}
actualTopology.put(this.dbNamePattern, tbs);
} else if (RuleUtils.isEmpty(tbShardRules)) {
// 没有表规则
// 该表分库不分表
Set<String> tbs = new TreeSet<String>();
tbs.add(this.tbNamePattern);
for (Rule<String> dbRule : dbShardRules) {
for (String dbIndex : vbvRule(dbRule, getEnumerates(dbRule), null)) {
actualTopology.put(dbIndex, tbs);
}
}
} else {
// 库表规则都有
// 该表不但分库,而且分表
if (checkRangeHash()) {
valueByValue(this.actualTopology,
this.actualTopologyOfExtraDb,
dbShardRules.get(0),
tbShardRules.get(0),
false);
} else {
for (Rule<String> dbRule : dbShardRules) {
for (Rule<String> tbRule : tbShardRules) {
if (this.tableSlotMap != null && this.dbTableMap != null) {
// 存在vnode
valueByValue(this.actualTopology, this.actualTopologyOfExtraDb, dbRule, tbRule, true);
} else if (this.isSimple()) {
// 简单规则,需要走简单规则的枚举逻辑
generateActualTopologyBySimpleRule();
} else {
// 复杂规则,需要走规则的枚举逻辑
valueByValue(this.actualTopology, this.actualTopologyOfExtraDb, dbRule, tbRule, false);
}
}
}
}
}
if (staticTopology != null) {
// 规则中手工配置了静态表拓扑
// 合并静态拓扑
for (Map.Entry<String, Set<String>> entry : staticTopology.entrySet()) {
Set<String> values = actualTopology.get(entry.getKey());
if (values != null) {
values.addAll(entry.getValue());
} else {
actualTopology.put(entry.getKey(), entry.getValue());
}
}
}
ruleDbCount = actualTopology.keySet().size();
int tempTbCount = 0;
for (Map.Entry<String, Set<String>> entry : actualTopology.entrySet()) {
Set<String> values = actualTopology.get(entry.getKey());
tempTbCount += values.size();
}
ruleTbCount = tempTbCount;
if (extPartitions != null) {
buildExtTopology(actualTopology);
}
// 基于拓扑的计算结果,计算dbCount与tbCount
int dbCountVal = actualTopology.keySet().size();
int tbCountVal = 0;
for (Map.Entry<String, Set<String>> actualTopologyItem : actualTopology.entrySet()) {
tbCountVal += actualTopologyItem.getValue().size();
}
this.actualDbCount = dbCountVal;
this.actualTbCount = tbCountVal;
extDbCount = dbCountVal - ruleDbCount;
extTbCount = tbCountVal - tempTbCount;
if (extTopology != null) {
for (Iterator<String> iterator = extTopology.keySet().iterator(); iterator.hasNext(); ) {
String next = iterator.next();
final Set<String> strings = extTopology.get(next);
if (strings == null || strings.size() == 0) {
continue;
}
if (actualTopology.containsKey(next)) {
actualTopology.get(next).addAll(strings);
} else {
actualTopology.put(next, strings);
}
}
}
if (!isSimple()) {
// 在DRDS模式下,非简单规则(一般都是新型拆分规则及按时间分表滚动的规则),dbCount与tbCount分别为用拓扑实际计算出来的分库数与分表数
dbCount = actualDbCount;
tbCount = actualTbCount;
}
if (logger.isDebugEnabled()) {
logger.debug("Initialized topology of virtual table " + this.virtualTbName);
showTopology(true);
}
}
private boolean checkRangeHash() {
if (this.dbShardFunctionMeta != null && this.tbShardFunctionMeta != null
&& this.dbShardFunctionMeta instanceof RangeHash1Meta
&& this.tbShardFunctionMeta instanceof RangeHash1Meta) {
if (((RangeHash1Meta) this.dbShardFunctionMeta).getShardKeys()
.equals(((RangeHash1Meta) this.tbShardFunctionMeta).getShardKeys())) {
return true;
}
}
if (dbShardFunctionMetaMap != null && tbShardFunctionMetaMap != null) {
if (dbShardFunctionMetaMap.get("classUrl") != null
&& dbShardFunctionMetaMap.get("classUrl").toString().contains("RangeHash1Meta")
&& tbShardFunctionMetaMap.get("classUrl") != null
&& tbShardFunctionMetaMap.get("classUrl").toString().contains("RangeHash1Meta")
) {
if (dbShardFunctionMetaMap.get("shardKeys").equals(tbShardFunctionMetaMap.get("shardKeys"))) {
return true;
}
}
}
return false;
}
private void generateActualTopologyBySimpleRule() {
String[] tmpTbNames = this.tbNames;
String[] tmpDbNames = this.dbNames;
for (int tbIndex = 0; tbIndex < tmpTbNames.length; tbIndex++) {
String actualTableName = tmpTbNames[tbIndex];
String actualDbName = tmpDbNames[tbIndex];
Set<String> tbNamesOfOneDb = this.actualTopology.get(actualDbName);
if (tbNamesOfOneDb == null) {
tbNamesOfOneDb = new HashSet<String>(this.tbCount / this.dbCount);
this.actualTopology.put(actualDbName, tbNamesOfOneDb);
}
tbNamesOfOneDb.add(actualTableName);
}
}
// ==================== build topology =====================
/**
* // 计算一下规则,并返回计算结果
* 基于传入的枚举样本samples,应用传入的规则参数rule,计算出这些枚举值所对应的物理分表名或(物理库名),并返回集合
*/
private Set<String> vbvRule(Rule<String> rule, Samples samples, Map<String, Object> calcParams) {
Set<String> finalRouteResult = new TreeSet<String>();
for (Map<String, Object> sample : samples) {
// tbs.add(rule.eval(sample, null));
String phyName = rule.eval(sample, outerContext, calcParams);
finalRouteResult.add(phyName);
}
return finalRouteResult;
}
/**
* // 计算一下规则,并返回计算结果
* 基于传入的枚举值集合enumerates,应用传入的规则参数rule,计算出这些枚举值所对应的物理分表名或(物理库名),并返回集合
*/
private Set<String> vbvRule(Rule<String> rule, Map<String, Set<Object>> enumerates,
Map<String, Object> calcParams) {
Set<String> finalRouteResult = new TreeSet<String>();
Samples samples = new Samples(enumerates);
for (Map<String, Object> sample : samples) {
// tbs.add(rule.eval(sample, null));
String phyName = rule.eval(sample, outerContext, calcParams);
finalRouteResult.add(phyName);
}
return finalRouteResult;
}
/**
* 计算一下规则,同时记录对应计算参数,通常是计算分库规则用
* <p>
* <pre>
* 基于传入的枚举值集合enumerates,应用传入的规则参数rule,
* 计算出这些枚举值所对应的物理分表名或(物理库名),
* 并返回这样的对应关系:
*
* Map<String, Samples>:
* key: groupKey
* val: 经过规则计算后产生能路由到这个groupKey的枚举值的集合
* </pre>
*/
private Map<String, Samples> vbvTrace(Rule<String> rule, Map<String, Set<Object>> enumerates,
Map<String, Object> calcParams) {
/**
* <pre>
* key: groupKey
* val: 经过规则计算后产生能路由到这个groupKey的枚举值的集合
* </pre>
*/
Map<String, Samples> db2Samples = new TreeMap<String, Samples>();
Samples dbSamples = new Samples(enumerates);
for (Map<String, Object> sample : dbSamples) {
// String v = rule.eval(sample, null);
String phyName = rule.eval(sample, outerContext, calcParams);
Samples s = db2Samples.get(phyName);
if (s == null) {
s = new Samples(sample.keySet());
db2Samples.put(phyName, s);
}
s.addSample(sample);
}
return db2Samples;
}
/**
* 复杂规则的初始化枚举方式
*/
private void valueByValue(Map<String, Set<String>> topology, Map<String, Set<String>> topologyForExtraDb,
Rule<String> dbRule, Rule<String> tbRule, boolean isVnode) {
/**
* <pre>
* 根据分库规则,从分库规则的初始枚举定义中,获取分库键的枚举值
*
* key: 分库键
* val: 分库键的初始化的枚举值
* </pre>
*/
Map<String/* 列名 */, Set<Object>> dbEnumerates = getEnumerates(dbRule);
/**
* <pre>
* 根据分表规则,从分表规则的初始枚举定义中,获取分表键的枚举值
* key: 分表键
* val: 分表键的初始化的枚举值
* </pre>
*/
Map<String/* 列名 */, Set<Object>> tbEnumerates = getEnumerates(tbRule);
// 以table rule列为基准
Set<AdvancedParameter> params = RuleUtils.cast(tbRule.getRuleColumnSet());
for (AdvancedParameter tbap : params) {
if (dbEnumerates.containsKey(tbap.key)) {
// 库表规则的公共列名,表枚举值要涵盖所有库枚举值跨越的范围= =!
/**
* 获取与分表键相同的分库键的对应的枚举值集合
*/
Set<Object> dbEnumValSetOfDbAdvancedParameter = dbEnumerates.get(tbap.key);
/**
* tbValuesBasedONdbValue保存着本次分表键tbap.key的所有枚举值值
*/
Set<Object> tbValuesBasedOnDbValue = new HashSet<Object>();
/**
* 针对每一个分库键的枚举值,让分表键基于分库键的这个枚举值生成该分表键对应的枚举集合
*/
for (Object dbValue : dbEnumValSetOfDbAdvancedParameter) {
/**
* 让分表键根据dbValue作为枚举基点,进行值枚举,并产生分表键的枚举集合
*/
Set<Object> tbEnumValSetOfTbApBaseOnDbVal = tbap.enumerateRange(dbValue);
tbValuesBasedOnDbValue.addAll(tbEnumValSetOfTbApBaseOnDbVal);
}
/**
* 将tbValuesBasedONdbValue保存着本次分表键tbap.key的所有枚举值值,将其加到分库键的枚举集合中
*/
dbEnumValSetOfDbAdvancedParameter.addAll(tbValuesBasedOnDbValue);
} else {
// 库表规则没有公共列名
Set<Object> tbEnumValSetOfTbAp = tbEnumerates.get(tbap.key);
/**
* 将分表键的枚举集合也同样添加到分库的键的枚举集合中,这里为什么要这样做?
*/
dbEnumerates.put(tbap.key, tbEnumValSetOfTbAp);
}
}
// 有虚拟节点的话按照虚拟节点计算
if (isVnode) {
Samples tabSamples = new Samples(tbEnumerates);
Set<String> tbs = new TreeSet<String>();
for (Map<String, Object> sample : tabSamples) {
// String value = tbRule.eval(sample, null);
String value = tbRule.eval(sample, outerContext);
tbs.add(value);
}
for (String table : tbs) {
Map<String, Object> sample = new HashMap<String, Object>(1);
sample.put(EnumerativeRule.REAL_TABLE_NAME_KEY, table);
// String db = dbRule.eval(sample, null);
String db = dbRule.eval(sample, outerContext);
if (topology.get(db) == null) {
Set<String> tabs = new HashSet<String>();
tabs.add(table);
topology.put(db, tabs);
} else {
topology.get(db).add(table);
}
}
return;
} else {
// 没有虚拟节点按正常走
buildTopogolyByDbEnumerates(topology, dbRule, tbRule, dbEnumerates, null);
}
}
private void buildTopogolyByDbEnumerates(Map<String, Set<String>> topology, Rule<String> dbRule,
Rule<String> tbRule, Map<String, Set<Object>> dbEnumerates,
Map<String, Object> calcParams) {
/**
* 获取groupKey与 经过规则计算后产生能路由到这个groupKey的枚举值的集合 的对应关系。
*
* <pre>
* dbRouteResultSet key: groupKey
* dbRouteResultSet val: 经过规则计算后产生能路由到这个groupKey的枚举值的集合
*
* dbRouteResultSet这个对像可以根据groupKey获取所有能够路由到它的对应枚举输入值集合
* </pre>
*/
Map<String, Samples> dbRouteResultSet = vbvTrace(dbRule, dbEnumerates, calcParams);
/**
* 对于每一个分库及其对应的枚举值,
*/
for (Map.Entry<String/* groupkey */, Samples/* groupkey对应的枚举值 */> dbRouteResult : dbRouteResultSet.entrySet()) {
String groupKey = dbRouteResult.getKey();
Samples samplesOfGroupKey = dbRouteResult.getValue();
Set<String> tbSetOfOneGroup = topology.get(groupKey);
if (tbSetOfOneGroup == null) {
/**
* 获取单个分库之下的所有物理分表的枚举结果
*/
tbSetOfOneGroup = vbvRule(tbRule, samplesOfGroupKey, null);
/**
* 将获取物理分表计算结果保存到拓扑中
*/
topology.put(groupKey, tbSetOfOneGroup);
} else {
/**
* 获取单个分库之下的所有物理分表的枚举结果
*/
Set<String> tbRouteResultSet = vbvRule(tbRule, samplesOfGroupKey, null);
/**
* 将获取物理分表计算结果保存到拓扑中,会自动去重
*/
tbSetOfOneGroup.addAll(tbRouteResultSet);
}
}
}
public String getDbGroovyShardMethodName() {
return dbGroovyShardMethodName;
}
public void setDbGroovyShardMethodName(String dbGroovyShardMethodName) {
this.dbGroovyShardMethodName = dbGroovyShardMethodName;
}
public String getTbGroovyShardMethodName() {
return tbGroovyShardMethodName;
}
public void setTbGroovyShardMethodName(String tbGroovyShardMethodName) {
this.tbGroovyShardMethodName = tbGroovyShardMethodName;
}
class SpecialDateMethodProcessor {
private Boolean isSpecialDate = null;
private Rule rule;
public SpecialDateMethodProcessor(Rule rule) {
this.rule = rule;
}
public void process(AdvancedParameter ap) {
if (ap.atomicIncreateType.isTime()) {
/**
* 判断当前规则中是否包含特殊的日期函数如mmdd_i和dd_i,这两个函数要求最大到366和31,否则从当前时间进行
* 枚举可能会无法达到这个值 只处理一次
*/
if (isSpecialDate == null) {
isSpecialDate = SimpleRuleProcessor.isSpecialDateMethod(rule.getExpression());
}
ap.setIsSpecialDateMethod(isSpecialDate);
}
}
}
/**
* 根据#id,1,32|512_64#中第三段定义的遍历值范围,枚举规则中每个列的遍历值
*/
private Map<String/* 列名 */, Set<Object>/* 列值 */> getEnumerates(Rule rule) {
/**
* 获取规则定义中所有的拆分键,有些情况下拆分键多于一个,每一个拆分列就是一个AdvancedParameter对象
*/
Set<AdvancedParameter> params = RuleUtils.cast(rule.getRuleColumnSet());
Map<String/* 列名 */, Set<Object>/* 列值 */> enumerates = new HashMap<String, Set<Object>>(params.size());
SpecialDateMethodProcessor dateProcessor = new SpecialDateMethodProcessor(rule);
for (AdvancedParameter ap : params) {
dateProcessor.process(ap);
/**
* 对于规则定义中每一个拆分键,让它根据本地规则进行枚举描点,枚举描点是基本规则定义,并得到枚举结果
*/
Set<Object> enumResult = ap.enumerateRange(this);
/**
* 将每一个拆分列得到的枚举结果进行保存
*/
enumerates.put(ap.key, enumResult);
}
return enumerates;
}
private String buildExtraPackagesStr(List<String> extraPackages) {
StringBuilder ep = new StringBuilder("");
if (extraPackages != null) {
int packNum = extraPackages.size();
for (int i = 0; i < packNum; i++) {
ep.append("import ");
ep.append(extraPackages.get(i));
ep.append(";");
}
}
return ep.toString();
}
/**
* 收集表的分区键,join 下推规则要求生成的 shardColumns 保持分库键在前分表键在后
* 如果分库键有多个,保持它们在规则定义中的顺序
* 如果分表键有多个,也要保持它们在规则定义中的顺序
*/
private void buildShardColumns() {
List<String> shardColumns = new ArrayList<>();
Set<String> dbPartitionKeys = new TreeSet<String>();
Set<String> tbPartitionKeys = new TreeSet<String>();
Set<String> shardColumnsUpper = new TreeSet<String>();
Set<String> dbPartitionKeysUpper = new TreeSet<String>();
Set<String> tbPartitionKeysUpper = new TreeSet<String>();
if (null != dbShardRules) {
for (Rule<String> rule : dbShardRules) {
Map<String, RuleColumn> columRule = rule.getRuleColumns();
if (null != columRule && !columRule.isEmpty()) {
for (String shardKey : columRule.keySet()) {
String shardKeyStr = shardKey;
String shardKeyStrUpper = shardKey.toUpperCase();
if (!shardColumnsUpper.contains(shardKeyStrUpper)) {
shardColumns.add(shardKeyStr);
shardColumnsUpper.add(shardKeyStrUpper);
}
if (!dbPartitionKeysUpper.contains(shardKeyStrUpper)) {
dbPartitionKeys.add(shardKeyStr);
dbPartitionKeysUpper.add(shardKeyStrUpper);
}
}
}
}
}
if (null != tbShardRules) {
for (Rule<String> rule : tbShardRules) {
Map<String, RuleColumn> columRule = rule.getRuleColumns();
if (null != columRule && !columRule.isEmpty()) {
for (String shardKey : columRule.keySet()) {
String shardKeyStr = shardKey;
String shardKeyStrUpper = shardKey.toUpperCase();
if (!shardColumnsUpper.contains(shardKeyStrUpper)) {
shardColumns.add(shardKeyStr);
shardColumnsUpper.add(shardKeyStrUpper);
}
if (!tbPartitionKeysUpper.contains(shardKeyStrUpper)) {
tbPartitionKeys.add(shardKeyStr);
tbPartitionKeysUpper.add(shardKeyStrUpper);
}
}
}
}
}
this.shardColumns = new ArrayList<String>(shardColumns);// 没有表配置,代表没有走分区
this.upperShardColumns = new ArrayList<String>(shardColumns.size());
for (String column : shardColumns) {
this.upperShardColumns.add(column.toUpperCase());
}
this.dbPartitionKeys = new ArrayList<String>(dbPartitionKeys);// 没有表配置,代表没有走分区
this.tbPartitionKeys = new ArrayList<String>(tbPartitionKeys);// 没有表配置,代表没有走分区
}
// ===================== setter / getter ====================
public void setDbRuleArray(List<String> dbRules) {
// 若类型改为String[],spring会自动以逗号分隔,变态!
dbRules = trimRuleString(dbRules);
this.dbRules = dbRules.toArray(new String[dbRules.size()]);
}
public List<String> getDbPartitionKeys() {
return dbPartitionKeys;
}
public List<String> getTbPartitionKeys() {
return tbPartitionKeys;
}
public void setTbRuleArray(List<String> tbRules) {
// 若类型改为String[],spring会自动以逗号分隔,变态!
tbRules = trimRuleString(tbRules);
this.tbRules = tbRules.toArray(new String[tbRules.size()]);
}
public void setDbRules(String dbRules) {
if (this.dbRules == null) {
// 优先级比dbRuleArray低
// this.dbRules = dbRules.split("\\|");
this.dbRules = new String[] {dbRules.trim()}; // 废掉|分隔符,没人用且容易造成混乱
}
}
public void setTbRules(String tbRules) {
if (this.tbRules == null) {
// 优先级比tbRuleArray低
// this.tbRules = tbRules.split("\\|");
this.tbRules = new String[] {tbRules.trim()}; // 废掉|分隔符,没人用且容易造成混乱
}
}
@Override
public void setRuleParames(String ruleParames) {
if (ruleParames.indexOf('|') != -1) {
// 优先用|线分隔,因为有些规则表达式中会有逗号
this.ruleParames = ruleParames.split("\\|");
} else {
this.ruleParames = ruleParames.split(",");
}
}
public void setDbNamePattern(String dbKeyPattern) {
this.dbNamePattern = dbKeyPattern;
}
public void setTbNamePattern(String tbKeyPattern) {
this.tbNamePattern = tbKeyPattern;
}
public void setExtraPackages(List<String> extraPackages) {
this.extraPackages = extraPackages;
}
public void setOuterContext(Object outerContext) {
this.outerContext = outerContext;
}
public void setAllowFullTableScan(boolean allowFullTableScan) {
this.allowFullTableScan = allowFullTableScan;
}
public boolean isCoverRule() {
return coverRule;
}
public void setCoverRule(boolean coverRule) {
this.coverRule = coverRule;
}
public CoverRuleProcessor getCoverRuleProcessor() {
return coverRuleProcessor;
}
public void setCoverRuleProcessor(CoverRuleProcessor coverRuleProcessor) {
this.coverRuleProcessor = coverRuleProcessor;
}
@Override
public void setDbType(DBType dbType) {
this.dbType = dbType;
}
public void setDbShardRules(List<Rule<String>> dbShardRules) {
this.dbShardRules = dbShardRules;
}
public void setTbShardRules(List<Rule<String>> tbShardRules) {
this.tbShardRules = tbShardRules;
}
@Override
public DBType getDbType() {
return dbType;
}
@Override
public List getDbShardRules() {
return dbShardRules;
}
@Override
public List getTbShardRules() {
return tbShardRules;
}
@Override
public Object getOuterContext() {
return outerContext;
}
@Override
public TableSlotMap getTableSlotMap() {
return tableSlotMap;
}
@Override
public DBTableMap getDbTableMap() {
return dbTableMap;
}
@Override
public boolean isAllowFullTableScan() {
return allowFullTableScan;
}
@Override
public String getTbNamePattern() {
return tbNamePattern;
}
@Override
public String getDbNamePattern() {
return dbNamePattern;
}
@Override
public String[] getDbRuleStrs() {
return dbRules;
}
@Override
public String[] getTbRulesStrs() {
return tbRules;
}
public void setDbTableMap(DBTableMap dbTableMap) {
this.dbTableMap = dbTableMap;
}
public void setTableSlotMap(TableSlotMap tableSlotMap) {
this.tableSlotMap = tableSlotMap;
}
public void setTableSlotKeyFormat(String tableSlotKeyFormat) {
this.tableSlotKeyFormat = tableSlotKeyFormat;
}
@Override
public boolean isBroadcast() {
return broadcast;
}
public void setBroadcast(boolean broadcast) {
this.broadcast = broadcast;
}
@Override
public String getJoinGroup() {
return joinGroup;
}
public void setJoinGroup(String joinGroup) {
this.joinGroup = joinGroup;
}
@Override
public List<String> getShardColumns() {
return shardColumns;
}
@Override
public List<String> getUpperShardColumns() {
return upperShardColumns;
}
@Override
public Map<String, Set<String>> getActualTopology() {
if (actualTopology == null) {
synchronized (this) {
if (actualTopology == null) {
// 基于rule计算一下拓扑结构
initActualTopology();
}
}
}
return actualTopology;
}
@Override
public Map<String, Set<String>> getActualTopology(Map topologyParams) {
final Map<String, Set<String>> actualTopology = getActualTopology();
if (topologyParams == null) {
return actualTopology;
}
Boolean shardForExtraDb = (Boolean) topologyParams.get(CalcParamsAttribute.SHARD_FOR_EXTRA_DB);
if (shardForExtraDb == null || !shardForExtraDb) {
return actualTopology;
}
if (actualTopology == null) {
synchronized (this) {
if (actualTopology == null) {
// 基于rule计算一下拓扑结构
initActualTopology();
}
}
}
return actualTopologyOfExtraDb;
}
// public Map<String, Set<String>> getActualTopology(Map<String, Object>
// topologyParams) {
// if (topologyParams == null) {
// return getActualTopology();
// }
// return null;
// }
public int getDbCount() {
return dbCount;
}
public void setDbCount(int dbCount) {
this.dbCount = dbCount;
}
public AtomIncreaseType getPartitionType() {
return partitionType;
}
public void setPartitionType(AtomIncreaseType partitionType) {
this.partitionType = partitionType;
}
public boolean isSimple() {
return simple;
}
public void setSimple(boolean simple) {
this.simple = simple;
}
public void setDbNames(String[] dbNames) {
this.dbNames = dbNames;
}
public String[] getDbNames() {
return dbNames;
}
public int getTbCount() {
return tbCount;
}
public void setTbCount(int tbCount) {
this.tbCount = tbCount;
}
public String[] getTbNames() {
return tbNames;
}
public void setTbNames(String[] tbNames) {
this.tbNames = tbNames;
}
public Integer getStart() {
return start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getEnd() {
return end;
}
public void setEnd(Integer end) {
this.end = end;
}
public void setActualTopology(Map actualTopology) {
Map<String, Set<String>> topologys = new TreeMap<String, Set<String>>();
for (Object obj : actualTopology.entrySet()) {
Map.Entry entry = (Map.Entry) obj;
String key = ObjectUtils.toString(entry.getKey());
Object value = entry.getValue();
if (value instanceof Set) {
// 兼容一下以前的Map<String,Set<String>>的接口
Set<String> tables = new HashSet<String>();
for (Object subValue : (Set) value) {
tables.add(ObjectUtils.toString(subValue));
}
topologys.put(key, tables);
} else {
buildTopology(topologys, key, ObjectUtils.toString(value));
}
}
this.actualTopology = topologys;
}
/**
* <pre>
* For setting extpartition first time, we need to initialize the topology information, multiple calls do not guarantee the correctness.
* </pre>
*/
public void initExtTopology() {
buildExtMapping();
buildExtTopology(this.actualTopology);
}
public Map<String, Set<String>> getStaticTopology() {
return staticTopology;
}
public String extractRandomSuffix() {
String randomSuffix = null;
if (TStringUtil.isNotEmpty(tbNamePattern)
&& (tbNamePattern.length() > RANDOM_SUFFIX_LENGTH_OF_PHYSICAL_TABLE_NAME)) {
int randomSuffixStartIndex = 0, randomSuffixEndIndex = 0;
int leftCurlyBraceIndex = TStringUtil.indexOf(tbNamePattern, "{");
if (TStringUtil.startsWithIgnoreCase(tbNamePattern, virtualTbName)) {
randomSuffixStartIndex = virtualTbName.length() + 1;
if (leftCurlyBraceIndex < 0) {
// No table number placeholder
randomSuffixEndIndex = tbNamePattern.length();
} else if (leftCurlyBraceIndex > virtualTbName.length()) {
// Table number placeholder exists
randomSuffixEndIndex = leftCurlyBraceIndex - 1;
}
if (randomSuffixEndIndex > (randomSuffixStartIndex + RANDOM_SUFFIX_LENGTH_OF_PHYSICAL_TABLE_NAME)) {
randomSuffixStartIndex = randomSuffixEndIndex - RANDOM_SUFFIX_LENGTH_OF_PHYSICAL_TABLE_NAME;
}
} else if (virtualTbName.length() > (MAX_TABLE_NAME_LENGTH_MYSQL_ALLOWS
- RANDOM_SUFFIX_LENGTH_OF_PHYSICAL_TABLE_NAME - 1)) {
// Logical table name has been truncated.
String truncatedTableName;
if (leftCurlyBraceIndex < 0) {
// No table number placeholder
truncatedTableName = TStringUtil.substring(tbNamePattern, 0,
tbNamePattern.length() - RANDOM_SUFFIX_LENGTH_OF_PHYSICAL_TABLE_NAME - 1);
if (TStringUtil.startsWithIgnoreCase(virtualTbName, truncatedTableName)) {
randomSuffixStartIndex = truncatedTableName.length() + 1;
randomSuffixEndIndex = tbNamePattern.length();
}
} else {
// Table number placeholder exists
truncatedTableName = TStringUtil.substring(tbNamePattern, 0,
leftCurlyBraceIndex - 1 - RANDOM_SUFFIX_LENGTH_OF_PHYSICAL_TABLE_NAME - 1);
if (TStringUtil.startsWithIgnoreCase(virtualTbName, truncatedTableName)) {
randomSuffixStartIndex = truncatedTableName.length() + 1;
randomSuffixEndIndex = leftCurlyBraceIndex - 1;
}
}
}
if (randomSuffixStartIndex > 0 && randomSuffixEndIndex > randomSuffixStartIndex) {
String possibleRandomSuffix =
TStringUtil.substring(tbNamePattern, randomSuffixStartIndex, randomSuffixEndIndex);
if (TStringUtil.isNotEmpty(possibleRandomSuffix)
&& possibleRandomSuffix.length() == RANDOM_SUFFIX_LENGTH_OF_PHYSICAL_TABLE_NAME) {
randomSuffix = possibleRandomSuffix;
}
}
}
return randomSuffix;
}
public String extractTableNamePrefix() {
String tableNamePrefix = null;
if (TStringUtil.isNotEmpty(tbNamePattern)) {
String possibleTableNamePrefix = null;
int leftCurlyBraceIndex = TStringUtil.indexOf(tbNamePattern, "{");
if (leftCurlyBraceIndex < 0) {
// No table number placeholder
possibleTableNamePrefix = TStringUtil.substring(tbNamePattern, 0);
} else if (leftCurlyBraceIndex > 1) {
// Table number placeholder exists
possibleTableNamePrefix = TStringUtil.substring(tbNamePattern, 0, leftCurlyBraceIndex - 1);
}
if (TStringUtil.isNotEmpty(possibleTableNamePrefix)) {
tableNamePrefix = possibleTableNamePrefix;
}
}
return tableNamePrefix;
}
private void buildStaticTopology(Map<String, String> staticTopology) {
Map<String, Set<String>> topologys = new HashMap<String, Set<String>>();
for (Map.Entry<String, String> entry : staticTopology.entrySet()) {
buildTopology(topologys, entry.getKey(), entry.getValue());
}
this.staticTopology = topologys;
}
private void buildExtTopology(Map<String, Set<String>> topologys) {
if (extPartitions == null) {
return;
}
if (topologys == null) {
topologys = new HashMap<>();
}
for (int i = 0; i < extPartitions.size(); i++) {
final MappingRule mappingRule = extPartitions.get(i);
final String db = mappingRule.getDb();
final String tb = mappingRule.getTb();
final String dbKeyValue = mappingRule.getDbKeyValue();
final String tbKeyValue = mappingRule.getTbKeyValue();
if (!topologys.containsKey(db)) {
Set<String> tables = new HashSet<String>();
topologys.put(db, tables);
}
if (StringUtils.isEmpty(tbKeyValue)) {
final Set<MappingRule> set = new HashSet<>();
HashMap<String, Set<Object>> enumerates = new HashMap<>();
final Rule<String> stringRule = dbShardRules.get(0);
final String column = stringRule.getRuleColumns().keySet().iterator().next();
Object realValue = dbKeyValue;
if (stringRule.getExpression().toLowerCase().startsWith("uni_hash")) {
final RuleColumn ruleColumn = ((ExtPartitionGroovyRule) stringRule).getRuleColumns().get(column);
if (ruleColumn instanceof AdvancedParameter) {
final AtomIncreaseType atomicIncreateType = ((AdvancedParameter) ruleColumn).atomicIncreateType;
if (AtomIncreaseType.NUMBER == atomicIncreateType) {
try {
realValue = Long.valueOf(dbKeyValue);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Hot rule not support value for " + dbKeyValue);
}
}
}
}
final HashSet values = new HashSet();
values.add(realValue);
enumerates.put(column, values);
for (Map<String, Object> sample : new Samples(enumerates)) { // 遍历笛卡尔抽样
String value = stringRule.eval(sample, outerContext, null);
final Set<String> strings = actualTopology.get(value);
topologys.get(db).addAll(strings);
mappingRule.setTbs(strings);
}
} else {
topologys.get(db).add(tb);
}
}
}
private void buildExtMapping() {
if (extPartitions == null) {
return;
}
extDbKeyToMappingRules = new HashMap<>();
extTbKeyToMappingRules = new HashMap<>();
for (int i = 0; i < extPartitions.size(); i++) {
final MappingRule mappingRule = extPartitions.get(i);
final String db = mappingRule.getDb();
final String tb = mappingRule.getTb();
final String dbKeyValue = mappingRule.getDbKeyValue();
final String tbKeyValue = mappingRule.getTbKeyValue();
// set DB key to Mapping rule
Set<MappingRule> mappingRules = extDbKeyToMappingRules.get(dbKeyValue);
if (mappingRules == null) {
mappingRules = new HashSet<>();
extDbKeyToMappingRules.put(dbKeyValue, mappingRules);
}
mappingRules.add(mappingRule);
// set TB key to Mapping rule
if (StringUtils.isNotEmpty(tbKeyValue)) {
final Set<MappingRule> set = new HashSet<>();
set.add(mappingRule);
extTbKeyToMappingRules.put(tbKeyValue, set);
}
}
}
private void buildTopology(Map<String, Set<String>> topologys, String entryKey, String entryValue) {
List<String> keys = buildSlotStrings(entryKey);
List<String> values = buildSlotStrings(entryValue);
if (keys.size() > 1 && values.size() > 1) {
throw new IllegalArgumentException("key/value size > 1 , keys : " + entryKey + " , values : " + entryValue);
} else if (keys.size() > 1) {
// 只分库不分表
String value = tbNamePattern;
if (values.size() == 1) {
value = values.get(0);
}
for (String key : keys) {
Set<String> tables = new HashSet<String>();
tables.add(value);
topologys.put(key, tables);
}
} else if (values.size() > 1) {
// 只分表不分库TB
String key = dbNamePattern;
if (keys.size() == 1) {
key = keys.get(0);
}
topologys.put(key, new HashSet<String>(values));
} else if (keys.size() == 1 || values.size() == 1) {
// 只处理单表
String key = dbNamePattern;
String value = tbNamePattern;
if (keys.size() == 1) {
key = keys.get(0);
}
if (values.size() == 1) {
value = values.get(0);
}
Set<String> tables = new HashSet<String>();
tables.add(value);
topologys.put(key, tables);
}
}
/**
* 解析 user_0,user_[1-128],user_extra
*/
private List<String> buildSlotStrings(String value) {
List<String> values = new ArrayList<String>();
String[] pieces = StringUtils.split(StringUtils.trim(value), ',');
for (String piece : pieces) {
// 首先匹配user_[0000-0128]_extra
Matcher matcher = TOPOLOGY_PATTERN.matcher(piece);
if (matcher.matches()) {
String prefix = matcher.group(1);
String startStr = matcher.group(3);
String ednStr = matcher.group(4);
int start = Integer.valueOf(startStr);
int end = Integer.valueOf(ednStr);
String postfix = matcher.group(5);
for (int i = start; i <= end; i++) {
StringBuilder builder = new StringBuilder(value.length());
String str = String.valueOf(i);
// 处理0001类型
if (startStr.length() == ednStr.length() && startStr.startsWith("0")) {
str = StringUtils.leftPad(String.valueOf(i), startStr.length(), '0');
}
builder.append(prefix).append(str).append(postfix);
values.add(builder.toString());
}
} else {
values.add(piece);
}
}
return values;
}
public int getActualTbCount() {
return actualTbCount;
}
public void setActualTbCount(int actualTbCount) {
this.actualTbCount = actualTbCount;
}
public int getActualDbCount() {
return actualDbCount;
}
public void setActualDbCount(int actualDbCount) {
this.actualDbCount = actualDbCount;
}
public ShardFunctionMeta getDbShardFunctionMeta() {
return dbShardFunctionMeta;
}
public void setDbShardFunctionMeta(ShardFunctionMeta dbShardFunctionMeta) {
this.dbShardFunctionMeta = dbShardFunctionMeta;
}
public ShardFunctionMeta getTbShardFunctionMeta() {
return tbShardFunctionMeta;
}
public void setTbShardFunctionMeta(ShardFunctionMeta tbShardFunctionMeta) {
this.tbShardFunctionMeta = tbShardFunctionMeta;
}
public Map<String, Object> getDbShardFunctionMetaMap() {
return dbShardFunctionMetaMap;
}
public void setDbShardFunctionMetaMap(Map<String, Object> dbShardFunctionMetaMap) {
this.dbShardFunctionMetaMap = dbShardFunctionMetaMap;
}
public Map<String, Object> getTbShardFunctionMetaMap() {
return tbShardFunctionMetaMap;
}
public void setTbShardFunctionMetaMap(Map<String, Object> tbShardFunctionMetaMap) {
this.tbShardFunctionMetaMap = tbShardFunctionMetaMap;
}
public String[] getTbNamesOfExtraDb() {
return tbNamesOfExtraDb;
}
public void setTbNamesOfExtraDb(String[] tbNamesOfExtraDb) {
this.tbNamesOfExtraDb = tbNamesOfExtraDb;
}
public String[] getDbNamesOfExtraDb() {
return dbNamesOfExtraDb;
}
public void setDbNamesOfExtraDb(String[] dbNamesOfExtraDb) {
this.dbNamesOfExtraDb = dbNamesOfExtraDb;
}
public List<MappingRule> getExtPartitions() {
return extPartitions;
}
public void setExtPartitions(List<MappingRule> extPartitions) {
this.extPartitions = extPartitions;
if (extPartitions != null && extPartitions.size() > 0) {
Collections.sort(extPartitions);
}
}
public Map<String, Set<MappingRule>> getExtDbKeyToMappingRules() {
return extDbKeyToMappingRules;
}
public Map<String, Set<MappingRule>> getExtTbKeyToMappingRules() {
return extTbKeyToMappingRules;
}
public int getRuleDbCount() {
final Map<String, Set<String>> actualTopology = getActualTopology();
Assert.assertTrue(actualTopology.size() >= ruleDbCount);
return ruleDbCount;
}
public int getExtDbCount() {
final Map<String, Set<String>> actualTopology = getActualTopology();
Assert.assertTrue(actualTopology.size() >= ruleDbCount);
return extDbCount;
}
public int getRuleTbCount() {
final Map<String, Set<String>> actualTopology = getActualTopology();
Assert.assertTrue(actualTopology.size() >= ruleDbCount);
return ruleTbCount;
}
public int getExtTbCount() {
final Map<String, Set<String>> actualTopology = getActualTopology();
Assert.assertTrue(actualTopology.size() >= ruleDbCount);
return extTbCount;
}
public boolean isRandomTableNamePatternEnabled() {
return randomTableNamePatternEnabled;
}
public void setRandomTableNamePatternEnabled(boolean randomTableNamePatternEnabled) {
this.randomTableNamePatternEnabled = randomTableNamePatternEnabled;
}
public String getExistingRandomSuffixForRecovery() {
return existingRandomSuffixForRecovery;
}
public void setExistingRandomSuffixForRecovery(String existingRandomSuffixForRecovery) {
this.existingRandomSuffixForRecovery = existingRandomSuffixForRecovery;
}
public String getTableNamePrefixForShadowTable() {
return tableNamePrefixForShadowTable;
}
public void setTableNamePrefixForShadowTable(String tableNamePrefixForShadowTable) {
this.tableNamePrefixForShadowTable = tableNamePrefixForShadowTable;
}
}
| polardb/polardbx-sql | polardbx-rule/src/main/java/com/alibaba/polardbx/rule/TableRule.java |
66,179 | package cn.liutils.api.util;
import java.util.List;
import net.minecraft.command.IEntitySelector;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MathHelper;
import net.minecraft.util.Vec3;
import net.minecraft.world.World;
import cn.liutils.core.entity.IEntityLink;
public final class MobHelper {
/**
* WeAthFolD: 把一个奇怪的生物生成到世界中。
*
* mkpoli: 喂 变态 哪里奇怪了
*
*/
public static Entity spawnCreature(World par0World,
Class<? extends Entity> c, EntityLivingBase thrower, boolean front) {
Entity entity = null;
try {
entity = c.getConstructor(World.class).newInstance(par0World);
} catch (Exception e) {
e.printStackTrace();
}
if (entity != null && entity instanceof EntityLivingBase) {
EntityLiving entityliving = (EntityLiving) entity;
float f = 0.4F;
Vec3 lookVec = thrower.getLookVec();
if(front)
entityliving.setLocationAndAngles(thrower.posX + lookVec.xCoord * 2,
thrower.posY, thrower.posZ + lookVec.zCoord * 2,
thrower.rotationYawHead, 0.0F);
else entityliving.setLocationAndAngles(thrower.posX,
thrower.posY, thrower.posZ,
thrower.rotationYawHead, 0.0F);
entityliving.rotationYawHead = entityliving.rotationYaw;
entityliving.renderYawOffset = entityliving.rotationYaw;
if (entityliving instanceof IEntityLink) {
((IEntityLink) entityliving).setLinkedEntity(thrower);
}
entityliving.onSpawnWithEgg((IEntityLivingData)null);
par0World.spawnEntityInWorld(entity);
entityliving.playLivingSound();
}
return entity;
}
public static Entity spawnCreature(World par0World, EntityPlayer thrower, Class<? extends Entity> c, double par2, double par4, double par6)
{
Entity entity = null;
try {
entity = c.getConstructor(World.class).newInstance(par0World);
} catch (Exception e) {
e.printStackTrace();
}
for (int j = 0; j < 1; ++j)
{
if (entity != null && entity instanceof EntityLivingBase)
{
EntityLiving entityliving = (EntityLiving)entity;
entity.setLocationAndAngles(par2, par4, par6, MathHelper.wrapAngleTo180_float(par0World.rand.nextFloat() * 360.0F), 0.0F);
entityliving.rotationYawHead = entityliving.rotationYaw;
entityliving.renderYawOffset = entityliving.rotationYaw;
entityliving.onSpawnWithEgg((IEntityLivingData)null);
if (entityliving instanceof IEntityLink && thrower != null) {
((IEntityLink) entityliving).setLinkedEntity(thrower);
}
par0World.spawnEntityInWorld(entity);
entityliving.playLivingSound();
}
}
return entity;
}
private static void setEntityHeading(Entity ent, double par1, double par3,
double par5, double moveSpeed) {
float f2 = MathHelper.sqrt_double(par1 * par1 + par3 * par3 + par5
* par5);
par1 /= f2;
par3 /= f2;
par5 /= f2;
par1 *= moveSpeed;
par3 *= moveSpeed;
par5 *= moveSpeed;
ent.motionX = par1;
ent.motionY = par3;
ent.motionZ = par5;
float f3 = MathHelper.sqrt_double(par1 * par1 + par5 * par5);
ent.prevRotationYaw = ent.rotationYaw = (float) (Math.atan2(par1, par5) * 180.0D / Math.PI);
ent.prevRotationPitch = ent.rotationPitch = (float) (Math.atan2(par3,
f3) * 180.0D / Math.PI);
}
public static Entity getNearestTargetWithinAABB(World world, double x, double y, double z, float range, IEntitySelector selector, Entity... exclusion) {
AxisAlignedBB box = AxisAlignedBB.getBoundingBox(x - range, y - range, z - range, x + range, y + range, z + range);
List<Entity> entList = world.getEntitiesWithinAABBExcludingEntity(null, box, selector);
double distance = range + 10000.0;
Entity target = null;
for(Entity e : entList) {
for(Entity ex : exclusion)
if(e == ex) continue;
double d = e.getDistanceSq(x, y, z);
if(d < distance) {
target = e;
distance = d;
}
}
return target;
}
}
| LambdaInnovation/LambdaCraft-Legacy | src/main/java/cn/liutils/api/util/MobHelper.java |
66,181 |
// 题目1389:变态跳台阶
/**
* @author:wangzq
* @email:[email protected]
* @date:2015-06-30 11:01:54
* @url:http://ac.jobdu.com/problem.php?pid=1389
*/
import java.io.StreamTokenizer;
public class Main {
/*
* 1389
*/
public static void main(String[] args) throws Exception {
StreamTokenizer st = new StreamTokenizer(System.in);
long array[] = new long[80];
array[0] = 1;
array[1] = 1;
for (int i = 2; i < array.length; i++) {
array[i] = 2 * array[i - 1];
}
while (st.nextToken() != StreamTokenizer.TT_EOF) {
int n = (int) st.nval;
System.out.println(array[n]);
}
}
}
/**************************************************************
Problem: 1389
User: wzqwsrf
Language: Java
Result: Accepted
Time:70 ms
Memory:14532 kb
****************************************************************/
| wzqwsrf/Jobdu | Java/题目1389:变态跳台阶.java |
66,183 | package nowcoder.剑指offer;
import java.util.Vector;
/**
* 变态跳台阶 ★★★★★
*
* 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
*
* 思路:方法一:动态规划 同上,N级台阶需要: f(n) = f(n-1)+f(n-2)+..+f(n- (n-1) )+f(n-n) 同时注意存储已经算好的数字 ;f(1) =1; f(2) = 2;f(3) = f(0)+f(1)+f(2) f(0)表示一次跳的方法
* 方法二:根据推倒可得 f(n) = 2 ^ (n-1) 即:f(n) = 2*f(n-1)
*
* @date 2016年4月27日 下午6:54:21
* @author yangengzhe
*
*/
public class code11 {
Vector<Integer> vectors = new Vector<Integer>();
//公式
public int JumpFloorII(int target) {
int result = 1;
while(target-->1)
result = result*2;
return result;
}
//递归
public int JumpFloorII2(int target) {
int sum = 0;
if(vectors.size()==0) vectors.add(0,1);
if(vectors.size()>target) return vectors.get(target);
for(int i=0;i<target;i++)
sum += JumpFloorII(i);
vectors.add(target, sum);
return sum;
}
public static void main(String args[]){
code11 c = new code11();
System.out.println(c.JumpFloorII(3));
}
}
| yangengzhe/coding-guide_i3geek | nowcoder/src/nowcoder/剑指offer/code11.java |
66,184 | //10.4 变态跳台阶
//虽然是变态,但是找到等比数列规律且发现可以用位移运算以后还是很简单的。
public class Solution {
public int JumpFloorII(int target) {
if(target<=0)
return 0;
return 1<<(target-1);//位移target-1次相当于求了2的多少次。
}
} | anliux/PracticePool | jzoffer/src/10_4_变态跳台阶.java |
66,185 | package sword_offer.code09_变态跳台阶;
public class Solution_递归方式 {
public static int JumpFloorII(int target) {
if(target<=2){
return target;
}
int count = 0;
for (int i = 1; i < target; i++) {
count += JumpFloorII(target - i);
}
return count + 1;
}
public static int JumpFloorII2(int target) {
int [] array = new int[target+1];
array[0] = 0;
array[1] = 1;
for(int i = 2; i <= target; i++) {
array[i] = 2 * array[i-1];
}
return array[target];
}
public static void main(String[] args) {
System.out.println(JumpFloorII(10));
System.out.println(JumpFloorII2(10));
}
} | frank-lam/interview_code | src/sword_offer/code09_变态跳台阶/Solution_递归方式.java |
66,187 | package sword.offer;
/**
* @ClassName 跳台阶
* @Description
* @Author cqutwangyu
* @DateTime 2019/3/12 20:00
* @GitHub https://github.com/cqutwangyu
*/
public class 变态跳台阶 {
public static void main(String[] args) {
System.out.println(JumpFloorII(4));
}
/**
* 变态跳台阶
* 左移1位就是乘以一个2,在1基础上左移number-1位就是1乘以2^(number-1)
*
* @param target
* @return
*/
public static int JumpFloorII(int target) {
//究极解法,用位移
return 1 << (target - 1);
// if (target == 0) {
// return -1;
// }
// if (target == 1) {
// return 1;
// }
// return 2 * JumpFloorII(target - 1);
}
}
| cqutwangyu/Java-Algorithm-Notes | src/sword/offer/变态跳台阶.java |
66,188 | package com.meteor.kit;
import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.TimeZone;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
/**
*
* @ClassName DateUtil
* @author Meteor
* @date 2015年8月10日 下午2:51:29
* @category 日期工具类
*/
public class DateKit {
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:44:55
* @Title Date2Str
* @param d
* @param format
* @return String 返回类型
* @category 日期转字符串 sqldate
*/
public static String Date2Str(Date d, String format) {
if (null == d) {
// d = new Date();
return "";
}
SimpleDateFormat df = new SimpleDateFormat(format);
java.sql.Date sDate = new java.sql.Date(d.getTime());
String strDate = df.format(sDate);
return strDate;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:55:28
* @Title dateToString
* @param date
* @param pattern
* @return String 返回类型
* @category 日期转字符串
*/
public static String dateToString(Date date, String pattern) {
if (date == null) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
return formatter.format(date);
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:23:33
* @Title dateToStr
* @param dateDate
* @return String 返回类型
* @category 将短时间格式时间转换为字符串 yyyy-MM-dd
*/
public static String dateToStr(Date dateDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(dateDate);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:29:20
* @Title dateToStrLong
* @param dateDate
* @return String 返回类型
* @category 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
*/
public static String dateToStrLong(Date dateDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(dateDate);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:14:58
* @Title strToDate
* @param strDate yyyy-MM-dd
* @return Date 返回类型
* @category 将短时间格式字符串转换为时间
*/
public static Date strToDate(String strDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:27:47
* @Title strToDateLong
* @param strDate yyyy-MM-dd HH:mm:ss
* @return Date 返回类型
* @category 将长时间格式字符串转换为时间
*/
public static Date strToDateLong(String strDate) {
if (StringUtils.isBlank(strDate)) {
return null;
}
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:29:22
* @Title strToDateLong
* @param strDate yyyy-MM-dd HH:mm:ss
* @param format
* @return Date 返回类型
* @category 将长时间格式字符串转换为时间
*/
public static Date strToDateLong(String strDate, String format) {
SimpleDateFormat formatter = new SimpleDateFormat(format);
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(strDate, pos);
return strtodate;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:03:18
* @Title getWeekXq
* @param sdate yyyy-MM-dd HH:mm:ss
* @return String 返回类型
* @category 返回日期的星期
*/
public static String getWeekXq(String sdate) {
int w = getWeekNum(sdate);
String s = "";
switch (w) {
case 0:
s = "星期天";
break;
case 1:
s = "星期一";
break;
case 2:
s = "星期二";
break;
case 3:
s = "星期三";
break;
case 4:
s = "星期四";
break;
case 5:
s = "星期五";
break;
case 6:
s = "星期六";
break;
}
return s;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:06:10
* @Title getWeekZhou
* @param sdate yyyy-MM-dd HH:mm:ss
* @return String 返回类型
* @category 返回日期的周数
*/
public static String getWeekZhou(String sdate) {
int w = getWeekNum(sdate);
String s = "";
switch (w) {
case 0:
s = "周日";
break;
case 1:
s = "周一";
break;
case 2:
s = "周二";
break;
case 3:
s = "周三";
break;
case 4:
s = "周四";
break;
case 5:
s = "周五";
break;
case 6:
s = "周六";
break;
}
return s;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:07:08
* @Title getWeekNum
* @param sdate yyyy-MM-dd HH:mm:ss
* @return int 返回类型
* @category 返回数字星期 星期天是0 星期一是1
*/
public static int getWeekNum(String sdate) {
Calendar cal = new GregorianCalendar();
cal.setTime(strToDate(sdate));
return cal.get(Calendar.DAY_OF_WEEK) - 1;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:09:34
* @Title getWeekEn
* @param sdate
* @return String 返回类型
* @category 返回英文星期
*/
public static String getWeekEn(String sdate) {
Date date = strToDate(sdate);
Calendar c = Calendar.getInstance();
c.setTime(date);
return new SimpleDateFormat("EEE", Locale.ENGLISH).format(c.getTime());
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:14:34
* @Title getNextMonth
* @param dates
* @param count
* @return String 返回类型
* @category 取得指定日期的下一个月
*/
public static String getNextMonth(String dates, int count) {
Date date = strToDate(dates);
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(date);
gc.add(Calendar.MONTH, count);
return dateToStr(gc.getTime());
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:08:41
* @Title getFutureDay
* @param appDate 指定日期
* @param format 指定日期格式yyyy-MM-dd
* @param days 指定天数
* @return String 返回类型
* @category 用于返回指定日期格式的日期增加指定天数的日期
*/
public static String getFutureDay(String appDate, String format, int days) {
String future = "";
try {
Calendar calendar = GregorianCalendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date date = simpleDateFormat.parse(appDate);
calendar.setTime(date);
calendar.add(Calendar.DATE, days);
date = calendar.getTime();
future = simpleDateFormat.format(date);
} catch (Exception e) {
}
return future;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:09:43
* @Title getNextDay
* @param nowdate
* @param delay
* @return String 返回类型 yyyy-MM-dd
* @category 得到一个时间延后或前移几天的时间,nowdate为时间,delay为前移或后延的天数
*/
public static String getNextDay(String nowdate, String delay) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String mdate = "";
Date d = null;
if (nowdate == null || "".equals(nowdate)) {
d = new Date();
} else {
d = strToDate(nowdate);
}
long myTime = (d.getTime() / 1000) + Integer.parseInt(delay) * 24 * 60 * 60;
d.setTime(myTime * 1000);
mdate = format.format(d);
return mdate;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:31:27
* @Title getPreTime
* @param sj1
* @param jj
* @return String 返回类型
* @category 时间前推或后推分钟,其中JJ表示分钟
*/
public static String getNextTime(String sj1, String jj) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String mydate1 = "";
try {
Date date1 = format.parse(sj1);
long Time = (date1.getTime() / 1000) + Integer.parseInt(jj) * 60;
date1.setTime(Time * 1000);
mydate1 = format.format(date1);
} catch (Exception e) {
}
return mydate1;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:44:03
* @Title getNextTimesec
* @param sj1
* @param jj
* @return String 返回类型
* @category 时间前推或后推秒钟,其中JJ表示秒钟.
*/
public static String getNextTimesec(String sj1, int jj) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String mydate1 = "";
try {
Date date1 = format.parse(sj1);
long Time = (date1.getTime() / 1000) + jj;
date1.setTime(Time * 1000);
mydate1 = format.format(date1);
} catch (Exception e) {
}
return mydate1;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:29:58
* @Title getCurrTime
* @return String 返回类型
* @category 获取当前时间 yyyyMMddHHmmss
*/
public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:31:20
* @Title getStrDateFormat
* @param strDate
* @return String 返回类型 yyyy年MM月dd日
* @category 转为中文格式显示
*/
public static String getStrDateFormat(String strDate) {
Date date = strToDateLong(strDate);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
String dateString = formatter.format(date);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:42:30
* @Title getTwoHour
* @param st1
* @param st2
* @return String 返回类型
* @category 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式,返回字符型的分钟
*/
public static String getTwoHour(String st1, String st2) {
String[] kk = null;
String[] jj = null;
kk = st1.split(":");
jj = st2.split(":");
if (Integer.parseInt(kk[0]) < Integer.parseInt(jj[0]))
return "0";
else {
double y = Double.parseDouble(kk[0]) + Double.parseDouble(kk[1]) / 60;
double u = Double.parseDouble(jj[0]) + Double.parseDouble(jj[1]) / 60;
if ((y - u) > 0)
return y - u + "";
else
return "0";
}
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:45:07
* @Title getMinutesFromTwoHour
* @param st1
* @param st2
* @return int 返回类型
* @category 二个小时时间间的差值,必须保证二个时间都是"HH:MM"的格式,返回分钟 VIP
*/
public static int getMinutesFromTwoHour(String st1, String st2) {
String[] kk = st1.split(":");
String[] jj = st2.split(":");
if(kk.length!=2||jj.length!=2){
return 0;
}
int y = NumberUtils.toInt(kk[0],0)*60 + NumberUtils.toInt(kk[1],0) ;
int u = NumberUtils.toInt(jj[0],0)*60 + NumberUtils.toInt(jj[1],0) ;
return u - y;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:32:42
* @Title DateDiff
* @param sDate1 yyyy-MM-dd 最新的时间
* @param sDate2 yyyy-MM-dd 相比较的时间
* @return int 返回类型
* @category 相差天数
*/
public static int DateDiff(String sDate1, String sDate2) { // sDate1和sDate2是2002-12-18格式
String[] aDate;
Integer iDays;
aDate = sDate1.split("-");
Integer jsrq = Integer.valueOf(aDate[0]) * 31 * 24 + Integer.valueOf(aDate[1]) * 31 + Integer.valueOf(aDate[2]); // 转换为12-18-2002格式
aDate = sDate2.split("-");
Integer ksrq = Integer.valueOf(aDate[0]) * 31 * 24 + Integer.valueOf(aDate[1]) * 31 + Integer.valueOf(aDate[2]);
iDays = jsrq - ksrq; // 把相差天数
return iDays;
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:06:16
* @Title twoDayWeeks
* @param ksrq
* @param jsrq
* @return int 返回类型
* @category 2个日期间所跨的周数
*/
public static int twoDayWeeks(String ksrq, String jsrq) {
int allDate = NumberUtils.toInt(getTwoDay(jsrq, ksrq)) + 1;
String sd = ksrq;
int count = 1;
for (int i = 1; i < allDate; i++) {
String d = getNextDay(ksrq, i + "");
if (!isSameWeekDates(strToDate(sd), strToDate(d))) {
count++;
}
sd = d;
}
return count;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:21:25
* @Title monthsBetween
* @param pLatterStr
* @param pFormerStr
* @return int 返回类型
* @category 给定两个时间相差的月数,String版
*/
public static int monthsBetween(String pLatterStr, String pFormerStr) {
GregorianCalendar vFormer = parse2Cal(pFormerStr);
GregorianCalendar vLatter = parse2Cal(pLatterStr);
return monthsBetween(vLatter, vFormer);
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:26:59
* @Title getTwoDay
* @param sj1
* @param sj2
* @return String 返回类型
* @category 得到二个日期间的间隔天数
*/
public static String getTwoDay(String sj1, String sj2) {
if (sj1 == null || sj1.equals(""))
return "";
if (sj2 == null || sj2.equals(""))
return "";
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
long day = 0;
try {
Date date = myFormatter.parse(sj1);
Date mydate = myFormatter.parse(sj2);
day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
} catch (Exception e) {
return "";
}
return day + "";
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:27:20
* @Title getTwoMil
* @param sj1
* @param sj2
* @return String 返回类型
* @category 得到二个日期间的间隔分钟
*/
public static String getTwoMil(String sj1, String sj2) {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long day = 0;
try {
Date date = myFormatter.parse(sj1);
Date mydate = myFormatter.parse(sj2);
day = (date.getTime() - mydate.getTime()) / (60 * 1000);
} catch (Exception e) {
return "";
}
return day + "";
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:27:31
* @Title getTwoSecond
* @param sj1
* @param sj2
* @return String 返回类型
* @category 得到二个日期间的间隔秒
*/
public static String getTwoSecond(String sj1, String sj2) {
SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long day = 0;
try {
Date date = myFormatter.parse(sj1);
Date mydate = myFormatter.parse(sj2);
day = (date.getTime() - mydate.getTime()) / (1000);
} catch (Exception e) {
return "";
}
return day + "";
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:33:50
* @Title getEndDateOfMonth
* @param dat
* @return String 返回类型
* @category 获取一个月的最后一天
*/
public static String getEndDateOfMonth(String dat) {// yyyy-MM-dd
String str = dat.substring(0, 7);
String month = dat.substring(5, 7);
int mon = Integer.parseInt(month);
if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
str += "-31";
} else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
str += "-30";
} else {
if (isLeapYear(dat)) {
str += "-29";
} else {
str += "-28";
}
}
return str;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:34:25
* @Title getFirstDateOfMonth
* @param dat
* @return String 返回类型
* @category 返回指定日期的第一天 日期为yyyy-MM-dd格式
*/
public static String getFirstDateOfMonth(String dat){
if(StringUtils.isBlank(dat)){
return null;
}
if(dat.length() < 7){
return null;
}
String str = dat.substring(0, 7);
return str + "-01";
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:35:45
* @Title getTheDateOfMonth
* @param dat
* @param day
* @return String 返回类型
* @category 返回指定日期所在月份的某天,包括大小月判断,如果指定月的天数小于day,则返回最后一天 日期为yyyy-MM-dd格式
*/
public static String getTheDateOfMonth(String dat,int day){
if(StringUtils.isBlank(dat)){
return null;
}
if(dat.length() < 7){
return null;
}
String str = dat.substring(0, 7);
String month = dat.substring(5, 7);
int maxDay = 31;
int mon = Integer.parseInt(month);
if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
maxDay = 30;
} else {
if(mon==2){
if (isLeapYear(dat)) {
maxDay = 29;
} else {
maxDay = 28;
}
}
}
if(day < 1){
day = 1;
}
if(day > maxDay){
day = maxDay;
}
if(String.valueOf(day).length() == 1){
return str + "-0" + day;
}else{
return str + "-" + day;
}
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:42:33
* @Title isLeapYear
* @param ddate
* @return boolean 返回类型
* @category 判断是否润年
*/
public static boolean isLeapYear(String ddate) {
/**
* 详细设计: 1.被400整除是闰年,否则: 2.不能被4整除则不是闰年 3.能被4整除同时不能被100整除则是闰年 3.能被4整除同时能被100整除则不是闰年
*/
Date d = strToDate(ddate);
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
gc.setTime(d);
int year = gc.get(Calendar.YEAR);
if ((year % 400) == 0)
return true;
else if ((year % 4) == 0) {
if ((year % 100) == 0)
return false;
else
return true;
} else
return false;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:30:23
* @Title getUserDate
* @param sformat
* @return String 返回类型
* @category 根据用户传入的时间表示格式,返回当前时间的格式 如yyyyMMdd,注意字母y不能大写。
*/
public static String getUserDate(String sformat) {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat(sformat);
String dateString = formatter.format(currentTime);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:34:34
* @Title getFormatDate
* @param str
* @param str
* @return String 返回类型
* @category 传入的时间和时间表示格式,将时间转换为指定格式 如果是yyyyMMdd,注意字母y不能大写。
*/
public static String getFormatDate(String str) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = strToDateLong(str);
String dateString = formatter.format(date);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:34:34
* @Title getFormatDate
* @param sformat
* @param str
* @return String 返回类型
* @category 传入的时间和时间表示格式,将时间转换为指定格式 如果是yyyyMMdd,注意字母y不能大写。
*/
public static String getFormatDate(String sformat, String str) {
SimpleDateFormat formatter = new SimpleDateFormat(sformat);
Date date = strToDateLong(str);
String dateString = formatter.format(date);
return dateString;
}
public static String fmtDateString(String date) {
try {
String sformat = "dd/MM/yyyy HH:mm:ss";
String sformat2 = "yyyy-MM-dd HH:mm:ss";
Date zhedate = new SimpleDateFormat(sformat).parse(date);
SimpleDateFormat sf = new SimpleDateFormat(sformat2);
date=sf.format(zhedate);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:48:14
* @Title fmtDate
* @param date
* @return String 返回类型
* @category 把一位月日时分秒格式化为2位
*/
public static String fmtDate(String date) {
if (StringUtils.isBlank(date)) {
return "";
}
String str = "";
String[] yyhh = date.split(" ");
if (yyhh.length > 0) {// yyyy-mm-dd
String[] yymmddsz = yyhh[0].split("-");
for (String s : yymmddsz) {
if (s.length() == 1) {
s = "0" + s;
}
if ("".equals(str)) {
str = s;
} else {
str += "-" + s;
}
}
}
if (yyhh.length > 1) {// hh:mm:ss
str += " ";
String[] hhmmsssz = yyhh[1].split(":");
for (int i = 0; i < hhmmsssz.length; i++) {
String s = hhmmsssz[i];
if (s.length() == 1) {
s = "0" + s;
}
if (i == 0) {
str += s;
} else {
str += ":" + s;
}
}
}
return str;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:50:09
* @Title startDateTime
* @param date
* @return Date 返回类型
* @category 补齐开始日期到秒.使其格式为YYYY-MM-DD HH24:MI:SS
*/
public static Date startDateTime(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
return new Timestamp(calendar.getTime().getTime());
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:50:22
* @Title endDateTime
* @param date
* @return Date 返回类型
* @category 补齐结束日期到秒.使其格式为YYYY-MM-DD HH24:MI:SS
*/
public static Date endDateTime(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.MILLISECOND, 999);
return new Timestamp(calendar.getTime().getTime());
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 上午11:16:12
* @Title KsrqString
* @param ksrq
* @return String 返回类型
* @category 补齐开始日期到秒.使其格式为YYYY-MM-DD HH24:MI:SS
*/
public static String KsrqString(String ksrq) {
ksrq=ksrq.trim();
String newKsrq = "";
// 形参字符串长度
Integer Stringlength = ksrq.trim().length();
switch (Stringlength) {
case 10:
newKsrq = ksrq + " 00:00:00";
break;
case 13:
newKsrq = ksrq + ":00:00";
break;
case 16:
newKsrq = ksrq + ":00";
break;
default:
newKsrq = ksrq;
break;
}
return newKsrq;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 上午11:16:50
* @Title JsrqString
* @param jsrq
* @return String 返回类型
* @category 补齐结束日期到秒.使其格式为YYYY-MM-DD HH24:MI:SS
*/
public static String JsrqString(String jsrq) {
jsrq=jsrq.trim();
String newJsrq = "";
// 形参字符串长度
Integer Stringlength = jsrq.trim().length();
switch (Stringlength) {
case 10:
newJsrq = jsrq + " 23:59:59";
break;
case 13:
newJsrq = jsrq + ":59:59";
break;
case 16:
newJsrq = jsrq + ":59";
break;
default:
newJsrq = jsrq;
break;
}
return newJsrq;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:52:55
* @Title dateTime
* @param date
* @param hour
* @param minute
* @param second
* @param millisecond
* @return Date 返回类型
* @category 补齐日期的到秒
*/
public static Date dateTime(Date date, int hour, int minute, int second, int millisecond) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, second);
calendar.set(Calendar.MILLISECOND, millisecond);
return new Timestamp(calendar.getTime().getTime());
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:53:48
* @Title convert
* @param date
* @param isLDate true时返回日期格式是带有时分秒的
* @return Date 返回类型
* @category 返回sqlDate日期格式
*/
public static Date convert(Date date, boolean isLDate) {
if (date == null) {
return null;
}
if (isLDate) {
return new Timestamp(date.getTime());
} else {
return new java.sql.Date(date.getTime());
}
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:53:59
* @Title convert
* @param strdate
* @param isLDate true时返回日期格式是带有时分秒的
* @return Date 返回类型
* @category 返回sqlDate日期格式
*/
public static Date convert(String strdate, boolean isLDate) {
Date date = strToDate(strdate);
return convert(date, isLDate);
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:58:43
* @Title isDate
* @param strDate
* @return boolean 返回类型
* @category 验证日期格式 yyyy-mm-dd
*/
public static boolean isDate(String strDate) {
return strDate.matches("((((19|20)\\d{2})-(0?[13578]|1[02])-"
+ "(0?[1-9]|[12]\\d|3[01]))|(((19|20)\\d{2})-(0?[469]|11)-"
+ "(0?[1-9]|[12]\\d|30))|(((19|20)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-9])))");
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:59:04
* @Title isDatetime
* @param datetime
* @return boolean 返回类型
* @category 验证日期时间格式 yyyy-mm-dd hh:mm:ss
*/
public static boolean isDatetime(String datetime) {
return datetime.matches("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?"
+ "((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|"
+ "(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?"
+ "((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))"
+ "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|"
+ "(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]"
+ "((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1][0-9])|([2][0-3]))\\:([0-5]?[0-9])"
+ "((\\s)|(\\:([0-5]?[0-9])))))$");
}
/**
*
* @param sql
* sql
* @param params
* params
* @param start
* start
* @param count
* count
* @return String String
*/
@SuppressWarnings("unchecked")
public static String debugSql(String sql, Collection params, int start, int count) {
if (params != null) {
Iterator iter = params.iterator();
while (iter.hasNext()) {
Object key = iter.next();
String p = "";
if (key instanceof String) {
p = "'" + key.toString() + "'";
} else if (key instanceof Date) {
p = "to_date('" + key.toString() + "','yyyy-mm-dd hh24:mi:ss')";
} else if (key instanceof Timestamp) {
p = "to_date('" + key.toString() + "','yyyy-mm-dd hh24:mi:ss')";
} else {
p = key == null ? "null" : key.toString();
}
sql = StringUtils.replaceOnce(sql, "?", p);
}
}
if (count > 0) {
StringBuffer sb = new StringBuffer("select b_table.* from (select a_table.*,rownum as linenum from");
sb.append("(").append(sql).append(" ) a_table where rownum <= ").append(start + count)
.append(") b_table where linenum >").append(start);
sql = sb.toString();
}
System.out.println(sql);
return sql;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:01:27
* @Title getMilForDate
* @param date
* @return String 返回类型
* @category 得到指定时间和当前时间的间隔分钟
*/
public static String getMilForDate(Date date) {
long day = 0;
try {
Date dt = new Date();
day = (date.getTime() - dt.getTime()) / (60 * 1000);
} catch (Exception e) {
return "";
}
return day + "";
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:03:15
* @Title getMilForDate
* @param date
* @return String 返回类型
* @category 得到指定时间和当前时间的间隔分钟
*/
public static String getMilForDate(String date) {
return getMilForDate(strToDateLong(date));
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:05:57
* @Title isRightDate
* @param date
* @param format
* @return boolean 返回类型
* @category 判断一个给定的日期字符串是否符合给定的格式,并且是有效的日期
*/
public static boolean isRightDate(String date, String format) {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
if (sdf.format(sdf.parse(date)).equalsIgnoreCase(date))
return true;
else
return false;
} catch (Exception ex) {
return false;
}
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:15:11
* @Title getZeroByDate
* @param date
* @return Date 返回类型
* @category 取传入日期的零时零分零秒
*/
public static Date getZeroByDate(Date date) {
if (date == null) {
date = new Date();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:16:57
* @Title timeToDate
* @param time
* @return Date 返回类型
* @category time为date类型的日期
*/
public static Date timeToDate(long time) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String d = format.format(time);
try {
Date date = format.parse(d);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:20:32
* @Title getMondayDate
* @param date
* @return String 返回类型
* @category 获得传入日期的本周星期一的日期
*/
public static String getMondayDate(String date) {
String monday = "";
String strFormat = "yyyy-MM-dd";
try {
SimpleDateFormat sdf = new SimpleDateFormat(strFormat, Locale.CHINA);
Calendar calendar = Calendar.getInstance(Locale.CHINA);
calendar.setTimeInMillis(strToDateLong(date, strFormat).getTime());
calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
monday = sdf.format(calendar.getTime());
} catch (Exception e) {
e.printStackTrace();
}
return monday;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:13:33
* @Title date2Calendar
* @param date
* @return Calendar 返回类型
* @category Date转Calendar
*/
public static Calendar date2Calendar(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
return c;
}
private static int monthsBetween(GregorianCalendar pLatter, GregorianCalendar pFormer) {
GregorianCalendar vFormer = pFormer, vLatter = pLatter;
boolean vPositive = true;
if (pFormer.before(pLatter)) {
vFormer = pFormer;
vLatter = pLatter;
} else {
vFormer = pLatter;
vLatter = pFormer;
vPositive = false;
}
int vCounter = 0;
while (vFormer.get(Calendar.YEAR) != vLatter.get(Calendar.YEAR)
|| vFormer.get(Calendar.MONTH) != vLatter.get(Calendar.MONTH)) {
vFormer.add(Calendar.MONTH, 1);
vCounter++;
}
if (vPositive)
return vCounter;
else
return -vCounter;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:22:34
* @Title parse2Cal
* @param pDateStr
* @return GregorianCalendar 返回类型
* @category 将字符串格式的日期转换为Calender
*/
public static GregorianCalendar parse2Cal(String pDateStr) {
StringTokenizer sToken;
sToken = new StringTokenizer(pDateStr, "-");
int vYear = Integer.parseInt(sToken.nextToken());
// GregorianCalendar的月份是从0开始算起的,变态!!
int vMonth = Integer.parseInt(sToken.nextToken()) - 1;
int vDayOfMonth = Integer.parseInt(sToken.nextToken());
return new GregorianCalendar(vYear, vMonth, vDayOfMonth);
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:07:24
* @Title getDateByCalendar
* @param calendar
* @return String 返回类型
* @category Calendar 转换为字符日期
*/
public static String getDateByCalendar(Calendar calendar) {
String future = "";
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = calendar.getTime();
future = format.format(date);
} catch (Exception e) {
}
return future;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:33:12
* @Title getTime
* @return String 返回类型
* @category 得到现在分钟
*/
public static String getTime() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
String min;
min = dateString.substring(14, 16);
return min;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午1:55:47
* @Title getHour
* @return String 返回类型
* @category 得到现在小时
*/
public static String getHour() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
String hour;
hour = dateString.substring(11, 13);
return hour;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:12:21
* @Title getNowTime
* @return String 返回类型 [HH:mm]
* @category 获取当前时间
*/
public static String getNowTime() {
return new SimpleDateFormat("HH:mm").format(new Date());
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:07:28
* @Title getStringDate
* @return String 返回类型 yyyy-MM-dd HH:mm:ss
* @category 获取现在时间
*/
public static String getStringDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:24:33
* @Title getStringDateShort
* @return String 返回类型 yyyy-MM-dd
* @category 获取现在时间
*/
public static String getStringDateShort() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:26:29
* @Title getStringDateShortmm
* @return String 返回类型 返回短时间字符串格式yyyy-MM-dd HHmm
* @category 获取现在时间
*/
public static String getStringDateShortmm() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HHmm");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:31:51
* @Title getStringToday
* @return String 返回类型 字符串 yyyyMMdd HHmmss
* @category 得到现在时间
*/
public static String getStringToday() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd HHmmss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:31:51
* @Title getStringToday
* @return String 返回类型 字符串 yyyyMMddHHmmss
* @category 得到现在时间
*/
public static String getStringTodayA() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月12日 下午11:31:17
* @Title getStringTodayB
* @return String 返回类型
* @category 得到现在时间
*/
public static String getStringTodayB() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:56:32
* @Title getNowDate
* @return Date 返回类型
* @category 获取现在时间 yyyy-MM-dd HH:mm:ss
*/
public static Date getNowDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(8);
Date currentTime_2 = formatter.parse(dateString, pos);
return currentTime_2;
}
/**
* 获取现在时间
*
* @return yyyy-MM-dd
*/
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:56:47
* @Title getNowDateShort
* @return Date 返回类型
* @category 获取现在时间 yyyy-MM-dd
*/
public static Date getNowDateShort() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String dateString = formatter.format(currentTime);
ParsePosition pos = new ParsePosition(0);
Date currentTime_2 = formatter.parse(dateString, pos);
return currentTime_2;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午10:57:40
* @Title getNowDateLong
* @return Date 返回类型
* @category 得到当前日期00:00:00 返回格式 yyyy-MM-dd 00:00:00
*/
public static Date getNowDateLong() {
String currentDate = getStringDateShort();
ParsePosition pos = new ParsePosition(0);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return formatter.parse(currentDate + " 00:00:00", pos);
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:28:28
* @Title getTimeShort
* @return String 返回类型
* @category 获取时间 小时:分;秒 HH:mm:ss
*/
public static String getTimeShort() {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
Date currentTime = new Date();
String dateString = formatter.format(currentTime);
return dateString;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:29:46
* @Title getNow
* @return Date 返回类型
* @category 得到现在时间
*/
public static Date getNow() {
Date currentTime = new Date();
return currentTime;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:47:40
* @Title getEDate
* @param str
* @return String 返回类型
* @category 返回美国时间格式 26 Apr 2006
*/
public static String getEDate(String str) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date strtodate = formatter.parse(str, pos);
String j = strtodate.toString();
String[] k = j.split(" ");
return k[2]+" "+ k[1]+" "+ k[5].substring(0, 4);
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:48:08
* @Title isSameWeekDates
* @param date1
* @param date2
* @return boolean 返回类型
* @category 判断二个时间是否在同一个周
*/
public static boolean isSameWeekDates(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
if (0 == subYear) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2.get(Calendar.WEEK_OF_YEAR))
return true;
}
return false;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:48:08
* @Title isSameWeekDates
* @param strdate1
* @param strdate2
* @return boolean 返回类型
* @category 判断二个时间是否在同一个周
*/
public static boolean isSameWeekDates(String strdate1, String strdate2) {
Date date1=strToDate(strdate1);
Date date2=strToDate(strdate2);
return isSameWeekDates(date1, date2);
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:51:01
* @Title getSeqWeek
* @return String 返回类型
* @category 产生周序列即得到当前时间所在的年度是第几周
*/
public static String getSeqWeek() {
Calendar c = Calendar.getInstance(Locale.CHINA);
String week = Integer.toString(c.get(Calendar.WEEK_OF_YEAR));
if (week.length() == 1)
week = "0" + week;
String year = Integer.toString(c.get(Calendar.YEAR));
return year + week;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:52:14
* @Title getWeek
* @param sdate
* @param num
* @return String 返回类型
* @category 获得一个日期所在的周的星期几的日期,如要找出2002年2月3日所在周的星期一是几号
*/
public static String getWeek(String sdate, String num) {
// 再转换为时间
Date dd = strToDate(sdate);
Calendar c = Calendar.getInstance();
c.setTime(dd);
if (num.equals("1")) // 返回星期一所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
else if (num.equals("2")) // 返回星期二所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY);
else if (num.equals("3")) // 返回星期三所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY);
else if (num.equals("4")) // 返回星期四所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.THURSDAY);
else if (num.equals("5")) // 返回星期五所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
else if (num.equals("6")) // 返回星期六所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
else if (num.equals("0")) // 返回星期日所在的日期
c.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:52:55
* @Title getWeek
* @param sdate
* @return String 返回类型
* @category 根据一个日期,返回是星期几的字符串
*/
public static String getWeek(String sdate) {
Date date = strToDate(sdate);
Calendar c = Calendar.getInstance();
c.setTime(date);
return new SimpleDateFormat("EEEE").format(c.getTime());
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:53:53
* @Title getWeekz1
* @param sdate
* @return String 返回类型
* @category 返回日期的周几
*/
public static String getWeekz1(String sdate) {
int w = getWeekNum(sdate);
String s = "";
switch (w) {
case 0:
s = "日";
break;
case 1:
s = "一";
break;
case 2:
s = "二";
break;
case 3:
s = "三";
break;
case 4:
s = "四";
break;
case 5:
s = "五";
break;
case 6:
s = "六";
break;
}
return s;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:55:07
* @Title getNowMonth
* @param sdate
* @return String 返回类型
* @category 形成如下的日历 , 根据传入的一个时间返回一个结构 星期日 星期一 星期二 星期三 星期四 星期五 星期六 下面是当月的各个时间 此函数返回该日历第一行星期日所在的日期
*/
public static String getNowMonth(String sdate) {
// 取该时间所在月的一号
sdate = sdate.substring(0, 8) + "01";
// 得到这个月的1号是星期几
Date date = strToDate(sdate);
Calendar c = Calendar.getInstance();
c.setTime(date);
int u = c.get(Calendar.DAY_OF_WEEK);
String newday = getNextDay(sdate, (1 - u) + "");
return newday;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:55:26
* @Title formatLongToTimeStr
* @param l
* @return String 返回类型
* @category 毫秒转为时分秒
*/
public static String formatLongToTimeStr(Long l) {
long hour = 0;
long minute = 0;
long second = 0;
second = l / 1000;
if (second > 60) {
minute = second / 60;
second = second % 60;
}
if (minute > 60) {
hour = minute / 60;
minute = minute % 60;
}
if (hour == 0 && minute == 0) {
return second + "秒";
}
String s = "";
if (hour != 0) {
s = hour + "时";
}
return (s + minute + "分" + second + "秒");
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:55:45
* @Title formatminuteToTimeStr
* @param l
* @return String 返回类型
* @category 分转为时分秒
*/
public static String formatminuteToTimeStr(Long l) {
long hour = 0;
long minute = 0;
if (l > 60) {
hour = l / 60;
minute = l % 60;
} else {
minute = l;
}
String s = "";
if (hour != 0) {
s = hour + "时";
}
return (s + minute + "分");
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:58:25
* @Title getWeekLastDate
* @param newdate
* @return String 返回类型
* @category 获得本周的最后一天
*/
@SuppressWarnings("static-access")
public static String getWeekLastDate(String newdate) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar calBegin = new GregorianCalendar();
calBegin.setTime(strToDate(newdate));
calBegin.add(calBegin.DATE, (7 - calBegin.get(calBegin.DAY_OF_WEEK)) + 1);
String WeekLastDate = format.format(calBegin.getTime());
return WeekLastDate;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:59:03
* @Title getEndWeekDate
* @return String 返回类型
* @category 获得下周的最后一天
*/
@SuppressWarnings("static-access")
public static String getEndWeekDate() {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Calendar calBegin = new GregorianCalendar();
calBegin.setTime(new Date());
calBegin.add(calBegin.DATE, (7 - calBegin.get(calBegin.DAY_OF_WEEK)) + 8);
String endWeekDate = format.format(calBegin.getTime());
return endWeekDate;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午11:59:15
* @Title getEndQuarter
* @param date
* @return String 返回类型
* @category 传入一个时间,获得下一季度的最后一天
*/
public static String getEndQuarter(String date) {// yyyy-mm-dd
String yy = date.substring(0, 4);
String month = date.substring(5, 7);
String dd = date.substring(8);
if ("01".equals(month) || "02".equals(month) || "03".equals(month)) {
month = "06";
} else if ("04".equals(month) || "05".equals(month) || "06".equals(month)) {
month = "09";
} else if ("07".equals(month) || "08".equals(month) || "09".equals(month)) {
month = "12";
} else if ("10".equals(month) || "11".equals(month) || "12".equals(month)) {
month = "03";
Integer year = Integer.parseInt(yy);
year += 1;
yy = year.toString();
}
String ymd = yy + "-" + month + "-" + dd;
return getEndDateOfMonth(ymd);
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:00:18
* @Title stratTime
* @param date
* @param unionMinute
* @return String 格式_HH:mm:ss.0000 _代表空格
* @category 取当前的时间偏移时间的时分秒 与endTime成对使用
*/
public static String stratTime(Calendar date, int unionMinute) {
SimpleDateFormat formatter = new SimpleDateFormat(" HH:mm:ss");
date.add(Calendar.MINUTE, unionMinute);
return formatter.format(date.getTime()) + ".0000";
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:00:43
* @Title endTime
* @param date
* @return String 格式_HH:mm:ss.999999 _代表空格
* @category 取当前的时间的时分秒 与startTime成对使用
*
*/
public static String endTime(Calendar date) {
SimpleDateFormat formatter = new SimpleDateFormat(" HH:mm:ss");
return formatter.format(date.getTime()) + ".999999";
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:01:10
* @Title getMonthDay
* @param dat
* @return int 返回类型
* @category 获得指定月的天数
*/
public static int getMonthDay(String dat) {
String month = dat.substring(5, 7);
int monthDay = 0;
int mon = Integer.parseInt(month);
if (mon == 1 || mon == 3 || mon == 5 || mon == 7 || mon == 8 || mon == 10 || mon == 12) {
monthDay = 31;
} else if (mon == 4 || mon == 6 || mon == 9 || mon == 11) {
monthDay = 30;
} else {
if (isLeapYear(dat)) {
monthDay = 29;
} else {
monthDay = 28;
}
}
return monthDay;
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:01:22
* @Title getMonthWeek
* @param year
* @param month
* @return int 返回类型
* @category 得到指定月的周数
*/
public static int getMonthWeek(String year, String month) {
String getFirst = year + "-" + month + "-01";
int monthDay = getMonthDay(getFirst); // 这个月有几天
int firstWeek = getWeekNum(getFirst); // 第一天星期几
int firsWeekDay = 6 - firstWeek + 1; // 第二周开始日期
int i = firsWeekDay;
int monthWeek = 1; // 一个月有几周
while (i < monthDay) {
i = i + 7;
monthWeek++;
}
return monthWeek;
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:01:34
* @Title getWeekByDay
* @param sdate
* @return int 返回类型
* @category 根据日期得到是这个月的第几周
*/
public static int getWeekByDay(String sdate) {
String getFirst = getFirstDateOfMonth(sdate);
int firstWeek = getWeekNum(getFirst); // 第一天星期几
int firsWeekDay = 7 - firstWeek; // 第一周有几天
int td = Integer.valueOf(sdate.substring(8, 10)); // 这天是这个月的第几天
if (td - firsWeekDay <= 0) {
return 1;
} else {
int a = td - firsWeekDay;
a = a / 7 + (a % 7 == 0 ? 0 : 1);
return a + 1;
}
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:01:48
* @Title getWeekDat
* @param year
* @param month
* @param week
* @return String[] 返回类型
* @category 得到指定年月周的日期第一天和最后一天
*/
public static String[] getWeekDat(String year, String month, int week) {
String[] re = new String[2];
String firstDay = year + "-" + month + "-01";
int monthDay = getMonthDay(firstDay);
int firstWeekEnd = 6 - getWeekNum(firstDay) + 1;
if (week == 1) {
re[0] = firstDay;
re[1] = year + "-" + month + "-0" + firstWeekEnd;
} else {
int startWeek = firstWeekEnd + 1 + (week - 2) * 7;
int endWeek = startWeek + 6; // 第几天
String start = startWeek + "";
if (start.length() <= 1) {
start = "0" + start;
}
if (endWeek > monthDay) {
endWeek = monthDay;
}
String end = endWeek + "";
if (end.length() <= 1) {
end = "0" + end;
}
re[0] = year + "-" + month + "-" + start;
re[1] = year + "-" + month + "-" + end;
}
return re;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:35:45
* @Title getRandom
* @param i 生成的随机数有几位
* @return String 返回类型
* @category 返回一个随机数
*/
public static String getRandom(int i) {
Random jjj = new Random();
if (i == 0)
return "";
String jj = "";
for (int k = 0; k < i; k++) {
jj = jj + jjj.nextInt(9);
}
return jj;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:44:10
* @Title buildRandom
* @param length
* @return int 返回类型
* @category 取出一个指定长度大小的随机正整数.
*/
public static int buildRandom(int length) {
int num = 1;
double random = Math.random();
if (random < 0.1) {
random = random + 0.1;
}
for (int i = 0; i < length; i++) {
num = num * 10;
}
return (int) ((random * num));
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:09:57
* @Title getStrRandom
* @param j
* @return String 返回类型
* @category 获取大写字母随机数
*/
public static String getStrRandom(int j){
String s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] c = s.toCharArray();
Random random = new Random();
String ss="";
for( int i = 0; i < j; i ++) {
ss=ss+c[random.nextInt(c.length)];
}
return ss;
}
/**
*
* @author Meteor
* @Cdate 2015年8月9日 下午2:34:09
* @Title getUUID
* @return String 返回类型
* @category 生成随机的且不重复的id(重复几率很小)
*/
public static String getUUID(){
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
return uuid;
}
/**
*
* @author Meteor
* @Cdate 2015年8月10日 上午12:13:51
* @Title pageTimeFormat
* @param date
* @return String 返回类型
* @category 格式化web页面显示时间样式
*/
public static String pageTimeFormat(String date){
String timeout="";
String nowdate=getStringDate();
int days=Integer.valueOf(getTwoDay(nowdate, date));
if(days<=6){
if(days==0){
timeout=getFormatDate("HH:mm:ss",date);
}else{
timeout=days+"天前";
}
}else{
if(days/7<=4 || days<=30){
timeout=days/7+"周前";
}else{
timeout=days/30+"月前";
}
}
return timeout;
}
/**
* 测试使用,计算方法执行时间
*/
private long bgtime=0;
public void getbgtime(){
bgtime=new Date().getTime();
}
public void getedtime(String name){
long edtime=new Date().getTime();
System.out.println(name+"方法执行时间:"+(edtime-bgtime)+"毫秒");
bgtime=0;
}
public long getedtimenoout(){
long edtime=new Date().getTime();
edtime=(edtime-bgtime)/1000+1;
bgtime=0;
return edtime;
}
public static String getTimeOff(long time){
long c=time;
SimpleDateFormat format =null;
Date d=new Date(c);
c=c/1000;
if(c<60)
format = new SimpleDateFormat("s秒");
else if(c<3600)
format = new SimpleDateFormat("mm:ss");
else if(c<86400)
format = new SimpleDateFormat("HH:mm:ss");
else
format = new SimpleDateFormat("d天 HH:mm:ss");
d.setHours(d.getHours()-1);
format.setTimeZone(TimeZone.getTimeZone("GMT-23"));
return format.format(d);
}
public static String getTimeOff(long timeed,long timebg){
long c=timeed-timebg;
return getTimeOff(c);
}
/**
* 得到文件修改时间
* @param filepath
* @return
*/
public static String getRealtime(String filepath){
File file = new File(filepath);
//毫秒数
long modifiedTime = file.lastModified();
//通过毫秒数构造日期 即可将毫秒数转换为日期
Date d = new Date(modifiedTime);
String shorttime=DateKit.Date2Str(d, "yyyy-MM-dd HH:mm:ss");
//System.out.println(shorttime);
return shorttime;
}
} | justlikemaki/KanPianManager | src/com/meteor/kit/DateKit.java |
66,189 | package org.bigmouth.nvwa.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.lang.StringUtils;
public class DateUtils {
public static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
public static String LONG_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
public static String NUMBER_DATE_FORMAT = "yyyyMMddHHmm";
public static String LONG_DATE_FORMAT_MINUTE = "yyyy-MM-dd HH:mm";
public static String YYYYMMDD = "yyyyMMdd";
/**
* 取得当前日期
*
* @return Date 当前日期
*/
public static Date getCurrentDate() {
return new Date(System.currentTimeMillis());
}
/**
* 返回当前日期对应的默认格式的字符串
*
* @return String 当前日期对应的字符串
*/
public static String getCurrentStringDate() {
return convertDate2String(getCurrentDate(), DEFAULT_DATE_FORMAT);
}
public static String getCurrentFirstDate() {
String date = getCurrentStringDate();
return date.substring(0, 8) + "01";
}
/**
* 返回当前日期对应的指定格式的字符串
*
* @param dateFormat - 日期格式
* @return String 当前日期对应的字符串
*/
public static String getCurrentStringDate(String dateFormat) {
return convertDate2String(getCurrentDate(), dateFormat);
}
/**
* 将日期转换成指定格式的字符串
*
* @param date - 要转换的日期
* @param dateFormat - 日期格式
* @return String 日期对应的字符串
*/
public static String convertDate2String(Date date, String dateFormat) {
if (date == null)
return "";
SimpleDateFormat sdf = null;
if (dateFormat != null && !dateFormat.equals("")) {
try {
sdf = new SimpleDateFormat(dateFormat);
}
catch (Exception e) {
// e.printStackTrace();
sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
}
else {
sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
return sdf.format(date);
}
/**
* 将日期转换成指定格式的字符串
*
* @param date - 要转换的日期
* @param dateFormat - 日期格式
* @return String 日期对应的字符串
*/
public static String convertDate2String(Date date) {
if (date == null)
return null;
SimpleDateFormat sdf = null;
sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
return sdf.format(date);
}
/**
* 将字符串转换成日期
*
* @param stringDate - 要转换的字符串格式的日期
* @return Date 字符串对应的日期
*/
public static Date convertString2Date(String stringDate) {
return convertString2Date(stringDate, DEFAULT_DATE_FORMAT);
}
/**
* 将字符串转换成日期
*
* @param stringDate - 要转换的字符串格式的日期
* @param dateFormat - 要转换的字符串对应的日期格式
* @return Date 字符串对应的日期
*/
public static Date convertString2Date(String stringDate, String dateFormat) {
if (StringUtils.isEmpty(stringDate)) {
return null;
}
SimpleDateFormat sdf = null;
if (dateFormat != null && !dateFormat.equals("")) {
try {
sdf = new SimpleDateFormat(dateFormat);
}
catch (Exception e) {
e.printStackTrace();
sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
}
else {
sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}
try {
return sdf.parse(stringDate);
}
catch (ParseException pe) {
pe.printStackTrace();
return new Date(System.currentTimeMillis());
}
}
/**
* 将一种格式的日期字符串转换成默认格式的日期字符串
*
* @param oldDate - 要格式化的日期字符串
* @param oldFormat - 要格式化的日期的格式
* @return String 格式化后的日期字符串
*/
public static String formatStringDate(String oldStringDate, String oldFormat) {
return convertDate2String(convertString2Date(oldStringDate, oldFormat), DEFAULT_DATE_FORMAT);
}
/**
* 将一种格式的日期字符串转换成另一种格式的日期字符串
*
* @param oldDate - 要格式化的日期字符串
* @param oldFormat - 要格式化的日期的格式
* @param newFormat - 格式化后的日期的格式
* @return String 格式化后的日期字符串
*/
public static String formatStringDate(String oldStringDate, String oldFormat, String newFormat) {
return convertDate2String(convertString2Date(oldStringDate, oldFormat), newFormat);
}
/**
* 根据年份和月份判断该月有几天
*
* @param year - 年份
* @param month - 月份
* @return int
*/
public static int days(int year, int month) {
int total = 30;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
total = 31;
break;
case 2:
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
total = 29;
else
total = 28;
break;
default:
break;
}
return total;
}
public static String getCurrDateByMonth(String date) {
int day = days(Integer.parseInt(date.substring(0, 4)), Integer.parseInt(date.substring(5, 7)));
return date + "-" + day;
}
/**
* 根据年份和月份判断该月的第一天是星期几
*
* @param year - 年份
* @param month - 月份
* @return int
*/
@SuppressWarnings("deprecation")
public static int firstDayOfWeek(int year, int month) {
Date firstDate = new Date(year - 1900, month - 1, 1);
return firstDate.getDay();
}
/**
* 根据年份和月份判断该月的最后一天是星期几
*
* @param year - 年份
* @param month - 月份
* @return int
*/
@SuppressWarnings("deprecation")
public static int lastDayOfWeek(int year, int month) {
Date lastDate = new Date(year - 1900, month - 1, days(year, month));
return lastDate.getDay();
}
/**
* 给定一个日期,返回是一周中的第几天 星期日为每周的第一天,星期六为每周的最后一天
* */
public static int dayOfWeek(Date date) {
// 首先定义一个calendar,必须使用getInstance()进行实例化
Calendar aCalendar = Calendar.getInstance();
// 里面野可以直接插入date类型
aCalendar.setTime(date);
// 计算此日期是一周中的哪一天
int x = aCalendar.get(Calendar.DAY_OF_WEEK);
return x;
}
/**
* 获取当前年份
*
* @return int
*/
@SuppressWarnings("deprecation")
public static int getCurrentYear() {
return getCurrentDate().getYear() + 1900;
}
/**
* 获取当前月份(1-12)
*
* @return int
*/
@SuppressWarnings("deprecation")
public static int getCurrentMonth() {
return getCurrentDate().getMonth();
}
@SuppressWarnings("deprecation")
public static String getCurrentMonthFormat() {
int i = getCurrentDate().getMonth() + 1;
if (i < 10) {
return "0" + i;
}
return String.valueOf(i);
}
public static String getCurrentMonth2String() {
String str = getCurrentStringDate();
return str.substring(0, 7) + "-01";
}
@SuppressWarnings("deprecation")
public static int getMonth(int i) {
return getCurrentDate().getMonth();
}
public static int getWeek(Date d) {
java.util.Date lastweek = d;
Calendar c = Calendar.getInstance();
c.setTime(lastweek);
return c.get(Calendar.WEEK_OF_YEAR);
}
/**
* 获取给定日期的下一个月的日期,返回格式为yyyy-MM-dd
*
* @param dateStr - 给定日期
* @param format - 给定日期的格式
* @return String
*/
@SuppressWarnings("deprecation")
public static String getNextMonth(String stringDate, String format) {
Date date = convertString2Date(stringDate, format);
int year = date.getYear() + 1900;
int month = date.getMonth() + 1;
if (month == 12) {
year = year + 1;
month = 1;
}
else {
month = month + 1;
}
return year + "-" + (month < 10 ? "0" : "") + month + "-01";
}
/**
* 获取给定日期的下一个月的日期,返回格式为yyyy-MM-dd
*
* @param dateStr - 给定日期
* @return String
*/
public static String getNextMonth(String stringDate) {
return getNextMonth(stringDate, DEFAULT_DATE_FORMAT);
}
/**
* 获取给定日期的前一天
*
* @param stringDate - 给定日期
* @param format - 给定日期的格式
* @return String
*/
@SuppressWarnings("deprecation")
public static String getBeforDate(String stringDate, String format) {
Date date = convertString2Date(stringDate, format);
int year = date.getYear() + 1900;
int month = date.getMonth() + 1;
int day = date.getDate();
if (day == 1) {
if (month == 1) {
return (year - 1) + "-12-31";
}
else {
month = month - 1;
day = days(year, month);
return year + "-" + (month < 10 ? "0" : "") + month + "-" + day;
}
}
else {
return year + "-" + (month < 10 ? "0" : "") + month + "-" + (day < 11 ? "0" : "") + (day - 1);
}
}
/**
* 获取给定日期的前一天
*
* @param stringDate - 给定日期
* @return String
*/
public static String getBeforDate(String stringDate) {
return getBeforDate(stringDate, DEFAULT_DATE_FORMAT);
}
/**
* 得到当前日期的前后日期 +为后 -为前
*
* @param day_i
* @return
*/
public static final String getBefDateString(String currentDate, int day_i, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(currentDate);
Calendar day = Calendar.getInstance();
day.setTime(date);
day.add(Calendar.DATE, day_i);
return sdf.format(day.getTime());
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static final String getBefDateString(String currentDate, int day_i) {
return getBefDateString(currentDate, day_i, DEFAULT_DATE_FORMAT);
}
public static String getCurrWeek() {
Calendar c = Calendar.getInstance();
int w = c.get(Calendar.WEEK_OF_YEAR);
if (w < 10) {
return "0" + w;
}
return String.valueOf(w);
}
/**
* 得到一个月的天数
*/
public static int getMonthDays(String dt) {
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(dt.substring(0, 4)), Integer.parseInt(dt.substring(5, 7)) - 1, 1);
int num = c.getActualMaximum(Calendar.DAY_OF_MONTH);
return num;
}
/**
* 得到一个月的天数
*/
@SuppressWarnings("static-access")
public static int getMonthDays(String dt, String format) {
try {
if (dt == null) {
throw new NullPointerException("日期参数为null");
}
else {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = sdf.parse(dt);
Calendar cld = Calendar.getInstance();
cld.setTime(date);
return cld.getActualMaximum(cld.DAY_OF_MONTH);
}
}
catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 得到当前日期的星期
*
* @param date
* @return
*/
@SuppressWarnings("deprecation")
public static final String getDateWeek(String currentDate) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Date date = sdf.parse(currentDate);
Integer i = date.getDay();
if (i == 0)
i = 7;
return i.toString();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static final char[] zeroArray = "0000000000".toCharArray();
/**
* 得到指定长度格式的字符串 ‘000000123456789’
*
* @param string
* @param length
* @return
*/
public static final String zeroPadString(String string, int length) {
if (string == null || string.length() > length) {
return string;
}
StringBuilder buf = new StringBuilder(length);
buf.append(zeroArray, 0, length - string.length()).append(string);
return buf.toString();
}
/** 得到这个月的第一天 **/
public static Date getMonthFirstDay(Date date) {
String strdate = convertDate2String(date);
strdate = strdate.substring(0, 8) + "01";
return convertString2Date(strdate);
}
/**
* 得到这个月的第一天 2009-08-01
* **/
public static String getMonthFirstDay2String() {
String strdate = convertDate2String(new Date());
strdate = strdate.substring(0, 4) + "-" + strdate.substring(5, 7) + "-01";
return strdate;
}
/** 秒数转化为小时格式 HH:MM:SS **/
public static String convertSecToHour(int sec) {
String time = "";
int hour = 0;
int minute = 0;
int second = 0;
hour = sec / 3600 > 0 ? sec / 3600 : 0;
minute = (sec - hour * 3600) / 60 > 0 ? (sec - hour * 3600) / 60 : 0;
second = sec - hour * 3600 - minute * 60 > 0 ? sec - hour * 3600 - minute * 60 : 0;
String shour = String.valueOf(hour).length() < 2 ? "0" + String.valueOf(hour) : String.valueOf(hour);
String sminute = String.valueOf(minute).length() < 2 ? "0" + String.valueOf(minute) : String.valueOf(minute);
String ssecond = String.valueOf(second).length() < 2 ? "0" + String.valueOf(second) : String.valueOf(second);
time = shour + ":" + sminute + ":" + ssecond;
return time;
}
/**
* Formats a Date as a fifteen character long String made up of the Date's padded millisecond value.
*/
public static final String dateToMillis(Date date) {
return zeroPadString(Long.toString(date.getTime()), 15);
}
public static final Date millisToDate(String stime) {
long time = Long.parseLong(stime);
return new Date(time);
}
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sFullFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static final String DATE_SEPARATOR = "-/";
/** 作日期分析之用 */
static StringTokenizer sToken;
/** 将日期变为字符串格式 * */
public String format(GregorianCalendar pCal) {
return sDateFormat.format(pCal.getTime());
}
public String format(Date pDate) {
return sDateFormat.format(pDate);
}
public String fullFormat(Date pDate) {
return sFullFormat.format(pDate);
}
/** 将字符串格式的日期转换为Calender* */
public static GregorianCalendar parse2Cal(String pDateStr) {
sToken = new StringTokenizer(pDateStr, DATE_SEPARATOR);
int vYear = Integer.parseInt(sToken.nextToken());
// GregorianCalendar的月份是从0开始算起的,变态!!
int vMonth = Integer.parseInt(sToken.nextToken()) - 1;
int vDayOfMonth = Integer.parseInt(sToken.nextToken());
return new GregorianCalendar(vYear, vMonth, vDayOfMonth);
}
/** 将字符串类型的日期(yyyy-MM-dd)转换成Date* */
public Date parse2Date(String pDate) {
try {
return sDateFormat.parse(pDate);
}
catch (ParseException ex) {
return null;
}
}
/** 给定两个时间相差的月数,String版* */
public static int monthsBetween(String pFormerStr, String pLatterStr) {
GregorianCalendar vFormer = parse2Cal(pFormerStr);
GregorianCalendar vLatter = parse2Cal(pLatterStr);
return monthsBetween(vFormer, vLatter);
}
@SuppressWarnings("static-access")
public static int monthsBetween(GregorianCalendar pFormer, GregorianCalendar pLatter) {
GregorianCalendar vFormer = pFormer, vLatter = pLatter;
boolean vPositive = true;
if (pFormer.before(pLatter)) {
vFormer = pFormer;
vLatter = pLatter;
}
else {
vFormer = pLatter;
vLatter = pFormer;
vPositive = false;
}
int vCounter = 0;
while (vFormer.get(vFormer.YEAR) != vLatter.get(vLatter.YEAR)
|| vFormer.get(vFormer.MONTH) != vLatter.get(vLatter.MONTH)) {
vFormer.add(Calendar.MONTH, 1);
vCounter++;
}
if (vPositive)
return vCounter;
else
return -vCounter;
}
// 年,月,日
public static int[] getYMD(String str) {
int re[] = null;
if (str.length() >= 10) {
re = new int[3];
re[0] = Integer.parseInt(str.substring(0, 4));
re[1] = Integer.parseInt(str.substring(5, 7));
re[2] = Integer.parseInt(str.substring(8, 10));
}
else if (str.length() >= 7) {
re = new int[2];
re[0] = Integer.parseInt(str.substring(0, 4));
re[1] = Integer.parseInt(str.substring(5, 7));
}
if (str.length() == 4) {
re = new int[1];
re[0] = Integer.parseInt(str.substring(0, 4));
}
return re;
}
@SuppressWarnings("deprecation")
public static String getPreMonth(String stringDate, String format) {
Date date = convertString2Date(stringDate, format);
int year = date.getYear() + 1900;
int month = date.getMonth() + 1;
if (month == 1) {
year = year - 1;
month = 12;
}
else {
month = month - 1;
}
return year + "-" + (month < 10 ? "0" : "") + month;
}
@SuppressWarnings("deprecation")
public static String getNowMonth() {
Date date = new Date();
int year = date.getYear() + 1900;
int month = date.getMonth() + 1;
return year + "-" + (month < 10 ? "0" : "") + month;
}
public static long getRuntime(long begintime) {
return ((System.currentTimeMillis() - begintime)) / 1000;
}
public static long getRuntimeMin(long begintime) {
return ((System.currentTimeMillis() - begintime)) / 60000;
}
public static String getCurrentYMD() {
return getCurrentStringDate().substring(0, 7) + "-01";
}
/**
* 获取工单完成时间 取最大的时间
*
* */
public static Date getMaxDate(List<Date> datelist) {
if (datelist != null && datelist.size() > 0) {
Date darray[] = new Date[datelist.size()];
for (int i = 0; i < datelist.size(); i++) {
darray[i] = datelist.get(i);
}
Date maxDate = darray[0];
for (int i = 0; i < darray.length; i++) {
if (darray[i] != null && maxDate != null && (darray[i].getTime() > maxDate.getTime()))
maxDate = darray[i];
}
return maxDate;
}
else
return null;
}
/**
* 工作日
* */
public static int workDays(Date d1, Date d2) {
Date d = d1.before(d2) ? d1 : d2;
Calendar cal = Calendar.getInstance();
cal.setTime(d);
int count = 0;
while (!d.after(d2)) {
int day = cal.get(Calendar.DAY_OF_WEEK);
if (day < 7 && day > 1)
count++;
cal.add(Calendar.DATE, 1);
d = cal.getTime();
}
return count;
}
/**
* 获取当前时间所在的周的第一天是哪一天。
*
*
* */
public static String getFirstWeekDay() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return (convertDate2String(cal.getTime()));
}
/**
* get the next day with date and given increment
*
* @param date
* @param incr
* @return
*/
public static Date getNextDay(Date date, int incr) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DATE, incr);
return new Date(calendar.getTimeInMillis());
}
public static Date getMinimumTimeOfMonth(Date date) {
checkNullDate(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int minimumDay = cal.getActualMinimum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, minimumDay);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
public static Date getMaximumTimeOfMonth(Date date) {
checkNullDate(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int maximumDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
cal.set(Calendar.DAY_OF_MONTH, maximumDay);
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
return cal.getTime();
}
public static Date getMinimumTimeOfQuarter(Date date) {
checkNullDate(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int quarter = (month / 3) + 1;
int minMonth = (quarter * 3) - 3;
cal.set(Calendar.MONTH, minMonth);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
private static void checkNullDate(Date date) {
if (null == date)
throw new NullPointerException("date");
}
public static Date getMaximumTimeOfQuarter(Date date) {
checkNullDate(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int month = cal.get(Calendar.MONTH);
int quarter = (month / 3) + 1;
int minMonth = (quarter * 3) - 1;
cal.set(Calendar.MONTH, minMonth);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
return cal.getTime();
}
public static Date getMinimumTimeOfYear(Date date) {
checkNullDate(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.MONTH, cal.getActualMinimum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMinimum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
return cal.getTime();
}
public static Date getMaximumTimeOfYear(Date date) {
checkNullDate(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.MONTH, cal.getActualMaximum(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
cal.set(Calendar.HOUR_OF_DAY, cal.getActualMaximum(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, cal.getActualMaximum(Calendar.MINUTE));
cal.set(Calendar.SECOND, cal.getActualMaximum(Calendar.SECOND));
return cal.getTime();
}
}
| big-mouth-cn/nvwa | nvwa-utils/src/main/java/org/bigmouth/nvwa/utils/DateUtils.java |
66,190 | /*
* Copyright 2024 SpCo
*
* 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
*
* 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 top.spco.service.command.commands;
import top.spco.api.Bot;
import top.spco.api.Interactive;
import top.spco.api.User;
import top.spco.api.message.Message;
import top.spco.service.command.AbstractCommand;
import top.spco.service.command.CommandMarker;
import top.spco.service.command.CommandMeta;
import top.spco.service.command.usage.Usage;
import top.spco.service.command.usage.UsageBuilder;
import top.spco.service.command.usage.parameters.StringParameter;
import top.spco.user.BotUser;
import top.spco.util.HashUtils;
import top.spco.util.TimeUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;
import java.util.*;
/**
* @author SpCo
* @version 3.0.0
* @since 0.1.0
*/
@CommandMarker
public class DivineCommand extends AbstractCommand {
@Override
public String[] getLabels() {
return new String[]{"divine"};
}
@Override
public String getDescriptions() {
return "占卜";
}
@Override
public List<Usage> getUsages() {
return List.of(new UsageBuilder(getLabels()[0], getDescriptions()).add(new StringParameter("所求事件", true, null, StringParameter.StringType.GREEDY_PHRASE)).build());
}
@Override
public void onCommand(Bot<?> bot, Interactive<?> from, User<?> sender, BotUser user, Message<?> message, int time, CommandMeta meta, String usageName) {
if (usageName.equals("占卜")) {
LocalDate today = TimeUtils.today();
try {
BigDecimal hundred = new BigDecimal("100.00");
StringBuilder sb = new StringBuilder();
sb.append("你好,").append(user.getId()).append("\n");
String event = (String) meta.getParams().get("所求事件");
if (event == null) {
BigDecimal probability = getProbability(user.getId() + "在" + today);
String fortune = getFortune(probability.doubleValue());
sb.append("汝的今日运势:").append(fortune).append("\n");
if (fortune.equals("大凶") || fortune.equals("凶")) {
sb.append("汝今天倒大霉概率是 ").append(probability).append("%");
} else {
sb.append("汝今天行大运概率是 ").append(hundred.subtract(probability)).append("%");
}
} else {
sb.append("所求事项:").append(event).append("\n");
if (isHentai(event)) {
if (randomBoolean(user.getId() + "在" + today + "做" + event)) {
sb.append("结果:").append("好变态哦!").append("\n");
} else {
sb.append("结果:").append("变态!").append("\n");
}
if (randomBoolean(user.getId() + "在" + today + "做2" + event)) {
sb.append("此事有 ").append("0.00").append("% 的概率不发生");
} else {
sb.append("此事有 ").append("100.00").append("% 的概率发生");
}
} else {
BigDecimal probability = getProbability(user.getId() + "在" + today + "做" + event);
String fortune = getFortune(probability.doubleValue());
sb.append("结果:").append(fortune).append("\n");
if (fortune.equals("大凶") || fortune.equals("凶")) {
sb.append("此事有 ").append(probability).append("% 的概率不发生");
} else {
sb.append("此事有 ").append(hundred.subtract(probability)).append("% 的概率发生");
}
}
}
from.quoteReply(message, sb.toString());
} catch (NoSuchAlgorithmException e) {
from.quoteReply(message, "[错误发生] 占卜失败,占卜师说:" + e.getMessage());
}
}
}
/**
* 获取倒大霉的概率
*/
private BigDecimal getProbability(String seed) throws NoSuchAlgorithmException {
// 将种子进行 SHA-256 加密
MessageDigest sha256Digest = MessageDigest.getInstance("SHA-256");
byte[] inputBytes = seed.getBytes();
byte[] hashBytes = sha256Digest.digest(inputBytes);
// 将加密结果作为种子
Random random = new Random();
random.setSeed(Arrays.hashCode(hashBytes));
BigDecimal bigDecimal = BigDecimal.valueOf(random.nextDouble() * 100.00);
return bigDecimal.setScale(2, RoundingMode.HALF_UP);
}
private boolean randomBoolean(String seed) throws NoSuchAlgorithmException {
seed = HashUtils.sha256(seed);
return new Random(seed.hashCode()).nextBoolean();
}
private String getFortune(double number) {
if (number >= 0.00 && number <= 20.00) {
return "大吉";
} else if (number > 20.00 && number <= 40.00) {
return "吉";
} else if (number > 40.00 && number <= 60.00) {
return "尚可";
} else if (number > 60.00 && number <= 80.00) {
return "凶";
} else if (number > 80.00 && number <= 100.00) {
return "大凶";
} else {
return "???";
}
}
private static boolean isHentai(String event) {
if (event.contains("手冲") || event.contains("帮我口") || event.contains("被超市")) {
return true;
}
Set<String> hentaiEvents = new HashSet<>();
hentaiEvents.add("说好变态哦");
hentaiEvents.add("说变态");
return hentaiEvents.contains(event);
}
} | SpCoGov/SpCoBot | src/main/java/top/spco/service/command/commands/DivineCommand.java |
66,191 | package 变态跳台阶;
/**
* 题目:
* <p>
* 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。
* 求该青蛙跳上一个n级的台阶总共有多少种跳法。
* <p>
* 第n阶可以从n-1阶到第1阶跳上来,也可以直接从第0阶跳到第n阶
* f(n) = f(n - 1) + f(n - 2) + ... + f(2) + f(1) + 1
* f(n - 1) = f(n - 2) + ... + f(2) + f(1) + 1
* f(n) = 2 * f(n - 1)
* f(n) = pow(2, n - 1)
*/
public class Solution {
public int JumpFloorII(int target) {
if (target <= 0) {
return 0;
}
return (int) Math.pow(2, target - 1);
}
} | lxhao/algorithm | 剑指offer/变态跳台阶/Solution.java |