file_id
stringlengths 5
8
| content
stringlengths 131
14.4k
| repo
stringlengths 9
59
| path
stringlengths 8
120
| token_length
int64 36
3.49k
| original_comment
stringlengths 5
791
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 135
14.3k
| excluded
float64 0
0
| file-tokens-Qwen/Qwen2-7B
int64 30
3.27k
| comment-tokens-Qwen/Qwen2-7B
int64 2
459
| file-tokens-bigcode/starcoder2-7b
int64 35
3.49k
| comment-tokens-bigcode/starcoder2-7b
int64 3
483
| file-tokens-google/codegemma-7b
int64 36
3.61k
| comment-tokens-google/codegemma-7b
int64 3
465
| file-tokens-ibm-granite/granite-8b-code-base
int64 35
3.49k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 3
483
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 44
4.13k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
592
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
66633_3 | package chapter08_05_Queue集合;
import java.util.*;
/**
* Description:
* 1.属于List接口实现类
* 2.实现Deque接口,可以被当成双端队列使用。因此也可以被当成栈来使用。
*
* 1.LinkedList、ArrayList、ArrayDeque实现机制完全不同
* ArrayList、ArrayDeque内部以数组形式保存集合元素,随机访问集合元素性能好
* LinkedList内部以链表保存集合元素,随机访问性能差,插入、删除元素性能出色,只改变指针所指向地址。
*
* 1.ArrayList.get()性能好
* 2.LinkedList,采用迭代器Iterator遍历性能好
*/
public class LinkedListTest
{
public static void main(String[] args)
{
LinkedList books = new LinkedList();
// 将字符串元素加入队列的尾部
books.offer("疯狂Java讲义");
// 将一个字符串元素加入栈的顶部
books.push("轻量级Java EE企业应用实战");
// 将字符串元素添加到队列的头部(相当于栈的顶部)
books.offerFirst("疯狂Android讲义");
// 以List的方式(按索引访问的方式)来遍历集合元素
for (int i = 0; i < books.size() ; i++ )
{
System.out.println("遍历中:" + books.get(i));
}
// 访问、并不删除栈顶的元素
System.out.println(books.peekFirst());
// 访问、并不删除队列的最后一个元素
System.out.println(books.peekLast());
// 将栈顶的元素弹出“栈”
System.out.println(books.pop());
// 下面输出将看到队列中第一个元素被删除
System.out.println(books);
// 访问、并删除队列的最后一个元素
System.out.println(books.pollLast());
// 下面输出:[轻量级Java EE企业应用实战]
System.out.println(books);
}
}
| 3792274/crazyJava3 | 第8章Java集合/chapter08_05_Queue集合/LinkedListTest.java | 501 | // 将字符串元素添加到队列的头部(相当于栈的顶部)
| line_comment | zh-cn | package chapter08_05_Queue集合;
import java.util.*;
/**
* Description:
* 1.属于List接口实现类
* 2.实现Deque接口,可以被当成双端队列使用。因此也可以被当成栈来使用。
*
* 1.LinkedList、ArrayList、ArrayDeque实现机制完全不同
* ArrayList、ArrayDeque内部以数组形式保存集合元素,随机访问集合元素性能好
* LinkedList内部以链表保存集合元素,随机访问性能差,插入、删除元素性能出色,只改变指针所指向地址。
*
* 1.ArrayList.get()性能好
* 2.LinkedList,采用迭代器Iterator遍历性能好
*/
public class LinkedListTest
{
public static void main(String[] args)
{
LinkedList books = new LinkedList();
// 将字符串元素加入队列的尾部
books.offer("疯狂Java讲义");
// 将一个字符串元素加入栈的顶部
books.push("轻量级Java EE企业应用实战");
// 将字 <SUF>
books.offerFirst("疯狂Android讲义");
// 以List的方式(按索引访问的方式)来遍历集合元素
for (int i = 0; i < books.size() ; i++ )
{
System.out.println("遍历中:" + books.get(i));
}
// 访问、并不删除栈顶的元素
System.out.println(books.peekFirst());
// 访问、并不删除队列的最后一个元素
System.out.println(books.peekLast());
// 将栈顶的元素弹出“栈”
System.out.println(books.pop());
// 下面输出将看到队列中第一个元素被删除
System.out.println(books);
// 访问、并删除队列的最后一个元素
System.out.println(books.pollLast());
// 下面输出:[轻量级Java EE企业应用实战]
System.out.println(books);
}
}
| 0 | 461 | 17 | 497 | 20 | 495 | 15 | 497 | 20 | 782 | 32 | false | false | false | false | false | true |
59062_0 | package com.hydrogen.mqtt.connector.msghandle.agv.handler;
import org.apache.mina.core.session.IoSession;
import com.hydrogen.mqtt.connector.car.House;
import com.hydrogen.mqtt.connector.msghandle.AGVMsgHandlerInterface;
import com.hydrogen.mqtt.connector.msghandle.AGVMsgInterface;
import com.hydrogen.mqtt.connector.msghandle.agv.AGVCar;
import com.hydrogen.mqtt.connector.msghandle.agv.msg.AGVBaseMsg;
import com.hydrogen.mqtt.connector.msghandle.agv.msg.AGVInfoRspMsg;
public abstract class AGVMsgHandler<T extends AGVBaseMsg> implements AGVMsgHandlerInterface{
@SuppressWarnings("unchecked")
@Override
public AGVMsgInterface process(AGVMsgInterface taskMsg, IoSession session) {
T msg = (T)taskMsg;
AGVInfoRspMsg rsp = new AGVInfoRspMsg(msg.getMsgseq());
AGVCar car = initCar(msg,session);
//改为异步操作车子
handler(msg,car);
return getCarInfo(rsp,car);
}
public abstract AGVBaseMsg handler(T italkmsg,AGVCar car);
public AGVCar initCar(AGVBaseMsg italkmsg,IoSession session) {
int carid = italkmsg.agvid();
if(carid!=0) {
session.setAttribute("carid", carid);
}
AGVCar car = (AGVCar)House.getCar(carid);
if(car!=null) {
return car;
}
car = new AGVCar();
car.setId(carid);
House.addCar(car);
car.init();
car.start();
return car;
}
public AGVInfoRspMsg getCarInfo(AGVInfoRspMsg rsp, AGVCar car) {
rsp.setStatus(car.getStatus());
rsp.setTaskComplete(car.getTaskComplete());
rsp.setTaskRedo(car.getTaskRedo());
rsp.setX(car.getX());
rsp.setY(car.getY());
rsp.setW(car.getW());
rsp.setOnTop(car.getOnTop());
rsp.setFlip(car.getFlip());
rsp.setHand(car.getHand());
rsp.setPower(car.getPower());
rsp.setSpeed(car.getSpeed());
rsp.setAlarmLength(car.getAlarmLength());
return rsp;
}
}
| 3dudu/simulatoragv | src/main/java/com/hydrogen/mqtt/connector/msghandle/agv/handler/AGVMsgHandler.java | 641 | //改为异步操作车子 | line_comment | zh-cn | package com.hydrogen.mqtt.connector.msghandle.agv.handler;
import org.apache.mina.core.session.IoSession;
import com.hydrogen.mqtt.connector.car.House;
import com.hydrogen.mqtt.connector.msghandle.AGVMsgHandlerInterface;
import com.hydrogen.mqtt.connector.msghandle.AGVMsgInterface;
import com.hydrogen.mqtt.connector.msghandle.agv.AGVCar;
import com.hydrogen.mqtt.connector.msghandle.agv.msg.AGVBaseMsg;
import com.hydrogen.mqtt.connector.msghandle.agv.msg.AGVInfoRspMsg;
public abstract class AGVMsgHandler<T extends AGVBaseMsg> implements AGVMsgHandlerInterface{
@SuppressWarnings("unchecked")
@Override
public AGVMsgInterface process(AGVMsgInterface taskMsg, IoSession session) {
T msg = (T)taskMsg;
AGVInfoRspMsg rsp = new AGVInfoRspMsg(msg.getMsgseq());
AGVCar car = initCar(msg,session);
//改为 <SUF>
handler(msg,car);
return getCarInfo(rsp,car);
}
public abstract AGVBaseMsg handler(T italkmsg,AGVCar car);
public AGVCar initCar(AGVBaseMsg italkmsg,IoSession session) {
int carid = italkmsg.agvid();
if(carid!=0) {
session.setAttribute("carid", carid);
}
AGVCar car = (AGVCar)House.getCar(carid);
if(car!=null) {
return car;
}
car = new AGVCar();
car.setId(carid);
House.addCar(car);
car.init();
car.start();
return car;
}
public AGVInfoRspMsg getCarInfo(AGVInfoRspMsg rsp, AGVCar car) {
rsp.setStatus(car.getStatus());
rsp.setTaskComplete(car.getTaskComplete());
rsp.setTaskRedo(car.getTaskRedo());
rsp.setX(car.getX());
rsp.setY(car.getY());
rsp.setW(car.getW());
rsp.setOnTop(car.getOnTop());
rsp.setFlip(car.getFlip());
rsp.setHand(car.getHand());
rsp.setPower(car.getPower());
rsp.setSpeed(car.getSpeed());
rsp.setAlarmLength(car.getAlarmLength());
return rsp;
}
}
| 0 | 534 | 6 | 641 | 7 | 634 | 5 | 641 | 7 | 756 | 15 | false | false | false | false | false | true |
33085_3 | package com.zhangfan.learn.classfile.attributeinfo;
//import com.sun.org.apache.bcel.internal.generic.Instruction;
import com.zhangfan.learn.UKind;
import com.zhangfan.learn.classfile.Count;
import com.zhangfan.learn.classfile.constant.ConstantInfo;
import com.zhangfan.learn.classfile.instruction.Instruction;
import com.zhangfan.learn.classfile.instruction.InstructionFactory;
import java.io.FileInputStream;
import java.util.stream.IntStream;
public class Code extends Attribute {
// Code出现在方法的属性集合表中
private Count maxStack; // 操作数栈深度的最大值。在方法执行的任意时刻,操作数栈都不会超过这个深度。
private Count maxLocals; // 局部变量所需的存储空间。在这里,max_local的单位是slot,slot是虚拟机为局部变量分配内存所使用的最小单位
/**
* code_length 和 code用来存储Java
* 源程序编译后生成的字节码指令。
* code_length 用来代表字节码的长度,
* code 是用于存储字节码指令的一系列字节流。
* 既然叫字节码指令,那么每个指令就是一个u1类型的单字节,当虚拟机读取到code中的一个字节码的时候,
* 就可以找到对应这个字节码代表的是什么指令,并且可以知道这条指令后面是否需要跟随参数,以及参数应当如何理解
* 我们知道一个u1数据结构的取值范围是0-255,也就是总共256条指令,目前,java虚拟机规范定义了其中约200条
* 对应的指令含义,编码与指令之间的对应关系可以啥表得知
* 既然
* ***/
private Count codeLength;
private Instruction[] codes; // 长度为codeLength
private Count exceptionTableLength;
private CodeException[] exceptionTable; // 长度为exceptionTableLength
private Count attributesCount;
private Attribute[] attributes;
public Code(FileInputStream fi, ConstantInfo[] constantPool) {
super(fi);
maxStack = new Count(fi);
maxLocals = new Count(fi);
codeLength = new Count(fi, UKind.U4);
codes = new Instruction[codeLength.getNum()];
// IntStream.range(0,codeLength.getNum()).forEach(i->
// codes[i] = InstructionFactory.getInstruction(fi)
// );
exceptionTableLength = new Count(fi);
exceptionTable = new CodeException[exceptionTableLength.getNum()];
IntStream.range(0, exceptionTableLength.getNum()).forEach(i->{
exceptionTable[i] = new CodeException(fi);
});
attributesCount = new Count(fi);
attributes = new Attribute[attributesCount.getNum()];
IntStream.range(0,attributesCount.getNum()).forEach(i->{
attributes[i] = Attribute.readAttribute(fi, constantPool);
});
}
}
| 413180794/JavaDecompiler | src/com/zhangfan/learn/classfile/attributeinfo/Code.java | 694 | // 局部变量所需的存储空间。在这里,max_local的单位是slot,slot是虚拟机为局部变量分配内存所使用的最小单位 | line_comment | zh-cn | package com.zhangfan.learn.classfile.attributeinfo;
//import com.sun.org.apache.bcel.internal.generic.Instruction;
import com.zhangfan.learn.UKind;
import com.zhangfan.learn.classfile.Count;
import com.zhangfan.learn.classfile.constant.ConstantInfo;
import com.zhangfan.learn.classfile.instruction.Instruction;
import com.zhangfan.learn.classfile.instruction.InstructionFactory;
import java.io.FileInputStream;
import java.util.stream.IntStream;
public class Code extends Attribute {
// Code出现在方法的属性集合表中
private Count maxStack; // 操作数栈深度的最大值。在方法执行的任意时刻,操作数栈都不会超过这个深度。
private Count maxLocals; // 局部 <SUF>
/**
* code_length 和 code用来存储Java
* 源程序编译后生成的字节码指令。
* code_length 用来代表字节码的长度,
* code 是用于存储字节码指令的一系列字节流。
* 既然叫字节码指令,那么每个指令就是一个u1类型的单字节,当虚拟机读取到code中的一个字节码的时候,
* 就可以找到对应这个字节码代表的是什么指令,并且可以知道这条指令后面是否需要跟随参数,以及参数应当如何理解
* 我们知道一个u1数据结构的取值范围是0-255,也就是总共256条指令,目前,java虚拟机规范定义了其中约200条
* 对应的指令含义,编码与指令之间的对应关系可以啥表得知
* 既然
* ***/
private Count codeLength;
private Instruction[] codes; // 长度为codeLength
private Count exceptionTableLength;
private CodeException[] exceptionTable; // 长度为exceptionTableLength
private Count attributesCount;
private Attribute[] attributes;
public Code(FileInputStream fi, ConstantInfo[] constantPool) {
super(fi);
maxStack = new Count(fi);
maxLocals = new Count(fi);
codeLength = new Count(fi, UKind.U4);
codes = new Instruction[codeLength.getNum()];
// IntStream.range(0,codeLength.getNum()).forEach(i->
// codes[i] = InstructionFactory.getInstruction(fi)
// );
exceptionTableLength = new Count(fi);
exceptionTable = new CodeException[exceptionTableLength.getNum()];
IntStream.range(0, exceptionTableLength.getNum()).forEach(i->{
exceptionTable[i] = new CodeException(fi);
});
attributesCount = new Count(fi);
attributes = new Attribute[attributesCount.getNum()];
IntStream.range(0,attributesCount.getNum()).forEach(i->{
attributes[i] = Attribute.readAttribute(fi, constantPool);
});
}
}
| 0 | 624 | 31 | 694 | 36 | 699 | 31 | 694 | 36 | 931 | 57 | false | false | false | false | false | true |
17583_23 | //傻瓜理解版
package GUI;
import Listener.*;
import ProjectViewer.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Vector;
public class GUI extends JFrame {
public static JFrame j1;//主窗口
public static Container c1;//主窗口的容器
public static Container pv1,pv2,pv3,pv4,pv5,pv6;//项目管理器的容器
public static JTextArea jt1;//写字区域
public static JList jlt1;//代码提示窗口
public static JList pvl1,pvl2,pvl3,pvl4,pvl5,pvl6;//项目管理器窗口栏
public static Vector vector1;//代码提示容器
public static Vector pvv1,pvv2,pvv3,pvv4,pvv5,pvv6;//项目管理器容器
public static JMenuBar jm1;//菜单栏
public static JMenu jmu1;//菜单容器
public static JMenuItem jmi1,jmi2,jmi3,jmi4;//仨菜单按钮
public static JTabbedPane jp1;//项目结构
public GUI(){
//给主窗口设置它的属性
j1=new JFrame("Mindustry Mod Maker");//创建新对象
j1.setLayout(null);//更改组件的排序(null是不自动排序)
j1.setSize(1500,800);//窗口大小
j1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//点击退出按钮的时候发生什么
c1=j1.getContentPane();//把c1这个容器设置成j1用的(容器是用来装组件的)
//菜单栏的设置
jm1=new JMenuBar();;
//下拉内容的设置
jmu1=new JMenu("选项");
jm1.add(jmu1);
//仨按钮
jmi1=new JMenuItem("保存");//保存
jmi1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
int i=jfc.showOpenDialog(getContentPane());
if(i==JFileChooser.APPROVE_OPTION){
File file=jfc.getSelectedFile();
try {
FileWriter f=new FileWriter(file);
f.write(jt1.getText());
f.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
jmi2=new JMenuItem("打开");
jmi2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
int i=jfc.showOpenDialog(getContentPane());
if(i==JFileChooser.APPROVE_OPTION) {
File file=jfc.getSelectedFile();
StringBuilder result = new StringBuilder();
try {
BufferedReader bf=new BufferedReader(new FileReader(file));
String s;
while((s = bf.readLine())!=null){
result.append(System.lineSeparator()+s);
}
bf.close();
jt1.setText(result.toString());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
jmi3=new JMenuItem("打开项目");
jmi3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProjectViewer pj=new ProjectViewer();
}
});
jmi4=new JMenuItem("项目管理器");
jmi4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProjectManagement pj=new ProjectManagement("项目管理器");
}
});
//
pv1=new Container();
pv2=new Container();
pv3=new Container();
pv4=new Container();
pv5=new Container();
pv6=new Container();
//
jmu1.add(jmi1);
jmu1.add(jmi2);
jmu1.add(jmi3);
jmu1.add(jmi4);
jmi2=new JMenuItem();//打开
//项目管理器
jp1=new JTabbedPane();
jp1.setBounds(0,300,300,300);
jp1.addTab("items",pv1);
jp1.addTab("liquids",pv2);
jp1.addTab("blocks",pv3);
jp1.addTab("mechs",pv4);
jp1.addTab("units",pv5);
jp1.addTab("scripts",pv6);
//
pvv1=new Vector();
pvv2=new Vector();
pvv3=new Vector();
pvv4=new Vector();
pvv5=new Vector();
pvv6=new Vector();
//
pvl1=new JList(pvv1);
pvl1.setSize(300,300);
pvl1.addListSelectionListener(new ItemProjectListener());
pvl2=new JList(pvv2);
pvl2.setSize(300,300);
pvl2.addListSelectionListener(new LiquidProjectListener());
pvl3=new JList(pvv3);
pvl3.setSize(300,300);
pvl3.addListSelectionListener(new BlockProjectListener());
pvl4=new JList(pvv4);
pvl4.setSize(300,300);
pvl4.addListSelectionListener(new MechProjectListener());
pvl5=new JList(pvv5);
pvl5.setSize(300,300);
pvl5.addListSelectionListener(new UnitProjectListener());
pvl6=new JList(pvv6);
pvl6.setSize(300,300);
pvl6.addListSelectionListener(new ScriptProjectListener());
//
pv1.add(pvl1);
pv2.add(pvl2);
pv3.add(pvl3);
pv4.add(pvl4);
pv5.add(pvl5);
pv6.add(pvl6);
c1.add(jp1);
// 给写字的地方设置属性
jt1=new JTextArea();
jt1.setBounds(325,25,750,700);
jt1.addKeyListener(new CodeLIstener());
c1.add(jt1);
//向量初始化
vector1=new Vector();
//代码提示
jlt1=new JList(vector1);
jlt1.addListSelectionListener(new ListLIstener());
jlt1.setBounds(0,0,300,300);
c1.add(jlt1);
j1.setJMenuBar(jm1);
j1.setVisible(true);//主窗口是否可见(放在最后免得刷新)
}
}
| 4156/MindustryModMaker | src/GUI/GUI.java | 1,667 | // 给写字的地方设置属性 | line_comment | zh-cn | //傻瓜理解版
package GUI;
import Listener.*;
import ProjectViewer.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Vector;
public class GUI extends JFrame {
public static JFrame j1;//主窗口
public static Container c1;//主窗口的容器
public static Container pv1,pv2,pv3,pv4,pv5,pv6;//项目管理器的容器
public static JTextArea jt1;//写字区域
public static JList jlt1;//代码提示窗口
public static JList pvl1,pvl2,pvl3,pvl4,pvl5,pvl6;//项目管理器窗口栏
public static Vector vector1;//代码提示容器
public static Vector pvv1,pvv2,pvv3,pvv4,pvv5,pvv6;//项目管理器容器
public static JMenuBar jm1;//菜单栏
public static JMenu jmu1;//菜单容器
public static JMenuItem jmi1,jmi2,jmi3,jmi4;//仨菜单按钮
public static JTabbedPane jp1;//项目结构
public GUI(){
//给主窗口设置它的属性
j1=new JFrame("Mindustry Mod Maker");//创建新对象
j1.setLayout(null);//更改组件的排序(null是不自动排序)
j1.setSize(1500,800);//窗口大小
j1.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//点击退出按钮的时候发生什么
c1=j1.getContentPane();//把c1这个容器设置成j1用的(容器是用来装组件的)
//菜单栏的设置
jm1=new JMenuBar();;
//下拉内容的设置
jmu1=new JMenu("选项");
jm1.add(jmu1);
//仨按钮
jmi1=new JMenuItem("保存");//保存
jmi1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
int i=jfc.showOpenDialog(getContentPane());
if(i==JFileChooser.APPROVE_OPTION){
File file=jfc.getSelectedFile();
try {
FileWriter f=new FileWriter(file);
f.write(jt1.getText());
f.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
jmi2=new JMenuItem("打开");
jmi2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
int i=jfc.showOpenDialog(getContentPane());
if(i==JFileChooser.APPROVE_OPTION) {
File file=jfc.getSelectedFile();
StringBuilder result = new StringBuilder();
try {
BufferedReader bf=new BufferedReader(new FileReader(file));
String s;
while((s = bf.readLine())!=null){
result.append(System.lineSeparator()+s);
}
bf.close();
jt1.setText(result.toString());
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
jmi3=new JMenuItem("打开项目");
jmi3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProjectViewer pj=new ProjectViewer();
}
});
jmi4=new JMenuItem("项目管理器");
jmi4.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ProjectManagement pj=new ProjectManagement("项目管理器");
}
});
//
pv1=new Container();
pv2=new Container();
pv3=new Container();
pv4=new Container();
pv5=new Container();
pv6=new Container();
//
jmu1.add(jmi1);
jmu1.add(jmi2);
jmu1.add(jmi3);
jmu1.add(jmi4);
jmi2=new JMenuItem();//打开
//项目管理器
jp1=new JTabbedPane();
jp1.setBounds(0,300,300,300);
jp1.addTab("items",pv1);
jp1.addTab("liquids",pv2);
jp1.addTab("blocks",pv3);
jp1.addTab("mechs",pv4);
jp1.addTab("units",pv5);
jp1.addTab("scripts",pv6);
//
pvv1=new Vector();
pvv2=new Vector();
pvv3=new Vector();
pvv4=new Vector();
pvv5=new Vector();
pvv6=new Vector();
//
pvl1=new JList(pvv1);
pvl1.setSize(300,300);
pvl1.addListSelectionListener(new ItemProjectListener());
pvl2=new JList(pvv2);
pvl2.setSize(300,300);
pvl2.addListSelectionListener(new LiquidProjectListener());
pvl3=new JList(pvv3);
pvl3.setSize(300,300);
pvl3.addListSelectionListener(new BlockProjectListener());
pvl4=new JList(pvv4);
pvl4.setSize(300,300);
pvl4.addListSelectionListener(new MechProjectListener());
pvl5=new JList(pvv5);
pvl5.setSize(300,300);
pvl5.addListSelectionListener(new UnitProjectListener());
pvl6=new JList(pvv6);
pvl6.setSize(300,300);
pvl6.addListSelectionListener(new ScriptProjectListener());
//
pv1.add(pvl1);
pv2.add(pvl2);
pv3.add(pvl3);
pv4.add(pvl4);
pv5.add(pvl5);
pv6.add(pvl6);
c1.add(jp1);
// 给写 <SUF>
jt1=new JTextArea();
jt1.setBounds(325,25,750,700);
jt1.addKeyListener(new CodeLIstener());
c1.add(jt1);
//向量初始化
vector1=new Vector();
//代码提示
jlt1=new JList(vector1);
jlt1.addListSelectionListener(new ListLIstener());
jlt1.setBounds(0,0,300,300);
c1.add(jlt1);
j1.setJMenuBar(jm1);
j1.setVisible(true);//主窗口是否可见(放在最后免得刷新)
}
}
| 0 | 1,445 | 7 | 1,667 | 9 | 1,754 | 7 | 1,667 | 9 | 2,150 | 12 | false | false | false | false | false | true |
43655_1 | package Models;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import main.Main;
//本类用于显示一个弹出提示窗口
public class WarningStage extends Stage {
private VBox pane;
private static Button OKbutton;
private static Text TextTitle, TextWarning, TextTips;
public WarningStage() {
super();
pane = new VBox();
pane.setSpacing(30);
TextTitle = new Text();
TextWarning = new Text();
TextTips = new Text();
//增加确认按钮
OKbutton = new Button("确认");
OKbutton.setMinSize(100, 50);
OKbutton.setCursor(Cursor.CLOSED_HAND);
//绑定按钮处理器
OKbutton.setOnAction(new ConfirmHandle(this));
//设置面板内容
TextWarning.setFill(Color.RED);
TextTitle.setFill(Color.RED);
TextWarning.setFont(Font.font(25));
pane.getChildren().add(TextWarning);
pane.getChildren().add(TextTips);
pane.getChildren().add(OKbutton);
pane.setAlignment(Pos.TOP_CENTER);
// 窗体属性设置
this.setResizable(false);
this.setScene(new Scene(pane, 400, 200));
this.getIcons().add(new Image(Main.class.getResourceAsStream("/resource/images/warning.png")));
/*阻止stage对象在隐藏时被系统关闭,防止产生空指针异常*/
this.setOnCloseRequest(e -> {
this.hide();
e.consume();
});
}
/*设置提示内容*/
public void setContents(String stagetitle, String warningText, String Tips) {
TextTitle.setText(stagetitle);
TextWarning.setText(warningText);
TextTips.setText(Tips);
this.setTitle(TextTitle.getText().toString());
this.centerOnScreen();
this.setAlwaysOnTop(true);
this.requestFocus();
this.show();
}
//关闭提示窗口
class ConfirmHandle implements EventHandler<ActionEvent> {
Stage closestag;
public ConfirmHandle(Stage stg) {
// TODO Auto-generated constructor stub
closestag = stg;
}
@Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
closestag.hide();
}
}
}
| 425868130/CpuDemo | src/Models/WarningStage.java | 636 | //增加确认按钮 | line_comment | zh-cn | package Models;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import main.Main;
//本类用于显示一个弹出提示窗口
public class WarningStage extends Stage {
private VBox pane;
private static Button OKbutton;
private static Text TextTitle, TextWarning, TextTips;
public WarningStage() {
super();
pane = new VBox();
pane.setSpacing(30);
TextTitle = new Text();
TextWarning = new Text();
TextTips = new Text();
//增加 <SUF>
OKbutton = new Button("确认");
OKbutton.setMinSize(100, 50);
OKbutton.setCursor(Cursor.CLOSED_HAND);
//绑定按钮处理器
OKbutton.setOnAction(new ConfirmHandle(this));
//设置面板内容
TextWarning.setFill(Color.RED);
TextTitle.setFill(Color.RED);
TextWarning.setFont(Font.font(25));
pane.getChildren().add(TextWarning);
pane.getChildren().add(TextTips);
pane.getChildren().add(OKbutton);
pane.setAlignment(Pos.TOP_CENTER);
// 窗体属性设置
this.setResizable(false);
this.setScene(new Scene(pane, 400, 200));
this.getIcons().add(new Image(Main.class.getResourceAsStream("/resource/images/warning.png")));
/*阻止stage对象在隐藏时被系统关闭,防止产生空指针异常*/
this.setOnCloseRequest(e -> {
this.hide();
e.consume();
});
}
/*设置提示内容*/
public void setContents(String stagetitle, String warningText, String Tips) {
TextTitle.setText(stagetitle);
TextWarning.setText(warningText);
TextTips.setText(Tips);
this.setTitle(TextTitle.getText().toString());
this.centerOnScreen();
this.setAlwaysOnTop(true);
this.requestFocus();
this.show();
}
//关闭提示窗口
class ConfirmHandle implements EventHandler<ActionEvent> {
Stage closestag;
public ConfirmHandle(Stage stg) {
// TODO Auto-generated constructor stub
closestag = stg;
}
@Override
public void handle(ActionEvent event) {
// TODO Auto-generated method stub
closestag.hide();
}
}
}
| 0 | 528 | 4 | 636 | 4 | 672 | 4 | 636 | 4 | 811 | 11 | false | false | false | false | false | true |
5540_5 | package yalong.site.frame.panel.client;
import lombok.extern.slf4j.Slf4j;
import yalong.site.frame.bo.ComponentBO;
import yalong.site.frame.bo.ItemBO;
import yalong.site.frame.panel.base.BaseComboBox;
import yalong.site.frame.panel.client.listener.GameStatusBoxItemListener;
import java.awt.*;
/**
* @author yaLong
*/
@Slf4j
public class GameStatusBox extends BaseComboBox<ItemBO> {
public GameStatusBox() {
this.setItems();
this.addItemListener(new GameStatusBoxItemListener());
}
/**
* @return 带布局的盒子
*/
public static ComponentBO builder() {
GameStatusBox box = new GameStatusBox();
GridBagConstraints grid = new GridBagConstraints(
// 第(0,3)个格子
0, 3,
// 占1列,占1行
1, 1,
//横向占100%长度,纵向占100%长度
2, 2,
//居中,组件小的话就两边铺满窗格
GridBagConstraints.CENTER, GridBagConstraints.NONE,
// 窗格之间的距离
new Insets(0, 0, 0, 0),
// 增加组件的首选宽度和高度
0, 0
);
return new ComponentBO(box, grid);
}
public void setItems() {
this.addItem(new ItemBO("chat", "在线"));
this.addItem(new ItemBO("away", "离开"));
this.addItem(new ItemBO("dnd", "游戏中"));
this.addItem(new ItemBO("offline", "离线"));
this.addItem(new ItemBO("mobile", "手机在线"));
}
}
| 4379711/lol-helper | src/main/java/yalong/site/frame/panel/client/GameStatusBox.java | 455 | //居中,组件小的话就两边铺满窗格 | line_comment | zh-cn | package yalong.site.frame.panel.client;
import lombok.extern.slf4j.Slf4j;
import yalong.site.frame.bo.ComponentBO;
import yalong.site.frame.bo.ItemBO;
import yalong.site.frame.panel.base.BaseComboBox;
import yalong.site.frame.panel.client.listener.GameStatusBoxItemListener;
import java.awt.*;
/**
* @author yaLong
*/
@Slf4j
public class GameStatusBox extends BaseComboBox<ItemBO> {
public GameStatusBox() {
this.setItems();
this.addItemListener(new GameStatusBoxItemListener());
}
/**
* @return 带布局的盒子
*/
public static ComponentBO builder() {
GameStatusBox box = new GameStatusBox();
GridBagConstraints grid = new GridBagConstraints(
// 第(0,3)个格子
0, 3,
// 占1列,占1行
1, 1,
//横向占100%长度,纵向占100%长度
2, 2,
//居中 <SUF>
GridBagConstraints.CENTER, GridBagConstraints.NONE,
// 窗格之间的距离
new Insets(0, 0, 0, 0),
// 增加组件的首选宽度和高度
0, 0
);
return new ComponentBO(box, grid);
}
public void setItems() {
this.addItem(new ItemBO("chat", "在线"));
this.addItem(new ItemBO("away", "离开"));
this.addItem(new ItemBO("dnd", "游戏中"));
this.addItem(new ItemBO("offline", "离线"));
this.addItem(new ItemBO("mobile", "手机在线"));
}
}
| 0 | 373 | 13 | 455 | 15 | 441 | 14 | 455 | 15 | 588 | 22 | false | false | false | false | false | true |
31311_29 | package com.alipush;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class PushUtils {
public static final String NotificationChannelId = "7777777";
private static String AliyunAppKey;
private static String AliyunAppSecret;
// 小米辅助通道
private static String XiaoMiAppId = "2882303761518018487";
private static String XiaoMiAppKey = "5371801843487";
// OPPO辅助通道
private static String OPPOAppKey = "7ac256813b8745928c2102c20dd49fde";
private static String OPPOAppSecret = "9b4ac44b4eee471097243658679910d1";
private SharedPreferences preference;
public PushUtils(Context context) {
this.preference = PreferenceManager.getDefaultSharedPreferences(context) ;
}
public static String getCurProcessName(Context context) {
int pid = android.os.Process.myPid();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
/**
* 获取推送配置信息
* @param applicationContext
*/
private static void getConfig(final Context applicationContext) throws PackageManager.NameNotFoundException {
ApplicationInfo appInfo = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA);
AliyunAppKey=appInfo.metaData.get("AliyunAppKey")+"";
AliyunAppSecret=appInfo.metaData.get("AliyunAppSecret")+"";
XiaoMiAppId =appInfo.metaData.get("XiaoMiAppId")+"";
XiaoMiAppKey=appInfo.metaData.get("XiaoMiAppKey")+"";
OPPOAppKey = appInfo.metaData.get("OPPOAppKey")+"";
OPPOAppSecret=appInfo.metaData.get("OPPOAppSecret")+"";
}
/**
* 初始化云推送通道
*
* @param applicationContext
*/
static void initPushService(final Context applicationContext) throws PackageManager.NameNotFoundException {
getConfig(applicationContext);
PushServiceFactory.init(applicationContext);
final CloudPushService pushService = PushServiceFactory.getCloudPushService();
pushService.setLogLevel(CloudPushService.LOG_DEBUG);
pushService.register(applicationContext,AliyunAppKey,AliyunAppSecret, new CommonCallback() {
@Override
public void onSuccess(String response) {
Log.i("==", "init cloudchannel success");
String deviceId=pushService.getDeviceId();
Log.i("== deviceId", deviceId + "");
}
@Override
public void onFailed(String errorCode, String errorMessage) {
Log.i("==", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
}
});
// 注册NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = NotificationChannelId;
// 用户可以看到的通知渠道的名字.
CharSequence name = "通知";
// 用户可以看到的通知渠道的描述
String description = "通知描述";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
// 设置通知出现时的震动(如果 android 设备支持的话)
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
// 最后在notificationmanager中创建该通知渠道
mNotificationManager.createNotificationChannel(mChannel);
// 设置8.0系统的通知小图标,必须要纯色的图
// PushServiceFactory.getCloudPushService().setNotificationSmallIcon(R.drawable.notify);
}
// 5. 在应用中初始化辅助通道
// 注册方法会自动判断是否支持小米系统推送,如不支持会跳过注册。
if(XiaoMiAppId!=null&&XiaoMiAppKey!=null) {
Log.i("XiaoMi Push registered", "XiaoMiAppId:" + XiaoMiAppId + " , XiaoMiAppKey:" + XiaoMiAppKey);
MiPushRegister.register(applicationContext, XiaoMiAppId, XiaoMiAppKey);
}
// 注册方法会自动判断是否支持华为系统推送,如不支持会跳过注册。
HuaWeiRegister.register(applicationContext);
// GCM/FCM辅助通道注册
// GcmRegister.register(this, sendId, applicationId);
// //sendId/applicationId为步骤获得的参数
// OPPO通道注册
if(OPPOAppKey!=null&&OPPOAppSecret!=null) {
Log.i("OPPO Push registered", "OPPOAppKey:" + OPPOAppKey + " , OPPOAppSecret:" + OPPOAppSecret);
OppoRegister.register(applicationContext, OPPOAppKey, OPPOAppSecret); // appKey/appSecret在OPPO通道开发者平台获取
}
}
/**
* 解决androidP 第一次打开程序出现莫名弹窗 弹窗内容“detected problems with api ”
*/
private void closeAndroidPDialog() {
try {
Class aClass = Class.forName("android.content.pm.PackageParser$Package");
Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class cls = Class.forName("android.app.ActivityThread");
Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
declaredMethod.setAccessible(true);
Object activityThread = declaredMethod.invoke(null);
Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
mHiddenApiWarningShown.setAccessible(true);
mHiddenApiWarningShown.setBoolean(activityThread, true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setNoticeJsonData(String jsonObject) {
//response为后台返回的json数据
preference.edit().putString("NoticeJsonData", jsonObject).apply(); //存入json串
}
public String getNotice() {
String jsonData = preference.getString("NoticeJsonData", "");
//每次取到json数据后,将其清空
preference.edit().putString("NoticeJsonData", "").apply();
try {
JSONObject data=new JSONObject(jsonData);
AliyunPush.pushData(data);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonData;
}
public void setIsShowNoticePermissions(boolean isShow) {
preference.edit().putBoolean("ShowNoticePermissions", isShow).apply();
}
public boolean getIsShowNoticePermissions() {
return preference.getBoolean("ShowNoticePermissions",true);
}
/**
* 请求通知权限
*/
public void isShowNoticeDialog(Activity context,String msg) {
NotificationManagerCompat notification = NotificationManagerCompat.from(context);
boolean isEnabled = notification.areNotificationsEnabled();
if(msg==null){
msg="建议你开启通知权限,第一时间收到提醒";
}
//未打开通知
if (!isEnabled) {
try {
if (preference.getBoolean("ShowNoticePermissions", true)) {
showDialog(context,msg);
} else {
int random = (int) (Math.random() * 10 + 1);
// Log.i("== random", random + "");
//随机数1-10,每次启动,如果除以3为0,则显示弹窗请求权限,否则就不弹窗
if (random % 3 == 0) {
showDialog(context,msg);
}
}
}catch (Exception ex){}
}
}
public void showDialog(Activity context,String msg) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("开启推送通知")
.setMessage(msg)
.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
@Override
public void onClick(DialogInterface dialog, int which) {
preference.edit().putBoolean("ShowNoticePermissions", false).apply();
}
})
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", context.getPackageName());
intent.putExtra("app_uid", context.getApplicationInfo().uid);
context.startActivity(intent);
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { //4.4
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + context.getPackageName()));
} else if (Build.VERSION.SDK_INT >= 15) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package",context.getPackageName(), null));
}
context.startActivity(intent);
}
})
.create();
if(context.isFinishing())return;
alertDialog.show();
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
}
},5000);
}
}
| 442623641/cordova-plugin-aliyunpush | src/android/PushUtils.java | 2,861 | //随机数1-10,每次启动,如果除以3为0,则显示弹窗请求权限,否则就不弹窗 | line_comment | zh-cn | package com.alipush;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.register.HuaWeiRegister;
import com.alibaba.sdk.android.push.register.MiPushRegister;
import com.alibaba.sdk.android.push.register.OppoRegister;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class PushUtils {
public static final String NotificationChannelId = "7777777";
private static String AliyunAppKey;
private static String AliyunAppSecret;
// 小米辅助通道
private static String XiaoMiAppId = "2882303761518018487";
private static String XiaoMiAppKey = "5371801843487";
// OPPO辅助通道
private static String OPPOAppKey = "7ac256813b8745928c2102c20dd49fde";
private static String OPPOAppSecret = "9b4ac44b4eee471097243658679910d1";
private SharedPreferences preference;
public PushUtils(Context context) {
this.preference = PreferenceManager.getDefaultSharedPreferences(context) ;
}
public static String getCurProcessName(Context context) {
int pid = android.os.Process.myPid();
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
if (appProcess.pid == pid) {
return appProcess.processName;
}
}
return null;
}
/**
* 获取推送配置信息
* @param applicationContext
*/
private static void getConfig(final Context applicationContext) throws PackageManager.NameNotFoundException {
ApplicationInfo appInfo = applicationContext.getPackageManager().getApplicationInfo(applicationContext.getPackageName(), PackageManager.GET_META_DATA);
AliyunAppKey=appInfo.metaData.get("AliyunAppKey")+"";
AliyunAppSecret=appInfo.metaData.get("AliyunAppSecret")+"";
XiaoMiAppId =appInfo.metaData.get("XiaoMiAppId")+"";
XiaoMiAppKey=appInfo.metaData.get("XiaoMiAppKey")+"";
OPPOAppKey = appInfo.metaData.get("OPPOAppKey")+"";
OPPOAppSecret=appInfo.metaData.get("OPPOAppSecret")+"";
}
/**
* 初始化云推送通道
*
* @param applicationContext
*/
static void initPushService(final Context applicationContext) throws PackageManager.NameNotFoundException {
getConfig(applicationContext);
PushServiceFactory.init(applicationContext);
final CloudPushService pushService = PushServiceFactory.getCloudPushService();
pushService.setLogLevel(CloudPushService.LOG_DEBUG);
pushService.register(applicationContext,AliyunAppKey,AliyunAppSecret, new CommonCallback() {
@Override
public void onSuccess(String response) {
Log.i("==", "init cloudchannel success");
String deviceId=pushService.getDeviceId();
Log.i("== deviceId", deviceId + "");
}
@Override
public void onFailed(String errorCode, String errorMessage) {
Log.i("==", "init cloudchannel failed -- errorcode:" + errorCode + " -- errorMessage:" + errorMessage);
}
});
// 注册NotificationChannel
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationManager mNotificationManager = (NotificationManager) applicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
// 通知渠道的id
String id = NotificationChannelId;
// 用户可以看到的通知渠道的名字.
CharSequence name = "通知";
// 用户可以看到的通知渠道的描述
String description = "通知描述";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
// 配置通知渠道的属性
mChannel.setDescription(description);
// 设置通知出现时的闪灯(如果 android 设备支持的话)
mChannel.enableLights(true);
mChannel.setLightColor(Color.RED);
// 设置通知出现时的震动(如果 android 设备支持的话)
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[] { 100, 200, 300, 400, 500, 400, 300, 200, 400 });
// 最后在notificationmanager中创建该通知渠道
mNotificationManager.createNotificationChannel(mChannel);
// 设置8.0系统的通知小图标,必须要纯色的图
// PushServiceFactory.getCloudPushService().setNotificationSmallIcon(R.drawable.notify);
}
// 5. 在应用中初始化辅助通道
// 注册方法会自动判断是否支持小米系统推送,如不支持会跳过注册。
if(XiaoMiAppId!=null&&XiaoMiAppKey!=null) {
Log.i("XiaoMi Push registered", "XiaoMiAppId:" + XiaoMiAppId + " , XiaoMiAppKey:" + XiaoMiAppKey);
MiPushRegister.register(applicationContext, XiaoMiAppId, XiaoMiAppKey);
}
// 注册方法会自动判断是否支持华为系统推送,如不支持会跳过注册。
HuaWeiRegister.register(applicationContext);
// GCM/FCM辅助通道注册
// GcmRegister.register(this, sendId, applicationId);
// //sendId/applicationId为步骤获得的参数
// OPPO通道注册
if(OPPOAppKey!=null&&OPPOAppSecret!=null) {
Log.i("OPPO Push registered", "OPPOAppKey:" + OPPOAppKey + " , OPPOAppSecret:" + OPPOAppSecret);
OppoRegister.register(applicationContext, OPPOAppKey, OPPOAppSecret); // appKey/appSecret在OPPO通道开发者平台获取
}
}
/**
* 解决androidP 第一次打开程序出现莫名弹窗 弹窗内容“detected problems with api ”
*/
private void closeAndroidPDialog() {
try {
Class aClass = Class.forName("android.content.pm.PackageParser$Package");
Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class cls = Class.forName("android.app.ActivityThread");
Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
declaredMethod.setAccessible(true);
Object activityThread = declaredMethod.invoke(null);
Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
mHiddenApiWarningShown.setAccessible(true);
mHiddenApiWarningShown.setBoolean(activityThread, true);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setNoticeJsonData(String jsonObject) {
//response为后台返回的json数据
preference.edit().putString("NoticeJsonData", jsonObject).apply(); //存入json串
}
public String getNotice() {
String jsonData = preference.getString("NoticeJsonData", "");
//每次取到json数据后,将其清空
preference.edit().putString("NoticeJsonData", "").apply();
try {
JSONObject data=new JSONObject(jsonData);
AliyunPush.pushData(data);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonData;
}
public void setIsShowNoticePermissions(boolean isShow) {
preference.edit().putBoolean("ShowNoticePermissions", isShow).apply();
}
public boolean getIsShowNoticePermissions() {
return preference.getBoolean("ShowNoticePermissions",true);
}
/**
* 请求通知权限
*/
public void isShowNoticeDialog(Activity context,String msg) {
NotificationManagerCompat notification = NotificationManagerCompat.from(context);
boolean isEnabled = notification.areNotificationsEnabled();
if(msg==null){
msg="建议你开启通知权限,第一时间收到提醒";
}
//未打开通知
if (!isEnabled) {
try {
if (preference.getBoolean("ShowNoticePermissions", true)) {
showDialog(context,msg);
} else {
int random = (int) (Math.random() * 10 + 1);
// Log.i("== random", random + "");
//随机 <SUF>
if (random % 3 == 0) {
showDialog(context,msg);
}
}
}catch (Exception ex){}
}
}
public void showDialog(Activity context,String msg) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(context)
.setTitle("开启推送通知")
.setMessage(msg)
.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
@RequiresApi(api = Build.VERSION_CODES.GINGERBREAD)
@Override
public void onClick(DialogInterface dialog, int which) {
preference.edit().putBoolean("ShowNoticePermissions", false).apply();
}
})
.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("android.provider.extra.APP_PACKAGE", context.getPackageName());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //5.0
intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
intent.putExtra("app_package", context.getPackageName());
intent.putExtra("app_uid", context.getApplicationInfo().uid);
context.startActivity(intent);
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { //4.4
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.addCategory(Intent.CATEGORY_DEFAULT);
intent.setData(Uri.parse("package:" + context.getPackageName()));
} else if (Build.VERSION.SDK_INT >= 15) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.fromParts("package",context.getPackageName(), null));
}
context.startActivity(intent);
}
})
.create();
if(context.isFinishing())return;
alertDialog.show();
alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
}
},5000);
}
}
| 0 | 2,457 | 28 | 2,861 | 30 | 2,943 | 27 | 2,861 | 30 | 3,650 | 52 | false | false | false | false | false | true |
5328_4 | package org.artbot;
public enum MessagerResult {
/**
* 一般是协议层错误,携带错误联系秋洛即可
*/
Error("发送错误", 0),
/**
* 发送成功不意味着发出,只是把包提交给了腾讯
*/
Success("发送成功", 1),
/**
* 例如:声明是群消息但是没有群号
*/
InputError("输入参数有误", 2),
/**
* 消息超过可发送消息的最大长度
*/
MessageLengthMax("爸爸,你这个消息长过头了", 3),
/**
* 消息内没有消息体或消息体无效
*/
EmptyMessage("爸爸,求求你给我个不是空的消息吧!记得里面的消息要有效,别给我个图片链接还是404的就行", 4);
MessagerResult(String msg, int id){
this.msg = msg;
this.id = id;
}
public final String msg;
public final int id;
}
| 448808614/ArtQQ | src/main/java/org/artbot/MessagerResult.java | 254 | /**
* 消息内没有消息体或消息体无效
*/ | block_comment | zh-cn | package org.artbot;
public enum MessagerResult {
/**
* 一般是协议层错误,携带错误联系秋洛即可
*/
Error("发送错误", 0),
/**
* 发送成功不意味着发出,只是把包提交给了腾讯
*/
Success("发送成功", 1),
/**
* 例如:声明是群消息但是没有群号
*/
InputError("输入参数有误", 2),
/**
* 消息超过可发送消息的最大长度
*/
MessageLengthMax("爸爸,你这个消息长过头了", 3),
/**
* 消息内 <SUF>*/
EmptyMessage("爸爸,求求你给我个不是空的消息吧!记得里面的消息要有效,别给我个图片链接还是404的就行", 4);
MessagerResult(String msg, int id){
this.msg = msg;
this.id = id;
}
public final String msg;
public final int id;
}
| 0 | 224 | 17 | 254 | 18 | 245 | 16 | 254 | 18 | 364 | 22 | false | false | false | false | false | true |
41446_2 | package com.liuyao.perfecttable;
public class Column implements IColumn{
private String columnName;
//多级列名支持,index 0是最上面,然后一级一级往下面排
private String[] parentName;
//反射取值
private String property;
//是否固定列,不许左右滑动
private boolean fix;
private Integer minWidthDp;
private Integer maxWidthDp;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String[] getParentName() {
return parentName;
}
public void setParentName(String[] parentName) {
this.parentName = parentName;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public boolean isFix() {
return fix;
}
public void setFix(boolean fix) {
this.fix = fix;
}
public Integer getMinWidthDp() {
return minWidthDp;
}
public void setMinWidthDp(Integer minWidthDp) {
this.minWidthDp = minWidthDp;
}
public Integer getMaxWidthDp() {
return maxWidthDp;
}
public void setMaxWidthDp(Integer maxWidthDp) {
this.maxWidthDp = maxWidthDp;
}
}
| 475789729/perfecttable | src/main/java/com/liuyao/perfecttable/Column.java | 311 | //是否固定列,不许左右滑动 | line_comment | zh-cn | package com.liuyao.perfecttable;
public class Column implements IColumn{
private String columnName;
//多级列名支持,index 0是最上面,然后一级一级往下面排
private String[] parentName;
//反射取值
private String property;
//是否 <SUF>
private boolean fix;
private Integer minWidthDp;
private Integer maxWidthDp;
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String[] getParentName() {
return parentName;
}
public void setParentName(String[] parentName) {
this.parentName = parentName;
}
public String getProperty() {
return property;
}
public void setProperty(String property) {
this.property = property;
}
public boolean isFix() {
return fix;
}
public void setFix(boolean fix) {
this.fix = fix;
}
public Integer getMinWidthDp() {
return minWidthDp;
}
public void setMinWidthDp(Integer minWidthDp) {
this.minWidthDp = minWidthDp;
}
public Integer getMaxWidthDp() {
return maxWidthDp;
}
public void setMaxWidthDp(Integer maxWidthDp) {
this.maxWidthDp = maxWidthDp;
}
}
| 0 | 308 | 10 | 311 | 11 | 348 | 9 | 311 | 11 | 431 | 19 | false | false | false | false | false | true |
44464_0 | package org.example.constant;
import org.example.system.Database;
import org.example.system.game.Leader;
import org.example.turnobj.FollowCard;
import org.example.turnobj.ThePlayer;
import org.example.system.util.Maps;
import org.example.turnobj.dota.幻影刺客;
import org.example.turnobj.dota.敌法师;
import org.example.turnobj.dota.斧王;
import org.example.turnobj.dota.鱼人夜行者;
import org.example.turnobj.hsr.三月七;
import org.example.turnobj.hsr.丹恒;
import org.example.turnobj.hsr.开拓者;
import org.example.turnobj.hsr.艾丝妲;
import org.example.turnobj.jojo.EnricoPucci;
import org.example.turnobj.pokemon.Fusigidane;
import org.example.turnobj.pokemon.Hitokage;
import org.example.turnobj.pokemon.Pikachu;
import org.example.turnobj.pokemon.Zenigame;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 预置牌组
*/
public class DeckPreset {
public static final Map<String,List<Class<? extends FollowCard>>> decks = new HashMap<>();
public static final Map<String,Class<? extends Leader>> deckLeader = new HashMap<>();
static {
decks.put("宝可梦御三家",List.of(
Pikachu.class, Zenigame.class, Hitokage.class, Fusigidane.class
));
decks.put("普奇神父完全体",List.of(
EnricoPucci.class
));
decks.put("星穹列车组",List.of(
开拓者.class, 三月七.class, 丹恒.class, 艾丝妲.class
));
decks.put("DotA",List.of(
鱼人夜行者.class, 敌法师.class, 斧王.class, 幻影刺客.class
));
}
public static List describe(){
List<Map<String,Object>> deckInfo = new ArrayList<>();
decks.forEach((name,cardClassList)-> {
final List<? extends FollowCard> prototypes = cardClassList.stream().map(Database::getPrototype).toList();
Leader leader;
try {
Class<? extends Leader> leaderClass = DeckPreset.deckLeader.get(name);
if(leaderClass==null){
leaderClass = ThePlayer.class;
}
leader = leaderClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
deckInfo.add(Maps.newMap("name", name, "leader", leader,"deck", prototypes));
});
return deckInfo;
}
}
| 476106017/tbs4j | src/main/java/org/example/constant/DeckPreset.java | 738 | /**
* 预置牌组
*/ | block_comment | zh-cn | package org.example.constant;
import org.example.system.Database;
import org.example.system.game.Leader;
import org.example.turnobj.FollowCard;
import org.example.turnobj.ThePlayer;
import org.example.system.util.Maps;
import org.example.turnobj.dota.幻影刺客;
import org.example.turnobj.dota.敌法师;
import org.example.turnobj.dota.斧王;
import org.example.turnobj.dota.鱼人夜行者;
import org.example.turnobj.hsr.三月七;
import org.example.turnobj.hsr.丹恒;
import org.example.turnobj.hsr.开拓者;
import org.example.turnobj.hsr.艾丝妲;
import org.example.turnobj.jojo.EnricoPucci;
import org.example.turnobj.pokemon.Fusigidane;
import org.example.turnobj.pokemon.Hitokage;
import org.example.turnobj.pokemon.Pikachu;
import org.example.turnobj.pokemon.Zenigame;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 预置牌 <SUF>*/
public class DeckPreset {
public static final Map<String,List<Class<? extends FollowCard>>> decks = new HashMap<>();
public static final Map<String,Class<? extends Leader>> deckLeader = new HashMap<>();
static {
decks.put("宝可梦御三家",List.of(
Pikachu.class, Zenigame.class, Hitokage.class, Fusigidane.class
));
decks.put("普奇神父完全体",List.of(
EnricoPucci.class
));
decks.put("星穹列车组",List.of(
开拓者.class, 三月七.class, 丹恒.class, 艾丝妲.class
));
decks.put("DotA",List.of(
鱼人夜行者.class, 敌法师.class, 斧王.class, 幻影刺客.class
));
}
public static List describe(){
List<Map<String,Object>> deckInfo = new ArrayList<>();
decks.forEach((name,cardClassList)-> {
final List<? extends FollowCard> prototypes = cardClassList.stream().map(Database::getPrototype).toList();
Leader leader;
try {
Class<? extends Leader> leaderClass = DeckPreset.deckLeader.get(name);
if(leaderClass==null){
leaderClass = ThePlayer.class;
}
leader = leaderClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
deckInfo.add(Maps.newMap("name", name, "leader", leader,"deck", prototypes));
});
return deckInfo;
}
}
| 0 | 563 | 10 | 738 | 10 | 704 | 9 | 738 | 10 | 848 | 14 | false | false | false | false | false | true |
40907_7 | package com.itheima.a04;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.context.support.GenericApplicationContext;
/*
bean 后处理器的作用
*/
public class A04 {
public static void main(String[] args) {
// ⬇️GenericApplicationContext 是一个【干净】的容器
GenericApplicationContext context = new GenericApplicationContext();
// ⬇️用原始方法注册三个 bean
context.registerBean("bean1", Bean1.class);
context.registerBean("bean2", Bean2.class);
context.registerBean("bean3", Bean3.class);
context.registerBean("bean4", Bean4.class);
context.getDefaultListableBeanFactory().setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
context.registerBean(AutowiredAnnotationBeanPostProcessor.class); // @Autowired @Value
context.registerBean(CommonAnnotationBeanPostProcessor.class); // @Resource @PostConstruct @PreDestroy
ConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());
// ⬇️初始化容器
context.refresh(); // 执行beanFactory后处理器, 添加bean后处理器, 初始化所有单例
System.out.println(context.getBean(Bean1.class));
// ⬇️销毁容器
context.close();
/*
学到了什么
a. @Autowired 等注解的解析属于 bean 生命周期阶段(依赖注入, 初始化)的扩展功能
b. 这些扩展功能由 bean 后处理器来完成
*/
}
}
| 4rnold/CodeRepo | SpringBoot/spring-samples/src/main/java/com/itheima/a04/A04.java | 441 | // ⬇️销毁容器
| line_comment | zh-cn | package com.itheima.a04;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.context.annotation.CommonAnnotationBeanPostProcessor;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.context.support.GenericApplicationContext;
/*
bean 后处理器的作用
*/
public class A04 {
public static void main(String[] args) {
// ⬇️GenericApplicationContext 是一个【干净】的容器
GenericApplicationContext context = new GenericApplicationContext();
// ⬇️用原始方法注册三个 bean
context.registerBean("bean1", Bean1.class);
context.registerBean("bean2", Bean2.class);
context.registerBean("bean3", Bean3.class);
context.registerBean("bean4", Bean4.class);
context.getDefaultListableBeanFactory().setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
context.registerBean(AutowiredAnnotationBeanPostProcessor.class); // @Autowired @Value
context.registerBean(CommonAnnotationBeanPostProcessor.class); // @Resource @PostConstruct @PreDestroy
ConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());
// ⬇️初始化容器
context.refresh(); // 执行beanFactory后处理器, 添加bean后处理器, 初始化所有单例
System.out.println(context.getBean(Bean1.class));
// ⬇️ <SUF>
context.close();
/*
学到了什么
a. @Autowired 等注解的解析属于 bean 生命周期阶段(依赖注入, 初始化)的扩展功能
b. 这些扩展功能由 bean 后处理器来完成
*/
}
}
| 0 | 374 | 8 | 434 | 10 | 433 | 6 | 434 | 10 | 559 | 15 | false | false | false | false | false | true |
46698_21 | package algorithms.困难;
public class 交错字符串97 {
// 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
//
// 示例 1:
//
// 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
// 输出: true
// 示例 2:
//
// 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
// 输出: false
//
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/interleaving-string
public static void main(String[] args) {
交错字符串97 solution = new 交错字符串97();
// int i = solution.romanToInt("IV");
// boolean interleave = solution.isInterleave("aabcc", "dbbca", "aadbbcbcac");
boolean interleave = solution.isInterleave("aabcc", "dbbca", "aadbbbaccc");
System.out.println(1);
}
// public boolean isInterleave(String s1, String s2, String s3) {
// if(s1.length() + s2.length() != s3.length()){
// return false;
// }
// List<String> collect3 = new ArrayList<>(Arrays.asList(s3.split("")));
// List<String> collect2 = new ArrayList<>(Arrays.asList(s2.split("")));
// List<String> collect1 = new ArrayList<>(Arrays.asList(s1.split("")));
// for (char c : s1.toCharArray()) {
// s3.indexOf(c);
// collect3.indexOf()
// }
//
//
// return false;
// }
int cur1 = 0, cur2 = 0, cur3 = 0; //三个指针,分别指向s1,s2,s3已经搜索到的位置
public boolean isInterleave(String s1, String s2, String s3) {
if (s1 == null && s2 == null && s3 == null) {
return true;
} else if (s1.length() + s2.length() != s3.length()) {
return false;
}
// 返回回溯结果
return recursive(s1, s2, s3);
}
public boolean recursive(String s1, String s2, String s3) {
// 递归终止条件:如果s3已经全部搜索完,则表明符合题意,返回true
if (cur3 >= s3.length()) {
return true;
}
if (cur1 < s1.length() && s3.charAt(cur3) == s1.charAt(cur1)) {
// 继续下一层回溯
cur1 += 1;
cur3 += 1;
if (recursive(s1, s2, s3)) {
return true;
}
// 还原指针
cur1 -= 1;
cur3 -= 1;
}
if (cur2 < s2.length() && s3.charAt(cur3) == s2.charAt(cur2)) {
cur2 += 1;
cur3 += 1;
if (recursive(s1, s2, s3)) {
return true;
}
cur2 -= 1;
cur3 -= 1;
}
return false;
}
}
| 501658362/JavaAlgorithms | src/main/java/algorithms/困难/交错字符串97.java | 846 | //三个指针,分别指向s1,s2,s3已经搜索到的位置 | line_comment | zh-cn | package algorithms.困难;
public class 交错字符串97 {
// 给定三个字符串 s1, s2, s3, 验证 s3 是否是由 s1 和 s2 交错组成的。
//
// 示例 1:
//
// 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
// 输出: true
// 示例 2:
//
// 输入: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
// 输出: false
//
// 来源:力扣(LeetCode)
// 链接:https://leetcode-cn.com/problems/interleaving-string
public static void main(String[] args) {
交错字符串97 solution = new 交错字符串97();
// int i = solution.romanToInt("IV");
// boolean interleave = solution.isInterleave("aabcc", "dbbca", "aadbbcbcac");
boolean interleave = solution.isInterleave("aabcc", "dbbca", "aadbbbaccc");
System.out.println(1);
}
// public boolean isInterleave(String s1, String s2, String s3) {
// if(s1.length() + s2.length() != s3.length()){
// return false;
// }
// List<String> collect3 = new ArrayList<>(Arrays.asList(s3.split("")));
// List<String> collect2 = new ArrayList<>(Arrays.asList(s2.split("")));
// List<String> collect1 = new ArrayList<>(Arrays.asList(s1.split("")));
// for (char c : s1.toCharArray()) {
// s3.indexOf(c);
// collect3.indexOf()
// }
//
//
// return false;
// }
int cur1 = 0, cur2 = 0, cur3 = 0; //三个 <SUF>
public boolean isInterleave(String s1, String s2, String s3) {
if (s1 == null && s2 == null && s3 == null) {
return true;
} else if (s1.length() + s2.length() != s3.length()) {
return false;
}
// 返回回溯结果
return recursive(s1, s2, s3);
}
public boolean recursive(String s1, String s2, String s3) {
// 递归终止条件:如果s3已经全部搜索完,则表明符合题意,返回true
if (cur3 >= s3.length()) {
return true;
}
if (cur1 < s1.length() && s3.charAt(cur3) == s1.charAt(cur1)) {
// 继续下一层回溯
cur1 += 1;
cur3 += 1;
if (recursive(s1, s2, s3)) {
return true;
}
// 还原指针
cur1 -= 1;
cur3 -= 1;
}
if (cur2 < s2.length() && s3.charAt(cur3) == s2.charAt(cur2)) {
cur2 += 1;
cur3 += 1;
if (recursive(s1, s2, s3)) {
return true;
}
cur2 -= 1;
cur3 -= 1;
}
return false;
}
}
| 0 | 759 | 17 | 846 | 18 | 861 | 18 | 846 | 18 | 1,006 | 32 | false | false | false | false | false | true |
44418_41 | package dao;
/**
* 该类是用于存放SQL语句的 创建于:2016年6月12日21:17:36
*/
public class Maps {
// 查询个人会员
private static final String allPersonalMember = "SELECT count(*) FROM user where GroupNumber=\'1\'";
// 查询企业会员
private static final String allCompanyMember = "SELECT count(*) FROM user where GroupNumber=\'2\'";
// 按条件查询个人会员
private static final String queryPersonalMember = "select usernumber,username,email,question,answer,safecode from user where GroupNumber=\'1\' limit ?,?";
// 按条件查询企业会员
private static final String queryCompanyMember = "select usernumber,username,email,question,answer,safecode from user where GroupNumber=\'2\' limit ?,?";
// 删除用户
private static final String deletePersonalMemberSql = "delete from user where usernumber=?";
// 删除个人会员详细信息
private static final String deleteUserinfoSql = "delete from userinfo where username=?";
// 删除企业会员详细信息
private static final String deleteCompanyinfoSql = "delete from companyinfo where username=?";
// 管理员添加会员
private static final String AddPersonalMemberSql = "insert into user (usernumber,username,password,question,answer,safecode,img,email,GroupNumber,shenfen) values (?,?,?,?,?,?,?,?,?,?)";
// 验证登录用户名
private static final String checkUserSql = "select password,username from manager where username=?";
// 会员成功登录时获得两个积分
private static final String UpdateUserPoint = "UPDATE user SET point=point+2 WHERE username=?";
// 注册成功时添加会员用户
private static final String addMemberSql = "insert into user(usernumber,username,password,question,answer,safecode,img,email,GroupNumber,shenfen) values(?,?,?,?,?,?,?,?,?,?)";
// 从会员表里选取最大会员编号,添加会员编号时使用
private static final String selectMaxIdSql = "select max(usernumber) from user";
// 查询所有会员记录数
private static final String allMemberCount = "SELECT count(*) FROM user";
// 按条件查询全部会员
private static final String queryAllMember = "select usernumber,username,GroupNumber from user limit ?,?";
// 根据会员编号更改该会员会员组编号及会员身份
private static final String updateMemberNumberById = "update user set GroupNumber=?,shenfen=? where usernumber=?";
// 根据会员编号更改该会员资料
private static final String UpdateMemberSql = "update user set question=?,answer=?,safecode=? where usernumber=?";
// 添加商品
private static final String AddProductSql = "insert into product (ProductID,Version,PType,Content,bound,URL_1,addTime) values (?,?,?,?,?,?,?)";
// 查询所有商品记录数
private static final String allProduct = "SELECT count(*) FROM product";
// 根据商品id查询商品名称
private static final String queryProductById = "select ProductID from product where id=?";
// 按条件查询商品
private static final String queryProduct = "SELECT * FROM product limit ?,?";
// 更新商品
private static final String UpdateProductSql = "UPDATE product SET ProductID=?,Version=?,PType=?,Content=? WHERE id=?";
// 删除商品
private static String deleteProductSql;
// 按积分查询商品
private static final String queryBound = "SELECT id,ProductId,Version,PType,Content,bound FROM product limit ?,?";
// 更新积分
private static final String UpdateBoundSql = "UPDATE product SET bound=? WHERE id=?";
// 管理员添加点卡/用户充值点卡
private static final String AddCardSql = "insert into card (CardNumber,CardPassword,Point,username,TimeOutDate,addTime) values (?,?,?,?,?,?)";
// 查询所有点卡
private static final String allCard = "SELECT count(*) FROM card";
// 按条件查询点卡
private static final String queryCard = "SELECT * FROM card limit ?,?";
// 更新商品
private static final String UpdateCardSql = "UPDATE card SET CardNumber=?,CardPassword=?,point=?,TimeOutDate=? WHERE CardID=?";
// 企业会员登录后完善企业信息
private static final String addCompanyMessageSql = "insert into companyuserinfo(username,C_Name,C_PostCode,C_Province,C_City,C_Address,C_ConactName,C_Vocation,C_WebSite,C_size,C_Tel,C_BankName,C_Capital) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
// 个人会员登录后完善个人信息
private static final String addPersonalMessageSql = "insert into userinfo(username,uname, sex,birthday, zjlb, zjhm, szsf, city, addr,yzbm,Tel,hompage,qq) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
// 购买点卡后更新会员积分
private static final String RechargeAndAddPointSql = "update user t1 join (select point from user where username = ?) as t2 on t1.point>=0 set t1.point=t1.point+? where t1.username = ?";
// 用户兑换积分
private static final String ExchangeSql = "update user u,card c join (select Point from card where CardNumber=?)as t2 set u.point=u.point+?,c.Point=t2.Point-? where u.username=? and c.CardNumber=?";
// 管理员端展示交易明细
private static final String showBuyProduct = "SELECT count(*) from buyproduct";
// 按条件查询全部交易信息
private static final String queryAllBuyProduct = "SELECT u.username,u.shenfen,p.ProductID,p.Version,p.PType,p.Content,p.bound FROM user u,product p,buyproduct b where b.id=p.id and u.username=b.username limit ?,?";
// 管理员端展示交易明细
private static final String showMemberBuyProduct = "SELECT count(*) from buyproduct where usernme=?";
// 按条件查询个人交易信息
private static final String queryOneMemberBuyProduct = "SELECT p.ProductID,p.Version,p.PType,p.Content,p.bound FROM user u,product p,buyproduct b where b.id=p.id and u.username=b.username and b.username=? limit ?,?";
// 会员购买商品后扣除积分
private static final String updateMemberPoint = "update user set point=point-? where username=?";
// 根据商品编号获得商品id字段
private static final String getProductid = "select id from product where ProductID=?";
// 添加商品
private static final String AddToBuyProduct = "insert into buyproduct (username,id) values (?,?)";
// 用户购买后更新商品表中的已下载次数
private static final String UpdateProductUseNumSql = "UPDATE product SET useNum=useNum+1 WHERE id=?";
// 按积分查询所有会员
private static final String allqueryPointSql = "SELECT username,point FROM user limit ?,?";
// 更新会员积分
private static final String updatePointSql = "UPDATE user SET point=? WHERE username=?";
// 下载后更新会员积分
private static final String usePointSql = "update user t1 join (select point from user where username = ?) as t2 on t1.point>=0 set t1.point=t1.point-? where t1.username = ?";
// 查询所有公告
private static final String allAnnouncement = "SELECT count(*) FROM announcement";
// 按条件查询公告
private static final String queryAnnouncement = "SELECT aid,title,people,pubdate FROM announcement limit ?,?";
// 管理员添加公告
private static final String addAnnouncementSql = "insert into announcement (title, people, pubdate, announcement) values (?,?,?,?)";
// 删除公告
private static String deleteAnnouncementSql;
// 查询已购买的点卡数量
private static final String mycard = "SELECT count(*) FROM card where username=?";
// 按条件查询全部已购买点卡
private static final String queryAllMyCard = "select CardNumber,CardPassword,Point,TimeOutDate,AddTime from card where username=? limit ?,?";
// 用户兑换积分时检查输入的卡号和密码是否正确
private static final String CheckCardNumberSql = "select * from card where CardNumber=? and CardPassword=?";
// 查询某张点卡的点数
private static final String selectPointFromCardSql = "select Point from card where CardNumber=?";
//添加评论
private static final String addCommentSql = "insert into comment(aid,username,content,commentTime) values(?,?,?,now())";
public static String getAllcompanymember() {
return allCompanyMember;
}
public static String getAllpersonalmember() {
return allPersonalMember;
}
public static String getQuerypersonalmember() {
return queryPersonalMember;
}
public static String getQuerycompanymember() {
return queryCompanyMember;
}
public static String getDeletePersonalMemberSql() {
return deletePersonalMemberSql;
}
public static String getAddPersonalMemberSql() {
return AddPersonalMemberSql;
}
public static String getCheckUserSql() {
return checkUserSql;
}
public static String getAddMemberSql() {
return addMemberSql;
}
public static String getSelectMaxIdSql() {
return selectMaxIdSql;
}
public static String getAddProductSql() {
return AddProductSql;
}
public static String getProductCount() {
return allProduct;
}
public static String getQueryProduct() {
return queryProduct;
}
public static String getQueryProductByIdSql() {
return queryProductById;
}
public static String getUpdateProductSql() {
return UpdateProductSql;
}
public static String getDeleteProductSql(String ids) {
deleteProductSql = "update product set UserDel=1 where id in(" + ids
+ ")";
return deleteProductSql;
}
public static String getAllMemberCount() {
return allMemberCount;
}
public static String getQueryAllMember() {
return queryAllMember;
}
public static String getUpdateMemberNumberById() {
return updateMemberNumberById;
}
public static String getAddCardSql() {
return AddCardSql;
}
public static String getCardCount() {
return allCard;
}
public static String getQueryCard() {
return queryCard;
}
public static String getUpdateCardSql() {
return UpdateCardSql;
}
public static String getDeleteCardSql(String ids) {
deleteProductSql = "delete from card where CardID in(" + ids + ")";
return deleteProductSql;
}
public static String getAddCompanyMessageSql() {
return addCompanyMessageSql;
}
public static String getAddPersonalMessageSql() {
return addPersonalMessageSql;
}
public static String getQueryBound() {
return queryBound;
}
public static String getUpdateBoundSql() {
return UpdateBoundSql;
}
public static String getRechargeAndAddPointSql() {
return RechargeAndAddPointSql;
}
public static String getExchangeSql() {
return ExchangeSql;
}
public static String getShowBuyProduct() {
return showBuyProduct;
}
public static String getQueryAllBuyProduct() {
return queryAllBuyProduct;
}
public static String getShowMemberBuyProduct() {
return showMemberBuyProduct;
}
public static String getQueryOneMemberBuyProduct() {
return queryOneMemberBuyProduct;
}
public static String getUpdateMemberPoint() {
return updateMemberPoint;
}
public static String getProductid() {
return getProductid;
}
public static String getAddToBuyProduct() {
return AddToBuyProduct;
}
public static String getUpdateProductUsenumSql() {
return UpdateProductUseNumSql;
}
public static String getUpdateUserPoint() {
return UpdateUserPoint;
}
public static String getUpdatePointSql() {
return updatePointSql;
}
public static String getUsePointSql() {
return usePointSql;
}
public static String getAnnouncementCount() {
return allAnnouncement;
}
public static String getQueryAnnouncement() {
return queryAnnouncement;
}
public static String getAddAnnouncementSql() {
return addAnnouncementSql;
}
public static String getDeleteAnnouncementSql(String ids) {
deleteAnnouncementSql = "delete from announcement where aid in(" + ids
+ ")";
return deleteAnnouncementSql;
}
public static String getAllQueryPoint() {
return allqueryPointSql;
}
public static String getDeleteUserinfoSql() {
return deleteUserinfoSql;
}
public static String getDeleteCompanyInfoSql() {
return deleteCompanyinfoSql;
}
public static String getMyCard() {
return mycard;
}
public static String getQueryAllMyCard() {
return queryAllMyCard;
}
public static String getCheckCardNumberSql() {
return CheckCardNumberSql;
}
public static String getSelectPointFromCardSql() {
return selectPointFromCardSql;
}
public static String getUpdateMemberSql() {
return UpdateMemberSql;
}
public static String getAddCommentSql() {
return addCommentSql;
}
}
| 511733119/Member | src/dao/Maps.java | 3,371 | // 按积分查询所有会员 | line_comment | zh-cn | package dao;
/**
* 该类是用于存放SQL语句的 创建于:2016年6月12日21:17:36
*/
public class Maps {
// 查询个人会员
private static final String allPersonalMember = "SELECT count(*) FROM user where GroupNumber=\'1\'";
// 查询企业会员
private static final String allCompanyMember = "SELECT count(*) FROM user where GroupNumber=\'2\'";
// 按条件查询个人会员
private static final String queryPersonalMember = "select usernumber,username,email,question,answer,safecode from user where GroupNumber=\'1\' limit ?,?";
// 按条件查询企业会员
private static final String queryCompanyMember = "select usernumber,username,email,question,answer,safecode from user where GroupNumber=\'2\' limit ?,?";
// 删除用户
private static final String deletePersonalMemberSql = "delete from user where usernumber=?";
// 删除个人会员详细信息
private static final String deleteUserinfoSql = "delete from userinfo where username=?";
// 删除企业会员详细信息
private static final String deleteCompanyinfoSql = "delete from companyinfo where username=?";
// 管理员添加会员
private static final String AddPersonalMemberSql = "insert into user (usernumber,username,password,question,answer,safecode,img,email,GroupNumber,shenfen) values (?,?,?,?,?,?,?,?,?,?)";
// 验证登录用户名
private static final String checkUserSql = "select password,username from manager where username=?";
// 会员成功登录时获得两个积分
private static final String UpdateUserPoint = "UPDATE user SET point=point+2 WHERE username=?";
// 注册成功时添加会员用户
private static final String addMemberSql = "insert into user(usernumber,username,password,question,answer,safecode,img,email,GroupNumber,shenfen) values(?,?,?,?,?,?,?,?,?,?)";
// 从会员表里选取最大会员编号,添加会员编号时使用
private static final String selectMaxIdSql = "select max(usernumber) from user";
// 查询所有会员记录数
private static final String allMemberCount = "SELECT count(*) FROM user";
// 按条件查询全部会员
private static final String queryAllMember = "select usernumber,username,GroupNumber from user limit ?,?";
// 根据会员编号更改该会员会员组编号及会员身份
private static final String updateMemberNumberById = "update user set GroupNumber=?,shenfen=? where usernumber=?";
// 根据会员编号更改该会员资料
private static final String UpdateMemberSql = "update user set question=?,answer=?,safecode=? where usernumber=?";
// 添加商品
private static final String AddProductSql = "insert into product (ProductID,Version,PType,Content,bound,URL_1,addTime) values (?,?,?,?,?,?,?)";
// 查询所有商品记录数
private static final String allProduct = "SELECT count(*) FROM product";
// 根据商品id查询商品名称
private static final String queryProductById = "select ProductID from product where id=?";
// 按条件查询商品
private static final String queryProduct = "SELECT * FROM product limit ?,?";
// 更新商品
private static final String UpdateProductSql = "UPDATE product SET ProductID=?,Version=?,PType=?,Content=? WHERE id=?";
// 删除商品
private static String deleteProductSql;
// 按积分查询商品
private static final String queryBound = "SELECT id,ProductId,Version,PType,Content,bound FROM product limit ?,?";
// 更新积分
private static final String UpdateBoundSql = "UPDATE product SET bound=? WHERE id=?";
// 管理员添加点卡/用户充值点卡
private static final String AddCardSql = "insert into card (CardNumber,CardPassword,Point,username,TimeOutDate,addTime) values (?,?,?,?,?,?)";
// 查询所有点卡
private static final String allCard = "SELECT count(*) FROM card";
// 按条件查询点卡
private static final String queryCard = "SELECT * FROM card limit ?,?";
// 更新商品
private static final String UpdateCardSql = "UPDATE card SET CardNumber=?,CardPassword=?,point=?,TimeOutDate=? WHERE CardID=?";
// 企业会员登录后完善企业信息
private static final String addCompanyMessageSql = "insert into companyuserinfo(username,C_Name,C_PostCode,C_Province,C_City,C_Address,C_ConactName,C_Vocation,C_WebSite,C_size,C_Tel,C_BankName,C_Capital) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
// 个人会员登录后完善个人信息
private static final String addPersonalMessageSql = "insert into userinfo(username,uname, sex,birthday, zjlb, zjhm, szsf, city, addr,yzbm,Tel,hompage,qq) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
// 购买点卡后更新会员积分
private static final String RechargeAndAddPointSql = "update user t1 join (select point from user where username = ?) as t2 on t1.point>=0 set t1.point=t1.point+? where t1.username = ?";
// 用户兑换积分
private static final String ExchangeSql = "update user u,card c join (select Point from card where CardNumber=?)as t2 set u.point=u.point+?,c.Point=t2.Point-? where u.username=? and c.CardNumber=?";
// 管理员端展示交易明细
private static final String showBuyProduct = "SELECT count(*) from buyproduct";
// 按条件查询全部交易信息
private static final String queryAllBuyProduct = "SELECT u.username,u.shenfen,p.ProductID,p.Version,p.PType,p.Content,p.bound FROM user u,product p,buyproduct b where b.id=p.id and u.username=b.username limit ?,?";
// 管理员端展示交易明细
private static final String showMemberBuyProduct = "SELECT count(*) from buyproduct where usernme=?";
// 按条件查询个人交易信息
private static final String queryOneMemberBuyProduct = "SELECT p.ProductID,p.Version,p.PType,p.Content,p.bound FROM user u,product p,buyproduct b where b.id=p.id and u.username=b.username and b.username=? limit ?,?";
// 会员购买商品后扣除积分
private static final String updateMemberPoint = "update user set point=point-? where username=?";
// 根据商品编号获得商品id字段
private static final String getProductid = "select id from product where ProductID=?";
// 添加商品
private static final String AddToBuyProduct = "insert into buyproduct (username,id) values (?,?)";
// 用户购买后更新商品表中的已下载次数
private static final String UpdateProductUseNumSql = "UPDATE product SET useNum=useNum+1 WHERE id=?";
// 按积 <SUF>
private static final String allqueryPointSql = "SELECT username,point FROM user limit ?,?";
// 更新会员积分
private static final String updatePointSql = "UPDATE user SET point=? WHERE username=?";
// 下载后更新会员积分
private static final String usePointSql = "update user t1 join (select point from user where username = ?) as t2 on t1.point>=0 set t1.point=t1.point-? where t1.username = ?";
// 查询所有公告
private static final String allAnnouncement = "SELECT count(*) FROM announcement";
// 按条件查询公告
private static final String queryAnnouncement = "SELECT aid,title,people,pubdate FROM announcement limit ?,?";
// 管理员添加公告
private static final String addAnnouncementSql = "insert into announcement (title, people, pubdate, announcement) values (?,?,?,?)";
// 删除公告
private static String deleteAnnouncementSql;
// 查询已购买的点卡数量
private static final String mycard = "SELECT count(*) FROM card where username=?";
// 按条件查询全部已购买点卡
private static final String queryAllMyCard = "select CardNumber,CardPassword,Point,TimeOutDate,AddTime from card where username=? limit ?,?";
// 用户兑换积分时检查输入的卡号和密码是否正确
private static final String CheckCardNumberSql = "select * from card where CardNumber=? and CardPassword=?";
// 查询某张点卡的点数
private static final String selectPointFromCardSql = "select Point from card where CardNumber=?";
//添加评论
private static final String addCommentSql = "insert into comment(aid,username,content,commentTime) values(?,?,?,now())";
public static String getAllcompanymember() {
return allCompanyMember;
}
public static String getAllpersonalmember() {
return allPersonalMember;
}
public static String getQuerypersonalmember() {
return queryPersonalMember;
}
public static String getQuerycompanymember() {
return queryCompanyMember;
}
public static String getDeletePersonalMemberSql() {
return deletePersonalMemberSql;
}
public static String getAddPersonalMemberSql() {
return AddPersonalMemberSql;
}
public static String getCheckUserSql() {
return checkUserSql;
}
public static String getAddMemberSql() {
return addMemberSql;
}
public static String getSelectMaxIdSql() {
return selectMaxIdSql;
}
public static String getAddProductSql() {
return AddProductSql;
}
public static String getProductCount() {
return allProduct;
}
public static String getQueryProduct() {
return queryProduct;
}
public static String getQueryProductByIdSql() {
return queryProductById;
}
public static String getUpdateProductSql() {
return UpdateProductSql;
}
public static String getDeleteProductSql(String ids) {
deleteProductSql = "update product set UserDel=1 where id in(" + ids
+ ")";
return deleteProductSql;
}
public static String getAllMemberCount() {
return allMemberCount;
}
public static String getQueryAllMember() {
return queryAllMember;
}
public static String getUpdateMemberNumberById() {
return updateMemberNumberById;
}
public static String getAddCardSql() {
return AddCardSql;
}
public static String getCardCount() {
return allCard;
}
public static String getQueryCard() {
return queryCard;
}
public static String getUpdateCardSql() {
return UpdateCardSql;
}
public static String getDeleteCardSql(String ids) {
deleteProductSql = "delete from card where CardID in(" + ids + ")";
return deleteProductSql;
}
public static String getAddCompanyMessageSql() {
return addCompanyMessageSql;
}
public static String getAddPersonalMessageSql() {
return addPersonalMessageSql;
}
public static String getQueryBound() {
return queryBound;
}
public static String getUpdateBoundSql() {
return UpdateBoundSql;
}
public static String getRechargeAndAddPointSql() {
return RechargeAndAddPointSql;
}
public static String getExchangeSql() {
return ExchangeSql;
}
public static String getShowBuyProduct() {
return showBuyProduct;
}
public static String getQueryAllBuyProduct() {
return queryAllBuyProduct;
}
public static String getShowMemberBuyProduct() {
return showMemberBuyProduct;
}
public static String getQueryOneMemberBuyProduct() {
return queryOneMemberBuyProduct;
}
public static String getUpdateMemberPoint() {
return updateMemberPoint;
}
public static String getProductid() {
return getProductid;
}
public static String getAddToBuyProduct() {
return AddToBuyProduct;
}
public static String getUpdateProductUsenumSql() {
return UpdateProductUseNumSql;
}
public static String getUpdateUserPoint() {
return UpdateUserPoint;
}
public static String getUpdatePointSql() {
return updatePointSql;
}
public static String getUsePointSql() {
return usePointSql;
}
public static String getAnnouncementCount() {
return allAnnouncement;
}
public static String getQueryAnnouncement() {
return queryAnnouncement;
}
public static String getAddAnnouncementSql() {
return addAnnouncementSql;
}
public static String getDeleteAnnouncementSql(String ids) {
deleteAnnouncementSql = "delete from announcement where aid in(" + ids
+ ")";
return deleteAnnouncementSql;
}
public static String getAllQueryPoint() {
return allqueryPointSql;
}
public static String getDeleteUserinfoSql() {
return deleteUserinfoSql;
}
public static String getDeleteCompanyInfoSql() {
return deleteCompanyinfoSql;
}
public static String getMyCard() {
return mycard;
}
public static String getQueryAllMyCard() {
return queryAllMyCard;
}
public static String getCheckCardNumberSql() {
return CheckCardNumberSql;
}
public static String getSelectPointFromCardSql() {
return selectPointFromCardSql;
}
public static String getUpdateMemberSql() {
return UpdateMemberSql;
}
public static String getAddCommentSql() {
return addCommentSql;
}
}
| 0 | 2,901 | 8 | 3,371 | 9 | 3,219 | 6 | 3,371 | 9 | 4,028 | 15 | false | false | false | false | false | true |
30752_2 | package cn.it.shop.serviceImpl;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import cn.it.shop.model.Forder;
import cn.it.shop.model.Product;
import cn.it.shop.model.Sorder;
import cn.it.shop.service.SorderService;
/*
* 模块自身的业务逻辑
*/
@Service("sorderService")
public class SorderServiceImpl extends BaseServiceImpl<Sorder> implements SorderService {
@Override
public Forder addSorder(Forder forder,Product product,int num) {
boolean isHave = false;
Sorder sorder = productToSorder(product,num);
//判断当前购物项是否重复,如果重复则增加数量即可
if(forder.getSorderSet()!=null){
for(Sorder old: forder.getSorderSet()){
if(old.getProduct().getId().equals(sorder.getProduct().getId())){
//购物项有重复,增加数量即可
old.setNumber(old.getNumber() + sorder.getNumber());
isHave=true;
break;
}
}
}else{
forder.setSorderSet(new HashSet<Sorder>());
}
if(!isHave){
//建立购物项与购物车的关联,此时forder。id为null,但是在入库的时候是先入库购物车,在入库购物项,那时就有forder就有主键
sorder.setForder(forder);
forder.getSorderSet().add(sorder);
}
return forder;
}
@Override
public Sorder productToSorder(Product product,int num) {
Sorder sorder = new Sorder();
sorder.setName(product.getName());
sorder.setNumber(num);
sorder.setPrice(product.getPrice());
sorder.setProduct(product);
return sorder;
}
@Override
public Forder updateSorder(Forder forder,Sorder sorder) {
for(Sorder temp : forder.getSorderSet()){
if(temp.getProduct().getId().equals(sorder.getProduct().getId())){
temp.setNumber(sorder.getNumber());
}
}
return forder;
}
@Override
public List<Object> querySale(int number) {
return sorderDao.querySale(number);
}
}
| 511733119/shop | src/cn/it/shop/serviceImpl/SorderServiceImpl.java | 646 | //购物项有重复,增加数量即可 | line_comment | zh-cn | package cn.it.shop.serviceImpl;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import cn.it.shop.model.Forder;
import cn.it.shop.model.Product;
import cn.it.shop.model.Sorder;
import cn.it.shop.service.SorderService;
/*
* 模块自身的业务逻辑
*/
@Service("sorderService")
public class SorderServiceImpl extends BaseServiceImpl<Sorder> implements SorderService {
@Override
public Forder addSorder(Forder forder,Product product,int num) {
boolean isHave = false;
Sorder sorder = productToSorder(product,num);
//判断当前购物项是否重复,如果重复则增加数量即可
if(forder.getSorderSet()!=null){
for(Sorder old: forder.getSorderSet()){
if(old.getProduct().getId().equals(sorder.getProduct().getId())){
//购物 <SUF>
old.setNumber(old.getNumber() + sorder.getNumber());
isHave=true;
break;
}
}
}else{
forder.setSorderSet(new HashSet<Sorder>());
}
if(!isHave){
//建立购物项与购物车的关联,此时forder。id为null,但是在入库的时候是先入库购物车,在入库购物项,那时就有forder就有主键
sorder.setForder(forder);
forder.getSorderSet().add(sorder);
}
return forder;
}
@Override
public Sorder productToSorder(Product product,int num) {
Sorder sorder = new Sorder();
sorder.setName(product.getName());
sorder.setNumber(num);
sorder.setPrice(product.getPrice());
sorder.setProduct(product);
return sorder;
}
@Override
public Forder updateSorder(Forder forder,Sorder sorder) {
for(Sorder temp : forder.getSorderSet()){
if(temp.getProduct().getId().equals(sorder.getProduct().getId())){
temp.setNumber(sorder.getNumber());
}
}
return forder;
}
@Override
public List<Object> querySale(int number) {
return sorderDao.querySale(number);
}
}
| 0 | 485 | 9 | 646 | 10 | 613 | 9 | 646 | 10 | 810 | 20 | false | false | false | false | false | true |
16217_8 | package com.us.geoip;
import com.fasterxml.jackson.databind.JsonNode;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import java.io.File;
import java.io.IOException;
import com.maxmind.db.Reader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.maxmind.db.Reader.FileMode;
import com.maxmind.db.CHMCache;
/**
* https://github.com/maxmind/MaxMind-DB-Reader-java
* <p>
* Java 通过ip 获取 地理位置
*
* @author yyb
* @time 2019/6/19
*/
public class GeoipTest {
private static volatile DatabaseReader readerIp;
public static void main(String[] args) throws Exception {
// noCache("1.180.164.207");
// haveCache("1.180.164.207");
}
private static void haveCache(String ip) throws IOException {
File database = new File("/Users/yangyibo/test/GeoLite2-City/GeoLite2-City.mmdb");
Reader r = new Reader(database, FileMode.MEMORY_MAPPED, new CHMCache());
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
JsonNode response = r.get(ipAddress);
//国家
System.out.println(response.get("country").get("iso_code"));
System.out.println(response.get("country").get("geoname_id"));
System.out.println(response.get("country").get("names").get("zh-CN"));
//省
System.out.println(response.get("subdivisions").get("iso_code"));
System.out.println(response.get("subdivisions").get("geoname_id"));
System.out.println(response.get("subdivisions").get("names").get("zh-CN"));
//城市
System.out.println(response.get("city").get("iso_code"));
System.out.println(response.get("city").get("geoname_id"));
System.out.println(response.get("city").get("names").get("zh-CN"));
//经纬度
System.out.println(response.get("location").get("latitude"));
System.out.println(response.get("location").get("longitude"));
}
private static String noCache(String ip) throws Exception {
DatabaseReader reader = GeoipTest.getIpInstance();
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
CityResponse response = reader.city(ipAddress);
// 获取国家信息
Country country = response.getCountry();
System.out.println("国家code:" + country.getIsoCode());
System.out.println("国家:" + country.getNames().get("zh-CN"));
// 获取省份
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println("省份code:" + subdivision.getIsoCode());
System.out.println("省份:" + subdivision.getNames().get("zh-CN"));
//城市
City city = response.getCity();
System.out.println("城市code:" + city.getGeoNameId());
System.out.println("城市:" + city.getNames().get("zh-CN"));
// 获取经纬度
Location location = response.getLocation();
System.out.println("经度:" + location.getLatitude());
System.out.println("维度:" + location.getLongitude());
return subdivision.getNames().get("zh-CN") + "--";
}
/**
* 获取数据库连接对象,单例
*
* @return
*/
public static DatabaseReader getIpInstance() throws IOException {
if (readerIp == null) {
synchronized (GeoipTest.class) {
if (readerIp == null) {
File database = new File("/Users/yangyibo/test/GeoLite2-City/GeoLite2-City.mmdb");
readerIp = new DatabaseReader.Builder(database).build();
}
}
}
return readerIp;
}
}
| 527515025/JavaTest | src/main/java/com/us/geoip/GeoipTest.java | 1,036 | // 获取经纬度 | line_comment | zh-cn | package com.us.geoip;
import com.fasterxml.jackson.databind.JsonNode;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import java.io.File;
import java.io.IOException;
import com.maxmind.db.Reader;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.maxmind.db.Reader.FileMode;
import com.maxmind.db.CHMCache;
/**
* https://github.com/maxmind/MaxMind-DB-Reader-java
* <p>
* Java 通过ip 获取 地理位置
*
* @author yyb
* @time 2019/6/19
*/
public class GeoipTest {
private static volatile DatabaseReader readerIp;
public static void main(String[] args) throws Exception {
// noCache("1.180.164.207");
// haveCache("1.180.164.207");
}
private static void haveCache(String ip) throws IOException {
File database = new File("/Users/yangyibo/test/GeoLite2-City/GeoLite2-City.mmdb");
Reader r = new Reader(database, FileMode.MEMORY_MAPPED, new CHMCache());
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
JsonNode response = r.get(ipAddress);
//国家
System.out.println(response.get("country").get("iso_code"));
System.out.println(response.get("country").get("geoname_id"));
System.out.println(response.get("country").get("names").get("zh-CN"));
//省
System.out.println(response.get("subdivisions").get("iso_code"));
System.out.println(response.get("subdivisions").get("geoname_id"));
System.out.println(response.get("subdivisions").get("names").get("zh-CN"));
//城市
System.out.println(response.get("city").get("iso_code"));
System.out.println(response.get("city").get("geoname_id"));
System.out.println(response.get("city").get("names").get("zh-CN"));
//经纬度
System.out.println(response.get("location").get("latitude"));
System.out.println(response.get("location").get("longitude"));
}
private static String noCache(String ip) throws Exception {
DatabaseReader reader = GeoipTest.getIpInstance();
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
CityResponse response = reader.city(ipAddress);
// 获取国家信息
Country country = response.getCountry();
System.out.println("国家code:" + country.getIsoCode());
System.out.println("国家:" + country.getNames().get("zh-CN"));
// 获取省份
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println("省份code:" + subdivision.getIsoCode());
System.out.println("省份:" + subdivision.getNames().get("zh-CN"));
//城市
City city = response.getCity();
System.out.println("城市code:" + city.getGeoNameId());
System.out.println("城市:" + city.getNames().get("zh-CN"));
// 获取 <SUF>
Location location = response.getLocation();
System.out.println("经度:" + location.getLatitude());
System.out.println("维度:" + location.getLongitude());
return subdivision.getNames().get("zh-CN") + "--";
}
/**
* 获取数据库连接对象,单例
*
* @return
*/
public static DatabaseReader getIpInstance() throws IOException {
if (readerIp == null) {
synchronized (GeoipTest.class) {
if (readerIp == null) {
File database = new File("/Users/yangyibo/test/GeoLite2-City/GeoLite2-City.mmdb");
readerIp = new DatabaseReader.Builder(database).build();
}
}
}
return readerIp;
}
}
| 0 | 853 | 4 | 1,036 | 6 | 1,070 | 5 | 1,036 | 6 | 1,225 | 9 | false | false | false | false | false | true |
44152_1 | package com.abel.problem;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by yangyibo on 17/11/7.
*/
public class Client {
public static void main(String[] args) {
//随机生成几个女性
Random rand = new Random();
List<IWomen> womens = new ArrayList();
for (int i = 0; i < 5; i++) {
womens.add(new Women(rand.nextInt(3), "我要去逛街"));
}
IHandler father = new Father();
IHandler husband = new Husband();
IHandler son = new Son();
for (IWomen women : womens) {
if (women.getType() == 0) {
// 未婚少女请示父亲
System.out.println("\n--------女儿向父亲请示-------");
father.HandleMessage(women);
} else if (women.getType() == 1) {
//已婚美女请示老公
System.out.println("\n--------老婆向老公请示 -------");
husband.HandleMessage(women);
} else if (women.getType() == 2) {
//妈妈向儿子
System.out.println("\n--------妈妈向儿子请示-------");
son.HandleMessage(women);
} else {
//暂时什么也不做
}
}
}
}
| 527515025/design_pattern | responsibilityChain/src/main/java/com/abel/problem/Client.java | 365 | //随机生成几个女性 | line_comment | zh-cn | package com.abel.problem;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Created by yangyibo on 17/11/7.
*/
public class Client {
public static void main(String[] args) {
//随机 <SUF>
Random rand = new Random();
List<IWomen> womens = new ArrayList();
for (int i = 0; i < 5; i++) {
womens.add(new Women(rand.nextInt(3), "我要去逛街"));
}
IHandler father = new Father();
IHandler husband = new Husband();
IHandler son = new Son();
for (IWomen women : womens) {
if (women.getType() == 0) {
// 未婚少女请示父亲
System.out.println("\n--------女儿向父亲请示-------");
father.HandleMessage(women);
} else if (women.getType() == 1) {
//已婚美女请示老公
System.out.println("\n--------老婆向老公请示 -------");
husband.HandleMessage(women);
} else if (women.getType() == 2) {
//妈妈向儿子
System.out.println("\n--------妈妈向儿子请示-------");
son.HandleMessage(women);
} else {
//暂时什么也不做
}
}
}
}
| 0 | 287 | 5 | 365 | 6 | 345 | 5 | 365 | 6 | 431 | 13 | false | false | false | false | false | true |
7004_3 | package com.us.example.config;
import com.us.example.service.CustomUserService;
import com.us.example.service.MyFilterSecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
/**
* Created by yangyibo on 17/1/18.
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilterSecurityInterceptor myFilterSecurityInterceptor;
@Bean
UserDetailsService customUserService() { //注册UserDetailsService 的bean
return new CustomUserService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService()); //user Details Service验证
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated() //任何请求,登录后可以访问
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll() //登录页面用户任意访问
.and()
.logout().permitAll(); //注销行为任意访问
http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class)
.csrf().disable();
}
}
| 527515025/springBoot | springboot-springSecurity3/src/main/java/com/us/example/config/WebSecurityConfig.java | 423 | //任何请求,登录后可以访问 | line_comment | zh-cn | package com.us.example.config;
import com.us.example.service.CustomUserService;
import com.us.example.service.MyFilterSecurityInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
/**
* Created by yangyibo on 17/1/18.
*/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private MyFilterSecurityInterceptor myFilterSecurityInterceptor;
@Bean
UserDetailsService customUserService() { //注册UserDetailsService 的bean
return new CustomUserService();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(customUserService()); //user Details Service验证
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated() //任何 <SUF>
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.permitAll() //登录页面用户任意访问
.and()
.logout().permitAll(); //注销行为任意访问
http.addFilterBefore(myFilterSecurityInterceptor, FilterSecurityInterceptor.class)
.csrf().disable();
}
}
| 0 | 338 | 8 | 423 | 8 | 436 | 8 | 423 | 8 | 511 | 15 | false | false | false | false | false | true |
65851_4 | package com.study.dto.output;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author 大脑补丁
* @project cne-power-operation-facade
* @description: 导出Excel:申请单
* @create 2020-03-26 15:26
*/
@Data
public class SendBillOutput implements Serializable {
// 客户名称
private String customerName;
// 是否一般纳税人
private String isGeneralTaxpayer;
// 税号
private String taxNumber;
// 客户公司地址及电话
private String addressAndPhone;
// 开户银行和账号
private String bankAndAccount;
// 信息列表
private List<StationBillOutput> stationBillList;
// 合计栏
private StationAmountOutput stationAmount;
}
| 541211190/freemarker-excel | src/main/java/com/study/dto/output/SendBillOutput.java | 225 | // 开户银行和账号 | line_comment | zh-cn | package com.study.dto.output;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @author 大脑补丁
* @project cne-power-operation-facade
* @description: 导出Excel:申请单
* @create 2020-03-26 15:26
*/
@Data
public class SendBillOutput implements Serializable {
// 客户名称
private String customerName;
// 是否一般纳税人
private String isGeneralTaxpayer;
// 税号
private String taxNumber;
// 客户公司地址及电话
private String addressAndPhone;
// 开户 <SUF>
private String bankAndAccount;
// 信息列表
private List<StationBillOutput> stationBillList;
// 合计栏
private StationAmountOutput stationAmount;
}
| 0 | 184 | 6 | 225 | 8 | 208 | 6 | 225 | 8 | 267 | 13 | false | false | false | false | false | true |
31932_33 | /**
* Bp神经网络
* reference https://www.cnblogs.com/hesi/p/7218602.html
*/
public class Bp {
private double[] hide1_x; // 输入层即第一层隐含层的输入; hide1_x[数据的特征数目+1],hide1_w[0]为1
private double[][] hide1_w; // 隐含层权值,hide1_w[本层节点数目][数据的特征数目+1];hide_w[0][0]为偏置量
private double[] hide1_errors; // 隐含层的误差,hide1_errors[节点个数]
private double[] hide1_theta; // 隐含层的阈值,hide1_errors[节点个数]
private double[] out_x; // 输出层的输入值即第二层隐含层的输出 out_x[上一层的节点数+1], out_x[0]为1
private double[][] out_w; // 输出层的权值,hide1_w[节点的数目][上一层的节点数目+1], out_w[0][0]为偏置量
private double[] out_errors; // 输出层的误差,hide1_error[节点个数]
private double[] pre_out_errors; // 上一次输出层的误差,hide1_error[节点个数]
private double[] out_theta; // 输出层的阈值,out_node[节点个数]
private double[] target; // 目标值,target[输出层的节点个数]
private double MS_error; // 计算均方误差
private double rate; // 学习速率
Bp(int input_node, int hide1_node, int out_node, double rate) {
super();
// 输入层即第一层隐含层的输入
hide1_x = new double[input_node + 1];
// 第一层隐含层
hide1_w = new double[hide1_node][input_node + 1];
hide1_errors = new double[hide1_node];
hide1_theta = new double[hide1_node];
// 输出层
out_x = new double[hide1_node + 1];
out_w = new double[out_node][hide1_node + 1];
out_errors = new double[out_node];
out_theta = new double[out_node];
pre_out_errors = new double[out_node];
// 输出层
target = new double[out_node];
// 均方误差为0
MS_error = 0;
// 学习速率
this.rate = rate;
init_weight();// 1.初始化网络的权值
init_theta(); // 2.初始化网络的阈值
}
/**
* 初始化阈值
*/
private void init_theta() {
set_theta(hide1_theta);
set_theta(out_theta);
}
/**
* 初始化阈值
*
* @param theta 阈值
*/
private void set_theta(double[] theta) {
for (int i = 0; i < theta.length; i++) {
theta[i] = Math.random();
}
}
/**
* 初始化权值
*/
private void init_weight() {
set_weight(hide1_w);
set_weight(out_w);
}
/**
* 权值初始化为0
*
* @param weight 传入初始权值
*/
private void set_weight(double[][] weight) {
for (int i = 0; i < weight.length; i++) {
for (int j = 0; j < weight[i].length; j++) {
weight[i][j] = Math.random();
}
}
}
/**
* 传入原始数据
*
* @param Data 传入数据
*/
private void setHide1_x(double[] Data) {
if (Data.length != hide1_x.length - 1) {
throw new IllegalArgumentException("数据大小与输出层节点不匹配");
}
System.arraycopy(Data, 0, hide1_x, 1, Data.length);
hide1_x[0] = 1.0;
}
/**
* 设置目标数据
*
* @param target 目标数据
*/
private void setTarget(double[] target) {
this.target = target;
}
public void train(double[] TrainData, double[] target) {
// 2.1.导入训练数据集和目标值
setHide1_x(TrainData);
setTarget(target);
// 2.2.向前传播得到输出值
double[] output = new double[out_w.length + 1];
forword(hide1_x, output);
// 2.3.反向传播
backpropagation(output);
}
/**
* 反向传播过程
*
* @param output 预测结果
*/
private void backpropagation(double[] output) {
// 2.3.1.获取输出层的误差;
get_out_error(output, target, out_errors);
// 2.3.2.获取隐含层的误差;
get_hide_error(out_errors, out_w, out_x, hide1_errors);
// 2.3.3.更新输入层到隐含层的权值;
update_weight(hide1_errors, hide1_w, hide1_x);
// 2.3.4 更新隐含层的阈值;
update_theta(hide1_errors, hide1_theta);
// 2.3.5.更新隐含层到输出层的权值;
update_weight(out_errors, out_w, out_x);
// 2.3.6.更新输出层的阈值;
update_theta(out_errors, out_theta);
}
/**
* 新的阈值=原阈值+(-学习速率×该节点的误差)
*
* @param hide1_errors 该层误差
* @param hide1_theta 原阈值
*/
private void update_theta(double[] hide1_errors, double[] hide1_theta) {
double newTheta = 0.0;
for (int i = 0; i < hide1_errors.length; i++) {
newTheta = - rate * hide1_errors[i];
hide1_theta[i] += newTheta;
}
}
/**
* 新的权值=原权值+学习速率×该节点的误差×激励函数的导函数的值
*
* @param error 该层误差
* @param weight 原来权重
* @param input 上层输出
*/
private void update_weight(double[] error, double[][] weight, double[] input) {
double newWeight = 0.0;
for (int i = 0; i < weight.length; i++) {
for (int j = 0; j < weight[i].length; j++) {
newWeight = rate * error[i] * input[j];
weight[i][j] = weight[i][j] + newWeight;
}
}
}
/**
* 获取隐含层的误差,西瓜书eh
*
* @param NextLayorError 下一层的误差
* @param NextWeight 下一层的权值
* @param NextOutput 下一层的输入
* @param error 本层误差数组
*/
private void get_hide_error(double[] NextLayorError, double[][] NextWeight, double[] NextOutput, double[] error) {
for (int i = 0; i < error.length; i++) {
double sum = 0;
for (int j = 0; j < NextWeight.length; j++) {
sum += NextWeight[j][i + 1] * NextLayorError[j];
}
error[i] = sum * NextOutput[i + 1] * (1d - NextOutput[i + 1]);
}
}
/**
* 获取输出层的误差,西瓜树gj
*
* @param output 预测输出值
* @param target 目标值
* @param out_errors 输出层误差
*/
private void get_out_error(double[] output, double[] target, double[] out_errors) {
for (int i = 0; i < target.length; i++) {
pre_out_errors[i] = out_errors[i];
out_errors[i] = (target[i] - output[i + 1]) * output[i + 1] * (1d - output[i + 1]);
}
}
/**
* 向前传播
*
* @param input 输入层输入
* @param output 输出层输出
*/
private void forword(double[] input, double[] output) {
// 2.2.1.获取隐含层的输出
get_net_out(input, hide1_w, hide1_theta, out_x);
// 2.2.2.获取输出层的输出
get_net_out(out_x, out_w, out_theta, output);
}
/**
* 获取网络层的输出
*
* @param input 输入矩阵
* @param weight 权值矩阵
* @param theta 阈值
* @param output 接受网络层的输出数据
*/
private void get_net_out(double[] input, double[][] weight, double[] theta, double[] output) {
output[0] = 1d;
for (int i = 0; i < weight.length; i++) {
output[i + 1] = get_node_put(input, weight[i], theta[i]);
}
}
/**
* 获取单个节点的输出
*
* @param input 输入矩阵
* @param weight 权值
* @param theta 阈值
* @return 输出值
*/
private double get_node_put(double[] input, double[] weight, double theta) {
double z = 0d;
for (int i = 0; i < input.length; i++) {
z += input[i] * weight[i];
}
// 激励函数
return sigmoid(z + theta);
}
/**
* sigmoid激励函数
*
* @param x 输入
* @return 输出
*/
private double sigmoid(double x) {
return 1d / (1d + Math.exp(-x));
}
/**
* 预测函数
*
* @param data 预测输入
* @param output 预测输出
*/
public void predict(double[] data, double[] output, double[] target) {
double[] out_y = new double[out_w.length + 1];
setHide1_x(data);
forword(hide1_x, out_y);
System.arraycopy(out_y, 1, output, 0, output.length);
calc_error(target, output);
}
/**
* 计算前后两次训练的误差
*/
private void calc_error(double[] target, double[] output) {
for (int i = 0; i < target.length; i++) {
MS_error += 0.5 * (Math.pow(target[i], 2) - Math.pow(output[i], 2));
}
}
/**
* 返回均方误差
*
* @return 均方误差
*/
public double getMSError() {
return MS_error;
}
/**
* 计算前后两次训练误差
*
* @return 返回训练误差的绝对值
*/
public double CalcErrDiff() {
double min = 10000;
for (int i = 0; i < pre_out_errors.length; i++) {
double diff = out_errors[i] - pre_out_errors[i];
min = min > diff ? diff : min;
}
return Math.abs(min);
}
/**
* 返回隐含层第一层的权重
*
* @return 权重矩阵
*/
public double[][] getWeightHide1() {
return hide1_w;
}
/**
* 返回输出层的权重
*
* @return 权重矩阵
*/
public double[][] getWeightOutput() {
return out_w;
}
/**
* 返回隐层的阈值
* @return 阈值
*/
public double[] getThetaHide1(){
return hide1_theta;
}
/**
* 返回输出层的阈值
* @return 阈值
*/
public double[] getThetaOutput(){
return out_theta;
}
}
| 543877815/uestc_Internet_plus_course_project | machine-learning/src/Bp.java | 3,030 | // 2.3.3.更新输入层到隐含层的权值; | line_comment | zh-cn | /**
* Bp神经网络
* reference https://www.cnblogs.com/hesi/p/7218602.html
*/
public class Bp {
private double[] hide1_x; // 输入层即第一层隐含层的输入; hide1_x[数据的特征数目+1],hide1_w[0]为1
private double[][] hide1_w; // 隐含层权值,hide1_w[本层节点数目][数据的特征数目+1];hide_w[0][0]为偏置量
private double[] hide1_errors; // 隐含层的误差,hide1_errors[节点个数]
private double[] hide1_theta; // 隐含层的阈值,hide1_errors[节点个数]
private double[] out_x; // 输出层的输入值即第二层隐含层的输出 out_x[上一层的节点数+1], out_x[0]为1
private double[][] out_w; // 输出层的权值,hide1_w[节点的数目][上一层的节点数目+1], out_w[0][0]为偏置量
private double[] out_errors; // 输出层的误差,hide1_error[节点个数]
private double[] pre_out_errors; // 上一次输出层的误差,hide1_error[节点个数]
private double[] out_theta; // 输出层的阈值,out_node[节点个数]
private double[] target; // 目标值,target[输出层的节点个数]
private double MS_error; // 计算均方误差
private double rate; // 学习速率
Bp(int input_node, int hide1_node, int out_node, double rate) {
super();
// 输入层即第一层隐含层的输入
hide1_x = new double[input_node + 1];
// 第一层隐含层
hide1_w = new double[hide1_node][input_node + 1];
hide1_errors = new double[hide1_node];
hide1_theta = new double[hide1_node];
// 输出层
out_x = new double[hide1_node + 1];
out_w = new double[out_node][hide1_node + 1];
out_errors = new double[out_node];
out_theta = new double[out_node];
pre_out_errors = new double[out_node];
// 输出层
target = new double[out_node];
// 均方误差为0
MS_error = 0;
// 学习速率
this.rate = rate;
init_weight();// 1.初始化网络的权值
init_theta(); // 2.初始化网络的阈值
}
/**
* 初始化阈值
*/
private void init_theta() {
set_theta(hide1_theta);
set_theta(out_theta);
}
/**
* 初始化阈值
*
* @param theta 阈值
*/
private void set_theta(double[] theta) {
for (int i = 0; i < theta.length; i++) {
theta[i] = Math.random();
}
}
/**
* 初始化权值
*/
private void init_weight() {
set_weight(hide1_w);
set_weight(out_w);
}
/**
* 权值初始化为0
*
* @param weight 传入初始权值
*/
private void set_weight(double[][] weight) {
for (int i = 0; i < weight.length; i++) {
for (int j = 0; j < weight[i].length; j++) {
weight[i][j] = Math.random();
}
}
}
/**
* 传入原始数据
*
* @param Data 传入数据
*/
private void setHide1_x(double[] Data) {
if (Data.length != hide1_x.length - 1) {
throw new IllegalArgumentException("数据大小与输出层节点不匹配");
}
System.arraycopy(Data, 0, hide1_x, 1, Data.length);
hide1_x[0] = 1.0;
}
/**
* 设置目标数据
*
* @param target 目标数据
*/
private void setTarget(double[] target) {
this.target = target;
}
public void train(double[] TrainData, double[] target) {
// 2.1.导入训练数据集和目标值
setHide1_x(TrainData);
setTarget(target);
// 2.2.向前传播得到输出值
double[] output = new double[out_w.length + 1];
forword(hide1_x, output);
// 2.3.反向传播
backpropagation(output);
}
/**
* 反向传播过程
*
* @param output 预测结果
*/
private void backpropagation(double[] output) {
// 2.3.1.获取输出层的误差;
get_out_error(output, target, out_errors);
// 2.3.2.获取隐含层的误差;
get_hide_error(out_errors, out_w, out_x, hide1_errors);
// 2. <SUF>
update_weight(hide1_errors, hide1_w, hide1_x);
// 2.3.4 更新隐含层的阈值;
update_theta(hide1_errors, hide1_theta);
// 2.3.5.更新隐含层到输出层的权值;
update_weight(out_errors, out_w, out_x);
// 2.3.6.更新输出层的阈值;
update_theta(out_errors, out_theta);
}
/**
* 新的阈值=原阈值+(-学习速率×该节点的误差)
*
* @param hide1_errors 该层误差
* @param hide1_theta 原阈值
*/
private void update_theta(double[] hide1_errors, double[] hide1_theta) {
double newTheta = 0.0;
for (int i = 0; i < hide1_errors.length; i++) {
newTheta = - rate * hide1_errors[i];
hide1_theta[i] += newTheta;
}
}
/**
* 新的权值=原权值+学习速率×该节点的误差×激励函数的导函数的值
*
* @param error 该层误差
* @param weight 原来权重
* @param input 上层输出
*/
private void update_weight(double[] error, double[][] weight, double[] input) {
double newWeight = 0.0;
for (int i = 0; i < weight.length; i++) {
for (int j = 0; j < weight[i].length; j++) {
newWeight = rate * error[i] * input[j];
weight[i][j] = weight[i][j] + newWeight;
}
}
}
/**
* 获取隐含层的误差,西瓜书eh
*
* @param NextLayorError 下一层的误差
* @param NextWeight 下一层的权值
* @param NextOutput 下一层的输入
* @param error 本层误差数组
*/
private void get_hide_error(double[] NextLayorError, double[][] NextWeight, double[] NextOutput, double[] error) {
for (int i = 0; i < error.length; i++) {
double sum = 0;
for (int j = 0; j < NextWeight.length; j++) {
sum += NextWeight[j][i + 1] * NextLayorError[j];
}
error[i] = sum * NextOutput[i + 1] * (1d - NextOutput[i + 1]);
}
}
/**
* 获取输出层的误差,西瓜树gj
*
* @param output 预测输出值
* @param target 目标值
* @param out_errors 输出层误差
*/
private void get_out_error(double[] output, double[] target, double[] out_errors) {
for (int i = 0; i < target.length; i++) {
pre_out_errors[i] = out_errors[i];
out_errors[i] = (target[i] - output[i + 1]) * output[i + 1] * (1d - output[i + 1]);
}
}
/**
* 向前传播
*
* @param input 输入层输入
* @param output 输出层输出
*/
private void forword(double[] input, double[] output) {
// 2.2.1.获取隐含层的输出
get_net_out(input, hide1_w, hide1_theta, out_x);
// 2.2.2.获取输出层的输出
get_net_out(out_x, out_w, out_theta, output);
}
/**
* 获取网络层的输出
*
* @param input 输入矩阵
* @param weight 权值矩阵
* @param theta 阈值
* @param output 接受网络层的输出数据
*/
private void get_net_out(double[] input, double[][] weight, double[] theta, double[] output) {
output[0] = 1d;
for (int i = 0; i < weight.length; i++) {
output[i + 1] = get_node_put(input, weight[i], theta[i]);
}
}
/**
* 获取单个节点的输出
*
* @param input 输入矩阵
* @param weight 权值
* @param theta 阈值
* @return 输出值
*/
private double get_node_put(double[] input, double[] weight, double theta) {
double z = 0d;
for (int i = 0; i < input.length; i++) {
z += input[i] * weight[i];
}
// 激励函数
return sigmoid(z + theta);
}
/**
* sigmoid激励函数
*
* @param x 输入
* @return 输出
*/
private double sigmoid(double x) {
return 1d / (1d + Math.exp(-x));
}
/**
* 预测函数
*
* @param data 预测输入
* @param output 预测输出
*/
public void predict(double[] data, double[] output, double[] target) {
double[] out_y = new double[out_w.length + 1];
setHide1_x(data);
forword(hide1_x, out_y);
System.arraycopy(out_y, 1, output, 0, output.length);
calc_error(target, output);
}
/**
* 计算前后两次训练的误差
*/
private void calc_error(double[] target, double[] output) {
for (int i = 0; i < target.length; i++) {
MS_error += 0.5 * (Math.pow(target[i], 2) - Math.pow(output[i], 2));
}
}
/**
* 返回均方误差
*
* @return 均方误差
*/
public double getMSError() {
return MS_error;
}
/**
* 计算前后两次训练误差
*
* @return 返回训练误差的绝对值
*/
public double CalcErrDiff() {
double min = 10000;
for (int i = 0; i < pre_out_errors.length; i++) {
double diff = out_errors[i] - pre_out_errors[i];
min = min > diff ? diff : min;
}
return Math.abs(min);
}
/**
* 返回隐含层第一层的权重
*
* @return 权重矩阵
*/
public double[][] getWeightHide1() {
return hide1_w;
}
/**
* 返回输出层的权重
*
* @return 权重矩阵
*/
public double[][] getWeightOutput() {
return out_w;
}
/**
* 返回隐层的阈值
* @return 阈值
*/
public double[] getThetaHide1(){
return hide1_theta;
}
/**
* 返回输出层的阈值
* @return 阈值
*/
public double[] getThetaOutput(){
return out_theta;
}
}
| 0 | 2,798 | 19 | 3,030 | 19 | 3,207 | 18 | 3,030 | 19 | 4,005 | 31 | false | false | false | false | false | true |
54581_11 | package com.opendata.common.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @title KeywordFilter
* @description TODO
* @author
* @date 2014-4-17
* @version 1.0
*/
public class KeywordFilter {
/** 敏感词集合
* {法={isEnd=0, 轮={isEnd=1}}, 中={isEnd=0, 国={isEnd=0, 人={isEnd=1}, 男={isEnd=0, 人={isEnd=1}}}}}
* */
private HashMap keysMap = new HashMap();
/**
* 添加敏感词
* @param keywords
*/
public void addKeywords(List<String> keywords) {
for (int i = 0; i < keywords.size(); i++) {
String key = keywords.get(i).trim();
HashMap nowhash = keysMap;//初始从最外层遍历
for (int j = 0; j < key.length(); j++) {
char word = key.charAt(j);
Object wordMap = nowhash.get(word);
if (wordMap != null) {
nowhash = (HashMap) wordMap;
} else {
HashMap<String, String> newWordHash = new HashMap<String, String>();
newWordHash.put("isEnd", "0");
nowhash.put(word, newWordHash);
nowhash = newWordHash;
}
if (j == key.length() - 1) {
nowhash.put("isEnd", "1");
}
}
}
}
/**
* 检查一个字符串从begin位置起开始是否有keyword符合,
* 如果没有,则返回0
* 如果有符合的keyword值,继续遍历,直至遇到isEnd = 1,返回匹配的keyword的长度,
*/
private int checkKeyWords(String txt, int begin) {
HashMap nowhash = keysMap;
int res = 0;
for (int i = begin; i < txt.length(); i++) {
char word = txt.charAt(i);
Object wordMap = nowhash.get(word);//得到该字符对应的HashMap
if (wordMap == null) {
return 0;//如果该字符没有对应的HashMap,return 0
}
res++;//如果该字符对应的HashMap不为null,说明匹配到了一个字符,+1
nowhash = (HashMap) wordMap;//将遍历的HashMap指向该字符对应的HashMap
if (((String) nowhash.get("isEnd")).equals("1")) {//如果该字符为敏感词的结束字符,直接返回
return res;
} else {
continue;
}
}
return res;
}
/**
* 判断txt中是否有关键字
*/
public boolean isContentKeyWords(String txt) {
for (int i = 0; i < txt.length(); i++) {
int len = checkKeyWords(txt, i);
if (len > 0) {
return true;
}
}
return false;
}
/**
* 返回txt中关键字的列表
*/
public List<String> getTxtKeyWords(String txt) {
List<String> list = new ArrayList<String>();
int l = txt.length();
for (int i = 0; i < l;) {
int len = checkKeyWords(txt, i);
if (len > 0) {
String tt = txt.substring(i, i + len);
list.add(tt);
i += len;
} else {
i++;
}
}
return list;
}
/**
* 初始化敏感词列表
* */
public void initfiltercode() {
List<String> keywords = new ArrayList<String>();
keywords.add("中国人");
keywords.add("中国男人");
keywords.add("法轮");
this.addKeywords(keywords);
}
public static void main(String[] args) throws IOException {
KeywordFilter filter = new KeywordFilter();
filter.initfiltercode();
String txt = "哈哈,反倒是 法轮热舞功,中国人,";
boolean boo = filter.isContentKeyWords(txt);
System.out.println(boo);
List<String> set = filter.getTxtKeyWords(txt);
System.out.println("包含的敏感词如下:" + set);
}
} | 545473750/zswxsqxt | src/main/java/com/opendata/common/util/KeywordFilter.java | 1,031 | /**
* 返回txt中关键字的列表
*/ | block_comment | zh-cn | package com.opendata.common.util;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @title KeywordFilter
* @description TODO
* @author
* @date 2014-4-17
* @version 1.0
*/
public class KeywordFilter {
/** 敏感词集合
* {法={isEnd=0, 轮={isEnd=1}}, 中={isEnd=0, 国={isEnd=0, 人={isEnd=1}, 男={isEnd=0, 人={isEnd=1}}}}}
* */
private HashMap keysMap = new HashMap();
/**
* 添加敏感词
* @param keywords
*/
public void addKeywords(List<String> keywords) {
for (int i = 0; i < keywords.size(); i++) {
String key = keywords.get(i).trim();
HashMap nowhash = keysMap;//初始从最外层遍历
for (int j = 0; j < key.length(); j++) {
char word = key.charAt(j);
Object wordMap = nowhash.get(word);
if (wordMap != null) {
nowhash = (HashMap) wordMap;
} else {
HashMap<String, String> newWordHash = new HashMap<String, String>();
newWordHash.put("isEnd", "0");
nowhash.put(word, newWordHash);
nowhash = newWordHash;
}
if (j == key.length() - 1) {
nowhash.put("isEnd", "1");
}
}
}
}
/**
* 检查一个字符串从begin位置起开始是否有keyword符合,
* 如果没有,则返回0
* 如果有符合的keyword值,继续遍历,直至遇到isEnd = 1,返回匹配的keyword的长度,
*/
private int checkKeyWords(String txt, int begin) {
HashMap nowhash = keysMap;
int res = 0;
for (int i = begin; i < txt.length(); i++) {
char word = txt.charAt(i);
Object wordMap = nowhash.get(word);//得到该字符对应的HashMap
if (wordMap == null) {
return 0;//如果该字符没有对应的HashMap,return 0
}
res++;//如果该字符对应的HashMap不为null,说明匹配到了一个字符,+1
nowhash = (HashMap) wordMap;//将遍历的HashMap指向该字符对应的HashMap
if (((String) nowhash.get("isEnd")).equals("1")) {//如果该字符为敏感词的结束字符,直接返回
return res;
} else {
continue;
}
}
return res;
}
/**
* 判断txt中是否有关键字
*/
public boolean isContentKeyWords(String txt) {
for (int i = 0; i < txt.length(); i++) {
int len = checkKeyWords(txt, i);
if (len > 0) {
return true;
}
}
return false;
}
/**
* 返回t <SUF>*/
public List<String> getTxtKeyWords(String txt) {
List<String> list = new ArrayList<String>();
int l = txt.length();
for (int i = 0; i < l;) {
int len = checkKeyWords(txt, i);
if (len > 0) {
String tt = txt.substring(i, i + len);
list.add(tt);
i += len;
} else {
i++;
}
}
return list;
}
/**
* 初始化敏感词列表
* */
public void initfiltercode() {
List<String> keywords = new ArrayList<String>();
keywords.add("中国人");
keywords.add("中国男人");
keywords.add("法轮");
this.addKeywords(keywords);
}
public static void main(String[] args) throws IOException {
KeywordFilter filter = new KeywordFilter();
filter.initfiltercode();
String txt = "哈哈,反倒是 法轮热舞功,中国人,";
boolean boo = filter.isContentKeyWords(txt);
System.out.println(boo);
List<String> set = filter.getTxtKeyWords(txt);
System.out.println("包含的敏感词如下:" + set);
}
} | 0 | 955 | 13 | 1,026 | 11 | 1,096 | 15 | 1,026 | 11 | 1,329 | 22 | false | false | false | false | false | true |
54214_21 | package net.cgt.weixin;
/**
* Static constants for this package.<br>
* 静态常量
*
* @author lijian
* @date 2014-11-22
*/
public interface Constants {
/** SharedPreferences 文件名 **/
String SHARED_PREFERENCE_NAME = "client_preferences";
/********************************** 用户登陆管理 ***************************************************************************************************/
/** 用户最后登陆时间 **/
String LAST_TIME = "LAST_TIME";
/** 一个月内自动登陆 : 60 * 60 * 24 * 30 = 2592000 **/
long AUTO_LOGIN = 2592000;
/** 记录上次退出时页面 **/
String PAGENUMBER = "PAGENUMBER";
/********************************** 偏好设置 ***************************************************************************************************/
/** 回调Activity的包名 **/
String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME";
/** 回调Activity的全类名 **/
String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME";
/** XMPP密钥 **/
String API_KEY = "API_KEY";
/** 版本号 **/
String VERSION = "VERSION";
/** XMPP的IP **/
String XMPP_HOST = "XMPP_HOST";
/** XMPP的端口 **/
String XMPP_PORT = "XMPP_PORT";
/** XMPP的用户名 **/
String XMPP_USERNAME = "XMPP_USERNAME";
/** XMPP的密码 **/
String XMPP_PASSWORD = "XMPP_PASSWORD";
// String USER_KEY = "USER_KEY";
/** 设备ID(手机*#06#) **/
String DEVICE_ID = "DEVICE_ID";
/** 模拟器ID **/
String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID";
/** 通知的logo图片 **/
String NOTIFICATION_ICON = "NOTIFICATION_ICON";
/** 是否显示推送的通知 **/
String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED";
/** 当接到推送通知-->是否播放通知声音 **/
String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED";
/** 当接到推送通知-->是否震动手机 **/
String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED";
/** 当接到推送通知-->是否显示吐司 **/
String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED";
/********************************** 通知 ***************************************************************************************************/
/** 通知的ID **/
String NOTIFICATION_ID = "NOTIFICATION_ID";
/** 通知的密钥 **/
String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY";
/** 通知的标题 **/
String NOTIFICATION_TITLE = "NOTIFICATION_TITLE";
/** 通知的正文 **/
String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE";
/** 通知的Url **/
String NOTIFICATION_URI = "NOTIFICATION_URI";
/********************************** intent动作 ***************************************************************************************************/
/** 显示通知 **/
String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION";
/** 通知被点击 **/
String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED";
/** 清除通知 **/
String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED";
}
| 54cgt/weixin | 微信/src/net/cgt/weixin/Constants.java | 856 | /** 当接到推送通知-->是否震动手机 **/ | block_comment | zh-cn | package net.cgt.weixin;
/**
* Static constants for this package.<br>
* 静态常量
*
* @author lijian
* @date 2014-11-22
*/
public interface Constants {
/** SharedPreferences 文件名 **/
String SHARED_PREFERENCE_NAME = "client_preferences";
/********************************** 用户登陆管理 ***************************************************************************************************/
/** 用户最后登陆时间 **/
String LAST_TIME = "LAST_TIME";
/** 一个月内自动登陆 : 60 * 60 * 24 * 30 = 2592000 **/
long AUTO_LOGIN = 2592000;
/** 记录上次退出时页面 **/
String PAGENUMBER = "PAGENUMBER";
/********************************** 偏好设置 ***************************************************************************************************/
/** 回调Activity的包名 **/
String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME";
/** 回调Activity的全类名 **/
String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME";
/** XMPP密钥 **/
String API_KEY = "API_KEY";
/** 版本号 **/
String VERSION = "VERSION";
/** XMPP的IP **/
String XMPP_HOST = "XMPP_HOST";
/** XMPP的端口 **/
String XMPP_PORT = "XMPP_PORT";
/** XMPP的用户名 **/
String XMPP_USERNAME = "XMPP_USERNAME";
/** XMPP的密码 **/
String XMPP_PASSWORD = "XMPP_PASSWORD";
// String USER_KEY = "USER_KEY";
/** 设备ID(手机*#06#) **/
String DEVICE_ID = "DEVICE_ID";
/** 模拟器ID **/
String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID";
/** 通知的logo图片 **/
String NOTIFICATION_ICON = "NOTIFICATION_ICON";
/** 是否显示推送的通知 **/
String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED";
/** 当接到推送通知-->是否播放通知声音 **/
String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED";
/** 当接到 <SUF>*/
String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED";
/** 当接到推送通知-->是否显示吐司 **/
String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED";
/********************************** 通知 ***************************************************************************************************/
/** 通知的ID **/
String NOTIFICATION_ID = "NOTIFICATION_ID";
/** 通知的密钥 **/
String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY";
/** 通知的标题 **/
String NOTIFICATION_TITLE = "NOTIFICATION_TITLE";
/** 通知的正文 **/
String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE";
/** 通知的Url **/
String NOTIFICATION_URI = "NOTIFICATION_URI";
/********************************** intent动作 ***************************************************************************************************/
/** 显示通知 **/
String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION";
/** 通知被点击 **/
String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED";
/** 清除通知 **/
String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED";
}
| 0 | 645 | 11 | 855 | 14 | 815 | 11 | 855 | 14 | 1,179 | 22 | false | false | false | false | false | true |
28765_18 | package Utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import domain.Student;
import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by Cheung on 2017/12/19.
*
* Apache POI操作Excel对象
* HSSF:操作Excel 2007之前版本(.xls)格式,生成的EXCEL不经过压缩直接导出
* XSSF:操作Excel 2007及之后版本(.xlsx)格式,内存占用高于HSSF
* SXSSF:从POI3.8 beta3开始支持,基于XSSF,低内存占用,专门处理大数据量(建议)。
*
* 注意:
* 值得注意的是SXSSFWorkbook只能写(导出)不能读(导入)
*
* 说明:
* .xls格式的excel(最大行数65536行,最大列数256列)
* .xlsx格式的excel(最大行数1048576行,最大列数16384列)
*/
public class ExcelUtil {
public static final String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日";// 默认日期格式
public static final int DEFAULT_COLUMN_WIDTH = 17;// 默认列宽
/**
* 导出Excel(.xlsx)格式
* @param titleList 表格头信息集合
* @param dataArray 数据数组
* @param os 文件输出流
*/
public static void exportExcel(ArrayList<LinkedHashMap> titleList, JSONArray dataArray, OutputStream os) {
String datePattern = DEFAULT_DATE_PATTERN;
int minBytes = DEFAULT_COLUMN_WIDTH;
/**
* 声明一个工作薄
*/
SXSSFWorkbook workbook = new SXSSFWorkbook(1000);// 大于1000行时会把之前的行写入硬盘
workbook.setCompressTempFiles(true);
// 表头1样式
CellStyle title1Style = workbook.createCellStyle();
title1Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中
title1Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
Font titleFont = workbook.createFont();// 字体
titleFont.setFontHeightInPoints((short) 20);
titleFont.setBoldweight((short) 700);
title1Style.setFont(titleFont);
// 表头2样式
CellStyle title2Style = workbook.createCellStyle();
title2Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
title2Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
title2Style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
title2Style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右
title2Style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下
title2Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左
Font title2Font = workbook.createFont();
title2Font.setUnderline((byte) 1);
title2Font.setColor(HSSFColor.BLUE.index);
title2Style.setFont(title2Font);
// head样式
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
headerStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);// 设置颜色
headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 前景色纯色填充
headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Font headerFont = workbook.createFont();
headerFont.setFontHeightInPoints((short) 12);
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerStyle.setFont(headerFont);
// 单元格样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Font cellFont = workbook.createFont();
cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
cellStyle.setFont(cellFont);
String title1 = (String) titleList.get(0).get("title1");
String title2 = (String) titleList.get(0).get("title2");
LinkedHashMap<String, String> headMap = titleList.get(1);
/**
* 生成一个(带名称)表格
*/
SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet(title1);
sheet.createFreezePane(0, 3, 0, 3);// (单独)冻结前三行
/**
* 生成head相关信息+设置每列宽度
*/
int[] colWidthArr = new int[headMap.size()];// 列宽数组
String[] headKeyArr = new String[headMap.size()];// headKey数组
String[] headValArr = new String[headMap.size()];// headVal数组
int i = 0;
for (Map.Entry<String, String> entry : headMap.entrySet()) {
headKeyArr[i] = entry.getKey();
headValArr[i] = entry.getValue();
int bytes = headKeyArr[i].getBytes().length;
colWidthArr[i] = bytes < minBytes ? minBytes : bytes;
sheet.setColumnWidth(i, colWidthArr[i] * 256);// 设置列宽
i++;
}
/**
* 遍历数据集合,产生Excel行数据
*/
int rowIndex = 0;
for (Object obj : dataArray) {
// 生成title+head信息
if (rowIndex == 0) {
SXSSFRow title1Row = (SXSSFRow) sheet.createRow(0);// title1行
title1Row.createCell(0).setCellValue(title1);
title1Row.getCell(0).setCellStyle(title1Style);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));// 合并单元格
SXSSFRow title2Row = (SXSSFRow) sheet.createRow(1);// title2行
title2Row.createCell(0).setCellValue(title2);
CreationHelper createHelper = workbook.getCreationHelper();
XSSFHyperlink hyperLink = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL);
hyperLink.setAddress(title2);
title2Row.getCell(0).setHyperlink(hyperLink);// 添加超链接
title2Row.getCell(0).setCellStyle(title2Style);
sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, headMap.size() - 1));// 合并单元格
SXSSFRow headerRow = (SXSSFRow) sheet.createRow(2);// head行
for (int j = 0; j < headValArr.length; j++) {
headerRow.createCell(j).setCellValue(headValArr[j]);
headerRow.getCell(j).setCellStyle(headerStyle);
}
rowIndex = 3;
}
JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
// 生成数据
SXSSFRow dataRow = (SXSSFRow) sheet.createRow(rowIndex);// 创建行
for (int k = 0; k < headKeyArr.length; k++) {
SXSSFCell cell = (SXSSFCell) dataRow.createCell(k);// 创建单元格
Object o = jo.get(headKeyArr[k]);
String cellValue = "";
if (o == null) {
cellValue = "";
} else if (o instanceof Date) {
cellValue = new SimpleDateFormat(datePattern).format(o);
} else if (o instanceof Float || o instanceof Double) {
cellValue = new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
} else {
cellValue = o.toString();
}
if (cellValue.equals("true")) {
cellValue = "男";
} else if (cellValue.equals("false")) {
cellValue = "女";
}
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle);
}
rowIndex++;
}
try {
workbook.write(os);
os.flush();// 刷新此输出流并强制将所有缓冲的输出字节写出
os.close();// 关闭流
workbook.dispose();// 释放workbook所占用的所有windows资源
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 550690513/large-amount-data-export | src/main/java/Utils/ExcelUtil.java | 2,526 | // 列宽数组 | line_comment | zh-cn | package Utils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import domain.Student;
import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by Cheung on 2017/12/19.
*
* Apache POI操作Excel对象
* HSSF:操作Excel 2007之前版本(.xls)格式,生成的EXCEL不经过压缩直接导出
* XSSF:操作Excel 2007及之后版本(.xlsx)格式,内存占用高于HSSF
* SXSSF:从POI3.8 beta3开始支持,基于XSSF,低内存占用,专门处理大数据量(建议)。
*
* 注意:
* 值得注意的是SXSSFWorkbook只能写(导出)不能读(导入)
*
* 说明:
* .xls格式的excel(最大行数65536行,最大列数256列)
* .xlsx格式的excel(最大行数1048576行,最大列数16384列)
*/
public class ExcelUtil {
public static final String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日";// 默认日期格式
public static final int DEFAULT_COLUMN_WIDTH = 17;// 默认列宽
/**
* 导出Excel(.xlsx)格式
* @param titleList 表格头信息集合
* @param dataArray 数据数组
* @param os 文件输出流
*/
public static void exportExcel(ArrayList<LinkedHashMap> titleList, JSONArray dataArray, OutputStream os) {
String datePattern = DEFAULT_DATE_PATTERN;
int minBytes = DEFAULT_COLUMN_WIDTH;
/**
* 声明一个工作薄
*/
SXSSFWorkbook workbook = new SXSSFWorkbook(1000);// 大于1000行时会把之前的行写入硬盘
workbook.setCompressTempFiles(true);
// 表头1样式
CellStyle title1Style = workbook.createCellStyle();
title1Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平居中
title1Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直居中
Font titleFont = workbook.createFont();// 字体
titleFont.setFontHeightInPoints((short) 20);
titleFont.setBoldweight((short) 700);
title1Style.setFont(titleFont);
// 表头2样式
CellStyle title2Style = workbook.createCellStyle();
title2Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
title2Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
title2Style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
title2Style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右
title2Style.setBorderBottom(HSSFCellStyle.BORDER_THIN);// 下
title2Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左
Font title2Font = workbook.createFont();
title2Font.setUnderline((byte) 1);
title2Font.setColor(HSSFColor.BLUE.index);
title2Style.setFont(title2Font);
// head样式
CellStyle headerStyle = workbook.createCellStyle();
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
headerStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);// 设置颜色
headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// 前景色纯色填充
headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Font headerFont = workbook.createFont();
headerFont.setFontHeightInPoints((short) 12);
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerStyle.setFont(headerFont);
// 单元格样式
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
Font cellFont = workbook.createFont();
cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
cellStyle.setFont(cellFont);
String title1 = (String) titleList.get(0).get("title1");
String title2 = (String) titleList.get(0).get("title2");
LinkedHashMap<String, String> headMap = titleList.get(1);
/**
* 生成一个(带名称)表格
*/
SXSSFSheet sheet = (SXSSFSheet) workbook.createSheet(title1);
sheet.createFreezePane(0, 3, 0, 3);// (单独)冻结前三行
/**
* 生成head相关信息+设置每列宽度
*/
int[] colWidthArr = new int[headMap.size()];// 列宽 <SUF>
String[] headKeyArr = new String[headMap.size()];// headKey数组
String[] headValArr = new String[headMap.size()];// headVal数组
int i = 0;
for (Map.Entry<String, String> entry : headMap.entrySet()) {
headKeyArr[i] = entry.getKey();
headValArr[i] = entry.getValue();
int bytes = headKeyArr[i].getBytes().length;
colWidthArr[i] = bytes < minBytes ? minBytes : bytes;
sheet.setColumnWidth(i, colWidthArr[i] * 256);// 设置列宽
i++;
}
/**
* 遍历数据集合,产生Excel行数据
*/
int rowIndex = 0;
for (Object obj : dataArray) {
// 生成title+head信息
if (rowIndex == 0) {
SXSSFRow title1Row = (SXSSFRow) sheet.createRow(0);// title1行
title1Row.createCell(0).setCellValue(title1);
title1Row.getCell(0).setCellStyle(title1Style);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));// 合并单元格
SXSSFRow title2Row = (SXSSFRow) sheet.createRow(1);// title2行
title2Row.createCell(0).setCellValue(title2);
CreationHelper createHelper = workbook.getCreationHelper();
XSSFHyperlink hyperLink = (XSSFHyperlink) createHelper.createHyperlink(Hyperlink.LINK_URL);
hyperLink.setAddress(title2);
title2Row.getCell(0).setHyperlink(hyperLink);// 添加超链接
title2Row.getCell(0).setCellStyle(title2Style);
sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, headMap.size() - 1));// 合并单元格
SXSSFRow headerRow = (SXSSFRow) sheet.createRow(2);// head行
for (int j = 0; j < headValArr.length; j++) {
headerRow.createCell(j).setCellValue(headValArr[j]);
headerRow.getCell(j).setCellStyle(headerStyle);
}
rowIndex = 3;
}
JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
// 生成数据
SXSSFRow dataRow = (SXSSFRow) sheet.createRow(rowIndex);// 创建行
for (int k = 0; k < headKeyArr.length; k++) {
SXSSFCell cell = (SXSSFCell) dataRow.createCell(k);// 创建单元格
Object o = jo.get(headKeyArr[k]);
String cellValue = "";
if (o == null) {
cellValue = "";
} else if (o instanceof Date) {
cellValue = new SimpleDateFormat(datePattern).format(o);
} else if (o instanceof Float || o instanceof Double) {
cellValue = new BigDecimal(o.toString()).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
} else {
cellValue = o.toString();
}
if (cellValue.equals("true")) {
cellValue = "男";
} else if (cellValue.equals("false")) {
cellValue = "女";
}
cell.setCellValue(cellValue);
cell.setCellStyle(cellStyle);
}
rowIndex++;
}
try {
workbook.write(os);
os.flush();// 刷新此输出流并强制将所有缓冲的输出字节写出
os.close();// 关闭流
workbook.dispose();// 释放workbook所占用的所有windows资源
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 0 | 2,090 | 6 | 2,526 | 5 | 2,389 | 4 | 2,526 | 5 | 3,279 | 8 | false | false | false | false | false | true |
57896_0 |
/*建立一个简易的投票软件,基本外观如下:有4根红颜色的柱形图横向摆放,
* 每个柱形图上方显示得票数,每个柱形图下方都有个“投票”按钮。
* 一开始得票数为0,柱形图高度为1像素,点击投票时根据得票的增加柱形图的高度也增加。*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends JFrame {
int[] count = new int[4];
final int total = 4;
JButton keys[] = new JButton[total];
JTextField jl[] = new JTextField[total];
public MyFrame() {
Container container = getContentPane();
setLayout(null);
setSize(500, 300);
setVisible(true);
setLocation(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < jl.length; i++) {
jl[i] = new JTextField("0");
jl[i].setBounds(10, 10 + 60 * i, 18, 15);
jl[i].setEditable(false);
container.add(jl[i]);
}
for (int i = 0; i < keys.length; i++) {
keys[i] = new JButton("刷票");
keys[i].setBounds(10, 50 + 60 * i, 60, 20);
container.add(keys[i]);
final int j = i;
keys[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count[j]++;
String str = " " + count[j];
jl[j].setText(str);
repaint();
}
});
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillRect(20, 60, 1 + count[0], 10);
g.fillRect(20, 120, 1 + count[1], 10);
g.fillRect(20, 180, 1 + count[2], 10);
g.fillRect(20, 240, 1 + count[3], 10);
}
}
public class Lab9_2 {
public static void main(String[] args) {
new MyFrame();
}
}
| 5522MIKE/JAVA-DRAFT | Lab9/src/Lab9_2.java | 644 | /*建立一个简易的投票软件,基本外观如下:有4根红颜色的柱形图横向摆放,
* 每个柱形图上方显示得票数,每个柱形图下方都有个“投票”按钮。
* 一开始得票数为0,柱形图高度为1像素,点击投票时根据得票的增加柱形图的高度也增加。*/ | block_comment | zh-cn |
/*建立一 <SUF>*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MyFrame extends JFrame {
int[] count = new int[4];
final int total = 4;
JButton keys[] = new JButton[total];
JTextField jl[] = new JTextField[total];
public MyFrame() {
Container container = getContentPane();
setLayout(null);
setSize(500, 300);
setVisible(true);
setLocation(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (int i = 0; i < jl.length; i++) {
jl[i] = new JTextField("0");
jl[i].setBounds(10, 10 + 60 * i, 18, 15);
jl[i].setEditable(false);
container.add(jl[i]);
}
for (int i = 0; i < keys.length; i++) {
keys[i] = new JButton("刷票");
keys[i].setBounds(10, 50 + 60 * i, 60, 20);
container.add(keys[i]);
final int j = i;
keys[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
count[j]++;
String str = " " + count[j];
jl[j].setText(str);
repaint();
}
});
}
}
public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.RED);
g.fillRect(20, 60, 1 + count[0], 10);
g.fillRect(20, 120, 1 + count[1], 10);
g.fillRect(20, 180, 1 + count[2], 10);
g.fillRect(20, 240, 1 + count[3], 10);
}
}
public class Lab9_2 {
public static void main(String[] args) {
new MyFrame();
}
}
| 0 | 534 | 83 | 644 | 102 | 619 | 86 | 644 | 102 | 804 | 161 | false | true | false | true | true | false |
11417_4 | package com.bj58.argo.utils;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ClassUtils {
private ClassUtils() {}
/**
* 从包package中获取所有的Class
*
* @param pack 包名
* @return
*/
public static Set<Class<?>> getClasses(String pack) {
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(
packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
System.err.println("file类型的扫描");
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath,
recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
System.err.println("jar类型的扫描");
JarFile jar;
try {
// 获取jar
jar = ((JarURLConnection) url.openConnection())
.getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx)
.replace('/', '.');
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) | recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class")
&& !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(
packageName.length() + 1, name
.length() - 6);
try {
// 添加到classes
classes.add(Class
.forName(packageName + '.'
+ className));
} catch (ClassNotFoundException e) {
// log
// .error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
// log.error("在扫描用户定义视图时从jar包获取文件出错");
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
private static void findAndAddClassesInPackageByFile(String packageName,
String packagePath, final boolean recursive, Set<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory())
|| (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "."
+ file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0,
file.getName().length() - 6);
try {
// 添加到集合中去
//classes.add(Class.forName(packageName + '.' + className));
//经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
} catch (ClassNotFoundException e) {
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
/**
* 得到方法参数名称数组
* 由于java没有提供获得参数名称的api,利用了javassist来实现
*
* @return 参数名称数组
*/
public static String[] getMethodParamNames(Class<?> clazz, Method method) {
Class<?>[] paramTypes = method.getParameterTypes();
try {
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(clazz));
CtClass cc = pool.get(clazz.getName());
String[] paramTypeNames = new String[method.getParameterTypes().length];
for (int i = 0; i < paramTypes.length; i++)
paramTypeNames[i] = paramTypes[i].getName();
CtMethod cm = cc.getDeclaredMethod(method.getName(), pool.get(paramTypeNames));
// 使用javaassist的反射方法获取方法的参数名
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
throw new RuntimeException("class:" + clazz.getName()
+ ", have no LocalVariableTable, please use javac -g:{vars} to compile the source file");
}
int startIndex = getStartIndex(attr);
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++)
paramNames[i] = attr.variableName(startIndex + i + pos);
return paramNames;
} catch (NotFoundException e) {
e.printStackTrace();
return new String[0];
}
}
private static int getStartIndex(LocalVariableAttribute attr) {
int startIndex = 0;
for (int i = 0; i < attr.length(); i++) {
if ("this".equals(attr.variableName(i))) {
startIndex = i;
break;
}
}
return startIndex;
}
}
| 58code/Argo | core/src/main/java/com/bj58/argo/utils/ClassUtils.java | 1,911 | // 定义一个枚举的集合 并进行循环来处理这个目录下的things
| line_comment | zh-cn | package com.bj58.argo.utils;
import javassist.*;
import javassist.bytecode.CodeAttribute;
import javassist.bytecode.LocalVariableAttribute;
import javassist.bytecode.MethodInfo;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ClassUtils {
private ClassUtils() {}
/**
* 从包package中获取所有的Class
*
* @param pack 包名
* @return
*/
public static Set<Class<?>> getClasses(String pack) {
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
// 定义 <SUF>
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(
packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
System.err.println("file类型的扫描");
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath,
recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
System.err.println("jar类型的扫描");
JarFile jar;
try {
// 获取jar
jar = ((JarURLConnection) url.openConnection())
.getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx)
.replace('/', '.');
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) | recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class")
&& !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(
packageName.length() + 1, name
.length() - 6);
try {
// 添加到classes
classes.add(Class
.forName(packageName + '.'
+ className));
} catch (ClassNotFoundException e) {
// log
// .error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
// log.error("在扫描用户定义视图时从jar包获取文件出错");
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
private static void findAndAddClassesInPackageByFile(String packageName,
String packagePath, final boolean recursive, Set<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory())
|| (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "."
+ file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0,
file.getName().length() - 6);
try {
// 添加到集合中去
//classes.add(Class.forName(packageName + '.' + className));
//经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
} catch (ClassNotFoundException e) {
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
/**
* 得到方法参数名称数组
* 由于java没有提供获得参数名称的api,利用了javassist来实现
*
* @return 参数名称数组
*/
public static String[] getMethodParamNames(Class<?> clazz, Method method) {
Class<?>[] paramTypes = method.getParameterTypes();
try {
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(clazz));
CtClass cc = pool.get(clazz.getName());
String[] paramTypeNames = new String[method.getParameterTypes().length];
for (int i = 0; i < paramTypes.length; i++)
paramTypeNames[i] = paramTypes[i].getName();
CtMethod cm = cc.getDeclaredMethod(method.getName(), pool.get(paramTypeNames));
// 使用javaassist的反射方法获取方法的参数名
MethodInfo methodInfo = cm.getMethodInfo();
CodeAttribute codeAttribute = methodInfo.getCodeAttribute();
LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute
.getAttribute(LocalVariableAttribute.tag);
if (attr == null) {
throw new RuntimeException("class:" + clazz.getName()
+ ", have no LocalVariableTable, please use javac -g:{vars} to compile the source file");
}
int startIndex = getStartIndex(attr);
String[] paramNames = new String[cm.getParameterTypes().length];
int pos = Modifier.isStatic(cm.getModifiers()) ? 0 : 1;
for (int i = 0; i < paramNames.length; i++)
paramNames[i] = attr.variableName(startIndex + i + pos);
return paramNames;
} catch (NotFoundException e) {
e.printStackTrace();
return new String[0];
}
}
private static int getStartIndex(LocalVariableAttribute attr) {
int startIndex = 0;
for (int i = 0; i < attr.length(); i++) {
if ("this".equals(attr.variableName(i))) {
startIndex = i;
break;
}
}
return startIndex;
}
}
| 0 | 1,784 | 20 | 1,893 | 19 | 2,039 | 17 | 1,893 | 19 | 2,697 | 37 | false | false | false | false | false | true |
17087_21 | package com.example.administrator.wechat.Comfig;
/**
* Created by Administrator on 2017-7-16.
*/
import android.os.Environment;
import java.io.File;
public class BmobConfig {
/**
* 当前SDK版本号
*/
public static final String SDK_VERSION="1.1.9";
/**
* 每个人的好友查询个数上限
*/
public static int LIMIT_CONTACTS = 100;
/**
* 录音文件存储目录
*/
public static final String BMOB_VOICE_DIR =Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator+"BmobChat"+File.separator+"voice";
/**
* 消息类型:目前暂支持文本(包含表情)的发送
*/
public static final int TYPE_TEXT=1;
/**
* 消息类型:图片
*/
public static final int TYPE_IMAGE=2;
/**
* 消息类型:位置
*/
public static final int TYPE_LOCATION=3;
/**
* 消息类型:声音
*/
public static final int TYPE_VOICE=4;
/**
* 消息是否未读:未读
*/
public static final int STATE_UNREAD=0;
/**
* 消息是否未读:已读
*/
public static final int STATE_READED=1;
/**
* 消息是否未读:未读但已收到
*/
public static final int STATE_UNREAD_RECEIVED=2;
/**
* 消息发送状态:消息开始发送-
*/
public static final int STATUS_SEND_START=0;
/**
* 消息发送状态:成功
*/
public static final int STATUS_SEND_SUCCESS=1;
/**
* 消息发送状态:失败
*/
public static final int STATUS_SEND_FAIL=2;
/**
* 消息发送状态:发送接收到
*/
public static final int STATUS_SEND_RECEIVERED=3;
/**
* 好友邀请状态:发送添加好友请求时候的状态是未验证--等同于
*/
public static final int INVITE_ADD_NO_VALIDATION=0;//
/**
* 好友邀请状态:对方同意添加好友
*/
public static final int INVITE_ADD_AGREE=1;//
/**
* 好友邀请状态:收到对方的好友请求,但未处理
*/
public static final int INVITE_ADD_NO_VALI_RECEIVED = 2;
/**
* 标签消息种类:添加好友
*/
public static final String TAG_ADD_CONTACT="add";//添加好友
/**
* 标签消息种类:同意添加好友
*/
public static final String TAG_ADD_AGREE="agree";//
/**
* 标签消息种类:已读
*/
public static final String TAG_READED="readed";//
/**
* 标签消息种类:下线
*/
public static final String TAG_OFFLINE="offline";//
/**
* 本地已存在
*/
public static final int CODE_COMMON_EXISTED=1002;//
/**
* 是黑名单用户
*/
public static final String BLACK_YES = "y";
/**
* 不是黑名单用户
*/
public static final String BLACK_NO = "n";
/**
* Tag消息
*/
public static final String BROADCAST_NEW_MESSAGE="cn.bmob.new_msg";
/**
* 标签消息
*/
public static final String BROADCAST_ADD_USER_MESSAGE="cn.bmob.add_user_msg";
/**
* 查询成功,无数据返回
*/
public static final int CODE_COMMON_NONE=1000;//响应成功,无返回值
/**
* 查询失败
*/
public static final int CODE_COMMON_FAILURE=1001;//响应出错
public static final int CODE_USER_NULL=1003;//用户为空
public static final int CODE_USERNAME_NULL=1004;//用户名为空
public static final int CODE_PASSWORD_NULL=1005;//密码为空
public static final int CODE_NETWORK_ERROR=1006;//无网络
}
| 600849155/Wechat | comfig/BmobConfig.java | 998 | /**
* 标签消息种类:已读
*/ | block_comment | zh-cn | package com.example.administrator.wechat.Comfig;
/**
* Created by Administrator on 2017-7-16.
*/
import android.os.Environment;
import java.io.File;
public class BmobConfig {
/**
* 当前SDK版本号
*/
public static final String SDK_VERSION="1.1.9";
/**
* 每个人的好友查询个数上限
*/
public static int LIMIT_CONTACTS = 100;
/**
* 录音文件存储目录
*/
public static final String BMOB_VOICE_DIR =Environment.getExternalStorageDirectory().getAbsolutePath() +
File.separator+"BmobChat"+File.separator+"voice";
/**
* 消息类型:目前暂支持文本(包含表情)的发送
*/
public static final int TYPE_TEXT=1;
/**
* 消息类型:图片
*/
public static final int TYPE_IMAGE=2;
/**
* 消息类型:位置
*/
public static final int TYPE_LOCATION=3;
/**
* 消息类型:声音
*/
public static final int TYPE_VOICE=4;
/**
* 消息是否未读:未读
*/
public static final int STATE_UNREAD=0;
/**
* 消息是否未读:已读
*/
public static final int STATE_READED=1;
/**
* 消息是否未读:未读但已收到
*/
public static final int STATE_UNREAD_RECEIVED=2;
/**
* 消息发送状态:消息开始发送-
*/
public static final int STATUS_SEND_START=0;
/**
* 消息发送状态:成功
*/
public static final int STATUS_SEND_SUCCESS=1;
/**
* 消息发送状态:失败
*/
public static final int STATUS_SEND_FAIL=2;
/**
* 消息发送状态:发送接收到
*/
public static final int STATUS_SEND_RECEIVERED=3;
/**
* 好友邀请状态:发送添加好友请求时候的状态是未验证--等同于
*/
public static final int INVITE_ADD_NO_VALIDATION=0;//
/**
* 好友邀请状态:对方同意添加好友
*/
public static final int INVITE_ADD_AGREE=1;//
/**
* 好友邀请状态:收到对方的好友请求,但未处理
*/
public static final int INVITE_ADD_NO_VALI_RECEIVED = 2;
/**
* 标签消息种类:添加好友
*/
public static final String TAG_ADD_CONTACT="add";//添加好友
/**
* 标签消息种类:同意添加好友
*/
public static final String TAG_ADD_AGREE="agree";//
/**
* 标签消 <SUF>*/
public static final String TAG_READED="readed";//
/**
* 标签消息种类:下线
*/
public static final String TAG_OFFLINE="offline";//
/**
* 本地已存在
*/
public static final int CODE_COMMON_EXISTED=1002;//
/**
* 是黑名单用户
*/
public static final String BLACK_YES = "y";
/**
* 不是黑名单用户
*/
public static final String BLACK_NO = "n";
/**
* Tag消息
*/
public static final String BROADCAST_NEW_MESSAGE="cn.bmob.new_msg";
/**
* 标签消息
*/
public static final String BROADCAST_ADD_USER_MESSAGE="cn.bmob.add_user_msg";
/**
* 查询成功,无数据返回
*/
public static final int CODE_COMMON_NONE=1000;//响应成功,无返回值
/**
* 查询失败
*/
public static final int CODE_COMMON_FAILURE=1001;//响应出错
public static final int CODE_USER_NULL=1003;//用户为空
public static final int CODE_USERNAME_NULL=1004;//用户名为空
public static final int CODE_PASSWORD_NULL=1005;//密码为空
public static final int CODE_NETWORK_ERROR=1006;//无网络
}
| 0 | 917 | 14 | 998 | 13 | 1,026 | 13 | 998 | 13 | 1,382 | 21 | false | false | false | false | false | true |
57844_2 | /**
* java生成线程的四种方式
* 继承Thread类
* 实现Runnable接口
* 使用Executor框架来创建线程池
* 实现Callable接口
*/
public class thread1 {
/**
* 模拟龟兔赛跑
* 1、创建多线程(方式一):继承 CreateThread + 重写run方法(线程体)
* 2、使用线程:创建子类对象 + 对象.start()方法 线程启动
* 启动:创建子类对象+对象.start()
* 缺点:Java只支持单继承,如果我们的类已经从一个类继承,则无法再继承Thread类。
*/
public static void main(String[] args) {
//创建子类对象
Rabbit rab = new Rabbit();
Tortoise tor = new Tortoise();
//调用start方法 ,启动线程。 内部由CPU管控
rab.start(); //不要调用run方法,由内部自己调用。
tor.start();
for (int i = 0; i < 30; i++) {
System.out.println("main-->" + i);
}
}
}
class Rabbit extends Thread {
//线程体 一切从run开始
@Override
public void run() {
//线程体
for (int i = 0; i < 30; i++) {
System.out.println("兔子跑了" + i + "步");
}
}
}
class Tortoise extends Thread {
@Override
public void run() {
//线程体
for (int i = 0; i < 30; i++) {
System.out.println("乌龟跑了" + i + "步");
}
}
}
| 600849155/thread | src/thread1.java | 405 | //创建子类对象 | line_comment | zh-cn | /**
* java生成线程的四种方式
* 继承Thread类
* 实现Runnable接口
* 使用Executor框架来创建线程池
* 实现Callable接口
*/
public class thread1 {
/**
* 模拟龟兔赛跑
* 1、创建多线程(方式一):继承 CreateThread + 重写run方法(线程体)
* 2、使用线程:创建子类对象 + 对象.start()方法 线程启动
* 启动:创建子类对象+对象.start()
* 缺点:Java只支持单继承,如果我们的类已经从一个类继承,则无法再继承Thread类。
*/
public static void main(String[] args) {
//创建 <SUF>
Rabbit rab = new Rabbit();
Tortoise tor = new Tortoise();
//调用start方法 ,启动线程。 内部由CPU管控
rab.start(); //不要调用run方法,由内部自己调用。
tor.start();
for (int i = 0; i < 30; i++) {
System.out.println("main-->" + i);
}
}
}
class Rabbit extends Thread {
//线程体 一切从run开始
@Override
public void run() {
//线程体
for (int i = 0; i < 30; i++) {
System.out.println("兔子跑了" + i + "步");
}
}
}
class Tortoise extends Thread {
@Override
public void run() {
//线程体
for (int i = 0; i < 30; i++) {
System.out.println("乌龟跑了" + i + "步");
}
}
}
| 0 | 391 | 5 | 405 | 5 | 406 | 5 | 405 | 5 | 561 | 7 | false | false | false | false | false | true |
61956_1 | package com.xiaoazhai.easywechat.enums;
/**
* @author zhai
* @date 2020年5月6日20:32:40
* 语言枚举
*/
public enum LanguageEnum {
//语言默认采用枚举具体释义如下
// 1、简体中文 "zh_CN"
zh_CN,
// 2、繁体中文TW "zh_TW"
zh_TW,
// 3、繁体中文HK "zh_HK"
zh_HK,
// 4、英文 "en"
en,
// 5、印尼 "id"
id,
// 6、马来 "ms"
ms,
// 7、西班牙 "es"
es,
// 8、韩国 "ko"
ko,
// 9、意大利 "it"
it,
// 10、日本 "ja"
ja,
// 11、波兰 "pl"
pl,
// 12、葡萄牙 "pt"
pt,
// 13、俄国 "ru"
ru,
// 14、泰文 "th"
th,
// 15、越南 "vi"
vi,
// 16、阿拉伯语 "ar"
ar,
// 17、北印度 "hi"
hi,
// 18、希伯来 "he"
he,
// 19、土耳其 "tr"
tr,
// 20、德语 "de"
de,
// 21、法语 "fr"
fr,
}
| 602122993/easywechat | src/main/java/com/xiaoazhai/easywechat/enums/LanguageEnum.java | 393 | //语言默认采用枚举具体释义如下 | line_comment | zh-cn | package com.xiaoazhai.easywechat.enums;
/**
* @author zhai
* @date 2020年5月6日20:32:40
* 语言枚举
*/
public enum LanguageEnum {
//语言 <SUF>
// 1、简体中文 "zh_CN"
zh_CN,
// 2、繁体中文TW "zh_TW"
zh_TW,
// 3、繁体中文HK "zh_HK"
zh_HK,
// 4、英文 "en"
en,
// 5、印尼 "id"
id,
// 6、马来 "ms"
ms,
// 7、西班牙 "es"
es,
// 8、韩国 "ko"
ko,
// 9、意大利 "it"
it,
// 10、日本 "ja"
ja,
// 11、波兰 "pl"
pl,
// 12、葡萄牙 "pt"
pt,
// 13、俄国 "ru"
ru,
// 14、泰文 "th"
th,
// 15、越南 "vi"
vi,
// 16、阿拉伯语 "ar"
ar,
// 17、北印度 "hi"
hi,
// 18、希伯来 "he"
he,
// 19、土耳其 "tr"
tr,
// 20、德语 "de"
de,
// 21、法语 "fr"
fr,
}
| 0 | 351 | 10 | 393 | 10 | 409 | 10 | 393 | 10 | 493 | 25 | false | false | false | false | false | true |
38235_27 | package com.ceit.ebs.ebp.entity;
/**
*@author gr
*@date 2014-8-10 上午10:19:19
*/
public class EbpProject{
// Fields
private Integer id;//id
private Integer planId;//计划id
private String projectName;//项目名称
private String projectCode;//编码方式
private String isPlan;//是否为计划
private String createTime;//创建时间
private Integer budgetMoney;//预算金额
private Integer needDepartmentId;//需求部门
private Integer projectManagerId;//管理id
private String projectRemark;//项目描述
private String projectYear;//招标年份
private String isPublic;//公开/邀请,Y:公开;N:邀请
private String winRule;//中标规则
private String projectStatus;//项目状态:准备状态、招标中、开标等等,具体根据枚举文件详细说明
private String smallStatus;//项目小状态,例如招标准备中分包、分标等,具体根据枚举文件详细说明
private Integer numberTurn;//招标轮次
private Integer creatorId;//招标项目创建人id
private String isValid;
private String updateTime;
private String startBuyTime;//标书开始购买时间
private String endBuyTime;//标书购买截至时间
private String closeBidTime;//截标时间
private String openBidTime;//开标时间
private String singBidTime;//唱标时间
private String sureBidTime;//定标时间
private String replyStartTime;//应答开始时间
private String replyStopTime;//应答结束时间
private String isPrequalification;//是否需要资格认证,Y:需要
private String projectAuditStatus;//项目审核状态:未审核、审核中、审核通过、审核未通过等,根据枚举文件详细说明
private Integer projectAuditId;//审核人编号
private String projectAuditOpinion;//项目审核意见
private String priceUnit;//报价单位,人民币、美元等
private String isObject;//是否分标(三层结构),Y:分
private String comments;//备注
private Integer dispIndex;//索引
/**
* 抽取专家状态字段
*/
private String expertProjectStatus;//备注
// Constructors
/** default constructor */
public EbpProject() {
}
// Property accessors
public Integer getId() {
return this.id;
}
public String getExpertProjectStatus() {
return expertProjectStatus;
}
public void setExpertProjectStatus(String expertProjectStatus) {
this.expertProjectStatus = expertProjectStatus;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPlanId() {
return this.planId;
}
public void setPlanId(Integer planId) {
this.planId = planId;
}
public String getProjectName() {
return this.projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectCode() {
return this.projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public String getIsPlan() {
return this.isPlan;
}
public void setIsPlan(String isPlan) {
this.isPlan = isPlan;
}
public String getCreateTime() {
return this.createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Integer getBudgetMoney() {
return this.budgetMoney;
}
public void setBudgetMoney(Integer budgetMoney) {
this.budgetMoney = budgetMoney;
}
public Integer getNeedDepartmentId() {
return this.needDepartmentId;
}
public void setNeedDepartmentId(Integer needDepartmentId) {
this.needDepartmentId = needDepartmentId;
}
public Integer getProjectManagerId() {
return this.projectManagerId;
}
public void setProjectManagerId(Integer projectManagerId) {
this.projectManagerId = projectManagerId;
}
public String getProjectRemark() {
return this.projectRemark;
}
public void setProjectRemark(String projectRemark) {
this.projectRemark = projectRemark;
}
public String getProjectYear() {
return this.projectYear;
}
public void setProjectYear(String projectYear) {
this.projectYear = projectYear;
}
public String getIsPublic() {
return this.isPublic;
}
public void setIsPublic(String isPublic) {
this.isPublic = isPublic;
}
public String getWinRule() {
return this.winRule;
}
public void setWinRule(String winRule) {
this.winRule = winRule;
}
public String getProjectStatus() {
return this.projectStatus;
}
public void setProjectStatus(String projectStatus) {
this.projectStatus = projectStatus;
}
public String getSmallStatus() {
return this.smallStatus;
}
public void setSmallStatus(String smallStatus) {
this.smallStatus = smallStatus;
}
public Integer getNumberTurn() {
return this.numberTurn;
}
public void setNumberTurn(Integer numberTurn) {
this.numberTurn = numberTurn;
}
public Integer getCreatorId() {
return this.creatorId;
}
public void setCreatorId(Integer creatorId) {
this.creatorId = creatorId;
}
public String getIsValid() {
return this.isValid;
}
public void setIsValid(String isValid) {
this.isValid = isValid;
}
public String getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getStartBuyTime() {
return this.startBuyTime;
}
public void setStartBuyTime(String startBuyTime) {
this.startBuyTime = startBuyTime;
}
public String getEndBuyTime() {
return this.endBuyTime;
}
public void setEndBuyTime(String endBuyTime) {
this.endBuyTime = endBuyTime;
}
public String getCloseBidTime() {
return this.closeBidTime;
}
public void setCloseBidTime(String closeBidTime) {
this.closeBidTime = closeBidTime;
}
public String getOpenBidTime() {
return this.openBidTime;
}
public void setOpenBidTime(String openBidTime) {
this.openBidTime = openBidTime;
}
public String getSingBidTime() {
return this.singBidTime;
}
public void setSingBidTime(String singBidTime) {
this.singBidTime = singBidTime;
}
public String getSureBidTime() {
return this.sureBidTime;
}
public void setSureBidTime(String sureBidTime) {
this.sureBidTime = sureBidTime;
}
public String getReplyStartTime() {
return this.replyStartTime;
}
public void setReplyStartTime(String replyStartTime) {
this.replyStartTime = replyStartTime;
}
public String getReplyStopTime() {
return this.replyStopTime;
}
public void setReplyStopTime(String replyStopTime) {
this.replyStopTime = replyStopTime;
}
public String getIsPrequalification() {
return this.isPrequalification;
}
public void setIsPrequalification(String isPrequalification) {
this.isPrequalification = isPrequalification;
}
public String getProjectAuditStatus() {
return this.projectAuditStatus;
}
public void setProjectAuditStatus(String projectAuditStatus) {
this.projectAuditStatus = projectAuditStatus;
}
public Integer getProjectAuditId() {
return this.projectAuditId;
}
public void setProjectAuditId(Integer projectAuditId) {
this.projectAuditId = projectAuditId;
}
public String getProjectAuditOpinion() {
return this.projectAuditOpinion;
}
public void setProjectAuditOpinion(String projectAuditOpinion) {
this.projectAuditOpinion = projectAuditOpinion;
}
public String getPriceUnit() {
return this.priceUnit;
}
public void setPriceUnit(String priceUnit) {
this.priceUnit = priceUnit;
}
public String getIsObject() {
return this.isObject;
}
public void setIsObject(String isObject) {
this.isObject = isObject;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Integer getDispIndex() {
return dispIndex;
}
public void setDispIndex(Integer dispIndex) {
this.dispIndex = dispIndex;
}
// public String getExtends1() {
// return this.extends1;
// }
//
// public void setExtends1(String extends1) {
// this.extends1 = extends1;
// }
//
// public String getExtends2() {
// return this.extends2;
// }
//
// public void setExtends2(String extends2) {
// this.extends2 = extends2;
// }
//
// public String getExtends3() {
// return this.extends3;
// }
//
// public void setExtends3(String extends3) {
// this.extends3 = extends3;
// }
//
// public String getExtends4() {
// return this.extends4;
// }
//
// public void setExtends4(String extends4) {
// this.extends4 = extends4;
// }
//
// public String getExtends5() {
// return this.extends5;
// }
//
// public void setExtends5(String extends5) {
// this.extends5 = extends5;
// }
//
// public String getExtends6() {
// return this.extends6;
// }
//
// public void setExtends6(String extends6) {
// this.extends6 = extends6;
// }
//
// public String getExtends7() {
// return this.extends7;
// }
//
// public void setExtends7(String extends7) {
// this.extends7 = extends7;
// }
//
// public String getExtends8() {
// return this.extends8;
// }
//
// public void setExtends8(String extends8) {
// this.extends8 = extends8;
// }
//
// public String getExtends9() {
// return this.extends9;
// }
//
// public void setExtends9(String extends9) {
// this.extends9 = extends9;
// }
//
// public String getExtends10() {
// return this.extends10;
// }
//
// public void setExtends10(String extends10) {
// this.extends10 = extends10;
// }
} | 623860762/EBS | src/com/ceit/ebs/ebp/entity/EbpProject.java | 2,888 | //项目审核状态:未审核、审核中、审核通过、审核未通过等,根据枚举文件详细说明 | line_comment | zh-cn | package com.ceit.ebs.ebp.entity;
/**
*@author gr
*@date 2014-8-10 上午10:19:19
*/
public class EbpProject{
// Fields
private Integer id;//id
private Integer planId;//计划id
private String projectName;//项目名称
private String projectCode;//编码方式
private String isPlan;//是否为计划
private String createTime;//创建时间
private Integer budgetMoney;//预算金额
private Integer needDepartmentId;//需求部门
private Integer projectManagerId;//管理id
private String projectRemark;//项目描述
private String projectYear;//招标年份
private String isPublic;//公开/邀请,Y:公开;N:邀请
private String winRule;//中标规则
private String projectStatus;//项目状态:准备状态、招标中、开标等等,具体根据枚举文件详细说明
private String smallStatus;//项目小状态,例如招标准备中分包、分标等,具体根据枚举文件详细说明
private Integer numberTurn;//招标轮次
private Integer creatorId;//招标项目创建人id
private String isValid;
private String updateTime;
private String startBuyTime;//标书开始购买时间
private String endBuyTime;//标书购买截至时间
private String closeBidTime;//截标时间
private String openBidTime;//开标时间
private String singBidTime;//唱标时间
private String sureBidTime;//定标时间
private String replyStartTime;//应答开始时间
private String replyStopTime;//应答结束时间
private String isPrequalification;//是否需要资格认证,Y:需要
private String projectAuditStatus;//项目 <SUF>
private Integer projectAuditId;//审核人编号
private String projectAuditOpinion;//项目审核意见
private String priceUnit;//报价单位,人民币、美元等
private String isObject;//是否分标(三层结构),Y:分
private String comments;//备注
private Integer dispIndex;//索引
/**
* 抽取专家状态字段
*/
private String expertProjectStatus;//备注
// Constructors
/** default constructor */
public EbpProject() {
}
// Property accessors
public Integer getId() {
return this.id;
}
public String getExpertProjectStatus() {
return expertProjectStatus;
}
public void setExpertProjectStatus(String expertProjectStatus) {
this.expertProjectStatus = expertProjectStatus;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getPlanId() {
return this.planId;
}
public void setPlanId(Integer planId) {
this.planId = planId;
}
public String getProjectName() {
return this.projectName;
}
public void setProjectName(String projectName) {
this.projectName = projectName;
}
public String getProjectCode() {
return this.projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public String getIsPlan() {
return this.isPlan;
}
public void setIsPlan(String isPlan) {
this.isPlan = isPlan;
}
public String getCreateTime() {
return this.createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public Integer getBudgetMoney() {
return this.budgetMoney;
}
public void setBudgetMoney(Integer budgetMoney) {
this.budgetMoney = budgetMoney;
}
public Integer getNeedDepartmentId() {
return this.needDepartmentId;
}
public void setNeedDepartmentId(Integer needDepartmentId) {
this.needDepartmentId = needDepartmentId;
}
public Integer getProjectManagerId() {
return this.projectManagerId;
}
public void setProjectManagerId(Integer projectManagerId) {
this.projectManagerId = projectManagerId;
}
public String getProjectRemark() {
return this.projectRemark;
}
public void setProjectRemark(String projectRemark) {
this.projectRemark = projectRemark;
}
public String getProjectYear() {
return this.projectYear;
}
public void setProjectYear(String projectYear) {
this.projectYear = projectYear;
}
public String getIsPublic() {
return this.isPublic;
}
public void setIsPublic(String isPublic) {
this.isPublic = isPublic;
}
public String getWinRule() {
return this.winRule;
}
public void setWinRule(String winRule) {
this.winRule = winRule;
}
public String getProjectStatus() {
return this.projectStatus;
}
public void setProjectStatus(String projectStatus) {
this.projectStatus = projectStatus;
}
public String getSmallStatus() {
return this.smallStatus;
}
public void setSmallStatus(String smallStatus) {
this.smallStatus = smallStatus;
}
public Integer getNumberTurn() {
return this.numberTurn;
}
public void setNumberTurn(Integer numberTurn) {
this.numberTurn = numberTurn;
}
public Integer getCreatorId() {
return this.creatorId;
}
public void setCreatorId(Integer creatorId) {
this.creatorId = creatorId;
}
public String getIsValid() {
return this.isValid;
}
public void setIsValid(String isValid) {
this.isValid = isValid;
}
public String getUpdateTime() {
return this.updateTime;
}
public void setUpdateTime(String updateTime) {
this.updateTime = updateTime;
}
public String getStartBuyTime() {
return this.startBuyTime;
}
public void setStartBuyTime(String startBuyTime) {
this.startBuyTime = startBuyTime;
}
public String getEndBuyTime() {
return this.endBuyTime;
}
public void setEndBuyTime(String endBuyTime) {
this.endBuyTime = endBuyTime;
}
public String getCloseBidTime() {
return this.closeBidTime;
}
public void setCloseBidTime(String closeBidTime) {
this.closeBidTime = closeBidTime;
}
public String getOpenBidTime() {
return this.openBidTime;
}
public void setOpenBidTime(String openBidTime) {
this.openBidTime = openBidTime;
}
public String getSingBidTime() {
return this.singBidTime;
}
public void setSingBidTime(String singBidTime) {
this.singBidTime = singBidTime;
}
public String getSureBidTime() {
return this.sureBidTime;
}
public void setSureBidTime(String sureBidTime) {
this.sureBidTime = sureBidTime;
}
public String getReplyStartTime() {
return this.replyStartTime;
}
public void setReplyStartTime(String replyStartTime) {
this.replyStartTime = replyStartTime;
}
public String getReplyStopTime() {
return this.replyStopTime;
}
public void setReplyStopTime(String replyStopTime) {
this.replyStopTime = replyStopTime;
}
public String getIsPrequalification() {
return this.isPrequalification;
}
public void setIsPrequalification(String isPrequalification) {
this.isPrequalification = isPrequalification;
}
public String getProjectAuditStatus() {
return this.projectAuditStatus;
}
public void setProjectAuditStatus(String projectAuditStatus) {
this.projectAuditStatus = projectAuditStatus;
}
public Integer getProjectAuditId() {
return this.projectAuditId;
}
public void setProjectAuditId(Integer projectAuditId) {
this.projectAuditId = projectAuditId;
}
public String getProjectAuditOpinion() {
return this.projectAuditOpinion;
}
public void setProjectAuditOpinion(String projectAuditOpinion) {
this.projectAuditOpinion = projectAuditOpinion;
}
public String getPriceUnit() {
return this.priceUnit;
}
public void setPriceUnit(String priceUnit) {
this.priceUnit = priceUnit;
}
public String getIsObject() {
return this.isObject;
}
public void setIsObject(String isObject) {
this.isObject = isObject;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Integer getDispIndex() {
return dispIndex;
}
public void setDispIndex(Integer dispIndex) {
this.dispIndex = dispIndex;
}
// public String getExtends1() {
// return this.extends1;
// }
//
// public void setExtends1(String extends1) {
// this.extends1 = extends1;
// }
//
// public String getExtends2() {
// return this.extends2;
// }
//
// public void setExtends2(String extends2) {
// this.extends2 = extends2;
// }
//
// public String getExtends3() {
// return this.extends3;
// }
//
// public void setExtends3(String extends3) {
// this.extends3 = extends3;
// }
//
// public String getExtends4() {
// return this.extends4;
// }
//
// public void setExtends4(String extends4) {
// this.extends4 = extends4;
// }
//
// public String getExtends5() {
// return this.extends5;
// }
//
// public void setExtends5(String extends5) {
// this.extends5 = extends5;
// }
//
// public String getExtends6() {
// return this.extends6;
// }
//
// public void setExtends6(String extends6) {
// this.extends6 = extends6;
// }
//
// public String getExtends7() {
// return this.extends7;
// }
//
// public void setExtends7(String extends7) {
// this.extends7 = extends7;
// }
//
// public String getExtends8() {
// return this.extends8;
// }
//
// public void setExtends8(String extends8) {
// this.extends8 = extends8;
// }
//
// public String getExtends9() {
// return this.extends9;
// }
//
// public void setExtends9(String extends9) {
// this.extends9 = extends9;
// }
//
// public String getExtends10() {
// return this.extends10;
// }
//
// public void setExtends10(String extends10) {
// this.extends10 = extends10;
// }
} | 0 | 2,285 | 25 | 2,888 | 25 | 2,827 | 25 | 2,888 | 25 | 3,506 | 66 | false | false | false | false | false | true |
37831_1 | package cn.practice;
import java.util.Random;
/**
* <p>Description:实现一个抽奖效果,中奖率为30%</p>
* <p>Class:Random</p>
* <p>Powered by zxy On 2023-04-10 22:00 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class WinaPrize30 {
public static void main(String[] args) {
//实现一个抽奖效果,中奖率为30%
Random rand = new Random();
int ok = rand.nextInt(1, 101);
if (ok <= 30) {
System.out.println("恭喜,你中奖了," + ok);
} else {
System.err.println("遗憾,未中奖.");
}
}
}
| 629y/javase | demo/Javase/src/cn/practice/WinaPrize30.java | 237 | //实现一个抽奖效果,中奖率为30% | line_comment | zh-cn | package cn.practice;
import java.util.Random;
/**
* <p>Description:实现一个抽奖效果,中奖率为30%</p>
* <p>Class:Random</p>
* <p>Powered by zxy On 2023-04-10 22:00 </p>
*
* @author zxy [zxy06291@163.com]
* @version 1.0
* @since 17
*/
public class WinaPrize30 {
public static void main(String[] args) {
//实现 <SUF>
Random rand = new Random();
int ok = rand.nextInt(1, 101);
if (ok <= 30) {
System.out.println("恭喜,你中奖了," + ok);
} else {
System.err.println("遗憾,未中奖.");
}
}
}
| 0 | 203 | 12 | 237 | 14 | 237 | 14 | 237 | 14 | 281 | 25 | false | false | false | false | false | true |
37144_2 | package com.xiaolin.adpter;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.xiaolin.R;
import com.xiaolin.bean.AttendDaysOFMonthBean;
import com.xiaolin.utils.DebugUtil;
import java.util.ArrayList;
import java.util.List;
/**
* AttendDayActivity中listView的适配
*/
public class AttendDayAdapter extends BaseAdapter {
private static final String TAG = "calendar";
List<AttendDaysOFMonthBean> list;
Context context;
public LayoutInflater inflater;
public AttendDayAdapter(Context context, ArrayList<AttendDaysOFMonthBean> list) {
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
public class WidgetHolder {
public TextView tv_moringTime;
public TextView tv_lateTime;
public TextView tv_moringType;
public TextView tv_lateType;
public TextView tv_moringState;
public TextView tv_lateState;
}
@Override
public int getCount() {
if (list != null) {
return list.size();
}
return 0;
}
@Override
public Object getItem(int i) {
return list.get(i
);
}
@Override
public long getItemId(int i) {
return i;
}
//listView赋值
public void setEntityList(ArrayList entityList) {
this.list.clear();
this.list.addAll(entityList);
notifyDataSetChanged();
}
WidgetHolder holder;
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
//该布局上的控件
holder = new WidgetHolder();
view = inflater.inflate(R.layout.item_attend_detail, new LinearLayout(context), false);
holder.tv_moringTime = (TextView) view.findViewById(R.id.tv_moringTime);
holder.tv_lateTime = (TextView) view.findViewById(R.id.tv_lateTime);
holder.tv_moringType = (TextView) view.findViewById(R.id.tv_morningType);
holder.tv_lateType = (TextView) view.findViewById(R.id.tv_lateType);
holder.tv_moringState = (TextView) view.findViewById(R.id.tv_morningState);
holder.tv_lateState = (TextView) view.findViewById(R.id.tv_lateState);
view.setTag(holder);
} else {
holder = (WidgetHolder) view.getTag();
}
AttendDaysOFMonthBean bean = list.get(i);
//签到
holder.tv_moringTime.setText(bean.getFirstAttendDateTime());
holder.tv_moringType.setText(bean.getFirstAttendType());
if (bean.getFirstState().contains("迟到")) {
DebugUtil.d(TAG, "签到--迟到");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (bean.getFirstState().contains("正常")) {
DebugUtil.d(TAG, "签到--正常");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.green));
} else {
DebugUtil.d(TAG, "签到--缺勤");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.red));
}
//签退
holder.tv_lateTime.setText(bean.getLastAttendDateTime());
holder.tv_lateType.setText(bean.getLastAttendType());
if (bean.getLastState().contains("早退")) {
DebugUtil.d(TAG, "签退--早退");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (bean.getLastState().contains("正常")) {
DebugUtil.d(TAG, "签退--正常");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.green));
} else {
DebugUtil.d(TAG, "签退--缺勤");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.red));
}
return view;
}
}
| 66668/IEMClient | app/src/main/java/com/xiaolin/adpter/AttendDayAdapter.java | 1,162 | //该布局上的控件 | line_comment | zh-cn | package com.xiaolin.adpter;
import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.xiaolin.R;
import com.xiaolin.bean.AttendDaysOFMonthBean;
import com.xiaolin.utils.DebugUtil;
import java.util.ArrayList;
import java.util.List;
/**
* AttendDayActivity中listView的适配
*/
public class AttendDayAdapter extends BaseAdapter {
private static final String TAG = "calendar";
List<AttendDaysOFMonthBean> list;
Context context;
public LayoutInflater inflater;
public AttendDayAdapter(Context context, ArrayList<AttendDaysOFMonthBean> list) {
this.context = context;
this.list = list;
inflater = LayoutInflater.from(context);
}
public class WidgetHolder {
public TextView tv_moringTime;
public TextView tv_lateTime;
public TextView tv_moringType;
public TextView tv_lateType;
public TextView tv_moringState;
public TextView tv_lateState;
}
@Override
public int getCount() {
if (list != null) {
return list.size();
}
return 0;
}
@Override
public Object getItem(int i) {
return list.get(i
);
}
@Override
public long getItemId(int i) {
return i;
}
//listView赋值
public void setEntityList(ArrayList entityList) {
this.list.clear();
this.list.addAll(entityList);
notifyDataSetChanged();
}
WidgetHolder holder;
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
//该布 <SUF>
holder = new WidgetHolder();
view = inflater.inflate(R.layout.item_attend_detail, new LinearLayout(context), false);
holder.tv_moringTime = (TextView) view.findViewById(R.id.tv_moringTime);
holder.tv_lateTime = (TextView) view.findViewById(R.id.tv_lateTime);
holder.tv_moringType = (TextView) view.findViewById(R.id.tv_morningType);
holder.tv_lateType = (TextView) view.findViewById(R.id.tv_lateType);
holder.tv_moringState = (TextView) view.findViewById(R.id.tv_morningState);
holder.tv_lateState = (TextView) view.findViewById(R.id.tv_lateState);
view.setTag(holder);
} else {
holder = (WidgetHolder) view.getTag();
}
AttendDaysOFMonthBean bean = list.get(i);
//签到
holder.tv_moringTime.setText(bean.getFirstAttendDateTime());
holder.tv_moringType.setText(bean.getFirstAttendType());
if (bean.getFirstState().contains("迟到")) {
DebugUtil.d(TAG, "签到--迟到");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (bean.getFirstState().contains("正常")) {
DebugUtil.d(TAG, "签到--正常");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.green));
} else {
DebugUtil.d(TAG, "签到--缺勤");
holder.tv_moringState.setText(bean.getFirstState());
holder.tv_moringState.setTextColor(ContextCompat.getColor(context, R.color.red));
}
//签退
holder.tv_lateTime.setText(bean.getLastAttendDateTime());
holder.tv_lateType.setText(bean.getLastAttendType());
if (bean.getLastState().contains("早退")) {
DebugUtil.d(TAG, "签退--早退");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.orange));
} else if (bean.getLastState().contains("正常")) {
DebugUtil.d(TAG, "签退--正常");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.green));
} else {
DebugUtil.d(TAG, "签退--缺勤");
holder.tv_lateState.setText(bean.getLastState());
holder.tv_lateState.setTextColor(ContextCompat.getColor(context, R.color.red));
}
return view;
}
}
| 0 | 926 | 6 | 1,162 | 5 | 1,210 | 5 | 1,162 | 5 | 1,365 | 8 | false | false | false | false | false | true |
28218_0 | package com.zhongou.common.calendarcommon;
public class CalendarTpyeArray {
public final static String[] sch_type = { "会议", "约会", "电话", "纪念日", "生日", "课程", "其他" }; // 日程类型
public final static String[] remind = {"提醒一次","隔10分钟","隔30分钟","隔一小时","每天重复","每周重复","每月重复","每年重复"};
}
| 66668/ZOERP | app/src/main/java/com/zhongou/common/calendarcommon/CalendarTpyeArray.java | 119 | // 日程类型 | line_comment | zh-cn | package com.zhongou.common.calendarcommon;
public class CalendarTpyeArray {
public final static String[] sch_type = { "会议", "约会", "电话", "纪念日", "生日", "课程", "其他" }; // 日程 <SUF>
public final static String[] remind = {"提醒一次","隔10分钟","隔30分钟","隔一小时","每天重复","每周重复","每月重复","每年重复"};
}
| 0 | 92 | 4 | 119 | 5 | 101 | 4 | 119 | 5 | 150 | 6 | false | false | false | false | false | true |
15935_1 | package com.liuliuzhu.autojs;
import android.app.Application;
import android.util.Log;
import com.liuliuzhu.autojs.utils.HookUtils;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
/**
* @author 溜溜猪
* @date 2020/05/23
* @desc 微信公众号:AI小子
*/
public class Hook extends Application implements IXposedHookLoadPackage, Config {
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {
final Class<?> clazz = XposedHelpers.findClass(
"com.stardust.autojs.engine.encryption.ScriptEncryption",
loadPackageParam.classLoader);
XposedHelpers.findAndHookMethod(
clazz,
"decrypt",
byte[].class,
int.class,
int.class,
new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// 拿到的解密数据
String str = HookUtils.bytesToString((byte[]) param.getResult());
HookUtils.strToFile(str, FILEPATH);
}
});
}
}
| 66pig/Autojs_tools | app/src/main/java/com/liuliuzhu/autojs/Hook.java | 347 | // 拿到的解密数据 | line_comment | zh-cn | package com.liuliuzhu.autojs;
import android.app.Application;
import android.util.Log;
import com.liuliuzhu.autojs.utils.HookUtils;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
/**
* @author 溜溜猪
* @date 2020/05/23
* @desc 微信公众号:AI小子
*/
public class Hook extends Application implements IXposedHookLoadPackage, Config {
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {
final Class<?> clazz = XposedHelpers.findClass(
"com.stardust.autojs.engine.encryption.ScriptEncryption",
loadPackageParam.classLoader);
XposedHelpers.findAndHookMethod(
clazz,
"decrypt",
byte[].class,
int.class,
int.class,
new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// 拿到 <SUF>
String str = HookUtils.bytesToString((byte[]) param.getResult());
HookUtils.strToFile(str, FILEPATH);
}
});
}
}
| 0 | 291 | 9 | 347 | 7 | 350 | 5 | 347 | 7 | 412 | 11 | false | false | false | false | false | true |
7799_39 | package com.dou361.jjdxm_ijkplayer.videomonitoring;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PowerManager;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.dou361.jjdxm_ijkplayer.R;
import com.dou361.jjdxm_ijkplayer.videomonitoring.utlis.MediaUtils;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZPlayer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static android.content.ContentValues.TAG;
public class VideoEZplayer extends Activity implements View.OnClickListener , MyRadioGroup.OnCheckedChangeListener ,SurfaceHolder.Callback{
EZPlayer mEZPlayer1;
private int count = 0;
public String hostURL="http://vehicleroadcloud.faw.cn:60443/backend/appBackend/";
private String testURL=
// "ezopen://open.ys7.com/C78957921/1.live";
"ezopen://open.ys7.com/231236707/1.live";
public CountDownTimer countDownTimer;
public VideoRequest videoRequest;
public VideoReply videoReply,videoReply2;
public String videoResponseString,mergeVideoString;//视频Post请求返回数据
private Context mContext;
private PowerManager.WakeLock wakeLock;
View rootView;
private Integer videoPlayingNum=5;
private MyRadioGroup videoRatioGroup;
private RadioButton buttonFront, buttonBack, buttonLeft, buttonRight, channelGodPerspective;
private HashMap<String, RadioButton> channels = new HashMap<>(5);
private ImageButton lightControllerButton;
@SuppressLint("InvalidWakeLockTag")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hcplay);
Log.d(TAG, "onCreate: EZplayer Creating");
mEZPlayer1 = EZOpenSDK.getInstance().createPlayerWithUrl("https://hls01open.ys7.com/openlive/6e0b2be040a943489ef0b9bb344b96b8.hd.m3u8");
// SurfaceView mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview);
// SurfaceHolder mSurfaceHolder1 = mSurfaceView1.getHolder();
// Log.d(TAG, "playViaDevSerial: 播放器绑定界面"+mEZPlayer1.setSurfaceHold(mSurfaceHolder1));
// mSurfaceHolder1.addCallback(this);
// mEZPlayer=EZOpenSDK.getInstance().createPlayer("E40958484",1);
// mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview);
// mSurfaceHolder2 = mSurfaceView2.getHolder();
// mEZPlayer2.setSurfaceHold(mSurfaceHolder2);
// mSurfaceHolder2.addCallback(this);
/* mSurfaceView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (count++%2 == 0){
Log.d(TAG, "onClick: count"+count);
mEZPlayer.stopRealPlay();
}else{
mEZPlayer.startRealPlay();
}
}
});*/
this.mContext = this;
// rootView = getLayoutInflater().from(this).inflate(R.layout.activity_hcplay, null);
// setContentView(rootView);
// setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// lightControllerButton=(ImageButton) findViewById(R.id.light);
// lightControllerButton.setOnClickListener(this);
buttonFront = (RadioButton) findViewById(R.id.front_Click);
buttonBack = (RadioButton)findViewById(R.id.back_Click);
buttonLeft = (RadioButton)findViewById(R.id.left_Click);
buttonRight = (RadioButton)findViewById(R.id.right_Click);
channelGodPerspective = (RadioButton)findViewById(R.id.god_perspective_Click);
buttonFront.setOnClickListener(this);
buttonBack.setOnClickListener(this);
buttonLeft.setOnClickListener(this);
buttonRight.setOnClickListener(this);
channelGodPerspective.setOnClickListener(this);
channels.put("Channel_Front",buttonFront);
channels.put("Channel_Back",buttonBack);
channels.put("Channel_Left",buttonLeft);
channels.put("Channel_Right",buttonRight);
channels.put("Channel_God_Perspective", channelGodPerspective);
//
// replyTextView=findViewById(R.id.replyTextView);
// requestTextView=findViewById(R.id.requestTextView);
/**常亮*/
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG");
wakeLock.acquire();
// for(int i=1;i<7;i++){//for循環打開所有視頻流
// postVideoRequest(i,1);}
videoRatioGroup = (MyRadioGroup)findViewById(R.id.radiogroup);
videoRatioGroup.setOnCheckedChangeListener(new MyRadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(MyRadioGroup group, int checkedId) {
switch (checkedId){
case R.id.left_Click:
Log.d(TAG, "onCheckedChanged: 左视角");
playVideo(3);
// try2play(3);
break;
case R.id.right_Click:
playVideo(4);
// try2play(4);
break;
case R.id.front_Click:
playVideo(1);
// try2play(0);
break;
case R.id.back_Click:
playVideo(2);
// try2play(2);
break;
case R.id.god_perspective_Click:
playVideo(5);
// try2play(5);
break;
default:
Toast defualt =Toast.makeText(VideoEZplayer.this, "上帝", Toast.LENGTH_SHORT);
new ShowMyToast().showMyToast(defualt,100);
break;
}
}
});
}
/**
* Post video request string
*
* @param videoNum video num 视频类型
* @param serviceType service type 1表示打开,0表示关闭
* @return the string
*/
public String postVideoRequest(final int videoNum, int serviceType){
videoRequest = new VideoRequest();
videoRequest.setUserId("6D");
videoRequest.setVin("test");
videoRequest.setVideo_type(Integer.toString(videoNum));
videoRequest.setServicetype(Integer.toString(serviceType));
final String videoRequestJson = JSON.toJSONString(videoRequest);//序列化
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.d(TAG, "postVideoRequest: "+videoRequestJson);
OkHttpClient videoClient=new OkHttpClient();
Request videoRequest= new Request.Builder()
.url(hostURL+"videoRequest")
.post(RequestBody.create(MediaType.parse("application/json"),videoRequestJson))
.build();//创造HTTP请求
//执行发送的指令
Response videoResponse = videoClient.newCall(videoRequest).execute();
Log.d(TAG, "run: 到了videoResponse");
if(videoNum!=6){
videoResponseString=videoResponse.body().string();
Log.d(TAG, "run: videoResponseString:"+videoResponseString);
}
else {
mergeVideoString = videoResponse.body().string();
Log.d(TAG, "run: Merge");
}
Log.d(TAG, "run: 返回结果"+videoNum+"路视频:\n"+videoResponseString+"\n"+mergeVideoString);
}catch (Exception e){
e.printStackTrace();
Log.d("POST失敗", "onClick: "+e.toString());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(VideoEZplayer.this,"請求視頻失败!",Toast.LENGTH_LONG).show();
}
});
}
}
}).start();
Log.d(TAG, "run: 返回结果"+videoNum+"路视频:\n"+videoResponseString);
if (videoNum!=6){
return videoResponseString;}
else {
return mergeVideoString;
}
}
public void playVideo(int videoNum){
if(videoPlayingNum==videoNum) {
return;
}
switch (videoNum){
//E40958484 E40958558 E40958703 E40958817 右左前后序列号
case 0:
break;
case 1:
//只播原始視頻
Log.d(TAG, "playVideo: 前视角");
// playViaDevSerial(testURL);
playViaDevSerial("E40958703");
// playViaDevSerial("E40958703",mSurfaceHolder);
// mEZPlayer1.stopRealPlay();
break;
case 2:
//后视角
playViaDevSerial("E40958817");
// surfaceCreated(mSurfaceHolder);
break;
case 3:
//左视角
playViaDevSerial("D30723108");
// mEZPlayer1=EZOpenSDK.getInstance().createPlayer("E40958484",1);
// mEZPlayer1.startRealPlay();
break;
case 4:
//右视角
playViaDevSerial("E40958484");
break;
case 5:
//上帝视角
// playViaDevSerial("231236707");
playViaDevSerial(testURL);
// mEZPlayer1=EZOpenSDK.getInstance().createPlayerWithUrl("ezopen://open.ys7.com/C78957921/1.live");
break;
case 6:
//只有融合視頻
break;
default:
break;
}
videoPlayingNum=videoNum;
}
public void playViaDevSerial(final String deviceSerial){
SurfaceView mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview);
SurfaceHolder mSurfaceHolder1 = mSurfaceView1.getHolder();
mEZPlayer1.release();
if(testURL.equals(deviceSerial)){
mEZPlayer1=EZOpenSDK.getInstance().createPlayerWithUrl(testURL);}
else{
mEZPlayer1 = EZOpenSDK.getInstance().createPlayer(deviceSerial, 1);
}
Log.d(TAG, "playViaDevSerial: 播放器绑定界面"+mEZPlayer1.setSurfaceHold(mSurfaceHolder1));
mSurfaceHolder1.addCallback(this);
Log.d(TAG, "playViaDevSerial: 播放器设备"+deviceSerial);
// mEZPlayer1.setSurfaceHold(holder);
// mEZPlayer.setHandler(mHandler);
// holder.addCallback(this);
Log.d(TAG, "playViaDevSerial: 播放成功?"+mEZPlayer1.startRealPlay());
}
@Override
protected void onPause() {
super.onPause();
/**demo的内容,恢复系统其它媒体的状态*/
MediaUtils.muteAudioFocus(mContext, true);
}
@Override
protected void onResume() {
super.onResume();
/**demo的内容,暂停系统其它媒体的状态*/
MediaUtils.muteAudioFocus(mContext, false);
/**demo的内容,激活设备常亮状态*/
if (wakeLock != null) {
wakeLock.acquire();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public void onBackPressed() {
super.onBackPressed();
/**demo的内容,恢复设备亮度状态*/
if (wakeLock != null) {
wakeLock.release();
}
}
@Override
public void onCheckedChanged(MyRadioGroup group, int checkedId) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated: 播放器创建");
/*// mSurfaceHolder = holder;
// Intent intent = getIntent();
// mEZPlayer1=EZOpenSDK.getInstance().createPlayer("231236707",1);
// mEZPlayer=EZOpenSDK.getInstance().createPlayer("E40958484",1);
mEZPlayer1.setSurfaceHold(holder);
// mEZPlayer.setHandler(mHandler);
mEZPlayer1.startRealPlay();*/
// mEZPlayer1.startRealPlay();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void onClick(View view) {
}
}
| 6D1996/zz_ijkplayer-master | app/src/main/java/com/dou361/jjdxm_ijkplayer/videomonitoring/VideoEZplayer.java | 3,379 | //后视角 | line_comment | zh-cn | package com.dou361.jjdxm_ijkplayer.videomonitoring;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.PowerManager;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Toast;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.dou361.jjdxm_ijkplayer.R;
import com.dou361.jjdxm_ijkplayer.videomonitoring.utlis.MediaUtils;
import com.videogo.exception.BaseException;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.EZPlayer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import static android.content.ContentValues.TAG;
public class VideoEZplayer extends Activity implements View.OnClickListener , MyRadioGroup.OnCheckedChangeListener ,SurfaceHolder.Callback{
EZPlayer mEZPlayer1;
private int count = 0;
public String hostURL="http://vehicleroadcloud.faw.cn:60443/backend/appBackend/";
private String testURL=
// "ezopen://open.ys7.com/C78957921/1.live";
"ezopen://open.ys7.com/231236707/1.live";
public CountDownTimer countDownTimer;
public VideoRequest videoRequest;
public VideoReply videoReply,videoReply2;
public String videoResponseString,mergeVideoString;//视频Post请求返回数据
private Context mContext;
private PowerManager.WakeLock wakeLock;
View rootView;
private Integer videoPlayingNum=5;
private MyRadioGroup videoRatioGroup;
private RadioButton buttonFront, buttonBack, buttonLeft, buttonRight, channelGodPerspective;
private HashMap<String, RadioButton> channels = new HashMap<>(5);
private ImageButton lightControllerButton;
@SuppressLint("InvalidWakeLockTag")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hcplay);
Log.d(TAG, "onCreate: EZplayer Creating");
mEZPlayer1 = EZOpenSDK.getInstance().createPlayerWithUrl("https://hls01open.ys7.com/openlive/6e0b2be040a943489ef0b9bb344b96b8.hd.m3u8");
// SurfaceView mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview);
// SurfaceHolder mSurfaceHolder1 = mSurfaceView1.getHolder();
// Log.d(TAG, "playViaDevSerial: 播放器绑定界面"+mEZPlayer1.setSurfaceHold(mSurfaceHolder1));
// mSurfaceHolder1.addCallback(this);
// mEZPlayer=EZOpenSDK.getInstance().createPlayer("E40958484",1);
// mSurfaceView2 = (SurfaceView) findViewById(R.id.surfaceview);
// mSurfaceHolder2 = mSurfaceView2.getHolder();
// mEZPlayer2.setSurfaceHold(mSurfaceHolder2);
// mSurfaceHolder2.addCallback(this);
/* mSurfaceView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (count++%2 == 0){
Log.d(TAG, "onClick: count"+count);
mEZPlayer.stopRealPlay();
}else{
mEZPlayer.startRealPlay();
}
}
});*/
this.mContext = this;
// rootView = getLayoutInflater().from(this).inflate(R.layout.activity_hcplay, null);
// setContentView(rootView);
// setContentView(R.layout.activity_main);
ButterKnife.bind(this);
// lightControllerButton=(ImageButton) findViewById(R.id.light);
// lightControllerButton.setOnClickListener(this);
buttonFront = (RadioButton) findViewById(R.id.front_Click);
buttonBack = (RadioButton)findViewById(R.id.back_Click);
buttonLeft = (RadioButton)findViewById(R.id.left_Click);
buttonRight = (RadioButton)findViewById(R.id.right_Click);
channelGodPerspective = (RadioButton)findViewById(R.id.god_perspective_Click);
buttonFront.setOnClickListener(this);
buttonBack.setOnClickListener(this);
buttonLeft.setOnClickListener(this);
buttonRight.setOnClickListener(this);
channelGodPerspective.setOnClickListener(this);
channels.put("Channel_Front",buttonFront);
channels.put("Channel_Back",buttonBack);
channels.put("Channel_Left",buttonLeft);
channels.put("Channel_Right",buttonRight);
channels.put("Channel_God_Perspective", channelGodPerspective);
//
// replyTextView=findViewById(R.id.replyTextView);
// requestTextView=findViewById(R.id.requestTextView);
/**常亮*/
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "liveTAG");
wakeLock.acquire();
// for(int i=1;i<7;i++){//for循環打開所有視頻流
// postVideoRequest(i,1);}
videoRatioGroup = (MyRadioGroup)findViewById(R.id.radiogroup);
videoRatioGroup.setOnCheckedChangeListener(new MyRadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(MyRadioGroup group, int checkedId) {
switch (checkedId){
case R.id.left_Click:
Log.d(TAG, "onCheckedChanged: 左视角");
playVideo(3);
// try2play(3);
break;
case R.id.right_Click:
playVideo(4);
// try2play(4);
break;
case R.id.front_Click:
playVideo(1);
// try2play(0);
break;
case R.id.back_Click:
playVideo(2);
// try2play(2);
break;
case R.id.god_perspective_Click:
playVideo(5);
// try2play(5);
break;
default:
Toast defualt =Toast.makeText(VideoEZplayer.this, "上帝", Toast.LENGTH_SHORT);
new ShowMyToast().showMyToast(defualt,100);
break;
}
}
});
}
/**
* Post video request string
*
* @param videoNum video num 视频类型
* @param serviceType service type 1表示打开,0表示关闭
* @return the string
*/
public String postVideoRequest(final int videoNum, int serviceType){
videoRequest = new VideoRequest();
videoRequest.setUserId("6D");
videoRequest.setVin("test");
videoRequest.setVideo_type(Integer.toString(videoNum));
videoRequest.setServicetype(Integer.toString(serviceType));
final String videoRequestJson = JSON.toJSONString(videoRequest);//序列化
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.d(TAG, "postVideoRequest: "+videoRequestJson);
OkHttpClient videoClient=new OkHttpClient();
Request videoRequest= new Request.Builder()
.url(hostURL+"videoRequest")
.post(RequestBody.create(MediaType.parse("application/json"),videoRequestJson))
.build();//创造HTTP请求
//执行发送的指令
Response videoResponse = videoClient.newCall(videoRequest).execute();
Log.d(TAG, "run: 到了videoResponse");
if(videoNum!=6){
videoResponseString=videoResponse.body().string();
Log.d(TAG, "run: videoResponseString:"+videoResponseString);
}
else {
mergeVideoString = videoResponse.body().string();
Log.d(TAG, "run: Merge");
}
Log.d(TAG, "run: 返回结果"+videoNum+"路视频:\n"+videoResponseString+"\n"+mergeVideoString);
}catch (Exception e){
e.printStackTrace();
Log.d("POST失敗", "onClick: "+e.toString());
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(VideoEZplayer.this,"請求視頻失败!",Toast.LENGTH_LONG).show();
}
});
}
}
}).start();
Log.d(TAG, "run: 返回结果"+videoNum+"路视频:\n"+videoResponseString);
if (videoNum!=6){
return videoResponseString;}
else {
return mergeVideoString;
}
}
public void playVideo(int videoNum){
if(videoPlayingNum==videoNum) {
return;
}
switch (videoNum){
//E40958484 E40958558 E40958703 E40958817 右左前后序列号
case 0:
break;
case 1:
//只播原始視頻
Log.d(TAG, "playVideo: 前视角");
// playViaDevSerial(testURL);
playViaDevSerial("E40958703");
// playViaDevSerial("E40958703",mSurfaceHolder);
// mEZPlayer1.stopRealPlay();
break;
case 2:
//后视 <SUF>
playViaDevSerial("E40958817");
// surfaceCreated(mSurfaceHolder);
break;
case 3:
//左视角
playViaDevSerial("D30723108");
// mEZPlayer1=EZOpenSDK.getInstance().createPlayer("E40958484",1);
// mEZPlayer1.startRealPlay();
break;
case 4:
//右视角
playViaDevSerial("E40958484");
break;
case 5:
//上帝视角
// playViaDevSerial("231236707");
playViaDevSerial(testURL);
// mEZPlayer1=EZOpenSDK.getInstance().createPlayerWithUrl("ezopen://open.ys7.com/C78957921/1.live");
break;
case 6:
//只有融合視頻
break;
default:
break;
}
videoPlayingNum=videoNum;
}
public void playViaDevSerial(final String deviceSerial){
SurfaceView mSurfaceView1 = (SurfaceView) findViewById(R.id.surfaceview);
SurfaceHolder mSurfaceHolder1 = mSurfaceView1.getHolder();
mEZPlayer1.release();
if(testURL.equals(deviceSerial)){
mEZPlayer1=EZOpenSDK.getInstance().createPlayerWithUrl(testURL);}
else{
mEZPlayer1 = EZOpenSDK.getInstance().createPlayer(deviceSerial, 1);
}
Log.d(TAG, "playViaDevSerial: 播放器绑定界面"+mEZPlayer1.setSurfaceHold(mSurfaceHolder1));
mSurfaceHolder1.addCallback(this);
Log.d(TAG, "playViaDevSerial: 播放器设备"+deviceSerial);
// mEZPlayer1.setSurfaceHold(holder);
// mEZPlayer.setHandler(mHandler);
// holder.addCallback(this);
Log.d(TAG, "playViaDevSerial: 播放成功?"+mEZPlayer1.startRealPlay());
}
@Override
protected void onPause() {
super.onPause();
/**demo的内容,恢复系统其它媒体的状态*/
MediaUtils.muteAudioFocus(mContext, true);
}
@Override
protected void onResume() {
super.onResume();
/**demo的内容,暂停系统其它媒体的状态*/
MediaUtils.muteAudioFocus(mContext, false);
/**demo的内容,激活设备常亮状态*/
if (wakeLock != null) {
wakeLock.acquire();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public void onBackPressed() {
super.onBackPressed();
/**demo的内容,恢复设备亮度状态*/
if (wakeLock != null) {
wakeLock.release();
}
}
@Override
public void onCheckedChanged(MyRadioGroup group, int checkedId) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "surfaceCreated: 播放器创建");
/*// mSurfaceHolder = holder;
// Intent intent = getIntent();
// mEZPlayer1=EZOpenSDK.getInstance().createPlayer("231236707",1);
// mEZPlayer=EZOpenSDK.getInstance().createPlayer("E40958484",1);
mEZPlayer1.setSurfaceHold(holder);
// mEZPlayer.setHandler(mHandler);
mEZPlayer1.startRealPlay();*/
// mEZPlayer1.startRealPlay();
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
@Override
public void onClick(View view) {
}
}
| 0 | 2,914 | 3 | 3,379 | 4 | 3,492 | 3 | 3,379 | 4 | 4,098 | 4 | false | false | false | false | false | true |
40213_5 | package com.liefox.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SignInfo {
private int userid;//用户唯一id
private int signid;//表单唯一id
private int schoolid;//来自哪个学校
private String username;//用户名
private String temperature;//体温
private String address;//地址
private String date;//时间
private String qr_code_color;//健康码颜色
private String is_to_dongguan;//是否去过中高风险地区,之前写的是东莞,懒得改数据库了
}
| 6DDUU6/HealthCheck | src/main/java/com/liefox/pojo/SignInfo.java | 149 | //是否去过中高风险地区,之前写的是东莞,懒得改数据库了 | line_comment | zh-cn | package com.liefox.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SignInfo {
private int userid;//用户唯一id
private int signid;//表单唯一id
private int schoolid;//来自哪个学校
private String username;//用户名
private String temperature;//体温
private String address;//地址
private String date;//时间
private String qr_code_color;//健康码颜色
private String is_to_dongguan;//是否 <SUF>
}
| 0 | 127 | 17 | 149 | 24 | 149 | 20 | 149 | 24 | 213 | 35 | false | false | false | false | false | true |
64382_2 | package com.kefu.netty.server;
import com.kefu.netty.config.NettyProperties;
import com.kefu.netty.initializer.TcpServerInitializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* 引导Netty服务器
*
* @author feng
* @date 2019-04-20
*/
@Component
public class TcpChatServer {
private int port;
public TcpChatServer(NettyProperties nettyProperties) {
this.port = nettyProperties.getTcp().getPort();
}
/**
* 开始引导服务器
* 注意:不带 child 的是设置服务端的 Channel,带 child 的方法是设置每一条连接
*/
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap
// 指定线程模型,这里是主从线程模型
.group(bossGroup, workerGroup)
// 指定服务端的 Channel 的 I/O 模型
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true)
// 指定处理新连接数据的读写处理逻辑:每次有新连接到来,都会去执行ChannelInitializer.initChannel(),并new一大堆handler。所以如果handler中无成员变量,则可写成单例
.childHandler(new TcpServerInitializer());
serverBootstrap.bind(port).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
System.out.println("tcp端口绑定成功 port = " + port);
} else {
System.out.println("tcp端口绑定失败");
}
});
}
}
| 6ag/im-demo-netty-tcp-websocket | src/main/java/com/kefu/netty/server/TcpChatServer.java | 507 | // 指定线程模型,这里是主从线程模型 | line_comment | zh-cn | package com.kefu.netty.server;
import com.kefu.netty.config.NettyProperties;
import com.kefu.netty.initializer.TcpServerInitializer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* 引导Netty服务器
*
* @author feng
* @date 2019-04-20
*/
@Component
public class TcpChatServer {
private int port;
public TcpChatServer(NettyProperties nettyProperties) {
this.port = nettyProperties.getTcp().getPort();
}
/**
* 开始引导服务器
* 注意:不带 child 的是设置服务端的 Channel,带 child 的方法是设置每一条连接
*/
public void start() {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap
// 指定 <SUF>
.group(bossGroup, workerGroup)
// 指定服务端的 Channel 的 I/O 模型
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.option(ChannelOption.TCP_NODELAY, true)
// 指定处理新连接数据的读写处理逻辑:每次有新连接到来,都会去执行ChannelInitializer.initChannel(),并new一大堆handler。所以如果handler中无成员变量,则可写成单例
.childHandler(new TcpServerInitializer());
serverBootstrap.bind(port).addListener((ChannelFutureListener) future -> {
if (future.isSuccess()) {
System.out.println("tcp端口绑定成功 port = " + port);
} else {
System.out.println("tcp端口绑定失败");
}
});
}
}
| 0 | 451 | 15 | 507 | 11 | 516 | 10 | 507 | 11 | 662 | 18 | false | false | false | false | false | true |
54700_2 | package org.superboot.config.datasource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.superboot.base.BaseConstants;
import javax.persistence.EntityManagerFactory;
/**
* <b> 读写分离配置及事务管理 </b>
* <p>
* 功能描述:提供事务支持及读写分离等操作支持
* </p>
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "org.superboot.dao.jpa",
entityManagerFactoryRef = "dataEntityManagerFactory",
transactionManagerRef = "dataTransactionManager")
public class DataSourceTransactionConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
@Qualifier("routingDataSource")
private AbstractRoutingDataSource dataSource;
/**
* 我们通过LocalContainerEntityManagerFactoryBean来获取EntityManagerFactory实例
*
* @return
*/
@Bean(name = "dataEntityManagerFactoryBean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(dataSource)
.properties(jpaProperties.getProperties())
//设置实体类所在位置
.packages("org.superboot.entity.jpa")
.persistenceUnit("dataPersistenceUnit")
.build();
}
/**
* EntityManagerFactory类似于Hibernate的SessionFactory,mybatis的SqlSessionFactory
* 总之,在执行操作之前,我们总要获取一个EntityManager,这就类似于Hibernate的Session,
* mybatis的sqlSession.
*
* @param builder
* @return
*/
@Bean(name = "dataEntityManagerFactory")
@Primary
public EntityManagerFactory entityManagerFactory(EntityManagerFactoryBuilder builder) {
return this.entityManagerFactoryBean(builder).getObject();
}
/**
* 配置事物管理器
*
* @return
*/
@Bean(name = "dataTransactionManager")
@Primary
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactory(builder));
}
}
| 7040210/SuperBoot | super-boot-global/src/main/java/org/superboot/config/datasource/DataSourceTransactionConfig.java | 627 | //设置实体类所在位置 | line_comment | zh-cn | package org.superboot.config.datasource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.superboot.base.BaseConstants;
import javax.persistence.EntityManagerFactory;
/**
* <b> 读写分离配置及事务管理 </b>
* <p>
* 功能描述:提供事务支持及读写分离等操作支持
* </p>
*/
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "org.superboot.dao.jpa",
entityManagerFactoryRef = "dataEntityManagerFactory",
transactionManagerRef = "dataTransactionManager")
public class DataSourceTransactionConfig {
@Autowired
private JpaProperties jpaProperties;
@Autowired
@Qualifier("routingDataSource")
private AbstractRoutingDataSource dataSource;
/**
* 我们通过LocalContainerEntityManagerFactoryBean来获取EntityManagerFactory实例
*
* @return
*/
@Bean(name = "dataEntityManagerFactoryBean")
public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean(EntityManagerFactoryBuilder builder) {
return builder
.dataSource(dataSource)
.properties(jpaProperties.getProperties())
//设置 <SUF>
.packages("org.superboot.entity.jpa")
.persistenceUnit("dataPersistenceUnit")
.build();
}
/**
* EntityManagerFactory类似于Hibernate的SessionFactory,mybatis的SqlSessionFactory
* 总之,在执行操作之前,我们总要获取一个EntityManager,这就类似于Hibernate的Session,
* mybatis的sqlSession.
*
* @param builder
* @return
*/
@Bean(name = "dataEntityManagerFactory")
@Primary
public EntityManagerFactory entityManagerFactory(EntityManagerFactoryBuilder builder) {
return this.entityManagerFactoryBean(builder).getObject();
}
/**
* 配置事物管理器
*
* @return
*/
@Bean(name = "dataTransactionManager")
@Primary
public PlatformTransactionManager transactionManager(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(entityManagerFactory(builder));
}
}
| 0 | 532 | 6 | 627 | 6 | 649 | 6 | 627 | 6 | 792 | 10 | false | false | false | false | false | true |
57653_2 | package com.com.mr_wrong.Socket;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.Utils.LogUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
/**
* Created by Mr_Wrong on 15/9/30.
*/
public class TCPServerService extends Service {
private boolean mIsServiceDestoryed = false;
private String[] mDefinedMessages = new String[]{"你好啊", "buhao", "哈哈哈", "呵呵", "笔笔什么呢"};
@Override
public void onCreate() {
new Thread(new TcpService()).start();
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
mIsServiceDestoryed = true;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class TcpService implements Runnable {
@Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8688);
} catch (IOException e) {
LogUtils.d("zhao'bu'd找不到8688端口玩个毛");
e.printStackTrace();
}
while (!mIsServiceDestoryed) {
try {
final Socket client = serverSocket.accept();
LogUtils.e("接受到了");
new Thread() {
@Override
public void run() {
try {
responseClient(client);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void responseClient(Socket client) throws IOException {
//读取客户端消息
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//发送消息给客户端
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())), true);
out.println("欢迎啊 小伙子");
while (!mIsServiceDestoryed) {
String str = in.readLine();
LogUtils.e("来自客户端的消息" + str);
if (str == null) {
break;//断开连接
}
int i = new Random().nextInt(mDefinedMessages.length);
String msg = mDefinedMessages[i];
out.println(msg);
LogUtils.e("服务器发送消息了:" + msg);
}
LogUtils.e("客户端退出了");
if (in != null)
in.close();
if (out != null)
out.close();
client.close();
}
}
| 70kg/Android-Studio-Project | app/src/main/java/com/com/mr_wrong/Socket/TCPServerService.java | 683 | //发送消息给客户端 | line_comment | zh-cn | package com.com.mr_wrong.Socket;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import com.Utils.LogUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
/**
* Created by Mr_Wrong on 15/9/30.
*/
public class TCPServerService extends Service {
private boolean mIsServiceDestoryed = false;
private String[] mDefinedMessages = new String[]{"你好啊", "buhao", "哈哈哈", "呵呵", "笔笔什么呢"};
@Override
public void onCreate() {
new Thread(new TcpService()).start();
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
mIsServiceDestoryed = true;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private class TcpService implements Runnable {
@Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8688);
} catch (IOException e) {
LogUtils.d("zhao'bu'd找不到8688端口玩个毛");
e.printStackTrace();
}
while (!mIsServiceDestoryed) {
try {
final Socket client = serverSocket.accept();
LogUtils.e("接受到了");
new Thread() {
@Override
public void run() {
try {
responseClient(client);
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void responseClient(Socket client) throws IOException {
//读取客户端消息
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
//发送 <SUF>
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(client.getOutputStream())), true);
out.println("欢迎啊 小伙子");
while (!mIsServiceDestoryed) {
String str = in.readLine();
LogUtils.e("来自客户端的消息" + str);
if (str == null) {
break;//断开连接
}
int i = new Random().nextInt(mDefinedMessages.length);
String msg = mDefinedMessages[i];
out.println(msg);
LogUtils.e("服务器发送消息了:" + msg);
}
LogUtils.e("客户端退出了");
if (in != null)
in.close();
if (out != null)
out.close();
client.close();
}
}
| 0 | 591 | 5 | 683 | 5 | 722 | 5 | 683 | 5 | 884 | 11 | false | false | false | false | false | true |
28402_4 | package info.meizi.net;
import android.app.IntentService;
import android.content.Intent;
import com.squareup.okhttp.OkHttpClient;
import java.io.IOException;
import java.util.List;
import info.meizi.bean.MainBean;
import info.meizi.utils.LogUtils;
import info.meizi.utils.Utils;
import io.realm.Realm;
/**
* Created by Mr_Wrong on 15/10/9.
*/
public class MainService extends IntentService {
private static final String TAG = "MainService";
private final OkHttpClient client = new OkHttpClient();
private Realm realm;
private Intent resuleintent;
private String type;//首页的类型 性感,日本。。
private String html;
private String mPage;//加载更多的
public MainService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
type = intent.getStringExtra("type");
mPage = intent.getStringExtra("page");
//返回结果的
resuleintent = new Intent(type);
realm = Realm.getInstance(this);
List<MainBean> latest = MainBean.all(realm, type);
boolean hasdata = latest.size() >= Page2int(mPage) * 24;//数据库有数据
boolean firstload = Page2int(mPage) == 1;//第一次加载||刷新
boolean loadmore = Page2int(mPage) != 1;//加载更多
LogUtils.e("数据库有数据:" + hasdata + " 第一次加载||刷新:" + firstload + " loadmore:" + loadmore);
if (hasdata) {//数据库有
if (firstload) {//刷新
resuleintent.putExtra("isRefreshe", true);
}
} else {//数据库没有 就是第一次加载
if (loadmore) {
resuleintent.putExtra("isLoadmore", true);
} else {
resuleintent.putExtra("isFirstload", true);
}
}
loaddata();
sendBroadcast(resuleintent);
realm.close();
}
//加载数据
private void loaddata() {
try {
html = client.newCall(RequestFactory.make(Utils.makeUrl(type, mPage))).execute().body().string();
LogUtils.d("http://www.mzitu.com/" + Utils.makeUrl(type, mPage));
List<MainBean> list = ContentParser.ParserMainBean(html, type);
saveDb(realm, list);
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveDb(Realm realm, List<MainBean> list) {
realm.beginTransaction();
realm.copyToRealmOrUpdate(list);
realm.commitTransaction();
}
int Page2int(String s) {
int i = 1;
if (!s.equals("")) {
i = Integer.parseInt(s);
}
return i;
}
}
| 70kg/Meizi | app/src/main/java/info/meizi/net/MainService.java | 684 | //数据库有数据 | line_comment | zh-cn | package info.meizi.net;
import android.app.IntentService;
import android.content.Intent;
import com.squareup.okhttp.OkHttpClient;
import java.io.IOException;
import java.util.List;
import info.meizi.bean.MainBean;
import info.meizi.utils.LogUtils;
import info.meizi.utils.Utils;
import io.realm.Realm;
/**
* Created by Mr_Wrong on 15/10/9.
*/
public class MainService extends IntentService {
private static final String TAG = "MainService";
private final OkHttpClient client = new OkHttpClient();
private Realm realm;
private Intent resuleintent;
private String type;//首页的类型 性感,日本。。
private String html;
private String mPage;//加载更多的
public MainService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
type = intent.getStringExtra("type");
mPage = intent.getStringExtra("page");
//返回结果的
resuleintent = new Intent(type);
realm = Realm.getInstance(this);
List<MainBean> latest = MainBean.all(realm, type);
boolean hasdata = latest.size() >= Page2int(mPage) * 24;//数据 <SUF>
boolean firstload = Page2int(mPage) == 1;//第一次加载||刷新
boolean loadmore = Page2int(mPage) != 1;//加载更多
LogUtils.e("数据库有数据:" + hasdata + " 第一次加载||刷新:" + firstload + " loadmore:" + loadmore);
if (hasdata) {//数据库有
if (firstload) {//刷新
resuleintent.putExtra("isRefreshe", true);
}
} else {//数据库没有 就是第一次加载
if (loadmore) {
resuleintent.putExtra("isLoadmore", true);
} else {
resuleintent.putExtra("isFirstload", true);
}
}
loaddata();
sendBroadcast(resuleintent);
realm.close();
}
//加载数据
private void loaddata() {
try {
html = client.newCall(RequestFactory.make(Utils.makeUrl(type, mPage))).execute().body().string();
LogUtils.d("http://www.mzitu.com/" + Utils.makeUrl(type, mPage));
List<MainBean> list = ContentParser.ParserMainBean(html, type);
saveDb(realm, list);
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveDb(Realm realm, List<MainBean> list) {
realm.beginTransaction();
realm.copyToRealmOrUpdate(list);
realm.commitTransaction();
}
int Page2int(String s) {
int i = 1;
if (!s.equals("")) {
i = Integer.parseInt(s);
}
return i;
}
}
| 0 | 607 | 4 | 684 | 4 | 723 | 4 | 684 | 4 | 837 | 7 | false | false | false | false | false | true |
53280_1 | package OMWork2.task3;
/* 数据操作类*/
public class DateOperator {
/* 年,月,日*/
int year;
int month;
int day;
/* year构造函数*/
public DateOperator(int year) {
this.year = year;
}
/* 全参构造*/
public DateOperator(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
/* 根据日期计算星期数*/
public int getWeekNum(){
/* 借助吉姆拉尔森公式*/
int year;
int month;
int day;
if(this.month == 1 || this.month == 2){
month = this.month + 12;
year = this.year - 1;
}
else {
month = this.month;
year = this.year;
}
day = this.day;
return (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400+1)%7;
}
/* 打印日历基本信息*/
public void printBasicInfo(){
System.out.print("\n\n "+this.year+"年"+this.month+"月\n");
System.out.print("日\t一\t二\t三\t四\t五\t六\n");
}
/* 给定年份,判断是否为闰年*/
public boolean judLeapYear(){
// bug修复 https://github.com/711lxsky/In-classStorage/issues/1
return (this.year % 4 == 0 && this.year % 100 != 0) || this.year /% 400 == 0;
}
/* 根据月份,返回该月天数*/
public int getDayNum(){
switch (this.month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
/* 闰年2月29天*/
if(this.judLeapYear()){
return 29;
}
else {
return 28;
}
default:
return 0;
}
}
/* 打印日历*/
public void printCalender(){
/* 循环打印月份日历*/
for(int i = 0 ; i < 12 ; i ++){
this.month = i + 1;
this.day = 1 ;
this.printBasicInfo();
while (this.day <= this.getDayNum()){
/* 抓取每月1号的星期数,以此为基准打印其余天数*/
int weekNum = this.getWeekNum();
if(this.day == 1){
for(int j = 0 ; j < weekNum ; j ++){
System.out.print("\t");
}
System.out.print(this.day+"\t");
}
else {
System.out.print(this.day+"\t");
}
if(weekNum == 6){
System.out.print("\n");
}
this.day++;
}
}
}
}
| 711lxsky/In-classStorage | java程序设计/交作业整理/22009200439_赵宇阳_第2次上机作业/src/OMWork2/task3/DateOperator.java | 799 | /* 年,月,日*/ | block_comment | zh-cn | package OMWork2.task3;
/* 数据操作类*/
public class DateOperator {
/* 年,月 <SUF>*/
int year;
int month;
int day;
/* year构造函数*/
public DateOperator(int year) {
this.year = year;
}
/* 全参构造*/
public DateOperator(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
/* 根据日期计算星期数*/
public int getWeekNum(){
/* 借助吉姆拉尔森公式*/
int year;
int month;
int day;
if(this.month == 1 || this.month == 2){
month = this.month + 12;
year = this.year - 1;
}
else {
month = this.month;
year = this.year;
}
day = this.day;
return (day+2*month+3*(month+1)/5+year+year/4-year/100+year/400+1)%7;
}
/* 打印日历基本信息*/
public void printBasicInfo(){
System.out.print("\n\n "+this.year+"年"+this.month+"月\n");
System.out.print("日\t一\t二\t三\t四\t五\t六\n");
}
/* 给定年份,判断是否为闰年*/
public boolean judLeapYear(){
// bug修复 https://github.com/711lxsky/In-classStorage/issues/1
return (this.year % 4 == 0 && this.year % 100 != 0) || this.year /% 400 == 0;
}
/* 根据月份,返回该月天数*/
public int getDayNum(){
switch (this.month){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
/* 闰年2月29天*/
if(this.judLeapYear()){
return 29;
}
else {
return 28;
}
default:
return 0;
}
}
/* 打印日历*/
public void printCalender(){
/* 循环打印月份日历*/
for(int i = 0 ; i < 12 ; i ++){
this.month = i + 1;
this.day = 1 ;
this.printBasicInfo();
while (this.day <= this.getDayNum()){
/* 抓取每月1号的星期数,以此为基准打印其余天数*/
int weekNum = this.getWeekNum();
if(this.day == 1){
for(int j = 0 ; j < weekNum ; j ++){
System.out.print("\t");
}
System.out.print(this.day+"\t");
}
else {
System.out.print(this.day+"\t");
}
if(weekNum == 6){
System.out.print("\n");
}
this.day++;
}
}
}
}
| 0 | 721 | 8 | 799 | 7 | 867 | 7 | 799 | 7 | 970 | 8 | false | false | false | false | false | true |
65330_6 | /*
* @Author: error: git config user.name && git config user.email & please set dead value or install git
* @Date: 2022-08-23 23:55:45
* @LastEditors: error: git config user.name && git config user.email & please set dead value or install git
* @LastEditTime: 2022-08-24 00:02:41
* @FilePath: \CareUEveryDay\src\main\java\cn\ofpp\Application.java
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
package cn.ofpp;
import cn.ofpp.core.BoyFriend;
import cn.ofpp.core.GirlFriend;
import cn.ofpp.core.MessageFactory;
import cn.ofpp.core.Wx;
/**
* 启动类
*
* 这个理论上只能用测试号 正式的号 个人认证是不支持模板消息的 企业认证的又必须使用微信模板库里的模板 只有测试的可以自定义模板内容
* <a href="https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index">申请公众号测试应用地址</a>
*
* @author DokiYolo
* Date 2022-08-22
*/
public class Application {
/**
* <li>创建配置</li>
* <li>创建几个 男/女 朋友</li>
* <li>发消息</li>
*/
public static void main(String[] args) {
// load and init
Bootstrap.init();
// ----------------- 以下为演示数据 ------------------------
// new 一个 女友
GirlFriend girlFriend = new GirlFriend("某女友",
"江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE56Ptipba5kSXWlNk2CG6-uA");
Wx.sendTemplateMessage(MessageFactory.resolveMessage(girlFriend));
// new 一个 男友 也可单独针对一个friend设置模板ID 以达到不同人不同消息
BoyFriend boyFriend = new BoyFriend("某男友",
"江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE5ywPoqRjCOLOjZkZMDni1Qo");
Wx.sendTemplateMessage(MessageFactory.resolveMessage(boyFriend));
BoyFriend boysFriend = new BoyFriend("某男友",
"江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE53eR8ceYplm-cqOiz2luJD8");
Wx.sendTemplateMessage(MessageFactory.resolveMessage(boysFriend));
}
}
| 717986230/daynew | src/main/java/cn/ofpp/Application.java | 784 | // new 一个 男友 也可单独针对一个friend设置模板ID 以达到不同人不同消息
| line_comment | zh-cn | /*
* @Author: error: git config user.name && git config user.email & please set dead value or install git
* @Date: 2022-08-23 23:55:45
* @LastEditors: error: git config user.name && git config user.email & please set dead value or install git
* @LastEditTime: 2022-08-24 00:02:41
* @FilePath: \CareUEveryDay\src\main\java\cn\ofpp\Application.java
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/
package cn.ofpp;
import cn.ofpp.core.BoyFriend;
import cn.ofpp.core.GirlFriend;
import cn.ofpp.core.MessageFactory;
import cn.ofpp.core.Wx;
/**
* 启动类
*
* 这个理论上只能用测试号 正式的号 个人认证是不支持模板消息的 企业认证的又必须使用微信模板库里的模板 只有测试的可以自定义模板内容
* <a href="https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index">申请公众号测试应用地址</a>
*
* @author DokiYolo
* Date 2022-08-22
*/
public class Application {
/**
* <li>创建配置</li>
* <li>创建几个 男/女 朋友</li>
* <li>发消息</li>
*/
public static void main(String[] args) {
// load and init
Bootstrap.init();
// ----------------- 以下为演示数据 ------------------------
// new 一个 女友
GirlFriend girlFriend = new GirlFriend("某女友",
"江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE56Ptipba5kSXWlNk2CG6-uA");
Wx.sendTemplateMessage(MessageFactory.resolveMessage(girlFriend));
// ne <SUF>
BoyFriend boyFriend = new BoyFriend("某男友",
"江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE5ywPoqRjCOLOjZkZMDni1Qo");
Wx.sendTemplateMessage(MessageFactory.resolveMessage(boyFriend));
BoyFriend boysFriend = new BoyFriend("某男友",
"江苏省", "南京市", "1999-08-08", "2011-04-16", "oV7oE53eR8ceYplm-cqOiz2luJD8");
Wx.sendTemplateMessage(MessageFactory.resolveMessage(boysFriend));
}
}
| 0 | 696 | 23 | 779 | 26 | 745 | 21 | 779 | 26 | 933 | 41 | false | false | false | false | false | true |
19565_14 | package com.yuu.recruit.vo;
import com.yuu.recruit.domain.Employee;
import com.yuu.recruit.domain.Employer;
import com.yuu.recruit.domain.TaskCategory;
import com.yuu.recruit.domain.TaskSkill;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 任务页面展示对象
*
* @author by yuu
* @Classname TaskVo
* @Date 2019/10/13 20:19
* @see com.yuu.recruit.vo
*/
@Data
public class TaskVo implements Serializable {
private static final long serialVersionUID = -1264009471871480548L;
/**
* 任务ID
*/
private Long id;
/**
* 任务分类
*/
private TaskCategory taskCategory;
/**
* 任务发布雇主信息
*/
private Employer employer;
/**
* 任务标题
*/
private String taskTitle;
/**
* 任务简介
*/
private String taskProfile;
/**
* 任务描述
*/
private String taskDesc;
/**
* 最低预算价格
*/
private Double feesLow;
/**
* 最高预算价格
*/
private Double feesHigh;
/**
* 任务附件地址
*/
private String feesFile;
/**
* 任务附件地址
*/
private String filename;
/**
* 完成任务雇员ID
*/
private Employee employee;
/**
* 任务成交价格
*/
private Double taskPrice;
/**
* 任务状态
*/
private Byte taskStatus;
/**
* 任务中标时间
*/
private Date bidTime;
/**
* 任务成交时间
*/
private Date closeTime;
/**
* 创建时间
*/
private Date createTime;
/**
* 多久以前发布
*/
private String beforeTime;
/**
* 任务到期时间
*/
private Date expireTime;
/**
* 任务所需技能标签
*/
private List<TaskSkill> skills;
/**
* 该任务所有竞标者
*/
private List<BidVo> bidVos;
/**
* 平均竞标价格
*/
private Double avgPrice;
}
| 71yuu/springboot-recruit | src/main/java/com/yuu/recruit/vo/TaskVo.java | 569 | /**
* 任务中标时间
*/ | block_comment | zh-cn | package com.yuu.recruit.vo;
import com.yuu.recruit.domain.Employee;
import com.yuu.recruit.domain.Employer;
import com.yuu.recruit.domain.TaskCategory;
import com.yuu.recruit.domain.TaskSkill;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 任务页面展示对象
*
* @author by yuu
* @Classname TaskVo
* @Date 2019/10/13 20:19
* @see com.yuu.recruit.vo
*/
@Data
public class TaskVo implements Serializable {
private static final long serialVersionUID = -1264009471871480548L;
/**
* 任务ID
*/
private Long id;
/**
* 任务分类
*/
private TaskCategory taskCategory;
/**
* 任务发布雇主信息
*/
private Employer employer;
/**
* 任务标题
*/
private String taskTitle;
/**
* 任务简介
*/
private String taskProfile;
/**
* 任务描述
*/
private String taskDesc;
/**
* 最低预算价格
*/
private Double feesLow;
/**
* 最高预算价格
*/
private Double feesHigh;
/**
* 任务附件地址
*/
private String feesFile;
/**
* 任务附件地址
*/
private String filename;
/**
* 完成任务雇员ID
*/
private Employee employee;
/**
* 任务成交价格
*/
private Double taskPrice;
/**
* 任务状态
*/
private Byte taskStatus;
/**
* 任务中 <SUF>*/
private Date bidTime;
/**
* 任务成交时间
*/
private Date closeTime;
/**
* 创建时间
*/
private Date createTime;
/**
* 多久以前发布
*/
private String beforeTime;
/**
* 任务到期时间
*/
private Date expireTime;
/**
* 任务所需技能标签
*/
private List<TaskSkill> skills;
/**
* 该任务所有竞标者
*/
private List<BidVo> bidVos;
/**
* 平均竞标价格
*/
private Double avgPrice;
}
| 0 | 524 | 10 | 569 | 10 | 600 | 11 | 569 | 10 | 779 | 14 | false | false | false | false | false | true |
11400_7 | package me.chanjar.weixin.mp.bean.kefu.result;
import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
/**
* 客服基本信息以及客服在线状态信息
*
* @author Binary Wang
*/
@Data
public class WxMpKfInfo implements Serializable {
private static final long serialVersionUID = -5877300750666022290L;
/**
* kf_account 完整客服账号,格式为:账号前缀@公众号微信号
*/
@SerializedName("kf_account")
private String account;
/**
* kf_headimgurl 客服头像地址
*/
@SerializedName("kf_headimgurl")
private String headImgUrl;
/**
* kf_id 客服工号
*/
@SerializedName("kf_id")
private String id;
/**
* kf_nick 客服昵称
*/
@SerializedName("kf_nick")
private String nick;
/**
* kf_wx 如果客服帐号已绑定了客服人员微信号,则此处显示微信号
*/
@SerializedName("kf_wx")
private String wxAccount;
/**
* invite_wx 如果客服帐号尚未绑定微信号,但是已经发起了一个绑定邀请,则此处显示绑定邀请的微信号
*/
@SerializedName("invite_wx")
private String inviteWx;
/**
* invite_expire_time 如果客服帐号尚未绑定微信号,但是已经发起过一个绑定邀请,则此处显示为邀请的过期时间,为unix 时间戳
*/
@SerializedName("invite_expire_time")
private Long inviteExpireTime;
/**
* invite_status 邀请的状态,有等待确认“waiting”,被拒绝“rejected”,过期“expired”
*/
@SerializedName("invite_status")
private String inviteStatus;
/**
* status 客服在线状态,目前为:1、web 在线
*/
@SerializedName("status")
private Integer status;
/**
* accepted_case 客服当前正在接待的会话数
*/
@Expose
@SerializedName("accepted_case")
private Integer acceptedCase;
@Override
public String toString() {
return WxMpGsonBuilder.create().toJson(this);
}
}
| 723580451/Wechat-Group-WxJava | weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/kefu/result/WxMpKfInfo.java | 601 | /**
* invite_expire_time 如果客服帐号尚未绑定微信号,但是已经发起过一个绑定邀请,则此处显示为邀请的过期时间,为unix 时间戳
*/ | block_comment | zh-cn | package me.chanjar.weixin.mp.bean.kefu.result;
import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder;
/**
* 客服基本信息以及客服在线状态信息
*
* @author Binary Wang
*/
@Data
public class WxMpKfInfo implements Serializable {
private static final long serialVersionUID = -5877300750666022290L;
/**
* kf_account 完整客服账号,格式为:账号前缀@公众号微信号
*/
@SerializedName("kf_account")
private String account;
/**
* kf_headimgurl 客服头像地址
*/
@SerializedName("kf_headimgurl")
private String headImgUrl;
/**
* kf_id 客服工号
*/
@SerializedName("kf_id")
private String id;
/**
* kf_nick 客服昵称
*/
@SerializedName("kf_nick")
private String nick;
/**
* kf_wx 如果客服帐号已绑定了客服人员微信号,则此处显示微信号
*/
@SerializedName("kf_wx")
private String wxAccount;
/**
* invite_wx 如果客服帐号尚未绑定微信号,但是已经发起了一个绑定邀请,则此处显示绑定邀请的微信号
*/
@SerializedName("invite_wx")
private String inviteWx;
/**
* inv <SUF>*/
@SerializedName("invite_expire_time")
private Long inviteExpireTime;
/**
* invite_status 邀请的状态,有等待确认“waiting”,被拒绝“rejected”,过期“expired”
*/
@SerializedName("invite_status")
private String inviteStatus;
/**
* status 客服在线状态,目前为:1、web 在线
*/
@SerializedName("status")
private Integer status;
/**
* accepted_case 客服当前正在接待的会话数
*/
@Expose
@SerializedName("accepted_case")
private Integer acceptedCase;
@Override
public String toString() {
return WxMpGsonBuilder.create().toJson(this);
}
}
| 0 | 511 | 37 | 601 | 53 | 596 | 42 | 601 | 53 | 833 | 79 | false | false | false | false | false | true |
33526_2 | package servlet;
import java.io.IOException;
import java.lang.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PlayGamesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
/**
* 获取用户名和密码
*/
String numberString=request.getParameter("number");
String usernameString=request.getParameter("user");
int number=Integer.valueOf(numberString);
/**
* 随机生成数字
*/
int integer=(int)(1+Math.random()*10);
String msgString=null;
if(number>integer) {
msgString="猜大啦!";
}else if (number==integer) {
msgString="猜中了!恭喜";
}else {
msgString="猜小了!";
}
request.setAttribute("msg", msgString);
//封装request后需要用转发而不是重定向,不然数据传不过去
request.getRequestDispatcher("doGames").forward(request, response);
//response.sendRedirect("doGames");
}
}
| 729748198/JSPandServlet | src/servlet/PlayGamesServlet.java | 317 | /**
* 随机生成数字
*/ | block_comment | zh-cn | package servlet;
import java.io.IOException;
import java.lang.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PlayGamesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
/**
* 获取用户名和密码
*/
String numberString=request.getParameter("number");
String usernameString=request.getParameter("user");
int number=Integer.valueOf(numberString);
/**
* 随机生 <SUF>*/
int integer=(int)(1+Math.random()*10);
String msgString=null;
if(number>integer) {
msgString="猜大啦!";
}else if (number==integer) {
msgString="猜中了!恭喜";
}else {
msgString="猜小了!";
}
request.setAttribute("msg", msgString);
//封装request后需要用转发而不是重定向,不然数据传不过去
request.getRequestDispatcher("doGames").forward(request, response);
//response.sendRedirect("doGames");
}
}
| 0 | 247 | 12 | 311 | 9 | 311 | 11 | 311 | 9 | 394 | 18 | false | false | false | false | false | true |
64212_8 | //问题描述
// 自从Peter Stuyvesant和Abel Tasman的日子以后,荷兰商人已经周游世界来买卖商品。有一次在Verweggistan的贸易,但是它在很短的时间后就结束了。在读完这个故事之后你就明白了。
// 在当时Verweggistan是非常受欢迎的,因为世界上只有那个地方的人知道怎样制作一个“prul”(或者“prullen”,荷兰语中的复数形式),并且如今只有很少的人知道什么是一个“prul”。
// “prul”是在工场里生产的。当一个“prul”做完的时候,它被包装在一个箱子里,然后放在之前生产的“prul”所装的箱子堆的上面。
// 价格取决于生产“prul”所需要的时间。如果一切顺利,一个“prul”的价格会是1或者2弗罗林,但是在一个恶劣的日子,价格会很容易地上升到15弗罗林或者更高。“prul”在品质上没有什么差别,所有的“prul”具有相同的价值。
// 在这些天,“prul”在荷兰的售价为每件10弗罗林。交通运输的费用是可以忽略的,因为“prul”无论如何都会作为额外的东西被装载到要航行的船上。当一个荷兰商人去Verweggistan时,他有一个明确的目的:买“prul”,在荷兰销售,并且最大化他的利润。不幸的是,Verweggistan地区对“prul”的交易方式使得这比某些人预想的更为复杂。
// 有人认为这很简单,商人会买那些最便宜的“prul”,而那些售价比10弗罗林高的“prul”会一直不能出售。不幸的是,Verweggistan的所有工场按照一种奇怪的顺序销售“prul”。堆顶的箱子里的“prul”会最先销售,然后销售从顶上开始数的第二个箱子里的“prul”,以此类推。所以即使第五个箱子里的“prul”是最便宜的,商人也必须买它上面四个箱子里的“prul”才能得到它。
// 正如你想象的那样,这使得商人通过购买正确的“prul”的组合来最大化他们的利润是相当难的。没有电脑帮助他们的优化,他们迅速彻底失去了交易“prul”的兴趣。
// 在这个问题中,给你对几个工场里箱子堆的描述。你必须根据上面所给的限制,计算出一个商人通过购买箱子堆中的“prul”可以获得的最大利润。另外,你必须确定他需要买多少个“prul”才能获得最大利润。
//输入格式
// 输入文件包含多组测试数据。每个测试数据的第一行是一个整数w(1<=w<=50),该测试数据中工场的数目。
// 接下来有w行,每行描述一个放“prul”的箱子堆。每行的第一个整数b(0<=b<=20),表示堆中的箱子数。接下来是b个正整数,表示堆中“prul”的价格(单位为弗罗林)。输入中箱子的顺序是从顶到底。
// 输入数据终止于w=0,不再有后续的描述内容。
//输出格式
// 对于每组测试数据,输出测试点的编号(1,2...)。然后输出两行,第一行输出商人可以获得的最大利润。第二行输出为获得最大利润商人需要买的“prul”数量。如果这个数量不是唯一确定的,按照升序输出可能的值。如果有超过10种可能的取值,只输出10个最小的取值。
//样例输入
//1
//6 12 3 10 7 16 5
//2
//5 7 3 11 9 10
//9 1 2 3 4 10 16 10 4 16
//0
//样例输出
//Workyards 1
//Maximum profit is 8.
//Number of pruls to buy: 4
//Workyards 2
//Maximum profit is 40.
//Number of pruls to buy: 6 7 8 9 10 12 13
//数据规模和约定
// 1<=w<=50,0<=b<=20,输入文件保证测试点个数不超过10。
package 算法提高;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Trade_on_Verweggistan {
private static int [][]book=new int[52][22];
private static Integer sum=0;
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// TODO Auto-generaed method stub
Scanner in=new Scanner(System.in);
int n;
ArrayList<Integer>[]list = null;
int ji=1;
while (in.hasNext()) {
n=in.nextInt();
if(n==0) {
return;
}
list=new ArrayList[n];
int j2=0;
for(int i=0;j2<n;i++) {
j2++;
int l=in.nextInt();
if(l==0) {
i--;
continue;
}
list[i]=new ArrayList<>(l);
for(int j=0;j<l;j++) {
list[i].add(10-in.nextInt());
book[i][j]=0;
}
}
//存储每个工厂可能是购买数
ArrayList[]result=new ArrayList[n];
for(int i=0;i<n;i++) {
result[i]=new ArrayList<>();
}
//存储每个工厂的最大利润
ArrayList<Integer> maxnum=new ArrayList<>();
for(int i=0;i<list.length;i++) {
//用一个数组计算出每一个工厂最大利润和可能的购买数
int[]temp=new int[list[i].size()];
int max=0;
for(int j=0;j<list[i].size();j++) {
if(j==0) {
temp[0]=list[i].get(0);
}else
temp[j]=temp[j-1]+list[i].get(j);
if(temp[j]>max) {
max=temp[j];
}
}
//每个工厂的最大利润
maxnum.add(max);
boolean empty=true;
for(int j=0;j<temp.length;j++) {
//System.out.println("当前的最大和"+maxnum.get(i)+" temp[j]"+temp[j]);
if(temp[j]==maxnum.get(i)) {
empty=false;
result[i].add(j+1);
}
}
if(empty) {
result[i].add(0);
}
}
System.out.println("Workyards "+ji);
ji++;
//最大利润max
int max=0;
//System.out.println("每行最大利润");
for(int i=0;i<maxnum.size();i++) {
//System.out.print(maxnum.get(i)+" ");
max+=maxnum.get(i);
}
System.out.println("Maximum profit is "+max+".");
//可能的组合,每个
Set<Integer>set=new HashSet<>();
dfs(result, set,0);
System.out.print("Number of pruls to buy:");
Iterator iterator=set.iterator();
for(int i=0;i<10;i++) {
if(iterator.hasNext())
System.out.print(iterator.next()+" ");
else {
break;
}
}
System.out.println();
}
}
public static void dfs(ArrayList[]result,Set<Integer>set,int ji) {
if(ji>=result.length) {
set.add(sum);
return;
}
for(int i=0;i<result[ji].size();i++) {
if(book[ji][i]==0) {
sum+=(Integer) result[ji].get(i);
book[ji][i]=1;
dfs(result, set, ji+1);
sum-=(Integer)result[ji].get(i);
book[ji][i]=0;
}
}
}
}
| 729748198/Lanqiao | src/算法提高/Trade_on_Verweggistan.java | 2,281 | // 在这个问题中,给你对几个工场里箱子堆的描述。你必须根据上面所给的限制,计算出一个商人通过购买箱子堆中的“prul”可以获得的最大利润。另外,你必须确定他需要买多少个“prul”才能获得最大利润。
| line_comment | zh-cn | //问题描述
// 自从Peter Stuyvesant和Abel Tasman的日子以后,荷兰商人已经周游世界来买卖商品。有一次在Verweggistan的贸易,但是它在很短的时间后就结束了。在读完这个故事之后你就明白了。
// 在当时Verweggistan是非常受欢迎的,因为世界上只有那个地方的人知道怎样制作一个“prul”(或者“prullen”,荷兰语中的复数形式),并且如今只有很少的人知道什么是一个“prul”。
// “prul”是在工场里生产的。当一个“prul”做完的时候,它被包装在一个箱子里,然后放在之前生产的“prul”所装的箱子堆的上面。
// 价格取决于生产“prul”所需要的时间。如果一切顺利,一个“prul”的价格会是1或者2弗罗林,但是在一个恶劣的日子,价格会很容易地上升到15弗罗林或者更高。“prul”在品质上没有什么差别,所有的“prul”具有相同的价值。
// 在这些天,“prul”在荷兰的售价为每件10弗罗林。交通运输的费用是可以忽略的,因为“prul”无论如何都会作为额外的东西被装载到要航行的船上。当一个荷兰商人去Verweggistan时,他有一个明确的目的:买“prul”,在荷兰销售,并且最大化他的利润。不幸的是,Verweggistan地区对“prul”的交易方式使得这比某些人预想的更为复杂。
// 有人认为这很简单,商人会买那些最便宜的“prul”,而那些售价比10弗罗林高的“prul”会一直不能出售。不幸的是,Verweggistan的所有工场按照一种奇怪的顺序销售“prul”。堆顶的箱子里的“prul”会最先销售,然后销售从顶上开始数的第二个箱子里的“prul”,以此类推。所以即使第五个箱子里的“prul”是最便宜的,商人也必须买它上面四个箱子里的“prul”才能得到它。
// 正如你想象的那样,这使得商人通过购买正确的“prul”的组合来最大化他们的利润是相当难的。没有电脑帮助他们的优化,他们迅速彻底失去了交易“prul”的兴趣。
// <SUF>
//输入格式
// 输入文件包含多组测试数据。每个测试数据的第一行是一个整数w(1<=w<=50),该测试数据中工场的数目。
// 接下来有w行,每行描述一个放“prul”的箱子堆。每行的第一个整数b(0<=b<=20),表示堆中的箱子数。接下来是b个正整数,表示堆中“prul”的价格(单位为弗罗林)。输入中箱子的顺序是从顶到底。
// 输入数据终止于w=0,不再有后续的描述内容。
//输出格式
// 对于每组测试数据,输出测试点的编号(1,2...)。然后输出两行,第一行输出商人可以获得的最大利润。第二行输出为获得最大利润商人需要买的“prul”数量。如果这个数量不是唯一确定的,按照升序输出可能的值。如果有超过10种可能的取值,只输出10个最小的取值。
//样例输入
//1
//6 12 3 10 7 16 5
//2
//5 7 3 11 9 10
//9 1 2 3 4 10 16 10 4 16
//0
//样例输出
//Workyards 1
//Maximum profit is 8.
//Number of pruls to buy: 4
//Workyards 2
//Maximum profit is 40.
//Number of pruls to buy: 6 7 8 9 10 12 13
//数据规模和约定
// 1<=w<=50,0<=b<=20,输入文件保证测试点个数不超过10。
package 算法提高;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
public class Trade_on_Verweggistan {
private static int [][]book=new int[52][22];
private static Integer sum=0;
@SuppressWarnings("unchecked")
public static void main(String[] args) {
// TODO Auto-generaed method stub
Scanner in=new Scanner(System.in);
int n;
ArrayList<Integer>[]list = null;
int ji=1;
while (in.hasNext()) {
n=in.nextInt();
if(n==0) {
return;
}
list=new ArrayList[n];
int j2=0;
for(int i=0;j2<n;i++) {
j2++;
int l=in.nextInt();
if(l==0) {
i--;
continue;
}
list[i]=new ArrayList<>(l);
for(int j=0;j<l;j++) {
list[i].add(10-in.nextInt());
book[i][j]=0;
}
}
//存储每个工厂可能是购买数
ArrayList[]result=new ArrayList[n];
for(int i=0;i<n;i++) {
result[i]=new ArrayList<>();
}
//存储每个工厂的最大利润
ArrayList<Integer> maxnum=new ArrayList<>();
for(int i=0;i<list.length;i++) {
//用一个数组计算出每一个工厂最大利润和可能的购买数
int[]temp=new int[list[i].size()];
int max=0;
for(int j=0;j<list[i].size();j++) {
if(j==0) {
temp[0]=list[i].get(0);
}else
temp[j]=temp[j-1]+list[i].get(j);
if(temp[j]>max) {
max=temp[j];
}
}
//每个工厂的最大利润
maxnum.add(max);
boolean empty=true;
for(int j=0;j<temp.length;j++) {
//System.out.println("当前的最大和"+maxnum.get(i)+" temp[j]"+temp[j]);
if(temp[j]==maxnum.get(i)) {
empty=false;
result[i].add(j+1);
}
}
if(empty) {
result[i].add(0);
}
}
System.out.println("Workyards "+ji);
ji++;
//最大利润max
int max=0;
//System.out.println("每行最大利润");
for(int i=0;i<maxnum.size();i++) {
//System.out.print(maxnum.get(i)+" ");
max+=maxnum.get(i);
}
System.out.println("Maximum profit is "+max+".");
//可能的组合,每个
Set<Integer>set=new HashSet<>();
dfs(result, set,0);
System.out.print("Number of pruls to buy:");
Iterator iterator=set.iterator();
for(int i=0;i<10;i++) {
if(iterator.hasNext())
System.out.print(iterator.next()+" ");
else {
break;
}
}
System.out.println();
}
}
public static void dfs(ArrayList[]result,Set<Integer>set,int ji) {
if(ji>=result.length) {
set.add(sum);
return;
}
for(int i=0;i<result[ji].size();i++) {
if(book[ji][i]==0) {
sum+=(Integer) result[ji].get(i);
book[ji][i]=1;
dfs(result, set, ji+1);
sum-=(Integer)result[ji].get(i);
book[ji][i]=0;
}
}
}
}
| 0 | 1,795 | 63 | 2,245 | 76 | 2,016 | 65 | 2,245 | 76 | 3,113 | 127 | false | false | false | false | false | true |
58988_2 | /**
* Copyright© 2003-2016 浙江汇信科技有限公司, All Rights Reserved. <br/>
*/
package com.icinfo.cs.base.model;
import com.icinfo.framework.mybatis.mapper.annotation.Before;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
/**
* 描述: cs_code_regorg 对应的实体类.<br>
* WARNING:不是表中字段的属性必须加@Transient注解
* @author framework generator
* @date 2016年09月12日
*/
@Table(name = "cs_code_regorg")
public class CodeRegorg implements Serializable {
@Id
@Column(name = "id")
@Before
@GeneratedValue(strategy = GenerationType.IDENTITY,generator="select replace(uuid(), '-', '')")
private Integer id;
@Column(name = "ContentWord")
private String contentWord;
@Column(name = "ContentShort")
private String contentShort;
@Column(name = "Content")
private String content;
@Column(name = "Code")
private String code;
//登记机关联络员
@Column(name = "LiaName")
private String liaName;
//联络员电话号码
@Column(name = "LiaPhone")
private String liaPhone;
private static final long serialVersionUID = 1L;
/**
* @return id
*/
public Integer getId() {
return id;
}
/**
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return ContentWord
*/
public String getContentWord() {
return contentWord;
}
/**
* @param contentWord
*/
public void setContentWord(String contentWord) {
this.contentWord = contentWord;
}
/**
* @return ContentShort
*/
public String getContentShort() {
return contentShort;
}
/**
* @param contentShort
*/
public void setContentShort(String contentShort) {
this.contentShort = contentShort;
}
/**
* @return Content
*/
public String getContent() {
return content;
}
/**
* @param content
*/
public void setContent(String content) {
this.content = content;
}
/**
* @return Code
*/
public String getCode() {
return code;
}
/**
* @param code
*/
public void setCode(String code) {
this.code = code;
}
public void setLiaName(String liaName) {
this.liaName = liaName;
}
public String getLiaName() {
return liaName;
}
public void setLiaPhone(String liaPhone) {
this.liaPhone = liaPhone;
}
public String getLiaPhone() {
return liaPhone;
}
} | 7373/enterprise-information-exchange-and-sharing-system | src/main/java/com/src/xt/base/model/CodeRegorg.java | 701 | //登记机关联络员 | line_comment | zh-cn | /**
* Copyright© 2003-2016 浙江汇信科技有限公司, All Rights Reserved. <br/>
*/
package com.icinfo.cs.base.model;
import com.icinfo.framework.mybatis.mapper.annotation.Before;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.*;
/**
* 描述: cs_code_regorg 对应的实体类.<br>
* WARNING:不是表中字段的属性必须加@Transient注解
* @author framework generator
* @date 2016年09月12日
*/
@Table(name = "cs_code_regorg")
public class CodeRegorg implements Serializable {
@Id
@Column(name = "id")
@Before
@GeneratedValue(strategy = GenerationType.IDENTITY,generator="select replace(uuid(), '-', '')")
private Integer id;
@Column(name = "ContentWord")
private String contentWord;
@Column(name = "ContentShort")
private String contentShort;
@Column(name = "Content")
private String content;
@Column(name = "Code")
private String code;
//登记 <SUF>
@Column(name = "LiaName")
private String liaName;
//联络员电话号码
@Column(name = "LiaPhone")
private String liaPhone;
private static final long serialVersionUID = 1L;
/**
* @return id
*/
public Integer getId() {
return id;
}
/**
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
* @return ContentWord
*/
public String getContentWord() {
return contentWord;
}
/**
* @param contentWord
*/
public void setContentWord(String contentWord) {
this.contentWord = contentWord;
}
/**
* @return ContentShort
*/
public String getContentShort() {
return contentShort;
}
/**
* @param contentShort
*/
public void setContentShort(String contentShort) {
this.contentShort = contentShort;
}
/**
* @return Content
*/
public String getContent() {
return content;
}
/**
* @param content
*/
public void setContent(String content) {
this.content = content;
}
/**
* @return Code
*/
public String getCode() {
return code;
}
/**
* @param code
*/
public void setCode(String code) {
this.code = code;
}
public void setLiaName(String liaName) {
this.liaName = liaName;
}
public String getLiaName() {
return liaName;
}
public void setLiaPhone(String liaPhone) {
this.liaPhone = liaPhone;
}
public String getLiaPhone() {
return liaPhone;
}
} | 0 | 627 | 5 | 701 | 7 | 760 | 6 | 701 | 7 | 855 | 10 | false | false | false | false | false | true |
51170_8 | package cn.itcast.heima2;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
public static void main(String[] args) {
//固定线程池
// ExecutorService threadPool = Executors.newFixedThreadPool(3);
//缓存线程池,任务执行不过来,自动增加新的线程
// ExecutorService threadPool = Executors.newCachedThreadPool();
//一个线程,好处,如果池子中的线程死了,会自动增加一个线程 (可以解决:如何实现线程死掉后重新启动)
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for(int i = 1; i <= 10; i++){
final int task = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
for(int j = 1; j <= 10; j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task " + task);
}
}
});
}
System.out.println(" all of 10 task have committed!!");
// threadPool.shutdown();//任务干完后关闭线程
// threadPool.shutdownNow();//任务没执行完毕也关闭
//定时器的线程池
Executors.newScheduledThreadPool(3).schedule(new Runnable() {
@Override
public void run() {
System.out.println("bombing !!!");
}
},
10,//多长时间后执行,10秒后执行
TimeUnit.SECONDS);
//每隔多长时间执行一次,以固定饿频率执行
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("bombing!!!!!");
}
},
6,//6秒后开始执行
2, //每隔2秒执行一次
TimeUnit.SECONDS);
}
}
| 75168859/ThreadTest2 | src/cn/itcast/heima2/ThreadPoolTest.java | 532 | //定时器的线程池 | line_comment | zh-cn | package cn.itcast.heima2;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolTest {
public static void main(String[] args) {
//固定线程池
// ExecutorService threadPool = Executors.newFixedThreadPool(3);
//缓存线程池,任务执行不过来,自动增加新的线程
// ExecutorService threadPool = Executors.newCachedThreadPool();
//一个线程,好处,如果池子中的线程死了,会自动增加一个线程 (可以解决:如何实现线程死掉后重新启动)
ExecutorService threadPool = Executors.newSingleThreadExecutor();
for(int i = 1; i <= 10; i++){
final int task = i;
threadPool.execute(new Runnable() {
@Override
public void run() {
for(int j = 1; j <= 10; j++){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " is looping of " + j + " for task " + task);
}
}
});
}
System.out.println(" all of 10 task have committed!!");
// threadPool.shutdown();//任务干完后关闭线程
// threadPool.shutdownNow();//任务没执行完毕也关闭
//定时 <SUF>
Executors.newScheduledThreadPool(3).schedule(new Runnable() {
@Override
public void run() {
System.out.println("bombing !!!");
}
},
10,//多长时间后执行,10秒后执行
TimeUnit.SECONDS);
//每隔多长时间执行一次,以固定饿频率执行
Executors.newScheduledThreadPool(3).scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("bombing!!!!!");
}
},
6,//6秒后开始执行
2, //每隔2秒执行一次
TimeUnit.SECONDS);
}
}
| 0 | 485 | 7 | 532 | 6 | 534 | 5 | 532 | 6 | 809 | 8 | false | false | false | false | false | true |
28838_1 | package com.lol.constans;
import com.lol.util.Utils;
public class MonsterData {
public static final java.util.HashMap<Integer, MonsterModel> monsterMap = new java.util.HashMap<Integer, MonsterModel>();
/**
* 静态构造 初次访问的时候自动调用
*/
static {
int random = Utils.getRandomNum(4, 7);
BuffModel river = new BuffModel();
BuffModel red = new BuffModel();
BuffModel blue = new BuffModel();
BuffModel wind_gragon = new BuffModel();
BuffModel fire_gragon = new BuffModel();
BuffModel water_gragon = new BuffModel();
BuffModel soil_gragon = new BuffModel();
BuffModel ancient_dragon = new BuffModel();
BuffModel pioneer_valley = new BuffModel();
BuffModel nash_baron = new BuffModel();
create(1, "红BUFF怪",0,70,4000,300,0,0,0,5,15,new int[]{},true,60,true,red,true);
create(2, "蓝BUFF怪",0,70,4000,300,0,0,0,0,0,new int[]{},true,60,true,blue,true);
create(3, "峡谷先锋",250,200,12000,300,0,0,0,0,0,new int[]{},false,0,true,pioneer_valley,true);
create(4, "纳什男爵",600,500,100000,300,0,0,0,0,0,new int[]{},true,3000,true,nash_baron,true);
//4龙 随机选1
create(5,BuffEnum.fromCode(random).getDescription()
,0,0,8000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(6,"三狼",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(6,"三狼儿子1",120,30,500,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(7,"三狼儿子2",120,30,500,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(8,"F4老爸",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(9,"F4儿子1",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(10,"F4儿子2",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(11,"F4儿子3",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(12,"F4儿子4",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(13,"石头老爸",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(14,"石头儿子1",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(15,"石头儿子2",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(16,"蛤蟆",150,50,2000,300,0,0,0,5,15,new int[]{},true,30,false,null,true);
create(17,"河蟹",0,0,4000,300,0,0,0,0,0,new int[]{},true,45,true,river,true);
}
/**
* 创建模型并添加进字典
* @param code
* @param name
* @param atkBase
* @param defBase
* @param hpBase
* @param speed
* @param atkArr
* @param defArr
* @param hpArr
* @param atkRange
* @param tailRange
* @param skills
* @param reborn
* @param rebornTime
* @param provideBuff
* @param buff
* @param neutrality
*/
private static void create(int code, String name, int atkBase, int defBase, int hpBase,int speed,int atkArr,
float defArr, int hpArr, float atkRange, float tailRange, int[] skills,
boolean reborn,int rebornTime,boolean provideBuff,BuffModel buff, boolean neutrality) {
MonsterModel model = new MonsterModel();
model.setCode(code); //策划定义的唯一编号
model.setName(name); //怪物名称
model.setAtkBase(atkBase); //初始(基础)攻击力
model.setDefBase(defBase); //初始防御
model.setHpBase(hpBase); //初始血量
model.setSpeed(speed); //移动速度
model.setAtkArr(atkArr); //攻击成长
model.setDefArr(defArr); //防御成长
model.setHpArr(hpArr); //血量成长
model.setAtkRange(atkRange); //攻击距离
model.setTailRange(tailRange); //跟踪范围
model.setSkills(skills); //拥有技能
model.setReborn(reborn); //是否复活
model.setRebornTime(rebornTime); //复活时间
model.setProvideBuff(provideBuff); //杀死后是否提供增益BUF
model.setBuff(buff); //buff;
model.setNeutrality(neutrality); //是否中立
monsterMap.put(code, model);
}
}
| 765741668/lolserver | Protocol/src/main/java/com/lol/constans/MonsterData.java | 1,667 | //4龙 随机选1 | line_comment | zh-cn | package com.lol.constans;
import com.lol.util.Utils;
public class MonsterData {
public static final java.util.HashMap<Integer, MonsterModel> monsterMap = new java.util.HashMap<Integer, MonsterModel>();
/**
* 静态构造 初次访问的时候自动调用
*/
static {
int random = Utils.getRandomNum(4, 7);
BuffModel river = new BuffModel();
BuffModel red = new BuffModel();
BuffModel blue = new BuffModel();
BuffModel wind_gragon = new BuffModel();
BuffModel fire_gragon = new BuffModel();
BuffModel water_gragon = new BuffModel();
BuffModel soil_gragon = new BuffModel();
BuffModel ancient_dragon = new BuffModel();
BuffModel pioneer_valley = new BuffModel();
BuffModel nash_baron = new BuffModel();
create(1, "红BUFF怪",0,70,4000,300,0,0,0,5,15,new int[]{},true,60,true,red,true);
create(2, "蓝BUFF怪",0,70,4000,300,0,0,0,0,0,new int[]{},true,60,true,blue,true);
create(3, "峡谷先锋",250,200,12000,300,0,0,0,0,0,new int[]{},false,0,true,pioneer_valley,true);
create(4, "纳什男爵",600,500,100000,300,0,0,0,0,0,new int[]{},true,3000,true,nash_baron,true);
//4龙 <SUF>
create(5,BuffEnum.fromCode(random).getDescription()
,0,0,8000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(6,"三狼",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(6,"三狼儿子1",120,30,500,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(7,"三狼儿子2",120,30,500,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(8,"F4老爸",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(9,"F4儿子1",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(10,"F4儿子2",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(11,"F4儿子3",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(12,"F4儿子4",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(13,"石头老爸",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(14,"石头儿子1",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(15,"石头儿子2",120,50,1000,300,0,0,0,0,0,new int[]{},true,30,false,null,true);
create(16,"蛤蟆",150,50,2000,300,0,0,0,5,15,new int[]{},true,30,false,null,true);
create(17,"河蟹",0,0,4000,300,0,0,0,0,0,new int[]{},true,45,true,river,true);
}
/**
* 创建模型并添加进字典
* @param code
* @param name
* @param atkBase
* @param defBase
* @param hpBase
* @param speed
* @param atkArr
* @param defArr
* @param hpArr
* @param atkRange
* @param tailRange
* @param skills
* @param reborn
* @param rebornTime
* @param provideBuff
* @param buff
* @param neutrality
*/
private static void create(int code, String name, int atkBase, int defBase, int hpBase,int speed,int atkArr,
float defArr, int hpArr, float atkRange, float tailRange, int[] skills,
boolean reborn,int rebornTime,boolean provideBuff,BuffModel buff, boolean neutrality) {
MonsterModel model = new MonsterModel();
model.setCode(code); //策划定义的唯一编号
model.setName(name); //怪物名称
model.setAtkBase(atkBase); //初始(基础)攻击力
model.setDefBase(defBase); //初始防御
model.setHpBase(hpBase); //初始血量
model.setSpeed(speed); //移动速度
model.setAtkArr(atkArr); //攻击成长
model.setDefArr(defArr); //防御成长
model.setHpArr(hpArr); //血量成长
model.setAtkRange(atkRange); //攻击距离
model.setTailRange(tailRange); //跟踪范围
model.setSkills(skills); //拥有技能
model.setReborn(reborn); //是否复活
model.setRebornTime(rebornTime); //复活时间
model.setProvideBuff(provideBuff); //杀死后是否提供增益BUF
model.setBuff(buff); //buff;
model.setNeutrality(neutrality); //是否中立
monsterMap.put(code, model);
}
}
| 0 | 1,494 | 9 | 1,667 | 7 | 1,641 | 7 | 1,667 | 7 | 1,879 | 10 | false | false | false | false | false | true |
57101_5 | package greedarithmetic;
import java.util.Arrays;
import java.util.PriorityQueue;
/**
* Created by Terry
* User: Administrator
* Date: 2021-12-25
* Time: 19:34
* Description:最多可参与的会议数量
* https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended/
*/
public class Code07_MaxJoinConference {
public int maxEvents(int[][] events) {
if (events == null || events.length == 0) {
return 0;
}
//先对数组进行排序,第一列的数是会议的开始时间,让开始时间相等的在一堆
Arrays.sort(events, (o1, o2)-> {
return o1[0] - o2[0]; //升序
});
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
int curDay = 1;
int res = 0;
int i = 0;
while (i < events.length || !minHeap.isEmpty()) {
while (i < events.length && events[i][0] == curDay) {//当前数据的开始时间与cur相等
minHeap.add(events[i][1]);//将结束时间放入小堆
i++;
}
//当前堆中的结束时间小于当前之间,直接舍弃
while (!minHeap.isEmpty() && minHeap.peek() < curDay) {
minHeap.poll();
}
if (!minHeap.isEmpty()) { //每天只能开一个会议
minHeap.poll();
res++;
}
curDay++;
}
return res;
}
}
| 7flyx/Algorithm-of-test-library | bitTrainProblem/untitled/src/greedarithmetic/Code07_MaxJoinConference.java | 403 | //每天只能开一个会议 | line_comment | zh-cn | package greedarithmetic;
import java.util.Arrays;
import java.util.PriorityQueue;
/**
* Created by Terry
* User: Administrator
* Date: 2021-12-25
* Time: 19:34
* Description:最多可参与的会议数量
* https://leetcode-cn.com/problems/maximum-number-of-events-that-can-be-attended/
*/
public class Code07_MaxJoinConference {
public int maxEvents(int[][] events) {
if (events == null || events.length == 0) {
return 0;
}
//先对数组进行排序,第一列的数是会议的开始时间,让开始时间相等的在一堆
Arrays.sort(events, (o1, o2)-> {
return o1[0] - o2[0]; //升序
});
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
int curDay = 1;
int res = 0;
int i = 0;
while (i < events.length || !minHeap.isEmpty()) {
while (i < events.length && events[i][0] == curDay) {//当前数据的开始时间与cur相等
minHeap.add(events[i][1]);//将结束时间放入小堆
i++;
}
//当前堆中的结束时间小于当前之间,直接舍弃
while (!minHeap.isEmpty() && minHeap.peek() < curDay) {
minHeap.poll();
}
if (!minHeap.isEmpty()) { //每天 <SUF>
minHeap.poll();
res++;
}
curDay++;
}
return res;
}
}
| 0 | 353 | 6 | 403 | 8 | 413 | 6 | 403 | 8 | 510 | 12 | false | false | false | false | false | true |
43120_4 | package com.test.entity;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 打印存在Object里的实体类的字段和值
* @Explain
* 为了方便开发中便于调试,写了这个接口,存入实体类,反射遍历出这个实体类里面的所有字段和值,
* 这里只写出了两个常用的普通字段和值的输出,有其他集合或者更负责的解析可以自己修改代码
* @author sevennight
*/
public class EmptyPrinting {
/**
* 输出实体类
* @param model
*/
public static void print(Object model) {
Class cls = model.getClass();
Field[] fields = cls.getDeclaredFields();
System.out.println("实体类:"+model.getClass().getName());
for (Field field : fields) {
char[] buffer = field.getName().toCharArray();
buffer[0] = Character.toUpperCase(buffer[0]);
String mothodName = "get" + new String(buffer);
try {
Method method = cls.getDeclaredMethod(mothodName);
Object resutl = method.invoke(model, null);
System.out.println(field.getName() + " : " + resutl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 输出实体类指定的属性
* @param model
* @param fields
*/
public static void print(Object model, String[] fields) {
Class cls = model.getClass();
System.out.println("实体类:"+model.getClass().getName());
for (String field : fields) {
char[] buffer = field.toCharArray();
buffer[0] = Character.toUpperCase(buffer[0]);
String mothodName = "get" + new String(buffer);
try {
Method method = cls.getDeclaredMethod(mothodName);
Object resutl = method.invoke(model, null);
System.out.println(field + ": " + resutl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//测试
public static void main(String[] args) throws Exception {
//这是一个实体类
ClassBean1009 bean1009 = new ClassBean1009();
bean1009.setNzxHelpMeType(1);
bean1009.setSzxAuthString("234242342343243");
//现在是一个未知类型的对象(模拟一下)
Object obj = bean1009;
//调用
print(obj);
}
}
| 7ye/javacode | EmptyPrinting.java | 634 | //现在是一个未知类型的对象(模拟一下) | line_comment | zh-cn | package com.test.entity;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 打印存在Object里的实体类的字段和值
* @Explain
* 为了方便开发中便于调试,写了这个接口,存入实体类,反射遍历出这个实体类里面的所有字段和值,
* 这里只写出了两个常用的普通字段和值的输出,有其他集合或者更负责的解析可以自己修改代码
* @author sevennight
*/
public class EmptyPrinting {
/**
* 输出实体类
* @param model
*/
public static void print(Object model) {
Class cls = model.getClass();
Field[] fields = cls.getDeclaredFields();
System.out.println("实体类:"+model.getClass().getName());
for (Field field : fields) {
char[] buffer = field.getName().toCharArray();
buffer[0] = Character.toUpperCase(buffer[0]);
String mothodName = "get" + new String(buffer);
try {
Method method = cls.getDeclaredMethod(mothodName);
Object resutl = method.invoke(model, null);
System.out.println(field.getName() + " : " + resutl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 输出实体类指定的属性
* @param model
* @param fields
*/
public static void print(Object model, String[] fields) {
Class cls = model.getClass();
System.out.println("实体类:"+model.getClass().getName());
for (String field : fields) {
char[] buffer = field.toCharArray();
buffer[0] = Character.toUpperCase(buffer[0]);
String mothodName = "get" + new String(buffer);
try {
Method method = cls.getDeclaredMethod(mothodName);
Object resutl = method.invoke(model, null);
System.out.println(field + ": " + resutl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//测试
public static void main(String[] args) throws Exception {
//这是一个实体类
ClassBean1009 bean1009 = new ClassBean1009();
bean1009.setNzxHelpMeType(1);
bean1009.setSzxAuthString("234242342343243");
//现在 <SUF>
Object obj = bean1009;
//调用
print(obj);
}
}
| 0 | 567 | 10 | 634 | 12 | 674 | 10 | 634 | 12 | 814 | 21 | false | false | false | false | false | true |
23268_1 | //this
public class Emp{
String name;
int age;
String des;
public Emp(String name,int agess,String desss){
this.name = name; //不使用this时,默认先从当前函数寻找变量,找不到再从类里面寻找,当有同名变量是,需要使用this来表明使用类的变量
this.age = agess;
des = desss;
}
public void printEmp(){
System.out.println("我叫"+name);
System.out.println("年龄"+age);
System.out.println("爱好"+des);
}
} | 835501209/JavaTest | Emp.java | 148 | //不使用this时,默认先从当前函数寻找变量,找不到再从类里面寻找,当有同名变量是,需要使用this来表明使用类的变量 | line_comment | zh-cn | //this
public class Emp{
String name;
int age;
String des;
public Emp(String name,int agess,String desss){
this.name = name; //不使 <SUF>
this.age = agess;
des = desss;
}
public void printEmp(){
System.out.println("我叫"+name);
System.out.println("年龄"+age);
System.out.println("爱好"+des);
}
} | 0 | 128 | 36 | 148 | 42 | 152 | 36 | 148 | 42 | 187 | 63 | false | false | false | false | false | true |
28178_22 | /*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2024 miaixz.org and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
* *
********************************************************************************/
package org.miaixz.bus.core.math;
import org.miaixz.bus.core.lang.Symbol;
import org.miaixz.bus.core.xyz.StringKit;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
/**
* 数字解析器
* 用于将字符串解析为对应的数字类型,支持包括:
* <ul>
* <li>0开头的忽略开头的0</li>
* <li>空串返回0</li>
* <li>NaN返回0</li>
* <li>其它情况按照10进制转换</li>
* <li>.123形式返回0.123(按照小于0的小数对待)</li>
* </ul>
*
* <p>
* 构造时可选是否将NaN转为0,默认为true。
* 参考:https://stackoverflow.com/questions/5876369/why-does-casting-double-nan-to-int-not-throw-an-exception-in-java
* </p>
*
* @author Kimi Liu
* @since Java 17+
*/
public class NumberParser {
/**
* 单例
*/
public static final NumberParser INSTANCE = of(null);
private static final String NaN = "NaN";
private final Locale locale;
private final boolean zeroIfNaN;
/**
* 构造
*
* @param locale 地域,{@code null}表示默认本地
* @param zeroIfNaN 如果用户传入NaN,是否转为0,如果为{@code false},则抛出{@link NumberFormatException}
*/
public NumberParser(final Locale locale, final boolean zeroIfNaN) {
this.locale = locale;
this.zeroIfNaN = zeroIfNaN;
}
/**
* 构建NumberParser
*
* @param locale 地域,{@code null}表示默认本地
* @return NumberParser
*/
public static NumberParser of(final Locale locale) {
return of(locale, true);
}
/**
* 构建NumberParser
*
* @param locale 地域,{@code null}表示默认本地
* @param zeroIfNaN 如果用户传入NaN,是否转为0,如果为{@code false},则抛出{@link NumberFormatException}
* @return NumberParser
*/
public static NumberParser of(final Locale locale, final boolean zeroIfNaN) {
return new NumberParser(locale, zeroIfNaN);
}
/**
* 解析转换数字字符串为int型数字,规则如下:
*
* <pre>
* 1、0x开头的视为16进制数字
* 2、0开头的忽略开头的0
* 3、其它情况按照10进制转换
* 4、空串返回0
* 5、.123形式返回0(按照小于0的小数对待)
* 6、123.56截取小数点之前的数字,忽略小数部分
* 7、科学计数法抛出NumberFormatException异常
* </pre>
*
* @param numberStr 数字字符串
* @return the int
* @throws NumberFormatException 数字格式异常
*/
public int parseInt(final String numberStr) throws NumberFormatException {
if (isBlankOrNaN(numberStr)) {
return 0;
}
if (StringKit.startWithIgnoreCase(numberStr, "0x")) {
// 0x04表示16进制数
return Integer.parseInt(numberStr.substring(2), 16);
}
if (StringKit.containsIgnoreCase(numberStr, "E")) {
// 科学计数法忽略支持,科学计数法一般用于表示非常小和非常大的数字,这类数字转换为int后精度丢失,没有意义。
throw new NumberFormatException(StringKit.format("Unsupported int format: [{}]", numberStr));
}
try {
return Integer.parseInt(numberStr);
} catch (final NumberFormatException e) {
return doParse(numberStr).intValue();
}
}
/**
* 解析转换数字字符串为long型数字,规则如下:
*
* <pre>
* 1、0x开头的视为16进制数字
* 2、0开头的忽略开头的0
* 3、空串返回0
* 4、其它情况按照10进制转换
* 5、.123形式返回0(按照小于0的小数对待)
* 6、123.56截取小数点之前的数字,忽略小数部分
* </pre>
*
* @param numberStr 数字字符串
* @return the long
*/
public long parseLong(final String numberStr) {
if (isBlankOrNaN(numberStr)) {
return 0;
}
if (StringKit.startWithIgnoreCase(numberStr, "0x")) {
// 0x04表示16进制数
return Long.parseLong(numberStr.substring(2), 16);
}
try {
return Long.parseLong(numberStr);
} catch (final NumberFormatException e) {
return doParse(numberStr).longValue();
}
}
/**
* 解析转换数字字符串为long型数字,规则如下:
*
* <pre>
* 1、0开头的忽略开头的0
* 2、空串返回0
* 3、其它情况按照10进制转换
* 4、.123形式返回0.123(按照小于0的小数对待)
* </pre>
*
* @param numberStr 数字字符串
* @return the long
*/
public float parseFloat(final String numberStr) {
if (isBlankOrNaN(numberStr)) {
return 0;
}
try {
return Float.parseFloat(numberStr);
} catch (final NumberFormatException e) {
return doParse(numberStr).floatValue();
}
}
/**
* 解析转换数字字符串为long型数字,规则如下:
*
* <pre>
* 1、0开头的忽略开头的0
* 2、空串返回0
* 3、其它情况按照10进制转换
* 4、.123形式返回0.123(按照小于0的小数对待)
* 5、NaN返回0
* </pre>
*
* @param numberStr 数字字符串
* @return the double
*/
public double parseDouble(final String numberStr) {
if (isBlankOrNaN(numberStr)) {
return 0;
}
try {
return Double.parseDouble(numberStr);
} catch (final NumberFormatException e) {
return doParse(numberStr).doubleValue();
}
}
/**
* 解析为{@link BigInteger},支持16进制、10进制和8进制,如果传入空白串返回null
*
* @param text 数字字符串
* @return {@link BigInteger}
*/
public BigInteger parseBigInteger(String text) {
text = StringKit.trimToNull(text);
if (null == text) {
return null;
}
int pos = 0; // 数字字符串位置
int radix = 10;
boolean negate = false; // 负数与否
if (text.startsWith(Symbol.MINUS)) {
negate = true;
pos = 1;
}
if (text.startsWith("0x", pos) || text.startsWith("0X", pos)) {
// hex
radix = 16;
pos += 2;
} else if (text.startsWith(Symbol.SHAPE, pos)) {
// alternative hex (allowed by Long/Integer)
radix = 16;
pos++;
} else if (text.startsWith("0", pos) && text.length() > pos + 1) {
// octal; so long as there are additional digits
radix = 8;
pos++;
} // default is to treat as decimal
if (pos > 0) {
text = text.substring(pos);
}
final BigInteger value = new BigInteger(text, radix);
return negate ? value.negate() : value;
}
/**
* 将指定字符串转换为{@link Number} 对象
* 此方法不支持科学计数法
*
* <ul>
* <li>空白符和NaN转换为0</li>
* <li>0x开头使用16进制解析为Long类型</li>
* </ul>
*
* <p>
* 需要注意的是,在不同Locale下,数字的表示形式也是不同的,例如:
* 德国、荷兰、比利时、丹麦、意大利、罗马尼亚和欧洲大多地区使用`,`区分小数
* 也就是说,在这些国家地区,1.20表示120,而非1.2。
* </p>
*
* @param numberStr 数字字符串
* @return Number对象
* @throws NumberFormatException 包装了{@link ParseException},当给定的数字字符串无法解析时抛出
*/
public Number parseNumber(final String numberStr) throws NumberFormatException {
if (isBlankOrNaN(numberStr)) {
// 在JDK9+中,NaN的处理逻辑是返回0,此处保持一致
return 0;
}
// 16进制
if (StringKit.startWithIgnoreCase(numberStr, "0x")) {
// 0x04表示16进制数
return Long.parseLong(numberStr.substring(2), 16);
}
return doParse(numberStr);
}
/**
* 使用{@link NumberFormat} 完成数字解析
* 如果为{@link DecimalFormat}
*
* @return 数字
*/
private Number doParse(String numberStr) {
Locale locale = this.locale;
if (null == locale) {
locale = Locale.getDefault(Locale.Category.FORMAT);
}
if (StringKit.startWith(numberStr, Symbol.C_PLUS)) {
numberStr = StringKit.subSuf(numberStr, 1);
}
try {
final NumberFormat format = NumberFormat.getInstance(locale);
if (format instanceof DecimalFormat) {
// 当字符串数字超出double的长度时,会导致截断,此处使用BigDecimal接收
((DecimalFormat) format).setParseBigDecimal(true);
}
return format.parse(numberStr);
} catch (final ParseException e) {
final NumberFormatException nfe = new NumberFormatException(e.getMessage());
nfe.initCause(e);
throw nfe;
}
}
/**
* 是否空白串或者NaN
* 如果{@link #zeroIfNaN}为{@code false},则抛出{@link NumberFormatException}
*
* @return 是否空白串或者NaN
*/
private boolean isBlankOrNaN(final String numberStr) throws NumberFormatException {
if (StringKit.isBlank(numberStr)) {
return true;
}
if (NaN.equals(numberStr)) {
if (zeroIfNaN) {
return true;
} else {
throw new NumberFormatException("Can not parse NaN when 'zeroIfNaN' is false!");
}
}
return false;
}
}
| 839128/bus | bus-core/src/main/java/org/miaixz/bus/core/math/NumberParser.java | 2,974 | // 16进制 | line_comment | zh-cn | /*********************************************************************************
* *
* The MIT License (MIT) *
* *
* Copyright (c) 2015-2024 miaixz.org and other contributors. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
* *
********************************************************************************/
package org.miaixz.bus.core.math;
import org.miaixz.bus.core.lang.Symbol;
import org.miaixz.bus.core.xyz.StringKit;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Locale;
/**
* 数字解析器
* 用于将字符串解析为对应的数字类型,支持包括:
* <ul>
* <li>0开头的忽略开头的0</li>
* <li>空串返回0</li>
* <li>NaN返回0</li>
* <li>其它情况按照10进制转换</li>
* <li>.123形式返回0.123(按照小于0的小数对待)</li>
* </ul>
*
* <p>
* 构造时可选是否将NaN转为0,默认为true。
* 参考:https://stackoverflow.com/questions/5876369/why-does-casting-double-nan-to-int-not-throw-an-exception-in-java
* </p>
*
* @author Kimi Liu
* @since Java 17+
*/
public class NumberParser {
/**
* 单例
*/
public static final NumberParser INSTANCE = of(null);
private static final String NaN = "NaN";
private final Locale locale;
private final boolean zeroIfNaN;
/**
* 构造
*
* @param locale 地域,{@code null}表示默认本地
* @param zeroIfNaN 如果用户传入NaN,是否转为0,如果为{@code false},则抛出{@link NumberFormatException}
*/
public NumberParser(final Locale locale, final boolean zeroIfNaN) {
this.locale = locale;
this.zeroIfNaN = zeroIfNaN;
}
/**
* 构建NumberParser
*
* @param locale 地域,{@code null}表示默认本地
* @return NumberParser
*/
public static NumberParser of(final Locale locale) {
return of(locale, true);
}
/**
* 构建NumberParser
*
* @param locale 地域,{@code null}表示默认本地
* @param zeroIfNaN 如果用户传入NaN,是否转为0,如果为{@code false},则抛出{@link NumberFormatException}
* @return NumberParser
*/
public static NumberParser of(final Locale locale, final boolean zeroIfNaN) {
return new NumberParser(locale, zeroIfNaN);
}
/**
* 解析转换数字字符串为int型数字,规则如下:
*
* <pre>
* 1、0x开头的视为16进制数字
* 2、0开头的忽略开头的0
* 3、其它情况按照10进制转换
* 4、空串返回0
* 5、.123形式返回0(按照小于0的小数对待)
* 6、123.56截取小数点之前的数字,忽略小数部分
* 7、科学计数法抛出NumberFormatException异常
* </pre>
*
* @param numberStr 数字字符串
* @return the int
* @throws NumberFormatException 数字格式异常
*/
public int parseInt(final String numberStr) throws NumberFormatException {
if (isBlankOrNaN(numberStr)) {
return 0;
}
if (StringKit.startWithIgnoreCase(numberStr, "0x")) {
// 0x04表示16进制数
return Integer.parseInt(numberStr.substring(2), 16);
}
if (StringKit.containsIgnoreCase(numberStr, "E")) {
// 科学计数法忽略支持,科学计数法一般用于表示非常小和非常大的数字,这类数字转换为int后精度丢失,没有意义。
throw new NumberFormatException(StringKit.format("Unsupported int format: [{}]", numberStr));
}
try {
return Integer.parseInt(numberStr);
} catch (final NumberFormatException e) {
return doParse(numberStr).intValue();
}
}
/**
* 解析转换数字字符串为long型数字,规则如下:
*
* <pre>
* 1、0x开头的视为16进制数字
* 2、0开头的忽略开头的0
* 3、空串返回0
* 4、其它情况按照10进制转换
* 5、.123形式返回0(按照小于0的小数对待)
* 6、123.56截取小数点之前的数字,忽略小数部分
* </pre>
*
* @param numberStr 数字字符串
* @return the long
*/
public long parseLong(final String numberStr) {
if (isBlankOrNaN(numberStr)) {
return 0;
}
if (StringKit.startWithIgnoreCase(numberStr, "0x")) {
// 0x04表示16进制数
return Long.parseLong(numberStr.substring(2), 16);
}
try {
return Long.parseLong(numberStr);
} catch (final NumberFormatException e) {
return doParse(numberStr).longValue();
}
}
/**
* 解析转换数字字符串为long型数字,规则如下:
*
* <pre>
* 1、0开头的忽略开头的0
* 2、空串返回0
* 3、其它情况按照10进制转换
* 4、.123形式返回0.123(按照小于0的小数对待)
* </pre>
*
* @param numberStr 数字字符串
* @return the long
*/
public float parseFloat(final String numberStr) {
if (isBlankOrNaN(numberStr)) {
return 0;
}
try {
return Float.parseFloat(numberStr);
} catch (final NumberFormatException e) {
return doParse(numberStr).floatValue();
}
}
/**
* 解析转换数字字符串为long型数字,规则如下:
*
* <pre>
* 1、0开头的忽略开头的0
* 2、空串返回0
* 3、其它情况按照10进制转换
* 4、.123形式返回0.123(按照小于0的小数对待)
* 5、NaN返回0
* </pre>
*
* @param numberStr 数字字符串
* @return the double
*/
public double parseDouble(final String numberStr) {
if (isBlankOrNaN(numberStr)) {
return 0;
}
try {
return Double.parseDouble(numberStr);
} catch (final NumberFormatException e) {
return doParse(numberStr).doubleValue();
}
}
/**
* 解析为{@link BigInteger},支持16进制、10进制和8进制,如果传入空白串返回null
*
* @param text 数字字符串
* @return {@link BigInteger}
*/
public BigInteger parseBigInteger(String text) {
text = StringKit.trimToNull(text);
if (null == text) {
return null;
}
int pos = 0; // 数字字符串位置
int radix = 10;
boolean negate = false; // 负数与否
if (text.startsWith(Symbol.MINUS)) {
negate = true;
pos = 1;
}
if (text.startsWith("0x", pos) || text.startsWith("0X", pos)) {
// hex
radix = 16;
pos += 2;
} else if (text.startsWith(Symbol.SHAPE, pos)) {
// alternative hex (allowed by Long/Integer)
radix = 16;
pos++;
} else if (text.startsWith("0", pos) && text.length() > pos + 1) {
// octal; so long as there are additional digits
radix = 8;
pos++;
} // default is to treat as decimal
if (pos > 0) {
text = text.substring(pos);
}
final BigInteger value = new BigInteger(text, radix);
return negate ? value.negate() : value;
}
/**
* 将指定字符串转换为{@link Number} 对象
* 此方法不支持科学计数法
*
* <ul>
* <li>空白符和NaN转换为0</li>
* <li>0x开头使用16进制解析为Long类型</li>
* </ul>
*
* <p>
* 需要注意的是,在不同Locale下,数字的表示形式也是不同的,例如:
* 德国、荷兰、比利时、丹麦、意大利、罗马尼亚和欧洲大多地区使用`,`区分小数
* 也就是说,在这些国家地区,1.20表示120,而非1.2。
* </p>
*
* @param numberStr 数字字符串
* @return Number对象
* @throws NumberFormatException 包装了{@link ParseException},当给定的数字字符串无法解析时抛出
*/
public Number parseNumber(final String numberStr) throws NumberFormatException {
if (isBlankOrNaN(numberStr)) {
// 在JDK9+中,NaN的处理逻辑是返回0,此处保持一致
return 0;
}
// 16 <SUF>
if (StringKit.startWithIgnoreCase(numberStr, "0x")) {
// 0x04表示16进制数
return Long.parseLong(numberStr.substring(2), 16);
}
return doParse(numberStr);
}
/**
* 使用{@link NumberFormat} 完成数字解析
* 如果为{@link DecimalFormat}
*
* @return 数字
*/
private Number doParse(String numberStr) {
Locale locale = this.locale;
if (null == locale) {
locale = Locale.getDefault(Locale.Category.FORMAT);
}
if (StringKit.startWith(numberStr, Symbol.C_PLUS)) {
numberStr = StringKit.subSuf(numberStr, 1);
}
try {
final NumberFormat format = NumberFormat.getInstance(locale);
if (format instanceof DecimalFormat) {
// 当字符串数字超出double的长度时,会导致截断,此处使用BigDecimal接收
((DecimalFormat) format).setParseBigDecimal(true);
}
return format.parse(numberStr);
} catch (final ParseException e) {
final NumberFormatException nfe = new NumberFormatException(e.getMessage());
nfe.initCause(e);
throw nfe;
}
}
/**
* 是否空白串或者NaN
* 如果{@link #zeroIfNaN}为{@code false},则抛出{@link NumberFormatException}
*
* @return 是否空白串或者NaN
*/
private boolean isBlankOrNaN(final String numberStr) throws NumberFormatException {
if (StringKit.isBlank(numberStr)) {
return true;
}
if (NaN.equals(numberStr)) {
if (zeroIfNaN) {
return true;
} else {
throw new NumberFormatException("Can not parse NaN when 'zeroIfNaN' is false!");
}
}
return false;
}
}
| 0 | 2,795 | 6 | 2,974 | 5 | 3,126 | 5 | 2,974 | 5 | 3,933 | 6 | false | false | false | false | false | true |
61896_0 | package pattern.staticfactory;
public class NvWa {
public static void main(String[] args) {
Human human = null;
//白人
human = HumanFactory.createHuman(WhiteHuman.class);
human.eat();
human.laugh();
human.run();
//黑人
human = HumanFactory.createHuman(BlackHuman.class);
human.eat();
human.laugh();
human.run();
//黄种人
human = HumanFactory.createHuman(YelloHuman.class);
human.eat();
human.laugh();
human.run();
System.out.println("============随机生成人类==============================");
for (int i = 0; i < 100; i++) {
human = HumanFactory.createHuman();
human.eat();
human.run();
human.laugh();
}
}
}
| 898349230/test | src/main/java/pattern/staticfactory/NvWa.java | 203 | //黄种人 | line_comment | zh-cn | package pattern.staticfactory;
public class NvWa {
public static void main(String[] args) {
Human human = null;
//白人
human = HumanFactory.createHuman(WhiteHuman.class);
human.eat();
human.laugh();
human.run();
//黑人
human = HumanFactory.createHuman(BlackHuman.class);
human.eat();
human.laugh();
human.run();
//黄种 <SUF>
human = HumanFactory.createHuman(YelloHuman.class);
human.eat();
human.laugh();
human.run();
System.out.println("============随机生成人类==============================");
for (int i = 0; i < 100; i++) {
human = HumanFactory.createHuman();
human.eat();
human.run();
human.laugh();
}
}
}
| 0 | 183 | 4 | 203 | 4 | 221 | 4 | 203 | 4 | 250 | 4 | false | false | false | false | false | true |
58130_3 | package cn.wt3.weconds;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import cn.wt3.weconds.R;
public class FloatBallView {
private Context context;
private int height = 0;
private int width = 0;
private int flag = 1;
public static FloatBallView floatView2;
private TextView condstext = null;
public static FloatBallView getInstance(Context context) {
if (floatView2 == null) {
floatView2 = new FloatBallView(context);
}
return floatView2;
}
public FloatBallView(Context c) {
this.context = c;
}
private WindowManager wm;
private View view;// 浮动模块
WindowManager.LayoutParams params;
//添加悬浮View
public void createFloatView() {
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.floatview, null);
}
wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
height = wm.getDefaultDisplay().getHeight();
width = wm.getDefaultDisplay().getWidth();
params = new WindowManager.LayoutParams();
params.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;// 所有程序窗口的“基地”窗口,其他应用程序窗口都显示在它上面。
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
params.format = PixelFormat.TRANSLUCENT;// 不设置这个弹出框的透明遮罩显示为黑色
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.TOP | Gravity.LEFT;
int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
int screenHeight = context.getResources().getDisplayMetrics().heightPixels;
params.y = screenHeight - (4 * height) / 5;//设置距离底部高度为屏幕五分之四
params.x = screenWidth;
view.setBackgroundColor(Color.TRANSPARENT);
view.setVisibility(View.VISIBLE);
// 触屏监听移动悬浮框
view.setOnTouchListener(new View.OnTouchListener() {
float lastX, lastY;
int oldOffsetX, oldOffsetY;
int tag = 0;// 悬浮框 所需成员变量
@Override
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction();
float x = event.getX();
float y = event.getY();
if (tag == 0) {
oldOffsetX = params.x; // 偏移量
oldOffsetY = params.y; // 偏移量
}
if (action == MotionEvent.ACTION_DOWN) {
lastX = x;
lastY = y;
} else if (action == MotionEvent.ACTION_MOVE) {
params.x += (int) (x - lastX) / 3; // 减小偏移量,防止过度抖动
params.y += (int) (y - lastY) / 3; // 减小偏移量,防止过度抖动
tag = 1;
wm.updateViewLayout(view, params);
} else if (action == MotionEvent.ACTION_UP) {
int newOffsetX = params.x;
int newOffsetY = params.y;
// 只要按钮一动位置不是很大,就认为是点击事件
if (Math.abs(oldOffsetX - newOffsetX) <= 20
&& Math.abs(oldOffsetY - newOffsetY) <= 20) {
if (l != null) {
l.onClick(view);
}
} else {
if (params.x < width / 2) {
params.x = 0;
} else {
params.x = width;
}
wm.updateViewLayout(view, params);
tag = 0;
}
}
return true;
}
});
try {
//将控件view和布局参数params加入到windowmanager
wm.addView(view, params);
} catch (Exception e) {
System.out.println("addView失败");
}
}
//点击浮动按钮触发事件,需要override该方法
private View.OnClickListener l;
public void onFloatViewClick(View.OnClickListener l) {
this.l = l;
}
//将悬浮View从WindowManager中移除,需要与createFloatView()成对出现
public void removeFloatView() {
if (wm != null && view != null) {
wm.removeViewImmediate(view);
view = null;
wm = null;
}
}
//秒数框数据更新方法
public void updata(String ss) {
if (wm != null && view != null && view.isShown()) {
condstext = (TextView) view.findViewById(R.id.condstext);
condstext.setText(ss);
}
}
public boolean isopfl() {
if (wm != null && view != null && view.isShown()) {
return true;
} else {
return false;
}
}
//设置浮窗大小尺寸方法
public void setsize(float fontsize, int width, int height) {
//获取TextView对应的LayoutParams
ViewGroup.LayoutParams layoutParams = condstext.getLayoutParams();
if (layoutParams != null) {
final float scale = context.getResources().getDisplayMetrics().density;
//设置字体大小
condstext.setTextSize(fontsize);
//设置数字在框内居中
condstext.setGravity(Gravity.CENTER);
//设置宽度
layoutParams.width = (int) (width * scale + 0.5f);
//设置高度
layoutParams.height = (int) (height * scale + 0.5f);
condstext.setLayoutParams(layoutParams);
}
}
//设置浮框不可触摸方法
public boolean notouch() {
if (wm != null && view != null) {
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
wm.updateViewLayout(view, params);
return true;
} else {
return false;
}
}
//恢复浮框可触摸方法
public boolean retouch() {
if (wm != null && view != null) {
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
wm.updateViewLayout(view, params);
return true;
} else {
return false;
}
}
}
| 8mv/Weconds | app/src/main/java/cn/wt3/weconds/FloatBallView.java | 1,688 | // 不设置这个弹出框的透明遮罩显示为黑色 | line_comment | zh-cn | package cn.wt3.weconds;
import android.content.Context;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.TextView;
import cn.wt3.weconds.R;
public class FloatBallView {
private Context context;
private int height = 0;
private int width = 0;
private int flag = 1;
public static FloatBallView floatView2;
private TextView condstext = null;
public static FloatBallView getInstance(Context context) {
if (floatView2 == null) {
floatView2 = new FloatBallView(context);
}
return floatView2;
}
public FloatBallView(Context c) {
this.context = c;
}
private WindowManager wm;
private View view;// 浮动模块
WindowManager.LayoutParams params;
//添加悬浮View
public void createFloatView() {
if (view == null) {
view = LayoutInflater.from(context).inflate(R.layout.floatview, null);
}
wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
height = wm.getDefaultDisplay().getHeight();
width = wm.getDefaultDisplay().getWidth();
params = new WindowManager.LayoutParams();
params.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;// 所有程序窗口的“基地”窗口,其他应用程序窗口都显示在它上面。
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
params.format = PixelFormat.TRANSLUCENT;// 不设 <SUF>
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
}
params.width = WindowManager.LayoutParams.WRAP_CONTENT;
params.height = WindowManager.LayoutParams.WRAP_CONTENT;
params.gravity = Gravity.TOP | Gravity.LEFT;
int screenWidth = context.getResources().getDisplayMetrics().widthPixels;
int screenHeight = context.getResources().getDisplayMetrics().heightPixels;
params.y = screenHeight - (4 * height) / 5;//设置距离底部高度为屏幕五分之四
params.x = screenWidth;
view.setBackgroundColor(Color.TRANSPARENT);
view.setVisibility(View.VISIBLE);
// 触屏监听移动悬浮框
view.setOnTouchListener(new View.OnTouchListener() {
float lastX, lastY;
int oldOffsetX, oldOffsetY;
int tag = 0;// 悬浮框 所需成员变量
@Override
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction();
float x = event.getX();
float y = event.getY();
if (tag == 0) {
oldOffsetX = params.x; // 偏移量
oldOffsetY = params.y; // 偏移量
}
if (action == MotionEvent.ACTION_DOWN) {
lastX = x;
lastY = y;
} else if (action == MotionEvent.ACTION_MOVE) {
params.x += (int) (x - lastX) / 3; // 减小偏移量,防止过度抖动
params.y += (int) (y - lastY) / 3; // 减小偏移量,防止过度抖动
tag = 1;
wm.updateViewLayout(view, params);
} else if (action == MotionEvent.ACTION_UP) {
int newOffsetX = params.x;
int newOffsetY = params.y;
// 只要按钮一动位置不是很大,就认为是点击事件
if (Math.abs(oldOffsetX - newOffsetX) <= 20
&& Math.abs(oldOffsetY - newOffsetY) <= 20) {
if (l != null) {
l.onClick(view);
}
} else {
if (params.x < width / 2) {
params.x = 0;
} else {
params.x = width;
}
wm.updateViewLayout(view, params);
tag = 0;
}
}
return true;
}
});
try {
//将控件view和布局参数params加入到windowmanager
wm.addView(view, params);
} catch (Exception e) {
System.out.println("addView失败");
}
}
//点击浮动按钮触发事件,需要override该方法
private View.OnClickListener l;
public void onFloatViewClick(View.OnClickListener l) {
this.l = l;
}
//将悬浮View从WindowManager中移除,需要与createFloatView()成对出现
public void removeFloatView() {
if (wm != null && view != null) {
wm.removeViewImmediate(view);
view = null;
wm = null;
}
}
//秒数框数据更新方法
public void updata(String ss) {
if (wm != null && view != null && view.isShown()) {
condstext = (TextView) view.findViewById(R.id.condstext);
condstext.setText(ss);
}
}
public boolean isopfl() {
if (wm != null && view != null && view.isShown()) {
return true;
} else {
return false;
}
}
//设置浮窗大小尺寸方法
public void setsize(float fontsize, int width, int height) {
//获取TextView对应的LayoutParams
ViewGroup.LayoutParams layoutParams = condstext.getLayoutParams();
if (layoutParams != null) {
final float scale = context.getResources().getDisplayMetrics().density;
//设置字体大小
condstext.setTextSize(fontsize);
//设置数字在框内居中
condstext.setGravity(Gravity.CENTER);
//设置宽度
layoutParams.width = (int) (width * scale + 0.5f);
//设置高度
layoutParams.height = (int) (height * scale + 0.5f);
condstext.setLayoutParams(layoutParams);
}
}
//设置浮框不可触摸方法
public boolean notouch() {
if (wm != null && view != null) {
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
wm.updateViewLayout(view, params);
return true;
} else {
return false;
}
}
//恢复浮框可触摸方法
public boolean retouch() {
if (wm != null && view != null) {
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
wm.updateViewLayout(view, params);
return true;
} else {
return false;
}
}
}
| 0 | 1,448 | 14 | 1,688 | 18 | 1,767 | 13 | 1,688 | 18 | 2,209 | 32 | false | false | false | false | false | true |
37232_2 | package pachong;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
static String SendGet(String url){
String result = null;//定义一个字符串来存储网页内容
BufferedReader in = null ;//空
try{
URL realUrl = new URL(url);
URLConnection connection =realUrl.openConnection();//返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
connection.connect();// 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gbk"));//字节流转化为字符流通过缓冲流读操作
String line;
while((line=in.readLine())!=null){
result +=line+"\r\n";
System.out.println(result);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(in !=null){
in.close();
}
}catch(Exception e2){
e2.printStackTrace();
}
}
return result;
}
public static Map<String, String> transStringToMap(String mapString){
String [] str;
Map<String, String> map = new HashMap<String, String>();
String pattern = "\\d{4}-\\d{1,2}-\\d{1,2}[,]\\d{2}[:]\\d{2}[:]\\d{2}[,]\\d{2}[:]\\d{2}[:]\\d{2}[,][\\u4E00-\\u9FA5]+";
Pattern r = Pattern.compile(pattern);//将给定的正则表达式编译到模式中。
Matcher m = r.matcher(mapString);// 创建匹配给定输入与此模式的匹配器
while(m.find()){// 尝试查找与该模式匹配的输入序列的下一个子序列
// m.find();
str=m.group().split(",");//m.group:返回由以前匹配操作所匹配的输入子序列.split:根据给定正则表达式的匹配拆分此字符串,返回值为数组
map.put(str[0], str[3]);
}
return map;
}
public static void main(String[] args) {
String url = "http://hq.sinajs.cn/?list=market_stock_sh";
SendGet(url);
Map<String,String> map= transStringToMap(SendGet(url));
for (String key : map.keySet()) {
System.out.println("key= " + key + " and value= " + map.get(key));
}
}
}
| 905251926/PaChong01 | Main.java | 724 | // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。 | line_comment | zh-cn | package pachong;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
static String SendGet(String url){
String result = null;//定义一个字符串来存储网页内容
BufferedReader in = null ;//空
try{
URL realUrl = new URL(url);
URLConnection connection =realUrl.openConnection();//返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。
connection.connect();// 打开 <SUF>
in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"gbk"));//字节流转化为字符流通过缓冲流读操作
String line;
while((line=in.readLine())!=null){
result +=line+"\r\n";
System.out.println(result);
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(in !=null){
in.close();
}
}catch(Exception e2){
e2.printStackTrace();
}
}
return result;
}
public static Map<String, String> transStringToMap(String mapString){
String [] str;
Map<String, String> map = new HashMap<String, String>();
String pattern = "\\d{4}-\\d{1,2}-\\d{1,2}[,]\\d{2}[:]\\d{2}[:]\\d{2}[,]\\d{2}[:]\\d{2}[:]\\d{2}[,][\\u4E00-\\u9FA5]+";
Pattern r = Pattern.compile(pattern);//将给定的正则表达式编译到模式中。
Matcher m = r.matcher(mapString);// 创建匹配给定输入与此模式的匹配器
while(m.find()){// 尝试查找与该模式匹配的输入序列的下一个子序列
// m.find();
str=m.group().split(",");//m.group:返回由以前匹配操作所匹配的输入子序列.split:根据给定正则表达式的匹配拆分此字符串,返回值为数组
map.put(str[0], str[3]);
}
return map;
}
public static void main(String[] args) {
String url = "http://hq.sinajs.cn/?list=market_stock_sh";
SendGet(url);
Map<String,String> map= transStringToMap(SendGet(url));
for (String key : map.keySet()) {
System.out.println("key= " + key + " and value= " + map.get(key));
}
}
}
| 0 | 610 | 22 | 724 | 23 | 747 | 18 | 724 | 23 | 931 | 38 | false | false | false | false | false | true |
17046_0 | package pattern.adapter;
// 适配器类
//适配器Adapter继承自Adaptee,同时又实现了目标(Target)接口。
public class Adapter extends Adaptee implements Target {
//所以适配器只是将SpecificRequest()方法作了一层封装,封装成Target可以调用的Request()而已
@Override
public void Request() {
this.SpecificRequest();
}
} | 925781609/pattern | src/main/java/pattern/adapter/Adapter.java | 92 | // 适配器类 | line_comment | zh-cn | package pattern.adapter;
// 适配 <SUF>
//适配器Adapter继承自Adaptee,同时又实现了目标(Target)接口。
public class Adapter extends Adaptee implements Target {
//所以适配器只是将SpecificRequest()方法作了一层封装,封装成Target可以调用的Request()而已
@Override
public void Request() {
this.SpecificRequest();
}
} | 0 | 87 | 6 | 92 | 6 | 89 | 5 | 92 | 6 | 134 | 8 | false | false | false | false | false | true |
20689_12 | import java.io.*;
import java.util.Scanner;
public class Studynote80_StandardStream {
}
/*
流的类型:只要记住大体分为 输入流和输出流,根据流的类型分类:字节流和字符流,根据流的传输类型:节点流,处理流,对象流,标准输入/输出流,转换流
标准流
类型 默认设备
System.in标准输入 InputStream 键盘
System.out标准输出 PrintStream 显示器
打印流(只有输出流,没有输入流):PrintStream字节流和PrintWriter字符流
*/
class InputAndOutput {
public static void main(String[] args) {
//System 类 的 public final static InputStream in = null;
// System.in 编译类型 InputStream
// System.in 运行类型 BufferedInputStream
// 表示的是标准输入 键盘
System.out.println(System.in.getClass());
//1. System.out public final static PrintStream out = null;
//2. 编译类型 PrintStream
//3. 运行类型 PrintStream
//4. 表示标准输出 显示器
System.out.println(System.out.getClass());
System.out.println("System.out 方法将数据输出到显示器");
Scanner scanner = new Scanner(System.in);
System.out.println("传统的方法,Scanner是从标准输入System.in 获取键盘数据");
String next = scanner.next();
System.out.println("scanner获取到的 next=" + next);
}
}
//演示PrintStream (字节打印流/输出流)
class PrintStream_ {
public static void main(String[] args) throws IOException {
PrintStream out = System.out;
//System.out是System类的静态属性,指向PrintStream类的对象。在底层其实被赋值了;final对类的要求是地址不能变,里面的值可以更改
// initializeSystemClass()方法里可以看到,只是赋值具体过程调用的native本地方法,即C++方法无法获取
//在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
/*源码
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
*/
out.print("john, hello");
//这里out.print 和 out.write 调用的 write 方法不一样,out.print 方法调用的write 是被private修饰的,
// 而这里直接调用的write是public,因此调用write进行打印/输出时需要转为byte[]数组传入
//打印Sting时,底层调用的是BufferedWriter的wirte(Sting)方法,但是这个方法是私有的
out.write("约翰,你好".getBytes());
out.close();
//我们可以去修改打印流输出的位置/设备
//1. 输出修改成到 "e:\\f1.txt"
//2. "伊万,你好" 就会输出到 e:\f1.txt
//3. public static void setOut(PrintStream out) {
// checkIO();
// setOut0(out); // native 方法,修改了out
// }
System.setOut(new PrintStream("e:\\f1.txt"));//构造器中传入文件位置
System.out.println("伊万,你好");
//要改回来就再次调用那个setOut()方法,把上面的out传进去,因为上面那个out对象是输出到控制台
}
}
class PrintWriter_ {
public static void main(String[] args) throws IOException {
//可以指定打印位置
//PrintWriter printWriter = new PrintWriter(System.out);
PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
printWriter.print("hi, 北京你好~~~~");
//flush + 关闭流, 才会将数据写入到文件..
//不只是输出到文件,就算是打印到控制台也是要 flush 刷新一下
printWriter.close();
}
}
/*转换流InputStreamReader和OutputStreamWriter:将字节流转换为字符流
单用字符流,他默认使用的是我们之前ide设置的(默认UTF-8),不能指定,只能改文件或ide。转换流可以指定更灵活
>介绍
1.InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流)
2.OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)
3.当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
4.可以在使用时指定编码格式(比如utf-8,gbk,gb2312,IS08859-1等)
编码转换:
构造器InputStreamReader(InputStream,Charset)传入字节流、编码方式两种参数,
构造器OutputStreamReader(OutputStream,Charset)传入字节流、编码方式两种参数,
*/
//演示使用转换流解决中文乱码问题:编程将字节流 FileInputStream 包装成(转换成)字符流 InputStreamReader
// 对文件进行读取(按照utf-8/gbk格式),进而包装成BufferedReader
class InputStreamReader_ {
public static void main(String[] args) throws IOException {
//读取gbk格式的文件
String filePath = "e:\\a.txt";
//解读
//1. 把 FileInputStream 转成 InputStreamReader
//2. 指定编码 gbk
//InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
//3. 把 InputStreamReader 传入 BufferedReader
//BufferedReader br = new BufferedReader(isr);
//将2 和 3 合在一起
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath), "gbk"));
//4. 读取
String s = br.readLine();
System.out.println("读取内容=" + s);
//5. 关闭外层流
br.close();
}
}
//演示 OutputStreamWriter 使用:把FileOutputStream 字节流,转成字符流 OutputStreamWriter
// 指定输出的编码 utf-8/utf8
class OutputStreamWriter_ {
public static void main(String[] args) throws IOException {
String filePath = "e:\\hsp.txt";
String charSet = "utf-8";//如果要输出的字符没有中文,最终也可能显示为别的格式
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
osw.write("按照 " + charSet + " 格式输出字符");
osw.close();
System.out.println("按照 " + charSet + " 保存文件成功~");
}
}
| 92rw/Java-Study-Notes | JavaNote/Studynote80_StandardStream.java | 1,563 | //在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器
| line_comment | zh-cn | import java.io.*;
import java.util.Scanner;
public class Studynote80_StandardStream {
}
/*
流的类型:只要记住大体分为 输入流和输出流,根据流的类型分类:字节流和字符流,根据流的传输类型:节点流,处理流,对象流,标准输入/输出流,转换流
标准流
类型 默认设备
System.in标准输入 InputStream 键盘
System.out标准输出 PrintStream 显示器
打印流(只有输出流,没有输入流):PrintStream字节流和PrintWriter字符流
*/
class InputAndOutput {
public static void main(String[] args) {
//System 类 的 public final static InputStream in = null;
// System.in 编译类型 InputStream
// System.in 运行类型 BufferedInputStream
// 表示的是标准输入 键盘
System.out.println(System.in.getClass());
//1. System.out public final static PrintStream out = null;
//2. 编译类型 PrintStream
//3. 运行类型 PrintStream
//4. 表示标准输出 显示器
System.out.println(System.out.getClass());
System.out.println("System.out 方法将数据输出到显示器");
Scanner scanner = new Scanner(System.in);
System.out.println("传统的方法,Scanner是从标准输入System.in 获取键盘数据");
String next = scanner.next();
System.out.println("scanner获取到的 next=" + next);
}
}
//演示PrintStream (字节打印流/输出流)
class PrintStream_ {
public static void main(String[] args) throws IOException {
PrintStream out = System.out;
//System.out是System类的静态属性,指向PrintStream类的对象。在底层其实被赋值了;final对类的要求是地址不能变,里面的值可以更改
// initializeSystemClass()方法里可以看到,只是赋值具体过程调用的native本地方法,即C++方法无法获取
//在默 <SUF>
/*源码
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}
*/
out.print("john, hello");
//这里out.print 和 out.write 调用的 write 方法不一样,out.print 方法调用的write 是被private修饰的,
// 而这里直接调用的write是public,因此调用write进行打印/输出时需要转为byte[]数组传入
//打印Sting时,底层调用的是BufferedWriter的wirte(Sting)方法,但是这个方法是私有的
out.write("约翰,你好".getBytes());
out.close();
//我们可以去修改打印流输出的位置/设备
//1. 输出修改成到 "e:\\f1.txt"
//2. "伊万,你好" 就会输出到 e:\f1.txt
//3. public static void setOut(PrintStream out) {
// checkIO();
// setOut0(out); // native 方法,修改了out
// }
System.setOut(new PrintStream("e:\\f1.txt"));//构造器中传入文件位置
System.out.println("伊万,你好");
//要改回来就再次调用那个setOut()方法,把上面的out传进去,因为上面那个out对象是输出到控制台
}
}
class PrintWriter_ {
public static void main(String[] args) throws IOException {
//可以指定打印位置
//PrintWriter printWriter = new PrintWriter(System.out);
PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));
printWriter.print("hi, 北京你好~~~~");
//flush + 关闭流, 才会将数据写入到文件..
//不只是输出到文件,就算是打印到控制台也是要 flush 刷新一下
printWriter.close();
}
}
/*转换流InputStreamReader和OutputStreamWriter:将字节流转换为字符流
单用字符流,他默认使用的是我们之前ide设置的(默认UTF-8),不能指定,只能改文件或ide。转换流可以指定更灵活
>介绍
1.InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流)
2.OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流)
3.当处理纯文本数据时,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
4.可以在使用时指定编码格式(比如utf-8,gbk,gb2312,IS08859-1等)
编码转换:
构造器InputStreamReader(InputStream,Charset)传入字节流、编码方式两种参数,
构造器OutputStreamReader(OutputStream,Charset)传入字节流、编码方式两种参数,
*/
//演示使用转换流解决中文乱码问题:编程将字节流 FileInputStream 包装成(转换成)字符流 InputStreamReader
// 对文件进行读取(按照utf-8/gbk格式),进而包装成BufferedReader
class InputStreamReader_ {
public static void main(String[] args) throws IOException {
//读取gbk格式的文件
String filePath = "e:\\a.txt";
//解读
//1. 把 FileInputStream 转成 InputStreamReader
//2. 指定编码 gbk
//InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
//3. 把 InputStreamReader 传入 BufferedReader
//BufferedReader br = new BufferedReader(isr);
//将2 和 3 合在一起
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(filePath), "gbk"));
//4. 读取
String s = br.readLine();
System.out.println("读取内容=" + s);
//5. 关闭外层流
br.close();
}
}
//演示 OutputStreamWriter 使用:把FileOutputStream 字节流,转成字符流 OutputStreamWriter
// 指定输出的编码 utf-8/utf8
class OutputStreamWriter_ {
public static void main(String[] args) throws IOException {
String filePath = "e:\\hsp.txt";
String charSet = "utf-8";//如果要输出的字符没有中文,最终也可能显示为别的格式
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
osw.write("按照 " + charSet + " 格式输出字符");
osw.close();
System.out.println("按照 " + charSet + " 保存文件成功~");
}
}
| 0 | 1,456 | 19 | 1,541 | 20 | 1,539 | 18 | 1,541 | 20 | 2,141 | 36 | false | false | false | false | false | true |
55115_12 | /*
* @Author: your name
* @Date: 2022-02-15 13:58:56
* @LastEditTime: 2022-02-16 10:05:09
* @LastEditors: Please set LastEditors
* @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
* @FilePath: /Blog/img/java/testCode/DobleTest.java
*/
// public class DoubleTest {
// public static void main (String[] args) {
// // 1.声明一个boolean类型的变量并初始化
// boolean b1 = true;
// // 2.打印变量的数值
// System. out .println("b1 = " + b1); // b1 = true
// // 3.修改变量b1的数值=赋值运算符,用于将=右边的数据赋值给=左边的变量,覆盖变量中原来的数值
// b1 = false;
// System. out .println("b1 = " + b1); // b1 = false
// bl = 1; // 错误:不兼容的类型: int无法转换为boolean
// }
// }
/**
* 编程实现字符类型的使用
*/
public class DoubleTest {
public static void main (String[] args) {
// 1.声明一个char类型的变量 并初始化
char c1 = 'a'; // char类型 使用 单引号 引起来
// 2.打印变量的数值
System.out.println("c1 = " + c1); // c1 = a
System.out.println("对应的编号是:" + (int)c1 ); // 表示将 char类型 的c1 强制转换为 inta类型 并打印 97
// 1.声明一个char类型的变量 并初始化
char c2 = 98;
// 2.打印变量的数值
System.out.println("c2 = " + c2); // c2 = b
System.out.println("对应的编号是:" + (int)c2 ); // 98
char c3 = '\u5947';
char c4 = '\u70b9';
System.out.println("最终的结果是: " + c3 + c4); // 奇点
}
} | 946629031/Blog | img/java/testCode/DoubleTest.java | 588 | // 1.声明一个char类型的变量 并初始化 | line_comment | zh-cn | /*
* @Author: your name
* @Date: 2022-02-15 13:58:56
* @LastEditTime: 2022-02-16 10:05:09
* @LastEditors: Please set LastEditors
* @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
* @FilePath: /Blog/img/java/testCode/DobleTest.java
*/
// public class DoubleTest {
// public static void main (String[] args) {
// // 1.声明一个boolean类型的变量并初始化
// boolean b1 = true;
// // 2.打印变量的数值
// System. out .println("b1 = " + b1); // b1 = true
// // 3.修改变量b1的数值=赋值运算符,用于将=右边的数据赋值给=左边的变量,覆盖变量中原来的数值
// b1 = false;
// System. out .println("b1 = " + b1); // b1 = false
// bl = 1; // 错误:不兼容的类型: int无法转换为boolean
// }
// }
/**
* 编程实现字符类型的使用
*/
public class DoubleTest {
public static void main (String[] args) {
// 1. <SUF>
char c1 = 'a'; // char类型 使用 单引号 引起来
// 2.打印变量的数值
System.out.println("c1 = " + c1); // c1 = a
System.out.println("对应的编号是:" + (int)c1 ); // 表示将 char类型 的c1 强制转换为 inta类型 并打印 97
// 1.声明一个char类型的变量 并初始化
char c2 = 98;
// 2.打印变量的数值
System.out.println("c2 = " + c2); // c2 = b
System.out.println("对应的编号是:" + (int)c2 ); // 98
char c3 = '\u5947';
char c4 = '\u70b9';
System.out.println("最终的结果是: " + c3 + c4); // 奇点
}
} | 0 | 558 | 12 | 588 | 12 | 573 | 11 | 588 | 12 | 719 | 21 | false | false | false | false | false | true |
53312_16 | package com.xk.customview.custom.recyclerview;
import android.content.Context;
import android.support.annotation.IdRes;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import com.xk.customview.R;
import java.util.ArrayList;
import java.util.List;
/**
* 大致实现了一个可以向上滚动,回收上面item,添加下面item的功能。不借助scrollBy方法的实现。着重理解原理
* Created by xuekai on 2019/4/6.
*/
public class RecyclerView extends ViewGroup {
@IdRes
private final int TAG_TYPE = 1;
/**
* 内容的偏移量,比如内容的头部距离view的顶部一段距离了,那段距离就是scrollY
*/
int scrollY;
private Adapter adapter;
//当前显示的view
private List<View> viewList;
//行数
private int rowCount;
//初始化???
private boolean needRelayout;
//recyclerview的宽度
private int width;
//recyclerview的高度
private int height;
//孩子们的高度
private int[] heights;
//回收池
private Recycler recycler;
//第一个显示的item的position,该变量用来记录第一个显示的item的position。在onLayout的时候,从这个position开始向后布局
private int firstVisiablePosition = 0;
//手指按下的Y
private float downY;
//上一次事件的Y
private float lastY;
private int scaledTouchSlop;
public RecyclerView(Context context) {
this(context, null);
}
public RecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setAdapter(Adapter adapter) {
this.adapter = adapter;
init();
requestLayout();
}
private void init() {
ViewConfiguration vc = ViewConfiguration.get(getContext());
scaledTouchSlop = vc.getScaledTouchSlop();
needRelayout = true;
viewList = new ArrayList<>();
if (adapter != null) {
recycler = new Recycler(adapter.getViewTypeCount());
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (adapter != null && needRelayout) {
needRelayout = false;
viewList.clear();
removeAllViews();
//正在摆放的孩子的top。
// TODO: by xk 2019/4/6 18:41 如果只是第一次初始化,top为0,但是如果实在刷新的话,可能第一个显示的孩子的top并不一定是0
int top = 0;
if (adapter != null) {
width = r - l;
height = b - t;
// TODO: by xk 2019/4/6 18:43 为啥从0开始,应该是从firstVisiableView开始
//开始循环摆放子控件,但是不是从0开始摆所有,而是只摆放边界之内的。通过top<=height来判断
for (int i = 0; i < adapter.getCount() && top <= height; i++) {
makeAndStepView(0, top, r, top + heights[i], i);
top += heights[i];
}
}
}
}
/**
* 创建、获取并且安装一个子View
*/
private void makeAndStepView(int l, int t, int r, int b, int position) {
View view = obtainView(position);
//测量孩子。说实话,我们下面layout的时候,位置父亲已经制定好了,不需要测量了。毕竟测量出来的数字也就是为了layout使用。但是最好还是测量一下,毕竟子view自定义控件里面或许自己需要。
view.measure(MeasureSpec.makeMeasureSpec(r - l, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(b - t, MeasureSpec.EXACTLY));
view.layout(l, t, r, b);
}
private View obtainView(int position) {
//通过回收池拿到了一个View,可能为空。然后让adapter去处理。如果是空的,getView中创建。如果不为空,getView设置一下数据直接给返回。
View convertView = recycler.getViewByItemType(adapter.getItemType(position));
View view = adapter.getView(position, convertView, this);
if (view == null) {
throw new RuntimeException("getView返回的view为空了");
}
//???为啥要给第一个添加
viewList.add(view);
view.setTag(R.id.tag_type, adapter.getItemType(position));
addView(view);
return view;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int tempH = 0;
//把所有孩子的高度遍历放到heights集合中。同时,计算出recyclerview的高度。
if (adapter != null) {
heights = new int[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++) {
heights[i] = adapter.getHeight();
tempH += heights[i];
}
}
//上一步计算的高度和控件父亲约束的高度取最小值
int minHeight = Math.min(heightSize, tempH);
setMeasuredDimension(widthSize,
minHeight);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
lastY = downY = ev.getY();
Log.i("RecyclerView", "onInterceptTouchEvent-->down");
break;
case MotionEvent.ACTION_MOVE:
float diffY = downY - ev.getY();
if (Math.abs(diffY) > Math.abs(scaledTouchSlop)) {
Log.i("RecyclerView", "onInterceptTouchEvent-->move");
//拦截
return true;
}
break;
default:
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i("RecyclerView", "onTouchEvent" + event.getAction());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
int diffY = (int) (lastY - event.getY());
lastY = event.getY();
scrollBy(0, diffY);
break;
default:
break;
}
return super.onTouchEvent(event);
}
@Override
public void scrollBy(int x, int y) {
scrollY += y;
//添加孩子、删除孩子
View firstVisiableView = viewList.get(0);
if (y > 0) {
if (-firstVisiableView.getTop() > adapter.getHeight()) {
//这个被划出去了
removeTopView(firstVisiableView);
}
if (needAddBottom(y)) {
addBottomView();
}
}
firstTop = viewList.get(0).getTop() - y;
reLayoutChild();
}
private void addBottomView() {
int lastPosition = firstVisiablePosition + viewList.size();
View view = obtainView(lastPosition);
//测量孩子。说实话,我们下面layout的时候,位置父亲已经制定好了,不需要测量了。毕竟测量出来的数字也就是为了layout使用。但是最好还是测量一下,毕竟子view自定义控件里面或许自己需要。
view.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(adapter.getHeight(), MeasureSpec.EXACTLY));
}
private boolean needAddBottom(int y) {
int firstTop = viewList.get(0).getTop() - y;
int height = 0;
for (View view : viewList) {
height += view.getHeight();
}
//屏幕展示的内容的高度
int showHeight = height - firstTop;
return showHeight < getHeight();
}
private void removeTopView(View view) {
removeView(view);
viewList.remove(0);
firstVisiablePosition++;
recycler.saveView(view, (Integer) view.getTag(R.id.tag_type));
}
int firstTop = 0;
private void reLayoutChild() {
int top = firstTop;
for (View view : viewList) {
view.layout(0, top, width, adapter.getHeight() + top);
top += adapter.getHeight();
}
}
@Override
public void removeView(View view) {
super.removeView(view);
}
}
| 94kai/Learning-CustomView | app/src/main/java/com/xk/customview/custom/recyclerview/RecyclerView.java | 2,129 | //测量孩子。说实话,我们下面layout的时候,位置父亲已经制定好了,不需要测量了。毕竟测量出来的数字也就是为了layout使用。但是最好还是测量一下,毕竟子view自定义控件里面或许自己需要。 | line_comment | zh-cn | package com.xk.customview.custom.recyclerview;
import android.content.Context;
import android.support.annotation.IdRes;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import com.xk.customview.R;
import java.util.ArrayList;
import java.util.List;
/**
* 大致实现了一个可以向上滚动,回收上面item,添加下面item的功能。不借助scrollBy方法的实现。着重理解原理
* Created by xuekai on 2019/4/6.
*/
public class RecyclerView extends ViewGroup {
@IdRes
private final int TAG_TYPE = 1;
/**
* 内容的偏移量,比如内容的头部距离view的顶部一段距离了,那段距离就是scrollY
*/
int scrollY;
private Adapter adapter;
//当前显示的view
private List<View> viewList;
//行数
private int rowCount;
//初始化???
private boolean needRelayout;
//recyclerview的宽度
private int width;
//recyclerview的高度
private int height;
//孩子们的高度
private int[] heights;
//回收池
private Recycler recycler;
//第一个显示的item的position,该变量用来记录第一个显示的item的position。在onLayout的时候,从这个position开始向后布局
private int firstVisiablePosition = 0;
//手指按下的Y
private float downY;
//上一次事件的Y
private float lastY;
private int scaledTouchSlop;
public RecyclerView(Context context) {
this(context, null);
}
public RecyclerView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public void setAdapter(Adapter adapter) {
this.adapter = adapter;
init();
requestLayout();
}
private void init() {
ViewConfiguration vc = ViewConfiguration.get(getContext());
scaledTouchSlop = vc.getScaledTouchSlop();
needRelayout = true;
viewList = new ArrayList<>();
if (adapter != null) {
recycler = new Recycler(adapter.getViewTypeCount());
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (adapter != null && needRelayout) {
needRelayout = false;
viewList.clear();
removeAllViews();
//正在摆放的孩子的top。
// TODO: by xk 2019/4/6 18:41 如果只是第一次初始化,top为0,但是如果实在刷新的话,可能第一个显示的孩子的top并不一定是0
int top = 0;
if (adapter != null) {
width = r - l;
height = b - t;
// TODO: by xk 2019/4/6 18:43 为啥从0开始,应该是从firstVisiableView开始
//开始循环摆放子控件,但是不是从0开始摆所有,而是只摆放边界之内的。通过top<=height来判断
for (int i = 0; i < adapter.getCount() && top <= height; i++) {
makeAndStepView(0, top, r, top + heights[i], i);
top += heights[i];
}
}
}
}
/**
* 创建、获取并且安装一个子View
*/
private void makeAndStepView(int l, int t, int r, int b, int position) {
View view = obtainView(position);
//测量 <SUF>
view.measure(MeasureSpec.makeMeasureSpec(r - l, MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(b - t, MeasureSpec.EXACTLY));
view.layout(l, t, r, b);
}
private View obtainView(int position) {
//通过回收池拿到了一个View,可能为空。然后让adapter去处理。如果是空的,getView中创建。如果不为空,getView设置一下数据直接给返回。
View convertView = recycler.getViewByItemType(adapter.getItemType(position));
View view = adapter.getView(position, convertView, this);
if (view == null) {
throw new RuntimeException("getView返回的view为空了");
}
//???为啥要给第一个添加
viewList.add(view);
view.setTag(R.id.tag_type, adapter.getItemType(position));
addView(view);
return view;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int tempH = 0;
//把所有孩子的高度遍历放到heights集合中。同时,计算出recyclerview的高度。
if (adapter != null) {
heights = new int[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++) {
heights[i] = adapter.getHeight();
tempH += heights[i];
}
}
//上一步计算的高度和控件父亲约束的高度取最小值
int minHeight = Math.min(heightSize, tempH);
setMeasuredDimension(widthSize,
minHeight);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
lastY = downY = ev.getY();
Log.i("RecyclerView", "onInterceptTouchEvent-->down");
break;
case MotionEvent.ACTION_MOVE:
float diffY = downY - ev.getY();
if (Math.abs(diffY) > Math.abs(scaledTouchSlop)) {
Log.i("RecyclerView", "onInterceptTouchEvent-->move");
//拦截
return true;
}
break;
default:
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
Log.i("RecyclerView", "onTouchEvent" + event.getAction());
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
int diffY = (int) (lastY - event.getY());
lastY = event.getY();
scrollBy(0, diffY);
break;
default:
break;
}
return super.onTouchEvent(event);
}
@Override
public void scrollBy(int x, int y) {
scrollY += y;
//添加孩子、删除孩子
View firstVisiableView = viewList.get(0);
if (y > 0) {
if (-firstVisiableView.getTop() > adapter.getHeight()) {
//这个被划出去了
removeTopView(firstVisiableView);
}
if (needAddBottom(y)) {
addBottomView();
}
}
firstTop = viewList.get(0).getTop() - y;
reLayoutChild();
}
private void addBottomView() {
int lastPosition = firstVisiablePosition + viewList.size();
View view = obtainView(lastPosition);
//测量孩子。说实话,我们下面layout的时候,位置父亲已经制定好了,不需要测量了。毕竟测量出来的数字也就是为了layout使用。但是最好还是测量一下,毕竟子view自定义控件里面或许自己需要。
view.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(adapter.getHeight(), MeasureSpec.EXACTLY));
}
private boolean needAddBottom(int y) {
int firstTop = viewList.get(0).getTop() - y;
int height = 0;
for (View view : viewList) {
height += view.getHeight();
}
//屏幕展示的内容的高度
int showHeight = height - firstTop;
return showHeight < getHeight();
}
private void removeTopView(View view) {
removeView(view);
viewList.remove(0);
firstVisiablePosition++;
recycler.saveView(view, (Integer) view.getTag(R.id.tag_type));
}
int firstTop = 0;
private void reLayoutChild() {
int top = firstTop;
for (View view : viewList) {
view.layout(0, top, width, adapter.getHeight() + top);
top += adapter.getHeight();
}
}
@Override
public void removeView(View view) {
super.removeView(view);
}
}
| 0 | 1,874 | 48 | 2,130 | 63 | 2,180 | 46 | 2,129 | 63 | 2,762 | 104 | false | false | false | false | false | true |
16341_1 | package entity;
import java.io.Serializable;
public class Article implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
//文章表
private int id;
private String title; //标题
private String content; //正文
private String lead; //导语
private String create_user;//创建人
private String create_time;//创建时间
private String type; //文章类型---技术交流1,我的困惑2,谈谈生活3,情感交流4
private String isdelete; //是否删除0不删除,1删除
private String top; //是否置顶0不置顶,1置顶
private int see; //访问量
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getLead() {
return lead;
}
public void setLead(String lead) {
this.lead = lead;
}
public String getCreate_user() {
return create_user;
}
public void setCreate_user(String create_user) {
this.create_user = create_user;
}
public String getCreate_time() {
return create_time;
}
public void setCreate_time(String create_time) {
this.create_time = create_time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getIsdelete() {
return isdelete;
}
public void setIsdelete(String isdelete) {
this.isdelete = isdelete;
}
public String getTop() {
return top;
}
public void setTop(String top) {
this.top = top;
}
public int getSee() {
return see;
}
public void setSee(int see) {
this.see = see;
}
}
| 970263611/boke | component/api/src/main/java/entity/Article.java | 588 | //创建人 | line_comment | zh-cn | package entity;
import java.io.Serializable;
public class Article implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
//文章表
private int id;
private String title; //标题
private String content; //正文
private String lead; //导语
private String create_user;//创建 <SUF>
private String create_time;//创建时间
private String type; //文章类型---技术交流1,我的困惑2,谈谈生活3,情感交流4
private String isdelete; //是否删除0不删除,1删除
private String top; //是否置顶0不置顶,1置顶
private int see; //访问量
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getLead() {
return lead;
}
public void setLead(String lead) {
this.lead = lead;
}
public String getCreate_user() {
return create_user;
}
public void setCreate_user(String create_user) {
this.create_user = create_user;
}
public String getCreate_time() {
return create_time;
}
public void setCreate_time(String create_time) {
this.create_time = create_time;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getIsdelete() {
return isdelete;
}
public void setIsdelete(String isdelete) {
this.isdelete = isdelete;
}
public String getTop() {
return top;
}
public void setTop(String top) {
this.top = top;
}
public int getSee() {
return see;
}
public void setSee(int see) {
this.see = see;
}
}
| 0 | 444 | 3 | 588 | 3 | 588 | 3 | 588 | 3 | 671 | 4 | false | false | false | false | false | true |
26397_2 | package appupdate.bitpai.comz.testz;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class LoadView extends View {
//背景颜色,圆环,字
int color_bg,color_circle,color_tv;
//背景圆半径,字,圆环宽度,加载时间
int size_cicle,size_tv,size_circle_width,size_time;
//字的长度
float length_tv;
//圆环的开始角度和结束角度
float angle_start=-90,angle_end;
//背景画笔
Paint paint_bg=new Paint();
Paint paint_cicle=new Paint();
Paint paint_tv=new Paint();
//圆环大小,位置
RectF rectF;
Path path = new Path();
ValueAnimator animator;
public LoadView(Context context) {
this(context, null, 0);
}
public LoadView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public LoadView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init(){
color_bg= Color.parseColor("#4D161515");
color_circle=Color.WHITE;
color_tv=Color.WHITE;
size_cicle=dip2px(getContext(),18);
size_tv=dip2px(getContext(),12);
paint_bg.setColor(color_bg);
paint_bg.setAntiAlias(true);
size_circle_width=dip2px(getContext(),2);
paint_cicle.setStyle(Paint.Style.STROKE);
paint_cicle.setStrokeWidth(size_circle_width);
paint_cicle.setColor(color_circle);
paint_cicle.setAntiAlias(true);
paint_tv.setTextSize(size_tv);
paint_tv.setColor(color_tv);
paint_tv.setAntiAlias(true);
length_tv= paint_tv.measureText("跳过");
size_time=2000;
rectF=new RectF(size_circle_width,size_circle_width,size_cicle*2-size_circle_width,size_cicle*2-size_circle_width);
animator=ValueAnimator.ofFloat(0,1);
animator.setDuration(2000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if(animation.getAnimatedFraction()==1){
if(getEndListener()!=null){
getEndListener().end();
}
}
path.reset();
path.addArc(rectF,-90,360*animation.getAnimatedFraction());
invalidate();
}
});
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.drawCircle(size_cicle,size_cicle,size_cicle,paint_bg);
canvas.drawText("跳过",size_cicle-length_tv/2,size_cicle+size_tv/2,paint_tv);
canvas.drawPath(path,paint_cicle);
}
public void start(){
animator.start();
}
public void end(){
animator.end();
}
public static int dip2px(Context context, float dpValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
private EndListener endListener;
public interface EndListener{
public void end();
}
public EndListener getEndListener() {
return endListener;
}
public void setEndListener(EndListener endListener) {
this.endListener = endListener;
}
}
| 979451341/MDemo | LoadView.java | 1,001 | //字的长度
| line_comment | zh-cn | package appupdate.bitpai.comz.testz;
import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
public class LoadView extends View {
//背景颜色,圆环,字
int color_bg,color_circle,color_tv;
//背景圆半径,字,圆环宽度,加载时间
int size_cicle,size_tv,size_circle_width,size_time;
//字的 <SUF>
float length_tv;
//圆环的开始角度和结束角度
float angle_start=-90,angle_end;
//背景画笔
Paint paint_bg=new Paint();
Paint paint_cicle=new Paint();
Paint paint_tv=new Paint();
//圆环大小,位置
RectF rectF;
Path path = new Path();
ValueAnimator animator;
public LoadView(Context context) {
this(context, null, 0);
}
public LoadView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public LoadView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public void init(){
color_bg= Color.parseColor("#4D161515");
color_circle=Color.WHITE;
color_tv=Color.WHITE;
size_cicle=dip2px(getContext(),18);
size_tv=dip2px(getContext(),12);
paint_bg.setColor(color_bg);
paint_bg.setAntiAlias(true);
size_circle_width=dip2px(getContext(),2);
paint_cicle.setStyle(Paint.Style.STROKE);
paint_cicle.setStrokeWidth(size_circle_width);
paint_cicle.setColor(color_circle);
paint_cicle.setAntiAlias(true);
paint_tv.setTextSize(size_tv);
paint_tv.setColor(color_tv);
paint_tv.setAntiAlias(true);
length_tv= paint_tv.measureText("跳过");
size_time=2000;
rectF=new RectF(size_circle_width,size_circle_width,size_cicle*2-size_circle_width,size_cicle*2-size_circle_width);
animator=ValueAnimator.ofFloat(0,1);
animator.setDuration(2000);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
if(animation.getAnimatedFraction()==1){
if(getEndListener()!=null){
getEndListener().end();
}
}
path.reset();
path.addArc(rectF,-90,360*animation.getAnimatedFraction());
invalidate();
}
});
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
canvas.drawCircle(size_cicle,size_cicle,size_cicle,paint_bg);
canvas.drawText("跳过",size_cicle-length_tv/2,size_cicle+size_tv/2,paint_tv);
canvas.drawPath(path,paint_cicle);
}
public void start(){
animator.start();
}
public void end(){
animator.end();
}
public static int dip2px(Context context, float dpValue) {
float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
private EndListener endListener;
public interface EndListener{
public void end();
}
public EndListener getEndListener() {
return endListener;
}
public void setEndListener(EndListener endListener) {
this.endListener = endListener;
}
}
| 0 | 792 | 5 | 985 | 5 | 1,030 | 5 | 985 | 5 | 1,227 | 6 | false | false | false | false | false | true |
3291_2 | package com.cf.forward.hk.task;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.cf.forward.hk.hardware.HkHelper;
import com.cf.forward.hk.hardware.handle.DvrMessageHandleImpl;
import com.cf.forward.hk.utils.SpringContextUtil;
import com.cf.framework.domain.response.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
/**
* @author why
*/
@Slf4j
public class CheckOrderTask {
/**
* 当前语音播报对象
*/
private static Map<String, JSONObject> radioObj = new ConcurrentHashMap<>();
private static Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();
public static void startCron(String carLogId, String deviceIP, String baseUrl) {
ThreadPoolTaskScheduler scheduler = SpringContextUtil.getBean(ThreadPoolTaskScheduler.class);
ScheduledFuture<?> future = futureMap.get(carLogId);
if (Objects.isNull(future)) {
// 注: 应该清空前一辆车记录,
// if (futureMap.size() > 0) {
// for (String key : futureMap.keySet()) {
// if(!key.equals(carLogId)){
// stopCron(key);
// }
// }
// }
// =========
future = scheduler.schedule(new Runnable() {
private int retryCount = 0;
@Override
public void run() {
if (retryCount < 600) {
retryCount++;
checkOrder(carLogId, deviceIP, baseUrl);
} else {
stopCron(carLogId);
}
}
}, new CronTrigger("0/5 * * * * *"));
log.info("开始检查订单是否支付");
futureMap.put(carLogId, future);
}
}
public static void stopCron(String carLogId) {
ScheduledFuture<?> future = futureMap.get(carLogId);
if (Objects.nonNull(future)) {
future.cancel(true);
futureMap.remove(carLogId);
}
log.info("已重试600次,停止检查");
}
/**
* 检查订单是否支付
*
* @param carLogId 记录ID
* @param deviceIP 设备IP
*/
private static void checkOrder(String carLogId, String deviceIP, String baseUrl) {
String url = baseUrl + "/carparkorder/check_order_is_pay?id=" + carLogId;
String result = HttpUtil.createGet(url).execute().body();
ObjectMapper mapper = new ObjectMapper();
ResponseResult responseResult = null;
try {
responseResult = mapper.readValue(result, ResponseResult.class);
} catch (IOException e) {
log.info(e.getMessage());
}
if (Objects.nonNull(responseResult) && responseResult.isSuccess() && responseResult.getCode() == 10002 && Objects.nonNull(responseResult.getData())) {
HkHelper hkHelper = SpringContextUtil.getBean(HkHelper.class);
JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(responseResult.getData()));
String carNo = json.getString("effectObject");
BigDecimal money = BigDecimal.ZERO;
BigDecimal amountActuallyPaid = json.getBigDecimal("amountActuallyPaid");
if (null != amountActuallyPaid) {
money = amountActuallyPaid;
}
Integer status = json.getInteger("status");
if (null != status && status == 1) {
// 判断是否有欠费订单
String effectObject = json.getString("effectObject");
JSONObject currencyMap = json.getJSONObject("currencyMap");
if (null != currencyMap && null != currencyMap.getJSONArray("arrearsOrder") && currencyMap.getJSONArray("arrearsOrder").size() > 0) {
JSONObject obj = CheckOrderTask.radioObj.get("carLogId");
if (null == obj) {
int size = currencyMap.getJSONArray("arrearsOrder").size();
String info = effectObject + " 还有" + size + "个 订单未支付 请先完成支付";
hkHelper.controlVoice(info);
JSONObject jsonObject = new JSONObject();
jsonObject.put("ceateTime", new Date());
jsonObject.put("numberPlate", effectObject);
CheckOrderTask.radioObj.put("carLogId", jsonObject);
SpaceNumAsyncTask.stopCarInfo.setCreateTime(new Date());
SpaceNumAsyncTask.stopCarInfo.setShowTxt(info);
SpaceNumAsyncTask.stopCarInfo.setNumberPlate(carNo);
} else {
}
} else {
stopCron(carLogId);
CheckOrderTask.radioObj.remove(carLogId);
log.info(String.format("ip:%s, 车牌号:%s,停车记录ID:%s,已支付:%s,尝试开闸", deviceIP, carNo, carLogId, money.toPlainString()));
hkHelper.openAndClose(true);
hkHelper.controlVoice("一路顺风");
DvrMessageHandleImpl dvrMessageHandle = SpringContextUtil.getBean(DvrMessageHandleImpl.class);
}
} else {
// 判断是否有欠费订单
String effectObject = json.getString("effectObject");
JSONObject currencyMap = json.getJSONObject("currencyMap");
if (null != currencyMap && null != currencyMap.getJSONArray("arrearsOrder") && currencyMap.getJSONArray("arrearsOrder").size() > 0) {
JSONObject obj = CheckOrderTask.radioObj.get("carLogId");
if (null == obj) {
int size = currencyMap.getJSONArray("arrearsOrder").size();
String info = effectObject + " 还有" + size + "个 订单未支付 请先完成支付";
hkHelper.controlVoice(info);
JSONObject jsonObject = new JSONObject();
jsonObject.put("ceateTime", new Date());
jsonObject.put("numberPlate", effectObject);
CheckOrderTask.radioObj.put("carLogId", jsonObject);
SpaceNumAsyncTask.stopCarInfo.setCreateTime(new Date());
SpaceNumAsyncTask.stopCarInfo.setShowTxt(info);
SpaceNumAsyncTask.stopCarInfo.setNumberPlate(carNo);
}
}
}
} else {
log.info(String.format("ip:%s,停车记录ID:%s,未支付", deviceIP, carLogId));
}
}
}
| 981011512/-- | cf-framework-parent/cf-internet-of-things/cf-car-park/forward/src/main/java/com/cf/forward/hk/task/CheckOrderTask.java | 1,608 | // 注: 应该清空前一辆车记录, | line_comment | zh-cn | package com.cf.forward.hk.task;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.cf.forward.hk.hardware.HkHelper;
import com.cf.forward.hk.hardware.handle.DvrMessageHandleImpl;
import com.cf.forward.hk.utils.SpringContextUtil;
import com.cf.framework.domain.response.ResponseResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
/**
* @author why
*/
@Slf4j
public class CheckOrderTask {
/**
* 当前语音播报对象
*/
private static Map<String, JSONObject> radioObj = new ConcurrentHashMap<>();
private static Map<String, ScheduledFuture<?>> futureMap = new ConcurrentHashMap<>();
public static void startCron(String carLogId, String deviceIP, String baseUrl) {
ThreadPoolTaskScheduler scheduler = SpringContextUtil.getBean(ThreadPoolTaskScheduler.class);
ScheduledFuture<?> future = futureMap.get(carLogId);
if (Objects.isNull(future)) {
// 注: <SUF>
// if (futureMap.size() > 0) {
// for (String key : futureMap.keySet()) {
// if(!key.equals(carLogId)){
// stopCron(key);
// }
// }
// }
// =========
future = scheduler.schedule(new Runnable() {
private int retryCount = 0;
@Override
public void run() {
if (retryCount < 600) {
retryCount++;
checkOrder(carLogId, deviceIP, baseUrl);
} else {
stopCron(carLogId);
}
}
}, new CronTrigger("0/5 * * * * *"));
log.info("开始检查订单是否支付");
futureMap.put(carLogId, future);
}
}
public static void stopCron(String carLogId) {
ScheduledFuture<?> future = futureMap.get(carLogId);
if (Objects.nonNull(future)) {
future.cancel(true);
futureMap.remove(carLogId);
}
log.info("已重试600次,停止检查");
}
/**
* 检查订单是否支付
*
* @param carLogId 记录ID
* @param deviceIP 设备IP
*/
private static void checkOrder(String carLogId, String deviceIP, String baseUrl) {
String url = baseUrl + "/carparkorder/check_order_is_pay?id=" + carLogId;
String result = HttpUtil.createGet(url).execute().body();
ObjectMapper mapper = new ObjectMapper();
ResponseResult responseResult = null;
try {
responseResult = mapper.readValue(result, ResponseResult.class);
} catch (IOException e) {
log.info(e.getMessage());
}
if (Objects.nonNull(responseResult) && responseResult.isSuccess() && responseResult.getCode() == 10002 && Objects.nonNull(responseResult.getData())) {
HkHelper hkHelper = SpringContextUtil.getBean(HkHelper.class);
JSONObject json = JSONObject.parseObject(JSONObject.toJSONString(responseResult.getData()));
String carNo = json.getString("effectObject");
BigDecimal money = BigDecimal.ZERO;
BigDecimal amountActuallyPaid = json.getBigDecimal("amountActuallyPaid");
if (null != amountActuallyPaid) {
money = amountActuallyPaid;
}
Integer status = json.getInteger("status");
if (null != status && status == 1) {
// 判断是否有欠费订单
String effectObject = json.getString("effectObject");
JSONObject currencyMap = json.getJSONObject("currencyMap");
if (null != currencyMap && null != currencyMap.getJSONArray("arrearsOrder") && currencyMap.getJSONArray("arrearsOrder").size() > 0) {
JSONObject obj = CheckOrderTask.radioObj.get("carLogId");
if (null == obj) {
int size = currencyMap.getJSONArray("arrearsOrder").size();
String info = effectObject + " 还有" + size + "个 订单未支付 请先完成支付";
hkHelper.controlVoice(info);
JSONObject jsonObject = new JSONObject();
jsonObject.put("ceateTime", new Date());
jsonObject.put("numberPlate", effectObject);
CheckOrderTask.radioObj.put("carLogId", jsonObject);
SpaceNumAsyncTask.stopCarInfo.setCreateTime(new Date());
SpaceNumAsyncTask.stopCarInfo.setShowTxt(info);
SpaceNumAsyncTask.stopCarInfo.setNumberPlate(carNo);
} else {
}
} else {
stopCron(carLogId);
CheckOrderTask.radioObj.remove(carLogId);
log.info(String.format("ip:%s, 车牌号:%s,停车记录ID:%s,已支付:%s,尝试开闸", deviceIP, carNo, carLogId, money.toPlainString()));
hkHelper.openAndClose(true);
hkHelper.controlVoice("一路顺风");
DvrMessageHandleImpl dvrMessageHandle = SpringContextUtil.getBean(DvrMessageHandleImpl.class);
}
} else {
// 判断是否有欠费订单
String effectObject = json.getString("effectObject");
JSONObject currencyMap = json.getJSONObject("currencyMap");
if (null != currencyMap && null != currencyMap.getJSONArray("arrearsOrder") && currencyMap.getJSONArray("arrearsOrder").size() > 0) {
JSONObject obj = CheckOrderTask.radioObj.get("carLogId");
if (null == obj) {
int size = currencyMap.getJSONArray("arrearsOrder").size();
String info = effectObject + " 还有" + size + "个 订单未支付 请先完成支付";
hkHelper.controlVoice(info);
JSONObject jsonObject = new JSONObject();
jsonObject.put("ceateTime", new Date());
jsonObject.put("numberPlate", effectObject);
CheckOrderTask.radioObj.put("carLogId", jsonObject);
SpaceNumAsyncTask.stopCarInfo.setCreateTime(new Date());
SpaceNumAsyncTask.stopCarInfo.setShowTxt(info);
SpaceNumAsyncTask.stopCarInfo.setNumberPlate(carNo);
}
}
}
} else {
log.info(String.format("ip:%s,停车记录ID:%s,未支付", deviceIP, carLogId));
}
}
}
| 0 | 1,390 | 12 | 1,608 | 15 | 1,669 | 11 | 1,608 | 15 | 2,008 | 20 | false | false | false | false | false | true |
46332_12 | package com.component.impl;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PhoneInfo {
private static final String TAG = PhoneInfo.class.getSimpleName();
private static final String FILE_MEMORY = "/proc/meminfo";
private static final String FILE_CPU = "/proc/cpuinfo";
public String mIMEI = null;
public int mPhoneType = 0;
public String mSysVersion = null;
public String mNetWorkCountryIso = null;
public String mNetWorkOperator = null;
public String mNetWorkOperatorName = null;
public int mNetWorkType = 0;
public boolean mIsOnLine = false;
public String mConnectTypeName = null;
public long mFreeMem = 0;
public long mTotalMem = 0;
public String mMem = null;
public String mCupInfo = null;
public String mProductName = null;
public String mModelName = null;
public String mManufacturerName = null;
public String mIP = null;
public String mISP = null;
public String mDeviceVersion = null;
private static PhoneInfo instance;
private static Activity context;
public static PhoneInfo getInstance() {
if (instance == null)
instance = new PhoneInfo();
return instance;
}
public PhoneInfo() {
init();
}
public static void init(Activity activity) {
PhoneInfo.context = activity;
}
// 设备版本号
public String getIMEI() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getDeviceId();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int getPhoneType() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getPhoneType();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
// ISP
public String getISP() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getSimOperatorName();
} catch (Exception e) {
Log.d("qhero", "get isp error!!", e);
}
return null;
}
// DeviceVersion
public String getDeviceVersion() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getDeviceSoftwareVersion();
} catch (Exception e) {
Log.d("qhero", "get device version error!!", e);
}
return null;
}
// 系统版本号
public String getSysVersion() {
PackageManager packageManager = context.getPackageManager();
PackageInfo packInfo = null;
try {
packInfo = packageManager.getPackageInfo(context.getPackageName(),
0);
return "Android:" + packInfo.versionName;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String getNetWorkCountryIso() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getNetworkCountryIso();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getNetWorkOperator() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getNetworkOperator();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getNetWorkOperatorName() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getNetworkOperatorName();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int getNetworkType() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getNetworkType();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public boolean isOnline() {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
}
return false;
}
public String getConnectTypeName() {
if (!isOnline()) {
return "OFFLINE";
}
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return info.getTypeName();
} else {
return "OFFLINE";
}
}
// 可用内存
public long getFreeMem() {
ActivityManager manager = (ActivityManager) context
.getSystemService(Activity.ACTIVITY_SERVICE);
MemoryInfo info = new MemoryInfo();
manager.getMemoryInfo(info);
long free = info.availMem / 1024 / 1024;
return free;
}
// 总内存
public long getTotalMem() {
try {
FileReader fr = new FileReader(FILE_MEMORY);
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
String[] array = text.split("\\s+");
return Long.valueOf(array[1]) / 1024;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public String getMem() {
return Long.toString(mTotalMem) + "M";
}
// cpu信息
public String getCpuInfo() {
try {
FileReader fr = new FileReader(FILE_CPU);
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
String[] array = text.split(":\\s+", 2);
// for (int i = 0; i < array.length; i++) {
// Log.w(TAG, " ..... " + array[i]);
// }
// Log.w(TAG, text);
return array[1];
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String getProductName() {
return Build.PRODUCT;
}
public String getModelName() {
return Build.MODEL;
}
public String getManufacturerName() {
return Build.MANUFACTURER;
}
// 取得IP地址
public String getIPAddress() {
//这段代码有问题,光取wifi的IP是没有用的,没考虑移动网络的情况,而且这只能取得本地IP,毫无意义 by Clark 2013/11/11
// WifiManager wifiMgr = (WifiManager) context
// .getSystemService(Context.WIFI_SERVICE);
// if (!wifiMgr.isWifiEnabled()) {
// wifiMgr.setWifiEnabled(true);
// }
// WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
// int ip = wifiInfo.getIpAddress();
// return intToIP(ip);
return "0.0.0.0";
}
private String intToIP(final int i) {
return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + (i >> 24 & 0xFF);
}
private void init() {
mIMEI = getIMEI();
mPhoneType = getPhoneType();
mSysVersion = getSysVersion();
mNetWorkCountryIso = getNetWorkCountryIso();
mNetWorkOperator = getNetWorkOperator();
mNetWorkOperatorName = getNetWorkOperatorName();
mNetWorkType = getNetworkType();
mIsOnLine = isOnline();
mConnectTypeName = getConnectTypeName();
mFreeMem = getFreeMem();
mTotalMem = getTotalMem();
mCupInfo = getCpuInfo();
mProductName = getProductName();
mModelName = getModelName();
mManufacturerName = getManufacturerName();
mIP = getIPAddress();
mISP = getISP();
mDeviceVersion = getDeviceVersion();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("IMEI : " + mIMEI + "\n");
builder.append("mPhoneType : " + mPhoneType + "\n");
builder.append("mSysVersion : " + mSysVersion + "\n");
builder.append("mNetWorkCountryIso : " + mNetWorkCountryIso + "\n");
builder.append("mNetWorkOperator : " + mNetWorkOperator + "\n");
builder.append("mNetWorkOperatorName : " + mNetWorkOperatorName + "\n");
builder.append("mNetWorkType : " + mNetWorkType + "\n");
builder.append("mIsOnLine : " + mIsOnLine + "\n");
builder.append("mConnectTypeName : " + mConnectTypeName + "\n");
builder.append("mFreeMem : " + mMem + "M\n");
builder.append("mTotalMem : " + mTotalMem + "M\n");
builder.append("mCupInfo : " + mCupInfo + "\n");
builder.append("mProductName : " + mProductName + "\n");
builder.append("mModelName : " + mModelName + "\n");
builder.append("mISP : " + mISP + "\n");
builder.append("mManufacturerName : " + mManufacturerName + "\n");
builder.append("ip : " + mIP + "\n");
return builder.toString();
}
} | 9miao/CartoonHouse | DMZJ/proj.android/src/com/component/impl/PhoneInfo.java | 2,702 | //这段代码有问题,光取wifi的IP是没有用的,没考虑移动网络的情况,而且这只能取得本地IP,毫无意义 by Clark 2013/11/11 | line_comment | zh-cn | package com.component.impl;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.util.Log;
public class PhoneInfo {
private static final String TAG = PhoneInfo.class.getSimpleName();
private static final String FILE_MEMORY = "/proc/meminfo";
private static final String FILE_CPU = "/proc/cpuinfo";
public String mIMEI = null;
public int mPhoneType = 0;
public String mSysVersion = null;
public String mNetWorkCountryIso = null;
public String mNetWorkOperator = null;
public String mNetWorkOperatorName = null;
public int mNetWorkType = 0;
public boolean mIsOnLine = false;
public String mConnectTypeName = null;
public long mFreeMem = 0;
public long mTotalMem = 0;
public String mMem = null;
public String mCupInfo = null;
public String mProductName = null;
public String mModelName = null;
public String mManufacturerName = null;
public String mIP = null;
public String mISP = null;
public String mDeviceVersion = null;
private static PhoneInfo instance;
private static Activity context;
public static PhoneInfo getInstance() {
if (instance == null)
instance = new PhoneInfo();
return instance;
}
public PhoneInfo() {
init();
}
public static void init(Activity activity) {
PhoneInfo.context = activity;
}
// 设备版本号
public String getIMEI() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getDeviceId();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int getPhoneType() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getPhoneType();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
// ISP
public String getISP() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getSimOperatorName();
} catch (Exception e) {
Log.d("qhero", "get isp error!!", e);
}
return null;
}
// DeviceVersion
public String getDeviceVersion() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getDeviceSoftwareVersion();
} catch (Exception e) {
Log.d("qhero", "get device version error!!", e);
}
return null;
}
// 系统版本号
public String getSysVersion() {
PackageManager packageManager = context.getPackageManager();
PackageInfo packInfo = null;
try {
packInfo = packageManager.getPackageInfo(context.getPackageName(),
0);
return "Android:" + packInfo.versionName;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public String getNetWorkCountryIso() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getNetworkCountryIso();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getNetWorkOperator() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getNetworkOperator();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getNetWorkOperatorName() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getNetworkOperatorName();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public int getNetworkType() {
try {
TelephonyManager manager = (TelephonyManager) context
.getSystemService(Activity.TELEPHONY_SERVICE);
return manager.getNetworkType();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public boolean isOnline() {
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
}
return false;
}
public String getConnectTypeName() {
if (!isOnline()) {
return "OFFLINE";
}
ConnectivityManager manager = (ConnectivityManager) context
.getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null) {
return info.getTypeName();
} else {
return "OFFLINE";
}
}
// 可用内存
public long getFreeMem() {
ActivityManager manager = (ActivityManager) context
.getSystemService(Activity.ACTIVITY_SERVICE);
MemoryInfo info = new MemoryInfo();
manager.getMemoryInfo(info);
long free = info.availMem / 1024 / 1024;
return free;
}
// 总内存
public long getTotalMem() {
try {
FileReader fr = new FileReader(FILE_MEMORY);
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
String[] array = text.split("\\s+");
return Long.valueOf(array[1]) / 1024;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 0;
}
public String getMem() {
return Long.toString(mTotalMem) + "M";
}
// cpu信息
public String getCpuInfo() {
try {
FileReader fr = new FileReader(FILE_CPU);
BufferedReader br = new BufferedReader(fr);
String text = br.readLine();
String[] array = text.split(":\\s+", 2);
// for (int i = 0; i < array.length; i++) {
// Log.w(TAG, " ..... " + array[i]);
// }
// Log.w(TAG, text);
return array[1];
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String getProductName() {
return Build.PRODUCT;
}
public String getModelName() {
return Build.MODEL;
}
public String getManufacturerName() {
return Build.MANUFACTURER;
}
// 取得IP地址
public String getIPAddress() {
//这段 <SUF>
// WifiManager wifiMgr = (WifiManager) context
// .getSystemService(Context.WIFI_SERVICE);
// if (!wifiMgr.isWifiEnabled()) {
// wifiMgr.setWifiEnabled(true);
// }
// WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
// int ip = wifiInfo.getIpAddress();
// return intToIP(ip);
return "0.0.0.0";
}
private String intToIP(final int i) {
return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF)
+ "." + (i >> 24 & 0xFF);
}
private void init() {
mIMEI = getIMEI();
mPhoneType = getPhoneType();
mSysVersion = getSysVersion();
mNetWorkCountryIso = getNetWorkCountryIso();
mNetWorkOperator = getNetWorkOperator();
mNetWorkOperatorName = getNetWorkOperatorName();
mNetWorkType = getNetworkType();
mIsOnLine = isOnline();
mConnectTypeName = getConnectTypeName();
mFreeMem = getFreeMem();
mTotalMem = getTotalMem();
mCupInfo = getCpuInfo();
mProductName = getProductName();
mModelName = getModelName();
mManufacturerName = getManufacturerName();
mIP = getIPAddress();
mISP = getISP();
mDeviceVersion = getDeviceVersion();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("IMEI : " + mIMEI + "\n");
builder.append("mPhoneType : " + mPhoneType + "\n");
builder.append("mSysVersion : " + mSysVersion + "\n");
builder.append("mNetWorkCountryIso : " + mNetWorkCountryIso + "\n");
builder.append("mNetWorkOperator : " + mNetWorkOperator + "\n");
builder.append("mNetWorkOperatorName : " + mNetWorkOperatorName + "\n");
builder.append("mNetWorkType : " + mNetWorkType + "\n");
builder.append("mIsOnLine : " + mIsOnLine + "\n");
builder.append("mConnectTypeName : " + mConnectTypeName + "\n");
builder.append("mFreeMem : " + mMem + "M\n");
builder.append("mTotalMem : " + mTotalMem + "M\n");
builder.append("mCupInfo : " + mCupInfo + "\n");
builder.append("mProductName : " + mProductName + "\n");
builder.append("mModelName : " + mModelName + "\n");
builder.append("mISP : " + mISP + "\n");
builder.append("mManufacturerName : " + mManufacturerName + "\n");
builder.append("ip : " + mIP + "\n");
return builder.toString();
}
} | 0 | 2,296 | 42 | 2,702 | 49 | 2,664 | 41 | 2,702 | 49 | 3,269 | 72 | false | false | false | false | false | true |
35217_0 | package org.CrossApp.lib;
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import com.tbruyelle.rxpermissions3.RxPermissions;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.rxjava3.functions.Consumer;
import static org.CrossApp.lib.CrossAppDevice.list;
public class CAPermissionsManager {
public static void request(List<String> types, CAPermissionsManagerCallBack capermissionsmanagercallback) {
final CrossAppActivity context = CrossAppActivity.getContext();
final RxPermissions rxPermissions = new RxPermissions(context);
String[] array = new String[types.size()];
for (int i = 0; i < types.size(); i++) {
String type = types.get(i);
switch (type) {
case "读取日历": {
array[i] = Manifest.permission.READ_CALENDAR;
}
break;
case "修改日历": {
array[i] = Manifest.permission.WRITE_CALENDAR;
}
break;
case "相机": {
array[i] = Manifest.permission.CAMERA;
}
break;
case "读取联系人": {
array[i] = Manifest.permission.READ_CONTACTS;
}
break;
case "修改联系人": {
array[i] = Manifest.permission.WRITE_CONTACTS;
}
break;
case "GPS定位": {
array[i] = Manifest.permission.ACCESS_FINE_LOCATION;
}
break;
case "WIFI定位": {
array[i] = Manifest.permission.ACCESS_COARSE_LOCATION;
}
break;
case "麦克风": {
array[i] = Manifest.permission.RECORD_AUDIO;
}
break;
case "拨号": {
array[i] = Manifest.permission.CALL_PHONE;
}
break;
case "传感器": {
array[i] = Manifest.permission.BODY_SENSORS;
}
break;
case "发短信": {
array[i] = Manifest.permission.SEND_SMS;
}
break;
case "读取存储卡": {
array[i] = Manifest.permission.READ_EXTERNAL_STORAGE;
}
break;
case "写入存储卡": {
array[i] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
}
break;
default:
break;
}
}
try {
rxPermissions.request(array)
.subscribe(granted -> {
if (granted) {
capermissionsmanagercallback.onCallBack(true);
} else {
new AlertDialog.Builder(context)
.setTitle("权限申请")
.setMessage("在设置-应用-" + CAPermissionsManager.getAppName() + "-权限中开启" +
CAPermissionsManager.getPermissionStr(types)
+ "权限,以正常使用" + CAPermissionsManager.getAppName() + "相关功能")
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
CameraView.closed();
}
})
.setNegativeButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {//处理异常
throwable.printStackTrace();
CameraView.closed();
}
});
} catch (Exception e) {
}
}
public interface CAPermissionsManagerCallBack {
void onCallBack(Boolean isSucess);
}
public static String getAppName() {
try {
PackageManager packageManager = CrossAppActivity.getContext().getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
CrossAppActivity.getContext().getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return CrossAppActivity.getContext().getResources().getString(labelRes);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static String getPermissionStr(List<String> types) {
String str = "";
for (int i = 0; i < types.size(); i++) {
if (i == types.size() - 1) {
str += types.get(i);
} else {
str += types.get(i) + "、";
}
}
return str;
}
private static native void imagePickerWriteCallback(int isSucess);
public static void requestImagePickerWrite() {
final CrossAppActivity context = CrossAppActivity.getContext();
context.runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayList<String> types = new ArrayList<String>();
types.add("读取存储卡");
types.add("写入存储卡");
CAPermissionsManager.request(types, new CAPermissionsManager.CAPermissionsManagerCallBack() {
@Override
public void onCallBack(Boolean isSucess) {
imagePickerWriteCallback(isSucess ? 1 : 0);
}
});
}
});
}
}
| 9miao/CrossApp | CrossApp/proj.android/src/org/CrossApp/lib/CAPermissionsManager.java | 1,231 | //处理异常 | line_comment | zh-cn | package org.CrossApp.lib;
import android.Manifest;
import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import com.tbruyelle.rxpermissions3.RxPermissions;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.rxjava3.functions.Consumer;
import static org.CrossApp.lib.CrossAppDevice.list;
public class CAPermissionsManager {
public static void request(List<String> types, CAPermissionsManagerCallBack capermissionsmanagercallback) {
final CrossAppActivity context = CrossAppActivity.getContext();
final RxPermissions rxPermissions = new RxPermissions(context);
String[] array = new String[types.size()];
for (int i = 0; i < types.size(); i++) {
String type = types.get(i);
switch (type) {
case "读取日历": {
array[i] = Manifest.permission.READ_CALENDAR;
}
break;
case "修改日历": {
array[i] = Manifest.permission.WRITE_CALENDAR;
}
break;
case "相机": {
array[i] = Manifest.permission.CAMERA;
}
break;
case "读取联系人": {
array[i] = Manifest.permission.READ_CONTACTS;
}
break;
case "修改联系人": {
array[i] = Manifest.permission.WRITE_CONTACTS;
}
break;
case "GPS定位": {
array[i] = Manifest.permission.ACCESS_FINE_LOCATION;
}
break;
case "WIFI定位": {
array[i] = Manifest.permission.ACCESS_COARSE_LOCATION;
}
break;
case "麦克风": {
array[i] = Manifest.permission.RECORD_AUDIO;
}
break;
case "拨号": {
array[i] = Manifest.permission.CALL_PHONE;
}
break;
case "传感器": {
array[i] = Manifest.permission.BODY_SENSORS;
}
break;
case "发短信": {
array[i] = Manifest.permission.SEND_SMS;
}
break;
case "读取存储卡": {
array[i] = Manifest.permission.READ_EXTERNAL_STORAGE;
}
break;
case "写入存储卡": {
array[i] = Manifest.permission.WRITE_EXTERNAL_STORAGE;
}
break;
default:
break;
}
}
try {
rxPermissions.request(array)
.subscribe(granted -> {
if (granted) {
capermissionsmanagercallback.onCallBack(true);
} else {
new AlertDialog.Builder(context)
.setTitle("权限申请")
.setMessage("在设置-应用-" + CAPermissionsManager.getAppName() + "-权限中开启" +
CAPermissionsManager.getPermissionStr(types)
+ "权限,以正常使用" + CAPermissionsManager.getAppName() + "相关功能")
.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialogInterface) {
CameraView.closed();
}
})
.setNegativeButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.create()
.show();
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {//处理 <SUF>
throwable.printStackTrace();
CameraView.closed();
}
});
} catch (Exception e) {
}
}
public interface CAPermissionsManagerCallBack {
void onCallBack(Boolean isSucess);
}
public static String getAppName() {
try {
PackageManager packageManager = CrossAppActivity.getContext().getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
CrossAppActivity.getContext().getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return CrossAppActivity.getContext().getResources().getString(labelRes);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
public static String getPermissionStr(List<String> types) {
String str = "";
for (int i = 0; i < types.size(); i++) {
if (i == types.size() - 1) {
str += types.get(i);
} else {
str += types.get(i) + "、";
}
}
return str;
}
private static native void imagePickerWriteCallback(int isSucess);
public static void requestImagePickerWrite() {
final CrossAppActivity context = CrossAppActivity.getContext();
context.runOnUiThread(new Runnable() {
@Override
public void run() {
ArrayList<String> types = new ArrayList<String>();
types.add("读取存储卡");
types.add("写入存储卡");
CAPermissionsManager.request(types, new CAPermissionsManager.CAPermissionsManagerCallBack() {
@Override
public void onCallBack(Boolean isSucess) {
imagePickerWriteCallback(isSucess ? 1 : 0);
}
});
}
});
}
}
| 0 | 1,077 | 3 | 1,231 | 3 | 1,361 | 3 | 1,231 | 3 | 1,663 | 7 | false | false | false | false | false | true |
6646_16 | package com.seu.learn.inheritance;
public class Person {
String name;
int age;
public void eat(){
System.out.println(" 人,吃饭");
}
public void walk(){
System.out.println(" 人,走路");
}
}
class Woman extends Person {
boolean isBeauty;
public void goShopping(){
System.out.println(" 女人喜欢购物");
}
public void eat(){
System.out.println(" 女人少吃,为了减肥。");
}
public void walk(){
System.out.println(" 女人,窈窕的走路。");
}
}
class Man extends Person {
boolean isSmoking;
public void earnMoney(){
System.out.println(" 男人负责工作养家");
}
public void eat() {
System.out.println(" 男人多吃肉,长肌肉");
}
public void walk() {
System.out.println(" 男人霸气的走路");
}
}
class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
p1.eat();
Man man = new Man();
man.eat();
man.age = 25;
man.earnMoney();
// ************************************
System.out.println("************************");
// 对象的多态性,父类的引用指向子类的对象
Person p2 = new Man();
// Person p3 = new Woman();
// 多态的使用: 当调用子父类同名同参数方法时,实际调用的是子类重写父类的方法--- 虚拟方法调用
p2.eat();
p2.walk();
// p2.earnMoney();
System.out.println("**************************");
// 不能调用子类所特有的方法、属性,编译时,p2 是Person类型,
p2.name = "Tom";
// p2.isSmoking = true;
// 有了对象的多态性以后,内存中实际上是加载了子类特有的属性和方法,但是由于变量声明
// 为父类类型,导致编译时,只能调用父类中声明的属性和方法。子类的属性和方法不能调用。
// 如何才能调用子类所特有的属性和方法?
// 使用强制类型转换符,也可称为: 向下转型
Man m1 = (Man) p2;
m1.earnMoney();
m1.isSmoking = true;
// 使用强转时,可能出现ClassCastException 异常
// Woman w1 = (Woman)p2;
// w1.goShopping();
/*
* instanceof 关键字的使用
* a instanceof A:判断对象a 是否是类A 的实例。如果是,
返回true,如果不是,返回false;
* 使用情境:为了避免在向下转型时出现ClassCastException
异常,我们在进行向下转型之前,先进行instanceof 的判断, 一旦返回
true, 就进行向下转型。如果返回false,不进行向下转型。
* 如果a instanceof A 返回true, 则a instanceof B 也返回
true。 其中类B 是类A 的父类。
*/
if (p2 instanceof Woman) {
Woman w1 = (Woman) p2;
w1.goShopping();
System.out.println("**********Woman*********");
}
if (p2 instanceof Man) {
Man m2 = (Man) p2;
m2.earnMoney();
System.out.println("*********Man************");
}
if (p2 instanceof Person) {
System.out.println("***********Person************");
}
if (p2 instanceof Object) {
System.out.println("***********object************");
}
// 向下转型的常见问题
// 练习
// 问题1: 编译时通过,运行时不通过
// 举例一
// Person p3 = new Woman();
// Man m3 = (Man)p3;
// 举例二
// Person p4 = new Person();
// Man m4 = (Man)p4;
// 问题二: 编译通过,运行时也通过
Object obj = new Woman();
Person p = (Person)obj;
// 问题三: 编译不通过
// Man m5 = new woman();
// String str = new Date();
// Object o = new Date();
// String str1 = (String)o;
}
}
| A-BigTree/Code_Learning | Java入门/code/inheritance/Person.java | 1,067 | // 举例一 | line_comment | zh-cn | package com.seu.learn.inheritance;
public class Person {
String name;
int age;
public void eat(){
System.out.println(" 人,吃饭");
}
public void walk(){
System.out.println(" 人,走路");
}
}
class Woman extends Person {
boolean isBeauty;
public void goShopping(){
System.out.println(" 女人喜欢购物");
}
public void eat(){
System.out.println(" 女人少吃,为了减肥。");
}
public void walk(){
System.out.println(" 女人,窈窕的走路。");
}
}
class Man extends Person {
boolean isSmoking;
public void earnMoney(){
System.out.println(" 男人负责工作养家");
}
public void eat() {
System.out.println(" 男人多吃肉,长肌肉");
}
public void walk() {
System.out.println(" 男人霸气的走路");
}
}
class PersonTest {
public static void main(String[] args) {
Person p1 = new Person();
p1.eat();
Man man = new Man();
man.eat();
man.age = 25;
man.earnMoney();
// ************************************
System.out.println("************************");
// 对象的多态性,父类的引用指向子类的对象
Person p2 = new Man();
// Person p3 = new Woman();
// 多态的使用: 当调用子父类同名同参数方法时,实际调用的是子类重写父类的方法--- 虚拟方法调用
p2.eat();
p2.walk();
// p2.earnMoney();
System.out.println("**************************");
// 不能调用子类所特有的方法、属性,编译时,p2 是Person类型,
p2.name = "Tom";
// p2.isSmoking = true;
// 有了对象的多态性以后,内存中实际上是加载了子类特有的属性和方法,但是由于变量声明
// 为父类类型,导致编译时,只能调用父类中声明的属性和方法。子类的属性和方法不能调用。
// 如何才能调用子类所特有的属性和方法?
// 使用强制类型转换符,也可称为: 向下转型
Man m1 = (Man) p2;
m1.earnMoney();
m1.isSmoking = true;
// 使用强转时,可能出现ClassCastException 异常
// Woman w1 = (Woman)p2;
// w1.goShopping();
/*
* instanceof 关键字的使用
* a instanceof A:判断对象a 是否是类A 的实例。如果是,
返回true,如果不是,返回false;
* 使用情境:为了避免在向下转型时出现ClassCastException
异常,我们在进行向下转型之前,先进行instanceof 的判断, 一旦返回
true, 就进行向下转型。如果返回false,不进行向下转型。
* 如果a instanceof A 返回true, 则a instanceof B 也返回
true。 其中类B 是类A 的父类。
*/
if (p2 instanceof Woman) {
Woman w1 = (Woman) p2;
w1.goShopping();
System.out.println("**********Woman*********");
}
if (p2 instanceof Man) {
Man m2 = (Man) p2;
m2.earnMoney();
System.out.println("*********Man************");
}
if (p2 instanceof Person) {
System.out.println("***********Person************");
}
if (p2 instanceof Object) {
System.out.println("***********object************");
}
// 向下转型的常见问题
// 练习
// 问题1: 编译时通过,运行时不通过
// 举例 <SUF>
// Person p3 = new Woman();
// Man m3 = (Man)p3;
// 举例二
// Person p4 = new Person();
// Man m4 = (Man)p4;
// 问题二: 编译通过,运行时也通过
Object obj = new Woman();
Person p = (Person)obj;
// 问题三: 编译不通过
// Man m5 = new woman();
// String str = new Date();
// Object o = new Date();
// String str1 = (String)o;
}
}
| 0 | 981 | 4 | 1,067 | 5 | 1,070 | 4 | 1,067 | 5 | 1,418 | 7 | false | false | false | false | false | true |
25769_2 | /**
* @author qhhu
* @date 2019/11/15 - 9:34
*
* [337] 打家劫舍 III
*
* 题目: 所有房屋排列类似二叉树, 返回在不触动劲爆的情况下, 小偷一晚上能够偷盗的最高金额
* (若两个直接相连的房子在同一天晚上被打劫, 房屋将自动报警)
*
* 难度: medium
*
* 思路: 树型dp, ans[0]代表`不偷盗`当前节点可以获得的最大金额, ans[1]代表`可以偷盗`当前节点可以过得的最大金额
* `可以偷盗`的意思是当前房屋可以偷盗也可以不偷盗
*/
class Solution {
/**
* 时间复杂度: O(n)
* 空间复杂度: O(n) (n为树的高度即递归栈的深度)
*/
public int rob(TreeNode root) {
int[] ans = dfs(root);
return Math.max(ans[0], ans[1]);
}
private int[] dfs(TreeNode root) {
if (root == null) {
return new int[] {0, 0};
}
int[] left = dfs(root.left);
int[] right = dfs(root.right);
int[] ans = new int[2];
ans[0] = left[1] + right[1];
// 可以偷盗当前房屋的情况下, 可以选择不偷盗当前房屋
ans[1] = Math.max(ans[0], root.val + left[0] + right[0]);
return ans;
}
}
| A11Might/leetcode | src/lc337.java | 437 | // 可以偷盗当前房屋的情况下, 可以选择不偷盗当前房屋 | line_comment | zh-cn | /**
* @author qhhu
* @date 2019/11/15 - 9:34
*
* [337] 打家劫舍 III
*
* 题目: 所有房屋排列类似二叉树, 返回在不触动劲爆的情况下, 小偷一晚上能够偷盗的最高金额
* (若两个直接相连的房子在同一天晚上被打劫, 房屋将自动报警)
*
* 难度: medium
*
* 思路: 树型dp, ans[0]代表`不偷盗`当前节点可以获得的最大金额, ans[1]代表`可以偷盗`当前节点可以过得的最大金额
* `可以偷盗`的意思是当前房屋可以偷盗也可以不偷盗
*/
class Solution {
/**
* 时间复杂度: O(n)
* 空间复杂度: O(n) (n为树的高度即递归栈的深度)
*/
public int rob(TreeNode root) {
int[] ans = dfs(root);
return Math.max(ans[0], ans[1]);
}
private int[] dfs(TreeNode root) {
if (root == null) {
return new int[] {0, 0};
}
int[] left = dfs(root.left);
int[] right = dfs(root.right);
int[] ans = new int[2];
ans[0] = left[1] + right[1];
// 可以 <SUF>
ans[1] = Math.max(ans[0], root.val + left[0] + right[0]);
return ans;
}
}
| 0 | 370 | 19 | 438 | 24 | 398 | 15 | 437 | 24 | 575 | 39 | false | false | false | false | false | true |
16448_23 | package hook;
import javassist.*;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
public class SqlHook implements ClassFileTransformer {
//声明一个Instrumentation 与ClassPool,设置为类中私有的变量
private Instrumentation inst;
private ClassPool classPool;
public SqlHook(Instrumentation inst) {
this.inst = inst;
this.classPool = new ClassPool(true);
}
//对sql语句进行执行的类进行Hook
//通过查看百度Rasp源码,得知jdbc执行statement查询的类名为:com/mysql/jdbc/StatementImpl或com/mysql/cj/jdbc/StatementImpl
//com.mysql.jdbc.Driver是mysql-connector-java 5中的,而com.mysql.cj.jdbc.Driver是mysql-connector-java 6中
//本此使用的是5
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if (className.equals("com/mysql/jdbc/StatementImpl")) {
CtClass ctClass = null;
try {
//找到 StatementImpl 对应的字节码
ctClass = this.classPool.get("com.mysql.jdbc.StatementImpl");
//获取所有method
/**
* 需要Hook的代码
* String sql ="select flag from sql_rasp where sql_test=1 or 1=1";
* Statement stmt =conn.createStatement();
*
* ResultSet rs =stmt.executeQuery(sql);
*/
// String src = "if ($1.substring(971).contains(\"or\"))" +
// "{System.out.println(\"危险,检测到sql注入!\");" +
// "System.out.println();"+
// "return null;}";
String src =" if($1.contains(\"=\")) {\n" +
" System.out.println(\"RASP_ZERO目前只通过正则匹配sql注入攻击\" );\n" +
" System.out.println(\"接收到sql语句\");\n" +
" System.out.println(\"RASP_ZERO将执行监控\");\n" +
" String pattern0 = \"^.*?=(.*)$\";\n" +
" String replacement = \"$1\";\n" +
" System.out.println();\n" +
" String sql = $1.replaceAll(pattern0, replacement);\n" +
" System.out.println(\"sql语句为:\" + sql);\n" +
" if (sql!=null) {\n" +
" String regex = \"(?i)\\\\b(select|order|by|information_schema|outfile|dumpfile|load_file|benchmark|pg_sleep|sleep|is_srvrolemember|updatexml|extractvalue|hex|char|chr|mid|ord|ascii|bin|or)\\\\b\";" +
" java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);\n" +
" java.util.regex.Matcher matcher = pattern.matcher(sql);\n" +
" while (matcher.find()) {\n" +
" System.out.println(\"检测到危险字符,RASP_ZERO将阻断此sql语句的执行\");\n" +
" return null;\n" +
" }\n" +
" }\n" +
" }";
// String src = "if ($1.contains(\"or\"))" +
// "{System.out.println(\"危险,检测到sql注入!\");" +
// "System.out.println();"+
// "return null;}";
// String src ="System.out.println(executeQuery.outParameterQuery.toString());";
// 获取所有method
CtMethod[] methods = ctClass.getMethods();
for (CtMethod method : methods) {
// 找到executeQuery方法,并插入拦截代码
if (method.getName().equals("executeQuery")) {
method.insertBefore(src);
break;
}
//方法信息
}
// 获取字段
// method.insertBefore(src);
// break;
//字节码转换
classfileBuffer = ctClass.toBytecode();
} catch (NotFoundException | CannotCompileException | IOException e) {
e.printStackTrace();
}
}
//如果判断存在恶意语句,则进行拦截
//使用javassist 对字节码进行增强(修改)
return classfileBuffer;
}
} | A1AAAAAAAAAA1/RASP_DEMO | RASP_ZERO/src/main/java/hook/SqlHook.java | 1,100 | //字节码转换
| line_comment | zh-cn | package hook;
import javassist.*;
import java.io.IOException;
import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;
public class SqlHook implements ClassFileTransformer {
//声明一个Instrumentation 与ClassPool,设置为类中私有的变量
private Instrumentation inst;
private ClassPool classPool;
public SqlHook(Instrumentation inst) {
this.inst = inst;
this.classPool = new ClassPool(true);
}
//对sql语句进行执行的类进行Hook
//通过查看百度Rasp源码,得知jdbc执行statement查询的类名为:com/mysql/jdbc/StatementImpl或com/mysql/cj/jdbc/StatementImpl
//com.mysql.jdbc.Driver是mysql-connector-java 5中的,而com.mysql.cj.jdbc.Driver是mysql-connector-java 6中
//本此使用的是5
@Override
public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
if (className.equals("com/mysql/jdbc/StatementImpl")) {
CtClass ctClass = null;
try {
//找到 StatementImpl 对应的字节码
ctClass = this.classPool.get("com.mysql.jdbc.StatementImpl");
//获取所有method
/**
* 需要Hook的代码
* String sql ="select flag from sql_rasp where sql_test=1 or 1=1";
* Statement stmt =conn.createStatement();
*
* ResultSet rs =stmt.executeQuery(sql);
*/
// String src = "if ($1.substring(971).contains(\"or\"))" +
// "{System.out.println(\"危险,检测到sql注入!\");" +
// "System.out.println();"+
// "return null;}";
String src =" if($1.contains(\"=\")) {\n" +
" System.out.println(\"RASP_ZERO目前只通过正则匹配sql注入攻击\" );\n" +
" System.out.println(\"接收到sql语句\");\n" +
" System.out.println(\"RASP_ZERO将执行监控\");\n" +
" String pattern0 = \"^.*?=(.*)$\";\n" +
" String replacement = \"$1\";\n" +
" System.out.println();\n" +
" String sql = $1.replaceAll(pattern0, replacement);\n" +
" System.out.println(\"sql语句为:\" + sql);\n" +
" if (sql!=null) {\n" +
" String regex = \"(?i)\\\\b(select|order|by|information_schema|outfile|dumpfile|load_file|benchmark|pg_sleep|sleep|is_srvrolemember|updatexml|extractvalue|hex|char|chr|mid|ord|ascii|bin|or)\\\\b\";" +
" java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(regex);\n" +
" java.util.regex.Matcher matcher = pattern.matcher(sql);\n" +
" while (matcher.find()) {\n" +
" System.out.println(\"检测到危险字符,RASP_ZERO将阻断此sql语句的执行\");\n" +
" return null;\n" +
" }\n" +
" }\n" +
" }";
// String src = "if ($1.contains(\"or\"))" +
// "{System.out.println(\"危险,检测到sql注入!\");" +
// "System.out.println();"+
// "return null;}";
// String src ="System.out.println(executeQuery.outParameterQuery.toString());";
// 获取所有method
CtMethod[] methods = ctClass.getMethods();
for (CtMethod method : methods) {
// 找到executeQuery方法,并插入拦截代码
if (method.getName().equals("executeQuery")) {
method.insertBefore(src);
break;
}
//方法信息
}
// 获取字段
// method.insertBefore(src);
// break;
//字节 <SUF>
classfileBuffer = ctClass.toBytecode();
} catch (NotFoundException | CannotCompileException | IOException e) {
e.printStackTrace();
}
}
//如果判断存在恶意语句,则进行拦截
//使用javassist 对字节码进行增强(修改)
return classfileBuffer;
}
} | 0 | 983 | 6 | 1,085 | 5 | 1,125 | 5 | 1,085 | 5 | 1,403 | 7 | false | false | false | false | false | true |
36273_6 | package day03;
//Assaultable 接口,接口类型的默认方法是public
interface Assaultable {
void attack();
}
// Mobile 接口
interface Mobile {
void move();
}
// 抽象类实现Assaultable,Mobile,实现接口权限必须大于或等于接口权限
abstract class Weapon implements Mobile, Assaultable {
public void attack() {
};
public void move() {
};
}
// 定义3个类:Tank,Flighter,WarShip都继承自Weapon
//分别用不同的方式实现 Weapon 类中的抽象方法。
class Tank extends Weapon {
public void attack() {
System.out.println("坦克攻击");
}
public void move() {
System.out.println("坦克移动");
}
}
class Flighter extends Weapon {
public void attack() {
System.out.println("飞机攻击");
}
public void move() {
System.out.println("飞机移动");
}
}
class WarShip extends Weapon {
public void attack() {
System.out.println("潜艇攻击");
}
public void move() {
System.out.println("潜艇移动");
}
}
// 写一个类Army,代表一支军队,这个类有一个属性是Weapon数组w(用来存储该军队所拥有的所有武器);
// 该类还提供一个构造方法,在构造方法里通过传一个int类型的参数来限定该类所能拥有的最大武器数量
// 并用这一大小来初始化数组w。
// 该类还提供一个方法addWeapon(Weapon wa),表示把参数wa所代表的武器加入到数组w中。
// 在这个类中还定义两个方法attackAll()和moveAll(),让w数组中的所有武器攻击和移动。
class Army {
private Weapon[] w;
static int size;
Army(int num) {
this.w = new Weapon[num];
size = 0;
}
void addWeapon(Weapon wa){
if(size<w.length)
w[size++]=wa;
}
void attackAll() {
for (int i = 0; i < size; i++) {
w[i].attack();
}
}
void moveAll() {
for(int i=0;i<size;i++){
w[i].move();
}
}
}
//主函数
class War {
public static void main(String[] args) {
Army army=new Army(3);
army.addWeapon(new Tank());
army.addWeapon(new Flighter());
army.addWeapon(new WarShip());
army.attackAll();
army.moveAll();
}
} | A203/Zhangyu123 | day03/War.java | 698 | // 该类还提供一个构造方法,在构造方法里通过传一个int类型的参数来限定该类所能拥有的最大武器数量 | line_comment | zh-cn | package day03;
//Assaultable 接口,接口类型的默认方法是public
interface Assaultable {
void attack();
}
// Mobile 接口
interface Mobile {
void move();
}
// 抽象类实现Assaultable,Mobile,实现接口权限必须大于或等于接口权限
abstract class Weapon implements Mobile, Assaultable {
public void attack() {
};
public void move() {
};
}
// 定义3个类:Tank,Flighter,WarShip都继承自Weapon
//分别用不同的方式实现 Weapon 类中的抽象方法。
class Tank extends Weapon {
public void attack() {
System.out.println("坦克攻击");
}
public void move() {
System.out.println("坦克移动");
}
}
class Flighter extends Weapon {
public void attack() {
System.out.println("飞机攻击");
}
public void move() {
System.out.println("飞机移动");
}
}
class WarShip extends Weapon {
public void attack() {
System.out.println("潜艇攻击");
}
public void move() {
System.out.println("潜艇移动");
}
}
// 写一个类Army,代表一支军队,这个类有一个属性是Weapon数组w(用来存储该军队所拥有的所有武器);
// 该类 <SUF>
// 并用这一大小来初始化数组w。
// 该类还提供一个方法addWeapon(Weapon wa),表示把参数wa所代表的武器加入到数组w中。
// 在这个类中还定义两个方法attackAll()和moveAll(),让w数组中的所有武器攻击和移动。
class Army {
private Weapon[] w;
static int size;
Army(int num) {
this.w = new Weapon[num];
size = 0;
}
void addWeapon(Weapon wa){
if(size<w.length)
w[size++]=wa;
}
void attackAll() {
for (int i = 0; i < size; i++) {
w[i].attack();
}
}
void moveAll() {
for(int i=0;i<size;i++){
w[i].move();
}
}
}
//主函数
class War {
public static void main(String[] args) {
Army army=new Army(3);
army.addWeapon(new Tank());
army.addWeapon(new Flighter());
army.addWeapon(new WarShip());
army.attackAll();
army.moveAll();
}
} | 0 | 541 | 29 | 698 | 33 | 648 | 29 | 698 | 33 | 895 | 51 | false | false | false | false | false | true |
40201_0 | package com.jinaihua.bmi3;
import android.os.Bundle;
import android.app.TabActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
public class TabhostActivity extends TabActivity {
private EditText height = null;
private EditText weight = null;
private Button button = null;
private TextView show = null;
private TabHost host;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabhost);
host = getTabHost();
//创建标签页
TabHost.TabSpec s1 = host.newTabSpec("one");
//标签名
s1.setIndicator("关于BMI");
//内容
s1.setContent(R.id.aboutBMI);
//将标签添加到tabHost组件
host.addTab(s1);
TabHost.TabSpec s2 = host.newTabSpec("two");
s2.setIndicator("BMI测试");
s2.setContent(R.id.testBMI);
host.addTab(s2);
Button button = (Button) findViewById(R.id.BMIbutton);
height = (EditText) findViewById(R.id.height);
weight = (EditText) findViewById(R.id.weight);
show = (TextView) findViewById(R.id.show);
button.setOnClickListener(new View.OnClickListener()
{
double bmi = 0;
public void onClick(View v) {
double h = Double.valueOf(height.getText().toString());
double w = Double.valueOf(weight.getText().toString());
bmi = w / (h * h);
double final_result = exchangeResult(bmi);
if (bmi < 18.5) {
show.setText("体重指数:" + final_result + " " + "偏轻");
} else if (bmi >= 18.5 && bmi < 24) {
show.setText("体重指数:" + final_result + " " + "健康");
} else if (bmi >= 24 && bmi < 28) {
show.setText("体重指数:" + final_result + " " + "偏重");
} else if (bmi >= 28 && bmi < 30) {
show.setText("体重指数:" + final_result + " " + "轻度肥胖");
} else if (bmi >= 30 && bmi < 35) {
show.setText("体重指数:" + final_result + " " + "中度肥胖");
} else if (bmi > 35) {
show.setText("体重指数:" + final_result + " " + "重度肥胖");
}
}
});
}
public double exchangeResult(double result) {
double first = result * 100;
double second = (int) first;
double second_first;
second_first = first - second;
if (second_first > 0.5) {
second++;
}
double jingo = second / 100;
return jingo;
}
}
| A203/jinaihua | BMI3/TabhostActivity.java | 769 | //创建标签页 | line_comment | zh-cn | package com.jinaihua.bmi3;
import android.os.Bundle;
import android.app.TabActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
public class TabhostActivity extends TabActivity {
private EditText height = null;
private EditText weight = null;
private Button button = null;
private TextView show = null;
private TabHost host;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabhost);
host = getTabHost();
//创建 <SUF>
TabHost.TabSpec s1 = host.newTabSpec("one");
//标签名
s1.setIndicator("关于BMI");
//内容
s1.setContent(R.id.aboutBMI);
//将标签添加到tabHost组件
host.addTab(s1);
TabHost.TabSpec s2 = host.newTabSpec("two");
s2.setIndicator("BMI测试");
s2.setContent(R.id.testBMI);
host.addTab(s2);
Button button = (Button) findViewById(R.id.BMIbutton);
height = (EditText) findViewById(R.id.height);
weight = (EditText) findViewById(R.id.weight);
show = (TextView) findViewById(R.id.show);
button.setOnClickListener(new View.OnClickListener()
{
double bmi = 0;
public void onClick(View v) {
double h = Double.valueOf(height.getText().toString());
double w = Double.valueOf(weight.getText().toString());
bmi = w / (h * h);
double final_result = exchangeResult(bmi);
if (bmi < 18.5) {
show.setText("体重指数:" + final_result + " " + "偏轻");
} else if (bmi >= 18.5 && bmi < 24) {
show.setText("体重指数:" + final_result + " " + "健康");
} else if (bmi >= 24 && bmi < 28) {
show.setText("体重指数:" + final_result + " " + "偏重");
} else if (bmi >= 28 && bmi < 30) {
show.setText("体重指数:" + final_result + " " + "轻度肥胖");
} else if (bmi >= 30 && bmi < 35) {
show.setText("体重指数:" + final_result + " " + "中度肥胖");
} else if (bmi > 35) {
show.setText("体重指数:" + final_result + " " + "重度肥胖");
}
}
});
}
public double exchangeResult(double result) {
double first = result * 100;
double second = (int) first;
double second_first;
second_first = first - second;
if (second_first > 0.5) {
second++;
}
double jingo = second / 100;
return jingo;
}
}
| 0 | 645 | 4 | 769 | 4 | 787 | 4 | 769 | 4 | 896 | 8 | false | false | false | false | false | true |
36282_2 | package 任务练习;
public class All {
//~~~~~~~~~~
public static void main(String[] args) {
Army zuoye = new Army(5);// 定义一只军队,武器上限为6
Weapon tank = new Tank();
Weapon flighter = new Flighter();
Weapon warship = new WarShip();
// 定义三种武器。
zuoye.addWeapon(tank);
zuoye.addWeapon(flighter);
zuoye.addWeapon(warship);
zuoye.moveAll();
zuoye.attackAll();
}
}
| A205/Liwu | Day03/任务练习/All.java | 154 | // 定义三种武器。 | line_comment | zh-cn | package 任务练习;
public class All {
//~~~~~~~~~~
public static void main(String[] args) {
Army zuoye = new Army(5);// 定义一只军队,武器上限为6
Weapon tank = new Tank();
Weapon flighter = new Flighter();
Weapon warship = new WarShip();
// 定义 <SUF>
zuoye.addWeapon(tank);
zuoye.addWeapon(flighter);
zuoye.addWeapon(warship);
zuoye.moveAll();
zuoye.attackAll();
}
}
| 0 | 134 | 7 | 154 | 8 | 133 | 5 | 154 | 8 | 190 | 9 | false | false | false | false | false | true |
47372_9 | package com.hfut.caimengqi;
public class Person {
String name;
int age;
String address;
//无参默认构造方法
Person(){
System.out.println("Person的默认构造方法被调用……");
}
//有参构造方法
// Person(String n,dint a,String add){
// name =n;
// age=a;
// address=add;
// } 会报错,一般情况下,当我们设计类时,应该为类显示的添加无参构造方法
//自我介绍
void introduce(){
System.out.println("大家好,我叫"+name+",今年"+age+"岁了,我在"+address);
}
public static void main(String[] args){
Person person =new Person();//实例化一个person对象
person.name ="张三";
person.age =20;
person.address ="USA";
person.introduce();
}
}
//当没有构造方法时,系统会自动生成一个默认构造方法
//构造方法是一种比较烦特殊的方法
//没有发挥类型,方法名和类同名 | A205/caimengqi | Day3/Person.java | 287 | //当没有构造方法时,系统会自动生成一个默认构造方法 | line_comment | zh-cn | package com.hfut.caimengqi;
public class Person {
String name;
int age;
String address;
//无参默认构造方法
Person(){
System.out.println("Person的默认构造方法被调用……");
}
//有参构造方法
// Person(String n,dint a,String add){
// name =n;
// age=a;
// address=add;
// } 会报错,一般情况下,当我们设计类时,应该为类显示的添加无参构造方法
//自我介绍
void introduce(){
System.out.println("大家好,我叫"+name+",今年"+age+"岁了,我在"+address);
}
public static void main(String[] args){
Person person =new Person();//实例化一个person对象
person.name ="张三";
person.age =20;
person.address ="USA";
person.introduce();
}
}
//当没 <SUF>
//构造方法是一种比较烦特殊的方法
//没有发挥类型,方法名和类同名 | 0 | 239 | 15 | 287 | 15 | 282 | 15 | 287 | 15 | 373 | 25 | false | false | false | false | false | true |
15276_13 | package daythree;
//导入包,加*表示不导入所有,而是根据需要去导入。
import daythree.boom.*;
public class Day3 {
public static void main(String[] args){
Phone p=new Phone();
p.name="note";
p.brand="爆米花";
p.price=78;
System.out.println("手机名称 "+p.name);
System.out.println("手机品牌:"+p.brand);
System.out.println("手机价格"+p.price);
p.sendMsg();
//Person
Person ps=new Person("zhangsan",56,"lunar Street");
ps.introduce();
//Fruit
Fruit apple=new Fruit("苹果",13,"兰州王宏农场");
apple.harvest();
//初始化块
Init example=new Init();
//使用另一个包中的类:包名.类名
daythree.pktest.PkTest table=new daythree.pktest.PkTest();
//访问修饰符的作用
daythree.pktest.Access acce=new daythree.pktest.Access();
acce.say_1();
//包的导入实验
Boom bo=new Boom();
//类继承的方法重写
Tiger tig=new Tiger();
tig.sleep("趴着睡");
System.out.println();
//动态绑定
Animal a=new Animal();
a.sleep("趴着睡");
Tiger t=new Tiger();
t.sleep("趴着睡");
Animal g=new Tiger();
g.sleep(g.name);
System.out.println("父类引用指向子类实例,得出的对象的属性:"+g.name);
g.sleep("diaozheshui");
}
}
//Phone 类
class Phone{
//属性
String name;
String brand;
int price;
//行为
void call(){
System.out.println("打电话");
}
void sendMsg(){
System.out.println("发短信");
}
}
class Person{
String name;
int age;
String address;
void introduce(){
System.out.println("大家好,我是"+name+",今年"+age+"岁"+",住在"+address);
}
Person(String name, int age){
this.name=name;
this.age=age;
}
//构造方法(无参数默认)
Person (){
System.out.println("构造函数被调用");
}
//有参数构造函数
Person(String nam,int ag, String add){
this(nam,ag);
address=add;
}
}
//演示this指针的使用
class Fruit{
String name;
int price;
String farmName;
//构造函数
Fruit(){
}
Fruit(String name,int price, String farmName){
this.name=name;
this.price=price;
this.farmName=farmName;
}
void harvest(){
System.out.println("今年收获了599吨水果");
}
}
//演示初始化块
class Init{
int num;
Init(){
num=5;
System.out.println("构造函数被调用");
}
//初始化块
{
System.out.println("初始化块被调用");
}
}
//类继承的方法重写
class Animal{
String name="动物";
String sleepPose;
Animal(){
}
Animal(String name){
this.name = name;
}
public void sleep(String sleepPose){
this.sleepPose=sleepPose;
System.out.println(this.name+"的睡觉姿势谁也不知道");
}
}
class Tiger extends Animal
{
String name="老虎";
String sleepPose;
Tiger(){
}
Tiger(String name){
this.name=name;
}
public void sleep(String sleepPose){
this.sleepPose=sleepPose;
System.out.println(this.name+"是"+sleepPose);
//System.out.println(this.name);
}
}
//抽象类
//多态:父类的某一个类型在不同的子类中有不同的形态
abstract class Worker{
String name;
int id;
public abstract void goToCmy();
public abstract void goToHom();
public abstract void getPayment();
}
class Singer extends Worker{
public void goToCmy(){
}
public void goToHom(){
}
public void getPayment(){
}
} | A205/chuchenggui | Day3.java | 1,201 | //构造函数 | line_comment | zh-cn | package daythree;
//导入包,加*表示不导入所有,而是根据需要去导入。
import daythree.boom.*;
public class Day3 {
public static void main(String[] args){
Phone p=new Phone();
p.name="note";
p.brand="爆米花";
p.price=78;
System.out.println("手机名称 "+p.name);
System.out.println("手机品牌:"+p.brand);
System.out.println("手机价格"+p.price);
p.sendMsg();
//Person
Person ps=new Person("zhangsan",56,"lunar Street");
ps.introduce();
//Fruit
Fruit apple=new Fruit("苹果",13,"兰州王宏农场");
apple.harvest();
//初始化块
Init example=new Init();
//使用另一个包中的类:包名.类名
daythree.pktest.PkTest table=new daythree.pktest.PkTest();
//访问修饰符的作用
daythree.pktest.Access acce=new daythree.pktest.Access();
acce.say_1();
//包的导入实验
Boom bo=new Boom();
//类继承的方法重写
Tiger tig=new Tiger();
tig.sleep("趴着睡");
System.out.println();
//动态绑定
Animal a=new Animal();
a.sleep("趴着睡");
Tiger t=new Tiger();
t.sleep("趴着睡");
Animal g=new Tiger();
g.sleep(g.name);
System.out.println("父类引用指向子类实例,得出的对象的属性:"+g.name);
g.sleep("diaozheshui");
}
}
//Phone 类
class Phone{
//属性
String name;
String brand;
int price;
//行为
void call(){
System.out.println("打电话");
}
void sendMsg(){
System.out.println("发短信");
}
}
class Person{
String name;
int age;
String address;
void introduce(){
System.out.println("大家好,我是"+name+",今年"+age+"岁"+",住在"+address);
}
Person(String name, int age){
this.name=name;
this.age=age;
}
//构造方法(无参数默认)
Person (){
System.out.println("构造函数被调用");
}
//有参数构造函数
Person(String nam,int ag, String add){
this(nam,ag);
address=add;
}
}
//演示this指针的使用
class Fruit{
String name;
int price;
String farmName;
//构造 <SUF>
Fruit(){
}
Fruit(String name,int price, String farmName){
this.name=name;
this.price=price;
this.farmName=farmName;
}
void harvest(){
System.out.println("今年收获了599吨水果");
}
}
//演示初始化块
class Init{
int num;
Init(){
num=5;
System.out.println("构造函数被调用");
}
//初始化块
{
System.out.println("初始化块被调用");
}
}
//类继承的方法重写
class Animal{
String name="动物";
String sleepPose;
Animal(){
}
Animal(String name){
this.name = name;
}
public void sleep(String sleepPose){
this.sleepPose=sleepPose;
System.out.println(this.name+"的睡觉姿势谁也不知道");
}
}
class Tiger extends Animal
{
String name="老虎";
String sleepPose;
Tiger(){
}
Tiger(String name){
this.name=name;
}
public void sleep(String sleepPose){
this.sleepPose=sleepPose;
System.out.println(this.name+"是"+sleepPose);
//System.out.println(this.name);
}
}
//抽象类
//多态:父类的某一个类型在不同的子类中有不同的形态
abstract class Worker{
String name;
int id;
public abstract void goToCmy();
public abstract void goToHom();
public abstract void getPayment();
}
class Singer extends Worker{
public void goToCmy(){
}
public void goToHom(){
}
public void getPayment(){
}
} | 0 | 914 | 3 | 1,201 | 3 | 1,162 | 3 | 1,201 | 3 | 1,501 | 5 | false | false | false | false | false | true |
25679_2 | package com.buzz.utils;
import com.buzz.entity.hotelorders;
import com.buzz.service.hotelOrdersService;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: jyh
* @Date: 2018/10/20 10:58
* 定时任务
*/
@Component
@Log4j2
public class timedTask {
@Resource
hotelOrdersService hotelOrdersService;
/**
* 订单超时,修改状态
* @Scheduled:将方法注册为定时任务 Scheduled:安排
* fixedRate:上一次启动时间点之后x毫秒执行一次 fixedRate:固定汇率
*/
@Scheduled(fixedRate=1000)
public void updateOrderState(){
Long currentMillis= System.currentTimeMillis(); //
List<hotelorders> hotelordersList=hotelOrdersService.hotelordersList();
for (hotelorders h:hotelordersList) {
if(h.getState().equals("待支付")){
Long orderMillis=h.getSubTime().getTime()+1*60*1000;
if(currentMillis>=orderMillis){ //订单超时
hotelOrdersService.byHotelOrderIdUpdateState(h.getOrderId(),"超时未支付");
}
}
}
}
}
| AAAJYH/buzz | src/main/java/com/buzz/utils/timedTask.java | 342 | //订单超时 | line_comment | zh-cn | package com.buzz.utils;
import com.buzz.entity.hotelorders;
import com.buzz.service.hotelOrdersService;
import lombok.extern.log4j.Log4j2;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author: jyh
* @Date: 2018/10/20 10:58
* 定时任务
*/
@Component
@Log4j2
public class timedTask {
@Resource
hotelOrdersService hotelOrdersService;
/**
* 订单超时,修改状态
* @Scheduled:将方法注册为定时任务 Scheduled:安排
* fixedRate:上一次启动时间点之后x毫秒执行一次 fixedRate:固定汇率
*/
@Scheduled(fixedRate=1000)
public void updateOrderState(){
Long currentMillis= System.currentTimeMillis(); //
List<hotelorders> hotelordersList=hotelOrdersService.hotelordersList();
for (hotelorders h:hotelordersList) {
if(h.getState().equals("待支付")){
Long orderMillis=h.getSubTime().getTime()+1*60*1000;
if(currentMillis>=orderMillis){ //订单 <SUF>
hotelOrdersService.byHotelOrderIdUpdateState(h.getOrderId(),"超时未支付");
}
}
}
}
}
| 0 | 305 | 4 | 342 | 3 | 353 | 3 | 342 | 3 | 453 | 7 | false | false | false | false | false | true |
58897_16 | package com.example.anan.AAChartCore.ChartsDemo.chartcomposer;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartModel;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AASeriesElement;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartAnimationType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartFontWeightType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartLineDashStyleType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartStackingType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartVerticalAlignType;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAAnimation;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAChart;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AADataLabels;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAHover;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AALabels;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAOptions;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPlotOptions;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPoint;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPointEvents;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AASelect;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AASeries;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStates;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStyle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATitle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATooltip;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAXAxis;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAYAxis;
import com.github.AAChartModel.AAChartCore.AATools.AAColor;
import com.github.AAChartModel.AAChartCore.AATools.AAGradientColor;
import com.github.AAChartModel.AAChartCore.AATools.AALinearGradientDirection;
import java.util.Map;
public class JSFunctionForAAOptionsComposer {
//https://github.com/AAChartModel/AAChartKit/issues/780
public static AAOptions customDoubleXAxesChart() {
Map<String, Object> gradientColorDic1 = AAGradientColor.linearGradient(
AALinearGradientDirection.ToTop,
"#7052f4",
"#00b0ff"//颜色字符串设置支持十六进制类型和 rgba 类型
);
Map<String, Object> gradientColorDic2 = AAGradientColor.linearGradient(
AALinearGradientDirection.ToTop,
"#EF71FF",
"#4740C8"//颜色字符串设置支持十六进制类型和 rgba 类型
);
AAChart aaChart = new AAChart()
.type(AAChartType.Bar);
AATitle aaTitle = new AATitle()
.text("2015 年德国人口金字塔")
.style(new AAStyle()
.color("#000000")
.fontSize(12.0));
String[] aaCategories = new String[]{"0-4", "5-9", "10-14", "15-19",
"20-24", "25-29", "30-34", "35-39", "40-44",
"45-49", "50-54", "55-59", "60-64", "65-69",
"70-74", "75-79", "80-84", "85-89", "90-94",
"95-99", "100 + "};
AAXAxis aaXAxis1 = new AAXAxis()
.reversed(true)
.categories(aaCategories)
.labels(new AALabels()
.step(1))
;
AAXAxis aaXAxis2 = new AAXAxis()
.reversed(true)
.opposite(true)
.categories(aaCategories)
.linkedTo(0)
.labels(new AALabels()
.step(1));
AAYAxis aaYAxis = new AAYAxis()
.gridLineWidth(0)// Y 轴网格线宽度
.title(new AATitle()
.text(""))//Y 轴标题
.labels(new AALabels()
.formatter("function () {\n" +
" return (Math.abs(this.value) / 1000000) + 'M';\n" +
"}"))
.min(-4000000)
.max(4000000);
AAPlotOptions aaPlotOptions = new AAPlotOptions()
.series(new AASeries()
.animation(new AAAnimation()
.duration(800)
.easing(AAChartAnimationType.Bounce)
)
.stacking(AAChartStackingType.Normal));
AATooltip aaTooltip = new AATooltip()
.enabled(true)
.shared(false)
.formatter("function () {\n" +
" return '<b>' + this.series.name + ', age ' + this.point.category + '</b><br/>' +\n" +
" '人口: ' + Highcharts.numberFormat(Math.abs(this.point.y), 0);\n" +
"}");
AASeriesElement aaSeriesElement1 = new AASeriesElement()
.name("Men")
.color(gradientColorDic1)
.data(new Object[]{-1746181, -1884428, -2089758, -2222362, -2537431, -2507081, -2443179,
-2664537, -3556505, -3680231, -3143062, -2721122, -2229181, -2227768,
-2176300, -1329968, -836804, -354784, -90569, -28367, -3878});
AASeriesElement aaSeriesElement2 = new AASeriesElement()
.name("Women")
.color(gradientColorDic2)
.data(new Object[]{1656154, 1787564, 1981671, 2108575, 2403438, 2366003, 2301402, 2519874,
3360596, 3493473, 3050775, 2759560, 2304444, 2426504, 2568938, 1785638,
1447162, 1005011, 330870, 130632, 21208});
return new AAOptions()
.chart(aaChart)
.title(aaTitle)
.xAxisArray(new AAXAxis[]{aaXAxis1,aaXAxis2})
.yAxis(aaYAxis)
.plotOptions(aaPlotOptions)
.tooltip(aaTooltip)
.series(new Object[]{aaSeriesElement1,aaSeriesElement2});
}
//https://github.com/AAChartModel/AAChartKit/issues/967
public static AAOptions disableColumnChartUnselectEventEffectBySeriesPointEventClickFunction() {
AAChartModel aaChartModel = new AAChartModel()
.chartType(AAChartType.Bar)
.title("Custom Bar Chart select color")
.yAxisReversed(true)
.xAxisReversed(true)
.series(new AASeriesElement[]{
new AASeriesElement()
.name("ElementOne")
.data(new Object[]{211,183,157,133,111,91,73,57,43,31,21,13,7,3})
.allowPointSelect(true)
.states(new AAStates()
.hover(new AAHover()
.color(AAColor.Yellow))
.select(new AASelect()
.color(AAColor.Red))
)
});
AAOptions aaOptions = aaChartModel.aa_toAAOptions();
AAPoint aaPoint = new AAPoint()
.events(new AAPointEvents()
.click("function () {\n" +
" if (this.selected == true) {\n" +
" this.selected = false;\n" +
" }\n" +
" return;\n" +
" }"));
aaOptions.plotOptions.series
.point(aaPoint);
return aaOptions;
}
// Refer to the issue https://github.com/AAChartModel/AAChartKit/issues/589
public static AAOptions customizeEveryDataLabelSinglelyByDataLabelsFormatter() {
AAChartModel aaChartModel = new AAChartModel()
.chartType(AAChartType.Areaspline)//图表类型
.dataLabelsEnabled(true)
.tooltipEnabled(false)
.colorsTheme(new Object[]{AAGradientColor.FizzyPeach})
.markerRadius(0)
.legendEnabled(false)
.categories(new String[]{"美国🇺🇸","欧洲🇪🇺","中国🇨🇳","日本🇯🇵","韩国🇰🇷","越南🇻🇳","中国香港🇭🇰",})
.series(new AASeriesElement[]{
new AASeriesElement()
.data(new Object[]{7.0, 6.9, 2.5, 14.5, 18.2, 21.5, 5.2}),
});
AAOptions aaOptions = aaChartModel.aa_toAAOptions();
aaOptions.yAxis.gridLineDashStyle = AAChartLineDashStyleType.LongDash;//设置Y轴的网格线样式为 AAChartLineDashStyleType.LongDash
String[] unitArr ={"美元", "欧元", "人民币", "日元", "韩元", "越南盾", "港币", };
String unitJSArrStr = javaScriptArrayStringWithJavaArray(unitArr);
String dataLabelsFormatter = String.format("function () {\n" +
" return this.y + %s[this.point.index]; \n" + //单组 series 图表, 获取选中的点的索引是 this.point.index ,多组并且共享提示框,则是this.points[0].index
" }", unitJSArrStr);
AADataLabels aaDatalabels = aaOptions.plotOptions.series.dataLabels;
aaDatalabels
.style(AAStyle.style(AAColor.Red, 10, AAChartFontWeightType.Bold, "1px 1px contrast"))
.formatter(dataLabelsFormatter)
.backgroundColor(AAColor.White)// white color
.borderColor(AAColor.Red)// red color
.borderRadius(1.5)
.borderWidth(1.3)
.x(3).y(-20)
.verticalAlign(AAChartVerticalAlignType.Middle);
return aaOptions;
}
//https://github.com/AAChartModel/AAChartKit-Swift/issues/404
public static AAOptions configureColorfulDataLabelsForPieChart() {
AAOptions aaOptions = new AAOptions()
.title(new AATitle()
.text("Colorful DataLabels For Pie Chart"))
.colors(new Object[]{
"#0c9674", "#7dffc0", "#ff3333", "#facd32", "#ffffa0",
"#EA007B", "#fe117c", "#ffc069", "#06caf4", "#7dffc0"
})
.series(new AASeriesElement[]{
new AASeriesElement()
.type(AAChartType.Pie)
.name("语言热度值")
.innerSize("20%")//内部圆环半径大小占比
.borderWidth(0)//描边的宽度
.allowPointSelect(true)//是否允许在点击数据点标记(扇形图点击选中的块发生位移)
.states(new AAStates()
.hover(new AAHover()
.enabled(false)))//禁用点击区块之后出现的半透明遮罩层
.dataLabels(new AADataLabels()
.allowOverlap(true)//允许字符重叠
.useHTML(true)
.formatter("function () {\n" +
" const point = this.point;\n" +
" return '<span style=\\\"color: ' + point.color + '\\\">' +\n" +
" point.name + ': ' + point.y + '%</span>';\n" +
" }"))
.data(new Object[][]{
{"Firefox", 3336.2},
{"IE", 26.8},
{"Chrome", 666.8},
{"Safari", 88.5},
{"Opera", 46.0},
{"Others", 223.0},
{"Firefox", 3336.2},
{"IE", 26.8},
{"Chrome", 666.8},
{"Safari", 88.5},
{"Opera", 46.0},
{"Others", 223.0},
})
});
return aaOptions;
}
private static String javaScriptArrayStringWithJavaArray(Object[] javaArray) {
StringBuilder originalJsArrStr = new StringBuilder();
for (Object element : javaArray) {
originalJsArrStr.append("'").append(element.toString()).append("',");
}
return "[" + originalJsArrStr + "]";
}
}
| AAChartModel/AAChartCore | app/src/main/java/com/example/anan/AAChartCore/ChartsDemo/chartcomposer/JSFunctionForAAOptionsComposer.java | 3,490 | //禁用点击区块之后出现的半透明遮罩层 | line_comment | zh-cn | package com.example.anan.AAChartCore.ChartsDemo.chartcomposer;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AAChartModel;
import com.github.AAChartModel.AAChartCore.AAChartCreator.AASeriesElement;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartAnimationType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartFontWeightType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartLineDashStyleType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartStackingType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartType;
import com.github.AAChartModel.AAChartCore.AAChartEnum.AAChartVerticalAlignType;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAAnimation;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAChart;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AADataLabels;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAHover;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AALabels;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAOptions;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPlotOptions;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPoint;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAPointEvents;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AASelect;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AASeries;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStates;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAStyle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATitle;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AATooltip;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAXAxis;
import com.github.AAChartModel.AAChartCore.AAOptionsModel.AAYAxis;
import com.github.AAChartModel.AAChartCore.AATools.AAColor;
import com.github.AAChartModel.AAChartCore.AATools.AAGradientColor;
import com.github.AAChartModel.AAChartCore.AATools.AALinearGradientDirection;
import java.util.Map;
public class JSFunctionForAAOptionsComposer {
//https://github.com/AAChartModel/AAChartKit/issues/780
public static AAOptions customDoubleXAxesChart() {
Map<String, Object> gradientColorDic1 = AAGradientColor.linearGradient(
AALinearGradientDirection.ToTop,
"#7052f4",
"#00b0ff"//颜色字符串设置支持十六进制类型和 rgba 类型
);
Map<String, Object> gradientColorDic2 = AAGradientColor.linearGradient(
AALinearGradientDirection.ToTop,
"#EF71FF",
"#4740C8"//颜色字符串设置支持十六进制类型和 rgba 类型
);
AAChart aaChart = new AAChart()
.type(AAChartType.Bar);
AATitle aaTitle = new AATitle()
.text("2015 年德国人口金字塔")
.style(new AAStyle()
.color("#000000")
.fontSize(12.0));
String[] aaCategories = new String[]{"0-4", "5-9", "10-14", "15-19",
"20-24", "25-29", "30-34", "35-39", "40-44",
"45-49", "50-54", "55-59", "60-64", "65-69",
"70-74", "75-79", "80-84", "85-89", "90-94",
"95-99", "100 + "};
AAXAxis aaXAxis1 = new AAXAxis()
.reversed(true)
.categories(aaCategories)
.labels(new AALabels()
.step(1))
;
AAXAxis aaXAxis2 = new AAXAxis()
.reversed(true)
.opposite(true)
.categories(aaCategories)
.linkedTo(0)
.labels(new AALabels()
.step(1));
AAYAxis aaYAxis = new AAYAxis()
.gridLineWidth(0)// Y 轴网格线宽度
.title(new AATitle()
.text(""))//Y 轴标题
.labels(new AALabels()
.formatter("function () {\n" +
" return (Math.abs(this.value) / 1000000) + 'M';\n" +
"}"))
.min(-4000000)
.max(4000000);
AAPlotOptions aaPlotOptions = new AAPlotOptions()
.series(new AASeries()
.animation(new AAAnimation()
.duration(800)
.easing(AAChartAnimationType.Bounce)
)
.stacking(AAChartStackingType.Normal));
AATooltip aaTooltip = new AATooltip()
.enabled(true)
.shared(false)
.formatter("function () {\n" +
" return '<b>' + this.series.name + ', age ' + this.point.category + '</b><br/>' +\n" +
" '人口: ' + Highcharts.numberFormat(Math.abs(this.point.y), 0);\n" +
"}");
AASeriesElement aaSeriesElement1 = new AASeriesElement()
.name("Men")
.color(gradientColorDic1)
.data(new Object[]{-1746181, -1884428, -2089758, -2222362, -2537431, -2507081, -2443179,
-2664537, -3556505, -3680231, -3143062, -2721122, -2229181, -2227768,
-2176300, -1329968, -836804, -354784, -90569, -28367, -3878});
AASeriesElement aaSeriesElement2 = new AASeriesElement()
.name("Women")
.color(gradientColorDic2)
.data(new Object[]{1656154, 1787564, 1981671, 2108575, 2403438, 2366003, 2301402, 2519874,
3360596, 3493473, 3050775, 2759560, 2304444, 2426504, 2568938, 1785638,
1447162, 1005011, 330870, 130632, 21208});
return new AAOptions()
.chart(aaChart)
.title(aaTitle)
.xAxisArray(new AAXAxis[]{aaXAxis1,aaXAxis2})
.yAxis(aaYAxis)
.plotOptions(aaPlotOptions)
.tooltip(aaTooltip)
.series(new Object[]{aaSeriesElement1,aaSeriesElement2});
}
//https://github.com/AAChartModel/AAChartKit/issues/967
public static AAOptions disableColumnChartUnselectEventEffectBySeriesPointEventClickFunction() {
AAChartModel aaChartModel = new AAChartModel()
.chartType(AAChartType.Bar)
.title("Custom Bar Chart select color")
.yAxisReversed(true)
.xAxisReversed(true)
.series(new AASeriesElement[]{
new AASeriesElement()
.name("ElementOne")
.data(new Object[]{211,183,157,133,111,91,73,57,43,31,21,13,7,3})
.allowPointSelect(true)
.states(new AAStates()
.hover(new AAHover()
.color(AAColor.Yellow))
.select(new AASelect()
.color(AAColor.Red))
)
});
AAOptions aaOptions = aaChartModel.aa_toAAOptions();
AAPoint aaPoint = new AAPoint()
.events(new AAPointEvents()
.click("function () {\n" +
" if (this.selected == true) {\n" +
" this.selected = false;\n" +
" }\n" +
" return;\n" +
" }"));
aaOptions.plotOptions.series
.point(aaPoint);
return aaOptions;
}
// Refer to the issue https://github.com/AAChartModel/AAChartKit/issues/589
public static AAOptions customizeEveryDataLabelSinglelyByDataLabelsFormatter() {
AAChartModel aaChartModel = new AAChartModel()
.chartType(AAChartType.Areaspline)//图表类型
.dataLabelsEnabled(true)
.tooltipEnabled(false)
.colorsTheme(new Object[]{AAGradientColor.FizzyPeach})
.markerRadius(0)
.legendEnabled(false)
.categories(new String[]{"美国🇺🇸","欧洲🇪🇺","中国🇨🇳","日本🇯🇵","韩国🇰🇷","越南🇻🇳","中国香港🇭🇰",})
.series(new AASeriesElement[]{
new AASeriesElement()
.data(new Object[]{7.0, 6.9, 2.5, 14.5, 18.2, 21.5, 5.2}),
});
AAOptions aaOptions = aaChartModel.aa_toAAOptions();
aaOptions.yAxis.gridLineDashStyle = AAChartLineDashStyleType.LongDash;//设置Y轴的网格线样式为 AAChartLineDashStyleType.LongDash
String[] unitArr ={"美元", "欧元", "人民币", "日元", "韩元", "越南盾", "港币", };
String unitJSArrStr = javaScriptArrayStringWithJavaArray(unitArr);
String dataLabelsFormatter = String.format("function () {\n" +
" return this.y + %s[this.point.index]; \n" + //单组 series 图表, 获取选中的点的索引是 this.point.index ,多组并且共享提示框,则是this.points[0].index
" }", unitJSArrStr);
AADataLabels aaDatalabels = aaOptions.plotOptions.series.dataLabels;
aaDatalabels
.style(AAStyle.style(AAColor.Red, 10, AAChartFontWeightType.Bold, "1px 1px contrast"))
.formatter(dataLabelsFormatter)
.backgroundColor(AAColor.White)// white color
.borderColor(AAColor.Red)// red color
.borderRadius(1.5)
.borderWidth(1.3)
.x(3).y(-20)
.verticalAlign(AAChartVerticalAlignType.Middle);
return aaOptions;
}
//https://github.com/AAChartModel/AAChartKit-Swift/issues/404
public static AAOptions configureColorfulDataLabelsForPieChart() {
AAOptions aaOptions = new AAOptions()
.title(new AATitle()
.text("Colorful DataLabels For Pie Chart"))
.colors(new Object[]{
"#0c9674", "#7dffc0", "#ff3333", "#facd32", "#ffffa0",
"#EA007B", "#fe117c", "#ffc069", "#06caf4", "#7dffc0"
})
.series(new AASeriesElement[]{
new AASeriesElement()
.type(AAChartType.Pie)
.name("语言热度值")
.innerSize("20%")//内部圆环半径大小占比
.borderWidth(0)//描边的宽度
.allowPointSelect(true)//是否允许在点击数据点标记(扇形图点击选中的块发生位移)
.states(new AAStates()
.hover(new AAHover()
.enabled(false)))//禁用 <SUF>
.dataLabels(new AADataLabels()
.allowOverlap(true)//允许字符重叠
.useHTML(true)
.formatter("function () {\n" +
" const point = this.point;\n" +
" return '<span style=\\\"color: ' + point.color + '\\\">' +\n" +
" point.name + ': ' + point.y + '%</span>';\n" +
" }"))
.data(new Object[][]{
{"Firefox", 3336.2},
{"IE", 26.8},
{"Chrome", 666.8},
{"Safari", 88.5},
{"Opera", 46.0},
{"Others", 223.0},
{"Firefox", 3336.2},
{"IE", 26.8},
{"Chrome", 666.8},
{"Safari", 88.5},
{"Opera", 46.0},
{"Others", 223.0},
})
});
return aaOptions;
}
private static String javaScriptArrayStringWithJavaArray(Object[] javaArray) {
StringBuilder originalJsArrStr = new StringBuilder();
for (Object element : javaArray) {
originalJsArrStr.append("'").append(element.toString()).append("',");
}
return "[" + originalJsArrStr + "]";
}
}
| 0 | 3,273 | 13 | 3,490 | 17 | 3,610 | 11 | 3,490 | 17 | 4,063 | 32 | false | false | false | false | false | true |
38744_12 | package com.aesop.demo.rfcclient.infra.rfc.multitask.multijob.impl;
import com.aesop.demo.rfcclient.infra.rfc.multitask.multijob.MultiStepJob;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* 此类实现了MultiStepJob接口 用于指定线程将要执行的任务,主要逻辑在runNextStep方法中,执行了RFC
*
* @author tttttwtt
*/
@Slf4j
@Service
@NoArgsConstructor
public class StatelessMultiStep implements MultiStepJob {
@Resource
private JCoDestination jCoDestination;
private JCoFunction function;
private int calls;// 调用次数
private int jobID = 0;// 任务编号
private int executedCalls = 0;// 记录调用次数,即任务步骤
private Exception ex = null;// 记录任务执行过程出现的异常
// private int remoteCounter;// 计数结果
public StatelessMultiStep(JCoFunction function, int calls, int jobID) {
this.function = function;
this.calls = calls;
this.jobID = jobID;
}
public boolean isFinished() {
// 如果已经调用完,或者调用过程中出现了异常,表示任务已完成
return executedCalls == calls || ex != null;
}
public String getName() {// 任务名
return "Job ID:" + jobID;
}
// 任务的某一步,究竟有多少步则外界来传递进来的calls变量来控制
public void runNextStep() {
try {
// 注:在调用远程RFC功能函数之前,JCo框架会去调用SessionReferenceProvider的getCurrentSessionReference()方法
// 取得当前任务所对应的远程会话,确保同一任务是在同一远程会话中执行的
function.execute(jCoDestination);
executedCalls++;//记录第几次调用
} catch (JCoException je) {
ex = je;
}
}
public void cleanUp() {// 任务结束后,清除任务
StringBuilder sb = new StringBuilder("任务 ").append(getName()).append(" 结束:");
if (ex != null) {
sb.append("异常结束 ").append(ex.toString());
} else {
// sb.append("成功执行完,计数器值 = ").append(remoteCounter);
sb.append("成功执行完毕! ");
}
log.info(sb.toString());
}
}
| AES0P/SAP-Interface | rfc-client/src/main/java/com/aesop/demo/rfcclient/infra/rfc/multitask/multijob/impl/StatelessMultiStep.java | 630 | // 任务结束后,清除任务 | line_comment | zh-cn | package com.aesop.demo.rfcclient.infra.rfc.multitask.multijob.impl;
import com.aesop.demo.rfcclient.infra.rfc.multitask.multijob.MultiStepJob;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoException;
import com.sap.conn.jco.JCoFunction;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
/**
* 此类实现了MultiStepJob接口 用于指定线程将要执行的任务,主要逻辑在runNextStep方法中,执行了RFC
*
* @author tttttwtt
*/
@Slf4j
@Service
@NoArgsConstructor
public class StatelessMultiStep implements MultiStepJob {
@Resource
private JCoDestination jCoDestination;
private JCoFunction function;
private int calls;// 调用次数
private int jobID = 0;// 任务编号
private int executedCalls = 0;// 记录调用次数,即任务步骤
private Exception ex = null;// 记录任务执行过程出现的异常
// private int remoteCounter;// 计数结果
public StatelessMultiStep(JCoFunction function, int calls, int jobID) {
this.function = function;
this.calls = calls;
this.jobID = jobID;
}
public boolean isFinished() {
// 如果已经调用完,或者调用过程中出现了异常,表示任务已完成
return executedCalls == calls || ex != null;
}
public String getName() {// 任务名
return "Job ID:" + jobID;
}
// 任务的某一步,究竟有多少步则外界来传递进来的calls变量来控制
public void runNextStep() {
try {
// 注:在调用远程RFC功能函数之前,JCo框架会去调用SessionReferenceProvider的getCurrentSessionReference()方法
// 取得当前任务所对应的远程会话,确保同一任务是在同一远程会话中执行的
function.execute(jCoDestination);
executedCalls++;//记录第几次调用
} catch (JCoException je) {
ex = je;
}
}
public void cleanUp() {// 任务 <SUF>
StringBuilder sb = new StringBuilder("任务 ").append(getName()).append(" 结束:");
if (ex != null) {
sb.append("异常结束 ").append(ex.toString());
} else {
// sb.append("成功执行完,计数器值 = ").append(remoteCounter);
sb.append("成功执行完毕! ");
}
log.info(sb.toString());
}
}
| 0 | 575 | 7 | 630 | 9 | 637 | 6 | 630 | 9 | 894 | 14 | false | false | false | false | false | true |
41201_22 | package com.Domain;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* @author Aexlord
* @date 2018年4月23日
* @text 邮件发送系统
*/
public class SendingEmail {
// 发件人的账户和密码
private static String myEmailAccount;
private static String myEmailPassword;
// 发件人的SMTP地址
private static String myEmailSMTPHost;
//获取配置信息
static {
Properties pro = new Properties();
try {
InputStream in = SendingEmail.class.getClassLoader()
.getResourceAsStream("account.properties");
pro.load(in);
} catch (Exception e) {
System.out.println("配置文件读取错误");
}
myEmailAccount = pro.getProperty("myEmailAccount");
myEmailPassword = pro.getProperty("myEmailPassword");
myEmailSMTPHost = pro.getProperty("myEmailSMTPHost");
}
public void sendingEmail(String subject,String content,String receiveMail) throws Exception {
// 1.创建参数配置,用于连接邮件服务器
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用Javamaile的协议规范
props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的smpt服务
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
final String smtpPort = "465"; //由于阿里云禁止了25端口,所以需要修改为465端口,并同时要改为ssl加密传输
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
Session session = Session.getInstance(props);
// session.setDebug(true);
// 3.创建一封邮件
MimeMessage message = creatMimeMessage(session, myEmailAccount, receiveMail,subject,content);
// 4.根据Session获取邮件传输对象
Transport transport = session.getTransport();
// 5.使用邮箱账号和密码链接邮件服务器
transport.connect(myEmailAccount, myEmailPassword);
// 6.发送邮件
transport.sendMessage(message, message.getAllRecipients());
// 7.关闭连接
transport.close();
}
/*
* 创建邮件
*/
private static MimeMessage creatMimeMessage(Session session, String sendMail, String receiveMail
,String subject,String content)
throws Exception {
// 创建一封邮件
MimeMessage message = new MimeMessage(session);
// From 发件人
message.setFrom(new InternetAddress(sendMail, "我的小助手", "UTF-8"));
// TO 收件人
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "主人", "UTF-8"));
// 邮件主题
message.setSubject(subject, "UTF-8");
// 邮件正文
message.setContent(content, "text/html;charset=UTF-8");
// 设置发送时间
message.setSentDate(new Date());
// 保存设置
message.saveChanges();
return message;
}
}
| AEXLORD/StockAssistant | src/com/Domain/SendingEmail.java | 882 | // 设置发送时间
| line_comment | zh-cn | package com.Domain;
import java.io.InputStream;
import java.util.Date;
import java.util.Properties;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* @author Aexlord
* @date 2018年4月23日
* @text 邮件发送系统
*/
public class SendingEmail {
// 发件人的账户和密码
private static String myEmailAccount;
private static String myEmailPassword;
// 发件人的SMTP地址
private static String myEmailSMTPHost;
//获取配置信息
static {
Properties pro = new Properties();
try {
InputStream in = SendingEmail.class.getClassLoader()
.getResourceAsStream("account.properties");
pro.load(in);
} catch (Exception e) {
System.out.println("配置文件读取错误");
}
myEmailAccount = pro.getProperty("myEmailAccount");
myEmailPassword = pro.getProperty("myEmailPassword");
myEmailSMTPHost = pro.getProperty("myEmailSMTPHost");
}
public void sendingEmail(String subject,String content,String receiveMail) throws Exception {
// 1.创建参数配置,用于连接邮件服务器
Properties props = new Properties(); // 参数配置
props.setProperty("mail.transport.protocol", "smtp"); // 使用Javamaile的协议规范
props.setProperty("mail.smtp.host", myEmailSMTPHost); // 发件人的smpt服务
props.setProperty("mail.smtp.auth", "true"); // 需要请求认证
final String smtpPort = "465"; //由于阿里云禁止了25端口,所以需要修改为465端口,并同时要改为ssl加密传输
props.setProperty("mail.smtp.port", smtpPort);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", smtpPort);
Session session = Session.getInstance(props);
// session.setDebug(true);
// 3.创建一封邮件
MimeMessage message = creatMimeMessage(session, myEmailAccount, receiveMail,subject,content);
// 4.根据Session获取邮件传输对象
Transport transport = session.getTransport();
// 5.使用邮箱账号和密码链接邮件服务器
transport.connect(myEmailAccount, myEmailPassword);
// 6.发送邮件
transport.sendMessage(message, message.getAllRecipients());
// 7.关闭连接
transport.close();
}
/*
* 创建邮件
*/
private static MimeMessage creatMimeMessage(Session session, String sendMail, String receiveMail
,String subject,String content)
throws Exception {
// 创建一封邮件
MimeMessage message = new MimeMessage(session);
// From 发件人
message.setFrom(new InternetAddress(sendMail, "我的小助手", "UTF-8"));
// TO 收件人
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveMail, "主人", "UTF-8"));
// 邮件主题
message.setSubject(subject, "UTF-8");
// 邮件正文
message.setContent(content, "text/html;charset=UTF-8");
// 设置 <SUF>
message.setSentDate(new Date());
// 保存设置
message.saveChanges();
return message;
}
}
| 0 | 762 | 5 | 876 | 5 | 869 | 5 | 876 | 5 | 1,158 | 9 | false | false | false | false | false | true |
59077_2 | package com.af.audio;
import android.net.Uri;
public interface IAudioRecordListener {
/**
* 初始化提示视图
*/
void initTipView();
/**
* 设置倒计时提示视图
*
* @param counter 10秒倒计时
*/
void setTimeoutTipView(int counter);
/**
* 设置正在录制提示视图
*/
void setRecordingTipView();
/**
* 设置语音长度太短提示视图
*/
void setAudioShortTipView();
/**
* 设置取消提示视图
*/
void setCancelTipView();
/**
* 销毁提示视图
*/
void destroyTipView();
/**
* 开始录制
* 如果是做IM的话,这里可以发送一个消息,如:对方正在讲话
*/
void onStartRecord();
/**
* 录制结束
*
* @param audioPath 语音文件路径
* @param duration 语音文件时长
*/
void onFinish(Uri audioPath, int duration);
/**
* 分贝改变
*
* @param db 分贝
*/
void onAudioDBChanged(int db);
}
| AFinalStone/AudioRecord | library/src/main/java/com/af/audio/IAudioRecordListener.java | 266 | /**
* 设置正在录制提示视图
*/ | block_comment | zh-cn | package com.af.audio;
import android.net.Uri;
public interface IAudioRecordListener {
/**
* 初始化提示视图
*/
void initTipView();
/**
* 设置倒计时提示视图
*
* @param counter 10秒倒计时
*/
void setTimeoutTipView(int counter);
/**
* 设置正 <SUF>*/
void setRecordingTipView();
/**
* 设置语音长度太短提示视图
*/
void setAudioShortTipView();
/**
* 设置取消提示视图
*/
void setCancelTipView();
/**
* 销毁提示视图
*/
void destroyTipView();
/**
* 开始录制
* 如果是做IM的话,这里可以发送一个消息,如:对方正在讲话
*/
void onStartRecord();
/**
* 录制结束
*
* @param audioPath 语音文件路径
* @param duration 语音文件时长
*/
void onFinish(Uri audioPath, int duration);
/**
* 分贝改变
*
* @param db 分贝
*/
void onAudioDBChanged(int db);
}
| 0 | 263 | 12 | 266 | 11 | 292 | 12 | 266 | 11 | 394 | 18 | false | false | false | false | false | true |
49153_11 | package com.zsc.game.ui.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.stx.xhb.xbanner.XBanner;
import com.zsc.game.R;
import com.zsc.game.base.BaseFragment;
import com.zsc.game.di.component.ActivityComponent;
import com.zsc.game.mvp.model.bean.VideoInfo;
import com.zsc.game.mvp.presenter.FaPresenter;
import com.zsc.game.mvp.view.FaView;
import com.zsc.game.ui.activity.SousuoActivity;
import com.zsc.game.ui.adapter.HomeAdapter;
import com.zsc.game.util.SystemUtil;
import java.util.ArrayList;
import java.util.List;
import butterknife.Unbinder;
/**
* 类的用途:
* <p>
* mac周昇辰
* 2017/12/15 18:33
*/
public class FragmentA extends BaseFragment<FaPresenter> implements FaView, SwipeRefreshLayout.OnRefreshListener {
Unbinder unbinder;
private XBanner mybanner;
private int imageHeight = 50; //设置渐变高度,一般为导航图片高度,自己控制
private XRecyclerView siftXr1;
private SwipeRefreshLayout idSwipe;
private HomeAdapter adapter;
private List<String> list = new ArrayList<>();
private ImageView goback;
private LinearLayout gobackLayout;
private LinearLayout titleBarLayout;
private TextView settv;
private TextView titleBarName;
private RelativeLayout relativeLayout;
private RelativeLayout relativeLayout1;
private TextView textView;
private NetworkChangeReciver network;
@Override
protected int setLayout() {
return R.layout.fragmenta;
}
@Override
protected void processLogic() {
mPresenter.loadata();
/**
* 注册广播,进行监听是否有网络
* */
IntentFilter intentfile=new IntentFilter();
intentfile.addAction("android.net.conn.CONNECTIVITY_CHANGE");
network = new NetworkChangeReciver();
getActivity().registerReceiver(network, intentfile);
}
@Override
protected void initInject(ActivityComponent mainComponent) {
mainComponent.Inject(this);
}
@Override
protected void addLayout() {
relativeLayout1 = findViewById(R.id.relative1);
relativeLayout = findViewById(R.id.relative);
textView = findViewById(R.id.xiexie);
siftXr1 = findViewById(R.id.sift_xr);
titleBarName = findViewById(R.id.title_bar_name);
settv = findViewById(R.id.settv);
titleBarLayout = findViewById(R.id.title_bar_layout);
gobackLayout = findViewById(R.id.gobackLayout);
goback = findViewById(R.id.goback);
idSwipe=findViewById(R.id.id_swipe);
if(!SystemUtil.isNetworkConnected()){
Log.i("www","宝宝");
relativeLayout1.setVisibility(View.GONE);
relativeLayout.setVisibility(View.VISIBLE);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"我点击了哦,宝贝",Toast.LENGTH_SHORT).show();
Log.i("www","宝宝111");
// 跳转到系统的网络设置界面
Intent intent = null;
// 先判断当前系统版本
if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
}
getActivity().startActivity(intent);
}
});
}
View abnv = View.inflate(getActivity(), R.layout.layout_bann, null);
init();
goback.setVisibility(View.GONE);
settv.setVisibility(View.GONE);
mybanner = abnv.findViewById(R.id.mybanner);
/**
* 查找头部相对应的控件
* */
TextView tv = abnv.findViewById(R.id.edit_sou);
titleBarLayout.bringToFront();
siftXr1.addHeaderView(abnv);
siftXr1.addOnScrollListener(new RecyclerView.OnScrollListener() {
private int y = 0;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
y+=dy;
if (y <= 0) {
titleBarName.setText("精选");
titleBarLayout.setBackgroundColor(Color.argb((int) 0,227,29,26));
titleBarName.setTextColor(Color.argb(0, 255, 255, 255));
} else if (y > 0 && y <= imageHeight) {
float scale = (float) y / imageHeight;
float alpha = (255 * scale);
// 只是layout背景透明
titleBarName.setText("精选");
titleBarLayout.setBackgroundColor(Color.argb((int) alpha,227,29,26));
titleBarName.setTextColor(Color.argb((int) alpha, 255, 255, 255));
} else {
titleBarName.setText("精选");
titleBarLayout.setBackgroundColor(Color.argb((int) 255,227,29,26));
titleBarName.setTextColor(Color.argb((int) 225, 255, 255, 255));
}
}
});
idSwipe.setOnRefreshListener(this);
/**
* 点击跳转搜索框
* */
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().startActivity(new Intent(getActivity(), SousuoActivity.class));
}
});
}
/**
* recycleview数据展示
* */
private void getData(final List<VideoInfo.RetBean.ListBean.ChildListBean> jcList) {
siftXr1.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter=new HomeAdapter(getActivity(),jcList);
siftXr1.setAdapter(adapter);
}
/**
* 上拉刷新下拉加载
* */
private void init( ) {
siftXr1.setLoadingListener(new XRecyclerView.LoadingListener() {
@Override
public void onRefresh() {
adapter.notifyDataSetChanged();
siftXr1.refreshComplete();
}
@Override
public void onLoadMore() {
siftXr1.loadMoreComplete();
}
});
}
//重写方法进行展示网络数据
/**
* 网络数据获取更新UI
* */
@Override
public void showToast(VideoInfo msg) {
List<VideoInfo.RetBean.ListBean.ChildListBean> childList = msg.getRet().getList().get(0).getChildList();
final List<String> xbanimg = new ArrayList<>();
for (int i = 0; i < childList.size(); i++) {
if(i!=3){
xbanimg.add(childList.get(i).getPic());
}
}
mybanner.setData(xbanimg, null);
mybanner.setmAutoPalyTime(2500);
mybanner.setmAdapter(new XBanner.XBannerAdapter() {
@Override
public void loadBanner(XBanner banner, View view, int position) {
Glide.with(getActivity()).load(xbanimg.get(position)).into((ImageView) view);
}
});
//获取精彩数据
VideoInfo.RetBean.ListBean listBean = msg.getRet().getList().get(4);
List<VideoInfo.RetBean.ListBean.ChildListBean> jcList = listBean.getChildList();
getData(jcList);
Log.i("ggg",listBean.getTitle());
}
@Override
public void onRefresh() {
idSwipe.setRefreshing(false);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if(unbinder != null){
unbinder.unbind();
}
}
/**
* 广播内部类
* */
class NetworkChangeReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub'
ConnectivityManager connectivityManager=(ConnectivityManager)getActivity().getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isAvailable()) {
Toast.makeText(context, "当前网络正常!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "当前网络处于断网!", Toast.LENGTH_SHORT).show();
Log.i("ttt","我真的很帅");
}
}
}
@Override
public void onDestroy() {
//注销广播
getActivity().unregisterReceiver(network);
super.onDestroy();
}
}
| AGreatTeam/MicroFilm | app/src/main/java/com/zsc/game/ui/fragment/FragmentA.java | 2,334 | //重写方法进行展示网络数据 | line_comment | zh-cn | package com.zsc.game.ui.fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.stx.xhb.xbanner.XBanner;
import com.zsc.game.R;
import com.zsc.game.base.BaseFragment;
import com.zsc.game.di.component.ActivityComponent;
import com.zsc.game.mvp.model.bean.VideoInfo;
import com.zsc.game.mvp.presenter.FaPresenter;
import com.zsc.game.mvp.view.FaView;
import com.zsc.game.ui.activity.SousuoActivity;
import com.zsc.game.ui.adapter.HomeAdapter;
import com.zsc.game.util.SystemUtil;
import java.util.ArrayList;
import java.util.List;
import butterknife.Unbinder;
/**
* 类的用途:
* <p>
* mac周昇辰
* 2017/12/15 18:33
*/
public class FragmentA extends BaseFragment<FaPresenter> implements FaView, SwipeRefreshLayout.OnRefreshListener {
Unbinder unbinder;
private XBanner mybanner;
private int imageHeight = 50; //设置渐变高度,一般为导航图片高度,自己控制
private XRecyclerView siftXr1;
private SwipeRefreshLayout idSwipe;
private HomeAdapter adapter;
private List<String> list = new ArrayList<>();
private ImageView goback;
private LinearLayout gobackLayout;
private LinearLayout titleBarLayout;
private TextView settv;
private TextView titleBarName;
private RelativeLayout relativeLayout;
private RelativeLayout relativeLayout1;
private TextView textView;
private NetworkChangeReciver network;
@Override
protected int setLayout() {
return R.layout.fragmenta;
}
@Override
protected void processLogic() {
mPresenter.loadata();
/**
* 注册广播,进行监听是否有网络
* */
IntentFilter intentfile=new IntentFilter();
intentfile.addAction("android.net.conn.CONNECTIVITY_CHANGE");
network = new NetworkChangeReciver();
getActivity().registerReceiver(network, intentfile);
}
@Override
protected void initInject(ActivityComponent mainComponent) {
mainComponent.Inject(this);
}
@Override
protected void addLayout() {
relativeLayout1 = findViewById(R.id.relative1);
relativeLayout = findViewById(R.id.relative);
textView = findViewById(R.id.xiexie);
siftXr1 = findViewById(R.id.sift_xr);
titleBarName = findViewById(R.id.title_bar_name);
settv = findViewById(R.id.settv);
titleBarLayout = findViewById(R.id.title_bar_layout);
gobackLayout = findViewById(R.id.gobackLayout);
goback = findViewById(R.id.goback);
idSwipe=findViewById(R.id.id_swipe);
if(!SystemUtil.isNetworkConnected()){
Log.i("www","宝宝");
relativeLayout1.setVisibility(View.GONE);
relativeLayout.setVisibility(View.VISIBLE);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"我点击了哦,宝贝",Toast.LENGTH_SHORT).show();
Log.i("www","宝宝111");
// 跳转到系统的网络设置界面
Intent intent = null;
// 先判断当前系统版本
if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
}
getActivity().startActivity(intent);
}
});
}
View abnv = View.inflate(getActivity(), R.layout.layout_bann, null);
init();
goback.setVisibility(View.GONE);
settv.setVisibility(View.GONE);
mybanner = abnv.findViewById(R.id.mybanner);
/**
* 查找头部相对应的控件
* */
TextView tv = abnv.findViewById(R.id.edit_sou);
titleBarLayout.bringToFront();
siftXr1.addHeaderView(abnv);
siftXr1.addOnScrollListener(new RecyclerView.OnScrollListener() {
private int y = 0;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
y+=dy;
if (y <= 0) {
titleBarName.setText("精选");
titleBarLayout.setBackgroundColor(Color.argb((int) 0,227,29,26));
titleBarName.setTextColor(Color.argb(0, 255, 255, 255));
} else if (y > 0 && y <= imageHeight) {
float scale = (float) y / imageHeight;
float alpha = (255 * scale);
// 只是layout背景透明
titleBarName.setText("精选");
titleBarLayout.setBackgroundColor(Color.argb((int) alpha,227,29,26));
titleBarName.setTextColor(Color.argb((int) alpha, 255, 255, 255));
} else {
titleBarName.setText("精选");
titleBarLayout.setBackgroundColor(Color.argb((int) 255,227,29,26));
titleBarName.setTextColor(Color.argb((int) 225, 255, 255, 255));
}
}
});
idSwipe.setOnRefreshListener(this);
/**
* 点击跳转搜索框
* */
tv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().startActivity(new Intent(getActivity(), SousuoActivity.class));
}
});
}
/**
* recycleview数据展示
* */
private void getData(final List<VideoInfo.RetBean.ListBean.ChildListBean> jcList) {
siftXr1.setLayoutManager(new LinearLayoutManager(getActivity()));
adapter=new HomeAdapter(getActivity(),jcList);
siftXr1.setAdapter(adapter);
}
/**
* 上拉刷新下拉加载
* */
private void init( ) {
siftXr1.setLoadingListener(new XRecyclerView.LoadingListener() {
@Override
public void onRefresh() {
adapter.notifyDataSetChanged();
siftXr1.refreshComplete();
}
@Override
public void onLoadMore() {
siftXr1.loadMoreComplete();
}
});
}
//重写 <SUF>
/**
* 网络数据获取更新UI
* */
@Override
public void showToast(VideoInfo msg) {
List<VideoInfo.RetBean.ListBean.ChildListBean> childList = msg.getRet().getList().get(0).getChildList();
final List<String> xbanimg = new ArrayList<>();
for (int i = 0; i < childList.size(); i++) {
if(i!=3){
xbanimg.add(childList.get(i).getPic());
}
}
mybanner.setData(xbanimg, null);
mybanner.setmAutoPalyTime(2500);
mybanner.setmAdapter(new XBanner.XBannerAdapter() {
@Override
public void loadBanner(XBanner banner, View view, int position) {
Glide.with(getActivity()).load(xbanimg.get(position)).into((ImageView) view);
}
});
//获取精彩数据
VideoInfo.RetBean.ListBean listBean = msg.getRet().getList().get(4);
List<VideoInfo.RetBean.ListBean.ChildListBean> jcList = listBean.getChildList();
getData(jcList);
Log.i("ggg",listBean.getTitle());
}
@Override
public void onRefresh() {
idSwipe.setRefreshing(false);
}
@Override
public void onDestroyView() {
super.onDestroyView();
if(unbinder != null){
unbinder.unbind();
}
}
/**
* 广播内部类
* */
class NetworkChangeReciver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub'
ConnectivityManager connectivityManager=(ConnectivityManager)getActivity().getSystemService(context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
if(networkInfo!=null&&networkInfo.isAvailable()) {
Toast.makeText(context, "当前网络正常!", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(context, "当前网络处于断网!", Toast.LENGTH_SHORT).show();
Log.i("ttt","我真的很帅");
}
}
}
@Override
public void onDestroy() {
//注销广播
getActivity().unregisterReceiver(network);
super.onDestroy();
}
}
| 0 | 1,962 | 8 | 2,334 | 8 | 2,442 | 8 | 2,334 | 8 | 2,864 | 15 | false | false | false | false | false | true |
34716_1 | package ch03.sec03;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.corpus.dictionary.NatureDictionaryMaker;
import com.hankcs.hanlp.corpus.document.CorpusLoader;
import com.hankcs.hanlp.corpus.document.sentence.word.IWord;
import com.hankcs.hanlp.dictionary.CoreBiGramTableDictionary;
import com.hankcs.hanlp.dictionary.CoreDictionary;
import com.hankcs.hanlp.seg.Dijkstra.DijkstraSegment;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.Viterbi.ViterbiSegment;
import java.util.List;
import static ch03.MSR.*;
import static tools.Tools.show_subtitle;
public class DemoNgramSegment {
public static void main(String[] args) {
// 第一次执行会报出警告,然后会转换 txt 文件为 bin 文件,后面就不再报错
// 连续执行两次时,第二次使用的是第一次载入的 bin 文件
// 交换以下现场代码的顺序就可以看到区别
show_subtitle("my_cws_model");
trainBigram(MY_CWS_CORPUS_PATH, MY_MODEL_PATH);
loadBigram(MY_MODEL_PATH);
// ToDo: HanLP 更新了版本,增加了 CoreDictionary.reload() 函数,我还没有更新版本,没有测试这个功能。
show_subtitle("msr_ngram");
trainBigram(MSR_TRAIN_PATH, MSR_MODEL_PATH);
loadBigram(MSR_MODEL_PATH);
}
/**
* 训练 bigram 模型
*
* @param corpusPath 语料库路径
* @param modelPath 模型保存路径
*/
public static void trainBigram(String corpusPath, String modelPath) {
List<List<IWord>> sentenceList = CorpusLoader.convert2SentenceList(corpusPath);
for (List<IWord> sentence : sentenceList)
for (IWord word : sentence)
if (word.getLabel() == null) word.setLabel("n"); // 赋予每个单词一个虚拟的名词词性
final NatureDictionaryMaker dictionaryMaker = new NatureDictionaryMaker();
dictionaryMaker.compute(sentenceList);
dictionaryMaker.saveTxtTo(modelPath);
}
public static Segment loadBigram(String modelPath) {
return loadBigram(modelPath, true, true);
}
public static Segment loadBigram(String modelPath, boolean verbose, boolean viterbi) {
// HanLP.Config.enableDebug();
HanLP.Config.CoreDictionaryPath = modelPath + ".txt";
HanLP.Config.BiGramDictionaryPath = modelPath + ".ngram.txt";
if (verbose) {
HanLP.Config.ShowTermNature = false;
System.out.println("「商品」的词频:" + CoreDictionary.getTermFrequency("商品"));
System.out.println("「商品@和」的频次:" + CoreBiGramTableDictionary.getBiFrequency("商品", "和"));
Segment segment = new DijkstraSegment()
.enableAllNamedEntityRecognize(false) // 禁用命名实体识别
.enableCustomDictionary(false); // 禁用用户词典
System.out.println(segment.seg("商品和服务"));
System.out.println(segment.seg("货币和服务"));
}
Segment viterbiSegment = new ViterbiSegment().enableAllNamedEntityRecognize(false).enableCustomDictionary(false);
Segment dijkstraSegment = new DijkstraSegment().enableAllNamedEntityRecognize(false).enableCustomDictionary(false);
return viterbi ? viterbiSegment : dijkstraSegment;
}
}
| AI-code-examples/Hanlp-Books-Examples | src/main/java/ch03/sec03/DemoNgramSegment.java | 898 | // 连续执行两次时,第二次使用的是第一次载入的 bin 文件 | line_comment | zh-cn | package ch03.sec03;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.corpus.dictionary.NatureDictionaryMaker;
import com.hankcs.hanlp.corpus.document.CorpusLoader;
import com.hankcs.hanlp.corpus.document.sentence.word.IWord;
import com.hankcs.hanlp.dictionary.CoreBiGramTableDictionary;
import com.hankcs.hanlp.dictionary.CoreDictionary;
import com.hankcs.hanlp.seg.Dijkstra.DijkstraSegment;
import com.hankcs.hanlp.seg.Segment;
import com.hankcs.hanlp.seg.Viterbi.ViterbiSegment;
import java.util.List;
import static ch03.MSR.*;
import static tools.Tools.show_subtitle;
public class DemoNgramSegment {
public static void main(String[] args) {
// 第一次执行会报出警告,然后会转换 txt 文件为 bin 文件,后面就不再报错
// 连续 <SUF>
// 交换以下现场代码的顺序就可以看到区别
show_subtitle("my_cws_model");
trainBigram(MY_CWS_CORPUS_PATH, MY_MODEL_PATH);
loadBigram(MY_MODEL_PATH);
// ToDo: HanLP 更新了版本,增加了 CoreDictionary.reload() 函数,我还没有更新版本,没有测试这个功能。
show_subtitle("msr_ngram");
trainBigram(MSR_TRAIN_PATH, MSR_MODEL_PATH);
loadBigram(MSR_MODEL_PATH);
}
/**
* 训练 bigram 模型
*
* @param corpusPath 语料库路径
* @param modelPath 模型保存路径
*/
public static void trainBigram(String corpusPath, String modelPath) {
List<List<IWord>> sentenceList = CorpusLoader.convert2SentenceList(corpusPath);
for (List<IWord> sentence : sentenceList)
for (IWord word : sentence)
if (word.getLabel() == null) word.setLabel("n"); // 赋予每个单词一个虚拟的名词词性
final NatureDictionaryMaker dictionaryMaker = new NatureDictionaryMaker();
dictionaryMaker.compute(sentenceList);
dictionaryMaker.saveTxtTo(modelPath);
}
public static Segment loadBigram(String modelPath) {
return loadBigram(modelPath, true, true);
}
public static Segment loadBigram(String modelPath, boolean verbose, boolean viterbi) {
// HanLP.Config.enableDebug();
HanLP.Config.CoreDictionaryPath = modelPath + ".txt";
HanLP.Config.BiGramDictionaryPath = modelPath + ".ngram.txt";
if (verbose) {
HanLP.Config.ShowTermNature = false;
System.out.println("「商品」的词频:" + CoreDictionary.getTermFrequency("商品"));
System.out.println("「商品@和」的频次:" + CoreBiGramTableDictionary.getBiFrequency("商品", "和"));
Segment segment = new DijkstraSegment()
.enableAllNamedEntityRecognize(false) // 禁用命名实体识别
.enableCustomDictionary(false); // 禁用用户词典
System.out.println(segment.seg("商品和服务"));
System.out.println(segment.seg("货币和服务"));
}
Segment viterbiSegment = new ViterbiSegment().enableAllNamedEntityRecognize(false).enableCustomDictionary(false);
Segment dijkstraSegment = new DijkstraSegment().enableAllNamedEntityRecognize(false).enableCustomDictionary(false);
return viterbi ? viterbiSegment : dijkstraSegment;
}
}
| 0 | 783 | 17 | 898 | 20 | 897 | 16 | 898 | 20 | 1,124 | 31 | false | false | false | false | false | true |
23682_3 | package com.tianyi.web.model;
/**
* Created by 雪峰 on 2018/1/3.
*/
public class UserSportsModel {
//运动状态,0未添加,1:零基础,2:有经验,3:经验丰富
private int sportsState;
//运动目的 0,未填写:1:健康,2:康复,3:完美
private int sportsGoal;
//喜欢的运动
private String sportsLiked;
//运动场地 json串
private String sportsFieild;
//运动天数 0:未填写,1:不动,2:1-2,3:3-4,3:5-7
private int sportDay;
//运动小时 0:未填写,1:30分钟,2:30-60,3:60-90,4:90以上
private int sportsHour;
//体重信息0:未填写 ,1:长胖,2:保持,3:不会胖
private int weightInfo;
//体型状态 0:未填写,1:圆润,2:标准,3:苗条
private int shape;
//手腕长度0:未填写 1:有间隙,2:,3:
private int wristLength;
public int getSportsState() {
return sportsState;
}
public void setSportsState(int sportsState) {
this.sportsState = sportsState;
}
public int getSportsGoal() {
return sportsGoal;
}
public void setSportsGoal(int sportsGoal) {
this.sportsGoal = sportsGoal;
}
public String getSportsLiked() {
return sportsLiked;
}
public void setSportsLiked(String sportsLiked) {
this.sportsLiked = sportsLiked;
}
public String getSportsFieild() {
return sportsFieild;
}
public void setSportsFieild(String sportsFieild) {
this.sportsFieild = sportsFieild;
}
public int getSportDay() {
return sportDay;
}
public void setSportDay(int sportDay) {
this.sportDay = sportDay;
}
public int getSportsHour() {
return sportsHour;
}
public void setSportsHour(int sportsHour) {
this.sportsHour = sportsHour;
}
public int getWeightInfo() {
return weightInfo;
}
public void setWeightInfo(int weightInfo) {
this.weightInfo = weightInfo;
}
public int getShape() {
return shape;
}
public void setShape(int shape) {
this.shape = shape;
}
public int getWristLength() {
return wristLength;
}
public void setWristLength(int wristLength) {
this.wristLength = wristLength;
}
}
| AIDOCGroup/Server | src/main/java/com/tianyi/web/model/UserSportsModel.java | 716 | //喜欢的运动 | line_comment | zh-cn | package com.tianyi.web.model;
/**
* Created by 雪峰 on 2018/1/3.
*/
public class UserSportsModel {
//运动状态,0未添加,1:零基础,2:有经验,3:经验丰富
private int sportsState;
//运动目的 0,未填写:1:健康,2:康复,3:完美
private int sportsGoal;
//喜欢 <SUF>
private String sportsLiked;
//运动场地 json串
private String sportsFieild;
//运动天数 0:未填写,1:不动,2:1-2,3:3-4,3:5-7
private int sportDay;
//运动小时 0:未填写,1:30分钟,2:30-60,3:60-90,4:90以上
private int sportsHour;
//体重信息0:未填写 ,1:长胖,2:保持,3:不会胖
private int weightInfo;
//体型状态 0:未填写,1:圆润,2:标准,3:苗条
private int shape;
//手腕长度0:未填写 1:有间隙,2:,3:
private int wristLength;
public int getSportsState() {
return sportsState;
}
public void setSportsState(int sportsState) {
this.sportsState = sportsState;
}
public int getSportsGoal() {
return sportsGoal;
}
public void setSportsGoal(int sportsGoal) {
this.sportsGoal = sportsGoal;
}
public String getSportsLiked() {
return sportsLiked;
}
public void setSportsLiked(String sportsLiked) {
this.sportsLiked = sportsLiked;
}
public String getSportsFieild() {
return sportsFieild;
}
public void setSportsFieild(String sportsFieild) {
this.sportsFieild = sportsFieild;
}
public int getSportDay() {
return sportDay;
}
public void setSportDay(int sportDay) {
this.sportDay = sportDay;
}
public int getSportsHour() {
return sportsHour;
}
public void setSportsHour(int sportsHour) {
this.sportsHour = sportsHour;
}
public int getWeightInfo() {
return weightInfo;
}
public void setWeightInfo(int weightInfo) {
this.weightInfo = weightInfo;
}
public int getShape() {
return shape;
}
public void setShape(int shape) {
this.shape = shape;
}
public int getWristLength() {
return wristLength;
}
public void setWristLength(int wristLength) {
this.wristLength = wristLength;
}
}
| 0 | 625 | 4 | 716 | 6 | 699 | 3 | 716 | 6 | 865 | 8 | false | false | false | false | false | true |
41584_2 | package com.demo.hutool.qr;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import java.awt.*;
import java.io.File;
import java.nio.charset.StandardCharsets;
/**
* <h1>二维码</h1>
*
* <p>
* createDate 2022/03/10 16:08:11
* </p>
*
* @author ALI[ali-k@foxmail.com]
* @since 1.0.0
**/
@Slf4j
public class Main {
private static final String content = "爱上对方过后就哭了啊123456789012345678901234567890";
private static final ErrorCorrectionLevel level = ErrorCorrectionLevel.M;
private static final String path1 = "E:/qr1.png";
private static final String path2 = "E:/qr2.png";
public static void main(String[] args) {
/*生成二维码*/
File file = new File(path1);
// 默认M和UTF-8
QrCodeUtil.generate(content, 300, 300, file);
/*识别二维码*/
String decode = QrCodeUtil.decode(file);
log.info("二维码:" + decode);
/*自定义参数*/
QrConfig config = new QrConfig(300, 300);
// 设置边距,既二维码和背景之间的边距
config.setMargin(1);
// 设置前景色
config.setForeColor(new Color(0x66ccff));
// 设置背景色
config.setBackColor(Color.BLACK);
// 设置二维码中的Logo
config.setImg(file);
// 设置纠错级别
config.setErrorCorrection(level);
// 设置文本编码
config.setCharset(StandardCharsets.UTF_8);
// 生成二维码到文件,也可以到流
QrCodeUtil.generate(content, config, new File(path2));
}
}
| ALI1416/springboot-demo | demo-util/src/main/java/com/demo/hutool/qr/Main.java | 544 | // 默认M和UTF-8 | line_comment | zh-cn | package com.demo.hutool.qr;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import java.awt.*;
import java.io.File;
import java.nio.charset.StandardCharsets;
/**
* <h1>二维码</h1>
*
* <p>
* createDate 2022/03/10 16:08:11
* </p>
*
* @author ALI[ali-k@foxmail.com]
* @since 1.0.0
**/
@Slf4j
public class Main {
private static final String content = "爱上对方过后就哭了啊123456789012345678901234567890";
private static final ErrorCorrectionLevel level = ErrorCorrectionLevel.M;
private static final String path1 = "E:/qr1.png";
private static final String path2 = "E:/qr2.png";
public static void main(String[] args) {
/*生成二维码*/
File file = new File(path1);
// 默认 <SUF>
QrCodeUtil.generate(content, 300, 300, file);
/*识别二维码*/
String decode = QrCodeUtil.decode(file);
log.info("二维码:" + decode);
/*自定义参数*/
QrConfig config = new QrConfig(300, 300);
// 设置边距,既二维码和背景之间的边距
config.setMargin(1);
// 设置前景色
config.setForeColor(new Color(0x66ccff));
// 设置背景色
config.setBackColor(Color.BLACK);
// 设置二维码中的Logo
config.setImg(file);
// 设置纠错级别
config.setErrorCorrection(level);
// 设置文本编码
config.setCharset(StandardCharsets.UTF_8);
// 生成二维码到文件,也可以到流
QrCodeUtil.generate(content, config, new File(path2));
}
}
| 0 | 467 | 7 | 544 | 7 | 539 | 7 | 544 | 7 | 692 | 9 | false | false | false | false | false | true |
23791_5 | package burp;
import burp.application.ApiScanner;
import burp.application.apitypes.ApiEndpoint;
import burp.application.apitypes.ApiType;
import burp.ui.ApiDocumentListTree;
import burp.ui.ExtensionTab;
import burp.utils.CommonUtils;
import burp.utils.Constants;
import burp.utils.UrlScanCount;
import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class PassiveScanner implements IScannerCheck {
private final UrlScanCount scanedUrl = new UrlScanCount();
private final ApiScanner apiScanner;
private int scannedCount = 1;
public PassiveScanner() {
this.apiScanner = new ApiScanner();
}
public ApiScanner getApiScanner() {
return apiScanner;
}
@Override
public List<IScanIssue> doPassiveScan(IHttpRequestResponse httpRequestResponse) {
URL httpRequestURL = BurpExtender.getHelpers().analyzeRequest(httpRequestResponse).getUrl();
String requestUrl = CommonUtils.getUrlWithoutFilename(httpRequestURL);
// 目前检测的查重是将 http://user:pass@host:port/deep/path/filename?query#fragment
// 归一化为 http://host:port/deep/path 后检测是否扫描过, 如果未来有对 query 有相关检测需求, 可以在修改 Common.getUrlWithoutFilename
if (this.scanedUrl.get(requestUrl) <= 0) {
this.scanedUrl.add(requestUrl);
} else {
return null; // 检测到重复, 直接返回
}
ArrayList<ApiType> apiTypes = this.apiScanner.detect(httpRequestResponse, true);
return this.parseApiDocument(apiTypes);
}
public List<IScanIssue> parseApiDocument(ArrayList<ApiType> apiTypes) {
List<IScanIssue> issues = new ArrayList<>();
ExtensionTab extensionTab = BurpExtender.getExtensionTab();
//遍历扫到的ApiType
for (ApiType apiType : apiTypes) {
Map<String, IHttpRequestResponse> apiDocuments = apiType.getApiDocuments();
//遍历ApiType中的接口文档
for (Map.Entry<String, IHttpRequestResponse> entry : apiDocuments.entrySet()) {
ApiDocumentListTree apiDocumentListTree = new ApiDocumentListTree(extensionTab);
ExtensionTab.ApiTableData mainApiData = new ExtensionTab.ApiTableData(false, apiDocumentListTree, String.valueOf(this.scannedCount), entry.getKey(), String.valueOf(BurpExtender.getHelpers().analyzeResponse(entry.getValue().getResponse()).getStatusCode()), apiType.getApiTypeName(), "true", entry.getValue(), CommonUtils.getCurrentDateTime());
ArrayList<ExtensionTab.ApiTableData> subApiData = new ArrayList<>();
mainApiData.setTreeStatus(Constants.TREE_STATUS_COLLAPSE);
apiDocumentListTree.setMainApiData(mainApiData);
apiDocumentListTree.setSubApiData(subApiData);
// 排序
List<ApiEndpoint> apiEndpoints = apiType.parseApiDocument(entry.getValue());
apiEndpoints.sort(Comparator.comparing(ApiEndpoint::getUrl));
// 遍历接口文档中的接口
for (ApiEndpoint apiEndpoint : apiEndpoints) {
IHttpRequestResponse apiParseRequestResponse = apiEndpoint.getHttpRequestResponse();
ExtensionTab.ApiTableData currentData = new ExtensionTab.ApiTableData(true,
apiDocumentListTree,
"",
apiEndpoint.getUrl(),
String.valueOf(BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode()),
apiType.getApiTypeName(),
(BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 200 && BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 405 && BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 500 ? "false" : "true"),
apiParseRequestResponse,
CommonUtils.getCurrentDateTime());
subApiData.add(currentData);
}
extensionTab.add(apiDocumentListTree);
this.scannedCount++;
}
// API 指纹检测 - 报告输出
issues.addAll(apiType.exportIssues());
// API 指纹检测 - 控制台报告输出
BurpExtender.getStdout().print(apiType.exportConsole());
}
return issues;
}
@Override
public List<IScanIssue> doActiveScan(IHttpRequestResponse httpRequestResponse, IScannerInsertionPoint insertionPoint) {
return null;
}
@Override
public int consolidateDuplicateIssues(IScanIssue existingIssue, IScanIssue newIssue) {
if (existingIssue.getIssueName().equals(newIssue.getIssueName())) {
return -1;
} else {
return 0;
}
}
}
| API-Security/APIKit | src/main/java/burp/PassiveScanner.java | 1,146 | // 遍历接口文档中的接口 | line_comment | zh-cn | package burp;
import burp.application.ApiScanner;
import burp.application.apitypes.ApiEndpoint;
import burp.application.apitypes.ApiType;
import burp.ui.ApiDocumentListTree;
import burp.ui.ExtensionTab;
import burp.utils.CommonUtils;
import burp.utils.Constants;
import burp.utils.UrlScanCount;
import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
public class PassiveScanner implements IScannerCheck {
private final UrlScanCount scanedUrl = new UrlScanCount();
private final ApiScanner apiScanner;
private int scannedCount = 1;
public PassiveScanner() {
this.apiScanner = new ApiScanner();
}
public ApiScanner getApiScanner() {
return apiScanner;
}
@Override
public List<IScanIssue> doPassiveScan(IHttpRequestResponse httpRequestResponse) {
URL httpRequestURL = BurpExtender.getHelpers().analyzeRequest(httpRequestResponse).getUrl();
String requestUrl = CommonUtils.getUrlWithoutFilename(httpRequestURL);
// 目前检测的查重是将 http://user:pass@host:port/deep/path/filename?query#fragment
// 归一化为 http://host:port/deep/path 后检测是否扫描过, 如果未来有对 query 有相关检测需求, 可以在修改 Common.getUrlWithoutFilename
if (this.scanedUrl.get(requestUrl) <= 0) {
this.scanedUrl.add(requestUrl);
} else {
return null; // 检测到重复, 直接返回
}
ArrayList<ApiType> apiTypes = this.apiScanner.detect(httpRequestResponse, true);
return this.parseApiDocument(apiTypes);
}
public List<IScanIssue> parseApiDocument(ArrayList<ApiType> apiTypes) {
List<IScanIssue> issues = new ArrayList<>();
ExtensionTab extensionTab = BurpExtender.getExtensionTab();
//遍历扫到的ApiType
for (ApiType apiType : apiTypes) {
Map<String, IHttpRequestResponse> apiDocuments = apiType.getApiDocuments();
//遍历ApiType中的接口文档
for (Map.Entry<String, IHttpRequestResponse> entry : apiDocuments.entrySet()) {
ApiDocumentListTree apiDocumentListTree = new ApiDocumentListTree(extensionTab);
ExtensionTab.ApiTableData mainApiData = new ExtensionTab.ApiTableData(false, apiDocumentListTree, String.valueOf(this.scannedCount), entry.getKey(), String.valueOf(BurpExtender.getHelpers().analyzeResponse(entry.getValue().getResponse()).getStatusCode()), apiType.getApiTypeName(), "true", entry.getValue(), CommonUtils.getCurrentDateTime());
ArrayList<ExtensionTab.ApiTableData> subApiData = new ArrayList<>();
mainApiData.setTreeStatus(Constants.TREE_STATUS_COLLAPSE);
apiDocumentListTree.setMainApiData(mainApiData);
apiDocumentListTree.setSubApiData(subApiData);
// 排序
List<ApiEndpoint> apiEndpoints = apiType.parseApiDocument(entry.getValue());
apiEndpoints.sort(Comparator.comparing(ApiEndpoint::getUrl));
// 遍历 <SUF>
for (ApiEndpoint apiEndpoint : apiEndpoints) {
IHttpRequestResponse apiParseRequestResponse = apiEndpoint.getHttpRequestResponse();
ExtensionTab.ApiTableData currentData = new ExtensionTab.ApiTableData(true,
apiDocumentListTree,
"",
apiEndpoint.getUrl(),
String.valueOf(BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode()),
apiType.getApiTypeName(),
(BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 200 && BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 405 && BurpExtender.getHelpers().analyzeResponse(apiParseRequestResponse.getResponse()).getStatusCode() != 500 ? "false" : "true"),
apiParseRequestResponse,
CommonUtils.getCurrentDateTime());
subApiData.add(currentData);
}
extensionTab.add(apiDocumentListTree);
this.scannedCount++;
}
// API 指纹检测 - 报告输出
issues.addAll(apiType.exportIssues());
// API 指纹检测 - 控制台报告输出
BurpExtender.getStdout().print(apiType.exportConsole());
}
return issues;
}
@Override
public List<IScanIssue> doActiveScan(IHttpRequestResponse httpRequestResponse, IScannerInsertionPoint insertionPoint) {
return null;
}
@Override
public int consolidateDuplicateIssues(IScanIssue existingIssue, IScanIssue newIssue) {
if (existingIssue.getIssueName().equals(newIssue.getIssueName())) {
return -1;
} else {
return 0;
}
}
}
| 0 | 1,036 | 9 | 1,146 | 7 | 1,204 | 7 | 1,146 | 7 | 1,454 | 18 | false | false | false | false | false | true |
18993_7 | /**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.example.qi.tt.permission;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
public class Permissions {
static final String TAG = Permissions.class.getSimpleName();
static final Object TRIGGER = new Object();
@VisibleForTesting
Lazy<PermissionsFragment> mPermissionsFragment;
public Permissions(@NonNull final FragmentActivity activity) {
mPermissionsFragment = getLazySingleton(activity.getSupportFragmentManager());
}
public Permissions(@NonNull final Fragment fragment) {
mPermissionsFragment = getLazySingleton(fragment.getChildFragmentManager());
}
@NonNull
private Lazy<PermissionsFragment> getLazySingleton(@NonNull final FragmentManager fragmentManager) {
return new Lazy<PermissionsFragment>() {
private PermissionsFragment permissionsFragment;
@Override
public synchronized PermissionsFragment get() {
if (permissionsFragment == null) {
permissionsFragment = getPermissionsFragment(fragmentManager);
}
return permissionsFragment;
}
};
}
private PermissionsFragment getPermissionsFragment(@NonNull final FragmentManager fragmentManager) {
PermissionsFragment rxPermissionsFragment = findPermissionsFragment(fragmentManager);
boolean isNewInstance = rxPermissionsFragment == null;
if (isNewInstance) {
rxPermissionsFragment = new PermissionsFragment();
fragmentManager
.beginTransaction()
.add(rxPermissionsFragment, TAG)
.commitNow();
}
return rxPermissionsFragment;
}
private PermissionsFragment findPermissionsFragment(@NonNull final FragmentManager fragmentManager) {
return (PermissionsFragment) fragmentManager.findFragmentByTag(TAG);
}
public void setLogging(boolean logging) {
mPermissionsFragment.get().setLogging(logging);
}
@TargetApi(Build.VERSION_CODES.M)
public Permissions requestEach(FragmentActivity activity, PermissionsFragment.PermissionCallBack callBack, final String... permissions) {
if (callBack!=null){
setCallBack(callBack);
}
// // 检测是否有 1、未获取到2、且不再提示 的权限,如果有 就 不再 请求权限 ,由于 第一次检测是否 弹出 询问 为 false 在此 无法使用
// if (!shouldShowRequestPermissionRationaleImplementation(activity,permissions)){
// mPermissionsFragment.get().onRequestPermissionsResult(new Permission("permission",false,false));
// return this;
// }
List<Permission> list = new ArrayList<>(permissions.length);
List<String> unrequestedPermissions = new ArrayList<>();
// In case of multiple permissions, we create an Observable for each of them.
// At the end, the observables are combined to have a unique response.
for (String permission : permissions) {
mPermissionsFragment.get().log("Requesting permission " + permission);
if (isGranted(permission)) { // 是否 已获取到权限
// Already granted, or not Android M
// Return a granted Permission object.
list.add(new Permission(permission, true, false));
continue;
}else if (isRevoked(permission)) {// 权限 是否已取消
// Revoked by a policy, return a denied Permission object.
list.add(new Permission(permission, false, false));
continue;
} else { //未请求 到权限
unrequestedPermissions.add(permission);
}
}
if (!unrequestedPermissions.isEmpty()) {//申请 未获取到的权限
String[] unrequestedPermissionsArray = unrequestedPermissions.toArray(new String[unrequestedPermissions.size()]);
requestPermissionsFromFragment(unrequestedPermissionsArray);
}else { // 权限 已 全部获取到
mPermissionsFragment.get().onRequestPermissionsResult(new Permission("permission",true,false));
}
return this;
}
@TargetApi(Build.VERSION_CODES.M)
private boolean shouldShowRequestPermissionRationaleImplementation(final Activity activity, final String... permissions) {
for (String p : permissions) {
if (!isGranted(p) && !activity.shouldShowRequestPermissionRationale(p)) {
return false;
}
}
return true;
}
@TargetApi(Build.VERSION_CODES.M)
void requestPermissionsFromFragment(String[] permissions) {
mPermissionsFragment.get().log("requestPermissionsFromFragment " + TextUtils.join(", ", permissions));
mPermissionsFragment.get().requestPermissions(permissions);
}
/**
* Returns true if the permission is already granted.
* <p>
* Always true if SDK < 23.
*/
@SuppressWarnings("WeakerAccess")
public boolean isGranted(String permission) {
return !isMarshmallow() || mPermissionsFragment.get().isGranted(permission);
}
/**
* Returns true if the permission has been revoked by a policy.
* <p>
* Always false if SDK < 23.
*/
@SuppressWarnings("WeakerAccess")
private boolean isRevoked(String permission) {
return isMarshmallow() && mPermissionsFragment.get().isRevoked(permission);
}
private boolean isMarshmallow() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
// private void onRequestPermissionsResult(String permissions[], int[] grantResults) {
// mPermissionsFragment.get().onRequestPermissionsResult(permissions, grantResults, new boolean[permissions.length]);
// }
@FunctionalInterface
public interface Lazy<V> {
V get();
}
/**
* 设置 回调 函数
* @param callBack
*/
public void setCallBack(PermissionsFragment.PermissionCallBack callBack){
mPermissionsFragment.get().setCallBack(callBack);
}
// public void setCallBack(new ){}
// abstract class PermissionCallBack{
// private PermissionsFragment.FragmentPermissionResultCallBack callBack;
// public void accept();
// public void refuse();
// public void noAsk();
// }
}
| AWQi/Permission | permission/Permissions.java | 1,580 | // 是否 已获取到权限
| line_comment | zh-cn | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.example.qi.tt.permission;
import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.annotation.VisibleForTesting;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.List;
public class Permissions {
static final String TAG = Permissions.class.getSimpleName();
static final Object TRIGGER = new Object();
@VisibleForTesting
Lazy<PermissionsFragment> mPermissionsFragment;
public Permissions(@NonNull final FragmentActivity activity) {
mPermissionsFragment = getLazySingleton(activity.getSupportFragmentManager());
}
public Permissions(@NonNull final Fragment fragment) {
mPermissionsFragment = getLazySingleton(fragment.getChildFragmentManager());
}
@NonNull
private Lazy<PermissionsFragment> getLazySingleton(@NonNull final FragmentManager fragmentManager) {
return new Lazy<PermissionsFragment>() {
private PermissionsFragment permissionsFragment;
@Override
public synchronized PermissionsFragment get() {
if (permissionsFragment == null) {
permissionsFragment = getPermissionsFragment(fragmentManager);
}
return permissionsFragment;
}
};
}
private PermissionsFragment getPermissionsFragment(@NonNull final FragmentManager fragmentManager) {
PermissionsFragment rxPermissionsFragment = findPermissionsFragment(fragmentManager);
boolean isNewInstance = rxPermissionsFragment == null;
if (isNewInstance) {
rxPermissionsFragment = new PermissionsFragment();
fragmentManager
.beginTransaction()
.add(rxPermissionsFragment, TAG)
.commitNow();
}
return rxPermissionsFragment;
}
private PermissionsFragment findPermissionsFragment(@NonNull final FragmentManager fragmentManager) {
return (PermissionsFragment) fragmentManager.findFragmentByTag(TAG);
}
public void setLogging(boolean logging) {
mPermissionsFragment.get().setLogging(logging);
}
@TargetApi(Build.VERSION_CODES.M)
public Permissions requestEach(FragmentActivity activity, PermissionsFragment.PermissionCallBack callBack, final String... permissions) {
if (callBack!=null){
setCallBack(callBack);
}
// // 检测是否有 1、未获取到2、且不再提示 的权限,如果有 就 不再 请求权限 ,由于 第一次检测是否 弹出 询问 为 false 在此 无法使用
// if (!shouldShowRequestPermissionRationaleImplementation(activity,permissions)){
// mPermissionsFragment.get().onRequestPermissionsResult(new Permission("permission",false,false));
// return this;
// }
List<Permission> list = new ArrayList<>(permissions.length);
List<String> unrequestedPermissions = new ArrayList<>();
// In case of multiple permissions, we create an Observable for each of them.
// At the end, the observables are combined to have a unique response.
for (String permission : permissions) {
mPermissionsFragment.get().log("Requesting permission " + permission);
if (isGranted(permission)) { // 是否 <SUF>
// Already granted, or not Android M
// Return a granted Permission object.
list.add(new Permission(permission, true, false));
continue;
}else if (isRevoked(permission)) {// 权限 是否已取消
// Revoked by a policy, return a denied Permission object.
list.add(new Permission(permission, false, false));
continue;
} else { //未请求 到权限
unrequestedPermissions.add(permission);
}
}
if (!unrequestedPermissions.isEmpty()) {//申请 未获取到的权限
String[] unrequestedPermissionsArray = unrequestedPermissions.toArray(new String[unrequestedPermissions.size()]);
requestPermissionsFromFragment(unrequestedPermissionsArray);
}else { // 权限 已 全部获取到
mPermissionsFragment.get().onRequestPermissionsResult(new Permission("permission",true,false));
}
return this;
}
@TargetApi(Build.VERSION_CODES.M)
private boolean shouldShowRequestPermissionRationaleImplementation(final Activity activity, final String... permissions) {
for (String p : permissions) {
if (!isGranted(p) && !activity.shouldShowRequestPermissionRationale(p)) {
return false;
}
}
return true;
}
@TargetApi(Build.VERSION_CODES.M)
void requestPermissionsFromFragment(String[] permissions) {
mPermissionsFragment.get().log("requestPermissionsFromFragment " + TextUtils.join(", ", permissions));
mPermissionsFragment.get().requestPermissions(permissions);
}
/**
* Returns true if the permission is already granted.
* <p>
* Always true if SDK < 23.
*/
@SuppressWarnings("WeakerAccess")
public boolean isGranted(String permission) {
return !isMarshmallow() || mPermissionsFragment.get().isGranted(permission);
}
/**
* Returns true if the permission has been revoked by a policy.
* <p>
* Always false if SDK < 23.
*/
@SuppressWarnings("WeakerAccess")
private boolean isRevoked(String permission) {
return isMarshmallow() && mPermissionsFragment.get().isRevoked(permission);
}
private boolean isMarshmallow() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M;
}
// private void onRequestPermissionsResult(String permissions[], int[] grantResults) {
// mPermissionsFragment.get().onRequestPermissionsResult(permissions, grantResults, new boolean[permissions.length]);
// }
@FunctionalInterface
public interface Lazy<V> {
V get();
}
/**
* 设置 回调 函数
* @param callBack
*/
public void setCallBack(PermissionsFragment.PermissionCallBack callBack){
mPermissionsFragment.get().setCallBack(callBack);
}
// public void setCallBack(new ){}
// abstract class PermissionCallBack{
// private PermissionsFragment.FragmentPermissionResultCallBack callBack;
// public void accept();
// public void refuse();
// public void noAsk();
// }
}
| 0 | 1,391 | 8 | 1,557 | 8 | 1,630 | 7 | 1,557 | 8 | 1,944 | 14 | false | false | false | false | false | true |
48684_8 | package com.common.dto;
import java.io.Serializable;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 返回给前端的数据
*/
@Data
@Schema(description = "用户信息DTO")
public class UserDto implements Serializable {
/**
* 用户id
*/
@Schema(description = "用户id", example = "1789548655582642177")
private Long userId;
/**
* 用户名
*/
@Schema(description = "用户名", example = "nick123", minLength = 4)
private String username;
/**
* 昵称
*/
@Schema(description = "用户昵称", example = "尼克", minLength = 6)
private String nickname;
/**
* 用户性别 男 女
*/
@Schema(description = "用户性别", example = "男")
private String gender;
/**
* 用户年龄
*/
@Schema(description = "用户年龄", example = "20", minimum = "0", maximum = "200")
private Integer age;
/**
* 用户头像url
*/
@Schema(description = "用户头像url", example = "https://ischool-bucket.oss-cn-beijing.aliyuncs.com/4c079b7b-0873-4c99-a666-0874a1595811.jpg")
private String userAvatar;
/**
* 用户邮箱
*/
@Schema(description = "用户邮箱", example = "han892577@qq.com")
private String email;
/**
* 用户所属学校名称
*/
@Schema(description = "用户所属学校名称", example = "哈尔滨理工大学")
private String schoolName;
/**
* 用户所属学校简写
*/
@Schema(description = "用户所属学校简写", example = "HRBUST")
private String schoolAbbr;
/**
* 用户获赞总数
*/
@Schema(description = "用户在社区模块的获赞总数", example = "100")
private Integer totalLikes;
/**
* 用户被评论总数
*/
@Schema(description = "用户在社区模块的被评论总数", example = "200")
private Integer totalComments;
/**
* 用户被评论总数
*/
@Schema(description = "用户未读评论的总数", example = "10")
private Integer unReadCommentsCount;
private static final long serialVersionUID = 1L;
} | AZCodingAccount/iSchool | iSchool-Server/iSchool-model/src/main/java/com/common/dto/UserDto.java | 627 | /**
* 用户邮箱
*/ | block_comment | zh-cn | package com.common.dto;
import java.io.Serializable;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 返回给前端的数据
*/
@Data
@Schema(description = "用户信息DTO")
public class UserDto implements Serializable {
/**
* 用户id
*/
@Schema(description = "用户id", example = "1789548655582642177")
private Long userId;
/**
* 用户名
*/
@Schema(description = "用户名", example = "nick123", minLength = 4)
private String username;
/**
* 昵称
*/
@Schema(description = "用户昵称", example = "尼克", minLength = 6)
private String nickname;
/**
* 用户性别 男 女
*/
@Schema(description = "用户性别", example = "男")
private String gender;
/**
* 用户年龄
*/
@Schema(description = "用户年龄", example = "20", minimum = "0", maximum = "200")
private Integer age;
/**
* 用户头像url
*/
@Schema(description = "用户头像url", example = "https://ischool-bucket.oss-cn-beijing.aliyuncs.com/4c079b7b-0873-4c99-a666-0874a1595811.jpg")
private String userAvatar;
/**
* 用户邮 <SUF>*/
@Schema(description = "用户邮箱", example = "han892577@qq.com")
private String email;
/**
* 用户所属学校名称
*/
@Schema(description = "用户所属学校名称", example = "哈尔滨理工大学")
private String schoolName;
/**
* 用户所属学校简写
*/
@Schema(description = "用户所属学校简写", example = "HRBUST")
private String schoolAbbr;
/**
* 用户获赞总数
*/
@Schema(description = "用户在社区模块的获赞总数", example = "100")
private Integer totalLikes;
/**
* 用户被评论总数
*/
@Schema(description = "用户在社区模块的被评论总数", example = "200")
private Integer totalComments;
/**
* 用户被评论总数
*/
@Schema(description = "用户未读评论的总数", example = "10")
private Integer unReadCommentsCount;
private static final long serialVersionUID = 1L;
} | 0 | 563 | 8 | 627 | 7 | 649 | 9 | 627 | 7 | 836 | 16 | false | false | false | false | false | true |
60104_11 | package com.game.user.handler;
import com.game.dispatcher.RequestAnnotation;
import com.game.property.manager.InjectProperty;
import com.game.role.bean.ConcreteRole;
import com.game.role.service.RoleService;
import com.game.user.manager.SessionMap;
import com.game.user.service.Login;
import com.game.user.service.RegisterService;
import com.game.utils.CacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 用户controller
*/
@RequestAnnotation("/user")
@Component
public class UserHandler {
/**
* 登录服务
*/
@Autowired
private Login login;
/**
* 注册服务
*/
@Autowired
private RegisterService registerService;
/**
* 角色服务
*/
@Autowired
private RoleService roleService;
/**
* 注入属性
*/
@Autowired
private InjectProperty injectProperty;
/**
* 用户登录
* @param username 用户名
* @param password 密码
* @return 信息
*/
@RequestAnnotation("/login")
public String login(String username, String password) {
boolean isSuccess = login.login(username,password);
ConcreteRole role = this.getRoleAfterLoginSuccess(username);
if(isSuccess){
//加用户名-角色对象
CacheUtils.getMapUsernameRole().put(username,role);
injectProperty.initProperty(role.getName());
//校验账号
checkAccount(username,role);
return role.getName()+"上线了";
}else{
return role.getName()+"登录失败";
}
}
/**
* 校验账号
* @param username 用户名
* @param role1 角色
*/
private void checkAccount(String username, ConcreteRole role1) {
ConcreteRole role = CacheUtils.getRole(role1.getName());
Map<String, ConcreteRole> sessionMap = SessionMap.getSessionMap();
ConcreteRole localRole = sessionMap.get(username);
if(localRole==null){
sessionMap.put(username,role);
}else{
localRole.getChannel().writeAndFlush("账号重复登录");
logout(username);
}
}
/**
* 用户登出
* @param username 用户名
*/
@RequestAnnotation("/logout")
public void logout(String username) {
//通过username找到map中的role
ConcreteRole role = CacheUtils.getMapUsernameRole().get(username);
//移除角色信息,下线
CacheUtils.getMapUsernameRole().remove(username);
role.getChannel().writeAndFlush(role.getName()+"下线了");
}
/**
* 打印当前场景的所有角色信息
* @param mapName 地图名字
* @return 信息
*/
@RequestAnnotation("/getRoleInfo")
public String getRoleInfo(String mapName) {
//获取当前场景的所有角色信息
Map<String,ConcreteRole> map = CacheUtils.getMapUsernameRole();
return returnRoleInfo(map,mapName);
}
/**
* 返回用户角色信息
* @param map 地图
* @param mapName 地图名字
* @return
*/
private String returnRoleInfo(Map<String, ConcreteRole> map,String mapName) {
Set<String> sets = map.keySet();
StringBuffer sb = new StringBuffer();
Iterator<String> iterator = sets.iterator();
while(iterator.hasNext()){
String name = iterator.next();
String map_name = map.get(name).getConcreteMap().getName();
if (map_name.equals(mapName)){
sb.append(map.get(name).getName()+","+map.get(name).getConcreteMap().getName()+","+map.get(name).getCurHp());
}
if(iterator.hasNext()){
sb.append(";");
}
}
return sb.toString();
}
/**
* 注册
* @param username 用户名
* @param password 密码
* @param ackpassword 确认密码
* @return 信息
*/
@RequestAnnotation("/registerService")
public String registerService(String username,String password,String ackpassword){
boolean isSuccess = registerService.register(username,password,ackpassword);
if(isSuccess){
return returnMsg(username);
}else{
return "注册失败";
}
}
private String returnMsg(String username) {
String msg = "成功注册用户"+username+",请继续注册游戏角色"+";\n"
+"职业描述:\n"
+"1、战士:高物理攻击和高防御,可以使用嘲讽技能,成为BOSS优先攻击的目标\n"
+"2、牧师:带有治疗的职业,强力的治疗技能需要有吟唱时间\n"
+"3、法师:群体法术伤害,可以攻击复数单位\n"
+"4、召唤师:能召唤召唤兽协助战斗。宝宝也能释放技能,而且玩家切换场景的时候自动跟随,玩家收到攻击或主动攻击,宝宝也会释放技能。\n";
return msg;
}
/**
* 成功登录后,获取用户对应人物角色
* @param username 用户名
* @return 角色
*/
public ConcreteRole getRoleAfterLoginSuccess(String username){
int id = login.getUserRoleIdByUsername(username);
//查找role
ConcreteRole role = roleService.getRole(id);
//返回role
return role;
}
} | Aaron-TangCode/MMORPG | src/main/java/com/game/user/handler/UserHandler.java | 1,414 | //移除角色信息,下线 | line_comment | zh-cn | package com.game.user.handler;
import com.game.dispatcher.RequestAnnotation;
import com.game.property.manager.InjectProperty;
import com.game.role.bean.ConcreteRole;
import com.game.role.service.RoleService;
import com.game.user.manager.SessionMap;
import com.game.user.service.Login;
import com.game.user.service.RegisterService;
import com.game.utils.CacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* 用户controller
*/
@RequestAnnotation("/user")
@Component
public class UserHandler {
/**
* 登录服务
*/
@Autowired
private Login login;
/**
* 注册服务
*/
@Autowired
private RegisterService registerService;
/**
* 角色服务
*/
@Autowired
private RoleService roleService;
/**
* 注入属性
*/
@Autowired
private InjectProperty injectProperty;
/**
* 用户登录
* @param username 用户名
* @param password 密码
* @return 信息
*/
@RequestAnnotation("/login")
public String login(String username, String password) {
boolean isSuccess = login.login(username,password);
ConcreteRole role = this.getRoleAfterLoginSuccess(username);
if(isSuccess){
//加用户名-角色对象
CacheUtils.getMapUsernameRole().put(username,role);
injectProperty.initProperty(role.getName());
//校验账号
checkAccount(username,role);
return role.getName()+"上线了";
}else{
return role.getName()+"登录失败";
}
}
/**
* 校验账号
* @param username 用户名
* @param role1 角色
*/
private void checkAccount(String username, ConcreteRole role1) {
ConcreteRole role = CacheUtils.getRole(role1.getName());
Map<String, ConcreteRole> sessionMap = SessionMap.getSessionMap();
ConcreteRole localRole = sessionMap.get(username);
if(localRole==null){
sessionMap.put(username,role);
}else{
localRole.getChannel().writeAndFlush("账号重复登录");
logout(username);
}
}
/**
* 用户登出
* @param username 用户名
*/
@RequestAnnotation("/logout")
public void logout(String username) {
//通过username找到map中的role
ConcreteRole role = CacheUtils.getMapUsernameRole().get(username);
//移除 <SUF>
CacheUtils.getMapUsernameRole().remove(username);
role.getChannel().writeAndFlush(role.getName()+"下线了");
}
/**
* 打印当前场景的所有角色信息
* @param mapName 地图名字
* @return 信息
*/
@RequestAnnotation("/getRoleInfo")
public String getRoleInfo(String mapName) {
//获取当前场景的所有角色信息
Map<String,ConcreteRole> map = CacheUtils.getMapUsernameRole();
return returnRoleInfo(map,mapName);
}
/**
* 返回用户角色信息
* @param map 地图
* @param mapName 地图名字
* @return
*/
private String returnRoleInfo(Map<String, ConcreteRole> map,String mapName) {
Set<String> sets = map.keySet();
StringBuffer sb = new StringBuffer();
Iterator<String> iterator = sets.iterator();
while(iterator.hasNext()){
String name = iterator.next();
String map_name = map.get(name).getConcreteMap().getName();
if (map_name.equals(mapName)){
sb.append(map.get(name).getName()+","+map.get(name).getConcreteMap().getName()+","+map.get(name).getCurHp());
}
if(iterator.hasNext()){
sb.append(";");
}
}
return sb.toString();
}
/**
* 注册
* @param username 用户名
* @param password 密码
* @param ackpassword 确认密码
* @return 信息
*/
@RequestAnnotation("/registerService")
public String registerService(String username,String password,String ackpassword){
boolean isSuccess = registerService.register(username,password,ackpassword);
if(isSuccess){
return returnMsg(username);
}else{
return "注册失败";
}
}
private String returnMsg(String username) {
String msg = "成功注册用户"+username+",请继续注册游戏角色"+";\n"
+"职业描述:\n"
+"1、战士:高物理攻击和高防御,可以使用嘲讽技能,成为BOSS优先攻击的目标\n"
+"2、牧师:带有治疗的职业,强力的治疗技能需要有吟唱时间\n"
+"3、法师:群体法术伤害,可以攻击复数单位\n"
+"4、召唤师:能召唤召唤兽协助战斗。宝宝也能释放技能,而且玩家切换场景的时候自动跟随,玩家收到攻击或主动攻击,宝宝也会释放技能。\n";
return msg;
}
/**
* 成功登录后,获取用户对应人物角色
* @param username 用户名
* @return 角色
*/
public ConcreteRole getRoleAfterLoginSuccess(String username){
int id = login.getUserRoleIdByUsername(username);
//查找role
ConcreteRole role = roleService.getRole(id);
//返回role
return role;
}
} | 0 | 1,159 | 8 | 1,414 | 7 | 1,360 | 7 | 1,414 | 7 | 1,828 | 10 | false | false | false | false | false | true |
46735_1 | package com.shakazxx.couponspeeder.core.wechat;
import android.accessibilityservice.AccessibilityService;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.accessibility.AccessibilityNodeInfo;
import com.shakazxx.couponspeeder.core.base.BaseAction;
import com.shakazxx.couponspeeder.core.party.CommentDict;
import com.shakazxx.couponspeeder.core.util.CommonUtil;
import com.shakazxx.couponspeeder.core.util.GestureUtil;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static com.shakazxx.couponspeeder.core.util.CommonUtil.sleep;
public class WechatScore extends BaseAction {
private BitSet enable = new BitSet(2);
private String password;
private boolean enableCovid9Report;
private boolean enablePartyReport;
public WechatScore(AccessibilityService service, Bundle bundle) {
super(service);
if (bundle == null) {
bundle = new Bundle();
}
enableCovid9Report = bundle.getBoolean("covid9_report", false);
enablePartyReport = bundle.getBoolean("party_report", false);
password = bundle.getString("password");
}
public void sendMessage(String name, String msg, boolean isGroupChat) {
boolean isOnChatPage;
// 个人和群组有不同的进入方式
if (!isGroupChat) {
isOnChatPage = enterInto("通讯录") && enterInto(name) && enterInto("发消息");
} else {
isOnChatPage = enterInto("通讯录") && enterInto("群聊") && enterInto(name);
}
if (isOnChatPage) {
AccessibilityNodeInfo inputNode = CommonUtil.findFirstNodeByClassName(accessibilityService, null, "android.widget.EditText");
CommonUtil.click(inputNode, 1000);
CommonUtil.inputText(inputNode, msg);
if (!CommonUtil.click(CommonUtil.findFirstNodeByText(accessibilityService, "发送", 2000, 500), 1500)) {
// 打开应用后只有第一次可以找到发送按钮,后续只能根据按钮位置点击
GestureUtil.click(accessibilityService, 990, 1230, 1500);
}
}
// 回到首页,恢复状态
goHomePage();
}
public void dailyReport(boolean isTodayPartyStudyDone, String resultLog) {
if (!loginIfNeeded()) {
return;
}
covid9Report();
partyStudyReport(isTodayPartyStudyDone, resultLog);
}
private void covid9Report() {
if (!enableCovid9Report) {
return;
}
SimpleDateFormat sdf = new SimpleDateFormat("M月d日");
String today = sdf.format(new Date());
String msg = "周沐唯体温36.7";
// sendMessage("哥", msg, false);
sendMessage("#2021#中一班", msg, true);
// sendMessage("机器人测试", msg, true);
sendMessage("哥", today + "幼儿园防疫消息已发", false);
enableCovid9Report = false;
}
private void partyStudyReport(boolean isTodayPartyStudyDone, String resultLog) {
if (!enablePartyReport) {
return;
}
SimpleDateFormat sdf = new SimpleDateFormat("M月d日");
String today = sdf.format(new Date());
String msg = String.format("[庆祝][庆祝]%s学习强国完成[烟花][烟花]\n%s", today, resultLog);
if (!isTodayPartyStudyDone) {
msg = String.format("[叹气][叹气]%s学习强国未完成[衰][衰]\n%s", today, resultLog);
}
sendMessage("姐", msg, false);
sendMessage("哥", msg, false);
enablePartyReport = false;
}
private boolean enterInto(String entryName) {
AccessibilityNodeInfo node = CommonUtil.findFirstNodeByText(accessibilityService, entryName, 10000, 1000);
if (node == null) {
return false;
}
if (!CommonUtil.click(node, 1500)) {
Rect rect = new Rect();
node.getBoundsInScreen(rect);
GestureUtil.click(accessibilityService, (rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2, 1500);
}
return true;
}
public void cmbScore() {
// both has finished
if (enable.cardinality() == 1) {
return;
}
if (!loginIfNeeded()) {
return;
}
signScore();
// programScore();
}
public void pbcc() {
if (!loginIfNeeded()) {
return;
}
exchangeMiles();
}
private boolean loginIfNeeded() {
AccessibilityNodeInfo pwd = CommonUtil.findFirstNodeByText(accessibilityService, null, "请填写微信密码");
if (pwd == null) {
return true;
}
CommonUtil.inputText(pwd, password);
// 点击登陆按钮
GestureUtil.click(accessibilityService, 600, 1100, 5000);
// 多等一会儿
return true;
}
private boolean signScore() {
if (enable.get(0)) {
return true;
}
if (CommonUtil.findFirstNodeByText(accessibilityService, "微信", 10000, 1000) == null) {
return false;
}
// 招行信用卡入口
GestureUtil.click(accessibilityService, 600, 300, 1000);
AccessibilityNodeInfo item = CommonUtil.findFirstNodeByText(accessibilityService, null, "领积分");
if (item == null) {
// title always change, let click fixed position
GestureUtil.click(accessibilityService, getWidth() - 10, getHeight() - 10, 5000);
} else {
CommonUtil.click(item, 5000);
}
item = CommonUtil.findFirstNodeByText(accessibilityService, null, "签到有好礼");
if (item == null) {
GestureUtil.click(accessibilityService, getWidth() - 100, getHeight() - 600, 5000);
} else {
if (!CommonUtil.click(item, 5000)) {
// go back to home page
goHomePage();
return false;
}
}
GestureUtil.click(accessibilityService, 500, 300, 1000);
enable.set(0);
// go back to home page
goHomePage();
return true;
}
private boolean programScore() {
if (enable.get(1)) {
return true;
}
GestureUtil.scrollDown(accessibilityService, -600);
sleep(1000);
List<AccessibilityNodeInfo> nodes = CommonUtil.findAllByViewId(accessibilityService, null, "com.tencent.mm:id/ct");
if (nodes.size() == 0) {
return false;
}
boolean find = false;
for (AccessibilityNodeInfo node : nodes) {
if (node.getText() != null && "招行信用卡".equalsIgnoreCase(node.getText().toString())) {
CommonUtil.click(node, 10000);
find = true;
break;
}
}
if (!find) {
return false;
}
GestureUtil.click(accessibilityService, 500, 1300, 10000);
GestureUtil.click(accessibilityService, 500, 600, 1000);
enable.set(1);
goHomePage();
return true;
}
private boolean exchangeMiles() {
// 看下时间是不是10点不到些
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour != 9) {
return false;
}
int minute = calendar.get(Calendar.MINUTE);
if (minute != 59) {
return false;
}
List<AccessibilityNodeInfo> nodes = CommonUtil.findAllByViewId(accessibilityService, null, "com.tencent.mm:id/b4o");
if (nodes.size() == 0) {
return false;
}
boolean find = false;
for (AccessibilityNodeInfo node : nodes) {
if (node.getText() != null && "浦发银行信用卡".equalsIgnoreCase(node.getText().toString())) {
CommonUtil.click(node, 5000);
find = true;
break;
}
}
if (!find) {
return false;
}
AccessibilityNodeInfo item = CommonUtil.findFirstNodeByText(accessibilityService, null, "小浦\uD83C\uDF81福利");
CommonUtil.click(item, 5000);
item = CommonUtil.findFirstNodeByText(accessibilityService, null, "消费红包·全能积分");
if (!CommonUtil.click(item, 5000)) {
return false;
}
GestureUtil.click(accessibilityService, 100, 1300, 3000);
GestureUtil.click(accessibilityService, 10, 300, 3000);
// 等到10点整,再点
while (true) {
calendar = Calendar.getInstance();
calendar.setTime(new Date());
hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour != 10) {
sleep(100);
continue;
}
GestureUtil.click(accessibilityService, 300, 1000, 3000);
break;
}
// go back to home page
goHomePage();
return true;
}
private void goHomePage() {
while (true) {
if (CommonUtil.findFirstNodeByText(accessibilityService, null, "通讯录") != null) {
return;
}
CommonUtil.globalBack(accessibilityService, 1000);
}
}
}
| AaronGeist/CouponSpeeder | app/src/main/java/com/shakazxx/couponspeeder/core/wechat/WechatScore.java | 2,465 | // 打开应用后只有第一次可以找到发送按钮,后续只能根据按钮位置点击 | line_comment | zh-cn | package com.shakazxx.couponspeeder.core.wechat;
import android.accessibilityservice.AccessibilityService;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.accessibility.AccessibilityNodeInfo;
import com.shakazxx.couponspeeder.core.base.BaseAction;
import com.shakazxx.couponspeeder.core.party.CommentDict;
import com.shakazxx.couponspeeder.core.util.CommonUtil;
import com.shakazxx.couponspeeder.core.util.GestureUtil;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static com.shakazxx.couponspeeder.core.util.CommonUtil.sleep;
public class WechatScore extends BaseAction {
private BitSet enable = new BitSet(2);
private String password;
private boolean enableCovid9Report;
private boolean enablePartyReport;
public WechatScore(AccessibilityService service, Bundle bundle) {
super(service);
if (bundle == null) {
bundle = new Bundle();
}
enableCovid9Report = bundle.getBoolean("covid9_report", false);
enablePartyReport = bundle.getBoolean("party_report", false);
password = bundle.getString("password");
}
public void sendMessage(String name, String msg, boolean isGroupChat) {
boolean isOnChatPage;
// 个人和群组有不同的进入方式
if (!isGroupChat) {
isOnChatPage = enterInto("通讯录") && enterInto(name) && enterInto("发消息");
} else {
isOnChatPage = enterInto("通讯录") && enterInto("群聊") && enterInto(name);
}
if (isOnChatPage) {
AccessibilityNodeInfo inputNode = CommonUtil.findFirstNodeByClassName(accessibilityService, null, "android.widget.EditText");
CommonUtil.click(inputNode, 1000);
CommonUtil.inputText(inputNode, msg);
if (!CommonUtil.click(CommonUtil.findFirstNodeByText(accessibilityService, "发送", 2000, 500), 1500)) {
// 打开 <SUF>
GestureUtil.click(accessibilityService, 990, 1230, 1500);
}
}
// 回到首页,恢复状态
goHomePage();
}
public void dailyReport(boolean isTodayPartyStudyDone, String resultLog) {
if (!loginIfNeeded()) {
return;
}
covid9Report();
partyStudyReport(isTodayPartyStudyDone, resultLog);
}
private void covid9Report() {
if (!enableCovid9Report) {
return;
}
SimpleDateFormat sdf = new SimpleDateFormat("M月d日");
String today = sdf.format(new Date());
String msg = "周沐唯体温36.7";
// sendMessage("哥", msg, false);
sendMessage("#2021#中一班", msg, true);
// sendMessage("机器人测试", msg, true);
sendMessage("哥", today + "幼儿园防疫消息已发", false);
enableCovid9Report = false;
}
private void partyStudyReport(boolean isTodayPartyStudyDone, String resultLog) {
if (!enablePartyReport) {
return;
}
SimpleDateFormat sdf = new SimpleDateFormat("M月d日");
String today = sdf.format(new Date());
String msg = String.format("[庆祝][庆祝]%s学习强国完成[烟花][烟花]\n%s", today, resultLog);
if (!isTodayPartyStudyDone) {
msg = String.format("[叹气][叹气]%s学习强国未完成[衰][衰]\n%s", today, resultLog);
}
sendMessage("姐", msg, false);
sendMessage("哥", msg, false);
enablePartyReport = false;
}
private boolean enterInto(String entryName) {
AccessibilityNodeInfo node = CommonUtil.findFirstNodeByText(accessibilityService, entryName, 10000, 1000);
if (node == null) {
return false;
}
if (!CommonUtil.click(node, 1500)) {
Rect rect = new Rect();
node.getBoundsInScreen(rect);
GestureUtil.click(accessibilityService, (rect.left + rect.right) / 2, (rect.top + rect.bottom) / 2, 1500);
}
return true;
}
public void cmbScore() {
// both has finished
if (enable.cardinality() == 1) {
return;
}
if (!loginIfNeeded()) {
return;
}
signScore();
// programScore();
}
public void pbcc() {
if (!loginIfNeeded()) {
return;
}
exchangeMiles();
}
private boolean loginIfNeeded() {
AccessibilityNodeInfo pwd = CommonUtil.findFirstNodeByText(accessibilityService, null, "请填写微信密码");
if (pwd == null) {
return true;
}
CommonUtil.inputText(pwd, password);
// 点击登陆按钮
GestureUtil.click(accessibilityService, 600, 1100, 5000);
// 多等一会儿
return true;
}
private boolean signScore() {
if (enable.get(0)) {
return true;
}
if (CommonUtil.findFirstNodeByText(accessibilityService, "微信", 10000, 1000) == null) {
return false;
}
// 招行信用卡入口
GestureUtil.click(accessibilityService, 600, 300, 1000);
AccessibilityNodeInfo item = CommonUtil.findFirstNodeByText(accessibilityService, null, "领积分");
if (item == null) {
// title always change, let click fixed position
GestureUtil.click(accessibilityService, getWidth() - 10, getHeight() - 10, 5000);
} else {
CommonUtil.click(item, 5000);
}
item = CommonUtil.findFirstNodeByText(accessibilityService, null, "签到有好礼");
if (item == null) {
GestureUtil.click(accessibilityService, getWidth() - 100, getHeight() - 600, 5000);
} else {
if (!CommonUtil.click(item, 5000)) {
// go back to home page
goHomePage();
return false;
}
}
GestureUtil.click(accessibilityService, 500, 300, 1000);
enable.set(0);
// go back to home page
goHomePage();
return true;
}
private boolean programScore() {
if (enable.get(1)) {
return true;
}
GestureUtil.scrollDown(accessibilityService, -600);
sleep(1000);
List<AccessibilityNodeInfo> nodes = CommonUtil.findAllByViewId(accessibilityService, null, "com.tencent.mm:id/ct");
if (nodes.size() == 0) {
return false;
}
boolean find = false;
for (AccessibilityNodeInfo node : nodes) {
if (node.getText() != null && "招行信用卡".equalsIgnoreCase(node.getText().toString())) {
CommonUtil.click(node, 10000);
find = true;
break;
}
}
if (!find) {
return false;
}
GestureUtil.click(accessibilityService, 500, 1300, 10000);
GestureUtil.click(accessibilityService, 500, 600, 1000);
enable.set(1);
goHomePage();
return true;
}
private boolean exchangeMiles() {
// 看下时间是不是10点不到些
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour != 9) {
return false;
}
int minute = calendar.get(Calendar.MINUTE);
if (minute != 59) {
return false;
}
List<AccessibilityNodeInfo> nodes = CommonUtil.findAllByViewId(accessibilityService, null, "com.tencent.mm:id/b4o");
if (nodes.size() == 0) {
return false;
}
boolean find = false;
for (AccessibilityNodeInfo node : nodes) {
if (node.getText() != null && "浦发银行信用卡".equalsIgnoreCase(node.getText().toString())) {
CommonUtil.click(node, 5000);
find = true;
break;
}
}
if (!find) {
return false;
}
AccessibilityNodeInfo item = CommonUtil.findFirstNodeByText(accessibilityService, null, "小浦\uD83C\uDF81福利");
CommonUtil.click(item, 5000);
item = CommonUtil.findFirstNodeByText(accessibilityService, null, "消费红包·全能积分");
if (!CommonUtil.click(item, 5000)) {
return false;
}
GestureUtil.click(accessibilityService, 100, 1300, 3000);
GestureUtil.click(accessibilityService, 10, 300, 3000);
// 等到10点整,再点
while (true) {
calendar = Calendar.getInstance();
calendar.setTime(new Date());
hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour != 10) {
sleep(100);
continue;
}
GestureUtil.click(accessibilityService, 300, 1000, 3000);
break;
}
// go back to home page
goHomePage();
return true;
}
private void goHomePage() {
while (true) {
if (CommonUtil.findFirstNodeByText(accessibilityService, null, "通讯录") != null) {
return;
}
CommonUtil.globalBack(accessibilityService, 1000);
}
}
}
| 0 | 2,232 | 19 | 2,465 | 20 | 2,574 | 17 | 2,465 | 20 | 3,045 | 41 | false | false | false | false | false | true |
18572_19 | //import java.util.logging.Handler;
//
///**
// * 完SyncTask的start方法,要求
// * 1,SyncTask的派生类的run方法抛到Handler所属的线程执行。
// * 2,SyncTask派生类的执行线程等待返回,除非等待的超时timeout
// * 3,如果timeout或出错,则返回默认值defultRet
// */
//public class wm {
// public abstract class SyncTask<R> {
// protected abstract R run();
// private R result;
// private byte[] lock = new byte[0];
// private boolean notified = false;
// private Runnable task = new Runnable() {
// @Override
// public void run() {
// R ret = SyncTask.this.run();
// synchronized (lock) {
// result = ret;
// lock.notify();
// notified = true;
// }
// }
// };
//
// /***
// * 将任务抛到其他线程,同步等待其返回结果
// * @param timeout 超过指定时间则直接返回ms
// * @param defaultRet 默认返回值,即超时后或出错的返回值
// * @param handler 执行线程handler
// * @return
// */
// public R start(final long timeout, final R defaultRet, Handler handler) {
//
// }
// }
//
//}
| AceXIE/lintcode | src/main/java/wm.java | 341 | // * 将任务抛到其他线程,同步等待其返回结果 | line_comment | zh-cn | //import java.util.logging.Handler;
//
///**
// * 完SyncTask的start方法,要求
// * 1,SyncTask的派生类的run方法抛到Handler所属的线程执行。
// * 2,SyncTask派生类的执行线程等待返回,除非等待的超时timeout
// * 3,如果timeout或出错,则返回默认值defultRet
// */
//public class wm {
// public abstract class SyncTask<R> {
// protected abstract R run();
// private R result;
// private byte[] lock = new byte[0];
// private boolean notified = false;
// private Runnable task = new Runnable() {
// @Override
// public void run() {
// R ret = SyncTask.this.run();
// synchronized (lock) {
// result = ret;
// lock.notify();
// notified = true;
// }
// }
// };
//
// /***
// * 将任 <SUF>
// * @param timeout 超过指定时间则直接返回ms
// * @param defaultRet 默认返回值,即超时后或出错的返回值
// * @param handler 执行线程handler
// * @return
// */
// public R start(final long timeout, final R defaultRet, Handler handler) {
//
// }
// }
//
//}
| 0 | 312 | 17 | 341 | 15 | 333 | 15 | 341 | 15 | 415 | 29 | false | false | false | false | false | true |
66221_2 | public class Object01{
public static void main (String[]args) {
String name1="黄冰棒";
String name2="黄文强";
int age1=28;
int age2=23;
String stydy1="不爱学习";
String study2="大师";
//单独变量解决 不利于数据管理,数组解决问题
String[]name3={"黄冰棒","28岁","不爱学习"};
man man1=new man();
man1.name="黄冰棒";
man1.age=28;
man1.study="不爱学习";
man man2=new man();
man2.name="黄文强";
man2.age=20;
man2.study="爱睡觉";
System.out.println("第一个人的信息"+man1.name+" "+man1.age+" "+man1.study);
System.out.println("第二个人的信息"+man2.name+" "+man2.age+" "+man2.study);
}
}//实例化一个人
//定义1个类型
class man {
String name;
int age;
String study;
} | Achilles0622/Achilles | java/Object01.java | 280 | //定义1个类型 | line_comment | zh-cn | public class Object01{
public static void main (String[]args) {
String name1="黄冰棒";
String name2="黄文强";
int age1=28;
int age2=23;
String stydy1="不爱学习";
String study2="大师";
//单独变量解决 不利于数据管理,数组解决问题
String[]name3={"黄冰棒","28岁","不爱学习"};
man man1=new man();
man1.name="黄冰棒";
man1.age=28;
man1.study="不爱学习";
man man2=new man();
man2.name="黄文强";
man2.age=20;
man2.study="爱睡觉";
System.out.println("第一个人的信息"+man1.name+" "+man1.age+" "+man1.study);
System.out.println("第二个人的信息"+man2.name+" "+man2.age+" "+man2.study);
}
}//实例化一个人
//定义 <SUF>
class man {
String name;
int age;
String study;
} | 0 | 235 | 5 | 280 | 5 | 304 | 5 | 280 | 5 | 384 | 7 | false | false | false | false | false | true |
30375_30 | /*
//加了flag以保持后台运行不退出,还没经过测试,(上一版本能用,如果出问题需要恢复上一版本,修改项参看所收藏的相关网页)
//2019.12.19增加悬浮窗权限判断:https://blog.csdn.net/qq_27885521/article/details/101510088
//2021.3.2 要添加在“最近应用列表”隐藏的功能。(搞定,并去掉了遮盖整个recent界面的功能)
*/
package guard.anti_phoneaddiction;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class Guardian extends AppCompatActivity {
public int endTime=0;
public int startTime=0;
EditText startTimeText,endTimeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.guardian);
//enableDeviceAdmin();
//判断无障碍服务是否已经打开,没打开则进入无障碍设置界面
if (!isAccessibilitySettingsOn(this)) {
Toast.makeText(this, "请授权打开无障碍服务", Toast.LENGTH_LONG);
Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
this.startActivity(intent);
}
//在启动服务之前,需要先判断一下当前是否允许开启悬浮窗
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Toast.makeText(this, "当前无开启悬浮窗权限,请授权", Toast.LENGTH_LONG);
startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
}
//启动后台监控服务,用于监控是否按了recent键
this.startService(new Intent(this, Anti_PhoneAddictionService.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//加了flag以保持后台运行不退出,还没经过测试,(上一版本能用,如果出问题需要恢复上一版本,修改项参看所收藏的相关网页)
//不断循环启动应用锁
// int i=0;
// while(i<=20){
// try {
// Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.lxq.applocker");
// startActivity(LaunchIntent);
// //Thread.sleep(10);
// // 按Home键
//// Intent intent = new Intent(Intent.ACTION_MAIN);
//// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//// intent.addCategory(Intent.CATEGORY_HOME);
//// startActivity(intent);
// i++;
// Thread.sleep(300);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
//用按钮启动应用锁
// Button startLock =(Button)findViewById(R.id.StartLock);
// startLock.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.lxq.applocker");
// startActivity(LaunchIntent);
// }
// });
startTimeText=findViewById(R.id.startTime);
endTimeText=findViewById(R.id.endTime);
}
public void onClick(View v) {
//点击设置后把时间传送给后台服务
Anti_PhoneAddictionService.startTime_user=Integer.parseInt(startTimeText.getText().toString());
Anti_PhoneAddictionService.endTime_user=Integer.parseInt(endTimeText.getText().toString());
Toast.makeText(this,"已设置禁止使用手机的时间为"+startTime+" 至 "+ endTime,Toast.LENGTH_LONG);
// return true;
}
private void enableDeviceAdmin() {
ComponentName deviceAdmin = new ComponentName(this, DeviceAdmin.class);
DevicePolicyManager mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
// First of all, to access anything you must be device owner
if (mDpm.isDeviceOwnerApp(getPackageName())) {
// If not device admin, ask to become one
if (!mDpm.isAdminActive(deviceAdmin) &&
mDpm.isDeviceOwnerApp(getPackageName())) {
//Log.v(TAG, "Not device admin. Asking device owner to become one.");
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"You need to be a device admin to enable device admin.");
startActivity(intent);
}
// Device owner and admin : enter device admin
else if (Build.VERSION.SDK_INT >= 21) {
mDpm.setLockTaskPackages(deviceAdmin, new String[]{
getPackageName(), // PUT OTHER PACKAGE NAMES HERE! /
});
startLockTask();
}
}
}
private boolean isAccessibilitySettingsOn(Context mContext) {
int accessibilityEnabled = 0;
final String service = getPackageName() + "/" + Anti_PhoneAddictionService.class.getCanonicalName();
try {
accessibilityEnabled = Settings.Secure.getInt(
mContext.getApplicationContext().getContentResolver(),
Settings.Secure.ACCESSIBILITY_ENABLED);
// Log.v(TAG, "accessibilityEnabled = " + accessibilityEnabled);
} catch (Settings.SettingNotFoundException e) {
// Log.e(TAG, "Error finding setting, default accessibility to not found: "
// + e.getMessage());
}
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
if (accessibilityEnabled == 1) {
// Log.v(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------");
String settingValue = Settings.Secure.getString(
mContext.getApplicationContext().getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
mStringColonSplitter.setString(settingValue);
while (mStringColonSplitter.hasNext()) {
String accessibilityService = mStringColonSplitter.next();
// Log.v(TAG, "-------------- > accessibilityService :: " + accessibilityService + " " + service);
if (accessibilityService.equalsIgnoreCase(service)) {
// Log.v(TAG, "We've found the correct setting - accessibility is switched on!");
return true;
}
}
}
} else {
// Log.v(TAG, "***ACCESSIBILITY IS DISABLED***");
}
return false;
}
}
| ActionWind/Anti-PhoneAddiction | app/src/main/java/guard/anti_phoneaddiction/Guardian.java | 1,703 | //点击设置后把时间传送给后台服务 | line_comment | zh-cn | /*
//加了flag以保持后台运行不退出,还没经过测试,(上一版本能用,如果出问题需要恢复上一版本,修改项参看所收藏的相关网页)
//2019.12.19增加悬浮窗权限判断:https://blog.csdn.net/qq_27885521/article/details/101510088
//2021.3.2 要添加在“最近应用列表”隐藏的功能。(搞定,并去掉了遮盖整个recent界面的功能)
*/
package guard.anti_phoneaddiction;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class Guardian extends AppCompatActivity {
public int endTime=0;
public int startTime=0;
EditText startTimeText,endTimeText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.guardian);
//enableDeviceAdmin();
//判断无障碍服务是否已经打开,没打开则进入无障碍设置界面
if (!isAccessibilitySettingsOn(this)) {
Toast.makeText(this, "请授权打开无障碍服务", Toast.LENGTH_LONG);
Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
this.startActivity(intent);
}
//在启动服务之前,需要先判断一下当前是否允许开启悬浮窗
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Toast.makeText(this, "当前无开启悬浮窗权限,请授权", Toast.LENGTH_LONG);
startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
}
//启动后台监控服务,用于监控是否按了recent键
this.startService(new Intent(this, Anti_PhoneAddictionService.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
//加了flag以保持后台运行不退出,还没经过测试,(上一版本能用,如果出问题需要恢复上一版本,修改项参看所收藏的相关网页)
//不断循环启动应用锁
// int i=0;
// while(i<=20){
// try {
// Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.lxq.applocker");
// startActivity(LaunchIntent);
// //Thread.sleep(10);
// // 按Home键
//// Intent intent = new Intent(Intent.ACTION_MAIN);
//// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//// intent.addCategory(Intent.CATEGORY_HOME);
//// startActivity(intent);
// i++;
// Thread.sleep(300);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
//用按钮启动应用锁
// Button startLock =(Button)findViewById(R.id.StartLock);
// startLock.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.lxq.applocker");
// startActivity(LaunchIntent);
// }
// });
startTimeText=findViewById(R.id.startTime);
endTimeText=findViewById(R.id.endTime);
}
public void onClick(View v) {
//点击 <SUF>
Anti_PhoneAddictionService.startTime_user=Integer.parseInt(startTimeText.getText().toString());
Anti_PhoneAddictionService.endTime_user=Integer.parseInt(endTimeText.getText().toString());
Toast.makeText(this,"已设置禁止使用手机的时间为"+startTime+" 至 "+ endTime,Toast.LENGTH_LONG);
// return true;
}
private void enableDeviceAdmin() {
ComponentName deviceAdmin = new ComponentName(this, DeviceAdmin.class);
DevicePolicyManager mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
// First of all, to access anything you must be device owner
if (mDpm.isDeviceOwnerApp(getPackageName())) {
// If not device admin, ask to become one
if (!mDpm.isAdminActive(deviceAdmin) &&
mDpm.isDeviceOwnerApp(getPackageName())) {
//Log.v(TAG, "Not device admin. Asking device owner to become one.");
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"You need to be a device admin to enable device admin.");
startActivity(intent);
}
// Device owner and admin : enter device admin
else if (Build.VERSION.SDK_INT >= 21) {
mDpm.setLockTaskPackages(deviceAdmin, new String[]{
getPackageName(), // PUT OTHER PACKAGE NAMES HERE! /
});
startLockTask();
}
}
}
private boolean isAccessibilitySettingsOn(Context mContext) {
int accessibilityEnabled = 0;
final String service = getPackageName() + "/" + Anti_PhoneAddictionService.class.getCanonicalName();
try {
accessibilityEnabled = Settings.Secure.getInt(
mContext.getApplicationContext().getContentResolver(),
Settings.Secure.ACCESSIBILITY_ENABLED);
// Log.v(TAG, "accessibilityEnabled = " + accessibilityEnabled);
} catch (Settings.SettingNotFoundException e) {
// Log.e(TAG, "Error finding setting, default accessibility to not found: "
// + e.getMessage());
}
TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');
if (accessibilityEnabled == 1) {
// Log.v(TAG, "***ACCESSIBILITY IS ENABLED*** -----------------");
String settingValue = Settings.Secure.getString(
mContext.getApplicationContext().getContentResolver(),
Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
if (settingValue != null) {
mStringColonSplitter.setString(settingValue);
while (mStringColonSplitter.hasNext()) {
String accessibilityService = mStringColonSplitter.next();
// Log.v(TAG, "-------------- > accessibilityService :: " + accessibilityService + " " + service);
if (accessibilityService.equalsIgnoreCase(service)) {
// Log.v(TAG, "We've found the correct setting - accessibility is switched on!");
return true;
}
}
}
} else {
// Log.v(TAG, "***ACCESSIBILITY IS DISABLED***");
}
return false;
}
}
| 0 | 1,399 | 10 | 1,703 | 11 | 1,711 | 10 | 1,703 | 11 | 2,144 | 18 | false | false | false | false | false | true |
32332_1 | package com.management.model.ov.resultsetting;
/**
* @program: management
* @description: 项目的类别
* @author: ggmr
* @create: 2018-12-17 23:49
*/
public class ConstCorrespond {
//这个第一个为空是有说法的,请勿删除
public final static String[] PROJECT_TYPE = {
"",
"经济管理类",
"人文哲学类",
"计算科学类",
"生物化学类"
};
public final static String[] APPLICAN_TYPE = {
"",
"本科生",
"研究生",
"博士生",
"研究员",
"教授"
};
public final static String[] reviewPhrase = {
"",
"业务员审核阶段",
"评审专家审核阶段",
"会评阶段",
"领导审核阶段",
"项目申请审核通过",
"项目申请审核失败",
"待提交任务书阶段",
"任务书审核阶段",
};
public final static String downloadAddress = "http://118.25.130.89:8081/api/file/download?fileAddress=";
public final static String[] PROJECT_PROGRESS = {
"",
"立项",
"中期报告阶段",
"结题报告审核阶段",
"项目结项",
"结题报告审核失败"
};
public final static String[] USER_AUTHORIZATION = {
"",
"ROLE_USER",
"ROLE_ADMIN",
"ROLE_EXPERT",
"ROLE_LEADER",
"ROLE_SUPERADMIN"
};
public final static String[] USER_IDENTITY = {
"",
"用户",
"业务员",
"专家",
"领导",
"系统管理员"
};
public final static int MIDDLE_PROGRESS = 2;
public final static int FINAL_PROGRESS = 3;
public final static int FINISH_PROGRESS_FAILED = 5;
public final static int FINISH_PROJECT = 4;
public static final String TOKEN_HEAD = "Bearer ";
}
| Actooors/ProjectManagement_Service | src/main/java/com/management/model/ov/resultsetting/ConstCorrespond.java | 496 | //这个第一个为空是有说法的,请勿删除 | line_comment | zh-cn | package com.management.model.ov.resultsetting;
/**
* @program: management
* @description: 项目的类别
* @author: ggmr
* @create: 2018-12-17 23:49
*/
public class ConstCorrespond {
//这个 <SUF>
public final static String[] PROJECT_TYPE = {
"",
"经济管理类",
"人文哲学类",
"计算科学类",
"生物化学类"
};
public final static String[] APPLICAN_TYPE = {
"",
"本科生",
"研究生",
"博士生",
"研究员",
"教授"
};
public final static String[] reviewPhrase = {
"",
"业务员审核阶段",
"评审专家审核阶段",
"会评阶段",
"领导审核阶段",
"项目申请审核通过",
"项目申请审核失败",
"待提交任务书阶段",
"任务书审核阶段",
};
public final static String downloadAddress = "http://118.25.130.89:8081/api/file/download?fileAddress=";
public final static String[] PROJECT_PROGRESS = {
"",
"立项",
"中期报告阶段",
"结题报告审核阶段",
"项目结项",
"结题报告审核失败"
};
public final static String[] USER_AUTHORIZATION = {
"",
"ROLE_USER",
"ROLE_ADMIN",
"ROLE_EXPERT",
"ROLE_LEADER",
"ROLE_SUPERADMIN"
};
public final static String[] USER_IDENTITY = {
"",
"用户",
"业务员",
"专家",
"领导",
"系统管理员"
};
public final static int MIDDLE_PROGRESS = 2;
public final static int FINAL_PROGRESS = 3;
public final static int FINISH_PROGRESS_FAILED = 5;
public final static int FINISH_PROJECT = 4;
public static final String TOKEN_HEAD = "Bearer ";
}
| 0 | 438 | 10 | 496 | 14 | 520 | 11 | 496 | 14 | 727 | 20 | false | false | false | false | false | true |
20719_2 | import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
/**
* main
*
* @author Acyco
* @create 2019-04-11 15:25
*/
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("JavaFX");
primaryStage.getIcons().add(new Image("/img/logo.jpg"));//设置图标
primaryStage.setWidth(300);//设置窗口宽度
primaryStage.setHeight(300);//设置窗口高度
// primaryStage.setIconified(true); //设置最小化
// primaryStage.setMaximized(true); //设置最大化
// primaryStage.close(); // 关闭窗口
// primaryStage.setResizable(false); // 设置 不可以改变窗口的大小
primaryStage.setWidth(500);
primaryStage.setHeight(500);
// primaryStage.setMaxWidth(800);
// primaryStage.setMaxHeight(800);
//
// primaryStage.setMinWidth(300);
// primaryStage.setMinHeight(300);
// getWidth() getHeight() 前面没有设置 一定要放到 放在show()后面
// System.out.println("宽度: "+primaryStage.getWidth());
// System.out.println("高度: "+primaryStage.getHeight());
primaryStage.heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("当前高度"+newValue);
}
});
primaryStage.widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("当前宽度"+newValue);
}
});
primaryStage.setFullScreen(true); //设置全屏 设置Scene
primaryStage.setScene(new Scene(new Group()));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| Acyco/JavaFX | Stage/src/Main.java | 592 | //设置窗口宽度 | line_comment | zh-cn | import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.image.Image;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
/**
* main
*
* @author Acyco
* @create 2019-04-11 15:25
*/
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("JavaFX");
primaryStage.getIcons().add(new Image("/img/logo.jpg"));//设置图标
primaryStage.setWidth(300);//设置 <SUF>
primaryStage.setHeight(300);//设置窗口高度
// primaryStage.setIconified(true); //设置最小化
// primaryStage.setMaximized(true); //设置最大化
// primaryStage.close(); // 关闭窗口
// primaryStage.setResizable(false); // 设置 不可以改变窗口的大小
primaryStage.setWidth(500);
primaryStage.setHeight(500);
// primaryStage.setMaxWidth(800);
// primaryStage.setMaxHeight(800);
//
// primaryStage.setMinWidth(300);
// primaryStage.setMinHeight(300);
// getWidth() getHeight() 前面没有设置 一定要放到 放在show()后面
// System.out.println("宽度: "+primaryStage.getWidth());
// System.out.println("高度: "+primaryStage.getHeight());
primaryStage.heightProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("当前高度"+newValue);
}
});
primaryStage.widthProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
System.out.println("当前宽度"+newValue);
}
});
primaryStage.setFullScreen(true); //设置全屏 设置Scene
primaryStage.setScene(new Scene(new Group()));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| 0 | 476 | 4 | 592 | 4 | 580 | 4 | 592 | 4 | 705 | 11 | false | false | false | false | false | true |
5392_18 | package basic.tree;
//因为一旦有符合的值就会立即返回,那么这个递归函数就会回溯这样的话,有的话立即结束,不会再次判断,所以就是四个结构(不正确)
//上面是线性的思路,这时的结构是回溯性质的非线性的要转换思路,从长驱直入转化到懂得用temp来保存,完成非线性的任务来实现
//也就是说递归要开发思路到非线性的,其特点就是用temp
//这样多分叉的结构需要用一个临时变量存起来,这是很重要的,考虑不够完全
//注意在韩老师的思路中是指要在Node中核心代码,在Tree中封装代码
//和我写的结构是不一样的
public class TraverseDemo {
public static void main(String[] args){
Tree tree = new Tree();
System.out.println(tree.delete(tree.getRoot(),18));
tree.Traverse("pre");
//System.out.println(basic.tree.preSearch(basic.tree.getRoot(),2));
}
}
//和链表的数据结构是一个样的,结点的定义是一个类,含有基本的逻辑关系
//数据结构的是一个类,对应的具体的唯一标识这个数据结构的结构就是上面的一个类
//这样的思路最好,就是有一个结点类,还有一个具体的数据结构类,也就是树类
class Tree{
//没事,没有一下子想出来没事
Node root;//对象就是指向该类对应开辟内存的部分的指针,root == null那么就是空树
public Tree(){
//先赋值获得堆内存,可以先不给后面的结点获取值
root= new Node(0);//覆盖掉了
root.left = new Node(1);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
}
//前序遍历
public void Traverse(String flag){
switch (flag){
case "pre" : preTraverse(root); break;
case "infix" :infixTraverse(root); break;
case "post" :postTraverse(root); break;
}
}
//前序遍历
public void preTraverse(Node node){
System.out.println(node.id);
if(node.left != null){
preTraverse(node.left);
}
if(node.right != null){
preTraverse(node.right);
}
}
//前序查找 -- 传的时候是root但是没办法再递归的方法体内体现出来
public Node preSearch(Node node,int id){
//如果在一个子树里面没有的话始终会传回一个null所以这样的思路是不对的,总需要一个变量存起来,逻辑就能变化
//之前的逻辑是无论遍历哪一个子树,只要没有找到总会返回null,并且在当前状态就结束递归了,说明我对递归的思路还没有把握透彻
//但是就是慢慢来,这个东西记住了,必须是这样的逻辑应当是若树中没有对应的结点,就应该全部遍历一遍,显然没有给后面一个机会
//若要给后面一个机会就是如果左子树不为空的话,那么说明找到了,如果为空的话就没找到,必须要都遍历一边
if(node.id == id){
return node;
}
Node res = null;
if(node.left != null){
res = preSearch(node.left,id);
}
if (res!= null){
return res;
}
if(node.right != null){
res = preSearch(node.right,id);
}
return res;
}
//中序遍历
public void infixTraverse(Node node){
if(node.left != null){
infixTraverse(node.left);
}
System.out.println(node.id);
if(node.right != null){
infixTraverse(node.right);
}
}
public Node infixSearch(Node node,int id){
Node res = null;
if(node.left != null){
res = infixSearch(node.left,id);
}
if( res !=null){
return res;
}
if(node.id == id){
return node;
}
if(node.right != null){
res = infixSearch(node.right,id);
}
return res;
}
//后序遍历
//同时也可以在一个树类里面进行遍历也就是this.left.preorder
//1.韩老师那个思路最好是在一个树里面来遍历就是在一个树类里面来遍历
//然后每个对象既是一个结点又是一棵树也就是Tree left, Tree right这样也可以,那这样的话写在树里面就可以自己调用自己了
//2.第二个就是还是按照之前的数据结构的思路,树类里面封装着方法,然后结点分别有不同的左右
//这样的实现思路就是只需要在树结构内部定义一个根节点就好,但是此时由于递归的特性需要再封装一个类,否则就应该去把头节点传进去
//其实这些不重要主要是思想或者是利用一个静态方法也可以 -- 最后这个比较好一点
//涉及到多分叉的查找应有temp的思想
public void postTraverse(Node node){
if(node.left != null){
postTraverse(node.left);
}
if(node.right != null){
postTraverse(node.right);
}
System.out.println(node.id);
}
public Node postSearch(Node node,int id){
Node res = null;
if(node.left != null){
res = postSearch(node.left,id);
}
if( res != null){
return res;
}
if(node.right != null){
res = postSearch(node.right,id);
}
if( res != null){
return res;
}
if(node.id == id){
return node;
}
return res;
}
public boolean delete(Node node,int id){//和递归的思想是一样的,但是实现方式真的是不一样
//id是唯一的
//在树这一章中非线性结构比较需要缓存变量
//思路就是如果找到对应的结点就删除,比如说要删除左右节点,需要先判断左右结点是否为空
//如果不判断的话,会出现空指针异常,整体思路不变还是递归遍历删除
//其实就是前序删除
if(node.left != null && node.left.id == id){
node.left = null;
return true;
}
if(node.right != null && node.right.id == id){
node.right = null;
return true;
}
//如果该结点都没有的话,这时才应该往下遍历
if(node.left != null && delete(node.left,id)){
return true;
}
if(node.right !=null && delete(node.right,id)){
return true;
}
return false;
}
public Node getRoot(){
return root;
}
}
class Node{
int id;
char ch = '0';
Node left;
Node right;
int leftType;
int rightType;
Node pre;
public Node( int id){
this.id = id;//这个赋值也能错也是够可以的
}
public Node( int id,char ch){
this.id = id;
this.ch = ch;
}
public String toString(){
return id+"";
}
}
//常见的思想是交给结点自身去递归查找,应该注意的一个点就是多分叉的结构应当是有temp的变量先存
//着这个东西最后都遍历结束再null | AdamZHC/DAlgorithm | src/basic/tree/TraverseDemo.java | 1,857 | //之前的逻辑是无论遍历哪一个子树,只要没有找到总会返回null,并且在当前状态就结束递归了,说明我对递归的思路还没有把握透彻 | line_comment | zh-cn | package basic.tree;
//因为一旦有符合的值就会立即返回,那么这个递归函数就会回溯这样的话,有的话立即结束,不会再次判断,所以就是四个结构(不正确)
//上面是线性的思路,这时的结构是回溯性质的非线性的要转换思路,从长驱直入转化到懂得用temp来保存,完成非线性的任务来实现
//也就是说递归要开发思路到非线性的,其特点就是用temp
//这样多分叉的结构需要用一个临时变量存起来,这是很重要的,考虑不够完全
//注意在韩老师的思路中是指要在Node中核心代码,在Tree中封装代码
//和我写的结构是不一样的
public class TraverseDemo {
public static void main(String[] args){
Tree tree = new Tree();
System.out.println(tree.delete(tree.getRoot(),18));
tree.Traverse("pre");
//System.out.println(basic.tree.preSearch(basic.tree.getRoot(),2));
}
}
//和链表的数据结构是一个样的,结点的定义是一个类,含有基本的逻辑关系
//数据结构的是一个类,对应的具体的唯一标识这个数据结构的结构就是上面的一个类
//这样的思路最好,就是有一个结点类,还有一个具体的数据结构类,也就是树类
class Tree{
//没事,没有一下子想出来没事
Node root;//对象就是指向该类对应开辟内存的部分的指针,root == null那么就是空树
public Tree(){
//先赋值获得堆内存,可以先不给后面的结点获取值
root= new Node(0);//覆盖掉了
root.left = new Node(1);
root.right = new Node(2);
root.left.left = new Node(3);
root.left.right = new Node(4);
root.right.left = new Node(5);
root.right.right = new Node(6);
}
//前序遍历
public void Traverse(String flag){
switch (flag){
case "pre" : preTraverse(root); break;
case "infix" :infixTraverse(root); break;
case "post" :postTraverse(root); break;
}
}
//前序遍历
public void preTraverse(Node node){
System.out.println(node.id);
if(node.left != null){
preTraverse(node.left);
}
if(node.right != null){
preTraverse(node.right);
}
}
//前序查找 -- 传的时候是root但是没办法再递归的方法体内体现出来
public Node preSearch(Node node,int id){
//如果在一个子树里面没有的话始终会传回一个null所以这样的思路是不对的,总需要一个变量存起来,逻辑就能变化
//之前 <SUF>
//但是就是慢慢来,这个东西记住了,必须是这样的逻辑应当是若树中没有对应的结点,就应该全部遍历一遍,显然没有给后面一个机会
//若要给后面一个机会就是如果左子树不为空的话,那么说明找到了,如果为空的话就没找到,必须要都遍历一边
if(node.id == id){
return node;
}
Node res = null;
if(node.left != null){
res = preSearch(node.left,id);
}
if (res!= null){
return res;
}
if(node.right != null){
res = preSearch(node.right,id);
}
return res;
}
//中序遍历
public void infixTraverse(Node node){
if(node.left != null){
infixTraverse(node.left);
}
System.out.println(node.id);
if(node.right != null){
infixTraverse(node.right);
}
}
public Node infixSearch(Node node,int id){
Node res = null;
if(node.left != null){
res = infixSearch(node.left,id);
}
if( res !=null){
return res;
}
if(node.id == id){
return node;
}
if(node.right != null){
res = infixSearch(node.right,id);
}
return res;
}
//后序遍历
//同时也可以在一个树类里面进行遍历也就是this.left.preorder
//1.韩老师那个思路最好是在一个树里面来遍历就是在一个树类里面来遍历
//然后每个对象既是一个结点又是一棵树也就是Tree left, Tree right这样也可以,那这样的话写在树里面就可以自己调用自己了
//2.第二个就是还是按照之前的数据结构的思路,树类里面封装着方法,然后结点分别有不同的左右
//这样的实现思路就是只需要在树结构内部定义一个根节点就好,但是此时由于递归的特性需要再封装一个类,否则就应该去把头节点传进去
//其实这些不重要主要是思想或者是利用一个静态方法也可以 -- 最后这个比较好一点
//涉及到多分叉的查找应有temp的思想
public void postTraverse(Node node){
if(node.left != null){
postTraverse(node.left);
}
if(node.right != null){
postTraverse(node.right);
}
System.out.println(node.id);
}
public Node postSearch(Node node,int id){
Node res = null;
if(node.left != null){
res = postSearch(node.left,id);
}
if( res != null){
return res;
}
if(node.right != null){
res = postSearch(node.right,id);
}
if( res != null){
return res;
}
if(node.id == id){
return node;
}
return res;
}
public boolean delete(Node node,int id){//和递归的思想是一样的,但是实现方式真的是不一样
//id是唯一的
//在树这一章中非线性结构比较需要缓存变量
//思路就是如果找到对应的结点就删除,比如说要删除左右节点,需要先判断左右结点是否为空
//如果不判断的话,会出现空指针异常,整体思路不变还是递归遍历删除
//其实就是前序删除
if(node.left != null && node.left.id == id){
node.left = null;
return true;
}
if(node.right != null && node.right.id == id){
node.right = null;
return true;
}
//如果该结点都没有的话,这时才应该往下遍历
if(node.left != null && delete(node.left,id)){
return true;
}
if(node.right !=null && delete(node.right,id)){
return true;
}
return false;
}
public Node getRoot(){
return root;
}
}
class Node{
int id;
char ch = '0';
Node left;
Node right;
int leftType;
int rightType;
Node pre;
public Node( int id){
this.id = id;//这个赋值也能错也是够可以的
}
public Node( int id,char ch){
this.id = id;
this.ch = ch;
}
public String toString(){
return id+"";
}
}
//常见的思想是交给结点自身去递归查找,应该注意的一个点就是多分叉的结构应当是有temp的变量先存
//着这个东西最后都遍历结束再null | 0 | 1,617 | 38 | 1,857 | 48 | 1,856 | 36 | 1,857 | 48 | 2,657 | 97 | false | false | false | false | false | true |
66404_8 | package com.gin.pixiv.response.body.user;
import lombok.Getter;
import lombok.Setter;
/**
* 用户完整信息字段
* @author : ginstone
* @version : v1.0.0
* @since : 2023/3/30 09:57
*/
@Getter
@Setter
public class UserInfoBodyFullData {
/**
* 是否可以私信
*/
Boolean canSendMessage;
/**
* 个人简介(备注)
*/
String comment;
/**
* 个人简介(备注) HTML格式
*/
String commentHtml;
/**
* 是否回关
*/
Boolean followedBack;
/**
* ta关注的人数
*/
Integer following;
/**
* 所属地区
*/
Region region;
/**
* 其他社交媒体
*/
Social social;
/**
* 个人主页
*/
String webpage;
/**
* 创作环境
*/
WorkSpace workspace;
@Getter
@Setter
static class Region {
String name;
/**
* 地方行政区域
*/
String prefecture;
String privacyLevel;
String region;
}
/**
* 其他社交媒体
*/
@Getter
@Setter
static class Social {
SocialUrl pawoo;
SocialUrl twitter;
}
@Getter
@Setter
static class SocialUrl {
String url;
}
@Getter
@Setter
static class WorkSpace {
/**
* 椅子
*/
String userWorkspaceChair;
/**
* 桌面大小
*/
String userWorkspaceDesk;
/**
* 桌面物品
*/
String userWorkspaceDesktop;
/**
* 显示器
*/
String userWorkspaceMonitor;
/**
* 操作系统
*/
String userWorkspacePc;
/**
* 数位板
*/
String userWorkspaceTablet;
/**
* 软件
*/
String userWorkspaceTool;
}
}
| AgMonk/pixiv-utils | src/main/java/com/gin/pixiv/response/body/user/UserInfoBodyFullData.java | 460 | /**
* 个人主页
*/ | block_comment | zh-cn | package com.gin.pixiv.response.body.user;
import lombok.Getter;
import lombok.Setter;
/**
* 用户完整信息字段
* @author : ginstone
* @version : v1.0.0
* @since : 2023/3/30 09:57
*/
@Getter
@Setter
public class UserInfoBodyFullData {
/**
* 是否可以私信
*/
Boolean canSendMessage;
/**
* 个人简介(备注)
*/
String comment;
/**
* 个人简介(备注) HTML格式
*/
String commentHtml;
/**
* 是否回关
*/
Boolean followedBack;
/**
* ta关注的人数
*/
Integer following;
/**
* 所属地区
*/
Region region;
/**
* 其他社交媒体
*/
Social social;
/**
* 个人主 <SUF>*/
String webpage;
/**
* 创作环境
*/
WorkSpace workspace;
@Getter
@Setter
static class Region {
String name;
/**
* 地方行政区域
*/
String prefecture;
String privacyLevel;
String region;
}
/**
* 其他社交媒体
*/
@Getter
@Setter
static class Social {
SocialUrl pawoo;
SocialUrl twitter;
}
@Getter
@Setter
static class SocialUrl {
String url;
}
@Getter
@Setter
static class WorkSpace {
/**
* 椅子
*/
String userWorkspaceChair;
/**
* 桌面大小
*/
String userWorkspaceDesk;
/**
* 桌面物品
*/
String userWorkspaceDesktop;
/**
* 显示器
*/
String userWorkspaceMonitor;
/**
* 操作系统
*/
String userWorkspacePc;
/**
* 数位板
*/
String userWorkspaceTablet;
/**
* 软件
*/
String userWorkspaceTool;
}
}
| 0 | 459 | 9 | 460 | 9 | 517 | 9 | 460 | 9 | 640 | 12 | false | false | false | false | false | true |
61987_8 | package com.dstz.form.generator;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dstz.base.api.exception.BusinessException;
import com.dstz.base.core.util.StringUtil;
import com.dstz.base.core.util.ThreadMapUtil;
import com.dstz.bus.api.constant.BusColumnCtrlType;
import com.dstz.bus.api.constant.BusTableRelType;
import com.dstz.bus.api.model.IBusTableRel;
import com.dstz.bus.api.model.IBusinessColumn;
/**
* 自定义表单控件生成器<br>
* input select radio dic 等等的生成<br>
* @author jeff
*/
@Component
public class MobileFormElementGenerator extends AbsFormElementGenerator{
public String getColumn(IBusinessColumn column,IBusTableRel relation) {
if("1".equals("1")) {
return super.getColumn(column, relation);
}
BusColumnCtrlType columnType = BusColumnCtrlType.getByKey(column.getCtrl().getType());
String boCode = relation.getBusObj().getKey();
ThreadMapUtil.put("boCode", boCode);
ThreadMapUtil.put("relation", relation);
return getColumnOnetext(column);
}
private void handleVModel(Element element,IBusinessColumn column) {
String boCode = (String) ThreadMapUtil.get("boCode");
IBusTableRel relation = (IBusTableRel) ThreadMapUtil.get("relation");
//如果是多行子表
if(relation.getType().equals(BusTableRelType.ONE_TO_MANY.getKey())) {
element.attr("v-model",column.getTable().getKey() + "." + column.getKey());
return ;
}
element.attr("v-model",getScopePath(relation)+ "." + column.getKey());
//添加上 placeholder 的支持
String configStr = column.getCtrl().getConfig();
if (StringUtil.isEmpty(configStr)) {
return;
}
JSONObject config = JSON.parseObject(configStr);
Boolean placeholder = config.getBoolean("placeholder");
if(placeholder == null || !placeholder )return ;
element.attr("placeholder", config.getString("placeholderText"));
}
protected String getColumnOnetext(IBusinessColumn column) {
Element element = getElement("input").attr("type", "text").addClass("weui-input");
handleVModel(element, column);
handlePermission(element, column);
handleValidateRules(element, column);
return element.toString();
}
//<ab-date v-model="data.kjcs.sr" format="YYYY-MM-DD HH:mm:ss" ab-validate="{"date":true}" desc="生日" v-ab-permission="permission.kjcs.cskj.sr"></ab-date>
protected String getColumnDate(IBusinessColumn column) {
Element element = getElement("ab-date");
handleVModel(element, column);
handleValidateRules(element, column);
handlePermission(element, column);
element.attr(":ab-permission", getPermissionPath(column));
String configStr = column.getCtrl().getConfig();
if(StringUtil.isEmpty(configStr)) {
throw new BusinessException(String.format("表【%s】日期字段 【%s】解析失败,配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
String format = JSON.parseObject(configStr).getString("format");
//yyyy-MM-dd HH:mm:ss pc 移动端为:YYYY-MM-DD HH:mm
element.attr("format",format.replace("yyyy", "YYYY").replace("dd", "DD").replace(":ss", ""));
return element.toString();
}
protected String getColumnDic(IBusinessColumn column) {
Element element = getElement("ab-dict").attr("type", "text").addClass("input-div");
handleVModel(element, column);
handleValidateRules(element, column);
handlePermission(element, column);
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("key")) {
throw new BusinessException(String.format("表【%s】数据字典 字段【%s】解析失败,alias 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
element.attr("dict-key", config.getString("key"));
return element.toString();
}
protected String getColumnIdentity(IBusinessColumn column) {
Element element = getElement("input").attr("type", "text").addClass("weui-input");
handleVModel(element, column);
handlePermission(element, column);
handleValidateRules(element, column);
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("alias")) {
throw new BusinessException(String.format("表【%s】流水号 字段【%s】解析失败,alias 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
element.attr("ab-serial-no", config.getString("alias"));
return element.toString();
}
protected String getColumnMultitext(IBusinessColumn column) {
Element element = getElement("textarea").attr("type", "text").addClass("weui-textarea");
handleVModel(element, column);
handlePermission(element, column);
handleValidateRules(element, column);
return element.toString();
}
/**
* <ab-checkbox v-model="data.kjcs.ah" v-ab-permission="permission.kjcs.cskj.ah" v-ab-validate="{}" desc="爱好">
<div slot-scope="scope">
<label class=" checkbox-inline"><input type="checkbox" name="testttt" v-model="scope.tempData.currentValue" value="y"/>羽毛器</label>
<label class=" checkbox-inline"><input name="testttt" type="checkbox" v-model="scope.tempData.currentValue" value="l"/>篮球</label>
<label class=" checkbox-inline"><input type="checkbox" name="testttt" v-model="scope.tempData.currentValue" value="s"/>游泳</label>
</div>
</ab-checkbox>
*/
protected String getColumnCheckBox(IBusinessColumn column) {
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("options")) {
throw new BusinessException(String.format("表【%s】CheckBox 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
Element checkbox = getElement("ab-checkbox");
handleVModel(checkbox, column);
handleValidateRules(checkbox, column);
handlePermission(checkbox,column);
Element template = checkbox.appendElement("div").attr("slot-scope", "scope");
JSONArray options = config.getJSONArray("options");
for (int i = 0; i < options.size(); i++) {
JSONObject option = options.getJSONObject(i);
Element element = template.appendElement("label").addClass("checkbox-inline");
Element child = element.appendElement("input").attr("type", "checkbox");
child.attr("v-model", "scope.tempData.currentValue");
child.attr("value", option.getString("key"));
child.attr("name",String.format("%s-%s-%s",(String) ThreadMapUtil.get("boCode"), column.getTable().getKey(),column.getName()));
handlePermission(child,column);
element.appendText(option.getString("txt"));
}
return checkbox.toString();
}
protected String getColumnRadio(IBusinessColumn column) {
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("options")) {
throw new BusinessException(String.format("表【%s】Radio 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
Element permissionElement = getElement("div");
JSONArray options = config.getJSONArray("options");
for (int i = 0; i < options.size(); i++) {
JSONObject option = options.getJSONObject(i);
Element label = permissionElement.appendElement("label").addClass("radio-inline");
Element child = label.appendElement("input").attr("type", "radio");
handleVModel(child, column);
child.attr("v-ab-permission", getPermissionPath(column));
handleValidateRules(child, column);
child.attr("value", option.getString("key"));
label.appendText(option.getString("txt"));
}
return permissionElement.toString();
}
protected String getColumnSelect(IBusinessColumn column,Boolean isMultiple) {
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("options")) {
throw new BusinessException(String.format("表【%s】Select 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
Element permissionElement = getElement("select").addClass("weui-input");
handleVModel(permissionElement, column);
permissionElement.attr("v-ab-permission",getPermissionPath(column));
handleValidateRules(permissionElement, column);
if(isMultiple) {
permissionElement.attr("multiple", "true");
}
Element select = permissionElement.appendElement("option");
select.attr("value", "");
select.text("请选择");
JSONArray options = config.getJSONArray("options");
for (int i = 0; i < options.size(); i++) {
JSONObject option = options.getJSONObject(i);
Element element = permissionElement.appendElement("option");
element.attr("value", option.getString("key"));
element.text(option.getString("txt"));
}
return permissionElement.toString();
}
/**
* <pre>
* <ab-upload v-model="files" v-bind:permission="xxx">
* <a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary fa fa-upload">上传</a>
* </ab-upload>
* </pre>
*/
protected String getColumnFile(IBusinessColumn column) {
Element element = getElement("ab-upload").attr("v-bind:permission", getPermissionPath(column));
handleVModel(element, column);
element.append("<a href=\"javascript:;\" class=\"weui-btn weui-btn_mini weui-btn_primary fa fa-upload\">"+column.getComment()+"</a>");
return element.toString();
}
// id="boCode-tableKey" ab-basic-permission="boCode.table.tableKey" ...
public String getSubAttrs(IBusTableRel rel) {
StringBuilder sb = new StringBuilder();
sb.append( " id="+"\""+ rel.getBusObj().getKey()+"-"+rel.getTableKey()+"\" ");
//一对多的三层情况下弹框展示
if(rel.getType().equals(BusTableRelType.ONE_TO_MANY.getKey())
&& !rel.getParent().getType().equals(BusTableRelType.MAIN.getKey())) {
sb.append(" v-transfer-dom ");
sb.append(" v-if=\"subTempData."+ rel.getTableKey() +"List\" ");
}
sb.append(" table-key=\""+rel.getTableKey()+"\" ");
return sb.toString() ;
}
protected void handlePermission(Element element,IBusinessColumn column) {
element.attr("v-ab-permission", getPermissionPath(column));
}
protected void handleValidateRules(Element element,IBusinessColumn column) {
super.handleValidateRules(element, column);
element.attr("v-ab-validate", element.attr("ab-validate"));
element.removeAttr("ab-validate");
}
@Override
public String getGeneratorName() {
return "mobileGenerator";
}
}
| AgileBPM/agile-bpm-basic | bus-form/form/form-core/src/main/java/com/dstz/form/generator/MobileFormElementGenerator.java | 3,013 | //一对多的三层情况下弹框展示 | line_comment | zh-cn | package com.dstz.form.generator;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dstz.base.api.exception.BusinessException;
import com.dstz.base.core.util.StringUtil;
import com.dstz.base.core.util.ThreadMapUtil;
import com.dstz.bus.api.constant.BusColumnCtrlType;
import com.dstz.bus.api.constant.BusTableRelType;
import com.dstz.bus.api.model.IBusTableRel;
import com.dstz.bus.api.model.IBusinessColumn;
/**
* 自定义表单控件生成器<br>
* input select radio dic 等等的生成<br>
* @author jeff
*/
@Component
public class MobileFormElementGenerator extends AbsFormElementGenerator{
public String getColumn(IBusinessColumn column,IBusTableRel relation) {
if("1".equals("1")) {
return super.getColumn(column, relation);
}
BusColumnCtrlType columnType = BusColumnCtrlType.getByKey(column.getCtrl().getType());
String boCode = relation.getBusObj().getKey();
ThreadMapUtil.put("boCode", boCode);
ThreadMapUtil.put("relation", relation);
return getColumnOnetext(column);
}
private void handleVModel(Element element,IBusinessColumn column) {
String boCode = (String) ThreadMapUtil.get("boCode");
IBusTableRel relation = (IBusTableRel) ThreadMapUtil.get("relation");
//如果是多行子表
if(relation.getType().equals(BusTableRelType.ONE_TO_MANY.getKey())) {
element.attr("v-model",column.getTable().getKey() + "." + column.getKey());
return ;
}
element.attr("v-model",getScopePath(relation)+ "." + column.getKey());
//添加上 placeholder 的支持
String configStr = column.getCtrl().getConfig();
if (StringUtil.isEmpty(configStr)) {
return;
}
JSONObject config = JSON.parseObject(configStr);
Boolean placeholder = config.getBoolean("placeholder");
if(placeholder == null || !placeholder )return ;
element.attr("placeholder", config.getString("placeholderText"));
}
protected String getColumnOnetext(IBusinessColumn column) {
Element element = getElement("input").attr("type", "text").addClass("weui-input");
handleVModel(element, column);
handlePermission(element, column);
handleValidateRules(element, column);
return element.toString();
}
//<ab-date v-model="data.kjcs.sr" format="YYYY-MM-DD HH:mm:ss" ab-validate="{"date":true}" desc="生日" v-ab-permission="permission.kjcs.cskj.sr"></ab-date>
protected String getColumnDate(IBusinessColumn column) {
Element element = getElement("ab-date");
handleVModel(element, column);
handleValidateRules(element, column);
handlePermission(element, column);
element.attr(":ab-permission", getPermissionPath(column));
String configStr = column.getCtrl().getConfig();
if(StringUtil.isEmpty(configStr)) {
throw new BusinessException(String.format("表【%s】日期字段 【%s】解析失败,配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
String format = JSON.parseObject(configStr).getString("format");
//yyyy-MM-dd HH:mm:ss pc 移动端为:YYYY-MM-DD HH:mm
element.attr("format",format.replace("yyyy", "YYYY").replace("dd", "DD").replace(":ss", ""));
return element.toString();
}
protected String getColumnDic(IBusinessColumn column) {
Element element = getElement("ab-dict").attr("type", "text").addClass("input-div");
handleVModel(element, column);
handleValidateRules(element, column);
handlePermission(element, column);
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("key")) {
throw new BusinessException(String.format("表【%s】数据字典 字段【%s】解析失败,alias 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
element.attr("dict-key", config.getString("key"));
return element.toString();
}
protected String getColumnIdentity(IBusinessColumn column) {
Element element = getElement("input").attr("type", "text").addClass("weui-input");
handleVModel(element, column);
handlePermission(element, column);
handleValidateRules(element, column);
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("alias")) {
throw new BusinessException(String.format("表【%s】流水号 字段【%s】解析失败,alias 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
element.attr("ab-serial-no", config.getString("alias"));
return element.toString();
}
protected String getColumnMultitext(IBusinessColumn column) {
Element element = getElement("textarea").attr("type", "text").addClass("weui-textarea");
handleVModel(element, column);
handlePermission(element, column);
handleValidateRules(element, column);
return element.toString();
}
/**
* <ab-checkbox v-model="data.kjcs.ah" v-ab-permission="permission.kjcs.cskj.ah" v-ab-validate="{}" desc="爱好">
<div slot-scope="scope">
<label class=" checkbox-inline"><input type="checkbox" name="testttt" v-model="scope.tempData.currentValue" value="y"/>羽毛器</label>
<label class=" checkbox-inline"><input name="testttt" type="checkbox" v-model="scope.tempData.currentValue" value="l"/>篮球</label>
<label class=" checkbox-inline"><input type="checkbox" name="testttt" v-model="scope.tempData.currentValue" value="s"/>游泳</label>
</div>
</ab-checkbox>
*/
protected String getColumnCheckBox(IBusinessColumn column) {
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("options")) {
throw new BusinessException(String.format("表【%s】CheckBox 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
Element checkbox = getElement("ab-checkbox");
handleVModel(checkbox, column);
handleValidateRules(checkbox, column);
handlePermission(checkbox,column);
Element template = checkbox.appendElement("div").attr("slot-scope", "scope");
JSONArray options = config.getJSONArray("options");
for (int i = 0; i < options.size(); i++) {
JSONObject option = options.getJSONObject(i);
Element element = template.appendElement("label").addClass("checkbox-inline");
Element child = element.appendElement("input").attr("type", "checkbox");
child.attr("v-model", "scope.tempData.currentValue");
child.attr("value", option.getString("key"));
child.attr("name",String.format("%s-%s-%s",(String) ThreadMapUtil.get("boCode"), column.getTable().getKey(),column.getName()));
handlePermission(child,column);
element.appendText(option.getString("txt"));
}
return checkbox.toString();
}
protected String getColumnRadio(IBusinessColumn column) {
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("options")) {
throw new BusinessException(String.format("表【%s】Radio 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
Element permissionElement = getElement("div");
JSONArray options = config.getJSONArray("options");
for (int i = 0; i < options.size(); i++) {
JSONObject option = options.getJSONObject(i);
Element label = permissionElement.appendElement("label").addClass("radio-inline");
Element child = label.appendElement("input").attr("type", "radio");
handleVModel(child, column);
child.attr("v-ab-permission", getPermissionPath(column));
handleValidateRules(child, column);
child.attr("value", option.getString("key"));
label.appendText(option.getString("txt"));
}
return permissionElement.toString();
}
protected String getColumnSelect(IBusinessColumn column,Boolean isMultiple) {
JSONObject config = JSON.parseObject(column.getCtrl().getConfig());
if(!config.containsKey("options")) {
throw new BusinessException(String.format("表【%s】Select 字段 【%s】解析失败,options 配置信息不能为空", column.getTable().getKey(),column.getComment()));
}
Element permissionElement = getElement("select").addClass("weui-input");
handleVModel(permissionElement, column);
permissionElement.attr("v-ab-permission",getPermissionPath(column));
handleValidateRules(permissionElement, column);
if(isMultiple) {
permissionElement.attr("multiple", "true");
}
Element select = permissionElement.appendElement("option");
select.attr("value", "");
select.text("请选择");
JSONArray options = config.getJSONArray("options");
for (int i = 0; i < options.size(); i++) {
JSONObject option = options.getJSONObject(i);
Element element = permissionElement.appendElement("option");
element.attr("value", option.getString("key"));
element.text(option.getString("txt"));
}
return permissionElement.toString();
}
/**
* <pre>
* <ab-upload v-model="files" v-bind:permission="xxx">
* <a href="javascript:;" class="weui-btn weui-btn_mini weui-btn_primary fa fa-upload">上传</a>
* </ab-upload>
* </pre>
*/
protected String getColumnFile(IBusinessColumn column) {
Element element = getElement("ab-upload").attr("v-bind:permission", getPermissionPath(column));
handleVModel(element, column);
element.append("<a href=\"javascript:;\" class=\"weui-btn weui-btn_mini weui-btn_primary fa fa-upload\">"+column.getComment()+"</a>");
return element.toString();
}
// id="boCode-tableKey" ab-basic-permission="boCode.table.tableKey" ...
public String getSubAttrs(IBusTableRel rel) {
StringBuilder sb = new StringBuilder();
sb.append( " id="+"\""+ rel.getBusObj().getKey()+"-"+rel.getTableKey()+"\" ");
//一对 <SUF>
if(rel.getType().equals(BusTableRelType.ONE_TO_MANY.getKey())
&& !rel.getParent().getType().equals(BusTableRelType.MAIN.getKey())) {
sb.append(" v-transfer-dom ");
sb.append(" v-if=\"subTempData."+ rel.getTableKey() +"List\" ");
}
sb.append(" table-key=\""+rel.getTableKey()+"\" ");
return sb.toString() ;
}
protected void handlePermission(Element element,IBusinessColumn column) {
element.attr("v-ab-permission", getPermissionPath(column));
}
protected void handleValidateRules(Element element,IBusinessColumn column) {
super.handleValidateRules(element, column);
element.attr("v-ab-validate", element.attr("ab-validate"));
element.removeAttr("ab-validate");
}
@Override
public String getGeneratorName() {
return "mobileGenerator";
}
}
| 0 | 2,477 | 9 | 3,013 | 11 | 3,052 | 9 | 3,013 | 11 | 3,622 | 22 | false | false | false | false | false | true |
60968_9 | package com.qgmodel.qggame.entity;
import android.util.Log;
public class MyCardSystem {
private static final String TAG = "MyCard";
private String[] originalCards = new String[]{"说数字", "说为什么", "说英文", "说成语", "说脏话", "说不要", "说好的", "说我没有", "说对不起", "说女朋友",
"说男朋友", "说谢谢", "说考试", "说年龄", "说钱", "说别动", "说明星名", "说歌曲名", "说我不说", "说怕", "说凭什么",
"说没有", "说方言", "说好难", "说该谁了", "说轮到你了", "说不会", "说人名", "说再见", "说回家", "称赞别人", "夸自己", "手托腮",
"回头看", "大叫", "回忆", "向上看", "叫人名", "摸头发", "拒绝别人", "点头", "摸鼻子", "表示同意", "大笑", "回答问题", "提问",
"打赌", "摇头", "怀疑别人", "摸嘴唇", "使眼色", "摸耳垂", "聊工作", "伸舌头","聊家人","聊猫","聊星座","说可爱","说真的","陷害别人",
"唱歌", "讨论玩法", "说听不清", "说没事", "安慰别人", "说不怕", "捂嘴","说电影名字","说刚才"};
private String[] cards = new String[originalCards.length];
private String[] resultCards;
//记录下标的数组
private int[] primes = {2,3,5,7,11,13,17,19};
private int[] indexes = new int[originalCards.length];
private int[] mark = new int[originalCards.length];
private int count = 0;
private int userNum = 4;
private int userCard = 10;
private int distributeCount = 0;
private int reset = 0;
public MyCardSystem(int userNum, int userCard){
this.userNum = userNum;
this.userCard = userCard;
reset =(int) Math.floor((double) originalCards.length/userCard);
Log.d(TAG, "=== reset--> "+reset);
}
private void shuffle(){
count++;
if (count == 1){
for(int i = 0; i< indexes.length; i++) {
indexes[i] = i;
}
}
//对坐标数组用洗牌算法
for (int i = originalCards.length-1; i >0; i--) {
int j = rand(0, i);
indexes[i] = indexes[i] + indexes[j];
indexes[j] = indexes[i] - indexes[j];
indexes[i] = indexes[i] - indexes[j];
}
for (int i = 0;i<cards.length;i++){
cards[i] = originalCards[indexes[i]];
}
}
private int rand(int start,int end){
int ret = (int)(Math.random()*(end - start)+start);
return ret;
}
public String[] getResultCards() {
//外部每次获取前重新分配
distribute();
return resultCards;
}
public void distribute(){
//每次分配都要先洗牌
shuffle();
distributeCount++;
if (distributeCount % reset ==0){
clearMark();
}
resultCards = new String[userNum*userCard];
//selected表示已算好的卡牌的数量
int selected = 0;
//userSign作为不同玩家的标志,均为质数,用于判断某牌是不是被该玩家抽中过
int userSign = primes[0];
int j = 1;
for (int i = 0;selected < userNum*userCard;i++){
if (mark[indexes[i % cards.length]]!=0&&mark[indexes[i % cards.length]] % userSign == 0){
//该牌已被该玩家抽到过
}else{
if (mark[indexes[i % cards.length]]==0){
//该牌没被任何玩家抽到过
mark[indexes[i % cards.length]]+=userSign;
}else if (mark[indexes[i % cards.length]] % userSign != 0){
//该牌没被 当前玩家 抽到过
mark[indexes[i % cards.length]]*=userSign;
}
resultCards[selected] = cards[i%cards.length];
selected++;
if (selected%userCard == 0 && j<userNum){
//如果当前玩家已分配好牌,为下一个玩家分配
userSign = primes[j++];
}
}
// Log.d(TAG, "=== i--> "+i);
}
// for (int i = 0;i<resultCards.length;i++)
// {
// Log.d(TAG, "=== resultCards--> "+resultCards[i]);
// }
// Log.d(TAG, "=== ************************************");
}
private void clearMark(){
for (int i = 0;i<mark.length;i++){
mark[i] = 0;
}
}
public int getUserNum() {
return userNum;
}
public void setUserNum(int userNum) {
this.userNum = userNum;
}
public int getUserCard() {
return userCard;
}
public void setUserCard(int userCard) {
this.userCard = userCard;
}
}
| AgoraIO-Community/RTE-2021-Innovation-Challenge | Application-Challenge/【瓜瓜队】狼人杀/langrensha/app/src/main/java/com/qgmodel/qggame/entity/MyCardSystem.java | 1,385 | //如果当前玩家已分配好牌,为下一个玩家分配 | line_comment | zh-cn | package com.qgmodel.qggame.entity;
import android.util.Log;
public class MyCardSystem {
private static final String TAG = "MyCard";
private String[] originalCards = new String[]{"说数字", "说为什么", "说英文", "说成语", "说脏话", "说不要", "说好的", "说我没有", "说对不起", "说女朋友",
"说男朋友", "说谢谢", "说考试", "说年龄", "说钱", "说别动", "说明星名", "说歌曲名", "说我不说", "说怕", "说凭什么",
"说没有", "说方言", "说好难", "说该谁了", "说轮到你了", "说不会", "说人名", "说再见", "说回家", "称赞别人", "夸自己", "手托腮",
"回头看", "大叫", "回忆", "向上看", "叫人名", "摸头发", "拒绝别人", "点头", "摸鼻子", "表示同意", "大笑", "回答问题", "提问",
"打赌", "摇头", "怀疑别人", "摸嘴唇", "使眼色", "摸耳垂", "聊工作", "伸舌头","聊家人","聊猫","聊星座","说可爱","说真的","陷害别人",
"唱歌", "讨论玩法", "说听不清", "说没事", "安慰别人", "说不怕", "捂嘴","说电影名字","说刚才"};
private String[] cards = new String[originalCards.length];
private String[] resultCards;
//记录下标的数组
private int[] primes = {2,3,5,7,11,13,17,19};
private int[] indexes = new int[originalCards.length];
private int[] mark = new int[originalCards.length];
private int count = 0;
private int userNum = 4;
private int userCard = 10;
private int distributeCount = 0;
private int reset = 0;
public MyCardSystem(int userNum, int userCard){
this.userNum = userNum;
this.userCard = userCard;
reset =(int) Math.floor((double) originalCards.length/userCard);
Log.d(TAG, "=== reset--> "+reset);
}
private void shuffle(){
count++;
if (count == 1){
for(int i = 0; i< indexes.length; i++) {
indexes[i] = i;
}
}
//对坐标数组用洗牌算法
for (int i = originalCards.length-1; i >0; i--) {
int j = rand(0, i);
indexes[i] = indexes[i] + indexes[j];
indexes[j] = indexes[i] - indexes[j];
indexes[i] = indexes[i] - indexes[j];
}
for (int i = 0;i<cards.length;i++){
cards[i] = originalCards[indexes[i]];
}
}
private int rand(int start,int end){
int ret = (int)(Math.random()*(end - start)+start);
return ret;
}
public String[] getResultCards() {
//外部每次获取前重新分配
distribute();
return resultCards;
}
public void distribute(){
//每次分配都要先洗牌
shuffle();
distributeCount++;
if (distributeCount % reset ==0){
clearMark();
}
resultCards = new String[userNum*userCard];
//selected表示已算好的卡牌的数量
int selected = 0;
//userSign作为不同玩家的标志,均为质数,用于判断某牌是不是被该玩家抽中过
int userSign = primes[0];
int j = 1;
for (int i = 0;selected < userNum*userCard;i++){
if (mark[indexes[i % cards.length]]!=0&&mark[indexes[i % cards.length]] % userSign == 0){
//该牌已被该玩家抽到过
}else{
if (mark[indexes[i % cards.length]]==0){
//该牌没被任何玩家抽到过
mark[indexes[i % cards.length]]+=userSign;
}else if (mark[indexes[i % cards.length]] % userSign != 0){
//该牌没被 当前玩家 抽到过
mark[indexes[i % cards.length]]*=userSign;
}
resultCards[selected] = cards[i%cards.length];
selected++;
if (selected%userCard == 0 && j<userNum){
//如果 <SUF>
userSign = primes[j++];
}
}
// Log.d(TAG, "=== i--> "+i);
}
// for (int i = 0;i<resultCards.length;i++)
// {
// Log.d(TAG, "=== resultCards--> "+resultCards[i]);
// }
// Log.d(TAG, "=== ************************************");
}
private void clearMark(){
for (int i = 0;i<mark.length;i++){
mark[i] = 0;
}
}
public int getUserNum() {
return userNum;
}
public void setUserNum(int userNum) {
this.userNum = userNum;
}
public int getUserCard() {
return userCard;
}
public void setUserCard(int userCard) {
this.userCard = userCard;
}
}
| 0 | 1,203 | 13 | 1,385 | 16 | 1,380 | 13 | 1,385 | 16 | 1,747 | 27 | false | false | false | false | false | true |
35826_7 | package io.agora.falcondemo.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import com.agora.baselibrary.utils.SPUtil;
import java.nio.charset.StandardCharsets;
public class AppStorageUtil {
////////////////////////////////////////////////////////////////////////
//////////////////////// Constant Definition ///////////////////////////
////////////////////////////////////////////////////////////////////////
//
// 应用存储参数键值
//
public static final String KEY_ACCOUNT = "KEY_ACCOUNT";
public static final String KEY_PASSWORD = "KEY_PASSWORD";
public static final String KEY_TOKEN = "KEY_TOKEN";
public static final String KEY_IDENTITYID = "KEY_IDENTITYID";
public static final String KEY_ENDPOINT = "KEY_ENDPOINT";
public static final String KEY_POOLTOKEN = "KEY_POOLTOKEN";
public static final String KEY_IDENTIFIER = "KEY_IDENTIFIER";
public static final String KEY_IDENTIFIERPOOLID = "KEY_IDENTIFIERPOOLID";
public static final String KEY_REGION = "KEY_REGION";
//////////////////////////////////////////////////////////////////
////////////////////// Public Methods ///////////////////////////
//////////////////////////////////////////////////////////////////
private static SharedPreferences sharedPreferences;
private volatile static AppStorageUtil instance;
public static AppStorageUtil init(Context context) {
if (instance == null) {
synchronized (AppStorageUtil.class) {
if (instance == null) {
instance = new AppStorageUtil(context);
}
}
}
return instance;
}
private AppStorageUtil(Context context) {
sharedPreferences = context.getSharedPreferences("IoTDemo", Context.MODE_PRIVATE);
}
public static void keepShared(String key, String value) {
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static void keepShared(String key, Integer value) {
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static void keepShared(String key, long value) {
Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
editor.commit();
}
public static void keepShared(String key, int value) {
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static void keepShared(String key, boolean value) {
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static String queryValue(String key, String defvalue) {
String value = sharedPreferences.getString(key, defvalue);
// if ("".equals(value)) {
// return "";
// }
return value;
}
public static String queryValue(String key) {
String value = sharedPreferences.getString(key, "");
if ("".equals(value)) {
return "";
}
return value;
}
public static Integer queryIntValue(String key) {
int value = sharedPreferences.getInt(key, 0);
return value;
}
public static Integer queryIntValue(String key, int defalut) {
int value = sharedPreferences.getInt(key, defalut);
return value;
}
public static boolean queryBooleanValue(String key) {
return sharedPreferences.getBoolean(key, false);
}
public static long queryLongValue(String key) {
return sharedPreferences.getLong(key, 0);
}
public static boolean deleteAllValue() {
return sharedPreferences.edit().clear().commit();
}
public static void deleteValue(String key) {
sharedPreferences.edit().remove(key).commit();
}
public static void safePutString(Context ctx, String key, String value) {
if (TextUtils.isEmpty(value)) {
SPUtil.Companion.getInstance(ctx).putString(key, value);
return;
}
String encryptValue = encryptString(value);
SPUtil.Companion.getInstance(ctx).putString(key, encryptValue);
}
public static String safeGetString(Context ctx,String key, String defValue) {
String encryptValue = SPUtil.Companion.getInstance(ctx).getString(key, defValue);
if (encryptValue == null) {
return null;
}
if (encryptValue.isEmpty()) {
return "";
}
String value = decryptString(encryptValue);
return value;
}
/**
* @biref 字符串加密
*/
public static String encryptString(String value) {
if (TextUtils.isEmpty(value)) {
return "";
}
// 转换成 Utf-8 字节流
byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
byte[] encryptData = enDeCrypt(utf8);
// 每个字节转换成 xxx, 数字
String encrypted = bytesToString(encryptData);
return encrypted;
}
/**
* @biref 字符串解密
*/
public static String decryptString(String value) {
if (TextUtils.isEmpty(value)) {
return "";
}
// 每个字节转换成utf8字节流
byte[] utf8 = stringToBytes(value);
byte[] decrypted = enDeCrypt(utf8);
// 文本字节由utf8字节流创建
String text = new String(decrypted, StandardCharsets.UTF_8);
return text;
}
/**
* @biref 将字节流数据转换成16进制
* @param data 字节流数据
* @return 返回转换后的文本
*/
public static String bytesToString(byte[] data) {
if (data == null) {
return "";
}
String text = "";
for (int j = 0; j < data.length; j++) {
String dataHex = String.format("%03d,", data[j]);
text += dataHex;
}
return text;
}
/**
* @biref 将字符串转换成字节流
* @param text 字符串
* @return 返回转换后的文本
*/
public static byte[] stringToBytes(final String text) {
if (text == null) {
return null;
}
String[] elemArray = text.split(",");
if (elemArray == null || elemArray.length <= 0) {
return null;
}
byte[] data = new byte[elemArray.length];
for (int i = 0; i < elemArray.length; i++) {
data[i] = Byte.valueOf(elemArray[i]);
}
return data;
}
public static byte[] enDeCrypt(byte[] inData) {
if (inData == null) {
return null;
}
int [] key = new int[] { 0x05, 0xEF, 0x4F, 0x28, 0x61, 0x46, 0x43, 0x6C, 0x73, 0x23, 0x22, 0x43, 0x7E, 0x7D, 0x96, 0xB4};
int keyLen = key.length;
int dataSize = inData.length;
byte[] outData = new byte[dataSize];
int i, j = 0;
for (i = 0; i < dataSize; i++) {
outData[i] = (byte)(inData[i] ^ key[j]);
j = (j + 1) % keyLen;
}
return outData;
}
// public static void UnitTest() {
// String orgText = "ABCDefgh012346+-*%_@!#$%^&()华叔[好人]<>";
// String encryptText = AppStorageUtil.encryptString(orgText);
// String decryptText = AppStorageUtil.decryptString(encryptText);
//
// if (orgText.compareToIgnoreCase(decryptText) != 0) {
// Log.d("UT", "encrypt error");
// } else {
// Log.d("UT", "encrypt OK");
// }
// }
}
| AgoraIO-Community/ag-iot-android-app | app/src/main/java/io/agora/falcondemo/utils/AppStorageUtil.java | 1,837 | // 每个字节转换成 xxx, 数字 | line_comment | zh-cn | package io.agora.falcondemo.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import com.agora.baselibrary.utils.SPUtil;
import java.nio.charset.StandardCharsets;
public class AppStorageUtil {
////////////////////////////////////////////////////////////////////////
//////////////////////// Constant Definition ///////////////////////////
////////////////////////////////////////////////////////////////////////
//
// 应用存储参数键值
//
public static final String KEY_ACCOUNT = "KEY_ACCOUNT";
public static final String KEY_PASSWORD = "KEY_PASSWORD";
public static final String KEY_TOKEN = "KEY_TOKEN";
public static final String KEY_IDENTITYID = "KEY_IDENTITYID";
public static final String KEY_ENDPOINT = "KEY_ENDPOINT";
public static final String KEY_POOLTOKEN = "KEY_POOLTOKEN";
public static final String KEY_IDENTIFIER = "KEY_IDENTIFIER";
public static final String KEY_IDENTIFIERPOOLID = "KEY_IDENTIFIERPOOLID";
public static final String KEY_REGION = "KEY_REGION";
//////////////////////////////////////////////////////////////////
////////////////////// Public Methods ///////////////////////////
//////////////////////////////////////////////////////////////////
private static SharedPreferences sharedPreferences;
private volatile static AppStorageUtil instance;
public static AppStorageUtil init(Context context) {
if (instance == null) {
synchronized (AppStorageUtil.class) {
if (instance == null) {
instance = new AppStorageUtil(context);
}
}
}
return instance;
}
private AppStorageUtil(Context context) {
sharedPreferences = context.getSharedPreferences("IoTDemo", Context.MODE_PRIVATE);
}
public static void keepShared(String key, String value) {
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static void keepShared(String key, Integer value) {
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static void keepShared(String key, long value) {
Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
editor.commit();
}
public static void keepShared(String key, int value) {
Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public static void keepShared(String key, boolean value) {
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static String queryValue(String key, String defvalue) {
String value = sharedPreferences.getString(key, defvalue);
// if ("".equals(value)) {
// return "";
// }
return value;
}
public static String queryValue(String key) {
String value = sharedPreferences.getString(key, "");
if ("".equals(value)) {
return "";
}
return value;
}
public static Integer queryIntValue(String key) {
int value = sharedPreferences.getInt(key, 0);
return value;
}
public static Integer queryIntValue(String key, int defalut) {
int value = sharedPreferences.getInt(key, defalut);
return value;
}
public static boolean queryBooleanValue(String key) {
return sharedPreferences.getBoolean(key, false);
}
public static long queryLongValue(String key) {
return sharedPreferences.getLong(key, 0);
}
public static boolean deleteAllValue() {
return sharedPreferences.edit().clear().commit();
}
public static void deleteValue(String key) {
sharedPreferences.edit().remove(key).commit();
}
public static void safePutString(Context ctx, String key, String value) {
if (TextUtils.isEmpty(value)) {
SPUtil.Companion.getInstance(ctx).putString(key, value);
return;
}
String encryptValue = encryptString(value);
SPUtil.Companion.getInstance(ctx).putString(key, encryptValue);
}
public static String safeGetString(Context ctx,String key, String defValue) {
String encryptValue = SPUtil.Companion.getInstance(ctx).getString(key, defValue);
if (encryptValue == null) {
return null;
}
if (encryptValue.isEmpty()) {
return "";
}
String value = decryptString(encryptValue);
return value;
}
/**
* @biref 字符串加密
*/
public static String encryptString(String value) {
if (TextUtils.isEmpty(value)) {
return "";
}
// 转换成 Utf-8 字节流
byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
byte[] encryptData = enDeCrypt(utf8);
// 每个 <SUF>
String encrypted = bytesToString(encryptData);
return encrypted;
}
/**
* @biref 字符串解密
*/
public static String decryptString(String value) {
if (TextUtils.isEmpty(value)) {
return "";
}
// 每个字节转换成utf8字节流
byte[] utf8 = stringToBytes(value);
byte[] decrypted = enDeCrypt(utf8);
// 文本字节由utf8字节流创建
String text = new String(decrypted, StandardCharsets.UTF_8);
return text;
}
/**
* @biref 将字节流数据转换成16进制
* @param data 字节流数据
* @return 返回转换后的文本
*/
public static String bytesToString(byte[] data) {
if (data == null) {
return "";
}
String text = "";
for (int j = 0; j < data.length; j++) {
String dataHex = String.format("%03d,", data[j]);
text += dataHex;
}
return text;
}
/**
* @biref 将字符串转换成字节流
* @param text 字符串
* @return 返回转换后的文本
*/
public static byte[] stringToBytes(final String text) {
if (text == null) {
return null;
}
String[] elemArray = text.split(",");
if (elemArray == null || elemArray.length <= 0) {
return null;
}
byte[] data = new byte[elemArray.length];
for (int i = 0; i < elemArray.length; i++) {
data[i] = Byte.valueOf(elemArray[i]);
}
return data;
}
public static byte[] enDeCrypt(byte[] inData) {
if (inData == null) {
return null;
}
int [] key = new int[] { 0x05, 0xEF, 0x4F, 0x28, 0x61, 0x46, 0x43, 0x6C, 0x73, 0x23, 0x22, 0x43, 0x7E, 0x7D, 0x96, 0xB4};
int keyLen = key.length;
int dataSize = inData.length;
byte[] outData = new byte[dataSize];
int i, j = 0;
for (i = 0; i < dataSize; i++) {
outData[i] = (byte)(inData[i] ^ key[j]);
j = (j + 1) % keyLen;
}
return outData;
}
// public static void UnitTest() {
// String orgText = "ABCDefgh012346+-*%_@!#$%^&()华叔[好人]<>";
// String encryptText = AppStorageUtil.encryptString(orgText);
// String decryptText = AppStorageUtil.decryptString(encryptText);
//
// if (orgText.compareToIgnoreCase(decryptText) != 0) {
// Log.d("UT", "encrypt error");
// } else {
// Log.d("UT", "encrypt OK");
// }
// }
}
| 0 | 1,686 | 13 | 1,837 | 10 | 2,020 | 8 | 1,837 | 10 | 2,264 | 15 | false | false | false | false | false | true |
65495_1 | package com.ahogek.lotterydrawdemo;
import com.ahogek.lotterydrawdemo.entity.LotteryData;
import com.ahogek.lotterydrawdemo.repository.LotteryDataRepository;
import com.ahogek.lotterydrawdemo.service.LotteryDataService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
@EnableTransactionManagement
@SpringBootApplication
public class LotteryDrawDemoApplication {
private static final Logger LOG = LoggerFactory.getLogger(LotteryDrawDemoApplication.class);
private final Random random = new Random();
public static void main(String[] args) {
SpringApplication.run(LotteryDrawDemoApplication.class, args);
}
private static void checkNewInputDrawNumber(LotteryDataRepository lotteryDateRepository, List<List<String>> inputNewDrawNumber) {
if (inputNewDrawNumber != null && !inputNewDrawNumber.isEmpty()) {
// 遍历 inputNewDrawNumber 集合
inputNewDrawNumber.forEach(itemNumbers -> {
// 遍历每一项,其中第一项为日期,先判断数据库有无该日期的数据,如果没有才执行操作
LocalDate date = LocalDate.parse(itemNumbers.getFirst(),
DateTimeFormatter.ofPattern("yyyy-MM-dd"));
if (lotteryDateRepository.countByLotteryDrawTime(date) == 0) {
List<LotteryData> insertList = new ArrayList<>();
for (int i = 1; i < itemNumbers.size(); i++) {
LotteryData lotteryDrawNumber = new LotteryData();
lotteryDrawNumber.setLotteryDrawNumber(itemNumbers.get(i));
lotteryDrawNumber.setLotteryDrawTime(date);
lotteryDrawNumber.setLotteryDrawNumberType(i - 1);
insertList.add(lotteryDrawNumber);
}
if (!insertList.isEmpty())
lotteryDateRepository.saveAll(insertList);
}
});
}
}
public static void groupAllData(List<List<String>> allData, List<LotteryData> all) {
for (int i = 0; i < 7; i++) {
int type = i;
allData.add(all.stream().filter(item -> type == item.getLotteryDrawNumberType())
.map(LotteryData::getLotteryDrawNumber).toList());
}
}
private static long getCount(LocalDate lastDate, LocalDate now) {
long count = 0;
LocalDate nextLotteryDate = lastDate.plusDays(1);
while (nextLotteryDate.isBefore(now) || (nextLotteryDate.isEqual(now) && LocalDateTime.now().getHour() >= 22)) {
if (nextLotteryDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.MONDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.WEDNESDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
count++;
} else {
nextLotteryDate = nextLotteryDate.plusDays(1);
}
}
return count;
}
@Bean
public CommandLineRunner getRandomLotteryNumber(LotteryDataService service, LotteryRequestManager request, LotteryDataRepository lotteryDateRepository) {
return args -> {
List<LotteryData> all = service.findAll();
if (all.isEmpty())
request.setData();
// 获取数据库中最新的一期数据的时间
LocalDate lastDate = lotteryDateRepository.findTopByOrderByLotteryDrawTimeDesc().getLotteryDrawTime();
// 根据但前时间判断 lastDate 是否是最新一期,彩票每周一 三 六开奖
LocalDate now = LocalDate.now();
if (ChronoUnit.DAYS.between(lastDate, now) >= 2) {
// 判断 lastDate 直到今天为止少了多少次开奖
long count = getCount(lastDate, now);
if (count > 0) {
// 根据 count 查询彩票网数据
JSONObject response = request.getNextPage(Math.toIntExact(count));
List<List<String>> inputNewDrawNumber = new ArrayList<>();
JSONArray list = response.getJSONObject("value").getJSONArray("list");
for (int i = 0; i < list.size(); i++) {
JSONObject data = list.getJSONObject(i);
String[] drawNumbers = data.getString("lotteryDrawResult").split(" ");
List<String> item = new ArrayList<>();
item.add(LocalDate.ofInstant(data.getDate("lotteryDrawTime").toInstant(),
ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
item.addAll(Arrays.asList(drawNumbers).subList(0, 7));
inputNewDrawNumber.add(item);
}
inputNewDrawNumber = inputNewDrawNumber.reversed();
checkNewInputDrawNumber(lotteryDateRepository, inputNewDrawNumber);
}
}
List<String> result = new ArrayList<>((int) (7 / 0.75f + 1));
// 前区五个球
Set<String> front = new HashSet<>();
// 后区两个球
Set<String> back = new HashSet<>();
List<List<String>> allDataGroup = new ArrayList<>();
groupAllData(allDataGroup, all);
for (int i = 0; i < 7; i++) {
// 随机一个列表里的String
drawNumbers(i, allDataGroup, front, back);
}
// 分别排序前后组
front.stream().sorted().forEach(result::add);
back.stream().sorted().forEach(result::add);
LOG.info("随机摇奖号码为:{},祝你好运!", result);
};
}
public void drawNumbers(int i, List<List<String>> allDataGroup, Set<String> front, Set<String> back) {
if (i < 5) {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
front.add(allDataGroup.get(i).get(index));
} while (front.size() != i + 1);
} else {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
back.add(allDataGroup.get(i).get(index));
} while (back.size() != i - 5 + 1);
}
}
}
| AhogeK/lottery-draw-demo | src/main/java/com/ahogek/lotterydrawdemo/LotteryDrawDemoApplication.java | 1,733 | // 遍历每一项,其中第一项为日期,先判断数据库有无该日期的数据,如果没有才执行操作 | line_comment | zh-cn | package com.ahogek.lotterydrawdemo;
import com.ahogek.lotterydrawdemo.entity.LotteryData;
import com.ahogek.lotterydrawdemo.repository.LotteryDataRepository;
import com.ahogek.lotterydrawdemo.service.LotteryDataService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
@EnableTransactionManagement
@SpringBootApplication
public class LotteryDrawDemoApplication {
private static final Logger LOG = LoggerFactory.getLogger(LotteryDrawDemoApplication.class);
private final Random random = new Random();
public static void main(String[] args) {
SpringApplication.run(LotteryDrawDemoApplication.class, args);
}
private static void checkNewInputDrawNumber(LotteryDataRepository lotteryDateRepository, List<List<String>> inputNewDrawNumber) {
if (inputNewDrawNumber != null && !inputNewDrawNumber.isEmpty()) {
// 遍历 inputNewDrawNumber 集合
inputNewDrawNumber.forEach(itemNumbers -> {
// 遍历 <SUF>
LocalDate date = LocalDate.parse(itemNumbers.getFirst(),
DateTimeFormatter.ofPattern("yyyy-MM-dd"));
if (lotteryDateRepository.countByLotteryDrawTime(date) == 0) {
List<LotteryData> insertList = new ArrayList<>();
for (int i = 1; i < itemNumbers.size(); i++) {
LotteryData lotteryDrawNumber = new LotteryData();
lotteryDrawNumber.setLotteryDrawNumber(itemNumbers.get(i));
lotteryDrawNumber.setLotteryDrawTime(date);
lotteryDrawNumber.setLotteryDrawNumberType(i - 1);
insertList.add(lotteryDrawNumber);
}
if (!insertList.isEmpty())
lotteryDateRepository.saveAll(insertList);
}
});
}
}
public static void groupAllData(List<List<String>> allData, List<LotteryData> all) {
for (int i = 0; i < 7; i++) {
int type = i;
allData.add(all.stream().filter(item -> type == item.getLotteryDrawNumberType())
.map(LotteryData::getLotteryDrawNumber).toList());
}
}
private static long getCount(LocalDate lastDate, LocalDate now) {
long count = 0;
LocalDate nextLotteryDate = lastDate.plusDays(1);
while (nextLotteryDate.isBefore(now) || (nextLotteryDate.isEqual(now) && LocalDateTime.now().getHour() >= 22)) {
if (nextLotteryDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.MONDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.WEDNESDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
count++;
} else {
nextLotteryDate = nextLotteryDate.plusDays(1);
}
}
return count;
}
@Bean
public CommandLineRunner getRandomLotteryNumber(LotteryDataService service, LotteryRequestManager request, LotteryDataRepository lotteryDateRepository) {
return args -> {
List<LotteryData> all = service.findAll();
if (all.isEmpty())
request.setData();
// 获取数据库中最新的一期数据的时间
LocalDate lastDate = lotteryDateRepository.findTopByOrderByLotteryDrawTimeDesc().getLotteryDrawTime();
// 根据但前时间判断 lastDate 是否是最新一期,彩票每周一 三 六开奖
LocalDate now = LocalDate.now();
if (ChronoUnit.DAYS.between(lastDate, now) >= 2) {
// 判断 lastDate 直到今天为止少了多少次开奖
long count = getCount(lastDate, now);
if (count > 0) {
// 根据 count 查询彩票网数据
JSONObject response = request.getNextPage(Math.toIntExact(count));
List<List<String>> inputNewDrawNumber = new ArrayList<>();
JSONArray list = response.getJSONObject("value").getJSONArray("list");
for (int i = 0; i < list.size(); i++) {
JSONObject data = list.getJSONObject(i);
String[] drawNumbers = data.getString("lotteryDrawResult").split(" ");
List<String> item = new ArrayList<>();
item.add(LocalDate.ofInstant(data.getDate("lotteryDrawTime").toInstant(),
ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
item.addAll(Arrays.asList(drawNumbers).subList(0, 7));
inputNewDrawNumber.add(item);
}
inputNewDrawNumber = inputNewDrawNumber.reversed();
checkNewInputDrawNumber(lotteryDateRepository, inputNewDrawNumber);
}
}
List<String> result = new ArrayList<>((int) (7 / 0.75f + 1));
// 前区五个球
Set<String> front = new HashSet<>();
// 后区两个球
Set<String> back = new HashSet<>();
List<List<String>> allDataGroup = new ArrayList<>();
groupAllData(allDataGroup, all);
for (int i = 0; i < 7; i++) {
// 随机一个列表里的String
drawNumbers(i, allDataGroup, front, back);
}
// 分别排序前后组
front.stream().sorted().forEach(result::add);
back.stream().sorted().forEach(result::add);
LOG.info("随机摇奖号码为:{},祝你好运!", result);
};
}
public void drawNumbers(int i, List<List<String>> allDataGroup, Set<String> front, Set<String> back) {
if (i < 5) {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
front.add(allDataGroup.get(i).get(index));
} while (front.size() != i + 1);
} else {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
back.add(allDataGroup.get(i).get(index));
} while (back.size() != i - 5 + 1);
}
}
}
| 0 | 1,506 | 27 | 1,733 | 27 | 1,747 | 25 | 1,733 | 27 | 2,108 | 47 | false | false | false | false | false | true |
55261_13 | package cn.aijiang.aop;
import org.aspectj.lang.annotation.*;
/**
* 定义一个切点
*
* 对于演出这个整体业务来说,观众在现实上表现得很重要(观众多,恰到钱就越多嘛)
* 但在业务代码里,我们只关心演出业务,观众应作为切面来看待
*/
@Aspect
public class Audience {
// /**
// * 表演开始前的表现一
// */
// @Before("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void silenceCellPhones() {
// System.out.println("手机静音了嗷。");
// }
//
// /**
// * 表演开始前的表现二
// */
// @Before("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void takeSeats() {
// System.out.println("谈话停止了嗷。");
// }
//
// /**
// * 表演精彩时的表现
// */
// @AfterReturning("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void applause() {
// System.out.println("喔喔喔喔!精彩极了啊!");
// }
//
// /**
// * 表演失败之后的表现
// */
// @AfterThrowing("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void demandRefund() {
// System.out.println("这表演真是太下饭,建议退钱!");
// }
/**
* 定义命名的切点
*/
@Pointcut("execution(* cn.aijiang.aop.Performance.perform(..))")
public void performance() {
}
/**
* 表演开始前的表现一
*/
@Before("performance()")
public void silenceCellPhones() {
System.out.println("手机静音了嗷。");
}
/**
* 表演开始前的表现二
*/
@Before("performance()")
public void takeSeats() {
System.out.println("谈话停止了嗷。");
}
/**
* 表演精彩时的表现
*/
@AfterReturning("performance()")
public void applause() {
System.out.println("喔喔喔喔!精彩极了啊!");
}
/**
* 表演失败之后的表现
*/
@AfterThrowing("performance()")
public void demandRefund() {
System.out.println("这表演真是太下饭,建议退钱!");
}
}
| AijiangyoubuAicu/JavaInterview | Spring/src/main/java/cn/aijiang/aop/Audience.java | 684 | // * 表演失败之后的表现 | line_comment | zh-cn | package cn.aijiang.aop;
import org.aspectj.lang.annotation.*;
/**
* 定义一个切点
*
* 对于演出这个整体业务来说,观众在现实上表现得很重要(观众多,恰到钱就越多嘛)
* 但在业务代码里,我们只关心演出业务,观众应作为切面来看待
*/
@Aspect
public class Audience {
// /**
// * 表演开始前的表现一
// */
// @Before("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void silenceCellPhones() {
// System.out.println("手机静音了嗷。");
// }
//
// /**
// * 表演开始前的表现二
// */
// @Before("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void takeSeats() {
// System.out.println("谈话停止了嗷。");
// }
//
// /**
// * 表演精彩时的表现
// */
// @AfterReturning("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void applause() {
// System.out.println("喔喔喔喔!精彩极了啊!");
// }
//
// /**
// * 表演 <SUF>
// */
// @AfterThrowing("execution(* cn.aijiang.aop.Performance.perform(..))")
// public void demandRefund() {
// System.out.println("这表演真是太下饭,建议退钱!");
// }
/**
* 定义命名的切点
*/
@Pointcut("execution(* cn.aijiang.aop.Performance.perform(..))")
public void performance() {
}
/**
* 表演开始前的表现一
*/
@Before("performance()")
public void silenceCellPhones() {
System.out.println("手机静音了嗷。");
}
/**
* 表演开始前的表现二
*/
@Before("performance()")
public void takeSeats() {
System.out.println("谈话停止了嗷。");
}
/**
* 表演精彩时的表现
*/
@AfterReturning("performance()")
public void applause() {
System.out.println("喔喔喔喔!精彩极了啊!");
}
/**
* 表演失败之后的表现
*/
@AfterThrowing("performance()")
public void demandRefund() {
System.out.println("这表演真是太下饭,建议退钱!");
}
}
| 0 | 538 | 9 | 684 | 11 | 622 | 8 | 684 | 11 | 889 | 15 | false | false | false | false | false | true |
14466_17 | package com.github.airsaid.accountbook.util;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.airsaid.accountbook.mvp.main.MainActivity;
import com.github.airsaid.accountbook.R;
import com.github.airsaid.accountbook.base.BaseApplication;
import com.github.airsaid.accountbook.mvp.login.LoginActivity;
/**
* Created by zhouyou on 2016/6/27.
* Class desc: ui 操作相关封装
*/
public class UiUtils {
/**
* 获取上下文
*/
public static Context getContext() {
return BaseApplication.getContext();
}
/**
* 获取资源操作类
*/
public static Resources getResources() {
return getContext().getResources();
}
/**
* 获取字符串资源
*
* @param id 资源id
* @return 字符串
*/
public static String getString(int id) {
return getResources().getString(id);
}
/**
* 获取字符串数组资源
*
* @param id 资源id
* @return 字符串数组
*/
public static String[] getStringArray(int id) {
return getResources().getStringArray(id);
}
/**
* 获取颜色资源
*/
public static int getColor(int id) {
return ContextCompat.getColor(getContext(), id);
}
/**
* 获取颜色资源
*
* @param id 资源id
* @param theme 样式
* @return
*/
public static int getColor(int id, Resources.Theme theme) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getResources().getColor(id, theme);
}
return getResources().getColor(id);
}
/**
* 获取drawable资源
*
* @param id 资源id
* @return
*/
public static Drawable getDrawable(int id) {
return ContextCompat.getDrawable(getContext(), id);
}
/**
* 通过图片名称获取图片资源 id
* @param imageName 图片名称
* @return 图片资源 id
*/
public static int getImageResIdByName(String imageName){
return getResources().getIdentifier(imageName, "mipmap"
, AppUtils.getPackageName());
}
/**
* 加载布局(使用View方式)
*
* @param resource 布局资源id
* @return View
*/
public static View inflate(int resource) {
return View.inflate(getContext(), resource, null);
}
/**
* 检查输入的内容是否为空
*/
public static boolean checkEmpty(EditText editText) {
if(TextUtils.isEmpty(editText.getText().toString())){
ToastUtils.show(UiUtils.getContext(), UiUtils.getString(R.string.hint_empty));
return true;
}
return false;
}
/**
* 设置透明状态栏
* @param activity
*/
public static void setStatusBar(Activity activity) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
// 对于4.4以上5.0以下版本,设置透明状态栏
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
// 5.0及以上版本,设置透明状态栏
Window window = activity.getWindow();
// 清理4.4Flag
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
// 添加标志位
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// 设置为透明
window.setStatusBarColor(0);
}
}
/**
* 进入首页
*/
public static void enterHomePage(Context context){
ActivityManager.getInstance().popAllActivity();
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
if(context instanceof Activity){
((Activity)context).finish();
}
}
/**
* 进入登录页
* @param context 上下文
*/
public static void enterLoginPage(Context context){
enterLoginPage(context, false);
}
/**
* 进入登录页
* @param context 上下文
* @param isFinish 是否关闭当前 Activity
*/
public static void enterLoginPage(Context context, boolean isFinish){
ActivityManager.getInstance().popAllActivity();
Intent intent = new Intent(context, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if(!(context instanceof Activity)){
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
if(isFinish && context instanceof Activity){
((Activity)context).finish();
}
}
public static ColorStateList getColorList(int resId) {
return ContextCompat.getColorStateList(UiUtils.getContext(), resId);
}
public static void setCompoundDrawables(TextView textView, Drawable left, Drawable top, Drawable right, Drawable bottom){
textView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
}
/**
* 获取列表为空时显示的 Empty View
* @return 默认 Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView){
return getEmptyView(context, recyclerView, null, -1);
}
/**
* 获取列表为空时显示的 Empty View
* @param emptyText 提示文字
* @return Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView, String emptyText){
return getEmptyView(context, recyclerView, emptyText, -1);
}
/**
* 获取列表为空时显示的 Empty View
* @param emptyText 提示文字
* @param emptyImgId 图片
* @return Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView, String emptyText, int emptyImgId){
View emptyView = LayoutInflater.from(context).inflate(R.layout.view_empty, (ViewGroup) recyclerView.getParent(), false);
if(emptyText != null){
((TextView)emptyView.findViewById(R.id.txt_empty)).setText(emptyText);
}
if(emptyImgId != -1){
((ImageView)emptyView.findViewById(R.id.img_empty)).setImageResource(emptyImgId);
}
return emptyView;
}
/**
* 通过场景名获取场景资源图片 id
* @param scene 场景名称
* @return 场景资源图片 id
*/
public static int getSceneImageResIdByName(String scene){
switch (scene){
case "日常":
return R.mipmap.book_scene1;
case "校园":
return R.mipmap.book_scene2;
case "生意":
return R.mipmap.book_scene3;
case "家庭":
return R.mipmap.book_scene4;
case "旅行":
return R.mipmap.book_scene5;
case "装修":
return R.mipmap.book_scene6;
case "结婚":
return R.mipmap.book_scene7;
default:
return R.mipmap.book_scene1;
}
}
/** 显示不带 null 的字符 */
public static String show(String text){
return text != null ? text : "";
}
/**
* 根据自定义属性获取对应颜色值.
* @param context 上下文
* @param attrs 自定义属性
* @param defColor 默认颜色
* @return 颜色
*/
public static int getColor(Context context, int attrs, int defColor){
int[] customAttrs = {attrs};
TypedArray a = context.obtainStyledAttributes(customAttrs);
int color = a.getColor(0, defColor);
a.recycle();
return color;
}
/**
* 根据自定义属性获取对应资源 id.
* @param context 上下文
* @param attrs 自定义属性
* @param defId 默认 id
* @return 资源 id
*/
public static int getResourceId(Context context, int attrs, int defId){
int[] customAttrs = {attrs};
TypedArray a = context.obtainStyledAttributes(customAttrs);
int id = a.getResourceId(0, defId);
a.recycle();
return id;
}
}
| Airsaid/AccountBook | app/src/main/java/com/github/airsaid/accountbook/util/UiUtils.java | 2,172 | /**
* 进入首页
*/ | block_comment | zh-cn | package com.github.airsaid.accountbook.util;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import com.github.airsaid.accountbook.mvp.main.MainActivity;
import com.github.airsaid.accountbook.R;
import com.github.airsaid.accountbook.base.BaseApplication;
import com.github.airsaid.accountbook.mvp.login.LoginActivity;
/**
* Created by zhouyou on 2016/6/27.
* Class desc: ui 操作相关封装
*/
public class UiUtils {
/**
* 获取上下文
*/
public static Context getContext() {
return BaseApplication.getContext();
}
/**
* 获取资源操作类
*/
public static Resources getResources() {
return getContext().getResources();
}
/**
* 获取字符串资源
*
* @param id 资源id
* @return 字符串
*/
public static String getString(int id) {
return getResources().getString(id);
}
/**
* 获取字符串数组资源
*
* @param id 资源id
* @return 字符串数组
*/
public static String[] getStringArray(int id) {
return getResources().getStringArray(id);
}
/**
* 获取颜色资源
*/
public static int getColor(int id) {
return ContextCompat.getColor(getContext(), id);
}
/**
* 获取颜色资源
*
* @param id 资源id
* @param theme 样式
* @return
*/
public static int getColor(int id, Resources.Theme theme) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getResources().getColor(id, theme);
}
return getResources().getColor(id);
}
/**
* 获取drawable资源
*
* @param id 资源id
* @return
*/
public static Drawable getDrawable(int id) {
return ContextCompat.getDrawable(getContext(), id);
}
/**
* 通过图片名称获取图片资源 id
* @param imageName 图片名称
* @return 图片资源 id
*/
public static int getImageResIdByName(String imageName){
return getResources().getIdentifier(imageName, "mipmap"
, AppUtils.getPackageName());
}
/**
* 加载布局(使用View方式)
*
* @param resource 布局资源id
* @return View
*/
public static View inflate(int resource) {
return View.inflate(getContext(), resource, null);
}
/**
* 检查输入的内容是否为空
*/
public static boolean checkEmpty(EditText editText) {
if(TextUtils.isEmpty(editText.getText().toString())){
ToastUtils.show(UiUtils.getContext(), UiUtils.getString(R.string.hint_empty));
return true;
}
return false;
}
/**
* 设置透明状态栏
* @param activity
*/
public static void setStatusBar(Activity activity) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
// 对于4.4以上5.0以下版本,设置透明状态栏
Window window = activity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}else if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
// 5.0及以上版本,设置透明状态栏
Window window = activity.getWindow();
// 清理4.4Flag
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
// 添加标志位
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// 设置为透明
window.setStatusBarColor(0);
}
}
/**
* 进入首 <SUF>*/
public static void enterHomePage(Context context){
ActivityManager.getInstance().popAllActivity();
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
if(context instanceof Activity){
((Activity)context).finish();
}
}
/**
* 进入登录页
* @param context 上下文
*/
public static void enterLoginPage(Context context){
enterLoginPage(context, false);
}
/**
* 进入登录页
* @param context 上下文
* @param isFinish 是否关闭当前 Activity
*/
public static void enterLoginPage(Context context, boolean isFinish){
ActivityManager.getInstance().popAllActivity();
Intent intent = new Intent(context, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if(!(context instanceof Activity)){
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
context.startActivity(intent);
if(isFinish && context instanceof Activity){
((Activity)context).finish();
}
}
public static ColorStateList getColorList(int resId) {
return ContextCompat.getColorStateList(UiUtils.getContext(), resId);
}
public static void setCompoundDrawables(TextView textView, Drawable left, Drawable top, Drawable right, Drawable bottom){
textView.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
}
/**
* 获取列表为空时显示的 Empty View
* @return 默认 Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView){
return getEmptyView(context, recyclerView, null, -1);
}
/**
* 获取列表为空时显示的 Empty View
* @param emptyText 提示文字
* @return Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView, String emptyText){
return getEmptyView(context, recyclerView, emptyText, -1);
}
/**
* 获取列表为空时显示的 Empty View
* @param emptyText 提示文字
* @param emptyImgId 图片
* @return Empty View
*/
public static View getEmptyView(Context context, RecyclerView recyclerView, String emptyText, int emptyImgId){
View emptyView = LayoutInflater.from(context).inflate(R.layout.view_empty, (ViewGroup) recyclerView.getParent(), false);
if(emptyText != null){
((TextView)emptyView.findViewById(R.id.txt_empty)).setText(emptyText);
}
if(emptyImgId != -1){
((ImageView)emptyView.findViewById(R.id.img_empty)).setImageResource(emptyImgId);
}
return emptyView;
}
/**
* 通过场景名获取场景资源图片 id
* @param scene 场景名称
* @return 场景资源图片 id
*/
public static int getSceneImageResIdByName(String scene){
switch (scene){
case "日常":
return R.mipmap.book_scene1;
case "校园":
return R.mipmap.book_scene2;
case "生意":
return R.mipmap.book_scene3;
case "家庭":
return R.mipmap.book_scene4;
case "旅行":
return R.mipmap.book_scene5;
case "装修":
return R.mipmap.book_scene6;
case "结婚":
return R.mipmap.book_scene7;
default:
return R.mipmap.book_scene1;
}
}
/** 显示不带 null 的字符 */
public static String show(String text){
return text != null ? text : "";
}
/**
* 根据自定义属性获取对应颜色值.
* @param context 上下文
* @param attrs 自定义属性
* @param defColor 默认颜色
* @return 颜色
*/
public static int getColor(Context context, int attrs, int defColor){
int[] customAttrs = {attrs};
TypedArray a = context.obtainStyledAttributes(customAttrs);
int color = a.getColor(0, defColor);
a.recycle();
return color;
}
/**
* 根据自定义属性获取对应资源 id.
* @param context 上下文
* @param attrs 自定义属性
* @param defId 默认 id
* @return 资源 id
*/
public static int getResourceId(Context context, int attrs, int defId){
int[] customAttrs = {attrs};
TypedArray a = context.obtainStyledAttributes(customAttrs);
int id = a.getResourceId(0, defId);
a.recycle();
return id;
}
}
| 0 | 1,923 | 10 | 2,172 | 8 | 2,303 | 10 | 2,172 | 8 | 2,806 | 12 | false | false | false | false | false | true |
36827_6 | package com.huawei;
import java.util.Collection;
import java.util.HashMap;
public class Road implements Comparable<Road> {
private int roadId;
private int length;
private int oriLength;
private int speed;
private int channel;
private Cross from;
private int fromId;
private Cross to;
private int toId;
private int isDuplex;
private Car[][] fromTo;
private Car[][] toFrom;
public int fromToLoad=0;//道路负载
public int toFromLoad=0;
public int planFromToLoad=0;//道路负载
public int planToFromLoad=0;
public int fromToLength=0;
public int toFromLength=0;
Road(int roadId , int length , int speed , int channel , int fromId , int toId , int isDuplex){
this.setRoadId(roadId);
this.setLength(length);
this.setSpeed(speed);
this.setChannel(channel);
this.setFromId(fromId);
this.setToId(toId);
this.setIsDuplex(isDuplex);
this.setFromTo();
this.setToFrom();
}
public void setLoadFator(double factor,boolean dir){
if(dir)
this.fromToLength*=factor;
else
this.toFromLength*=factor;
}
public int getFromToLoad(){
return fromToLoad;
}
public int getToFromLoad(){
return toFromLoad;
}
public int getLoadByNextCross(Cross nextCross){
if(nextCross==to)
return fromToLoad;
else
return toFromLoad;
}
public void addLoad(Car[][] roadInfo){
if(roadInfo==fromTo)
fromToLoad++;
else
toFromLoad++;
}
public void minLoad(Car[][] roadInfo){
if(roadInfo==fromTo)
fromToLoad--;
else
toFromLoad--;
}
public void addPlanLoad(Cross lastCross){
if(lastCross==from)
planFromToLoad++;
else
planToFromLoad++;
}
public void minPlanLoad(Cross lastCross){
if(lastCross==from)
planFromToLoad--;
else
planToFromLoad--;
}
public Car[][] getIntoFromCross(Cross currentCross){
if(currentCross==to)
return fromTo;
else {
// if(this.isDuplex==0)
// System.out.println("出发车辆道路错误,不存在该方向道路。");
return toFrom;
}
}
public Car[][] getOutFromCross(Cross currentCross){
if(currentCross==from)
return fromTo;
else {
// if(this.isDuplex==0)
// System.out.println("出发车辆道路错误,不存在该方向道路。");
return toFrom;
}
}
public Cross getNextCross(Cross currentCross){
if(currentCross==this.from)
return to;
else
return from;
}
public Cross getCrossByNextRoad(Road nextRoad){
if(this.to==nextRoad.from||this.to==nextRoad.to)
return to;
else
return from;
}
public void updateFromAndTo(HashMap<Integer,Cross> crosses){
setFrom(crosses.get(this.fromId));
setTo((crosses.get(this.toId)));
}
public int getRoadId() {
return roadId;
}
public void setRoadId(int roadId) {
this.roadId = roadId;
}
public int getLength() {
return length;
}
public int getLoadLength(Cross currentCross){
if(currentCross==from)
return fromToLength;
else
return toFromLength;
}
public void setLength(int length) {
this.length = length;
this.oriLength=length;
this.fromToLength=length;
this.toFromLength=length;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getChannel() {
return channel;
}
public void setChannel(int channel) {
this.channel = channel;
}
public int getFromId() {
return fromId;
}
public void setFromId(int fromId) {
this.fromId = fromId;
}
public int getToId() {
return toId;
}
public void setToId(int toId) {
this.toId = toId;
}
public int getIsDuplex() {
return isDuplex;
}
public void setIsDuplex(int isDuplex) {
this.isDuplex = isDuplex;
}
public void setFrom(Cross from) {
this.from = from;
}
public Cross getFrom(){
return this.from;
}
public void setTo(Cross to) {
this.to = to;
}
public Cross getTo(){
return this.to;
}
public Car[][] getFromTo() {
return fromTo;
}
public void setFromTo() {
this.fromTo = new Car[this.channel][this.length];
}
public Car[][] getToFrom() {
return toFrom;
}
public void setToFrom() {
if(this.isDuplex==1)
this.toFrom=new Car[this.channel][this.length];
else
this.toFrom=null;
}
//输出道路负载,n:道路负载最高为n米内一辆车
public void printLoad(double n){
System.out.println("道路:"+roadId+" 负载要求:"+length*channel/n + "当前道路(正)负载:"+fromToLoad + "当前道路(反)负载:"+toFromLoad);
}
//通过当前路口获取道路负载
public int getLoadByCurrentCross(Cross currentCross){
if(currentCross==from)
return fromToLoad;
else
return toFromLoad;
}
/*打印车道上车辆信息*/
public void printRoad(Cross currentCross){
if(currentCross==from && isDuplex==1){//第一种情况
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=length-1;i>=0;i--){
if(fromTo[j][i]==null){
System.out.print("00000<--");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
System.out.println(" toFrom:");
for(int j=0;j<channel;j++){/*打印toFrom*/
for(int i=0;i<length;i++){
if(toFrom[j][i]==null){
System.out.print("00000-->");
}
else{
if(toFrom[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(toFrom[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
else if(currentCross==from && isDuplex==0){/*打印toFrom*/
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=length-1;i>=0;i--){
if(fromTo[j][i]==null){
System.out.print("000000<--");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
if(currentCross==to && isDuplex==1){//第二种情况
System.out.println(" toFrom: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印toFrom*/
for(int i=length-1;i>=0;i--){
if(toFrom[j][i]==null){
System.out.print("000000<--");
}
else{
if(toFrom[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(toFrom[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
System.out.println(" fromTo:");
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=0;i<length;i++){
if(fromTo[j][i]==null){
System.out.print("000000-->");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
else if(currentCross==to && isDuplex==0){/*打印toFrom*/
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=0;i<length;i++){
if(fromTo[j][i]==null){
System.out.print("000000-->");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
}
@Override
public int compareTo(Road o) {
if(this.roadId<o.getRoadId())
return -1;
else if(this.roadId>o.getRoadId())
return 1;
else
return 0;
}
}
| Aka-me/Huawei-CodeCraft2019 | Road.java | 2,910 | //输出道路负载,n:道路负载最高为n米内一辆车
| line_comment | zh-cn | package com.huawei;
import java.util.Collection;
import java.util.HashMap;
public class Road implements Comparable<Road> {
private int roadId;
private int length;
private int oriLength;
private int speed;
private int channel;
private Cross from;
private int fromId;
private Cross to;
private int toId;
private int isDuplex;
private Car[][] fromTo;
private Car[][] toFrom;
public int fromToLoad=0;//道路负载
public int toFromLoad=0;
public int planFromToLoad=0;//道路负载
public int planToFromLoad=0;
public int fromToLength=0;
public int toFromLength=0;
Road(int roadId , int length , int speed , int channel , int fromId , int toId , int isDuplex){
this.setRoadId(roadId);
this.setLength(length);
this.setSpeed(speed);
this.setChannel(channel);
this.setFromId(fromId);
this.setToId(toId);
this.setIsDuplex(isDuplex);
this.setFromTo();
this.setToFrom();
}
public void setLoadFator(double factor,boolean dir){
if(dir)
this.fromToLength*=factor;
else
this.toFromLength*=factor;
}
public int getFromToLoad(){
return fromToLoad;
}
public int getToFromLoad(){
return toFromLoad;
}
public int getLoadByNextCross(Cross nextCross){
if(nextCross==to)
return fromToLoad;
else
return toFromLoad;
}
public void addLoad(Car[][] roadInfo){
if(roadInfo==fromTo)
fromToLoad++;
else
toFromLoad++;
}
public void minLoad(Car[][] roadInfo){
if(roadInfo==fromTo)
fromToLoad--;
else
toFromLoad--;
}
public void addPlanLoad(Cross lastCross){
if(lastCross==from)
planFromToLoad++;
else
planToFromLoad++;
}
public void minPlanLoad(Cross lastCross){
if(lastCross==from)
planFromToLoad--;
else
planToFromLoad--;
}
public Car[][] getIntoFromCross(Cross currentCross){
if(currentCross==to)
return fromTo;
else {
// if(this.isDuplex==0)
// System.out.println("出发车辆道路错误,不存在该方向道路。");
return toFrom;
}
}
public Car[][] getOutFromCross(Cross currentCross){
if(currentCross==from)
return fromTo;
else {
// if(this.isDuplex==0)
// System.out.println("出发车辆道路错误,不存在该方向道路。");
return toFrom;
}
}
public Cross getNextCross(Cross currentCross){
if(currentCross==this.from)
return to;
else
return from;
}
public Cross getCrossByNextRoad(Road nextRoad){
if(this.to==nextRoad.from||this.to==nextRoad.to)
return to;
else
return from;
}
public void updateFromAndTo(HashMap<Integer,Cross> crosses){
setFrom(crosses.get(this.fromId));
setTo((crosses.get(this.toId)));
}
public int getRoadId() {
return roadId;
}
public void setRoadId(int roadId) {
this.roadId = roadId;
}
public int getLength() {
return length;
}
public int getLoadLength(Cross currentCross){
if(currentCross==from)
return fromToLength;
else
return toFromLength;
}
public void setLength(int length) {
this.length = length;
this.oriLength=length;
this.fromToLength=length;
this.toFromLength=length;
}
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getChannel() {
return channel;
}
public void setChannel(int channel) {
this.channel = channel;
}
public int getFromId() {
return fromId;
}
public void setFromId(int fromId) {
this.fromId = fromId;
}
public int getToId() {
return toId;
}
public void setToId(int toId) {
this.toId = toId;
}
public int getIsDuplex() {
return isDuplex;
}
public void setIsDuplex(int isDuplex) {
this.isDuplex = isDuplex;
}
public void setFrom(Cross from) {
this.from = from;
}
public Cross getFrom(){
return this.from;
}
public void setTo(Cross to) {
this.to = to;
}
public Cross getTo(){
return this.to;
}
public Car[][] getFromTo() {
return fromTo;
}
public void setFromTo() {
this.fromTo = new Car[this.channel][this.length];
}
public Car[][] getToFrom() {
return toFrom;
}
public void setToFrom() {
if(this.isDuplex==1)
this.toFrom=new Car[this.channel][this.length];
else
this.toFrom=null;
}
//输出 <SUF>
public void printLoad(double n){
System.out.println("道路:"+roadId+" 负载要求:"+length*channel/n + "当前道路(正)负载:"+fromToLoad + "当前道路(反)负载:"+toFromLoad);
}
//通过当前路口获取道路负载
public int getLoadByCurrentCross(Cross currentCross){
if(currentCross==from)
return fromToLoad;
else
return toFromLoad;
}
/*打印车道上车辆信息*/
public void printRoad(Cross currentCross){
if(currentCross==from && isDuplex==1){//第一种情况
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=length-1;i>=0;i--){
if(fromTo[j][i]==null){
System.out.print("00000<--");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
System.out.println(" toFrom:");
for(int j=0;j<channel;j++){/*打印toFrom*/
for(int i=0;i<length;i++){
if(toFrom[j][i]==null){
System.out.print("00000-->");
}
else{
if(toFrom[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(toFrom[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
else if(currentCross==from && isDuplex==0){/*打印toFrom*/
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=length-1;i>=0;i--){
if(fromTo[j][i]==null){
System.out.print("000000<--");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
if(currentCross==to && isDuplex==1){//第二种情况
System.out.println(" toFrom: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印toFrom*/
for(int i=length-1;i>=0;i--){
if(toFrom[j][i]==null){
System.out.print("000000<--");
}
else{
if(toFrom[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(toFrom[j][i].getCarId()+"<--");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
System.out.println(" fromTo:");
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=0;i<length;i++){
if(fromTo[j][i]==null){
System.out.print("000000-->");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
else if(currentCross==to && isDuplex==0){/*打印toFrom*/
System.out.println(" fromTo: 道路:"+roadId);
for(int j=0;j<channel;j++){/*打印fromTo*/
for(int i=0;i<length;i++){
if(fromTo[j][i]==null){
System.out.print("000000-->");
}
else{
if(fromTo[j][i].getPriority())
System.out.print("*");
else
System.out.print("~");
System.out.print(fromTo[j][i].getCarId()+"-->");
}
}
System.out.println(" ("+j+") 路口:"+currentCross.getCrossId());
}
}
}
@Override
public int compareTo(Road o) {
if(this.roadId<o.getRoadId())
return -1;
else if(this.roadId>o.getRoadId())
return 1;
else
return 0;
}
}
| 0 | 2,283 | 17 | 2,904 | 24 | 2,817 | 17 | 2,904 | 24 | 3,669 | 32 | false | false | false | false | false | true |
56685_25 | package pers.ruchuby.learning.basic;
import java.util.Random;
import java.util.Scanner;
public class BasicGrammar {
public static void variable() {
//变量类型
// 整数类型
double a = 6.66; //默认用double 8个字节
float aa = 6.6f; //float要加f或F 4个字节
int b = 6;
byte e = 127; // -128~127
// String为引用数据类型
String c;
c = "来日等不过方长";
char d = 65; //字符 A
//空字符 中间用空格
System.out.println(' ');
//布尔类型
boolean flag = true;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
public static void typeConversion() {
// 自动类型转换
byte a = 10;
int b = a; //自动从小范围转换为大范围 内存中在左侧补充0
float c = b; // int to float(double也可以)
System.out.println(c);
double d = a + b + 2.3; //表达式 自动提升
// byte char 等类型在运算时都会转化为int
// 基本与C#一致
}
public static void operator() {
// + - * / %取余
//注意int相除的时候还是int
System.out.println(3 / 2);
System.out.println(3 * 1.0 / 2); //这样才能得到double
// 能计算就按原类型计算,否则按字符串合并
System.out.println(10 + 'a'); // 107
System.out.println('a' + "你好" + 10); // a你好10
// ++ -- 前后自增 自减
// += -= *= /= %=
//如a+=b 等同于 a = (a的类型) a+b 包含了强制类型转换
// 关系运算符 == != >= <=等等
//位运算符 位运算符判断时左右都会运算
System.out.println(true | false); // 或
System.out.println(false & true);// 与
System.out.println(!true); //非
System.out.println(true ^ true); //异或 两者不等则为true
// 逻辑运算符 ! && ||
//三元运算符
System.out.println(1 > 2 ? "1>2为真" : "1>2为假");
/*
运算符优先级 与c++有细微的差别
1. ()之类括号最高
2. ! ++ --
2. 加减乘除之类的
3. 左右移运算
4. 逻辑判断
4. 逻辑位运算
5. 逻辑运算(&& ||)
6. += -=之类
*/
}
public static void userInput() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入数字");
int a = sc.nextInt();
System.out.println(a);
System.out.println("请输入字符串");
String s = sc.next();
System.out.println(s);
}
public static void processControl() {
int a = 10;
int b = 20;
// if else
if (a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
// switch
switch (a) {
case 10:
System.out.println("a=10");
break;
default:
System.out.println("默认");
}
//for
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
//while
int i = 0;
while (true) {
System.out.println(i);
i++;
if (i > 3) break;
}
// do while 基本差不多
//死循环写法
// while (true)
// for (; ; )
// do{}while (true)
//随机数
Random r = new Random();
System.out.println(r.nextInt(100)); // 0-99
System.out.println(r.nextInt(100) + 10); // 10-109
}
public static void arr() {
//静态数组 就和c++差不多
// int[3] a = new int[]{1,2,3};
int[] a = {1, 2, 3, 4}; //简化写法(动态初始化)
// 整数类型的默认值为0 String 的为 null
int[] b = new int[10]; //但此时不能 {1,2,3,4}来赋值 (静态初始化)
//冒泡排序
int arr[] = {13, 51, 12, 48, 36};
//循环长度-1轮
for (int i = 0; i < arr.length - 1; i++) {
//没轮判断 长度-轮序号(从0开始)-1
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[i] < arr[j]) {
int tmp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = tmp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(i);
}
}
}
| AkiChase/Java-Learning | src/pers/ruchuby/learning/basic/BasicGrammar.java | 1,356 | //位运算符 位运算符判断时左右都会运算 | line_comment | zh-cn | package pers.ruchuby.learning.basic;
import java.util.Random;
import java.util.Scanner;
public class BasicGrammar {
public static void variable() {
//变量类型
// 整数类型
double a = 6.66; //默认用double 8个字节
float aa = 6.6f; //float要加f或F 4个字节
int b = 6;
byte e = 127; // -128~127
// String为引用数据类型
String c;
c = "来日等不过方长";
char d = 65; //字符 A
//空字符 中间用空格
System.out.println(' ');
//布尔类型
boolean flag = true;
System.out.println(a);
System.out.println(b);
System.out.println(c);
System.out.println(d);
}
public static void typeConversion() {
// 自动类型转换
byte a = 10;
int b = a; //自动从小范围转换为大范围 内存中在左侧补充0
float c = b; // int to float(double也可以)
System.out.println(c);
double d = a + b + 2.3; //表达式 自动提升
// byte char 等类型在运算时都会转化为int
// 基本与C#一致
}
public static void operator() {
// + - * / %取余
//注意int相除的时候还是int
System.out.println(3 / 2);
System.out.println(3 * 1.0 / 2); //这样才能得到double
// 能计算就按原类型计算,否则按字符串合并
System.out.println(10 + 'a'); // 107
System.out.println('a' + "你好" + 10); // a你好10
// ++ -- 前后自增 自减
// += -= *= /= %=
//如a+=b 等同于 a = (a的类型) a+b 包含了强制类型转换
// 关系运算符 == != >= <=等等
//位运 <SUF>
System.out.println(true | false); // 或
System.out.println(false & true);// 与
System.out.println(!true); //非
System.out.println(true ^ true); //异或 两者不等则为true
// 逻辑运算符 ! && ||
//三元运算符
System.out.println(1 > 2 ? "1>2为真" : "1>2为假");
/*
运算符优先级 与c++有细微的差别
1. ()之类括号最高
2. ! ++ --
2. 加减乘除之类的
3. 左右移运算
4. 逻辑判断
4. 逻辑位运算
5. 逻辑运算(&& ||)
6. += -=之类
*/
}
public static void userInput() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入数字");
int a = sc.nextInt();
System.out.println(a);
System.out.println("请输入字符串");
String s = sc.next();
System.out.println(s);
}
public static void processControl() {
int a = 10;
int b = 20;
// if else
if (a > b) {
System.out.println(a);
} else {
System.out.println(b);
}
// switch
switch (a) {
case 10:
System.out.println("a=10");
break;
default:
System.out.println("默认");
}
//for
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
//while
int i = 0;
while (true) {
System.out.println(i);
i++;
if (i > 3) break;
}
// do while 基本差不多
//死循环写法
// while (true)
// for (; ; )
// do{}while (true)
//随机数
Random r = new Random();
System.out.println(r.nextInt(100)); // 0-99
System.out.println(r.nextInt(100) + 10); // 10-109
}
public static void arr() {
//静态数组 就和c++差不多
// int[3] a = new int[]{1,2,3};
int[] a = {1, 2, 3, 4}; //简化写法(动态初始化)
// 整数类型的默认值为0 String 的为 null
int[] b = new int[10]; //但此时不能 {1,2,3,4}来赋值 (静态初始化)
//冒泡排序
int arr[] = {13, 51, 12, 48, 36};
//循环长度-1轮
for (int i = 0; i < arr.length - 1; i++) {
//没轮判断 长度-轮序号(从0开始)-1
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[i] < arr[j]) {
int tmp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = tmp;
}
}
}
for (int i = 0; i < arr.length; i++) {
System.out.println(i);
}
}
}
| 0 | 1,296 | 14 | 1,356 | 15 | 1,433 | 13 | 1,356 | 15 | 1,739 | 19 | false | false | false | false | false | true |