file_id
stringlengths 5
9
| content
stringlengths 24
16.1k
| repo
stringlengths 8
84
| path
stringlengths 7
167
| token_length
int64 18
3.48k
| original_comment
stringlengths 5
2.57k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 11
16.1k
| excluded
bool 1
class | file-tokens-Qwen/Qwen2-7B
int64 14
3.27k
| comment-tokens-Qwen/Qwen2-7B
int64 2
1.74k
| file-tokens-bigcode/starcoder2-7b
int64 18
3.48k
| comment-tokens-bigcode/starcoder2-7b
int64 2
2.11k
| file-tokens-google/codegemma-7b
int64 14
3.57k
| comment-tokens-google/codegemma-7b
int64 2
1.75k
| file-tokens-ibm-granite/granite-8b-code-base
int64 18
3.48k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 2
2.11k
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 31
3.93k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
2.71k
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
64753_3 | package cn.bc.remoting.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
/**
* Created by dragon on 2015/1/22.
*
* @ref http://www.ibm.com/developerworks/cn/java/j-lo-servlet30/
*/
@WebServlet(value = {"/asyncdemo"}
// 不指定默认为类的全名
//, name = "cn.bc.remoting.demo.AsyncDemoServlet"
// 异步支持
, asyncSupported = true
// 初始化参数
, initParams = {@WebInitParam(name = "author", value = "dragon")}
)
public class AsyncDemoServlet extends HttpServlet {
private static Logger logger = LoggerFactory.getLogger(AsyncDemoServlet.class);
@Override
public void init(ServletConfig config) throws ServletException {
logger.debug("author={}", config.getInitParameter("author"));
super.init(config);
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
logger.debug("doGet start {}", new Date());
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.println("进入Servlet的时间:" + new Date() + ".");
out.flush();
// 在子线程中执行业务调用,并由其负责输出响应,主线程退出
AsyncContext ctx = req.startAsync();
ctx.addListener(new DemoAsyncListener());// 监听异步处理的进展
new Thread(new DemoRunable(ctx)).start();
out.println("结束Servlet的时间:" + new Date() + ".");
out.flush();
logger.debug("doGet end {}", new Date());
req.getSession().invalidate();
logger.debug("session invalidate");
}
public class DemoRunable implements Runnable {
private AsyncContext ctx = null;
public DemoRunable(AsyncContext ctx) {
this.ctx = ctx;
}
public void run() {
logger.debug("DemoRunable start {}", new Date());
try {
//等待十秒钟,以模拟业务方法的执行
Thread.sleep(1000);
PrintWriter out = ctx.getResponse().getWriter();
out.println("业务处理完毕的时间:" + new Date() + ".");
out.flush();
ctx.complete();
} catch (Exception e) {
e.printStackTrace();
}
logger.debug("DemoRunable end {}", new Date());
}
}
public class DemoAsyncListener implements AsyncListener {
@Override
public void onComplete(AsyncEvent event) throws IOException {
logger.debug("DemoAsyncListener onComplete {}", new Date());
}
@Override
public void onTimeout(AsyncEvent event) throws IOException {
}
@Override
public void onError(AsyncEvent event) throws IOException {
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
// ? 测试结果:没有执行
logger.debug("DemoAsyncListener onStartAsync {}", new Date());
}
}
} | bcsoft/bc-framework | bc-remoting-server/src/main/java/cn/bc/remoting/demo/AsyncDemoServlet.java | 773 | // 异步支持 | line_comment | zh-cn | package cn.bc.remoting.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.*;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
/**
* Created by dragon on 2015/1/22.
*
* @ref http://www.ibm.com/developerworks/cn/java/j-lo-servlet30/
*/
@WebServlet(value = {"/asyncdemo"}
// 不指定默认为类的全名
//, name = "cn.bc.remoting.demo.AsyncDemoServlet"
// 异步 <SUF>
, asyncSupported = true
// 初始化参数
, initParams = {@WebInitParam(name = "author", value = "dragon")}
)
public class AsyncDemoServlet extends HttpServlet {
private static Logger logger = LoggerFactory.getLogger(AsyncDemoServlet.class);
@Override
public void init(ServletConfig config) throws ServletException {
logger.debug("author={}", config.getInitParameter("author"));
super.init(config);
}
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
logger.debug("doGet start {}", new Date());
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out = resp.getWriter();
out.println("进入Servlet的时间:" + new Date() + ".");
out.flush();
// 在子线程中执行业务调用,并由其负责输出响应,主线程退出
AsyncContext ctx = req.startAsync();
ctx.addListener(new DemoAsyncListener());// 监听异步处理的进展
new Thread(new DemoRunable(ctx)).start();
out.println("结束Servlet的时间:" + new Date() + ".");
out.flush();
logger.debug("doGet end {}", new Date());
req.getSession().invalidate();
logger.debug("session invalidate");
}
public class DemoRunable implements Runnable {
private AsyncContext ctx = null;
public DemoRunable(AsyncContext ctx) {
this.ctx = ctx;
}
public void run() {
logger.debug("DemoRunable start {}", new Date());
try {
//等待十秒钟,以模拟业务方法的执行
Thread.sleep(1000);
PrintWriter out = ctx.getResponse().getWriter();
out.println("业务处理完毕的时间:" + new Date() + ".");
out.flush();
ctx.complete();
} catch (Exception e) {
e.printStackTrace();
}
logger.debug("DemoRunable end {}", new Date());
}
}
public class DemoAsyncListener implements AsyncListener {
@Override
public void onComplete(AsyncEvent event) throws IOException {
logger.debug("DemoAsyncListener onComplete {}", new Date());
}
@Override
public void onTimeout(AsyncEvent event) throws IOException {
}
@Override
public void onError(AsyncEvent event) throws IOException {
}
@Override
public void onStartAsync(AsyncEvent event) throws IOException {
// ? 测试结果:没有执行
logger.debug("DemoAsyncListener onStartAsync {}", new Date());
}
}
} | false | 677 | 5 | 773 | 4 | 825 | 4 | 773 | 4 | 981 | 10 | false | false | false | false | false | true |
33530_7 | import apk.WalleSignUtil;
import beansoft.swing.OptionPane;
import beansoft.util.FileOperate;
import config.SavedState;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Theme;
import org.fife.ui.rtextarea.RTextScrollPane;
import util.ApkFileFilter;
import util.OSXSupport;
import util.StringUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 瓦力安卓渠道打包神器 界面版 by https://github.com/beansoftapp
* Created by beansoft on 2017/1/18.
*/
public class WalleAPKSignerGUI {
private JTextField textFieldSourceAPK;
private JPanel contentPane;
private JButton genButton;
private JButton exitButton;
private JLabel statusBar;
private JProgressBar progressBar;
private JButton checkButton;
private JButton browseButton;
private JButton settingButton;
private JScrollPane channelsPane;
private JPanel channelListPane;
private JFileChooser chooser;
private RTextScrollPane scrollPane;
private RSyntaxTextArea textArea;
private static ExecutorService threadPool = Executors.newFixedThreadPool(4);
private int totalFinished = 0;
public WalleAPKSignerGUI() {
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
genButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doChannel();
}
});
checkButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doCheck();
}
});
browseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
browseInputApk();
}
});
initUI();
settingButton.setAction(new PreferencesAction());
// Init directorys
FileOperate op = new FileOperate();
op.newFolder("输出渠道包");
op.newFolder("conf");
}
private void initUI() {
textArea = createTextArea();
scrollPane = new RTextScrollPane(textArea, true);
channelsPane.getViewport().add(scrollPane);
SavedState savedState = SavedState.getInstance();
textFieldSourceAPK.setText(savedState.lastFile);
}
/**
* Creates the text area for this application.
*
* @return The text area.
*/
private RSyntaxTextArea createTextArea() {
final RSyntaxTextArea textArea = new RSyntaxTextArea(25, 70);
textArea.setTabSize(3);
textArea.setCaretPosition(0);
textArea.setHighlightCurrentLine(true);
textArea.requestFocusInWindow();
textArea.setMarkOccurrences(true);
textArea.setCodeFoldingEnabled(true);
textArea.setClearWhitespaceLinesEnabled(false);
// textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_PROPERTIES_FILE);
SavedState savedState = SavedState.getInstance();
if(savedState.channelList != null) {
textArea.setText(savedState.channelList);
}
try {
InputStream in = getClass().getResourceAsStream("/dark.xml");
Theme theme = Theme.load(in);
theme.apply(textArea);
} catch (IOException ioe) {
ioe.printStackTrace();
}
textArea.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
saveChanneList();
}
});
return textArea;
}
// 变化时保存渠道列表
private void saveChanneList() {
SavedState savedState = SavedState.getInstance();
if(! (savedState.channelList !=null && textArea.getText().equals(savedState.channelList)) ) {
savedState.channelList = textArea.getText();
savedState.save();
}
}
// 浏览输入APK
private void browseInputApk() {
SavedState savedState = SavedState.getInstance();
initFileChooser(savedState.lastFile);
chooser.setDialogTitle("选择需要打包的APK文件");
int returnVal = chooser.showOpenDialog(this.contentPane);
if (returnVal == JFileChooser.APPROVE_OPTION) {
textFieldSourceAPK.setText(chooser.getSelectedFile().getPath());
savedState.lastFile = textFieldSourceAPK.getText();
savedState.save();
}
}
// 初始化文件选择器
private void initFileChooser(String currentFilePath) {
if( chooser == null) {
if(StringUtil.isEmpty(currentFilePath)) {
chooser = new JFileChooser(new File("."));
} else {
File currentFile = new File(currentFilePath);
chooser = new JFileChooser(currentFile);
}
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setFont(new Font("Tahoma", Font.PLAIN, 12));
chooser.setFileFilter(new ApkFileFilter());
chooser.setMultiSelectionEnabled(false);
}
}
// 检查渠道包
protected void doCheck() {
initFileChooser(WalleSignUtil.OUT_DIR);
chooser.setDialogTitle("选择需要验证的APK安装包");
int returnVal = chooser.showDialog(this.contentPane, "验证");
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
String channelName = WalleSignUtil.readChannel(chooser.getSelectedFile());
OptionPane.showInfoMessageDialog(contentPane, "渠道名称为:\n" + channelName, "检验成功");
return;
} catch (Exception ex) {
ex.printStackTrace();
}
OptionPane.showErrorMessageDialog(contentPane, "渠道名称无法读取, 请检查", "检验失败");
}
}
// 执行APK渠道打包工作
private void doChannel() {
final String inputApk = textFieldSourceAPK.getText();
if(StringUtil.isEmpty(inputApk)) {
textFieldSourceAPK.setBorder(BorderFactory.createLineBorder(Color.RED));
OptionPane.showErrorMessageDialog(this.contentPane, "请输入源APK",
"提示");
return;
} else {
textFieldSourceAPK.setBorder(null);
}
String channel = textArea.getText();
if(StringUtil.isEmpty(channel)) {
textArea.setBorder(BorderFactory.createLineBorder(Color.RED));
OptionPane.showErrorMessageDialog(this.contentPane, "请输入渠道列表",
"提示");
return;
} else {
textArea.setBorder(null);
}
final String fullInputApkPath = inputApk;
File apkFile = new File(fullInputApkPath);
if(!apkFile.exists()) {
OptionPane.showErrorMessageDialog(this.contentPane, "输入APK文件不可用",
"错误");
return;
}
genButton.setEnabled(false);
final String[] channels = channel.split("\\\n");
new Thread() {
public void run() {
doChannelAsync(fullInputApkPath, channels);
}
}.start();
}
// 异步处理生成渠道包
public void doChannelAsync(final String inputApk, String[] channels) {
try {
statusBar.setText("正在生成渠道包...");
OSXSupport.setDockIconBadge("0%");
final int length = channels.length;
totalFinished = 0;
for(int i = 0; i < length; i++) {
String channel = channels[i];
channel = channel.trim();
final String channelF = channel;
threadPool.execute(new Runnable() {
@Override
public void run() {
WalleSignUtil.createSignChannelAPKFile(inputApk, channelF);
totalFinished++;
progressBar.setValue(totalFinished * 100 / length);
statusBar.setText("完成生成渠道包 " + channelF + ".");
OSXSupport.setDockIconBadge((totalFinished * 100 / length) + "%");
// 打包完成
if(totalFinished >= length) {
genButton.setEnabled(true);
OptionPane.showInfoMessageDialog(contentPane, "操作成功",
"恭喜");
statusBar.setText("生成渠道包成功");
try {
Desktop.getDesktop().open(new File(WalleSignUtil.OUT_DIR));
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
OptionPane.showErrorMessageDialog(this.contentPane, "错误详情:\n" + e.getMessage(),
"生成渠道包出错");
}
}
private static JMenuBar createMenuBar() {
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("瓦力渠道包工具");
menu.add(new JMenuItem(new AboutAction()));
menu.add(new JMenuItem(new PreferencesAction()));
menu.add(new JMenuItem(new HomePageAction()) );
menu.addSeparator();
menu.add(new JMenuItem(new QuitAction()));
mb.add(menu);
return mb;
}
private static class AboutAction extends AbstractAction {
public AboutAction() {
putValue(NAME, "关于");
}
public void actionPerformed(ActionEvent e) {
OptionPane.showInfoMessageDialog(null,
"瓦力渠道包工具1.0", "关于");
}
}
// 退出Action
private static class QuitAction extends AbstractAction {
public QuitAction() {
putValue(NAME, "退出");
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private static class HomePageAction extends AbstractAction {
public HomePageAction() {
putValue(NAME, "访问网站&帮助");
}
public void actionPerformed(ActionEvent e) {
try {
Desktop.getDesktop().browse(new URI("https://github.com/beansoftapp/wallegui"));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
// 偏好设置
private static class PreferencesAction extends AbstractAction {
public PreferencesAction() {
putValue(NAME, "偏好设置...");
}
public void actionPerformed(ActionEvent e) {
OptionPane.showInfoMessageDialog(null, "明暗主题风格切换", "TODO");
}
}
public static void main(String[] args) {
System.setProperty("apple.laf.useScreenMenuBar", "true");// 整合Mac菜单
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "瓦力渠道包工具");// 仅Mac自带的Java 6有效
Locale.setDefault(Locale.CHINESE);
try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel("com.bulenkov.darcula.DarculaLaf");
} catch(Exception ex) {
}
JFrame frame = new JFrame("瓦力安卓渠道打包神器 界面版 by https://github.com/beansoftapp");
try {
Image iconImg =
new ImageIcon(WalleAPKSignerGUI.class.getResource("icon/chuck-highlight-image.png")).getImage();
// Application.getApplication().setDockIconImage(iconImg);
OSXSupport.initializeMacOSX(new AboutAction(), new QuitAction(), new PreferencesAction(), iconImg, null);
OSXSupport.setDockIconBadge("瓦力");
frame.setIconImage(iconImg);
} catch (Exception e) {
e.printStackTrace();
}
// if(!OSXSupport.isOSX()) {
frame.getRootPane().setJMenuBar(createMenuBar());
// }
final WalleAPKSignerGUI tool = new WalleAPKSignerGUI();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.out.println(" +++++++ windowClosing ++++++ ");
tool.saveChanneList();
}
});
frame.setContentPane(tool.contentPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);// 最大化显示
frame.setVisible(true);
}
private void createUIComponents() {
// TODO: place custom component creation code here
}
} | beansoft/wallegui | src/WalleAPKSignerGUI.java | 3,008 | // 检查渠道包 | line_comment | zh-cn | import apk.WalleSignUtil;
import beansoft.swing.OptionPane;
import beansoft.util.FileOperate;
import config.SavedState;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.Theme;
import org.fife.ui.rtextarea.RTextScrollPane;
import util.ApkFileFilter;
import util.OSXSupport;
import util.StringUtil;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* 瓦力安卓渠道打包神器 界面版 by https://github.com/beansoftapp
* Created by beansoft on 2017/1/18.
*/
public class WalleAPKSignerGUI {
private JTextField textFieldSourceAPK;
private JPanel contentPane;
private JButton genButton;
private JButton exitButton;
private JLabel statusBar;
private JProgressBar progressBar;
private JButton checkButton;
private JButton browseButton;
private JButton settingButton;
private JScrollPane channelsPane;
private JPanel channelListPane;
private JFileChooser chooser;
private RTextScrollPane scrollPane;
private RSyntaxTextArea textArea;
private static ExecutorService threadPool = Executors.newFixedThreadPool(4);
private int totalFinished = 0;
public WalleAPKSignerGUI() {
exitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
genButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doChannel();
}
});
checkButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
doCheck();
}
});
browseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
browseInputApk();
}
});
initUI();
settingButton.setAction(new PreferencesAction());
// Init directorys
FileOperate op = new FileOperate();
op.newFolder("输出渠道包");
op.newFolder("conf");
}
private void initUI() {
textArea = createTextArea();
scrollPane = new RTextScrollPane(textArea, true);
channelsPane.getViewport().add(scrollPane);
SavedState savedState = SavedState.getInstance();
textFieldSourceAPK.setText(savedState.lastFile);
}
/**
* Creates the text area for this application.
*
* @return The text area.
*/
private RSyntaxTextArea createTextArea() {
final RSyntaxTextArea textArea = new RSyntaxTextArea(25, 70);
textArea.setTabSize(3);
textArea.setCaretPosition(0);
textArea.setHighlightCurrentLine(true);
textArea.requestFocusInWindow();
textArea.setMarkOccurrences(true);
textArea.setCodeFoldingEnabled(true);
textArea.setClearWhitespaceLinesEnabled(false);
// textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_PROPERTIES_FILE);
SavedState savedState = SavedState.getInstance();
if(savedState.channelList != null) {
textArea.setText(savedState.channelList);
}
try {
InputStream in = getClass().getResourceAsStream("/dark.xml");
Theme theme = Theme.load(in);
theme.apply(textArea);
} catch (IOException ioe) {
ioe.printStackTrace();
}
textArea.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
saveChanneList();
}
});
return textArea;
}
// 变化时保存渠道列表
private void saveChanneList() {
SavedState savedState = SavedState.getInstance();
if(! (savedState.channelList !=null && textArea.getText().equals(savedState.channelList)) ) {
savedState.channelList = textArea.getText();
savedState.save();
}
}
// 浏览输入APK
private void browseInputApk() {
SavedState savedState = SavedState.getInstance();
initFileChooser(savedState.lastFile);
chooser.setDialogTitle("选择需要打包的APK文件");
int returnVal = chooser.showOpenDialog(this.contentPane);
if (returnVal == JFileChooser.APPROVE_OPTION) {
textFieldSourceAPK.setText(chooser.getSelectedFile().getPath());
savedState.lastFile = textFieldSourceAPK.getText();
savedState.save();
}
}
// 初始化文件选择器
private void initFileChooser(String currentFilePath) {
if( chooser == null) {
if(StringUtil.isEmpty(currentFilePath)) {
chooser = new JFileChooser(new File("."));
} else {
File currentFile = new File(currentFilePath);
chooser = new JFileChooser(currentFile);
}
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
chooser.setFont(new Font("Tahoma", Font.PLAIN, 12));
chooser.setFileFilter(new ApkFileFilter());
chooser.setMultiSelectionEnabled(false);
}
}
// 检查 <SUF>
protected void doCheck() {
initFileChooser(WalleSignUtil.OUT_DIR);
chooser.setDialogTitle("选择需要验证的APK安装包");
int returnVal = chooser.showDialog(this.contentPane, "验证");
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
String channelName = WalleSignUtil.readChannel(chooser.getSelectedFile());
OptionPane.showInfoMessageDialog(contentPane, "渠道名称为:\n" + channelName, "检验成功");
return;
} catch (Exception ex) {
ex.printStackTrace();
}
OptionPane.showErrorMessageDialog(contentPane, "渠道名称无法读取, 请检查", "检验失败");
}
}
// 执行APK渠道打包工作
private void doChannel() {
final String inputApk = textFieldSourceAPK.getText();
if(StringUtil.isEmpty(inputApk)) {
textFieldSourceAPK.setBorder(BorderFactory.createLineBorder(Color.RED));
OptionPane.showErrorMessageDialog(this.contentPane, "请输入源APK",
"提示");
return;
} else {
textFieldSourceAPK.setBorder(null);
}
String channel = textArea.getText();
if(StringUtil.isEmpty(channel)) {
textArea.setBorder(BorderFactory.createLineBorder(Color.RED));
OptionPane.showErrorMessageDialog(this.contentPane, "请输入渠道列表",
"提示");
return;
} else {
textArea.setBorder(null);
}
final String fullInputApkPath = inputApk;
File apkFile = new File(fullInputApkPath);
if(!apkFile.exists()) {
OptionPane.showErrorMessageDialog(this.contentPane, "输入APK文件不可用",
"错误");
return;
}
genButton.setEnabled(false);
final String[] channels = channel.split("\\\n");
new Thread() {
public void run() {
doChannelAsync(fullInputApkPath, channels);
}
}.start();
}
// 异步处理生成渠道包
public void doChannelAsync(final String inputApk, String[] channels) {
try {
statusBar.setText("正在生成渠道包...");
OSXSupport.setDockIconBadge("0%");
final int length = channels.length;
totalFinished = 0;
for(int i = 0; i < length; i++) {
String channel = channels[i];
channel = channel.trim();
final String channelF = channel;
threadPool.execute(new Runnable() {
@Override
public void run() {
WalleSignUtil.createSignChannelAPKFile(inputApk, channelF);
totalFinished++;
progressBar.setValue(totalFinished * 100 / length);
statusBar.setText("完成生成渠道包 " + channelF + ".");
OSXSupport.setDockIconBadge((totalFinished * 100 / length) + "%");
// 打包完成
if(totalFinished >= length) {
genButton.setEnabled(true);
OptionPane.showInfoMessageDialog(contentPane, "操作成功",
"恭喜");
statusBar.setText("生成渠道包成功");
try {
Desktop.getDesktop().open(new File(WalleSignUtil.OUT_DIR));
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
OptionPane.showErrorMessageDialog(this.contentPane, "错误详情:\n" + e.getMessage(),
"生成渠道包出错");
}
}
private static JMenuBar createMenuBar() {
JMenuBar mb = new JMenuBar();
JMenu menu = new JMenu("瓦力渠道包工具");
menu.add(new JMenuItem(new AboutAction()));
menu.add(new JMenuItem(new PreferencesAction()));
menu.add(new JMenuItem(new HomePageAction()) );
menu.addSeparator();
menu.add(new JMenuItem(new QuitAction()));
mb.add(menu);
return mb;
}
private static class AboutAction extends AbstractAction {
public AboutAction() {
putValue(NAME, "关于");
}
public void actionPerformed(ActionEvent e) {
OptionPane.showInfoMessageDialog(null,
"瓦力渠道包工具1.0", "关于");
}
}
// 退出Action
private static class QuitAction extends AbstractAction {
public QuitAction() {
putValue(NAME, "退出");
}
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
private static class HomePageAction extends AbstractAction {
public HomePageAction() {
putValue(NAME, "访问网站&帮助");
}
public void actionPerformed(ActionEvent e) {
try {
Desktop.getDesktop().browse(new URI("https://github.com/beansoftapp/wallegui"));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
}
// 偏好设置
private static class PreferencesAction extends AbstractAction {
public PreferencesAction() {
putValue(NAME, "偏好设置...");
}
public void actionPerformed(ActionEvent e) {
OptionPane.showInfoMessageDialog(null, "明暗主题风格切换", "TODO");
}
}
public static void main(String[] args) {
System.setProperty("apple.laf.useScreenMenuBar", "true");// 整合Mac菜单
System.setProperty("com.apple.mrj.application.apple.menu.about.name", "瓦力渠道包工具");// 仅Mac自带的Java 6有效
Locale.setDefault(Locale.CHINESE);
try {
// UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.setLookAndFeel("com.bulenkov.darcula.DarculaLaf");
} catch(Exception ex) {
}
JFrame frame = new JFrame("瓦力安卓渠道打包神器 界面版 by https://github.com/beansoftapp");
try {
Image iconImg =
new ImageIcon(WalleAPKSignerGUI.class.getResource("icon/chuck-highlight-image.png")).getImage();
// Application.getApplication().setDockIconImage(iconImg);
OSXSupport.initializeMacOSX(new AboutAction(), new QuitAction(), new PreferencesAction(), iconImg, null);
OSXSupport.setDockIconBadge("瓦力");
frame.setIconImage(iconImg);
} catch (Exception e) {
e.printStackTrace();
}
// if(!OSXSupport.isOSX()) {
frame.getRootPane().setJMenuBar(createMenuBar());
// }
final WalleAPKSignerGUI tool = new WalleAPKSignerGUI();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.out.println(" +++++++ windowClosing ++++++ ");
tool.saveChanneList();
}
});
frame.setContentPane(tool.contentPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);// 最大化显示
frame.setVisible(true);
}
private void createUIComponents() {
// TODO: place custom component creation code here
}
} | false | 2,590 | 7 | 3,008 | 7 | 3,103 | 4 | 3,008 | 7 | 3,823 | 11 | false | false | false | false | false | true |
36672_1 | package com.stardata.starshop2.authcontext.south.adapter;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.message.WxMaMessageHandler;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import javax.annotation.PostConstruct;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Configuration
@EnableConfigurationProperties(WxMiniAppProperties.class)
public class WxConfiguration {
private final WxMiniAppProperties properties;
private static final Map<String, WxMaMessageRouter> routers = Maps.newHashMap();
private static Map<String, WxMaService> maServices = Maps.newHashMap();
@Autowired
public WxConfiguration(WxMiniAppProperties properties) {
this.properties = properties;
}
//默认取得第一个微信appid的配置
public static WxMaService getMaService() {
if (maServices.isEmpty()) {
throw new IllegalArgumentException("None appid configuration.");
}
return maServices.values().iterator().next();
}
//取得指定微信appid的配置(便于支持多个appid)
public static WxMaService getMaService(String appid) {
WxMaService wxService = maServices.get(appid);
if (wxService == null) {
throw new IllegalArgumentException(String.format("Can not find configuration for corresponding appid=[%s]", appid));
}
return wxService;
}
public static WxMaMessageRouter getRouter(String appid) {
return routers.get(appid);
}
@PostConstruct
public void init() {
List<WxMiniAppProperties.Config> configs = this.properties.getConfigs();
if (configs == null) {
throw new RuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
}
maServices = configs.stream()
.map(a -> {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(a.getAppid());
config.setSecret(a.getSecret());
config.setToken(a.getToken());
config.setAesKey(a.getAesKey());
config.setMsgDataFormat(a.getMsgDataFormat());
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
routers.put(a.getAppid(), this.newRouter(service));
return service;
}).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));
}
private WxMaMessageRouter newRouter(WxMaService service) {
final WxMaMessageRouter router = new WxMaMessageRouter(service);
router
.rule().handler(logHandler).next()
.rule().async(false).content("订阅消息").handler(subscribeMsgHandler).end()
.rule().async(false).content("文本").handler(textHandler).end()
.rule().async(false).content("图片").handler(picHandler).end()
.rule().async(false).content("二维码").handler(qrcodeHandler).end();
return router;
}
private final WxMaMessageHandler subscribeMsgHandler = (wxMessage, context, service, sessionManager) -> {
service.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
.templateId("此处更换为自己的模板id")
.data(Lists.newArrayList(
new WxMaSubscribeMessage.MsgData("keyword1", "339208499")))
.toUser(wxMessage.getFromUser())
.build());
return null;
};
private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {
System.out.println("收到消息:" + wxMessage.toString());
service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson())
.toUser(wxMessage.getFromUser()).build());
return null;
};
private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> {
service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
.toUser(wxMessage.getFromUser()).build());
return null;
};
private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {
try {
WxMediaUploadResult uploadResult = service.getMediaService()
.uploadMedia("image", "png",
ClassLoader.getSystemResourceAsStream("tmp.png"));
service.getMsgService().sendKefuMsg(
WxMaKefuMessage
.newImageBuilder()
.mediaId(uploadResult.getMediaId())
.toUser(wxMessage.getFromUser())
.build());
} catch (WxErrorException e) {
e.printStackTrace();
}
return null;
};
private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {
try {
final File file = service.getQrcodeService().createQrcode("123", 430);
WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
service.getMsgService().sendKefuMsg(
WxMaKefuMessage
.newImageBuilder()
.mediaId(uploadResult.getMediaId())
.toUser(wxMessage.getFromUser())
.build());
} catch (WxErrorException e) {
e.printStackTrace();
}
return null;
};
}
| beautautumn/starshop | foundation/auth/src/main/java/com/stardata/starshop2/authcontext/south/adapter/WxConfiguration.java | 1,545 | //默认取得第一个微信appid的配置 | line_comment | zh-cn | package com.stardata.starshop2.authcontext.south.adapter;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.bean.WxMaKefuMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.message.WxMaMessageHandler;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import javax.annotation.PostConstruct;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@Configuration
@EnableConfigurationProperties(WxMiniAppProperties.class)
public class WxConfiguration {
private final WxMiniAppProperties properties;
private static final Map<String, WxMaMessageRouter> routers = Maps.newHashMap();
private static Map<String, WxMaService> maServices = Maps.newHashMap();
@Autowired
public WxConfiguration(WxMiniAppProperties properties) {
this.properties = properties;
}
//默认 <SUF>
public static WxMaService getMaService() {
if (maServices.isEmpty()) {
throw new IllegalArgumentException("None appid configuration.");
}
return maServices.values().iterator().next();
}
//取得指定微信appid的配置(便于支持多个appid)
public static WxMaService getMaService(String appid) {
WxMaService wxService = maServices.get(appid);
if (wxService == null) {
throw new IllegalArgumentException(String.format("Can not find configuration for corresponding appid=[%s]", appid));
}
return wxService;
}
public static WxMaMessageRouter getRouter(String appid) {
return routers.get(appid);
}
@PostConstruct
public void init() {
List<WxMiniAppProperties.Config> configs = this.properties.getConfigs();
if (configs == null) {
throw new RuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
}
maServices = configs.stream()
.map(a -> {
WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
config.setAppid(a.getAppid());
config.setSecret(a.getSecret());
config.setToken(a.getToken());
config.setAesKey(a.getAesKey());
config.setMsgDataFormat(a.getMsgDataFormat());
WxMaService service = new WxMaServiceImpl();
service.setWxMaConfig(config);
routers.put(a.getAppid(), this.newRouter(service));
return service;
}).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));
}
private WxMaMessageRouter newRouter(WxMaService service) {
final WxMaMessageRouter router = new WxMaMessageRouter(service);
router
.rule().handler(logHandler).next()
.rule().async(false).content("订阅消息").handler(subscribeMsgHandler).end()
.rule().async(false).content("文本").handler(textHandler).end()
.rule().async(false).content("图片").handler(picHandler).end()
.rule().async(false).content("二维码").handler(qrcodeHandler).end();
return router;
}
private final WxMaMessageHandler subscribeMsgHandler = (wxMessage, context, service, sessionManager) -> {
service.getMsgService().sendSubscribeMsg(WxMaSubscribeMessage.builder()
.templateId("此处更换为自己的模板id")
.data(Lists.newArrayList(
new WxMaSubscribeMessage.MsgData("keyword1", "339208499")))
.toUser(wxMessage.getFromUser())
.build());
return null;
};
private final WxMaMessageHandler logHandler = (wxMessage, context, service, sessionManager) -> {
System.out.println("收到消息:" + wxMessage.toString());
service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("收到信息为:" + wxMessage.toJson())
.toUser(wxMessage.getFromUser()).build());
return null;
};
private final WxMaMessageHandler textHandler = (wxMessage, context, service, sessionManager) -> {
service.getMsgService().sendKefuMsg(WxMaKefuMessage.newTextBuilder().content("回复文本消息")
.toUser(wxMessage.getFromUser()).build());
return null;
};
private final WxMaMessageHandler picHandler = (wxMessage, context, service, sessionManager) -> {
try {
WxMediaUploadResult uploadResult = service.getMediaService()
.uploadMedia("image", "png",
ClassLoader.getSystemResourceAsStream("tmp.png"));
service.getMsgService().sendKefuMsg(
WxMaKefuMessage
.newImageBuilder()
.mediaId(uploadResult.getMediaId())
.toUser(wxMessage.getFromUser())
.build());
} catch (WxErrorException e) {
e.printStackTrace();
}
return null;
};
private final WxMaMessageHandler qrcodeHandler = (wxMessage, context, service, sessionManager) -> {
try {
final File file = service.getQrcodeService().createQrcode("123", 430);
WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
service.getMsgService().sendKefuMsg(
WxMaKefuMessage
.newImageBuilder()
.mediaId(uploadResult.getMediaId())
.toUser(wxMessage.getFromUser())
.build());
} catch (WxErrorException e) {
e.printStackTrace();
}
return null;
};
}
| false | 1,367 | 8 | 1,545 | 8 | 1,602 | 8 | 1,545 | 8 | 1,840 | 15 | false | false | false | false | false | true |
58396_12 | package com.becoze.biback.model.vo;
import com.becoze.biback.model.entity.Post;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import lombok.Data;
import org.springframework.beans.BeanUtils;
/**
* 帖子视图
*
* @author <a href="https://github.com/liyupi">程序员鱼皮</a>
* @from <a href="https://yupi.icu">编程导航知识星球</a>
*/
@Data
public class PostVO implements Serializable {
private final static Gson GSON = new Gson();
/**
* id
*/
private Long id;
/**
* 标题
*/
private String title;
/**
* 内容
*/
private String content;
/**
* 点赞数
*/
private Integer thumbNum;
/**
* 收藏数
*/
private Integer favourNum;
/**
* 创建用户 id
*/
private Long userId;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
/**
* 标签列表
*/
private List<String> tagList;
/**
* 创建人信息
*/
private UserVO user;
/**
* 是否已点赞
*/
private Boolean hasThumb;
/**
* 是否已收藏
*/
private Boolean hasFavour;
/**
* 包装类转对象
*
* @param postVO
* @return
*/
public static Post voToObj(PostVO postVO) {
if (postVO == null) {
return null;
}
Post post = new Post();
BeanUtils.copyProperties(postVO, post);
List<String> tagList = postVO.getTagList();
if (tagList != null) {
post.setTags(GSON.toJson(tagList));
}
return post;
}
/**
* 对象转包装类
*
* @param post
* @return
*/
public static PostVO objToVo(Post post) {
if (post == null) {
return null;
}
PostVO postVO = new PostVO();
BeanUtils.copyProperties(post, postVO);
postVO.setTagList(GSON.fromJson(post.getTags(), new TypeToken<List<String>>() {
}.getType()));
return postVO;
}
}
| becoze/bi-back | src/main/java/com/becoze/biback/model/vo/PostVO.java | 591 | /**
* 是否已收藏
*/ | block_comment | zh-cn | package com.becoze.biback.model.vo;
import com.becoze.biback.model.entity.Post;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import lombok.Data;
import org.springframework.beans.BeanUtils;
/**
* 帖子视图
*
* @author <a href="https://github.com/liyupi">程序员鱼皮</a>
* @from <a href="https://yupi.icu">编程导航知识星球</a>
*/
@Data
public class PostVO implements Serializable {
private final static Gson GSON = new Gson();
/**
* id
*/
private Long id;
/**
* 标题
*/
private String title;
/**
* 内容
*/
private String content;
/**
* 点赞数
*/
private Integer thumbNum;
/**
* 收藏数
*/
private Integer favourNum;
/**
* 创建用户 id
*/
private Long userId;
/**
* 创建时间
*/
private Date createTime;
/**
* 更新时间
*/
private Date updateTime;
/**
* 标签列表
*/
private List<String> tagList;
/**
* 创建人信息
*/
private UserVO user;
/**
* 是否已点赞
*/
private Boolean hasThumb;
/**
* 是否已 <SUF>*/
private Boolean hasFavour;
/**
* 包装类转对象
*
* @param postVO
* @return
*/
public static Post voToObj(PostVO postVO) {
if (postVO == null) {
return null;
}
Post post = new Post();
BeanUtils.copyProperties(postVO, post);
List<String> tagList = postVO.getTagList();
if (tagList != null) {
post.setTags(GSON.toJson(tagList));
}
return post;
}
/**
* 对象转包装类
*
* @param post
* @return
*/
public static PostVO objToVo(Post post) {
if (post == null) {
return null;
}
PostVO postVO = new PostVO();
BeanUtils.copyProperties(post, postVO);
postVO.setTagList(GSON.fromJson(post.getTags(), new TypeToken<List<String>>() {
}.getType()));
return postVO;
}
}
| false | 539 | 9 | 591 | 9 | 647 | 10 | 591 | 9 | 751 | 13 | false | false | false | false | false | true |
18170_5 | package LEMS.vo.ordervo;
import LEMS.po.storepo.TransportType;
/**
* @author 宋益明
*
* 中转单值对象
* 包括: 中转日期、到达地、运输方式
* 航班号(飞机)或车次号(火车、汽车)、
* 货柜号(飞机)或车厢号(火车)或押运员(汽车)、
* 监装员
*/
public class TransferVO {
/**
* 中转日期
*/
private String date;
/**
* 到达地
*/
private String destination;
/**
* 运输方式
*/
private TransportType type;
/**
* 航班号(或车次号)
*/
private String flight;
/**
* 货柜号(或车厢号、或押运员)
*/
private String container;
/**
* 监装员
*/
private String superVision;
public String getDate() {
return date;
}
public String getDestination() {
return destination;
}
public String getFlight() {
return flight;
}
public String getContainer() {
return container;
}
public String getSuperVision() {
return superVision;
}
public TransportType getType() {
return type;
}
public void setType(TransportType type) {
this.type = type;
}
public void setDate(String date) {
this.date = date;
}
public void setDestination(String destination) {
this.destination = destination;
}
public void setFlight(String flight) {
this.flight = flight;
}
public void setContainer(String container) {
this.container = container;
}
public void setSuperVision(String superVision) {
this.superVision = superVision;
}
} | bedisdover/Ultraviolet | LEMS_Client/src/main/java/LEMS/vo/ordervo/TransferVO.java | 492 | /**
* 货柜号(或车厢号、或押运员)
*/ | block_comment | zh-cn | package LEMS.vo.ordervo;
import LEMS.po.storepo.TransportType;
/**
* @author 宋益明
*
* 中转单值对象
* 包括: 中转日期、到达地、运输方式
* 航班号(飞机)或车次号(火车、汽车)、
* 货柜号(飞机)或车厢号(火车)或押运员(汽车)、
* 监装员
*/
public class TransferVO {
/**
* 中转日期
*/
private String date;
/**
* 到达地
*/
private String destination;
/**
* 运输方式
*/
private TransportType type;
/**
* 航班号(或车次号)
*/
private String flight;
/**
* 货柜号 <SUF>*/
private String container;
/**
* 监装员
*/
private String superVision;
public String getDate() {
return date;
}
public String getDestination() {
return destination;
}
public String getFlight() {
return flight;
}
public String getContainer() {
return container;
}
public String getSuperVision() {
return superVision;
}
public TransportType getType() {
return type;
}
public void setType(TransportType type) {
this.type = type;
}
public void setDate(String date) {
this.date = date;
}
public void setDestination(String destination) {
this.destination = destination;
}
public void setFlight(String flight) {
this.flight = flight;
}
public void setContainer(String container) {
this.container = container;
}
public void setSuperVision(String superVision) {
this.superVision = superVision;
}
} | false | 395 | 20 | 492 | 23 | 491 | 21 | 492 | 23 | 612 | 32 | false | false | false | false | false | true |
8419_30 | package org.xiaowu.behappy.msm.service;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.xiaowu.behappy.api.common.vo.MsmVo;
import org.xiaowu.behappy.msm.config.AliSmsProperties;
/**
* @author xiaowu
*/
@Slf4j
@Service
@AllArgsConstructor
public class MsmService {
/**
* 初始化ascClient需要的几个参数
* 短信API产品名称(短信产品名固定,无需修改)
*/
final String product = "Dysmsapi";
private final AliSmsProperties aliSmsProperties;
@SneakyThrows
public boolean sendSms(String phone, String code) {
////设置超时时间-可自行调整
//System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
//System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//
////替换成你的AK
//final String accessKeyId = aliSmsProperties.getAccessKeyId();//你的accessKeyId,参考本文档步骤2
//final String accessKeySecret = aliSmsProperties.getAccessKeySecret();//你的accessKeySecret,参考本文档步骤2
//final String signName = aliSmsProperties.getSignName();//必填:短信签名-可在短信控制台中找到,参考本文档步骤2
////初始化ascClient,暂时不支持多region(请勿修改)
//IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
// accessKeySecret);
//DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product);
//IAcsClient acsClient = new DefaultAcsClient(profile);
////组装请求对象
//SendSmsRequest request = new SendSmsRequest();
////使用post提交
//request.setSysMethod(MethodType.POST);
////必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000”
//request.setPhoneNumbers(phone);
////必填:短信签名-可在短信控制台中找到
//request.setSignName(signName);
////必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
//request.setTemplateCode(aliSmsProperties.getTemplateCode());
////可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
////友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
////参考:request.setTemplateParam("{\"变量1\":\"值1\",\"变量2\":\"值2\",\"变量3\":\"值3\"}")
//request.setTemplateParam("{\"code\":" + code + "}");
////可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
////request.setSmsUpExtendCode("90997");
////可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
////request.setOutId("yourOutId");
////请求失败这里会抛ClientException异常
//SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
//return sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK");
// todo,模拟发送短信
log.info("-----------------------------------------------------------");
log.info("发送短信至 {}, 内容为: {}",phone,code);
log.info("-----------------------------------------------------------");
return true;
}
public boolean send(MsmVo msmVo) {
if (StrUtil.isNotBlank(msmVo.getPhone())) {
String code = JSONUtil.toJsonPrettyStr(msmVo.getParam());
return this.sendSms(msmVo.getPhone(), code);
}
return false;
}
}
| behappy-hospital/behappy-hospital | behappy-msm/src/main/java/org/xiaowu/behappy/msm/service/MsmService.java | 1,107 | ////可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 | line_comment | zh-cn | package org.xiaowu.behappy.msm.service;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.xiaowu.behappy.api.common.vo.MsmVo;
import org.xiaowu.behappy.msm.config.AliSmsProperties;
/**
* @author xiaowu
*/
@Slf4j
@Service
@AllArgsConstructor
public class MsmService {
/**
* 初始化ascClient需要的几个参数
* 短信API产品名称(短信产品名固定,无需修改)
*/
final String product = "Dysmsapi";
private final AliSmsProperties aliSmsProperties;
@SneakyThrows
public boolean sendSms(String phone, String code) {
////设置超时时间-可自行调整
//System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
//System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//
////替换成你的AK
//final String accessKeyId = aliSmsProperties.getAccessKeyId();//你的accessKeyId,参考本文档步骤2
//final String accessKeySecret = aliSmsProperties.getAccessKeySecret();//你的accessKeySecret,参考本文档步骤2
//final String signName = aliSmsProperties.getSignName();//必填:短信签名-可在短信控制台中找到,参考本文档步骤2
////初始化ascClient,暂时不支持多region(请勿修改)
//IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
// accessKeySecret);
//DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product);
//IAcsClient acsClient = new DefaultAcsClient(profile);
////组装请求对象
//SendSmsRequest request = new SendSmsRequest();
////使用post提交
//request.setSysMethod(MethodType.POST);
////必填:待发送手机号。支持以逗号分隔的形式进行批量调用,批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式;发送国际/港澳台消息时,接收号码格式为国际区号+号码,如“85200000000”
//request.setPhoneNumbers(phone);
////必填:短信签名-可在短信控制台中找到
//request.setSignName(signName);
////必填:短信模板-可在短信控制台中找到,发送国际/港澳台消息时,请使用国际/港澳台短信模版
//request.setTemplateCode(aliSmsProperties.getTemplateCode());
////可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
////友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
////参考:request.setTemplateParam("{\"变量1\":\"值1\",\"变量2\":\"值2\",\"变量3\":\"值3\"}")
//request.setTemplateParam("{\"code\":" + code + "}");
////可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段)
////request.setSmsUpExtendCode("90997");
////可选 <SUF>
////request.setOutId("yourOutId");
////请求失败这里会抛ClientException异常
//SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
//return sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK");
// todo,模拟发送短信
log.info("-----------------------------------------------------------");
log.info("发送短信至 {}, 内容为: {}",phone,code);
log.info("-----------------------------------------------------------");
return true;
}
public boolean send(MsmVo msmVo) {
if (StrUtil.isNotBlank(msmVo.getPhone())) {
String code = JSONUtil.toJsonPrettyStr(msmVo.getParam());
return this.sendSms(msmVo.getPhone(), code);
}
return false;
}
}
| false | 995 | 29 | 1,107 | 30 | 1,085 | 28 | 1,107 | 30 | 1,588 | 50 | false | false | false | false | false | true |
15547_5 | package com.jimmy.peripheral;
import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.LinearLayout;
public class DragViewGroup extends LinearLayout {
private static final String TAG = "TestViewGroup";
// 记录手指上次触摸的坐标
private float mLastPointX;
private float mLastPointY;
//用于识别最小的滑动距离
private int mSlop;
// 用于标识正在被拖拽的 child,为 null 时表明没有 child 被拖拽
private View mDragView;
// 状态分别空闲、拖拽两种
enum State {
IDLE,
DRAGGING
}
State mCurrentState;
public DragViewGroup(Context context) {
this(context,null);
}
public DragViewGroup(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public DragViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mSlop = ViewConfiguration.getWindowTouchSlop();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action){
case MotionEvent.ACTION_DOWN:
if ( isPointOnViews(event)) {
//标记状态为拖拽,并记录上次触摸坐标
mCurrentState = State.DRAGGING;
mLastPointX = event.getX();
mLastPointY = event.getY();
}
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) (event.getX() - mLastPointX);
int deltaY = (int) (event.getY() - mLastPointY);
if (mCurrentState == State.DRAGGING && mDragView != null
&& (Math.abs(deltaX) > mSlop || Math.abs(deltaY) > mSlop)) {
//如果符合条件则对被拖拽的 child 进行位置移动
ViewCompat.offsetLeftAndRight(mDragView,deltaX);
ViewCompat.offsetTopAndBottom(mDragView,deltaY);
mLastPointX = event.getX();
mLastPointY = event.getY();
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if ( mCurrentState == State.DRAGGING ){
// 标记状态为空闲,并将 mDragView 变量置为 null
mCurrentState = State.IDLE;
mDragView = null;
}
break;
}
return true;
}
/**
* 判断触摸的位置是否落在 child 身上
*
* */
private boolean isPointOnViews(MotionEvent ev) {
boolean result = false;
Rect rect = new Rect();
for (int i = 0;i < getChildCount();i++) {
View view = getChildAt(i);
rect.set((int)view.getX(),(int)view.getY(),(int)view.getX()+(int)view.getWidth()
,(int)view.getY()+view.getHeight());
if (rect.contains((int)ev.getX(),(int)ev.getY())){
//标记被拖拽的child
mDragView = view;
result = true;
break;
}
}
return result && mCurrentState != State.DRAGGING;
}
} | beibe218/peripheral | app/src/main/java/com/jimmy/peripheral/DragViewGroup.java | 856 | //如果符合条件则对被拖拽的 child 进行位置移动 | line_comment | zh-cn | package com.jimmy.peripheral;
import android.content.Context;
import android.graphics.Rect;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.LinearLayout;
public class DragViewGroup extends LinearLayout {
private static final String TAG = "TestViewGroup";
// 记录手指上次触摸的坐标
private float mLastPointX;
private float mLastPointY;
//用于识别最小的滑动距离
private int mSlop;
// 用于标识正在被拖拽的 child,为 null 时表明没有 child 被拖拽
private View mDragView;
// 状态分别空闲、拖拽两种
enum State {
IDLE,
DRAGGING
}
State mCurrentState;
public DragViewGroup(Context context) {
this(context,null);
}
public DragViewGroup(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public DragViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mSlop = ViewConfiguration.getWindowTouchSlop();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
switch (action){
case MotionEvent.ACTION_DOWN:
if ( isPointOnViews(event)) {
//标记状态为拖拽,并记录上次触摸坐标
mCurrentState = State.DRAGGING;
mLastPointX = event.getX();
mLastPointY = event.getY();
}
break;
case MotionEvent.ACTION_MOVE:
int deltaX = (int) (event.getX() - mLastPointX);
int deltaY = (int) (event.getY() - mLastPointY);
if (mCurrentState == State.DRAGGING && mDragView != null
&& (Math.abs(deltaX) > mSlop || Math.abs(deltaY) > mSlop)) {
//如果 <SUF>
ViewCompat.offsetLeftAndRight(mDragView,deltaX);
ViewCompat.offsetTopAndBottom(mDragView,deltaY);
mLastPointX = event.getX();
mLastPointY = event.getY();
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if ( mCurrentState == State.DRAGGING ){
// 标记状态为空闲,并将 mDragView 变量置为 null
mCurrentState = State.IDLE;
mDragView = null;
}
break;
}
return true;
}
/**
* 判断触摸的位置是否落在 child 身上
*
* */
private boolean isPointOnViews(MotionEvent ev) {
boolean result = false;
Rect rect = new Rect();
for (int i = 0;i < getChildCount();i++) {
View view = getChildAt(i);
rect.set((int)view.getX(),(int)view.getY(),(int)view.getX()+(int)view.getWidth()
,(int)view.getY()+view.getHeight());
if (rect.contains((int)ev.getX(),(int)ev.getY())){
//标记被拖拽的child
mDragView = view;
result = true;
break;
}
}
return result && mCurrentState != State.DRAGGING;
}
} | false | 752 | 15 | 856 | 17 | 874 | 14 | 856 | 17 | 1,102 | 25 | false | false | false | false | false | true |
59153_1 | package Egenericity;
public class genericity01 {
public static void main(String[] args) {
Book<String> book1 = new Book<String>("哈利波特");
System.out.println(book1.BookName);
book1.getclass();
/**
* 指定为String类型后就会变成这样。编译时类型就确定为所指定的String
*
*class Book<String>{
* String BookName;
*
* public Book(String bookName) {
* BookName = bookName;
* }
*
* public String getBookName() {
* return BookName;
* }
*
* public void setBookName(String bookName) {
* BookName = bookName;
* }
* }
*
*
*
* **/
}
}
// E表示泛型,传递什么类型就会替换成什么类型
class Book<E>{
E BookName;
public Book(E bookName) {
BookName = bookName;
}
public E getBookName() {
return BookName;
}
public void setBookName(E bookName) {
BookName = bookName;
}
public void getclass(){
System.out.println(BookName.getClass());
}
}
| beidaomitu233/changhuiengineer | backend/java/javabasic01/src/Egenericity/genericity01.java | 302 | // E表示泛型,传递什么类型就会替换成什么类型 | line_comment | zh-cn | package Egenericity;
public class genericity01 {
public static void main(String[] args) {
Book<String> book1 = new Book<String>("哈利波特");
System.out.println(book1.BookName);
book1.getclass();
/**
* 指定为String类型后就会变成这样。编译时类型就确定为所指定的String
*
*class Book<String>{
* String BookName;
*
* public Book(String bookName) {
* BookName = bookName;
* }
*
* public String getBookName() {
* return BookName;
* }
*
* public void setBookName(String bookName) {
* BookName = bookName;
* }
* }
*
*
*
* **/
}
}
// E表 <SUF>
class Book<E>{
E BookName;
public Book(E bookName) {
BookName = bookName;
}
public E getBookName() {
return BookName;
}
public void setBookName(E bookName) {
BookName = bookName;
}
public void getclass(){
System.out.println(BookName.getClass());
}
}
| false | 281 | 14 | 302 | 14 | 339 | 14 | 302 | 14 | 390 | 32 | false | false | false | false | false | true |
49707_8 | package com.qf.e_metadata;
import com.qf.utils.JdbcUtil;
import jdk.nashorn.internal.ir.SplitReturn;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* description:
* 公司:千锋教育
* author:博哥
* 公众号:Java架构栈
*/
public class Demo1 {
public static void main(String[] args) throws SQLException {
Connection connection = JdbcUtil.getConnection();
String sql = "insert into work(name, age, info) values(?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(sql);
//ParameterMetaData getParameterMetaData() 得到参数元数据
// preparedStatement
// throws SQLException
//检索的数量,这 PreparedStatement对象参数的类型和性质。
//结果
//一个 ParameterMetaData对象所包含的信息的数量,因为这 PreparedStatement对象的每个参数标记的类型和性质
//异常
//SQLException -如果一个数据库访问错误发生或调用此方法在一个封闭的 PreparedStatement
ParameterMetaData pm = ps.getParameterMetaData();
//ParameterMetaData 表示 sql的参数的所有的信息
int parameterCount = pm.getParameterCount();
System.out.println(parameterCount);
//声明了一个数组
Object[] objs = {"二狗", 23, "想念家乡"};
for (int i = 1; i <= parameterCount; i++) {
//对sql 的? 进行赋值的
ps.setObject(i , objs[i - 1]);
}
int i = ps.executeUpdate();
System.out.println(i);
JdbcUtil.close(ps, connection);
}
}
| beixiang654/MyJavaStudy-md | day30_7/code(5)/day30_wangbojdbc/src/com/qf/e_metadata/Demo1.java | 399 | //声明了一个数组 | line_comment | zh-cn | package com.qf.e_metadata;
import com.qf.utils.JdbcUtil;
import jdk.nashorn.internal.ir.SplitReturn;
import java.sql.Connection;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* description:
* 公司:千锋教育
* author:博哥
* 公众号:Java架构栈
*/
public class Demo1 {
public static void main(String[] args) throws SQLException {
Connection connection = JdbcUtil.getConnection();
String sql = "insert into work(name, age, info) values(?, ?, ?)";
PreparedStatement ps = connection.prepareStatement(sql);
//ParameterMetaData getParameterMetaData() 得到参数元数据
// preparedStatement
// throws SQLException
//检索的数量,这 PreparedStatement对象参数的类型和性质。
//结果
//一个 ParameterMetaData对象所包含的信息的数量,因为这 PreparedStatement对象的每个参数标记的类型和性质
//异常
//SQLException -如果一个数据库访问错误发生或调用此方法在一个封闭的 PreparedStatement
ParameterMetaData pm = ps.getParameterMetaData();
//ParameterMetaData 表示 sql的参数的所有的信息
int parameterCount = pm.getParameterCount();
System.out.println(parameterCount);
//声明 <SUF>
Object[] objs = {"二狗", 23, "想念家乡"};
for (int i = 1; i <= parameterCount; i++) {
//对sql 的? 进行赋值的
ps.setObject(i , objs[i - 1]);
}
int i = ps.executeUpdate();
System.out.println(i);
JdbcUtil.close(ps, connection);
}
}
| false | 356 | 4 | 399 | 4 | 408 | 4 | 399 | 4 | 547 | 10 | false | false | false | false | false | true |
63204_59 | package com.belerweb.social.weibo.bean;
import java.util.Date;
import java.util.Locale;
import org.json.JSONObject;
import com.belerweb.social.bean.Gender;
import com.belerweb.social.bean.JsonBean;
import com.belerweb.social.bean.OnlineStatus;
import com.belerweb.social.bean.Result;
/**
* 用户
*
* 文档地址:http://open.weibo.com/wiki/常见返回对象数据结构#.E7.94.A8.E6.88.B7.EF.BC.88user.EF.BC.89
*/
public class User extends JsonBean {
public User() {}
private User(JSONObject jsonObject) {
super(jsonObject);
}
private String id;// 用户UID
private String idstr;// 字符串型的用户UID
private String screenName;// 用户昵称
private String name;// screenName
private Integer province;// 用户所在省级ID
private Integer city;// 用户所在城市ID
private String location;// 用户所在地
private String description;// 用户个人描述
private String url;// 用户博客地址
private String profileImageUrl;// 用户头像地址,50×50像素
private String profileUrl;// 用户的微博统一URL地址
private String domain;// 用户的个性化域名
private String weihao;// 用户的微号
private Gender gender;// 性别
private Integer followersCount;// 粉丝数
private Integer friendsCount;// 关注数
private Integer statusesCount;// 微博数
private Integer favouritesCount;// 收藏数
private Date createdAt;// 用户创建(注册)时间
private Boolean following;// 暂未支持
private Boolean allowAllActMsg;// 是否允许所有人给我发私信
private Boolean geoEnabled;// 是否允许标识用户的地理位置
private Boolean verified;// 是否是微博认证用户,即加V用户
private Integer verifiedType;// 暂未支持
private String remark;// 用户备注信息,只有在查询用户关系时才返回此字段
private Status status;// 用户的最近一条微博信息字段 详细
private Boolean allowAllComment;// 是否允许所有人对我的微博进行评论
private String avatarLarge;// 用户大头像地址
private String verifiedReason;// 认证原因
private Boolean followMe;// 该用户是否关注当前登录用户
private OnlineStatus onlineStatus;// 用户的在线状态
private Integer biFollowersCount;// 用户的互粉数
private String lang;// 用户当前的语言版本,zh-cn:简体中文,zh-tw:繁体中文,en:英语
/**
* 用户UID
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* 字符串型的用户UID
*/
public String getIdstr() {
return idstr;
}
public void setIdstr(String idstr) {
this.idstr = idstr;
}
/**
* 用户昵称
*/
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
/**
* 友好显示名称
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 用户所在省级ID
*/
public Integer getProvince() {
return province;
}
public void setProvince(Integer province) {
this.province = province;
}
/**
* 用户所在城市ID
*/
public Integer getCity() {
return city;
}
public void setCity(Integer city) {
this.city = city;
}
/**
* 用户所在地
*/
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
/**
* 用户个人描述
*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* 用户博客地址
*/
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
/**
* 用户头像地址,50×50像素
*/
public String getProfileImageUrl() {
return profileImageUrl;
}
public void setProfileImageUrl(String profileImageUrl) {
this.profileImageUrl = profileImageUrl;
}
/**
* 用户的微博统一URL地址
*/
public String getProfileUrl() {
return profileUrl;
}
public void setProfileUrl(String profileUrl) {
this.profileUrl = profileUrl;
}
/**
* 用户的个性化域名
*/
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
/**
* 用户的微号
*/
public String getWeihao() {
return weihao;
}
public void setWeihao(String weihao) {
this.weihao = weihao;
}
/**
* 性别
*/
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
/**
* 粉丝数
*/
public Integer getFollowersCount() {
return followersCount;
}
public void setFollowersCount(Integer followersCount) {
this.followersCount = followersCount;
}
/**
* 关注数
*/
public Integer getFriendsCount() {
return friendsCount;
}
public void setFriendsCount(Integer friendsCount) {
this.friendsCount = friendsCount;
}
/**
* 微博数
*/
public Integer getStatusesCount() {
return statusesCount;
}
public void setStatusesCount(Integer statusesCount) {
this.statusesCount = statusesCount;
}
/**
* 收藏数
*/
public Integer getFavouritesCount() {
return favouritesCount;
}
public void setFavouritesCount(Integer favouritesCount) {
this.favouritesCount = favouritesCount;
}
/**
* 用户创建(注册)时间
*/
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
/**
* 暂未支持
*/
public Boolean getFollowing() {
return following;
}
public void setFollowing(Boolean following) {
this.following = following;
}
/**
* 是否允许所有人给我发私信
*/
public Boolean getAllowAllActMsg() {
return allowAllActMsg;
}
public void setAllowAllActMsg(Boolean allowAllActMsg) {
this.allowAllActMsg = allowAllActMsg;
}
/**
* 是否允许标识用户的地理位置
*/
public Boolean getGeoEnabled() {
return geoEnabled;
}
public void setGeoEnabled(Boolean geoEnabled) {
this.geoEnabled = geoEnabled;
}
/**
* 是否是微博认证用户,即加V用户
*/
public Boolean getVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
/**
* 暂未支持
*/
public Integer getVerifiedType() {
return verifiedType;
}
public void setVerifiedType(Integer verifiedType) {
this.verifiedType = verifiedType;
}
/**
* 用户备注信息,只有在查询用户关系时才返回此字段
*/
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 用户的最近一条微博信息字段 详细
*/
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
/**
* 是否允许所有人对我的微博进行评论
*/
public Boolean getAllowAllComment() {
return allowAllComment;
}
public void setAllowAllComment(Boolean allowAllComment) {
this.allowAllComment = allowAllComment;
}
/**
* 用户大头像地址
*/
public String getAvatarLarge() {
return avatarLarge;
}
public void setAvatarLarge(String avatarLarge) {
this.avatarLarge = avatarLarge;
}
/**
* 认证原因
*/
public String getVerifiedReason() {
return verifiedReason;
}
public void setVerifiedReason(String verifiedReason) {
this.verifiedReason = verifiedReason;
}
/**
* 该用户是否关注当前登录用户
*/
public Boolean getFollowMe() {
return followMe;
}
public void setFollowMe(Boolean followMe) {
this.followMe = followMe;
}
/**
* 用户的在线状态
*/
public OnlineStatus getOnlineStatus() {
return onlineStatus;
}
public void setOnlineStatus(OnlineStatus onlineStatus) {
this.onlineStatus = onlineStatus;
}
/**
* 用户的互粉数
*/
public Integer getBiFollowersCount() {
return biFollowersCount;
}
public void setBiFollowersCount(Integer biFollowersCount) {
this.biFollowersCount = biFollowersCount;
}
/**
* 用户当前的语言版本,zh-cn:简体中文,zh-tw:繁体中文,en:英语
*/
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public static User parse(JSONObject jsonObject) {
if (jsonObject == null) {
return null;
}
User obj = new User(jsonObject);
obj.id = Result.toString(jsonObject.get("id"));
obj.idstr = Result.toString(jsonObject.opt("idstr"));
obj.screenName = Result.toString(jsonObject.opt("screen_name"));
obj.name = Result.toString(jsonObject.opt("name"));
obj.province = Result.parseInteger(jsonObject.opt("province"));
obj.city = Result.parseInteger(jsonObject.opt("city"));
obj.location = Result.toString(jsonObject.opt("location"));
obj.description = Result.toString(jsonObject.opt("description"));
obj.url = Result.toString(jsonObject.opt("url"));
obj.profileImageUrl = Result.toString(jsonObject.opt("profile_image_url"));
obj.profileUrl = Result.toString(jsonObject.opt("profile_url"));
obj.domain = Result.toString(jsonObject.opt("domain"));
obj.weihao = Result.toString(jsonObject.opt("weihao"));
obj.gender = Gender.parse(jsonObject.optString("gender", null));
obj.followersCount = Result.parseInteger(jsonObject.opt("followers_count"));
obj.friendsCount = Result.parseInteger(jsonObject.opt("friends_count"));
obj.statusesCount = Result.parseInteger(jsonObject.opt("statuses_count"));
obj.favouritesCount = Result.parseInteger(jsonObject.opt("favourites_count"));
obj.createdAt =
Result
.parseDate(jsonObject.opt("created_at"), "EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
obj.following = Result.parseBoolean(jsonObject.opt("following"));
obj.allowAllActMsg = Result.parseBoolean(jsonObject.opt("allow_all_act_msg"));
obj.geoEnabled = Result.parseBoolean(jsonObject.opt("geo_enabled"));
obj.verified = Result.parseBoolean(jsonObject.opt("verified"));
obj.verifiedType = Result.parseInteger(jsonObject.opt("verified_type"));
obj.remark = Result.toString(jsonObject.opt("remark"));
obj.status = Status.parse(jsonObject.optJSONObject("status"));
obj.allowAllComment = Result.parseBoolean(jsonObject.opt("allow_all_comment"));
obj.avatarLarge = Result.toString(jsonObject.opt("avatar_large"));
obj.verifiedReason = Result.toString(jsonObject.opt("verified_reason"));
obj.followMe = Result.parseBoolean(jsonObject.opt("follow_me"));
obj.onlineStatus =
OnlineStatus.parse(Result.parseInteger(jsonObject.optString("online_status")));
obj.biFollowersCount = Result.parseInteger(jsonObject.opt("bi_followers_count"));
obj.lang = Result.toString(jsonObject.opt("lang"));
return obj;
}
}
| belerweb/social-sdk | src/main/java/com/belerweb/social/weibo/bean/User.java | 2,875 | /**
* 是否允许所有人对我的微博进行评论
*/ | block_comment | zh-cn | package com.belerweb.social.weibo.bean;
import java.util.Date;
import java.util.Locale;
import org.json.JSONObject;
import com.belerweb.social.bean.Gender;
import com.belerweb.social.bean.JsonBean;
import com.belerweb.social.bean.OnlineStatus;
import com.belerweb.social.bean.Result;
/**
* 用户
*
* 文档地址:http://open.weibo.com/wiki/常见返回对象数据结构#.E7.94.A8.E6.88.B7.EF.BC.88user.EF.BC.89
*/
public class User extends JsonBean {
public User() {}
private User(JSONObject jsonObject) {
super(jsonObject);
}
private String id;// 用户UID
private String idstr;// 字符串型的用户UID
private String screenName;// 用户昵称
private String name;// screenName
private Integer province;// 用户所在省级ID
private Integer city;// 用户所在城市ID
private String location;// 用户所在地
private String description;// 用户个人描述
private String url;// 用户博客地址
private String profileImageUrl;// 用户头像地址,50×50像素
private String profileUrl;// 用户的微博统一URL地址
private String domain;// 用户的个性化域名
private String weihao;// 用户的微号
private Gender gender;// 性别
private Integer followersCount;// 粉丝数
private Integer friendsCount;// 关注数
private Integer statusesCount;// 微博数
private Integer favouritesCount;// 收藏数
private Date createdAt;// 用户创建(注册)时间
private Boolean following;// 暂未支持
private Boolean allowAllActMsg;// 是否允许所有人给我发私信
private Boolean geoEnabled;// 是否允许标识用户的地理位置
private Boolean verified;// 是否是微博认证用户,即加V用户
private Integer verifiedType;// 暂未支持
private String remark;// 用户备注信息,只有在查询用户关系时才返回此字段
private Status status;// 用户的最近一条微博信息字段 详细
private Boolean allowAllComment;// 是否允许所有人对我的微博进行评论
private String avatarLarge;// 用户大头像地址
private String verifiedReason;// 认证原因
private Boolean followMe;// 该用户是否关注当前登录用户
private OnlineStatus onlineStatus;// 用户的在线状态
private Integer biFollowersCount;// 用户的互粉数
private String lang;// 用户当前的语言版本,zh-cn:简体中文,zh-tw:繁体中文,en:英语
/**
* 用户UID
*/
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* 字符串型的用户UID
*/
public String getIdstr() {
return idstr;
}
public void setIdstr(String idstr) {
this.idstr = idstr;
}
/**
* 用户昵称
*/
public String getScreenName() {
return screenName;
}
public void setScreenName(String screenName) {
this.screenName = screenName;
}
/**
* 友好显示名称
*/
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
/**
* 用户所在省级ID
*/
public Integer getProvince() {
return province;
}
public void setProvince(Integer province) {
this.province = province;
}
/**
* 用户所在城市ID
*/
public Integer getCity() {
return city;
}
public void setCity(Integer city) {
this.city = city;
}
/**
* 用户所在地
*/
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
/**
* 用户个人描述
*/
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
/**
* 用户博客地址
*/
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
/**
* 用户头像地址,50×50像素
*/
public String getProfileImageUrl() {
return profileImageUrl;
}
public void setProfileImageUrl(String profileImageUrl) {
this.profileImageUrl = profileImageUrl;
}
/**
* 用户的微博统一URL地址
*/
public String getProfileUrl() {
return profileUrl;
}
public void setProfileUrl(String profileUrl) {
this.profileUrl = profileUrl;
}
/**
* 用户的个性化域名
*/
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
/**
* 用户的微号
*/
public String getWeihao() {
return weihao;
}
public void setWeihao(String weihao) {
this.weihao = weihao;
}
/**
* 性别
*/
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
/**
* 粉丝数
*/
public Integer getFollowersCount() {
return followersCount;
}
public void setFollowersCount(Integer followersCount) {
this.followersCount = followersCount;
}
/**
* 关注数
*/
public Integer getFriendsCount() {
return friendsCount;
}
public void setFriendsCount(Integer friendsCount) {
this.friendsCount = friendsCount;
}
/**
* 微博数
*/
public Integer getStatusesCount() {
return statusesCount;
}
public void setStatusesCount(Integer statusesCount) {
this.statusesCount = statusesCount;
}
/**
* 收藏数
*/
public Integer getFavouritesCount() {
return favouritesCount;
}
public void setFavouritesCount(Integer favouritesCount) {
this.favouritesCount = favouritesCount;
}
/**
* 用户创建(注册)时间
*/
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
/**
* 暂未支持
*/
public Boolean getFollowing() {
return following;
}
public void setFollowing(Boolean following) {
this.following = following;
}
/**
* 是否允许所有人给我发私信
*/
public Boolean getAllowAllActMsg() {
return allowAllActMsg;
}
public void setAllowAllActMsg(Boolean allowAllActMsg) {
this.allowAllActMsg = allowAllActMsg;
}
/**
* 是否允许标识用户的地理位置
*/
public Boolean getGeoEnabled() {
return geoEnabled;
}
public void setGeoEnabled(Boolean geoEnabled) {
this.geoEnabled = geoEnabled;
}
/**
* 是否是微博认证用户,即加V用户
*/
public Boolean getVerified() {
return verified;
}
public void setVerified(Boolean verified) {
this.verified = verified;
}
/**
* 暂未支持
*/
public Integer getVerifiedType() {
return verifiedType;
}
public void setVerifiedType(Integer verifiedType) {
this.verifiedType = verifiedType;
}
/**
* 用户备注信息,只有在查询用户关系时才返回此字段
*/
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
/**
* 用户的最近一条微博信息字段 详细
*/
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
/**
* 是否允 <SUF>*/
public Boolean getAllowAllComment() {
return allowAllComment;
}
public void setAllowAllComment(Boolean allowAllComment) {
this.allowAllComment = allowAllComment;
}
/**
* 用户大头像地址
*/
public String getAvatarLarge() {
return avatarLarge;
}
public void setAvatarLarge(String avatarLarge) {
this.avatarLarge = avatarLarge;
}
/**
* 认证原因
*/
public String getVerifiedReason() {
return verifiedReason;
}
public void setVerifiedReason(String verifiedReason) {
this.verifiedReason = verifiedReason;
}
/**
* 该用户是否关注当前登录用户
*/
public Boolean getFollowMe() {
return followMe;
}
public void setFollowMe(Boolean followMe) {
this.followMe = followMe;
}
/**
* 用户的在线状态
*/
public OnlineStatus getOnlineStatus() {
return onlineStatus;
}
public void setOnlineStatus(OnlineStatus onlineStatus) {
this.onlineStatus = onlineStatus;
}
/**
* 用户的互粉数
*/
public Integer getBiFollowersCount() {
return biFollowersCount;
}
public void setBiFollowersCount(Integer biFollowersCount) {
this.biFollowersCount = biFollowersCount;
}
/**
* 用户当前的语言版本,zh-cn:简体中文,zh-tw:繁体中文,en:英语
*/
public String getLang() {
return lang;
}
public void setLang(String lang) {
this.lang = lang;
}
public static User parse(JSONObject jsonObject) {
if (jsonObject == null) {
return null;
}
User obj = new User(jsonObject);
obj.id = Result.toString(jsonObject.get("id"));
obj.idstr = Result.toString(jsonObject.opt("idstr"));
obj.screenName = Result.toString(jsonObject.opt("screen_name"));
obj.name = Result.toString(jsonObject.opt("name"));
obj.province = Result.parseInteger(jsonObject.opt("province"));
obj.city = Result.parseInteger(jsonObject.opt("city"));
obj.location = Result.toString(jsonObject.opt("location"));
obj.description = Result.toString(jsonObject.opt("description"));
obj.url = Result.toString(jsonObject.opt("url"));
obj.profileImageUrl = Result.toString(jsonObject.opt("profile_image_url"));
obj.profileUrl = Result.toString(jsonObject.opt("profile_url"));
obj.domain = Result.toString(jsonObject.opt("domain"));
obj.weihao = Result.toString(jsonObject.opt("weihao"));
obj.gender = Gender.parse(jsonObject.optString("gender", null));
obj.followersCount = Result.parseInteger(jsonObject.opt("followers_count"));
obj.friendsCount = Result.parseInteger(jsonObject.opt("friends_count"));
obj.statusesCount = Result.parseInteger(jsonObject.opt("statuses_count"));
obj.favouritesCount = Result.parseInteger(jsonObject.opt("favourites_count"));
obj.createdAt =
Result
.parseDate(jsonObject.opt("created_at"), "EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH);
obj.following = Result.parseBoolean(jsonObject.opt("following"));
obj.allowAllActMsg = Result.parseBoolean(jsonObject.opt("allow_all_act_msg"));
obj.geoEnabled = Result.parseBoolean(jsonObject.opt("geo_enabled"));
obj.verified = Result.parseBoolean(jsonObject.opt("verified"));
obj.verifiedType = Result.parseInteger(jsonObject.opt("verified_type"));
obj.remark = Result.toString(jsonObject.opt("remark"));
obj.status = Status.parse(jsonObject.optJSONObject("status"));
obj.allowAllComment = Result.parseBoolean(jsonObject.opt("allow_all_comment"));
obj.avatarLarge = Result.toString(jsonObject.opt("avatar_large"));
obj.verifiedReason = Result.toString(jsonObject.opt("verified_reason"));
obj.followMe = Result.parseBoolean(jsonObject.opt("follow_me"));
obj.onlineStatus =
OnlineStatus.parse(Result.parseInteger(jsonObject.optString("online_status")));
obj.biFollowersCount = Result.parseInteger(jsonObject.opt("bi_followers_count"));
obj.lang = Result.toString(jsonObject.opt("lang"));
return obj;
}
}
| false | 2,626 | 14 | 2,875 | 14 | 3,145 | 15 | 2,875 | 14 | 3,898 | 32 | false | false | false | false | false | true |
20653_0 | package Text;
public class text1 {
/*
需求:
人类: (Person)
成员变量: 姓名, 年龄
老师类:
成员变量: 姓名, 年龄
成员方法: teach
- 姓名为张三, 年龄为30岁的老师正在讲课
学生类:
成员变量: 姓名, 年龄, 成绩
成员方法: study
- 姓名为李四, 年龄为20岁, 成绩为100分的学生, 正在学习
*/
public static void main(String[] args) {
}
}
| believe-hjh/javase_text | javase_progressive/day1/Text/text1.java | 163 | /*
需求:
人类: (Person)
成员变量: 姓名, 年龄
老师类:
成员变量: 姓名, 年龄
成员方法: teach
- 姓名为张三, 年龄为30岁的老师正在讲课
学生类:
成员变量: 姓名, 年龄, 成绩
成员方法: study
- 姓名为李四, 年龄为20岁, 成绩为100分的学生, 正在学习
*/ | block_comment | zh-cn | package Text;
public class text1 {
/*
需求: <SUF>*/
public static void main(String[] args) {
}
}
| false | 158 | 136 | 163 | 136 | 148 | 119 | 163 | 136 | 231 | 200 | false | false | false | false | false | true |
40489_2 | package com.tcb.env.model;
/**
*
* <p>[功能描述]:超标采样设备箱子model</p>
* <p>Copyright (c) 1997-2018 TCB Corporation</p>
*
* @author 王垒
* @version 1.0, 2018年7月23日下午4:06:22
* @since EnvDust 1.0.0
*
*/
public class CollectDeviceBoxModel extends BaseModel {
private String boxId;
private String boxNo;
private String boxName;
private String boxStatus;//0-就绪(绿色),1-充满(黄色),2-故障(红色)
private String boxStatusName;//0-就绪(绿色),1-充满(黄色),2-故障(红色)
private String cdId;
private String cdCode;
private String cdMn;
private String cdName;
private String netStatus;
/**
* @return the boxId
*/
public String getBoxId() {
return boxId;
}
/**
* @param boxId the boxId to set
*/
public void setBoxId(String boxId) {
this.boxId = boxId;
}
/**
* @return the boxNo
*/
public String getBoxNo() {
return boxNo;
}
/**
* @param boxNo the boxNo to set
*/
public void setBoxNo(String boxNo) {
this.boxNo = boxNo;
}
/**
* @return the boxName
*/
public String getBoxName() {
return boxName;
}
/**
* @param boxName the boxName to set
*/
public void setBoxName(String boxName) {
this.boxName = boxName;
}
/**
* @return the boxStatus
*/
public String getBoxStatus() {
return boxStatus;
}
/**
* @param boxStatus the boxStatus to set
*/
public void setBoxStatus(String boxStatus) {
this.boxStatus = boxStatus;
}
/**
* @return the boxStatusName
*/
public String getBoxStatusName() {
return boxStatusName;
}
/**
* @param boxStatusName the boxStatusName to set
*/
public void setBoxStatusName(String boxStatusName) {
this.boxStatusName = boxStatusName;
}
/**
* @return the cdId
*/
public String getCdId() {
return cdId;
}
/**
* @param cdId the cdId to set
*/
public void setCdId(String cdId) {
this.cdId = cdId;
}
/**
* @return the cdCode
*/
public String getCdCode() {
return cdCode;
}
/**
* @param cdCode the cdCode to set
*/
public void setCdCode(String cdCode) {
this.cdCode = cdCode;
}
/**
* @return the cdMn
*/
public String getCdMn() {
return cdMn;
}
/**
* @param cdMn the cdMn to set
*/
public void setCdMn(String cdMn) {
this.cdMn = cdMn;
}
/**
* @return the cdName
*/
public String getCdName() {
return cdName;
}
/**
* @param cdName the cdName to set
*/
public void setCdName(String cdName) {
this.cdName = cdName;
}
/**
* @return the netStatus
*/
public String getNetStatus() {
return netStatus;
}
/**
* @param netStatus the netStatus to set
*/
public void setNetStatus(String netStatus) {
this.netStatus = netStatus;
}
}
| bellmit/EnvDustCompony | src/main/java/com/tcb/env/model/CollectDeviceBoxModel.java | 984 | //0-就绪(绿色),1-充满(黄色),2-故障(红色) | line_comment | zh-cn | package com.tcb.env.model;
/**
*
* <p>[功能描述]:超标采样设备箱子model</p>
* <p>Copyright (c) 1997-2018 TCB Corporation</p>
*
* @author 王垒
* @version 1.0, 2018年7月23日下午4:06:22
* @since EnvDust 1.0.0
*
*/
public class CollectDeviceBoxModel extends BaseModel {
private String boxId;
private String boxNo;
private String boxName;
private String boxStatus;//0-就绪(绿色),1-充满(黄色),2-故障(红色)
private String boxStatusName;//0- <SUF>
private String cdId;
private String cdCode;
private String cdMn;
private String cdName;
private String netStatus;
/**
* @return the boxId
*/
public String getBoxId() {
return boxId;
}
/**
* @param boxId the boxId to set
*/
public void setBoxId(String boxId) {
this.boxId = boxId;
}
/**
* @return the boxNo
*/
public String getBoxNo() {
return boxNo;
}
/**
* @param boxNo the boxNo to set
*/
public void setBoxNo(String boxNo) {
this.boxNo = boxNo;
}
/**
* @return the boxName
*/
public String getBoxName() {
return boxName;
}
/**
* @param boxName the boxName to set
*/
public void setBoxName(String boxName) {
this.boxName = boxName;
}
/**
* @return the boxStatus
*/
public String getBoxStatus() {
return boxStatus;
}
/**
* @param boxStatus the boxStatus to set
*/
public void setBoxStatus(String boxStatus) {
this.boxStatus = boxStatus;
}
/**
* @return the boxStatusName
*/
public String getBoxStatusName() {
return boxStatusName;
}
/**
* @param boxStatusName the boxStatusName to set
*/
public void setBoxStatusName(String boxStatusName) {
this.boxStatusName = boxStatusName;
}
/**
* @return the cdId
*/
public String getCdId() {
return cdId;
}
/**
* @param cdId the cdId to set
*/
public void setCdId(String cdId) {
this.cdId = cdId;
}
/**
* @return the cdCode
*/
public String getCdCode() {
return cdCode;
}
/**
* @param cdCode the cdCode to set
*/
public void setCdCode(String cdCode) {
this.cdCode = cdCode;
}
/**
* @return the cdMn
*/
public String getCdMn() {
return cdMn;
}
/**
* @param cdMn the cdMn to set
*/
public void setCdMn(String cdMn) {
this.cdMn = cdMn;
}
/**
* @return the cdName
*/
public String getCdName() {
return cdName;
}
/**
* @param cdName the cdName to set
*/
public void setCdName(String cdName) {
this.cdName = cdName;
}
/**
* @return the netStatus
*/
public String getNetStatus() {
return netStatus;
}
/**
* @param netStatus the netStatus to set
*/
public void setNetStatus(String netStatus) {
this.netStatus = netStatus;
}
}
| false | 843 | 20 | 984 | 27 | 1,009 | 20 | 984 | 27 | 1,107 | 37 | false | false | false | false | false | true |
40799_19 | /**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* 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 org.springblade.anbiao.shigu.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 事故报告调查处理-事故报告 实体类
*
* @author hyp
* @since 2019-04-28
*/
@Data
@TableName("anbiao_shigubaogao")
@ApiModel(value = "Shigubaogao对象", description = "Shigubaogao对象")
public class Shigubaogao implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(value = "id", type = IdType.UUID)
@ApiModelProperty(value = "主键id")
private String id;
/**
* 机构id
*/
@ApiModelProperty(value = "机构id")
@TableField("dept_id")
private Integer deptId;
@ApiModelProperty(value = "企业 名称")
@TableField(exist = false)
private String deptName;
/**
* 操作人
*/
@ApiModelProperty(value = "操作人")
private String caozuoren;
/**
* 操作人id
*/
@ApiModelProperty(value = "操作人id")
private Integer caozuorenid;
/**
* 操作时间
*/
@ApiModelProperty(value = "操作时间")
private String caozuoshijian;
/**
* 车牌号
*/
@ApiModelProperty(value = "车牌号")
private String chepaihao;
/**
* 车型
*/
@ApiModelProperty(value = "车型")
private String chexing;
/**
* 核载人(吨)数
*/
@ApiModelProperty(value = "核载人(吨)数")
private BigDecimal hezaishu = new BigDecimal(0);
/**
* 实载人(吨)数
*/
@ApiModelProperty(value = "实载人(吨)数")
private BigDecimal shizaishu = new BigDecimal(0);
/**
* 危险化学品品名
*/
@ApiModelProperty(value = "危险化学品品名")
private String weihuapinming;
/**
* 驾驶员姓名
*/
@ApiModelProperty(value = "驾驶员姓名")
private String jiashiyuan;
/**
* 从业资格类别
*/
@ApiModelProperty(value = "从业资格类别")
private String congyezigeleibie;
/**
* 从业资格证号
*/
@ApiModelProperty(value = "从业资格证号")
private String congyezigezhenghao;
/**
* 事故分类
*/
@ApiModelProperty(value = "事故分类")
private String shigufenlei;
/**
* 事故形态
*/
@ApiModelProperty(value = "事故形态")
private String shiguxingtai;
/**
* 事故发生时间
*/
@ApiModelProperty(value = "事故发生时间")
private LocalDateTime shigufashengshijian;
/**
* 事故发生地点
*/
@ApiModelProperty(value = "事故发生地点")
private String shigufashengdidian;
/**
* 天气情况
*/
@ApiModelProperty(value = "天气情况")
private String tianqiqingkuang;
/**
* 事发路段公路技术等级
*/
@ApiModelProperty(value = "事发路段公路技术等级")
private String gonglujishudengji;
/**
* 事发路段线性状况
*/
@ApiModelProperty(value = "事发路段线性状况")
private String xianxingzhuangkuang;
/**
* 事发路段路面状况
*/
@ApiModelProperty(value = "事发路段路面状况")
private String lumianzhuangkuang;
/**
* 事故直接原因
*/
@ApiModelProperty(value = "事故直接原因")
private String shiguzhijieyuanyin;
/**
* 运行线路
*/
@ApiModelProperty(value = "运行线路")
private String yunxingxianlu;
/**
* 线路类别
*/
@ApiModelProperty(value = "线路类别")
private String xianluleibie;
/**
* 始发站(地)
*/
@ApiModelProperty(value = "始发站(地)")
private String shifazhan;
/**
* 车站等级
*/
@ApiModelProperty(value = "车站等级")
private String chezhandengji;
/**
* 死亡(人)
*/
@ApiModelProperty(value = "死亡(人)")
private Integer siwang = 0;
/**
* 失踪(人)
*/
@ApiModelProperty(value = "失踪(人)")
private Integer shizong = 0;
/**
* 受伤(人)
*/
@ApiModelProperty(value = "受伤(人)")
private Integer shoushang = 0;
/**
* 外籍人员死亡(人)
*/
@ApiModelProperty(value = "外籍人员死亡(人)")
private Integer waijisiwang = 0;
/**
* 外籍人员失踪(人)
*/
@ApiModelProperty(value = "外籍人员失踪(人)")
private Integer waijishizong = 0;
/**
* 外籍人员受伤(人)
*/
@ApiModelProperty(value = "外籍人员受伤(人)")
private Integer waijishoushang = 0;
/**
* 财产损失(元)
*/
@ApiModelProperty(value = "财产损失(元)")
private BigDecimal caichansunshi = new BigDecimal(0);
;
/**
* 事故概况
*/
@ApiModelProperty(value = "事故概况")
private String shigugaikuang;
/**
* 事故初步原因及责任分析
*/
@ApiModelProperty(value = "事故初步原因及责任分析")
private String zerenfenxi;
/**
* 事故照片
*/
@ApiModelProperty(value = "事故照片")
private String shiguzhaopian;
/**
* 附件
*/
@ApiModelProperty(value = "附件")
private String fujian;
/**
* 是否删除
*/
@ApiModelProperty(value = "是否删除")
@TableField("is_deleted")
private Integer isdel = 0;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间",required = true)
private String createtime;
}
| bellmit/SafetyStandards_HN | blade-service-api/blade-anbiao-api/src/main/java/org/springblade/anbiao/shigu/entity/Shigubaogao.java | 1,857 | /**
* 天气情况
*/ | block_comment | zh-cn | /**
* Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
* <p>
* 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 org.springblade.anbiao.shigu.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 事故报告调查处理-事故报告 实体类
*
* @author hyp
* @since 2019-04-28
*/
@Data
@TableName("anbiao_shigubaogao")
@ApiModel(value = "Shigubaogao对象", description = "Shigubaogao对象")
public class Shigubaogao implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 主键id
*/
@TableId(value = "id", type = IdType.UUID)
@ApiModelProperty(value = "主键id")
private String id;
/**
* 机构id
*/
@ApiModelProperty(value = "机构id")
@TableField("dept_id")
private Integer deptId;
@ApiModelProperty(value = "企业 名称")
@TableField(exist = false)
private String deptName;
/**
* 操作人
*/
@ApiModelProperty(value = "操作人")
private String caozuoren;
/**
* 操作人id
*/
@ApiModelProperty(value = "操作人id")
private Integer caozuorenid;
/**
* 操作时间
*/
@ApiModelProperty(value = "操作时间")
private String caozuoshijian;
/**
* 车牌号
*/
@ApiModelProperty(value = "车牌号")
private String chepaihao;
/**
* 车型
*/
@ApiModelProperty(value = "车型")
private String chexing;
/**
* 核载人(吨)数
*/
@ApiModelProperty(value = "核载人(吨)数")
private BigDecimal hezaishu = new BigDecimal(0);
/**
* 实载人(吨)数
*/
@ApiModelProperty(value = "实载人(吨)数")
private BigDecimal shizaishu = new BigDecimal(0);
/**
* 危险化学品品名
*/
@ApiModelProperty(value = "危险化学品品名")
private String weihuapinming;
/**
* 驾驶员姓名
*/
@ApiModelProperty(value = "驾驶员姓名")
private String jiashiyuan;
/**
* 从业资格类别
*/
@ApiModelProperty(value = "从业资格类别")
private String congyezigeleibie;
/**
* 从业资格证号
*/
@ApiModelProperty(value = "从业资格证号")
private String congyezigezhenghao;
/**
* 事故分类
*/
@ApiModelProperty(value = "事故分类")
private String shigufenlei;
/**
* 事故形态
*/
@ApiModelProperty(value = "事故形态")
private String shiguxingtai;
/**
* 事故发生时间
*/
@ApiModelProperty(value = "事故发生时间")
private LocalDateTime shigufashengshijian;
/**
* 事故发生地点
*/
@ApiModelProperty(value = "事故发生地点")
private String shigufashengdidian;
/**
* 天气情 <SUF>*/
@ApiModelProperty(value = "天气情况")
private String tianqiqingkuang;
/**
* 事发路段公路技术等级
*/
@ApiModelProperty(value = "事发路段公路技术等级")
private String gonglujishudengji;
/**
* 事发路段线性状况
*/
@ApiModelProperty(value = "事发路段线性状况")
private String xianxingzhuangkuang;
/**
* 事发路段路面状况
*/
@ApiModelProperty(value = "事发路段路面状况")
private String lumianzhuangkuang;
/**
* 事故直接原因
*/
@ApiModelProperty(value = "事故直接原因")
private String shiguzhijieyuanyin;
/**
* 运行线路
*/
@ApiModelProperty(value = "运行线路")
private String yunxingxianlu;
/**
* 线路类别
*/
@ApiModelProperty(value = "线路类别")
private String xianluleibie;
/**
* 始发站(地)
*/
@ApiModelProperty(value = "始发站(地)")
private String shifazhan;
/**
* 车站等级
*/
@ApiModelProperty(value = "车站等级")
private String chezhandengji;
/**
* 死亡(人)
*/
@ApiModelProperty(value = "死亡(人)")
private Integer siwang = 0;
/**
* 失踪(人)
*/
@ApiModelProperty(value = "失踪(人)")
private Integer shizong = 0;
/**
* 受伤(人)
*/
@ApiModelProperty(value = "受伤(人)")
private Integer shoushang = 0;
/**
* 外籍人员死亡(人)
*/
@ApiModelProperty(value = "外籍人员死亡(人)")
private Integer waijisiwang = 0;
/**
* 外籍人员失踪(人)
*/
@ApiModelProperty(value = "外籍人员失踪(人)")
private Integer waijishizong = 0;
/**
* 外籍人员受伤(人)
*/
@ApiModelProperty(value = "外籍人员受伤(人)")
private Integer waijishoushang = 0;
/**
* 财产损失(元)
*/
@ApiModelProperty(value = "财产损失(元)")
private BigDecimal caichansunshi = new BigDecimal(0);
;
/**
* 事故概况
*/
@ApiModelProperty(value = "事故概况")
private String shigugaikuang;
/**
* 事故初步原因及责任分析
*/
@ApiModelProperty(value = "事故初步原因及责任分析")
private String zerenfenxi;
/**
* 事故照片
*/
@ApiModelProperty(value = "事故照片")
private String shiguzhaopian;
/**
* 附件
*/
@ApiModelProperty(value = "附件")
private String fujian;
/**
* 是否删除
*/
@ApiModelProperty(value = "是否删除")
@TableField("is_deleted")
private Integer isdel = 0;
/**
* 创建时间
*/
@ApiModelProperty(value = "创建时间",required = true)
private String createtime;
}
| false | 1,633 | 10 | 1,857 | 9 | 1,874 | 10 | 1,857 | 9 | 2,439 | 16 | false | false | false | false | false | true |
26914_14 | package site.dunhanson.aliyun.tablestore.entity.bidi.enterprise;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author jiangzf
* @version 1.0
* @date 2019/5/28 11:14
* @description TODO
*/
@Getter
@Setter
@ToString
public class EnterpriseProfileCourtAnnouncementItem {
//id
private Long tycId;
//公告id
private Long announce_id;
//公告号
private String bltnno;
//公告状态号
private String bltnstate;
//公告类型
private String bltntype;
//公告类型名称
private String bltntypename;
//案件号
private String caseno;
//案件内容
private String content;
//法院名
private String courtcode;
//处理等级
private String dealgrade;
//处理等级名称
private String dealgradename;
//法官
private String judge;
//法官电话
private String judgephone;
//手机号
private String mobilephone;
//原告
private String party1;
//当事人
private String party2;
private List<CompanyList> companyList;
//跳转到天眼查链接
private String party1Str;
//跳转到天眼查链接
private String party2Str;
//省份
private String province;
//刊登日期
private String publishdate;
//刊登版面
private String publishpage;
//原因
private String reason;
}
| bellmit/easy-tablestore | src/main/java/site/dunhanson/aliyun/tablestore/entity/bidi/enterprise/EnterpriseProfileCourtAnnouncementItem.java | 402 | //跳转到天眼查链接 | line_comment | zh-cn | package site.dunhanson.aliyun.tablestore.entity.bidi.enterprise;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import java.util.List;
/**
* @author jiangzf
* @version 1.0
* @date 2019/5/28 11:14
* @description TODO
*/
@Getter
@Setter
@ToString
public class EnterpriseProfileCourtAnnouncementItem {
//id
private Long tycId;
//公告id
private Long announce_id;
//公告号
private String bltnno;
//公告状态号
private String bltnstate;
//公告类型
private String bltntype;
//公告类型名称
private String bltntypename;
//案件号
private String caseno;
//案件内容
private String content;
//法院名
private String courtcode;
//处理等级
private String dealgrade;
//处理等级名称
private String dealgradename;
//法官
private String judge;
//法官电话
private String judgephone;
//手机号
private String mobilephone;
//原告
private String party1;
//当事人
private String party2;
private List<CompanyList> companyList;
//跳转 <SUF>
private String party1Str;
//跳转到天眼查链接
private String party2Str;
//省份
private String province;
//刊登日期
private String publishdate;
//刊登版面
private String publishpage;
//原因
private String reason;
}
| false | 377 | 8 | 402 | 7 | 421 | 7 | 402 | 7 | 504 | 15 | false | false | false | false | false | true |
37771_1 | package cn.gyw.frameworks.netty.base.handler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class TestClientHandler extends ChannelInboundHandlerAdapter {
private static int counter;
private byte[] req;
public TestClientHandler() {
String mock = "先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以塞忠谏之路也。宫中府中,俱为一体;陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不宜偏私,使内外异法也。侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯,是以先帝简拔以遗陛下。愚以为宫中之事,事无大小,悉以咨之,然后施行,必能裨补阙漏,有所广益。将军向宠,性行淑均,晓畅军事,试用于昔日,先帝称之曰能,是以众议举宠为督。愚以为营中之事,悉以咨之,必能使行阵和睦,优劣得所。亲贤臣,远小人,此先汉所以兴隆也;亲小人,远贤臣,此后汉所以倾颓也。先帝在时,每与臣论此事,未尝不叹息痛恨于桓、灵也。侍中、尚书、长史、参军,此悉贞良死节之臣,愿陛下亲之信之,则汉室之隆,可计日而待也。臣本布衣,躬耕于南阳,苟全性命于乱世,不求闻达于诸侯。先帝不以臣卑鄙,猥自枉屈,三顾臣于草庐之中,咨臣以当世之事,由是感激,遂许先帝以驱驰。后值倾覆,受任于败军之际,奉命于危难之间,尔来二十有一年矣。先帝知臣谨慎,故临崩寄臣以大事也。受命以来,夙夜忧叹,恐托付不效,以伤先帝之明;故五月渡泸,深入不毛。今南方已定,兵甲已足,当奖率三军,北定中原,庶竭驽钝,攘除奸凶,兴复汉室,还于旧都。此臣所以报先帝而忠陛下之职分也。至于斟酌损益,进尽忠言,则攸之、祎、允之任也。愿陛下托臣以讨贼兴复之效,不效,则治臣之罪,以告先帝之灵。若无兴德之言,则责攸之、祎、允等之慢,以彰其咎;陛下亦宜自谋,以咨诹善道,察纳雅言,深追先帝遗诏。臣不胜受恩感激。今当远离,临表涕零,不知所言。";
// req = ("current time:" + System.getProperty("line.separator")).getBytes();
req = ("current time:" + "$_").getBytes();
// 模拟拆包现象
// req = mock.getBytes();
req = (mock + System.getProperty("line.separator")).getBytes();
System.out.println("request length :" + req.length);
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ByteBuf firstMessage = null;
// 连接成功后,发送消息,连续发送100次,模拟数据交互的频繁
int cnt = 100; // 模拟粘包
// 粘包测试
for (int i = 0; i < cnt; i++) {
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
ctx.writeAndFlush(firstMessage);
System.out.println("Send message success...");
}
// 半包问题
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
String body = "";
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
body = new String(req, "UTF-8");
} else if (msg instanceof String) {
body = (String) msg;
}
System.out.println("now is [" + body + "] >> the counter is " + ++counter);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
// 释放资源
ctx.close();
}
}
| bellmit/individual-study | frameworks/netty/src/main/java/cn/gyw/frameworks/netty/base/handler/TestClientHandler.java | 1,479 | // 模拟拆包现象 | line_comment | zh-cn | package cn.gyw.frameworks.netty.base.handler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
public class TestClientHandler extends ChannelInboundHandlerAdapter {
private static int counter;
private byte[] req;
public TestClientHandler() {
String mock = "先帝创业未半而中道崩殂,今天下三分,益州疲弊,此诚危急存亡之秋也。然侍卫之臣不懈于内,忠志之士忘身于外者,盖追先帝之殊遇,欲报之于陛下也。诚宜开张圣听,以光先帝遗德,恢弘志士之气,不宜妄自菲薄,引喻失义,以塞忠谏之路也。宫中府中,俱为一体;陟罚臧否,不宜异同。若有作奸犯科及为忠善者,宜付有司论其刑赏,以昭陛下平明之理,不宜偏私,使内外异法也。侍中、侍郎郭攸之、费祎、董允等,此皆良实,志虑忠纯,是以先帝简拔以遗陛下。愚以为宫中之事,事无大小,悉以咨之,然后施行,必能裨补阙漏,有所广益。将军向宠,性行淑均,晓畅军事,试用于昔日,先帝称之曰能,是以众议举宠为督。愚以为营中之事,悉以咨之,必能使行阵和睦,优劣得所。亲贤臣,远小人,此先汉所以兴隆也;亲小人,远贤臣,此后汉所以倾颓也。先帝在时,每与臣论此事,未尝不叹息痛恨于桓、灵也。侍中、尚书、长史、参军,此悉贞良死节之臣,愿陛下亲之信之,则汉室之隆,可计日而待也。臣本布衣,躬耕于南阳,苟全性命于乱世,不求闻达于诸侯。先帝不以臣卑鄙,猥自枉屈,三顾臣于草庐之中,咨臣以当世之事,由是感激,遂许先帝以驱驰。后值倾覆,受任于败军之际,奉命于危难之间,尔来二十有一年矣。先帝知臣谨慎,故临崩寄臣以大事也。受命以来,夙夜忧叹,恐托付不效,以伤先帝之明;故五月渡泸,深入不毛。今南方已定,兵甲已足,当奖率三军,北定中原,庶竭驽钝,攘除奸凶,兴复汉室,还于旧都。此臣所以报先帝而忠陛下之职分也。至于斟酌损益,进尽忠言,则攸之、祎、允之任也。愿陛下托臣以讨贼兴复之效,不效,则治臣之罪,以告先帝之灵。若无兴德之言,则责攸之、祎、允等之慢,以彰其咎;陛下亦宜自谋,以咨诹善道,察纳雅言,深追先帝遗诏。臣不胜受恩感激。今当远离,临表涕零,不知所言。";
// req = ("current time:" + System.getProperty("line.separator")).getBytes();
req = ("current time:" + "$_").getBytes();
// 模拟 <SUF>
// req = mock.getBytes();
req = (mock + System.getProperty("line.separator")).getBytes();
System.out.println("request length :" + req.length);
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ByteBuf firstMessage = null;
// 连接成功后,发送消息,连续发送100次,模拟数据交互的频繁
int cnt = 100; // 模拟粘包
// 粘包测试
for (int i = 0; i < cnt; i++) {
firstMessage = Unpooled.buffer(req.length);
firstMessage.writeBytes(req);
ctx.writeAndFlush(firstMessage);
System.out.println("Send message success...");
}
// 半包问题
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
try {
String body = "";
if (msg instanceof ByteBuf) {
ByteBuf buf = (ByteBuf) msg;
byte[] req = new byte[buf.readableBytes()];
buf.readBytes(req);
body = new String(req, "UTF-8");
} else if (msg instanceof String) {
body = (String) msg;
}
System.out.println("now is [" + body + "] >> the counter is " + ++counter);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
// 释放资源
ctx.close();
}
}
| false | 1,131 | 7 | 1,479 | 8 | 1,212 | 5 | 1,479 | 8 | 1,913 | 12 | false | false | false | false | false | true |
18826_14 | package Ms;
import javax.sound.midi.Soundbank;
import java.beans.IntrospectionException;
/**
* @author Apache-x | A You Ok
* @version 1.0
* @date 2021/2/24 15:44
* @Description
*/
public class IntegerTest {
/**
* // == 比较的是地址值 equals 比较的是值 ? so 你在开玩笑吗 ?
*
* • 两个 int 相比 ==
* • 两个 new Integer 相比 [== & equals]
* • 两个 非 new Integer 相比 [== & equals]
* • 一个 new Integer 跟 一个 int 相比 [== & equals]
* • 一个 new Integer 跟 一个 非 new Integer 相比 [== & equals]
* • 一个 int 跟一 非 new Integer 相比 [== & equals]
*/
public static void main(String[] args) {
// 两个 int 相比 ==
int a = 1;
int b = 1;
System.out.println(a == b); // true 比较的是具体的值
// 两个 new Integer 相比 [== & equals]
Integer a1 = new Integer(100);
Integer a2 = new Integer(100);
System.out.println(a1 == a2); // false 比较的是 地址值
System.out.println(a1.equals(a2)); // true 比较的是 具体的值 value == ((Integer)obj).intValue(); intValue () 返回的是 int
//两个 非 new Integer 相比 [== & equals]
Integer z1 = 100;
Integer z2 = 100;
System.out.println(z1 == z2); // true 直接进行包装 包装的方法为 valueOf(100) valueOf 涉及到缓存池
System.out.println(z1.equals(z2)); // true
// 一个 new Integer 跟 一个 int 相比 [== & equals]
Integer q1 = new Integer(100);
int q2 = 100;
System.out.println("q1 == q2" + (q1 == q2)); // true 拆包 比较的是 具体的值 intValue () 返回的是 int
System.out.println(q1.equals(q2)); // true
// 一个 new Integer 跟 一个 非 new Integer 相比 [== & equals]
Integer w1 = new Integer(100);
Integer w2 = 100;
System.out.println(w1 == w2); // false 地址值 一个在常量池 一个在 堆空间
System.out.println(w1.equals(w2));//true 比较的是具体的值 intValue()
// 一个 int 跟一 非 new Integer 相比 [== & equals]
int e1 = 100;
Integer e2 = new Integer(100);
System.out.println(e1 == e2); // true
System.out.println(e2.equals(e1)); // true
// Integer 缓存以外的数字 -128 ~ 127
Integer c1 = new Integer(129);
Integer c2 = 129;
System.out.println(c1.equals(c2)); // true 具体值相同
System.out.println(c1 == c2); // false 引用不同
}
}
| bellmit/software-engineer | java/java-basis-package/src/main/java/Ms/IntegerTest.java | 828 | // false 地址值 一个在常量池 一个在 堆空间 | line_comment | zh-cn | package Ms;
import javax.sound.midi.Soundbank;
import java.beans.IntrospectionException;
/**
* @author Apache-x | A You Ok
* @version 1.0
* @date 2021/2/24 15:44
* @Description
*/
public class IntegerTest {
/**
* // == 比较的是地址值 equals 比较的是值 ? so 你在开玩笑吗 ?
*
* • 两个 int 相比 ==
* • 两个 new Integer 相比 [== & equals]
* • 两个 非 new Integer 相比 [== & equals]
* • 一个 new Integer 跟 一个 int 相比 [== & equals]
* • 一个 new Integer 跟 一个 非 new Integer 相比 [== & equals]
* • 一个 int 跟一 非 new Integer 相比 [== & equals]
*/
public static void main(String[] args) {
// 两个 int 相比 ==
int a = 1;
int b = 1;
System.out.println(a == b); // true 比较的是具体的值
// 两个 new Integer 相比 [== & equals]
Integer a1 = new Integer(100);
Integer a2 = new Integer(100);
System.out.println(a1 == a2); // false 比较的是 地址值
System.out.println(a1.equals(a2)); // true 比较的是 具体的值 value == ((Integer)obj).intValue(); intValue () 返回的是 int
//两个 非 new Integer 相比 [== & equals]
Integer z1 = 100;
Integer z2 = 100;
System.out.println(z1 == z2); // true 直接进行包装 包装的方法为 valueOf(100) valueOf 涉及到缓存池
System.out.println(z1.equals(z2)); // true
// 一个 new Integer 跟 一个 int 相比 [== & equals]
Integer q1 = new Integer(100);
int q2 = 100;
System.out.println("q1 == q2" + (q1 == q2)); // true 拆包 比较的是 具体的值 intValue () 返回的是 int
System.out.println(q1.equals(q2)); // true
// 一个 new Integer 跟 一个 非 new Integer 相比 [== & equals]
Integer w1 = new Integer(100);
Integer w2 = 100;
System.out.println(w1 == w2); // fa <SUF>
System.out.println(w1.equals(w2));//true 比较的是具体的值 intValue()
// 一个 int 跟一 非 new Integer 相比 [== & equals]
int e1 = 100;
Integer e2 = new Integer(100);
System.out.println(e1 == e2); // true
System.out.println(e2.equals(e1)); // true
// Integer 缓存以外的数字 -128 ~ 127
Integer c1 = new Integer(129);
Integer c2 = 129;
System.out.println(c1.equals(c2)); // true 具体值相同
System.out.println(c1 == c2); // false 引用不同
}
}
| false | 798 | 19 | 828 | 17 | 808 | 13 | 828 | 17 | 994 | 23 | false | false | false | false | false | true |
55096_1 | package com.haozhuo.datag.model.bisys;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.haozhuo.datag.common.JavaUtils;
import java.math.BigDecimal;
/**
* Created by Lucius on 1/17/19.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class OpsMallOrder {
int id;
String date;
//下单笔数
int orderNum;
//下单金额
double orderAmount;
//支付笔数
int payOrderNum;
//支付金额
double payOrderAmount;
//申请退款笔数
int applyRefundOrderNum;
//申请退款金额
double applyRefundOrderAmount;
//退款完成笔数
int refundOrderNum;
//退款完成金额
double refundOrderAmount;
public OpsMallOrder(int id, String date, int orderNum, double orderAmount, int payOrderNum, double payOrderAmount, int applyRefundOrderNum, double applyRefundOrderAmount, int refundOrderNum, double refundOrderAmount) {
this.id = id;
this.date = date;
this.orderNum = orderNum;
this.orderAmount = orderAmount;
this.payOrderNum = payOrderNum;
this.payOrderAmount = payOrderAmount;
this.applyRefundOrderNum = applyRefundOrderNum;
this.applyRefundOrderAmount = applyRefundOrderAmount;
this.refundOrderNum = refundOrderNum;
this.refundOrderAmount = refundOrderAmount;
}
public void setId(int id) {
this.id = id;
}
double grossProfit = -1;
double grossProfitRate = -1;
double payConversionRate = -1;
double refundRate = -1;
double refundGrossProfit = -1;
public void setRefundGrossProfit(double refundGrossProfit) {
this.refundGrossProfit = refundGrossProfit;
}
public double getRefundGrossProfit() {
return refundGrossProfit;
}
public void setGrossProfit(double grossProfit) {
this.grossProfit = grossProfit;
}
public void setGrossProfitRate(double grossProfitRate) {
this.grossProfitRate = grossProfitRate;
}
public void setPayConversionRate(double payConversionRate) {
this.payConversionRate = payConversionRate;
}
public void setRefundRate(double refundRate) {
this.refundRate = refundRate;
}
public OpsMallOrder(int id) {
this.id = id;
}
@JsonIgnore
public boolean isInputMallOrder() {
return isInputMallOrder(id);
}
public static boolean isInputMallOrder(int id) {
return id >= 10 && id <= 13;
}
//毛利润
public Double getGrossProfit() {
if (isInputMallOrder() && grossProfit >= 0) {
return grossProfit;
}
double value = 0D;
switch (id) {
case 1:
case 2:
value = payOrderAmount - payOrderNum * 22;
break;
case 3:
value = payOrderAmount * 0.3;
break;
case 4:
value = payOrderAmount - payOrderNum * 5;
break;
case 5:
value = payOrderAmount - payOrderNum * 15;
break;
case 6:
case 7:
case 8:
value = payOrderAmount;
break;
case 9:
if (payOrderNum > 0) {
value = payOrderAmount - 15;
}
break;
}
return JavaUtils.retainDecimal(value, 2);
}
public double round(double value) {
return new BigDecimal(value).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
//毛利润率
public Double getGrossProfitRate() {
if (isInputMallOrder() && grossProfitRate >= 0) {
return grossProfitRate;
}
if (payOrderNum == 0) {
return 0D;
} else {
return payOrderAmount == 0 ? 0 : JavaUtils.retainDecimal(getGrossProfit() / payOrderAmount, 4);
}
}
//支付转化率
public Double getPayConversionRate() {
if (isInputMallOrder() && payConversionRate >= 0) {
return payConversionRate;
}
if (orderNum == 0) {
return 0D;
} else {
return orderNum == 0 ? 0 : JavaUtils.retainDecimal(Double.valueOf(payOrderNum) / orderNum, 2);
}
}
//退款率
public Double getRefundRate() {
if (isInputMallOrder() && refundRate >= 0) {
return refundRate;
}
if (payOrderNum == 0) {
return 0D;
} else {
return payOrderNum == 0 ? 0 : JavaUtils.retainDecimal(Double.valueOf(refundOrderNum) / payOrderNum, 4);
}
}
@JsonIgnore
public String getGenre() {
return getGenre(id);
}
public static String getGenre(int id) {
switch (id) {
case 1:
return "电话解读";
case 2:
return "解读复购";
case 3:
return "电话问诊";
case 4:
return "深度解读";
case 5:
return "专项解读";
case 6:
return "一元听听";
case 7:
return "uplus会员";
case 8:
return "高血糖风险评估";
case 9:
return "冠心病";
case 10:
return "健管服务";
case 11:
return "绿通";
case 12:
return "美维口腔";
case 13:
return "基因检测";
default:
return "";
}
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getOrderNum() {
return orderNum;
}
public void setOrderNum(int orderNum) {
this.orderNum = orderNum;
}
public double getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(double orderAmount) {
this.orderAmount = orderAmount;
}
public int getPayOrderNum() {
return payOrderNum;
}
public void setPayOrderNum(int payOrderNum) {
this.payOrderNum = payOrderNum;
}
public double getPayOrderAmount() {
return payOrderAmount;
}
public void setPayOrderAmount(double payOrderAmount) {
this.payOrderAmount = payOrderAmount;
}
public int getApplyRefundOrderNum() {
return applyRefundOrderNum;
}
public void setApplyRefundOrderNum(int applyRefundOrderNum) {
this.applyRefundOrderNum = applyRefundOrderNum;
}
public double getApplyRefundOrderAmount() {
return applyRefundOrderAmount;
}
public void setApplyRefundOrderAmount(double applyRefundOrderAmount) {
this.applyRefundOrderAmount = applyRefundOrderAmount;
}
public int getRefundOrderNum() {
return refundOrderNum;
}
public void setRefundOrderNum(int refundOrderNum) {
this.refundOrderNum = refundOrderNum;
}
public double getRefundOrderAmount() {
return refundOrderAmount;
}
public void setRefundOrderAmount(double refundOrderAmount) {
this.refundOrderAmount = refundOrderAmount;
}
public int getId() {
return id;
}
public OpsMallOrder() {
}
}
| bellmit/spring-apps | datag/src/main/java/com/haozhuo/datag/model/bisys/OpsMallOrder.java | 1,843 | //下单笔数 | line_comment | zh-cn | package com.haozhuo.datag.model.bisys;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.haozhuo.datag.common.JavaUtils;
import java.math.BigDecimal;
/**
* Created by Lucius on 1/17/19.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class OpsMallOrder {
int id;
String date;
//下单 <SUF>
int orderNum;
//下单金额
double orderAmount;
//支付笔数
int payOrderNum;
//支付金额
double payOrderAmount;
//申请退款笔数
int applyRefundOrderNum;
//申请退款金额
double applyRefundOrderAmount;
//退款完成笔数
int refundOrderNum;
//退款完成金额
double refundOrderAmount;
public OpsMallOrder(int id, String date, int orderNum, double orderAmount, int payOrderNum, double payOrderAmount, int applyRefundOrderNum, double applyRefundOrderAmount, int refundOrderNum, double refundOrderAmount) {
this.id = id;
this.date = date;
this.orderNum = orderNum;
this.orderAmount = orderAmount;
this.payOrderNum = payOrderNum;
this.payOrderAmount = payOrderAmount;
this.applyRefundOrderNum = applyRefundOrderNum;
this.applyRefundOrderAmount = applyRefundOrderAmount;
this.refundOrderNum = refundOrderNum;
this.refundOrderAmount = refundOrderAmount;
}
public void setId(int id) {
this.id = id;
}
double grossProfit = -1;
double grossProfitRate = -1;
double payConversionRate = -1;
double refundRate = -1;
double refundGrossProfit = -1;
public void setRefundGrossProfit(double refundGrossProfit) {
this.refundGrossProfit = refundGrossProfit;
}
public double getRefundGrossProfit() {
return refundGrossProfit;
}
public void setGrossProfit(double grossProfit) {
this.grossProfit = grossProfit;
}
public void setGrossProfitRate(double grossProfitRate) {
this.grossProfitRate = grossProfitRate;
}
public void setPayConversionRate(double payConversionRate) {
this.payConversionRate = payConversionRate;
}
public void setRefundRate(double refundRate) {
this.refundRate = refundRate;
}
public OpsMallOrder(int id) {
this.id = id;
}
@JsonIgnore
public boolean isInputMallOrder() {
return isInputMallOrder(id);
}
public static boolean isInputMallOrder(int id) {
return id >= 10 && id <= 13;
}
//毛利润
public Double getGrossProfit() {
if (isInputMallOrder() && grossProfit >= 0) {
return grossProfit;
}
double value = 0D;
switch (id) {
case 1:
case 2:
value = payOrderAmount - payOrderNum * 22;
break;
case 3:
value = payOrderAmount * 0.3;
break;
case 4:
value = payOrderAmount - payOrderNum * 5;
break;
case 5:
value = payOrderAmount - payOrderNum * 15;
break;
case 6:
case 7:
case 8:
value = payOrderAmount;
break;
case 9:
if (payOrderNum > 0) {
value = payOrderAmount - 15;
}
break;
}
return JavaUtils.retainDecimal(value, 2);
}
public double round(double value) {
return new BigDecimal(value).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
//毛利润率
public Double getGrossProfitRate() {
if (isInputMallOrder() && grossProfitRate >= 0) {
return grossProfitRate;
}
if (payOrderNum == 0) {
return 0D;
} else {
return payOrderAmount == 0 ? 0 : JavaUtils.retainDecimal(getGrossProfit() / payOrderAmount, 4);
}
}
//支付转化率
public Double getPayConversionRate() {
if (isInputMallOrder() && payConversionRate >= 0) {
return payConversionRate;
}
if (orderNum == 0) {
return 0D;
} else {
return orderNum == 0 ? 0 : JavaUtils.retainDecimal(Double.valueOf(payOrderNum) / orderNum, 2);
}
}
//退款率
public Double getRefundRate() {
if (isInputMallOrder() && refundRate >= 0) {
return refundRate;
}
if (payOrderNum == 0) {
return 0D;
} else {
return payOrderNum == 0 ? 0 : JavaUtils.retainDecimal(Double.valueOf(refundOrderNum) / payOrderNum, 4);
}
}
@JsonIgnore
public String getGenre() {
return getGenre(id);
}
public static String getGenre(int id) {
switch (id) {
case 1:
return "电话解读";
case 2:
return "解读复购";
case 3:
return "电话问诊";
case 4:
return "深度解读";
case 5:
return "专项解读";
case 6:
return "一元听听";
case 7:
return "uplus会员";
case 8:
return "高血糖风险评估";
case 9:
return "冠心病";
case 10:
return "健管服务";
case 11:
return "绿通";
case 12:
return "美维口腔";
case 13:
return "基因检测";
default:
return "";
}
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getOrderNum() {
return orderNum;
}
public void setOrderNum(int orderNum) {
this.orderNum = orderNum;
}
public double getOrderAmount() {
return orderAmount;
}
public void setOrderAmount(double orderAmount) {
this.orderAmount = orderAmount;
}
public int getPayOrderNum() {
return payOrderNum;
}
public void setPayOrderNum(int payOrderNum) {
this.payOrderNum = payOrderNum;
}
public double getPayOrderAmount() {
return payOrderAmount;
}
public void setPayOrderAmount(double payOrderAmount) {
this.payOrderAmount = payOrderAmount;
}
public int getApplyRefundOrderNum() {
return applyRefundOrderNum;
}
public void setApplyRefundOrderNum(int applyRefundOrderNum) {
this.applyRefundOrderNum = applyRefundOrderNum;
}
public double getApplyRefundOrderAmount() {
return applyRefundOrderAmount;
}
public void setApplyRefundOrderAmount(double applyRefundOrderAmount) {
this.applyRefundOrderAmount = applyRefundOrderAmount;
}
public int getRefundOrderNum() {
return refundOrderNum;
}
public void setRefundOrderNum(int refundOrderNum) {
this.refundOrderNum = refundOrderNum;
}
public double getRefundOrderAmount() {
return refundOrderAmount;
}
public void setRefundOrderAmount(double refundOrderAmount) {
this.refundOrderAmount = refundOrderAmount;
}
public int getId() {
return id;
}
public OpsMallOrder() {
}
}
| false | 1,757 | 4 | 1,843 | 5 | 1,998 | 4 | 1,843 | 5 | 2,338 | 7 | false | false | false | false | false | true |
11973_10 | package com.sq.transportmanage.gateway.service.util;
import com.sq.transportmanage.gateway.service.common.constants.CheckConstants;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 检测工具.
*
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author lunan
* @since 1.0
* @version 1.0
*/
public class Check {
/**
* 检测Java对象是否为空.
*
* @param obj
* 待检测的对象
* @return true: 空; false:非空.
*/
public static boolean NuNObj(final Object obj) {
if(obj == null) {
return true;
}
if (obj instanceof String) {
return NuNStr((String) obj);
}
return false;
}
/**
* 检测Java对象是否为空. 同时检测多个指定的对象, 如果存在一个为空, 则全部为空.
*
* @param objs
* 待检测的对象
* @return true: 空; false:非空.
*/
public static boolean NuNObjs(final Object... objs) {
for (final Object obj : objs) {
final boolean nun = NuNObj(obj);
if (nun) {
return true;
}
}
return false;
}
/**
* 检测Java对象是否为空. 同时检测多个指定的对象, 如果存在一个为空, 则全部为空.
*
* @param objs
* 待检测的对象
* @return true: 空; false:非空.
*/
public static boolean NuNObject(final Object[] objs) {
if ((objs == null) || (objs.length == 0)) {
return true;
}
for (final Object obj : objs) {
final boolean nun = NuNObj(obj);
if (nun) {
return true;
}
}
return false;
}
/**
* 检测字符串是否为空.
* <p>
* 1. 未分配内存
* </p>
* <p>
* 2. 字符串剔除掉前后空格后的长度为0
* </p>
*
* @param str
* 待检测的字符串
* @return true: 空; false:非空.
*/
public static boolean NuNStr(final String str) {
return (str == null) || (str.trim().length() == 0);
}
/**
* 严格的检测字符串是否为空.
* <p>
* 1. 未分配内存
* </p>
* <p>
* 2. 字符串剔除掉前后空格后的长度为0
* </p>
* <p>
* 3. 字符串为'null'字串.
* </p>
*
* @param str
* 待检测的字符串
* @return true: 空; false:非空.
*/
public static boolean NuNStrStrict(final String str) {
return NuNStr(str) || "null".equalsIgnoreCase(str);
}
/**
* 判断集合是否为空
*
* @param colls
* 待检测的集合
* @return true: 空; false:非空.
*/
public static boolean NuNCollection(final Collection<?> colls) {
return (colls == null) || colls.isEmpty();
}
/**
* 判断Map集合是否为空
*
* @param map
* 待检测的集合
* @return true: 空; false:非空.
*/
public static boolean NuNMap(final Map<?, ?> map) {
return (map == null) || map.isEmpty();
}
/**
*
* 编码URL参数. 提供默认的URT-8编码格式
*
* @author YRJ
* @created 2014年12月21日 下午5:26:57
*
* @param params
* @return
*/
public static String encodeUrl(final String params) {
return encodeUrl(params, "UTF-8");
}
/**
*
* 编码URL参数
*
* @author YRJ
* @created 2014年12月21日 下午5:26:39
*
* @param params 待编码的值
* @param encode 编码格式
* @return
*/
public static String encodeUrl(final String params, final String encode) {
try {
return URLEncoder.encode(params, encode);
} catch (final UnsupportedEncodingException e) {
return encodeUrl(params, "UTF-8");//如果你再错, 就是混蛋王八蛋了.
}
}
public static String replaceBlank(String str) {
String dest = "";
if (str!=null) {
Pattern p = CheckConstants.p;
Matcher m = p.matcher(str);
dest = m.replaceAll("").toUpperCase();
}
return dest.replaceAll("\\s*", "");
}
private Check() {
throw new AssertionError("Uninstantiable class");
};
public static void main(String[] args) {
Long n1 = 6553699777L;
DecimalFormat df1 = new DecimalFormat("##,###.##");
System.out.println(df1.format(n1));//1,234.527
DecimalFormat a = new DecimalFormat(".##");
String s= a.format(33333);
System.err.println(s);
}
}
| bellmit/springboot-shiro | transport-manage-service/src/main/java/com/sq/transportmanage/gateway/service/util/Check.java | 1,426 | //如果你再错, 就是混蛋王八蛋了. | line_comment | zh-cn | package com.sq.transportmanage.gateway.service.util;
import com.sq.transportmanage.gateway.service.common.constants.CheckConstants;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 检测工具.
*
* <PRE>
* <BR> 修改记录
* <BR>-----------------------------------------------
* <BR> 修改日期 修改人 修改内容
* </PRE>
*
* @author lunan
* @since 1.0
* @version 1.0
*/
public class Check {
/**
* 检测Java对象是否为空.
*
* @param obj
* 待检测的对象
* @return true: 空; false:非空.
*/
public static boolean NuNObj(final Object obj) {
if(obj == null) {
return true;
}
if (obj instanceof String) {
return NuNStr((String) obj);
}
return false;
}
/**
* 检测Java对象是否为空. 同时检测多个指定的对象, 如果存在一个为空, 则全部为空.
*
* @param objs
* 待检测的对象
* @return true: 空; false:非空.
*/
public static boolean NuNObjs(final Object... objs) {
for (final Object obj : objs) {
final boolean nun = NuNObj(obj);
if (nun) {
return true;
}
}
return false;
}
/**
* 检测Java对象是否为空. 同时检测多个指定的对象, 如果存在一个为空, 则全部为空.
*
* @param objs
* 待检测的对象
* @return true: 空; false:非空.
*/
public static boolean NuNObject(final Object[] objs) {
if ((objs == null) || (objs.length == 0)) {
return true;
}
for (final Object obj : objs) {
final boolean nun = NuNObj(obj);
if (nun) {
return true;
}
}
return false;
}
/**
* 检测字符串是否为空.
* <p>
* 1. 未分配内存
* </p>
* <p>
* 2. 字符串剔除掉前后空格后的长度为0
* </p>
*
* @param str
* 待检测的字符串
* @return true: 空; false:非空.
*/
public static boolean NuNStr(final String str) {
return (str == null) || (str.trim().length() == 0);
}
/**
* 严格的检测字符串是否为空.
* <p>
* 1. 未分配内存
* </p>
* <p>
* 2. 字符串剔除掉前后空格后的长度为0
* </p>
* <p>
* 3. 字符串为'null'字串.
* </p>
*
* @param str
* 待检测的字符串
* @return true: 空; false:非空.
*/
public static boolean NuNStrStrict(final String str) {
return NuNStr(str) || "null".equalsIgnoreCase(str);
}
/**
* 判断集合是否为空
*
* @param colls
* 待检测的集合
* @return true: 空; false:非空.
*/
public static boolean NuNCollection(final Collection<?> colls) {
return (colls == null) || colls.isEmpty();
}
/**
* 判断Map集合是否为空
*
* @param map
* 待检测的集合
* @return true: 空; false:非空.
*/
public static boolean NuNMap(final Map<?, ?> map) {
return (map == null) || map.isEmpty();
}
/**
*
* 编码URL参数. 提供默认的URT-8编码格式
*
* @author YRJ
* @created 2014年12月21日 下午5:26:57
*
* @param params
* @return
*/
public static String encodeUrl(final String params) {
return encodeUrl(params, "UTF-8");
}
/**
*
* 编码URL参数
*
* @author YRJ
* @created 2014年12月21日 下午5:26:39
*
* @param params 待编码的值
* @param encode 编码格式
* @return
*/
public static String encodeUrl(final String params, final String encode) {
try {
return URLEncoder.encode(params, encode);
} catch (final UnsupportedEncodingException e) {
return encodeUrl(params, "UTF-8");//如果 <SUF>
}
}
public static String replaceBlank(String str) {
String dest = "";
if (str!=null) {
Pattern p = CheckConstants.p;
Matcher m = p.matcher(str);
dest = m.replaceAll("").toUpperCase();
}
return dest.replaceAll("\\s*", "");
}
private Check() {
throw new AssertionError("Uninstantiable class");
};
public static void main(String[] args) {
Long n1 = 6553699777L;
DecimalFormat df1 = new DecimalFormat("##,###.##");
System.out.println(df1.format(n1));//1,234.527
DecimalFormat a = new DecimalFormat(".##");
String s= a.format(33333);
System.err.println(s);
}
}
| false | 1,330 | 15 | 1,426 | 16 | 1,488 | 13 | 1,426 | 16 | 1,832 | 23 | false | false | false | false | false | true |
63271_3 | package com.tonbu.web.admin.action;
import com.tonbu.framework.dao.DBHelper;
import com.tonbu.framework.data.ResultEntity;
import com.tonbu.framework.data.UserEntity;
import com.tonbu.framework.exception.CustomizeException;
import com.tonbu.support.shiro.CustomRealm;
import com.tonbu.support.util.DESUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.*;
@Controller
public class LoginAction {
Logger logger = LogManager.getLogger(LoginAction.class.getName());
@Value("${im.ip}")
private String ip;
@RequestMapping(value = "/login")
public String login() {
Subject subject = SecurityUtils.getSubject();
if (subject != null && subject.isAuthenticated()) {
return "redirect:main";
} else {
return "login";
}
}
/**
* 移动端
* @return
*/
@RequestMapping(value = "/mobile/login")
public String mobileLogin() {
Subject subject = SecurityUtils.getSubject();
if (subject != null && subject.isAuthenticated()) {
return "redirect:mobile";
} else {
return "mobileLogin";
}
}
@RequestMapping(value = "/index")
public String index() {
return "index";
}
@RequestMapping(value = "/home")
public ModelAndView home() {
ModelAndView view = new ModelAndView("home");
view.addObject("attr", "12345");
return view;
}
@RequestMapping(value = "/main")
public String main() {
return "main";
}
/**
* 登录验证 客户端
*
* @return ResultEntity
*/
@RequestMapping(value = "/check", method = RequestMethod.POST)
@ResponseBody
public Object check(String username, String password) {
ResultEntity r = new ResultEntity();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
username, password);
usernamePasswordToken.setRememberMe(true);
String msg = "";
Subject subject = SecurityUtils.getSubject();
try {
subject.login(usernamePasswordToken); // 完成登录
UserEntity u = (UserEntity) subject.getPrincipal();
Session session = subject.getSession();
logger.info("sessionId:" + session.getId());
logger.info("sessionTimeOut:" + session.getTimeout());
logger.info("sessionHost:" + session.getHost());
subject.getSession().setAttribute("loginuser", u);
subject.getSession().setAttribute("im_ip", ip);
subject.getSession().setAttribute("userToken", DESUtils.encrypt(u.getUser_id()));
subject.getSession().setAttribute("ip", ip);
Collection<Object> lll = session.getAttributeKeys();
msg = "登陆成功!";
loginLog(u.getUser_id(), u.getLoginname(), u.getUsername(), 0, 1, session.getHost());
//更改登录时间
DBHelper.execute("UPDATE ACCOUNT SET LAST_LOGIN_TIME = SYSDATE WHERE ID = ?",u.getId());
List<Object> l = new ArrayList<Object>();
l.add(u);
r.setCode(1);
r.setDataset(l);
} catch (Exception exception) {
if (exception instanceof UnknownAccountException) {
logger.error("账号不存在: -- > UnknownAccountException");
msg = "登录失败,账号不存在或未关联系统用户!";
throw new CustomizeException(msg);
} else if (exception instanceof IncorrectCredentialsException) {
logger.error(" 密码不正确: -- >IncorrectCredentialsException");
msg = "登录失败,密码不正确!";
throw new CustomizeException(msg);
} else {
logger.error("else -- >" + exception);
msg = "登录失败,发生未知错误:" + exception;
throw new CustomizeException("登录失败,发生未知错误");
}
}
r.setMsg(msg);
return r;
}
/**
* 权限获取
*
* @return ResultEntity
*/
@RequestMapping(value = "/auth/list", method = RequestMethod.GET)
@ResponseBody
public Object check(String id) {
ResultEntity r = new ResultEntity();
String msg = "";
if (!StringUtils.isNotEmpty(id)) {
r.setCode(-1);
r.setMsg("父编号不能为空");
return r;
}
try {
//获取权限列表
UserEntity u = CustomRealm.GetLoginUser();
//重新set菜单。
// List<Map<String, Object>> newMenuList = DBHelper.queryForList("select sm.ID,sm.MENUNAME,sm.MENUTYPE,sm.PARENTID,(SELECT m.MENUNAME FROM SS_menu m where m.id = sm.parentid)as PMENUNAME,sm.SYMBOL,sm.ICON,sm.URL,sm.SORT,sm.STATUS from ss_menu sm where id <>00 and status=1 order by sm.Sort,sm.id ");
// u.setMenus(newMenuList);
List<Object> l = getMenus(id, u.getMenus());
r.setCode(1);
r.setDataset(l);
} catch (Exception exception) {
logger.error("权限获取异常:" + exception);
msg = "权限获取异常:" + exception;
r.setCode(-1);
} finally {
r.setMsg(msg);
return r;
}
}
private List<Object> getMenus(String id, List<Map<String, Object>> menus) {
List<Object> r = new ArrayList<>();
for (Map<String, Object> map : menus) {
if (map.get("ID").toString().equals("0005")){//去掉了考试管理部分,因为考试管理部分代码并不在项目中
continue;
}
if (StringUtils.equals(id, map.get("PARENTID").toString()) && map.get("MENUTYPE").toString().equals("0")) {
Map<String, Object> map_c = new HashMap<>();
map_c.put("id", map.get("ID"));
map_c.put("pid", map.get("PARENTID"));
map_c.put("url", map.get("URL"));
map_c.put("icon", map.get("ICON"));
map_c.put("title", map.get("MENUNAME"));
//找兒子,看兒子是不是有數據,如果有,遞歸;
List<Object> c = getMenus(map.get("ID").toString(), menus);
if (c.size() > 0) {
map_c.put("children", c);
}
r.add(map_c);
}
}
return r;
}
/**
* 注销退出
**/
@RequestMapping(value = "/logout")
public Object logout() {
Subject subject = SecurityUtils.getSubject();
UserEntity u = (UserEntity) subject.getPrincipal();
Session session = subject.getSession();
loginLog(u.getId(), u.getLoginname(), u.getUsername(), 1, 1, session.getHost());
logger.info("***用户登出:" + u.getLoginname());
subject.logout();
return "redirect:login";
}
/**
* 未授权
**/
@RequestMapping(value = "/unauth")
public Object unauth() {
logger.error("未授权");
return "redirect:login";
}
/**
* 写登录登出记录
*
* @param user_id
* @param index 0:登录(客户端) 1:下班 2:注销 3:登录管理端 4:登出管理端
*/
public void loginLog(String user_id, String loginname, String username, int index, int loginstatus, String host) {
try {
DBHelper.execute("INSERT INTO SS_LOG_LOGIN (ID,USER_ID,LOGINNAME,USERNAME,LOGINTIME,TYPE,LOGINIP,REMARK,STATUS) VALUES (SEQ_SS_LOG.NEXTVAL,?,?,?,SYSDATE,?,?,?,?)",
user_id, loginname, username, model_name[index], host, "", loginstatus);
} catch (Exception exception) {
logger.error("登录日志写入异常:" + exception);
}
}
private static String[] model_name = {"登录", "登出"};
}
| bellmit/xfgl | xfgl-web/src/main/java/com/tonbu/web/admin/action/LoginAction.java | 2,116 | //更改登录时间 | line_comment | zh-cn | package com.tonbu.web.admin.action;
import com.tonbu.framework.dao.DBHelper;
import com.tonbu.framework.data.ResultEntity;
import com.tonbu.framework.data.UserEntity;
import com.tonbu.framework.exception.CustomizeException;
import com.tonbu.support.shiro.CustomRealm;
import com.tonbu.support.util.DESUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.*;
@Controller
public class LoginAction {
Logger logger = LogManager.getLogger(LoginAction.class.getName());
@Value("${im.ip}")
private String ip;
@RequestMapping(value = "/login")
public String login() {
Subject subject = SecurityUtils.getSubject();
if (subject != null && subject.isAuthenticated()) {
return "redirect:main";
} else {
return "login";
}
}
/**
* 移动端
* @return
*/
@RequestMapping(value = "/mobile/login")
public String mobileLogin() {
Subject subject = SecurityUtils.getSubject();
if (subject != null && subject.isAuthenticated()) {
return "redirect:mobile";
} else {
return "mobileLogin";
}
}
@RequestMapping(value = "/index")
public String index() {
return "index";
}
@RequestMapping(value = "/home")
public ModelAndView home() {
ModelAndView view = new ModelAndView("home");
view.addObject("attr", "12345");
return view;
}
@RequestMapping(value = "/main")
public String main() {
return "main";
}
/**
* 登录验证 客户端
*
* @return ResultEntity
*/
@RequestMapping(value = "/check", method = RequestMethod.POST)
@ResponseBody
public Object check(String username, String password) {
ResultEntity r = new ResultEntity();
UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
username, password);
usernamePasswordToken.setRememberMe(true);
String msg = "";
Subject subject = SecurityUtils.getSubject();
try {
subject.login(usernamePasswordToken); // 完成登录
UserEntity u = (UserEntity) subject.getPrincipal();
Session session = subject.getSession();
logger.info("sessionId:" + session.getId());
logger.info("sessionTimeOut:" + session.getTimeout());
logger.info("sessionHost:" + session.getHost());
subject.getSession().setAttribute("loginuser", u);
subject.getSession().setAttribute("im_ip", ip);
subject.getSession().setAttribute("userToken", DESUtils.encrypt(u.getUser_id()));
subject.getSession().setAttribute("ip", ip);
Collection<Object> lll = session.getAttributeKeys();
msg = "登陆成功!";
loginLog(u.getUser_id(), u.getLoginname(), u.getUsername(), 0, 1, session.getHost());
//更改 <SUF>
DBHelper.execute("UPDATE ACCOUNT SET LAST_LOGIN_TIME = SYSDATE WHERE ID = ?",u.getId());
List<Object> l = new ArrayList<Object>();
l.add(u);
r.setCode(1);
r.setDataset(l);
} catch (Exception exception) {
if (exception instanceof UnknownAccountException) {
logger.error("账号不存在: -- > UnknownAccountException");
msg = "登录失败,账号不存在或未关联系统用户!";
throw new CustomizeException(msg);
} else if (exception instanceof IncorrectCredentialsException) {
logger.error(" 密码不正确: -- >IncorrectCredentialsException");
msg = "登录失败,密码不正确!";
throw new CustomizeException(msg);
} else {
logger.error("else -- >" + exception);
msg = "登录失败,发生未知错误:" + exception;
throw new CustomizeException("登录失败,发生未知错误");
}
}
r.setMsg(msg);
return r;
}
/**
* 权限获取
*
* @return ResultEntity
*/
@RequestMapping(value = "/auth/list", method = RequestMethod.GET)
@ResponseBody
public Object check(String id) {
ResultEntity r = new ResultEntity();
String msg = "";
if (!StringUtils.isNotEmpty(id)) {
r.setCode(-1);
r.setMsg("父编号不能为空");
return r;
}
try {
//获取权限列表
UserEntity u = CustomRealm.GetLoginUser();
//重新set菜单。
// List<Map<String, Object>> newMenuList = DBHelper.queryForList("select sm.ID,sm.MENUNAME,sm.MENUTYPE,sm.PARENTID,(SELECT m.MENUNAME FROM SS_menu m where m.id = sm.parentid)as PMENUNAME,sm.SYMBOL,sm.ICON,sm.URL,sm.SORT,sm.STATUS from ss_menu sm where id <>00 and status=1 order by sm.Sort,sm.id ");
// u.setMenus(newMenuList);
List<Object> l = getMenus(id, u.getMenus());
r.setCode(1);
r.setDataset(l);
} catch (Exception exception) {
logger.error("权限获取异常:" + exception);
msg = "权限获取异常:" + exception;
r.setCode(-1);
} finally {
r.setMsg(msg);
return r;
}
}
private List<Object> getMenus(String id, List<Map<String, Object>> menus) {
List<Object> r = new ArrayList<>();
for (Map<String, Object> map : menus) {
if (map.get("ID").toString().equals("0005")){//去掉了考试管理部分,因为考试管理部分代码并不在项目中
continue;
}
if (StringUtils.equals(id, map.get("PARENTID").toString()) && map.get("MENUTYPE").toString().equals("0")) {
Map<String, Object> map_c = new HashMap<>();
map_c.put("id", map.get("ID"));
map_c.put("pid", map.get("PARENTID"));
map_c.put("url", map.get("URL"));
map_c.put("icon", map.get("ICON"));
map_c.put("title", map.get("MENUNAME"));
//找兒子,看兒子是不是有數據,如果有,遞歸;
List<Object> c = getMenus(map.get("ID").toString(), menus);
if (c.size() > 0) {
map_c.put("children", c);
}
r.add(map_c);
}
}
return r;
}
/**
* 注销退出
**/
@RequestMapping(value = "/logout")
public Object logout() {
Subject subject = SecurityUtils.getSubject();
UserEntity u = (UserEntity) subject.getPrincipal();
Session session = subject.getSession();
loginLog(u.getId(), u.getLoginname(), u.getUsername(), 1, 1, session.getHost());
logger.info("***用户登出:" + u.getLoginname());
subject.logout();
return "redirect:login";
}
/**
* 未授权
**/
@RequestMapping(value = "/unauth")
public Object unauth() {
logger.error("未授权");
return "redirect:login";
}
/**
* 写登录登出记录
*
* @param user_id
* @param index 0:登录(客户端) 1:下班 2:注销 3:登录管理端 4:登出管理端
*/
public void loginLog(String user_id, String loginname, String username, int index, int loginstatus, String host) {
try {
DBHelper.execute("INSERT INTO SS_LOG_LOGIN (ID,USER_ID,LOGINNAME,USERNAME,LOGINTIME,TYPE,LOGINIP,REMARK,STATUS) VALUES (SEQ_SS_LOG.NEXTVAL,?,?,?,SYSDATE,?,?,?,?)",
user_id, loginname, username, model_name[index], host, "", loginstatus);
} catch (Exception exception) {
logger.error("登录日志写入异常:" + exception);
}
}
private static String[] model_name = {"登录", "登出"};
}
| false | 1,826 | 4 | 2,116 | 4 | 2,227 | 4 | 2,116 | 4 | 2,603 | 7 | false | false | false | false | false | true |
19968_4 | package com.lesson.activity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.example.lesson.R;
import com.lesson.adapter.CommentsAdapter;
import com.lesson.bean.Comments;
import com.lesson.bean.GOLBALVALUE;
import com.lesson.net.NetConnectionDate;
import com.lesson.util.ActivityCollector;
import com.lesson.util.Utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CommentsActivity1 extends Activity{
private Context context;
private Button backButton;
private LinearLayout sendcommentsLinearLayout;
private ListView allcommentsListView;
private List<Comments> comments;
private CommentsAdapter adapter;
private LinearLayout noneLinearLayout;
private TextView noneTextView;
private ImageView headImageImageView;
public static Handler handler;
private LinearLayout isConnectedLinearLayout;
private LinearLayout isNotConnectedLinearLayout;
private LinearLayout reConnectLinearLayout;
private HttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.comments1_layout);
isConnectedLinearLayout = (LinearLayout) findViewById(R.id.isConnection);
isNotConnectedLinearLayout = (LinearLayout) findViewById(R.id.isnotConnection);
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if(info != null && info.isConnected()){
//联网状态
isNotConnectedLinearLayout.setVisibility(View.GONE);
isConnectedLinearLayout.setVisibility(View.VISIBLE);
System.out.println("联网");
init();
}else{
//断网状态
isNotConnectedLinearLayout.setVisibility(View.VISIBLE);
isConnectedLinearLayout.setVisibility(View.GONE);
System.out.println("断网");
isNotConnectedInit();
}
}
private void isNotConnectedInit(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
reConnectLinearLayout = (LinearLayout) findViewById(R.id.reconnect);
reConnectLinearLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if(info != null && info.isConnected()){
//联网状态
isNotConnectedLinearLayout.setVisibility(View.GONE);
isConnectedLinearLayout.setVisibility(View.VISIBLE);
init();
}else{
//断网状态
isNotConnectedLinearLayout.setVisibility(View.VISIBLE);
isConnectedLinearLayout.setVisibility(View.GONE);
isNotConnectedInit();
}
}
});
}
private void init(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
context = this;
ActivityCollector.addActivity(this);
backButton = (Button) findViewById(R.id.back);
backButton.setOnClickListener(backButtonOnClickListener);
sendcommentsLinearLayout = (LinearLayout) findViewById(R.id.send_comment);
sendcommentsLinearLayout.setOnClickListener(sendcommentsLinearLayoutOnClickListener);
allcommentsListView = (ListView) findViewById(R.id.all_comments);
noneLinearLayout = (LinearLayout) findViewById(R.id.none);
noneLinearLayout.setVisibility(View.GONE);
noneTextView = (TextView) findViewById(R.id.none_text);
noneTextView.setVisibility(View.GONE);
headImageImageView = (ImageView) findViewById(R.id.headimage);
headImageImageView.setImageBitmap(Utils.getBitmap(GOLBALVALUE.user.getHeadImage()));
System.out.println("aaaa");
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what == GOLBALVALUE.ADDCOMMENT){
if(comments == null){
comments = new ArrayList<Comments>();
}
noneLinearLayout.setVisibility(View.GONE);
noneTextView.setVisibility(View.GONE);
allcommentsListView.setVisibility(View.VISIBLE);
Comments comment = (Comments) msg.obj;
comments.add(0, comment);
allcommentsListView.setSelection(0);
adapter = new CommentsAdapter(context, R.layout.comment_item, comments,allcommentsListView);
allcommentsListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
};
getAllComments();
}
private OnClickListener backButtonOnClickListener = new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ActivityCollector.removeActivity(CommentsActivity1.this);
CommentsActivity1.this.finish();
}
};
private OnClickListener sendcommentsLinearLayoutOnClickListener = new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(context,SendCommentActivity.class);
startActivity(intent);
}
};
private void getAllComments(){
String url = NetConnectionDate.url+"GetAllCommentsServlet";
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String urlString = arg0[0];
client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("courseinfid", "0"));
String jsonarray = null;
try {
HttpEntity entity = new UrlEncodedFormEntity(list,HTTP.UTF_8);//设置编码,防止中午乱码
post.setEntity(entity);
HttpResponse response = client.execute(post);
jsonarray = EntityUtils.toString(response.getEntity());
return jsonarray;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "faliure";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "faliure";
}
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("failure")){
Toast.makeText(context, "糟糕,网络出问题了", Toast.LENGTH_SHORT).show();
}else{
comments = new ArrayList<Comments>();
JSONArray jsonarray = new JSONArray(result);
for(int i=0;i<jsonarray.length();i++){
JSONObject json = jsonarray.getJSONObject(i);
Comments comment = new Comments();
comment.setId(json.getInt("id"));
comment.setContent(json.getString("content"));
comment.setPraisenum(json.getInt("praisenum"));
comment.setSender(json.getString("sender"));
comment.setSenderheadImage(json.getString("senderheadimage"));
comment.setSenderNickName(json.getString("sendernickname"));
comment.setSendtime(json.getString("sendertime"));
comments.add(comment);
System.out.println(comment.getPraisenum());
}
}
if(comments.size()>0){
noneLinearLayout.setVisibility(View.GONE);
noneTextView.setVisibility(View.GONE);
allcommentsListView.setVisibility(View.VISIBLE);
adapter = new CommentsAdapter(context, R.layout.comment_item, comments,allcommentsListView);
allcommentsListView.setAdapter(adapter);
allcommentsListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(context,CommentsActivity2.class);
intent.putExtra("comment", comments.get(position));
context.startActivity(intent);
}
});
}else{
noneLinearLayout.setVisibility(View.VISIBLE);
noneTextView.setVisibility(View.VISIBLE);
allcommentsListView.setVisibility(View.GONE);
noneLinearLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(context,SendCommentActivity.class);
startActivity(intent);
}
});
}
}
}.execute(url);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
ActivityCollector.removeActivity(CommentsActivity1.this);
CommentsActivity1.this.finish();
}
}
| ben12138/LessonApp | src/com/lesson/activity/CommentsActivity1.java | 2,654 | // 透明导航栏
| line_comment | zh-cn | package com.lesson.activity;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import com.example.lesson.R;
import com.lesson.adapter.CommentsAdapter;
import com.lesson.bean.Comments;
import com.lesson.bean.GOLBALVALUE;
import com.lesson.net.NetConnectionDate;
import com.lesson.util.ActivityCollector;
import com.lesson.util.Utils;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class CommentsActivity1 extends Activity{
private Context context;
private Button backButton;
private LinearLayout sendcommentsLinearLayout;
private ListView allcommentsListView;
private List<Comments> comments;
private CommentsAdapter adapter;
private LinearLayout noneLinearLayout;
private TextView noneTextView;
private ImageView headImageImageView;
public static Handler handler;
private LinearLayout isConnectedLinearLayout;
private LinearLayout isNotConnectedLinearLayout;
private LinearLayout reConnectLinearLayout;
private HttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.comments1_layout);
isConnectedLinearLayout = (LinearLayout) findViewById(R.id.isConnection);
isNotConnectedLinearLayout = (LinearLayout) findViewById(R.id.isnotConnection);
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if(info != null && info.isConnected()){
//联网状态
isNotConnectedLinearLayout.setVisibility(View.GONE);
isConnectedLinearLayout.setVisibility(View.VISIBLE);
System.out.println("联网");
init();
}else{
//断网状态
isNotConnectedLinearLayout.setVisibility(View.VISIBLE);
isConnectedLinearLayout.setVisibility(View.GONE);
System.out.println("断网");
isNotConnectedInit();
}
}
private void isNotConnectedInit(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 透明 <SUF>
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
reConnectLinearLayout = (LinearLayout) findViewById(R.id.reconnect);
reConnectLinearLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if(info != null && info.isConnected()){
//联网状态
isNotConnectedLinearLayout.setVisibility(View.GONE);
isConnectedLinearLayout.setVisibility(View.VISIBLE);
init();
}else{
//断网状态
isNotConnectedLinearLayout.setVisibility(View.VISIBLE);
isConnectedLinearLayout.setVisibility(View.GONE);
isNotConnectedInit();
}
}
});
}
private void init(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// 透明状态栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 透明导航栏
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
}
context = this;
ActivityCollector.addActivity(this);
backButton = (Button) findViewById(R.id.back);
backButton.setOnClickListener(backButtonOnClickListener);
sendcommentsLinearLayout = (LinearLayout) findViewById(R.id.send_comment);
sendcommentsLinearLayout.setOnClickListener(sendcommentsLinearLayoutOnClickListener);
allcommentsListView = (ListView) findViewById(R.id.all_comments);
noneLinearLayout = (LinearLayout) findViewById(R.id.none);
noneLinearLayout.setVisibility(View.GONE);
noneTextView = (TextView) findViewById(R.id.none_text);
noneTextView.setVisibility(View.GONE);
headImageImageView = (ImageView) findViewById(R.id.headimage);
headImageImageView.setImageBitmap(Utils.getBitmap(GOLBALVALUE.user.getHeadImage()));
System.out.println("aaaa");
handler = new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what == GOLBALVALUE.ADDCOMMENT){
if(comments == null){
comments = new ArrayList<Comments>();
}
noneLinearLayout.setVisibility(View.GONE);
noneTextView.setVisibility(View.GONE);
allcommentsListView.setVisibility(View.VISIBLE);
Comments comment = (Comments) msg.obj;
comments.add(0, comment);
allcommentsListView.setSelection(0);
adapter = new CommentsAdapter(context, R.layout.comment_item, comments,allcommentsListView);
allcommentsListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
};
getAllComments();
}
private OnClickListener backButtonOnClickListener = new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ActivityCollector.removeActivity(CommentsActivity1.this);
CommentsActivity1.this.finish();
}
};
private OnClickListener sendcommentsLinearLayoutOnClickListener = new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(context,SendCommentActivity.class);
startActivity(intent);
}
};
private void getAllComments(){
String url = NetConnectionDate.url+"GetAllCommentsServlet";
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String urlString = arg0[0];
client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair("courseinfid", "0"));
String jsonarray = null;
try {
HttpEntity entity = new UrlEncodedFormEntity(list,HTTP.UTF_8);//设置编码,防止中午乱码
post.setEntity(entity);
HttpResponse response = client.execute(post);
jsonarray = EntityUtils.toString(response.getEntity());
return jsonarray;
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "faliure";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "faliure";
}
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(result.equals("failure")){
Toast.makeText(context, "糟糕,网络出问题了", Toast.LENGTH_SHORT).show();
}else{
comments = new ArrayList<Comments>();
JSONArray jsonarray = new JSONArray(result);
for(int i=0;i<jsonarray.length();i++){
JSONObject json = jsonarray.getJSONObject(i);
Comments comment = new Comments();
comment.setId(json.getInt("id"));
comment.setContent(json.getString("content"));
comment.setPraisenum(json.getInt("praisenum"));
comment.setSender(json.getString("sender"));
comment.setSenderheadImage(json.getString("senderheadimage"));
comment.setSenderNickName(json.getString("sendernickname"));
comment.setSendtime(json.getString("sendertime"));
comments.add(comment);
System.out.println(comment.getPraisenum());
}
}
if(comments.size()>0){
noneLinearLayout.setVisibility(View.GONE);
noneTextView.setVisibility(View.GONE);
allcommentsListView.setVisibility(View.VISIBLE);
adapter = new CommentsAdapter(context, R.layout.comment_item, comments,allcommentsListView);
allcommentsListView.setAdapter(adapter);
allcommentsListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(context,CommentsActivity2.class);
intent.putExtra("comment", comments.get(position));
context.startActivity(intent);
}
});
}else{
noneLinearLayout.setVisibility(View.VISIBLE);
noneTextView.setVisibility(View.VISIBLE);
allcommentsListView.setVisibility(View.GONE);
noneLinearLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(context,SendCommentActivity.class);
startActivity(intent);
}
});
}
}
}.execute(url);
}
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
ActivityCollector.removeActivity(CommentsActivity1.this);
CommentsActivity1.this.finish();
}
}
| false | 2,006 | 6 | 2,612 | 7 | 2,594 | 5 | 2,612 | 7 | 3,466 | 12 | false | false | false | false | false | true |
61537_2 | public class UnionFindv5 implements UF {
public int[] parent;
public int[] rank;
public UnionFindv5(int size) {
parent = new int[size];
rank = new int[size];
for (int i=0; i<size; i++) {
parent[i] = i;
rank[i] = 1;
}
}
@Override
public int size() {
return parent.length;
}
@Override
public boolean unionContains(int p, int q) {
return find(p) == find(q);
}
@Override
public void union (int p, int q) {
int pIN = find(p);
int qIN = find(q);
if (pIN == qIN)
return;
// rank优化, 尽量保持深度一致
if (rank[pIN] > rank[qIN]) {
parent[qIN] = parent[pIN];
} else if (rank[pIN] < rank[qIN]){
parent[pIN] = parent[qIN];
} else {
parent[pIN] = parent[qIN];
rank[qIN]++;
}
}
// 时间复杂度为h, h表示树的高度
private int find(int i) {
if (i < 0 || i >= parent.length)
throw new IllegalArgumentException("Index out of range.");
while(i != parent[i]) {
// 路径压缩
parent[i] = parent[parent[i]];
i = parent[i];
}
return i;
}
} | benggee/data-structure | java/UnionFind/src/UnionFindv5.java | 360 | // 路径压缩 | line_comment | zh-cn | public class UnionFindv5 implements UF {
public int[] parent;
public int[] rank;
public UnionFindv5(int size) {
parent = new int[size];
rank = new int[size];
for (int i=0; i<size; i++) {
parent[i] = i;
rank[i] = 1;
}
}
@Override
public int size() {
return parent.length;
}
@Override
public boolean unionContains(int p, int q) {
return find(p) == find(q);
}
@Override
public void union (int p, int q) {
int pIN = find(p);
int qIN = find(q);
if (pIN == qIN)
return;
// rank优化, 尽量保持深度一致
if (rank[pIN] > rank[qIN]) {
parent[qIN] = parent[pIN];
} else if (rank[pIN] < rank[qIN]){
parent[pIN] = parent[qIN];
} else {
parent[pIN] = parent[qIN];
rank[qIN]++;
}
}
// 时间复杂度为h, h表示树的高度
private int find(int i) {
if (i < 0 || i >= parent.length)
throw new IllegalArgumentException("Index out of range.");
while(i != parent[i]) {
// 路径 <SUF>
parent[i] = parent[parent[i]];
i = parent[i];
}
return i;
}
} | false | 335 | 6 | 360 | 4 | 408 | 4 | 360 | 4 | 450 | 12 | false | false | false | false | false | true |
53307_2 | package com.cc150;
import java.util.Arrays;
/**
* 题目:
* 思路: 基于动态规划 背包问题求解 不是本题的最优解
* 基于贪心策略和回溯 可以有更快的速度, 这题剪枝效率非常好
* Counter case: [1, 7, 10] ,amount = 14
* 按照贪心策略: 会首先找到 10 + 1 + 1 + 1 + 1 而不是 7 + 7
*/
public class Solution3 {
private static int ans = Integer.MAX_VALUE;
public int coinChange(int[] coins, int amount) {
if (amount == 0)
return 0;
Arrays.sort(coins);
coinChange(coins, amount, coins.length - 1, 0);
if (ans == Integer.MAX_VALUE) return -1;
else {
int oldAns = ans;
ans = Integer.MAX_VALUE;
return oldAns;
}
// return ans == Integer.MAX_VALUE ? -1 : ans;
}
private void coinChange(int[] coins, int amount, int cIndex, int count) {
if (amount == 0) {
ans = Math.min(ans, count);
return;
}
if (cIndex == -1)
return;
/* 说实话 为什么效率高? 全在 k + count < ans 这句
* 当前已经找零数量 count 加上 目前准备用的数量 k 如果要大于目前知道的最优解ans
* 叉叉叉 不用找了,剪枝!对应到代码就是退出循环
* */
for (int k = amount / coins[cIndex]; k >= 0 && k + count < ans; --k) {
coinChange(coins, amount - k * coins[cIndex], cIndex - 1, count + k);
}
}
public static void main(String[] args) {
int[] coins = {2};
int amount = 3;
Solution3 sol3 = new Solution3();
System.out.println(sol3.coinChange(coins, amount));
}
}
| benjame/Alg | LeetCode_322_CoinChange/src/com/cc150/Solution3.java | 520 | /* 说实话 为什么效率高? 全在 k + count < ans 这句
* 当前已经找零数量 count 加上 目前准备用的数量 k 如果要大于目前知道的最优解ans
* 叉叉叉 不用找了,剪枝!对应到代码就是退出循环
* */ | block_comment | zh-cn | package com.cc150;
import java.util.Arrays;
/**
* 题目:
* 思路: 基于动态规划 背包问题求解 不是本题的最优解
* 基于贪心策略和回溯 可以有更快的速度, 这题剪枝效率非常好
* Counter case: [1, 7, 10] ,amount = 14
* 按照贪心策略: 会首先找到 10 + 1 + 1 + 1 + 1 而不是 7 + 7
*/
public class Solution3 {
private static int ans = Integer.MAX_VALUE;
public int coinChange(int[] coins, int amount) {
if (amount == 0)
return 0;
Arrays.sort(coins);
coinChange(coins, amount, coins.length - 1, 0);
if (ans == Integer.MAX_VALUE) return -1;
else {
int oldAns = ans;
ans = Integer.MAX_VALUE;
return oldAns;
}
// return ans == Integer.MAX_VALUE ? -1 : ans;
}
private void coinChange(int[] coins, int amount, int cIndex, int count) {
if (amount == 0) {
ans = Math.min(ans, count);
return;
}
if (cIndex == -1)
return;
/* 说实话 <SUF>*/
for (int k = amount / coins[cIndex]; k >= 0 && k + count < ans; --k) {
coinChange(coins, amount - k * coins[cIndex], cIndex - 1, count + k);
}
}
public static void main(String[] args) {
int[] coins = {2};
int amount = 3;
Solution3 sol3 = new Solution3();
System.out.println(sol3.coinChange(coins, amount));
}
}
| false | 481 | 71 | 520 | 74 | 522 | 67 | 520 | 74 | 672 | 130 | false | false | false | false | false | true |
41535_1 | package cn.huang.leetcode;
/*
391. Perfect Rectangle
Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.
Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented
as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).
Example 1:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
Return true. All 5 rectangles together form an exact cover of a rectangular region.
Example 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
Return false. Because there is a gap between the two rectangular regions.
Example 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
Return false. Because there is a gap in the top center.
Example 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
Return false. Because two of the rectangles overlap with each other.
*/
import java.util.HashSet;
import java.util.Set;
/*
给了一堆小矩形的坐标(左下角和右上角围成的),问其能否组合成一个完美的矩形(刚刚好,不多,不少,不交叉)。
核心思想就是:能够正好围成一个矩形的情况就是:
有且只有:
最左下/最左上/最右下/最右上的四个点只出现过一次,其他肯定是出现两次和四次(保证完全覆盖)
上面四个点围成的面积,正好等于所有子矩形的面积之和(保证不重复)
判断依据就是一个完美的正方形的4个顶点出现1次,其余的点都是出现偶数次,只需要做一个遍历即可完成,最后使用面积判断即可,
*/
public class LC_0391_PerfectRectangle {
public boolean isRectangleCover(int[][] rectangles) {
if(rectangles.length == 0 || rectangles[0].length == 0)
return false;
int x1 = Integer.MAX_VALUE;
int x2 = Integer.MIN_VALUE;
int y1 = Integer.MAX_VALUE;
int y2 = Integer.MIN_VALUE;
Set<String> set = new HashSet<>();
int area = 0;
for(int[] rect: rectangles){
x1 = Math.min(rect[0],x1);
y1 = Math.min(rect[1], y1);
x2 = Math.max(rect[2], x2);
y2 = Math.max(rect[3], y2);
area += (rect[2] - rect[0])*(rect[3] - rect[1]);
// the four corner node
String s1 = rect[0]+" "+rect[1];
String s2 = rect[0]+" "+rect[3];
String s3 = rect[2]+" "+rect[3];
String s4 = rect[2]+" "+rect[1];
if(!set.add(s1)) set.remove(s1);//already have, then remove
if(!set.add(s2)) set.remove(s2);
if(!set.add(s3)) set.remove(s3);
if(!set.add(s4)) set.remove(s4);
}
if(!set.contains(x1+" "+y1) || !set.contains(x1+" "+y2) || !set.contains(x2+" "+y1) || !set.contains(x2+" "+y2) || set.size()!=4)
return false;
return area == (x2 - x1) * (y2 - y1);
}
}
| benjaminhuanghuang/java-interview | src/main/java/cn/huang/leetcode/LC_0391_PerfectRectangle.java | 1,056 | /*
给了一堆小矩形的坐标(左下角和右上角围成的),问其能否组合成一个完美的矩形(刚刚好,不多,不少,不交叉)。
核心思想就是:能够正好围成一个矩形的情况就是:
有且只有:
最左下/最左上/最右下/最右上的四个点只出现过一次,其他肯定是出现两次和四次(保证完全覆盖)
上面四个点围成的面积,正好等于所有子矩形的面积之和(保证不重复)
判断依据就是一个完美的正方形的4个顶点出现1次,其余的点都是出现偶数次,只需要做一个遍历即可完成,最后使用面积判断即可,
*/ | block_comment | zh-cn | package cn.huang.leetcode;
/*
391. Perfect Rectangle
Given N axis-aligned rectangles where N > 0, determine if they all together form an exact cover of a rectangular region.
Each rectangle is represented as a bottom-left point and a top-right point. For example, a unit square is represented
as [1,1,2,2]. (coordinate of bottom-left point is (1, 1) and top-right point is (2, 2)).
Example 1:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[3,2,4,4],
[1,3,2,4],
[2,3,3,4]
]
Return true. All 5 rectangles together form an exact cover of a rectangular region.
Example 2:
rectangles = [
[1,1,2,3],
[1,3,2,4],
[3,1,4,2],
[3,2,4,4]
]
Return false. Because there is a gap between the two rectangular regions.
Example 3:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[3,2,4,4]
]
Return false. Because there is a gap in the top center.
Example 4:
rectangles = [
[1,1,3,3],
[3,1,4,2],
[1,3,2,4],
[2,2,4,4]
]
Return false. Because two of the rectangles overlap with each other.
*/
import java.util.HashSet;
import java.util.Set;
/*
给了一 <SUF>*/
public class LC_0391_PerfectRectangle {
public boolean isRectangleCover(int[][] rectangles) {
if(rectangles.length == 0 || rectangles[0].length == 0)
return false;
int x1 = Integer.MAX_VALUE;
int x2 = Integer.MIN_VALUE;
int y1 = Integer.MAX_VALUE;
int y2 = Integer.MIN_VALUE;
Set<String> set = new HashSet<>();
int area = 0;
for(int[] rect: rectangles){
x1 = Math.min(rect[0],x1);
y1 = Math.min(rect[1], y1);
x2 = Math.max(rect[2], x2);
y2 = Math.max(rect[3], y2);
area += (rect[2] - rect[0])*(rect[3] - rect[1]);
// the four corner node
String s1 = rect[0]+" "+rect[1];
String s2 = rect[0]+" "+rect[3];
String s3 = rect[2]+" "+rect[3];
String s4 = rect[2]+" "+rect[1];
if(!set.add(s1)) set.remove(s1);//already have, then remove
if(!set.add(s2)) set.remove(s2);
if(!set.add(s3)) set.remove(s3);
if(!set.add(s4)) set.remove(s4);
}
if(!set.contains(x1+" "+y1) || !set.contains(x1+" "+y2) || !set.contains(x2+" "+y1) || !set.contains(x2+" "+y2) || set.size()!=4)
return false;
return area == (x2 - x1) * (y2 - y1);
}
}
| false | 911 | 158 | 1,056 | 193 | 1,034 | 157 | 1,056 | 193 | 1,237 | 299 | false | false | false | false | false | true |
43917_2 | package com.opencdk.appwidget.utils;
import com.opencdk.appwidget.model.News;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
public class DataProvider {
public static final String[] NEWS_ARRAY = new String[] { "习近平两会全纪录 两会专题", "任正非李彦宏都欣赏的他,成功之路为何戛然而止",
"85后中国最牛富二代坐拥900亿 比王思聪低调", "谷歌工程师:AlphaGo是如何学会下围棋的", "司机将被AlphaGo淘汰 想像力与经验成人类最后堡垒",
"阿里巴巴探索虚拟现实VR 力图增强3D网上购物体验", "AlphaGo背后:谷歌有支“机器人军团”", "谷歌花2.5亿美元买下8栋办公楼:可容3000员工",
"金蝶国际公布2015全年业绩 云服务业务大幅增长80.1%", "从最新数据看中国可穿戴市场 暗流涌动 缺乏惊天一击", "papi酱只有一个 模仿不是捷径",
"从最新数据看中国可穿戴市场 暗流涌动 缺乏惊天一击", "京东拍卖频道正式上线 包含珍品和海关拍卖等业务", "智人时代:人类智能与机器智能平分秋色", "小米和360互诉不正当竞争 均索赔2000万元",
"从“德国匠心之旅”看华为消费者云业务的扎实功力", "大众旅游时代下的微观样本:酒店创业风口来了?", "腾讯2015年全年总收入1028.63亿元 同比增长22%" };
public static int[] getRandomArray(int total) {
int[] array = new int[total];
for (int i = 0; i < total; i++) {
array[i] = i;
}
Random random = new Random();
int temp2;
int end = total;
for (int i = 0; i < total; i++) {
int temp = random.nextInt(end);
temp2 = array[temp];
array[temp] = array[end - 1];
array[end - 1] = temp2;
end--;
}
return array;
}
public static String[] getRandomNewsArray(int count) {
int[] randomArray = getRandomArray(count);
String[] newsArray = new String[count];
for (int i = 0; i < count; i++) {
newsArray[i] = NEWS_ARRAY[randomArray[i]];
}
return newsArray;
}
/**
* 模拟新闻数据
*
* @return
*/
public static List<News> getRandomNews() {
List<News> newsList = new ArrayList<News>();
final int newsCount = 10;
News news = new News();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
String dateString = null;
// 随机新闻
String[] newsArray = DataProvider.getRandomNewsArray(newsCount);
// 随机新闻图片标签
int[] randMarkArray = DataProvider.getRandomArray(newsCount);
for (int i = 0; i < newsCount; i++) {
news = new News();
news.setTitle(newsArray[i]);
dateString = sdf.format(new Date());
news.setDate(dateString);
news.setNewsMark(randMarkArray[i]);
newsList.add(news);
}
return newsList;
}
}
| benniaobuguai/opencdk-appwidget | app/src/main/java/com/opencdk/appwidget/utils/DataProvider.java | 1,016 | // 随机新闻图片标签 | line_comment | zh-cn | package com.opencdk.appwidget.utils;
import com.opencdk.appwidget.model.News;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;
public class DataProvider {
public static final String[] NEWS_ARRAY = new String[] { "习近平两会全纪录 两会专题", "任正非李彦宏都欣赏的他,成功之路为何戛然而止",
"85后中国最牛富二代坐拥900亿 比王思聪低调", "谷歌工程师:AlphaGo是如何学会下围棋的", "司机将被AlphaGo淘汰 想像力与经验成人类最后堡垒",
"阿里巴巴探索虚拟现实VR 力图增强3D网上购物体验", "AlphaGo背后:谷歌有支“机器人军团”", "谷歌花2.5亿美元买下8栋办公楼:可容3000员工",
"金蝶国际公布2015全年业绩 云服务业务大幅增长80.1%", "从最新数据看中国可穿戴市场 暗流涌动 缺乏惊天一击", "papi酱只有一个 模仿不是捷径",
"从最新数据看中国可穿戴市场 暗流涌动 缺乏惊天一击", "京东拍卖频道正式上线 包含珍品和海关拍卖等业务", "智人时代:人类智能与机器智能平分秋色", "小米和360互诉不正当竞争 均索赔2000万元",
"从“德国匠心之旅”看华为消费者云业务的扎实功力", "大众旅游时代下的微观样本:酒店创业风口来了?", "腾讯2015年全年总收入1028.63亿元 同比增长22%" };
public static int[] getRandomArray(int total) {
int[] array = new int[total];
for (int i = 0; i < total; i++) {
array[i] = i;
}
Random random = new Random();
int temp2;
int end = total;
for (int i = 0; i < total; i++) {
int temp = random.nextInt(end);
temp2 = array[temp];
array[temp] = array[end - 1];
array[end - 1] = temp2;
end--;
}
return array;
}
public static String[] getRandomNewsArray(int count) {
int[] randomArray = getRandomArray(count);
String[] newsArray = new String[count];
for (int i = 0; i < count; i++) {
newsArray[i] = NEWS_ARRAY[randomArray[i]];
}
return newsArray;
}
/**
* 模拟新闻数据
*
* @return
*/
public static List<News> getRandomNews() {
List<News> newsList = new ArrayList<News>();
final int newsCount = 10;
News news = new News();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
String dateString = null;
// 随机新闻
String[] newsArray = DataProvider.getRandomNewsArray(newsCount);
// 随机 <SUF>
int[] randMarkArray = DataProvider.getRandomArray(newsCount);
for (int i = 0; i < newsCount; i++) {
news = new News();
news.setTitle(newsArray[i]);
dateString = sdf.format(new Date());
news.setDate(dateString);
news.setNewsMark(randMarkArray[i]);
newsList.add(news);
}
return newsList;
}
}
| false | 793 | 8 | 1,016 | 7 | 895 | 6 | 1,016 | 7 | 1,275 | 16 | false | false | false | false | false | true |
62055_4 | package net.oschina.runjs.beans;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import net.oschina.common.db.QueryHelper;
/**
* 留言、通知
*
* @author jack
*
*/
public class Msg extends Pojo {
public static final Msg INSTANCE = new Msg();
// 系统发送通知
public transient static final int SYSTEM = 0;
// 未读
public transient static final int UNREAD = 0;
// 已读
public transient static final int READ = 1;
// 评论类型
public transient static final int TYPE_COMMENT = 0;
// Fork类型
public transient static final int TYPE_FORK = 1;
// 顶类型
public transient static final int TYPE_UP = 2;
// 留言类型
public transient static final int TYPE_MSG = 3;
// 通知类型
public transient static final int TYPE_NOTIFY = 4;
// 没有引用
public transient static final int NULL_REFER = 0;
private long sender;
private long receiver;
private int status;
// 通知、留言类型
private int type;
private Timestamp create_time;
private String content;
private long refer;
@SuppressWarnings("unchecked")
public List<Msg> listUnreadMsg(long user) {
String sql = "SELECT id FROM " + this.TableName()
+ " WHERE status = ? AND receiver = ?";
List<Long> ids = QueryHelper.query(long.class, sql, UNREAD, user);
return this.LoadList(ids);
}
/**
* 列出不同类型的通知
*
* @param user
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public List<Msg> listMsgByType(long user, int type) {
String sql = "SELECT id FROM " + this.TableName()
+ " WHERE receiver = ? AND type = ? AND status = ? ORDER BY id DESC";
List<Long> ids = QueryHelper.query(long.class, sql, user, type, UNREAD);
return this.LoadList(ids);
}
/**
* 未读消息数量
*
* @param user
* @return
*/
public int GetUnreadCount(long user) {
String sql = "SELECT COUNT(id) FROM " + this.TableName()
+ " WHERE status = ? AND receiver = ?";
return (int) QueryHelper.stat(sql, UNREAD, user);
}
@SuppressWarnings("unchecked")
public List<Msg> listAllMsg(long user) {
String sql = "SELECT * FROM " + this.TableName()
+ " WHERE receiver = ?";
List<Long> ids = QueryHelper.query(long.class, sql, user);
return this.LoadList(ids);
}
/**
* 添加一条通知,留言
*
* @param sender
* @param reveicer
* @param content
* @return
*/
public boolean addMsg(long sender, long reveicer, int type, long refer,
String content) {
Msg msg = new Msg();
msg.setContent(content);
msg.setCreate_time(new Timestamp(new Date().getTime()));
msg.setReceiver(reveicer);
msg.setSender(sender);
msg.setStatus(UNREAD);
msg.setType(type);
msg.setRefer(refer);
if (0 != msg.Save())
return true;
return false;
}
public long getSender() {
return sender;
}
public void setSender(long sender) {
this.sender = sender;
}
public long getReceiver() {
return receiver;
}
public void setReceiver(long receiver) {
this.receiver = receiver;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Timestamp getCreate_time() {
return create_time;
}
public void setCreate_time(Timestamp create_time) {
this.create_time = create_time;
}
@Override
protected String TableName() {
return "osc_msgs";
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public long getRefer() {
return refer;
}
public void setRefer(long refer) {
this.refer = refer;
}
} | beone/JRUN | RunJS/src/net/oschina/runjs/beans/Msg.java | 1,171 | // 顶类型 | line_comment | zh-cn | package net.oschina.runjs.beans;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import net.oschina.common.db.QueryHelper;
/**
* 留言、通知
*
* @author jack
*
*/
public class Msg extends Pojo {
public static final Msg INSTANCE = new Msg();
// 系统发送通知
public transient static final int SYSTEM = 0;
// 未读
public transient static final int UNREAD = 0;
// 已读
public transient static final int READ = 1;
// 评论类型
public transient static final int TYPE_COMMENT = 0;
// Fork类型
public transient static final int TYPE_FORK = 1;
// 顶类 <SUF>
public transient static final int TYPE_UP = 2;
// 留言类型
public transient static final int TYPE_MSG = 3;
// 通知类型
public transient static final int TYPE_NOTIFY = 4;
// 没有引用
public transient static final int NULL_REFER = 0;
private long sender;
private long receiver;
private int status;
// 通知、留言类型
private int type;
private Timestamp create_time;
private String content;
private long refer;
@SuppressWarnings("unchecked")
public List<Msg> listUnreadMsg(long user) {
String sql = "SELECT id FROM " + this.TableName()
+ " WHERE status = ? AND receiver = ?";
List<Long> ids = QueryHelper.query(long.class, sql, UNREAD, user);
return this.LoadList(ids);
}
/**
* 列出不同类型的通知
*
* @param user
* @param type
* @return
*/
@SuppressWarnings("unchecked")
public List<Msg> listMsgByType(long user, int type) {
String sql = "SELECT id FROM " + this.TableName()
+ " WHERE receiver = ? AND type = ? AND status = ? ORDER BY id DESC";
List<Long> ids = QueryHelper.query(long.class, sql, user, type, UNREAD);
return this.LoadList(ids);
}
/**
* 未读消息数量
*
* @param user
* @return
*/
public int GetUnreadCount(long user) {
String sql = "SELECT COUNT(id) FROM " + this.TableName()
+ " WHERE status = ? AND receiver = ?";
return (int) QueryHelper.stat(sql, UNREAD, user);
}
@SuppressWarnings("unchecked")
public List<Msg> listAllMsg(long user) {
String sql = "SELECT * FROM " + this.TableName()
+ " WHERE receiver = ?";
List<Long> ids = QueryHelper.query(long.class, sql, user);
return this.LoadList(ids);
}
/**
* 添加一条通知,留言
*
* @param sender
* @param reveicer
* @param content
* @return
*/
public boolean addMsg(long sender, long reveicer, int type, long refer,
String content) {
Msg msg = new Msg();
msg.setContent(content);
msg.setCreate_time(new Timestamp(new Date().getTime()));
msg.setReceiver(reveicer);
msg.setSender(sender);
msg.setStatus(UNREAD);
msg.setType(type);
msg.setRefer(refer);
if (0 != msg.Save())
return true;
return false;
}
public long getSender() {
return sender;
}
public void setSender(long sender) {
this.sender = sender;
}
public long getReceiver() {
return receiver;
}
public void setReceiver(long receiver) {
this.receiver = receiver;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public Timestamp getCreate_time() {
return create_time;
}
public void setCreate_time(Timestamp create_time) {
this.create_time = create_time;
}
@Override
protected String TableName() {
return "osc_msgs";
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public long getRefer() {
return refer;
}
public void setRefer(long refer) {
this.refer = refer;
}
} | false | 944 | 4 | 1,171 | 4 | 1,168 | 4 | 1,171 | 4 | 1,376 | 7 | false | false | false | false | false | true |
51219_0 | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException, IOException {
Scanner sc=new Scanner(System.in);
InetAddress ip=InetAddress.getByAddress(new byte[]{127,0,0,1});
//本机的8888端口号提供服务器程序,客户端和服务器端建立通信连接
Socket socket=new Socket(ip,8888);
//System.out.println(socket);
//得到此次连接的输入、输出流
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
//1 客户端写数据
String line=sc.nextLine(); //读一行数据
os.write(line.getBytes()); //写到服务器端
socket.shutdownOutput(); //写出结束
//2 客户端接收数据,显示
int len=0;
byte[] bytes=new byte[10];
StringBuffer buffer=new StringBuffer();
while((len=is.read(bytes))!=-1){
buffer.append(new String(bytes,0,len));
}
//显示
System.out.println("Client has received:"+buffer.toString());
//关闭输入、输出流
is.close();
os.close();
//关闭通信连接
socket.close();
}
} | berrychiao/git_repository | Client.java | 344 | //本机的8888端口号提供服务器程序,客户端和服务器端建立通信连接 | line_comment | zh-cn | import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String[] args) throws IOException, IOException {
Scanner sc=new Scanner(System.in);
InetAddress ip=InetAddress.getByAddress(new byte[]{127,0,0,1});
//本机 <SUF>
Socket socket=new Socket(ip,8888);
//System.out.println(socket);
//得到此次连接的输入、输出流
InputStream is = socket.getInputStream();
OutputStream os = socket.getOutputStream();
//1 客户端写数据
String line=sc.nextLine(); //读一行数据
os.write(line.getBytes()); //写到服务器端
socket.shutdownOutput(); //写出结束
//2 客户端接收数据,显示
int len=0;
byte[] bytes=new byte[10];
StringBuffer buffer=new StringBuffer();
while((len=is.read(bytes))!=-1){
buffer.append(new String(bytes,0,len));
}
//显示
System.out.println("Client has received:"+buffer.toString());
//关闭输入、输出流
is.close();
os.close();
//关闭通信连接
socket.close();
}
} | false | 287 | 21 | 344 | 21 | 355 | 20 | 344 | 21 | 436 | 41 | false | false | false | false | false | true |
53323_5 | package leet.code.stack.monotonic;
import java.util.Deque;
import java.util.LinkedList;
/**
* 316. 去除重复字母
* <p></p>
* https://leetcode-cn.com/problems/remove-duplicate-letters/
* <pre>
* 给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。
* 需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
*
* 提示:
* 1 <= s.length <= 10^4
* s 由小写英文字母组成
* </pre>
*
* @author guangyi
*/
public class RemoveDuplicateLetters {
/**
* 由浅入深,单调栈思路去除重复字符
* https://leetcode-cn.com/problems/remove-duplicate-letters/solution/you-qian-ru-shen-dan-diao-zhan-si-lu-qu-chu-zhong-/
* <pre>
* 关于去重算法,应该没什么难度,往哈希集合里面塞不就行了么?
* 本文讲的问题应该是去重相关算法中难度最大的了,把这个问题搞懂,就再也不用怕数组去重问题了。
*
* 题目的要求总结出来有三点:
* 要求一、要去重。
* 要求二、去重字符串中的字符顺序不能打乱 s 中字符出现的相对顺序。
* 要求三、在所有符合上一条要求的去重字符串中,字典序最小的作为最终结果。
*
* 上述三条要求中,要求三可能有点难理解,举个例子。
* 比如说输入字符串 s = "babc",去重且符合相对位置的字符串有两个,
* 分别是 "bac" 和 "abc",但是我们的算法得返回 "abc",因为它的字典序更小。
*
* 我们先暂时忽略要求三,用「栈」来实现一下要求一和要求二。
*
* 这段代码的逻辑很简单吧,就是用布尔数组 inStack 记录栈中元素,达到去重的目的,此时栈中的元素都是没有重复的。
* 如果输入 s = "bcabc",这个算法会返回 "bca",已经符合要求一和要求二了,但是题目希望要的答案是 "abc" 对吧。
* 那我们想一想,如果想满足要求三,保证字典序,需要做些什么修改?
* 在向栈 stk 中插入字符 'a' 的这一刻,我们的算法需要知道,字符 'a' 的字典序和之前的两个字符 'b' 和 'c' 相比,谁大谁小?
* 如果当前字符 'a' 比之前的字符字典序小,就有可能需要把前面的字符 pop 出栈,让 'a' 排在前面,对吧?
*
* 这段代码也好理解,就是插入了一个 while 循环,连续 pop 出比当前字符小的栈顶字符,直到栈顶元素比当前元素的字典序还小为止。
* 是不是有点「单调栈」的意思了?
* 这样,对于输入 s = "bcabc",我们可以得出正确结果 "abc" 了。
*
* 但是,如果我改一下输入,假设 s = "bcac",按照刚才的算法逻辑,返回的结果是 "ac",而正确答案应该是 "bac",分析一下这是怎么回事?
* 很容易发现,因为 s 中只有唯一一个 'b',即便字符 'a' 的字典序比字符 'b' 要小,字符 'b' 也不应该被 pop 出去。
* 那问题出在哪里?
* 我们的算法在 stk.peek() > c 时才会 pop 元素,其实这时候应该分两种情况:
* 情况一、如果 stk.peek() 这个字符之后还会出现,那么可以把它 pop 出去,反正后面还有嘛,后面再 push 到栈里,刚好符合字典序的要求。
* 情况二、如果 stk.peek() 这个字符之后不会出现了,前面也说了栈中不会存在重复的元素,那么就不能把它 pop 出去,否则你就永远失去了这个字符。
*
* 回到 s = "bcac" 的例子,插入字符 'a' 的时候,发现前面的字符 'c' 的字典序比 'a' 大,
* 且在 'a' 之后还存在字符 'c',那么栈顶的这个 'c' 就会被 pop 掉。
* while 循环继续判断,发现前面的字符 'b' 的字典序还是比 'a' 大,但是在 'a' 之后再没有字符 'b' 了,所以不应该把 'b' pop 出去。
*
* 那么关键就在于,如何让算法知道字符 'a' 之后有几个 'b' 有几个 'c' 呢?
* 我们用了一个计数器 count,当字典序较小的字符试图「挤掉」栈顶元素的时候,
* 在 count 中检查栈顶元素是否是唯一的,只有当后面还存在栈顶元素的时候才能挤掉,否则不能挤掉。
* 至此,这个算法就结束了,时间空间复杂度都是 O(N)。
*
* 你还记得我们开头提到的三个要求吗?我们是怎么达成这三个要求的?
* 要求一、通过 inStack 这个布尔数组做到栈 stk 中不存在重复元素。
* 要求二、我们顺序遍历字符串 s,通过「栈」这种顺序结构的 push/pop 操作记录结果字符串,保证了字符出现的顺序和 s 中出现的顺序一致。
* 这里也可以想到为什么要用「栈」这种数据结构,因为先进后出的结构允许我们立即操作刚插入的字符,如果用「队列」的话肯定是做不到的。
* 要求三、我们用类似单调栈的思路,配合计数器 count 不断 pop 掉不符合最小字典序的字符,保证了最终得到的结果字典序最小。
*
* 当然,由于栈的结构特点,我们最后需要把栈中元素取出后再反转一次才是最终结果。
* 说实话,这应该是数组去重的最高境界了,没做过还真不容易想出来。你学会了吗?
* </pre>
*/
public static String removeDuplicateLetters(String str) {
// 递增栈
// 存放去重的结果
Deque<Character> monoStack = new LinkedList<>();
// 维护一个计数器记录字符串中字符的数量
// 因为输入为 ASCII 字符,大小 256 够用了
int[] count = new int[256];
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i)]++;
}
// 布尔数组初始值为 false,记录栈中是否存在某个字符
// 输入字符均为 ASCII 字符,所以大小 256 够用了
boolean[] inStack = new boolean[256];
for (char ch : str.toCharArray()) {
// 每遍历过一个字符,都将对应的计数减一
count[ch]--;
// 如果字符 c 存在栈中,直接跳过
if (inStack[ch]) {
continue;
}
// 插入之前,和之前的元素比较一下大小
// 如果字典序比前面的小,pop 前面的元素
while (!monoStack.isEmpty() && ch < monoStack.getFirst()) {
// 若之后不存在栈顶元素了,则停止 pop
if (count[monoStack.getFirst()] == 0) {
break;
}
// 出栈
// 若之后还有,则可以 pop
// 弹出栈顶元素,并把该元素标记为不在栈中
inStack[monoStack.removeFirst()] = false;
}
// 若不存在,则插入栈顶并标记为存在
monoStack.addFirst(ch);
inStack[ch] = true;
}
// 结果计算
StringBuilder sb = new StringBuilder(monoStack.size());
while (!monoStack.isEmpty()) {
sb.append(monoStack.removeFirst());
}
// 栈中元素插入顺序是反的,需要 reverse 一下
return sb.reverse().toString();
}
}
| bert82503/java-api-test | src/main/java/leet/code/stack/monotonic/RemoveDuplicateLetters.java | 2,019 | // 因为输入为 ASCII 字符,大小 256 够用了 | line_comment | zh-cn | package leet.code.stack.monotonic;
import java.util.Deque;
import java.util.LinkedList;
/**
* 316. 去除重复字母
* <p></p>
* https://leetcode-cn.com/problems/remove-duplicate-letters/
* <pre>
* 给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。
* 需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。
*
* 提示:
* 1 <= s.length <= 10^4
* s 由小写英文字母组成
* </pre>
*
* @author guangyi
*/
public class RemoveDuplicateLetters {
/**
* 由浅入深,单调栈思路去除重复字符
* https://leetcode-cn.com/problems/remove-duplicate-letters/solution/you-qian-ru-shen-dan-diao-zhan-si-lu-qu-chu-zhong-/
* <pre>
* 关于去重算法,应该没什么难度,往哈希集合里面塞不就行了么?
* 本文讲的问题应该是去重相关算法中难度最大的了,把这个问题搞懂,就再也不用怕数组去重问题了。
*
* 题目的要求总结出来有三点:
* 要求一、要去重。
* 要求二、去重字符串中的字符顺序不能打乱 s 中字符出现的相对顺序。
* 要求三、在所有符合上一条要求的去重字符串中,字典序最小的作为最终结果。
*
* 上述三条要求中,要求三可能有点难理解,举个例子。
* 比如说输入字符串 s = "babc",去重且符合相对位置的字符串有两个,
* 分别是 "bac" 和 "abc",但是我们的算法得返回 "abc",因为它的字典序更小。
*
* 我们先暂时忽略要求三,用「栈」来实现一下要求一和要求二。
*
* 这段代码的逻辑很简单吧,就是用布尔数组 inStack 记录栈中元素,达到去重的目的,此时栈中的元素都是没有重复的。
* 如果输入 s = "bcabc",这个算法会返回 "bca",已经符合要求一和要求二了,但是题目希望要的答案是 "abc" 对吧。
* 那我们想一想,如果想满足要求三,保证字典序,需要做些什么修改?
* 在向栈 stk 中插入字符 'a' 的这一刻,我们的算法需要知道,字符 'a' 的字典序和之前的两个字符 'b' 和 'c' 相比,谁大谁小?
* 如果当前字符 'a' 比之前的字符字典序小,就有可能需要把前面的字符 pop 出栈,让 'a' 排在前面,对吧?
*
* 这段代码也好理解,就是插入了一个 while 循环,连续 pop 出比当前字符小的栈顶字符,直到栈顶元素比当前元素的字典序还小为止。
* 是不是有点「单调栈」的意思了?
* 这样,对于输入 s = "bcabc",我们可以得出正确结果 "abc" 了。
*
* 但是,如果我改一下输入,假设 s = "bcac",按照刚才的算法逻辑,返回的结果是 "ac",而正确答案应该是 "bac",分析一下这是怎么回事?
* 很容易发现,因为 s 中只有唯一一个 'b',即便字符 'a' 的字典序比字符 'b' 要小,字符 'b' 也不应该被 pop 出去。
* 那问题出在哪里?
* 我们的算法在 stk.peek() > c 时才会 pop 元素,其实这时候应该分两种情况:
* 情况一、如果 stk.peek() 这个字符之后还会出现,那么可以把它 pop 出去,反正后面还有嘛,后面再 push 到栈里,刚好符合字典序的要求。
* 情况二、如果 stk.peek() 这个字符之后不会出现了,前面也说了栈中不会存在重复的元素,那么就不能把它 pop 出去,否则你就永远失去了这个字符。
*
* 回到 s = "bcac" 的例子,插入字符 'a' 的时候,发现前面的字符 'c' 的字典序比 'a' 大,
* 且在 'a' 之后还存在字符 'c',那么栈顶的这个 'c' 就会被 pop 掉。
* while 循环继续判断,发现前面的字符 'b' 的字典序还是比 'a' 大,但是在 'a' 之后再没有字符 'b' 了,所以不应该把 'b' pop 出去。
*
* 那么关键就在于,如何让算法知道字符 'a' 之后有几个 'b' 有几个 'c' 呢?
* 我们用了一个计数器 count,当字典序较小的字符试图「挤掉」栈顶元素的时候,
* 在 count 中检查栈顶元素是否是唯一的,只有当后面还存在栈顶元素的时候才能挤掉,否则不能挤掉。
* 至此,这个算法就结束了,时间空间复杂度都是 O(N)。
*
* 你还记得我们开头提到的三个要求吗?我们是怎么达成这三个要求的?
* 要求一、通过 inStack 这个布尔数组做到栈 stk 中不存在重复元素。
* 要求二、我们顺序遍历字符串 s,通过「栈」这种顺序结构的 push/pop 操作记录结果字符串,保证了字符出现的顺序和 s 中出现的顺序一致。
* 这里也可以想到为什么要用「栈」这种数据结构,因为先进后出的结构允许我们立即操作刚插入的字符,如果用「队列」的话肯定是做不到的。
* 要求三、我们用类似单调栈的思路,配合计数器 count 不断 pop 掉不符合最小字典序的字符,保证了最终得到的结果字典序最小。
*
* 当然,由于栈的结构特点,我们最后需要把栈中元素取出后再反转一次才是最终结果。
* 说实话,这应该是数组去重的最高境界了,没做过还真不容易想出来。你学会了吗?
* </pre>
*/
public static String removeDuplicateLetters(String str) {
// 递增栈
// 存放去重的结果
Deque<Character> monoStack = new LinkedList<>();
// 维护一个计数器记录字符串中字符的数量
// 因为 <SUF>
int[] count = new int[256];
for (int i = 0; i < str.length(); i++) {
count[str.charAt(i)]++;
}
// 布尔数组初始值为 false,记录栈中是否存在某个字符
// 输入字符均为 ASCII 字符,所以大小 256 够用了
boolean[] inStack = new boolean[256];
for (char ch : str.toCharArray()) {
// 每遍历过一个字符,都将对应的计数减一
count[ch]--;
// 如果字符 c 存在栈中,直接跳过
if (inStack[ch]) {
continue;
}
// 插入之前,和之前的元素比较一下大小
// 如果字典序比前面的小,pop 前面的元素
while (!monoStack.isEmpty() && ch < monoStack.getFirst()) {
// 若之后不存在栈顶元素了,则停止 pop
if (count[monoStack.getFirst()] == 0) {
break;
}
// 出栈
// 若之后还有,则可以 pop
// 弹出栈顶元素,并把该元素标记为不在栈中
inStack[monoStack.removeFirst()] = false;
}
// 若不存在,则插入栈顶并标记为存在
monoStack.addFirst(ch);
inStack[ch] = true;
}
// 结果计算
StringBuilder sb = new StringBuilder(monoStack.size());
while (!monoStack.isEmpty()) {
sb.append(monoStack.removeFirst());
}
// 栈中元素插入顺序是反的,需要 reverse 一下
return sb.reverse().toString();
}
}
| false | 1,880 | 18 | 2,019 | 18 | 1,899 | 16 | 2,019 | 18 | 3,033 | 24 | false | false | false | false | false | true |
57765_2 | package com.li.controller;
import com.li.manager.SocketManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;
import java.util.Map;
@RestController
@Slf4j
public class TestController {
@Autowired
private SimpMessagingTemplate template;
/**
* 服务器指定用户进行推送,需要前端开通 var socket = new SockJS(host+'/myUrl' + '?token=1234');
*/
@RequestMapping("/sendUser")
public void sendUser(String token) {
log.info("token = {} ,对其发送您好", token);
WebSocketSession webSocketSession = SocketManager.get(token);
if (webSocketSession != null) {
/**
* 主要防止broken pipe
*/
template.convertAndSendToUser(token, "/queue/sendUser", "您好");
}
}
/**
* 广播,服务器主动推给连接的客户端
*/
@RequestMapping("/sendTopic")
public void sendTopic() {
template.convertAndSend("/topic/sendTopic", "大家晚上好");
}
/**
* 客户端发消息,服务端接收
*
* @param message
*/
// 相当于RequestMapping
@MessageMapping("/sendServer")
public void sendServer(String message) {
log.info("message:{}", message);
}
/**
* 客户端发消息,大家都接收,相当于直播说话
*
* @param message
* @return
*/
@MessageMapping("/sendAllUser")
@SendTo("/topic/sendTopic")
public String sendAllUser(String message) {
// 也可以采用template方式
return message;
}
/**
* 点对点用户聊天,这边需要注意,由于前端传过来json数据,所以使用@RequestBody
* 这边需要前端开通var socket = new SockJS(host+'/myUrl' + '?token=4567'); token为指定name
* @param map
*/
@MessageMapping("/sendMyUser")
public void sendMyUser(@RequestBody Map<String, String> map) {
log.info("map = {}", map);
WebSocketSession webSocketSession = SocketManager.get(map.get("name"));
if (webSocketSession != null) {
log.info("sessionId = {}", webSocketSession.getId());
template.convertAndSendToUser(map.get("name"), "/queue/sendUser", map.get("message"));
}
}
}
| bertonlee/webSocket-01 | src/main/java/com/li/controller/TestController.java | 688 | /**
* 广播,服务器主动推给连接的客户端
*/ | block_comment | zh-cn | package com.li.controller;
import com.li.manager.SocketManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.WebSocketSession;
import java.util.Map;
@RestController
@Slf4j
public class TestController {
@Autowired
private SimpMessagingTemplate template;
/**
* 服务器指定用户进行推送,需要前端开通 var socket = new SockJS(host+'/myUrl' + '?token=1234');
*/
@RequestMapping("/sendUser")
public void sendUser(String token) {
log.info("token = {} ,对其发送您好", token);
WebSocketSession webSocketSession = SocketManager.get(token);
if (webSocketSession != null) {
/**
* 主要防止broken pipe
*/
template.convertAndSendToUser(token, "/queue/sendUser", "您好");
}
}
/**
* 广播, <SUF>*/
@RequestMapping("/sendTopic")
public void sendTopic() {
template.convertAndSend("/topic/sendTopic", "大家晚上好");
}
/**
* 客户端发消息,服务端接收
*
* @param message
*/
// 相当于RequestMapping
@MessageMapping("/sendServer")
public void sendServer(String message) {
log.info("message:{}", message);
}
/**
* 客户端发消息,大家都接收,相当于直播说话
*
* @param message
* @return
*/
@MessageMapping("/sendAllUser")
@SendTo("/topic/sendTopic")
public String sendAllUser(String message) {
// 也可以采用template方式
return message;
}
/**
* 点对点用户聊天,这边需要注意,由于前端传过来json数据,所以使用@RequestBody
* 这边需要前端开通var socket = new SockJS(host+'/myUrl' + '?token=4567'); token为指定name
* @param map
*/
@MessageMapping("/sendMyUser")
public void sendMyUser(@RequestBody Map<String, String> map) {
log.info("map = {}", map);
WebSocketSession webSocketSession = SocketManager.get(map.get("name"));
if (webSocketSession != null) {
log.info("sessionId = {}", webSocketSession.getId());
template.convertAndSendToUser(map.get("name"), "/queue/sendUser", map.get("message"));
}
}
}
| false | 594 | 17 | 688 | 17 | 716 | 17 | 688 | 17 | 869 | 30 | false | false | false | false | false | true |
42912_17 | package com.besscroft.diyfile.storage.service.impl;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.besscroft.diyfile.common.constant.FileConstants;
import com.besscroft.diyfile.common.enums.StorageTypeEnum;
import com.besscroft.diyfile.common.exception.DiyFileException;
import com.besscroft.diyfile.common.param.storage.init.QCloudCosParam;
import com.besscroft.diyfile.common.vo.FileInfoVo;
import com.besscroft.diyfile.storage.service.base.AbstractOSSBaseService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @Description 腾讯云 COS 服务实现类
* @Author Bess Croft
* @Date 2023/8/13 17:13
*/
@Slf4j
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class QCloudCosServiceImpl extends AbstractOSSBaseService<QCloudCosParam> {
private COSClient cosClient;
/**
* Q:你好,麻烦请问下腾讯云 COS 是否支持 AWS Java SDK 2.x 版本?查阅文档只看到 1.x 示例:https://cloud.tencent.com/document/product/436/37421#java,想确认下是否有支持 2.x
* A:您好,非常抱歉,辛苦您久等了,关于您这边反馈的问题,这边为您核实了一下呢,目前COS仅支持AWS Java SDK 1.x版本,暂不支持2.x版本的呢
*/
@Override
public void init() {
COSCredentials cred = new BasicCOSCredentials(initParam.getSecretId(), initParam.getSecretKey());
// 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
Region region = new Region(initParam.getRegion());
ClientConfig clientConfig = new ClientConfig(region);
// 这里建议设置使用 https 协议
// 从 5.6.54 版本开始,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);
// 生成 cos 客户端。
this.cosClient = new COSClient(cred, clientConfig);
initialized = true;
}
@Override
public String getFileDownloadUrl(String fileName, String filePath, String fullPath) {
return null;
}
@Override
public ResponseEntity<Resource> getFileResource(String fileName, String filePath) {
return null;
}
@Override
public List<FileInfoVo> getFileList(String folderPath) {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
// 设置 bucket 名称
listObjectsRequest.setBucketName(initParam.getBucketName());
// prefix 表示列出的 object 的 key 以 prefix 开始
listObjectsRequest.setPrefix(initParam.getMountPath());
// deliter 表示分隔符, 设置为/表示列出当前目录下的 object, 设置为空表示列出所有的 object
listObjectsRequest.setDelimiter(folderPath);
// 设置最大遍历出多少个对象, 一次 listobject 最大支持1000
listObjectsRequest.setMaxKeys(1000);
ObjectListing objectListing = null;
List<COSObjectSummary> summaryList = new ArrayList<>();
List<String> commonPrefixes = new ArrayList<>();
do {
try {
objectListing = cosClient.listObjects(listObjectsRequest);
} catch (Exception e) {
log.error("获取文件列表失败:{}", e.getMessage());
throw new DiyFileException("获取文件列表失败!");
}
// common prefix 表示被 delimiter 截断的路径, 如 delimter 设置为/, common prefix 则表示所有子目录的路径
List<String> commonPrefixs = objectListing.getCommonPrefixes();
commonPrefixes.addAll(commonPrefixs);
// object summary 表示所有列出的 object 列表
List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
summaryList.addAll(cosObjectSummaries);
String nextMarker = objectListing.getNextMarker();
listObjectsRequest.setMarker(nextMarker);
} while (objectListing.isTruncated());
return handleFileList(summaryList, commonPrefixes, folderPath);
}
@Override
public FileInfoVo getFileInfo(String filePath, String fileName) {
FileInfoVo fileInfoVo = new FileInfoVo();
fileInfoVo.setName(fileName);
fileInfoVo.setSize(0L);
fileInfoVo.setLastModifiedDateTime(null);
fileInfoVo.setType(FileConstants.FILE);
fileInfoVo.setPath(filePath);
fileInfoVo.setFile(null);
// 设置文件下载地址
fileInfoVo.setUrl(getObjectUrl(initParam.getBucketName(), filePath));
return fileInfoVo;
}
@Override
public void createItem(String folderPath, String fileName) {
throw new DiyFileException("腾讯云 COS 不支持创建对象!");
}
@Override
public void updateItem(String filePath, String fileName) {
throw new DiyFileException("腾讯云 COS 不支持修改对象!");
}
@Override
public void deleteItem(String filePath) {
cosClient.deleteObject(initParam.getBucketName(), filePath);
}
@Override
public void uploadItem(String folderPath, String fileName) {
// TODO 上传文件
throw new DiyFileException("腾讯云 COS 不支持上传对象!");
}
@Override
public String getUploadSession(String folderPath) {
return null;
}
@Override
public Integer getStorageType() {
return StorageTypeEnum.QCLOUD_COS.getValue();
}
@Override
public String getObjectUrl(String bucketName, String objectName) {
return cosClient.getObjectUrl(bucketName, objectName).toString();
}
@Override
public void moveItem(String startPath, String endPath) {
}
/**
* 获取文件列表
* @param summaryList 文件列表
* @param commonPrefixes 文件夹列表
* @param folderPath 文件夹路径
* @return 文件列表
*/
private List<FileInfoVo> handleFileList(@NonNull List<COSObjectSummary> summaryList, @NonNull List<String> commonPrefixes, @NonNull String folderPath) {
List<FileInfoVo> infoVoList = new ArrayList<>();
for(COSObjectSummary summary : summaryList) {
FileInfoVo fileInfoVo = new FileInfoVo();
int lastSlashIndex = summary.getKey().lastIndexOf('/');
if (Objects.equals("", summary.getKey().substring(lastSlashIndex + 1))) {
continue;
}
if (summary.getKey().contains("/")) {
fileInfoVo.setName(summary.getKey().substring(lastSlashIndex + 1));
} else {
fileInfoVo.setName(summary.getKey());
}
fileInfoVo.setFile(summary.getETag());
fileInfoVo.setLastModifiedDateTime(LocalDateTimeUtil.of(summary.getLastModified()));
fileInfoVo.setSize(summary.getSize());
fileInfoVo.setPath(folderPath);
fileInfoVo.setType(FileConstants.FILE);
fileInfoVo.setUrl(getObjectUrl(initParam.getBucketName(), summary.getKey()));
infoVoList.add(fileInfoVo);
}
for(String prefix : commonPrefixes) {
FileInfoVo fileInfoVo = new FileInfoVo();
int index = prefix.lastIndexOf("/");
fileInfoVo.setName(prefix.substring(0, index));
fileInfoVo.setFile(null);
fileInfoVo.setLastModifiedDateTime(null);
fileInfoVo.setSize(calculateFolderLength(cosClient, initParam.getBucketName(), prefix));
fileInfoVo.setPath(folderPath);
fileInfoVo.setType(FileConstants.FOLDER);
infoVoList.add(fileInfoVo);
}
return infoVoList;
}
/**
* 获取某个存储空间下指定目录(文件夹)下的文件大小。
* @param ossClient OSSClient实例
* @param bucketName 存储空间名称
* @param folder 指定目录(文件夹)
* @return 文件大小
*/
private static long calculateFolderLength(COSClient ossClient, String bucketName, String folder) {
long size = 0L;
ObjectListing objectListing = null;
do {
// MaxKey 默认值为 100,最大值为 1000。
ListObjectsRequest request = new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix(folder)
.withMaxKeys(1000);
if (objectListing != null) {
request.setMarker(objectListing.getNextMarker());
}
objectListing = ossClient.listObjects(request);
List<COSObjectSummary> sums = objectListing.getObjectSummaries();
for (COSObjectSummary s : sums) {
size += s.getSize();
}
} while (objectListing.isTruncated());
return size;
}
}
| besscroft/diyfile | diyfile-system/src/main/java/com/besscroft/diyfile/storage/service/impl/QCloudCosServiceImpl.java | 2,328 | // MaxKey 默认值为 100,最大值为 1000。 | line_comment | zh-cn | package com.besscroft.diyfile.storage.service.impl;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.besscroft.diyfile.common.constant.FileConstants;
import com.besscroft.diyfile.common.enums.StorageTypeEnum;
import com.besscroft.diyfile.common.exception.DiyFileException;
import com.besscroft.diyfile.common.param.storage.init.QCloudCosParam;
import com.besscroft.diyfile.common.vo.FileInfoVo;
import com.besscroft.diyfile.storage.service.base.AbstractOSSBaseService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.COSObjectSummary;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @Description 腾讯云 COS 服务实现类
* @Author Bess Croft
* @Date 2023/8/13 17:13
*/
@Slf4j
@Service
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class QCloudCosServiceImpl extends AbstractOSSBaseService<QCloudCosParam> {
private COSClient cosClient;
/**
* Q:你好,麻烦请问下腾讯云 COS 是否支持 AWS Java SDK 2.x 版本?查阅文档只看到 1.x 示例:https://cloud.tencent.com/document/product/436/37421#java,想确认下是否有支持 2.x
* A:您好,非常抱歉,辛苦您久等了,关于您这边反馈的问题,这边为您核实了一下呢,目前COS仅支持AWS Java SDK 1.x版本,暂不支持2.x版本的呢
*/
@Override
public void init() {
COSCredentials cred = new BasicCOSCredentials(initParam.getSecretId(), initParam.getSecretKey());
// 设置 bucket 的地域, COS 地域的简称请参见 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
Region region = new Region(initParam.getRegion());
ClientConfig clientConfig = new ClientConfig(region);
// 这里建议设置使用 https 协议
// 从 5.6.54 版本开始,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);
// 生成 cos 客户端。
this.cosClient = new COSClient(cred, clientConfig);
initialized = true;
}
@Override
public String getFileDownloadUrl(String fileName, String filePath, String fullPath) {
return null;
}
@Override
public ResponseEntity<Resource> getFileResource(String fileName, String filePath) {
return null;
}
@Override
public List<FileInfoVo> getFileList(String folderPath) {
ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
// 设置 bucket 名称
listObjectsRequest.setBucketName(initParam.getBucketName());
// prefix 表示列出的 object 的 key 以 prefix 开始
listObjectsRequest.setPrefix(initParam.getMountPath());
// deliter 表示分隔符, 设置为/表示列出当前目录下的 object, 设置为空表示列出所有的 object
listObjectsRequest.setDelimiter(folderPath);
// 设置最大遍历出多少个对象, 一次 listobject 最大支持1000
listObjectsRequest.setMaxKeys(1000);
ObjectListing objectListing = null;
List<COSObjectSummary> summaryList = new ArrayList<>();
List<String> commonPrefixes = new ArrayList<>();
do {
try {
objectListing = cosClient.listObjects(listObjectsRequest);
} catch (Exception e) {
log.error("获取文件列表失败:{}", e.getMessage());
throw new DiyFileException("获取文件列表失败!");
}
// common prefix 表示被 delimiter 截断的路径, 如 delimter 设置为/, common prefix 则表示所有子目录的路径
List<String> commonPrefixs = objectListing.getCommonPrefixes();
commonPrefixes.addAll(commonPrefixs);
// object summary 表示所有列出的 object 列表
List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
summaryList.addAll(cosObjectSummaries);
String nextMarker = objectListing.getNextMarker();
listObjectsRequest.setMarker(nextMarker);
} while (objectListing.isTruncated());
return handleFileList(summaryList, commonPrefixes, folderPath);
}
@Override
public FileInfoVo getFileInfo(String filePath, String fileName) {
FileInfoVo fileInfoVo = new FileInfoVo();
fileInfoVo.setName(fileName);
fileInfoVo.setSize(0L);
fileInfoVo.setLastModifiedDateTime(null);
fileInfoVo.setType(FileConstants.FILE);
fileInfoVo.setPath(filePath);
fileInfoVo.setFile(null);
// 设置文件下载地址
fileInfoVo.setUrl(getObjectUrl(initParam.getBucketName(), filePath));
return fileInfoVo;
}
@Override
public void createItem(String folderPath, String fileName) {
throw new DiyFileException("腾讯云 COS 不支持创建对象!");
}
@Override
public void updateItem(String filePath, String fileName) {
throw new DiyFileException("腾讯云 COS 不支持修改对象!");
}
@Override
public void deleteItem(String filePath) {
cosClient.deleteObject(initParam.getBucketName(), filePath);
}
@Override
public void uploadItem(String folderPath, String fileName) {
// TODO 上传文件
throw new DiyFileException("腾讯云 COS 不支持上传对象!");
}
@Override
public String getUploadSession(String folderPath) {
return null;
}
@Override
public Integer getStorageType() {
return StorageTypeEnum.QCLOUD_COS.getValue();
}
@Override
public String getObjectUrl(String bucketName, String objectName) {
return cosClient.getObjectUrl(bucketName, objectName).toString();
}
@Override
public void moveItem(String startPath, String endPath) {
}
/**
* 获取文件列表
* @param summaryList 文件列表
* @param commonPrefixes 文件夹列表
* @param folderPath 文件夹路径
* @return 文件列表
*/
private List<FileInfoVo> handleFileList(@NonNull List<COSObjectSummary> summaryList, @NonNull List<String> commonPrefixes, @NonNull String folderPath) {
List<FileInfoVo> infoVoList = new ArrayList<>();
for(COSObjectSummary summary : summaryList) {
FileInfoVo fileInfoVo = new FileInfoVo();
int lastSlashIndex = summary.getKey().lastIndexOf('/');
if (Objects.equals("", summary.getKey().substring(lastSlashIndex + 1))) {
continue;
}
if (summary.getKey().contains("/")) {
fileInfoVo.setName(summary.getKey().substring(lastSlashIndex + 1));
} else {
fileInfoVo.setName(summary.getKey());
}
fileInfoVo.setFile(summary.getETag());
fileInfoVo.setLastModifiedDateTime(LocalDateTimeUtil.of(summary.getLastModified()));
fileInfoVo.setSize(summary.getSize());
fileInfoVo.setPath(folderPath);
fileInfoVo.setType(FileConstants.FILE);
fileInfoVo.setUrl(getObjectUrl(initParam.getBucketName(), summary.getKey()));
infoVoList.add(fileInfoVo);
}
for(String prefix : commonPrefixes) {
FileInfoVo fileInfoVo = new FileInfoVo();
int index = prefix.lastIndexOf("/");
fileInfoVo.setName(prefix.substring(0, index));
fileInfoVo.setFile(null);
fileInfoVo.setLastModifiedDateTime(null);
fileInfoVo.setSize(calculateFolderLength(cosClient, initParam.getBucketName(), prefix));
fileInfoVo.setPath(folderPath);
fileInfoVo.setType(FileConstants.FOLDER);
infoVoList.add(fileInfoVo);
}
return infoVoList;
}
/**
* 获取某个存储空间下指定目录(文件夹)下的文件大小。
* @param ossClient OSSClient实例
* @param bucketName 存储空间名称
* @param folder 指定目录(文件夹)
* @return 文件大小
*/
private static long calculateFolderLength(COSClient ossClient, String bucketName, String folder) {
long size = 0L;
ObjectListing objectListing = null;
do {
// Ma <SUF>
ListObjectsRequest request = new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix(folder)
.withMaxKeys(1000);
if (objectListing != null) {
request.setMarker(objectListing.getNextMarker());
}
objectListing = ossClient.listObjects(request);
List<COSObjectSummary> sums = objectListing.getObjectSummaries();
for (COSObjectSummary s : sums) {
size += s.getSize();
}
} while (objectListing.isTruncated());
return size;
}
}
| false | 2,057 | 20 | 2,328 | 18 | 2,412 | 18 | 2,328 | 18 | 3,015 | 23 | false | false | false | false | false | true |
31385_6 | /*
* Copyright 2005-2017 shopxx.net. All rights reserved.
* Support: http://www.shopxx.net
* License: http://www.shopxx.net/license
*/
package net.shopxx.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.PreRemove;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Entity支付方式
*
* @author SHOP++ Team
* @version 5.0
*/
@Entity
public class PaymentMethod extends OrderedEntity<Long> {
private static final long serialVersionUID = 6949816500116581199L;
/**
* 类型
*/
public enum Type {
/**
* 款到发货
*/
deliveryAgainstPayment,
/**
* 货到付款
*/
cashOnDelivery
}
/**
* 方式
*/
public enum Method {
/**
* 在线支付
*/
online,
/**
* 线下支付
*/
offline
}
/**
* 名称
*/
@NotEmpty
@Length(max = 200)
@Column(nullable = false)
private String name;
/**
* 类型
*/
@NotNull
@Column(nullable = false)
private PaymentMethod.Type type;
/**
* 方式
*/
@NotNull
@Column(nullable = false)
private PaymentMethod.Method method;
/**
* 超时时间
*/
@Min(1)
private Integer timeout;
/**
* 图标
*/
@Length(max = 200)
@Pattern(regexp = "^(?i)(http:\\/\\/|https:\\/\\/|\\/).*$")
private String icon;
/**
* 介绍
*/
@Length(max = 200)
private String description;
/**
* 内容
*/
@Lob
private String content;
/**
* 配送方式
*/
@ManyToMany(mappedBy = "paymentMethods", fetch = FetchType.LAZY)
private Set<ShippingMethod> shippingMethods = new HashSet<>();
/**
* 订单
*/
@OneToMany(mappedBy = "paymentMethod", fetch = FetchType.LAZY)
private Set<Order> orders = new HashSet<>();
/**
* 获取名称
*
* @return 名称
*/
public String getName() {
return name;
}
/**
* 设置名称
*
* @param name
* 名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取类型
*
* @return 类型
*/
public PaymentMethod.Type getType() {
return type;
}
/**
* 设置类型
*
* @param type
* 类型
*/
public void setType(PaymentMethod.Type type) {
this.type = type;
}
/**
* 获取方式
*
* @return 方式
*/
public PaymentMethod.Method getMethod() {
return method;
}
/**
* 设置方式
*
* @param method
* 方式
*/
public void setMethod(PaymentMethod.Method method) {
this.method = method;
}
/**
* 获取超时时间
*
* @return 超时时间
*/
public Integer getTimeout() {
return timeout;
}
/**
* 设置超时时间
*
* @param timeout
* 超时时间
*/
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
/**
* 获取图标
*
* @return 图标
*/
public String getIcon() {
return icon;
}
/**
* 设置图标
*
* @param icon
* 图标
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* 获取介绍
*
* @return 介绍
*/
public String getDescription() {
return description;
}
/**
* 设置介绍
*
* @param description
* 介绍
*/
public void setDescription(String description) {
this.description = description;
}
/**
* 获取内容
*
* @return 内容
*/
public String getContent() {
return content;
}
/**
* 设置内容
*
* @param content
* 内容
*/
public void setContent(String content) {
this.content = content;
}
/**
* 获取配送方式
*
* @return 配送方式
*/
public Set<ShippingMethod> getShippingMethods() {
return shippingMethods;
}
/**
* 设置配送方式
*
* @param shippingMethods
* 配送方式
*/
public void setShippingMethods(Set<ShippingMethod> shippingMethods) {
this.shippingMethods = shippingMethods;
}
/**
* 获取订单
*
* @return 订单
*/
public Set<Order> getOrders() {
return orders;
}
/**
* 设置订单
*
* @param orders
* 订单
*/
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
/**
* 删除前处理
*/
@PreRemove
public void preRemove() {
Set<ShippingMethod> shippingMethods = getShippingMethods();
if (shippingMethods != null) {
for (ShippingMethod shippingMethod : shippingMethods) {
shippingMethod.getPaymentMethods().remove(this);
}
}
Set<Order> orders = getOrders();
if (orders != null) {
for (Order order : orders) {
order.setPaymentMethod(null);
}
}
}
} | bestfc/shop | src/net/shopxx/entity/PaymentMethod.java | 1,532 | /**
* 在线支付
*/ | block_comment | zh-cn | /*
* Copyright 2005-2017 shopxx.net. All rights reserved.
* Support: http://www.shopxx.net
* License: http://www.shopxx.net/license
*/
package net.shopxx.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.PreRemove;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Entity支付方式
*
* @author SHOP++ Team
* @version 5.0
*/
@Entity
public class PaymentMethod extends OrderedEntity<Long> {
private static final long serialVersionUID = 6949816500116581199L;
/**
* 类型
*/
public enum Type {
/**
* 款到发货
*/
deliveryAgainstPayment,
/**
* 货到付款
*/
cashOnDelivery
}
/**
* 方式
*/
public enum Method {
/**
* 在线支 <SUF>*/
online,
/**
* 线下支付
*/
offline
}
/**
* 名称
*/
@NotEmpty
@Length(max = 200)
@Column(nullable = false)
private String name;
/**
* 类型
*/
@NotNull
@Column(nullable = false)
private PaymentMethod.Type type;
/**
* 方式
*/
@NotNull
@Column(nullable = false)
private PaymentMethod.Method method;
/**
* 超时时间
*/
@Min(1)
private Integer timeout;
/**
* 图标
*/
@Length(max = 200)
@Pattern(regexp = "^(?i)(http:\\/\\/|https:\\/\\/|\\/).*$")
private String icon;
/**
* 介绍
*/
@Length(max = 200)
private String description;
/**
* 内容
*/
@Lob
private String content;
/**
* 配送方式
*/
@ManyToMany(mappedBy = "paymentMethods", fetch = FetchType.LAZY)
private Set<ShippingMethod> shippingMethods = new HashSet<>();
/**
* 订单
*/
@OneToMany(mappedBy = "paymentMethod", fetch = FetchType.LAZY)
private Set<Order> orders = new HashSet<>();
/**
* 获取名称
*
* @return 名称
*/
public String getName() {
return name;
}
/**
* 设置名称
*
* @param name
* 名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取类型
*
* @return 类型
*/
public PaymentMethod.Type getType() {
return type;
}
/**
* 设置类型
*
* @param type
* 类型
*/
public void setType(PaymentMethod.Type type) {
this.type = type;
}
/**
* 获取方式
*
* @return 方式
*/
public PaymentMethod.Method getMethod() {
return method;
}
/**
* 设置方式
*
* @param method
* 方式
*/
public void setMethod(PaymentMethod.Method method) {
this.method = method;
}
/**
* 获取超时时间
*
* @return 超时时间
*/
public Integer getTimeout() {
return timeout;
}
/**
* 设置超时时间
*
* @param timeout
* 超时时间
*/
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
/**
* 获取图标
*
* @return 图标
*/
public String getIcon() {
return icon;
}
/**
* 设置图标
*
* @param icon
* 图标
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* 获取介绍
*
* @return 介绍
*/
public String getDescription() {
return description;
}
/**
* 设置介绍
*
* @param description
* 介绍
*/
public void setDescription(String description) {
this.description = description;
}
/**
* 获取内容
*
* @return 内容
*/
public String getContent() {
return content;
}
/**
* 设置内容
*
* @param content
* 内容
*/
public void setContent(String content) {
this.content = content;
}
/**
* 获取配送方式
*
* @return 配送方式
*/
public Set<ShippingMethod> getShippingMethods() {
return shippingMethods;
}
/**
* 设置配送方式
*
* @param shippingMethods
* 配送方式
*/
public void setShippingMethods(Set<ShippingMethod> shippingMethods) {
this.shippingMethods = shippingMethods;
}
/**
* 获取订单
*
* @return 订单
*/
public Set<Order> getOrders() {
return orders;
}
/**
* 设置订单
*
* @param orders
* 订单
*/
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
/**
* 删除前处理
*/
@PreRemove
public void preRemove() {
Set<ShippingMethod> shippingMethods = getShippingMethods();
if (shippingMethods != null) {
for (ShippingMethod shippingMethod : shippingMethods) {
shippingMethod.getPaymentMethods().remove(this);
}
}
Set<Order> orders = getOrders();
if (orders != null) {
for (Order order : orders) {
order.setPaymentMethod(null);
}
}
}
} | false | 1,352 | 9 | 1,532 | 8 | 1,612 | 9 | 1,532 | 8 | 1,947 | 14 | false | false | false | false | false | true |
21504_18 | package com.example.fo_as;
import java.util.Stack;
import java.math.BigDecimal;
public class Formulautil {
/**大致思路是利用栈的出栈入栈压栈来处理一个运算式的先后级排序,进行相映的运算.*/
//数字栈:用于存储表达式中的各个数字
private Stack<BigDecimal> numberStack = null;
//符号栈:用于存储运算符和括号
private Stack<Character> symbolStack = null;
private int scale;//除法时出现循环小数保留精度
public Formulautil(int scale) {
super();
this.scale = scale;
}
public Formulautil() {
this(32);
}
/**从外面把字符串传递进来!!!*/
public BigDecimal caculate(String numStr) {
//判断算数表示是否结束,也就是判断结尾有木有=号!没有给加上!
//equals方法:值的比较
//charAt方法:检索方法
if (numStr.length() > 1
&& !"=".equals(numStr.charAt(numStr.length() - 1) + "")) {
numStr += "=";
}
//检查表达式是否是正确的!利用Standard方法(自定义)
if (!isStandard(numStr)) {
String isstandardtext;
isstandardtext = "出错";
return null;
}
// 初始化栈
if (numberStack == null) {
numberStack = new Stack<BigDecimal>();
}
numberStack.clear();
if (symbolStack == null) {
symbolStack = new Stack<Character>();
}
symbolStack.clear();
/**!!!!!!!!!!核 心!!!!!!!!!!!!*/
//创建一个StringBuffer,用来放多位的数字
StringBuffer temp = new StringBuffer();
// 从表达式的第一个字符开始处理
for (int i = 0; i < numStr.length(); i++) {
// 获取一个字符
char ch = numStr.charAt(i);
// 若当前字符是数字
if (isNumber(ch)) {
// 加入到数字缓存中
temp.append(ch);
} else { // 非数字的情况
// 将数字缓存转为字符串
String tempStr = temp.toString();
if (!tempStr.isEmpty()) {
BigDecimal num = new BigDecimal(tempStr);
// 将数字压栈
numberStack.push(num);
// 重置数字缓存
temp = new StringBuffer();
}
// 判断运算符的优先级,若当前优先级低于栈顶的优先级,则先把计算前面计算出来
while (!comparePri(ch) && !symbolStack.empty()) {
// 出栈,取出数字,后进先出
BigDecimal b = numberStack.pop();
BigDecimal a = numberStack.pop();
// 取出运算符进行相应运算,并把结果压栈进行下一次运算
switch ((char) symbolStack.pop()) {
case '+':
numberStack.push(a.add(b));
break;
case '-':
numberStack.push(a.subtract(b));
break;
case '×':
numberStack.push(a.multiply(b));
break;
case '÷':
try {
numberStack.push(a.divide(b));
} catch (java.lang.ArithmeticException e) {
// 进行除法出现无限循环小数时,就会抛异常,此处设置精度重新计算
numberStack.push(a.divide(b, this.scale,
BigDecimal.ROUND_HALF_EVEN));
}
break;
default:
break;
}
} // while循环结束
if (ch != '=') {
// 符号入栈
symbolStack.push(new Character(ch));
// 去括号
if (ch == ')') {
symbolStack.pop();
symbolStack.pop();
}
}
}
} // for循环结束
// 返回计算结果
return numberStack.pop();
}
/**=================================检查算数表达式是否合格======================================*/
private boolean isStandard(String numStr) {
// 表达式不能为空
if (numStr == null || numStr.isEmpty())
return false;
// 用来保存括号,检查左右括号是否匹配
Stack<Character> stack = new Stack<Character>();
// 用来标记'='符号是否存在多个
boolean b = false;
for (int i = 0; i < numStr.length(); i++) {
char n = numStr.charAt(i);
// 判断字符是否合法
if (!(isNumber(n) || "(".equals(n + "") || ")".equals(n + "")
|| "+".equals(n + "") || "-".equals(n + "")
|| "×".equals(n + "") || "÷".equals(n + "") || "=".equals(n
+ ""))) {
return false;
}
// 将左括号压栈,用来给后面的右括号进行匹配
if ("(".equals(n + "")) {
stack.push(n);
}
if (")".equals(n + "")) { // 匹配括号
if (stack.isEmpty() || !"(".equals((char) stack.pop() + "")) // 括号是否匹配
return false;
}
// 检查是否有多个'='号
if ("=".equals(n + "")) {
if (b)
return false;
b = true;
}
}
// 可能会有缺少右括号的情况
if (!stack.isEmpty())
return false;
// 检查'='号是否不在末尾
if (!("=".equals(numStr.charAt(numStr.length() - 1) + "")))
return false;
return true;
}
/**=================================判断是否是0-9的数字========================================*/
private boolean isNumber(char num) {
if ((num >= '0' && num <= '9') || num == '.')
return true;
return false;
}
/**==============比较优先级,如果当前运算符比栈顶元素运算符优先级高则返回true,否则返回false==========*/
private boolean comparePri(char symbol) {
// 空栈返回ture
if (symbolStack.empty()) {
return true;
}
/*
我设计得这个计算器加减乘除,lg,ln,括号,三角函数,正常得优先级就是有括号先算括号,然后再乘除,在加减
第一级:(
第二级: × ÷ sin cos tan lg ln
第三级: + -
第四级:)
*/
// 查看堆栈顶部的对象
char top = (char) symbolStack.peek();
if (top == '(') {
return true;
}
// 比较优先级
switch (symbol) {
case '(': // 优先级最高
return true;
// 优先级比'+'和'-'高
case '×': {
if (top == '+' || top == '-')
return true;
else
return false;
}
// 优先级比'+'和'-'高
case '÷':
if (top == '+' || top == '-')
return true;
else
return false;
case '+':
return false;
case '-':
return false;
// 优先级最低
case ')':
return false;
// 结束符
case '=':
return false;
default:
break;
}
return true;
}
}
| bestxiaoxiaoming-hm/AndroidStudio----java- | Formulautil.java | 1,703 | // 将数字压栈 | line_comment | zh-cn | package com.example.fo_as;
import java.util.Stack;
import java.math.BigDecimal;
public class Formulautil {
/**大致思路是利用栈的出栈入栈压栈来处理一个运算式的先后级排序,进行相映的运算.*/
//数字栈:用于存储表达式中的各个数字
private Stack<BigDecimal> numberStack = null;
//符号栈:用于存储运算符和括号
private Stack<Character> symbolStack = null;
private int scale;//除法时出现循环小数保留精度
public Formulautil(int scale) {
super();
this.scale = scale;
}
public Formulautil() {
this(32);
}
/**从外面把字符串传递进来!!!*/
public BigDecimal caculate(String numStr) {
//判断算数表示是否结束,也就是判断结尾有木有=号!没有给加上!
//equals方法:值的比较
//charAt方法:检索方法
if (numStr.length() > 1
&& !"=".equals(numStr.charAt(numStr.length() - 1) + "")) {
numStr += "=";
}
//检查表达式是否是正确的!利用Standard方法(自定义)
if (!isStandard(numStr)) {
String isstandardtext;
isstandardtext = "出错";
return null;
}
// 初始化栈
if (numberStack == null) {
numberStack = new Stack<BigDecimal>();
}
numberStack.clear();
if (symbolStack == null) {
symbolStack = new Stack<Character>();
}
symbolStack.clear();
/**!!!!!!!!!!核 心!!!!!!!!!!!!*/
//创建一个StringBuffer,用来放多位的数字
StringBuffer temp = new StringBuffer();
// 从表达式的第一个字符开始处理
for (int i = 0; i < numStr.length(); i++) {
// 获取一个字符
char ch = numStr.charAt(i);
// 若当前字符是数字
if (isNumber(ch)) {
// 加入到数字缓存中
temp.append(ch);
} else { // 非数字的情况
// 将数字缓存转为字符串
String tempStr = temp.toString();
if (!tempStr.isEmpty()) {
BigDecimal num = new BigDecimal(tempStr);
// 将数 <SUF>
numberStack.push(num);
// 重置数字缓存
temp = new StringBuffer();
}
// 判断运算符的优先级,若当前优先级低于栈顶的优先级,则先把计算前面计算出来
while (!comparePri(ch) && !symbolStack.empty()) {
// 出栈,取出数字,后进先出
BigDecimal b = numberStack.pop();
BigDecimal a = numberStack.pop();
// 取出运算符进行相应运算,并把结果压栈进行下一次运算
switch ((char) symbolStack.pop()) {
case '+':
numberStack.push(a.add(b));
break;
case '-':
numberStack.push(a.subtract(b));
break;
case '×':
numberStack.push(a.multiply(b));
break;
case '÷':
try {
numberStack.push(a.divide(b));
} catch (java.lang.ArithmeticException e) {
// 进行除法出现无限循环小数时,就会抛异常,此处设置精度重新计算
numberStack.push(a.divide(b, this.scale,
BigDecimal.ROUND_HALF_EVEN));
}
break;
default:
break;
}
} // while循环结束
if (ch != '=') {
// 符号入栈
symbolStack.push(new Character(ch));
// 去括号
if (ch == ')') {
symbolStack.pop();
symbolStack.pop();
}
}
}
} // for循环结束
// 返回计算结果
return numberStack.pop();
}
/**=================================检查算数表达式是否合格======================================*/
private boolean isStandard(String numStr) {
// 表达式不能为空
if (numStr == null || numStr.isEmpty())
return false;
// 用来保存括号,检查左右括号是否匹配
Stack<Character> stack = new Stack<Character>();
// 用来标记'='符号是否存在多个
boolean b = false;
for (int i = 0; i < numStr.length(); i++) {
char n = numStr.charAt(i);
// 判断字符是否合法
if (!(isNumber(n) || "(".equals(n + "") || ")".equals(n + "")
|| "+".equals(n + "") || "-".equals(n + "")
|| "×".equals(n + "") || "÷".equals(n + "") || "=".equals(n
+ ""))) {
return false;
}
// 将左括号压栈,用来给后面的右括号进行匹配
if ("(".equals(n + "")) {
stack.push(n);
}
if (")".equals(n + "")) { // 匹配括号
if (stack.isEmpty() || !"(".equals((char) stack.pop() + "")) // 括号是否匹配
return false;
}
// 检查是否有多个'='号
if ("=".equals(n + "")) {
if (b)
return false;
b = true;
}
}
// 可能会有缺少右括号的情况
if (!stack.isEmpty())
return false;
// 检查'='号是否不在末尾
if (!("=".equals(numStr.charAt(numStr.length() - 1) + "")))
return false;
return true;
}
/**=================================判断是否是0-9的数字========================================*/
private boolean isNumber(char num) {
if ((num >= '0' && num <= '9') || num == '.')
return true;
return false;
}
/**==============比较优先级,如果当前运算符比栈顶元素运算符优先级高则返回true,否则返回false==========*/
private boolean comparePri(char symbol) {
// 空栈返回ture
if (symbolStack.empty()) {
return true;
}
/*
我设计得这个计算器加减乘除,lg,ln,括号,三角函数,正常得优先级就是有括号先算括号,然后再乘除,在加减
第一级:(
第二级: × ÷ sin cos tan lg ln
第三级: + -
第四级:)
*/
// 查看堆栈顶部的对象
char top = (char) symbolStack.peek();
if (top == '(') {
return true;
}
// 比较优先级
switch (symbol) {
case '(': // 优先级最高
return true;
// 优先级比'+'和'-'高
case '×': {
if (top == '+' || top == '-')
return true;
else
return false;
}
// 优先级比'+'和'-'高
case '÷':
if (top == '+' || top == '-')
return true;
else
return false;
case '+':
return false;
case '-':
return false;
// 优先级最低
case ')':
return false;
// 结束符
case '=':
return false;
default:
break;
}
return true;
}
}
| false | 1,634 | 6 | 1,703 | 5 | 1,822 | 5 | 1,703 | 5 | 2,462 | 11 | false | false | false | false | false | true |
52504_5 | package com.yize.miniweather.view.fragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.yize.miniweather.R;
import com.yize.miniweather.bean.CityDetailBean;
import com.yize.miniweather.bean.CityShip;
import com.yize.miniweather.bean.WeatherBean;
import com.yize.miniweather.db.CityDatabaseHelper;
import com.yize.miniweather.txweather.TxWeatherHelper;
import com.yize.miniweather.util.AsyncHttpRequestListener;
import com.yize.miniweather.util.DateHelper;
import com.yize.miniweather.util.HttpAsyncTaskHelper;
import com.yize.miniweather.util.HttpLiteBusHelper;
import com.yize.miniweather.view.adapter.DayAdapter;
import com.yize.miniweather.view.adapter.HourAdapter;
import com.yize.miniweather.view.adapter.IndexAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import okhttp3.OkHttpClient;
/**
* A simple {@link Fragment} subclass.
*/
public class CityFragment extends Fragment {
private static final String TAG="CityFragment" ;
private TextView tv_thum_day,tv_thum_desc,tv_thum_temp,tv_current_temp,tv_current_state,tv_current_wind,tv_current_tips,tv_header_date
,tv_more_humi,tv_more_press,tv_more_air_index,tv_more_air_quality;
private ImageView iv_thum_weather_icon,iv_header_more;
private LinearLayout ll_header_show_more;
private RecyclerView rv_hour_list;
private RecyclerView rv_day_list;
private RecyclerView rv_index_list;
private HourAdapter hourAdapter;
private DayAdapter dayAdapter;
private IndexAdapter indexAdapter;
private List<WeatherBean.ForecastHour> forecastHourList=new ArrayList<>(48);
private List<WeatherBean.ForecastDay> forecastDayList=new ArrayList<>(15);
private List<WeatherBean.Index> indexList=new ArrayList<>(9);
private boolean showMore=true;
private CityDatabaseHelper dbHelper;
public CityFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_city, container, false);
initView(view);
refreshView();
return view;
}
private void initView(View view){
dbHelper=new CityDatabaseHelper(getActivity());
tv_header_date=view.findViewById(R.id.tv_header_date);
tv_current_temp=view.findViewById(R.id.tv_current_temp);
tv_current_state=view.findViewById(R.id.tv_current_state);
tv_current_wind=view.findViewById(R.id.tv_current_wind);
tv_current_tips=view.findViewById(R.id.tv_current_tips);
tv_thum_day=view.findViewById(R.id.tv_thum_day);
tv_thum_desc=view.findViewById(R.id.tv_thum_desc);
tv_thum_temp=view.findViewById(R.id.tv_thum_temp);
iv_thum_weather_icon=view.findViewById(R.id.iv_thum_weather_icon);
ll_header_show_more=view.findViewById(R.id.ll_header_show_more);
iv_header_more=view.findViewById(R.id.iv_header_more);
tv_more_humi=view.findViewById(R.id.tv_more_humi);
tv_more_press=view.findViewById(R.id.tv_more_press);
tv_more_air_index=view.findViewById(R.id.tv_more_air_index);
tv_more_air_quality=view.findViewById(R.id.tv_more_air_quality);
iv_header_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(showMore){
Glide.with(getContext()).load(R.drawable.ic_keyboard_arrow_up_black_24dp).into(iv_header_more);
ll_header_show_more.setVisibility(View.VISIBLE);
}else {
Glide.with(getContext()).load(R.drawable.ic_keyboard_arrow_down_black_24dp).into(iv_header_more);
ll_header_show_more.setVisibility(View.GONE);
}
showMore=!showMore;
}
});
rv_hour_list=view.findViewById(R.id.rv_hour_list);
rv_day_list=view.findViewById(R.id.rv_day_list);
rv_index_list=view.findViewById(R.id.rv_index_list);
LinearLayoutManager hourManager=new LinearLayoutManager(view.getContext());
hourManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rv_hour_list.setLayoutManager(hourManager);
hourAdapter=new HourAdapter(forecastHourList);
rv_hour_list.setAdapter(hourAdapter);
LinearLayoutManager dayManager=new LinearLayoutManager(view.getContext());
dayManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rv_day_list.setLayoutManager(dayManager);
dayAdapter=new DayAdapter(forecastDayList);
rv_day_list.setAdapter(dayAdapter);
GridLayoutManager indexManager=new GridLayoutManager(view.getContext(),4);
rv_index_list.setLayoutManager(indexManager);
indexAdapter=new IndexAdapter(indexList);
rv_index_list.setAdapter(indexAdapter);
}
private int retryCount=0;
private void refreshView(){
Bundle bundle=getArguments();
//更新城市信息的链接,应该直接传过来
String updateLink=bundle.getString("updateLink");
CityDetailBean cityDetailBean=(CityDetailBean)bundle.getSerializable("cityDetailBean");
HttpLiteBusHelper helper=new HttpLiteBusHelper(new AsyncHttpRequestListener() {
@Override
public void onSuccess(String result) {
//解析JSON 更新UI
WeatherBean weatherBean=TxWeatherHelper.parseWeatherData(result);
//48小时的每小时天气预报填充
if(forecastHourList.isEmpty()==false){
forecastHourList.clear();
}
Map<String, WeatherBean.ForecastHour> map=weatherBean.getData().getForecastHour();
for(String key:map.keySet()){
forecastHourList.add(map.get(key));
}
Collections.sort(forecastHourList, (o1, o2) -> o1.getUpdateTime().compareTo(o2.getUpdateTime()));
hourAdapter.notifyDataSetChanged();
Log.i("Fragment更新","48小时");
//7天天气预报填充
if(forecastDayList.size()!=0){
forecastDayList.clear();
}
Map<String, WeatherBean.ForecastDay> mmp=weatherBean.getData().getForecastDay();
for(String key:mmp.keySet()){
forecastDayList.add(Integer.valueOf(key),mmp.get(key));
}
Collections.sort(forecastDayList, (o1, o2) -> o1.getTime().compareTo(o2.getTime()));
dayAdapter.notifyDataSetChanged();
Log.i("Fragment更新","七日天气");
//天气指数填充
if(indexList.size()!=0){
indexList.clear();
}
WeatherBean.Indexs indexs=weatherBean.getData().getIndex();
indexList.add(indexs.getAirconditioner());
indexList.add(indexs.getCarwash());
indexList.add(indexs.getClothes());
indexList.add(indexs.getDrying());
indexList.add(indexs.getSports());
indexList.add(indexs.getTourism());
indexList.add(indexs.getUltraviolet());
indexAdapter.notifyDataSetChanged();
Log.i("Fragment更新","天气指数");
//今日数据填充
tv_thum_desc.setText(forecastDayList.get(1).getDayWeather());
tv_thum_temp.setText(forecastDayList.get(1).getMaxDegree()+"℃/"+forecastDayList.get(1).getMinDegree()+"℃");
String baseIconUrl=TxWeatherHelper.getWeatherStateIcon(forecastDayList.get(1).getDayWeatherCode(),true);
if(getContext()!=null){//防止fragment销毁后Glide仍然加载图片
Glide.with(getContext()).load(baseIconUrl).override(50).into(iv_thum_weather_icon);
}
Log.i("Fragment更新","今日天气");
//header数据填充
WeatherBean.Observe observe=weatherBean.getData().getObserve();
tv_current_temp.setText(observe.getDegree()+"℃");
tv_current_state.setText(observe.getWeather());
tv_current_tips.setText(weatherBean.getData().getTips().get("observe").getTip0()+"\n"+weatherBean.getData().getTips().get("observe").getTip1());
tv_current_wind.setText(observe.getWindDirection()+"/"+observe.getWindPower()+"级");
String time=forecastDayList.get(1).getTime();
tv_header_date.setText(time.substring(5)+" "+DateHelper.convertDateToWeek(time));
Log.i("Fragment更新","header数据");
//更新更多数据
tv_more_press.setText("大气压力:"+observe.getPressure());
tv_more_humi.setText("空气湿度:"+observe.getHumidity());
WeatherBean.Air air=weatherBean.getData().getAir();
tv_more_air_index.setText("污染指数:"+air.getAqi());
tv_more_air_quality.setText("空气质量:"+air.getAqiName());
Log.i("空气:",air.toString());
ll_header_show_more.setVisibility(View.VISIBLE);
//更新本地数据库
dbHelper.open();
dbHelper.updateCity(cityDetailBean);
dbHelper.close();
Log.i("Fragment更新","数据库更新");
}
@Override
public void onFailed(String reason) {
Log.i(TAG+"onFailed()\t",reason);
if(retryCount<2){
retryCount++;
refreshView();
}
}
});
helper.doAsyncRequest(updateLink);
}
}
| bestyize/MiniWeather | app/src/main/java/com/yize/miniweather/view/fragment/CityFragment.java | 2,630 | //48小时的每小时天气预报填充 | line_comment | zh-cn | package com.yize.miniweather.view.fragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.yize.miniweather.R;
import com.yize.miniweather.bean.CityDetailBean;
import com.yize.miniweather.bean.CityShip;
import com.yize.miniweather.bean.WeatherBean;
import com.yize.miniweather.db.CityDatabaseHelper;
import com.yize.miniweather.txweather.TxWeatherHelper;
import com.yize.miniweather.util.AsyncHttpRequestListener;
import com.yize.miniweather.util.DateHelper;
import com.yize.miniweather.util.HttpAsyncTaskHelper;
import com.yize.miniweather.util.HttpLiteBusHelper;
import com.yize.miniweather.view.adapter.DayAdapter;
import com.yize.miniweather.view.adapter.HourAdapter;
import com.yize.miniweather.view.adapter.IndexAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import okhttp3.OkHttpClient;
/**
* A simple {@link Fragment} subclass.
*/
public class CityFragment extends Fragment {
private static final String TAG="CityFragment" ;
private TextView tv_thum_day,tv_thum_desc,tv_thum_temp,tv_current_temp,tv_current_state,tv_current_wind,tv_current_tips,tv_header_date
,tv_more_humi,tv_more_press,tv_more_air_index,tv_more_air_quality;
private ImageView iv_thum_weather_icon,iv_header_more;
private LinearLayout ll_header_show_more;
private RecyclerView rv_hour_list;
private RecyclerView rv_day_list;
private RecyclerView rv_index_list;
private HourAdapter hourAdapter;
private DayAdapter dayAdapter;
private IndexAdapter indexAdapter;
private List<WeatherBean.ForecastHour> forecastHourList=new ArrayList<>(48);
private List<WeatherBean.ForecastDay> forecastDayList=new ArrayList<>(15);
private List<WeatherBean.Index> indexList=new ArrayList<>(9);
private boolean showMore=true;
private CityDatabaseHelper dbHelper;
public CityFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view=inflater.inflate(R.layout.fragment_city, container, false);
initView(view);
refreshView();
return view;
}
private void initView(View view){
dbHelper=new CityDatabaseHelper(getActivity());
tv_header_date=view.findViewById(R.id.tv_header_date);
tv_current_temp=view.findViewById(R.id.tv_current_temp);
tv_current_state=view.findViewById(R.id.tv_current_state);
tv_current_wind=view.findViewById(R.id.tv_current_wind);
tv_current_tips=view.findViewById(R.id.tv_current_tips);
tv_thum_day=view.findViewById(R.id.tv_thum_day);
tv_thum_desc=view.findViewById(R.id.tv_thum_desc);
tv_thum_temp=view.findViewById(R.id.tv_thum_temp);
iv_thum_weather_icon=view.findViewById(R.id.iv_thum_weather_icon);
ll_header_show_more=view.findViewById(R.id.ll_header_show_more);
iv_header_more=view.findViewById(R.id.iv_header_more);
tv_more_humi=view.findViewById(R.id.tv_more_humi);
tv_more_press=view.findViewById(R.id.tv_more_press);
tv_more_air_index=view.findViewById(R.id.tv_more_air_index);
tv_more_air_quality=view.findViewById(R.id.tv_more_air_quality);
iv_header_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(showMore){
Glide.with(getContext()).load(R.drawable.ic_keyboard_arrow_up_black_24dp).into(iv_header_more);
ll_header_show_more.setVisibility(View.VISIBLE);
}else {
Glide.with(getContext()).load(R.drawable.ic_keyboard_arrow_down_black_24dp).into(iv_header_more);
ll_header_show_more.setVisibility(View.GONE);
}
showMore=!showMore;
}
});
rv_hour_list=view.findViewById(R.id.rv_hour_list);
rv_day_list=view.findViewById(R.id.rv_day_list);
rv_index_list=view.findViewById(R.id.rv_index_list);
LinearLayoutManager hourManager=new LinearLayoutManager(view.getContext());
hourManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rv_hour_list.setLayoutManager(hourManager);
hourAdapter=new HourAdapter(forecastHourList);
rv_hour_list.setAdapter(hourAdapter);
LinearLayoutManager dayManager=new LinearLayoutManager(view.getContext());
dayManager.setOrientation(LinearLayoutManager.HORIZONTAL);
rv_day_list.setLayoutManager(dayManager);
dayAdapter=new DayAdapter(forecastDayList);
rv_day_list.setAdapter(dayAdapter);
GridLayoutManager indexManager=new GridLayoutManager(view.getContext(),4);
rv_index_list.setLayoutManager(indexManager);
indexAdapter=new IndexAdapter(indexList);
rv_index_list.setAdapter(indexAdapter);
}
private int retryCount=0;
private void refreshView(){
Bundle bundle=getArguments();
//更新城市信息的链接,应该直接传过来
String updateLink=bundle.getString("updateLink");
CityDetailBean cityDetailBean=(CityDetailBean)bundle.getSerializable("cityDetailBean");
HttpLiteBusHelper helper=new HttpLiteBusHelper(new AsyncHttpRequestListener() {
@Override
public void onSuccess(String result) {
//解析JSON 更新UI
WeatherBean weatherBean=TxWeatherHelper.parseWeatherData(result);
//48 <SUF>
if(forecastHourList.isEmpty()==false){
forecastHourList.clear();
}
Map<String, WeatherBean.ForecastHour> map=weatherBean.getData().getForecastHour();
for(String key:map.keySet()){
forecastHourList.add(map.get(key));
}
Collections.sort(forecastHourList, (o1, o2) -> o1.getUpdateTime().compareTo(o2.getUpdateTime()));
hourAdapter.notifyDataSetChanged();
Log.i("Fragment更新","48小时");
//7天天气预报填充
if(forecastDayList.size()!=0){
forecastDayList.clear();
}
Map<String, WeatherBean.ForecastDay> mmp=weatherBean.getData().getForecastDay();
for(String key:mmp.keySet()){
forecastDayList.add(Integer.valueOf(key),mmp.get(key));
}
Collections.sort(forecastDayList, (o1, o2) -> o1.getTime().compareTo(o2.getTime()));
dayAdapter.notifyDataSetChanged();
Log.i("Fragment更新","七日天气");
//天气指数填充
if(indexList.size()!=0){
indexList.clear();
}
WeatherBean.Indexs indexs=weatherBean.getData().getIndex();
indexList.add(indexs.getAirconditioner());
indexList.add(indexs.getCarwash());
indexList.add(indexs.getClothes());
indexList.add(indexs.getDrying());
indexList.add(indexs.getSports());
indexList.add(indexs.getTourism());
indexList.add(indexs.getUltraviolet());
indexAdapter.notifyDataSetChanged();
Log.i("Fragment更新","天气指数");
//今日数据填充
tv_thum_desc.setText(forecastDayList.get(1).getDayWeather());
tv_thum_temp.setText(forecastDayList.get(1).getMaxDegree()+"℃/"+forecastDayList.get(1).getMinDegree()+"℃");
String baseIconUrl=TxWeatherHelper.getWeatherStateIcon(forecastDayList.get(1).getDayWeatherCode(),true);
if(getContext()!=null){//防止fragment销毁后Glide仍然加载图片
Glide.with(getContext()).load(baseIconUrl).override(50).into(iv_thum_weather_icon);
}
Log.i("Fragment更新","今日天气");
//header数据填充
WeatherBean.Observe observe=weatherBean.getData().getObserve();
tv_current_temp.setText(observe.getDegree()+"℃");
tv_current_state.setText(observe.getWeather());
tv_current_tips.setText(weatherBean.getData().getTips().get("observe").getTip0()+"\n"+weatherBean.getData().getTips().get("observe").getTip1());
tv_current_wind.setText(observe.getWindDirection()+"/"+observe.getWindPower()+"级");
String time=forecastDayList.get(1).getTime();
tv_header_date.setText(time.substring(5)+" "+DateHelper.convertDateToWeek(time));
Log.i("Fragment更新","header数据");
//更新更多数据
tv_more_press.setText("大气压力:"+observe.getPressure());
tv_more_humi.setText("空气湿度:"+observe.getHumidity());
WeatherBean.Air air=weatherBean.getData().getAir();
tv_more_air_index.setText("污染指数:"+air.getAqi());
tv_more_air_quality.setText("空气质量:"+air.getAqiName());
Log.i("空气:",air.toString());
ll_header_show_more.setVisibility(View.VISIBLE);
//更新本地数据库
dbHelper.open();
dbHelper.updateCity(cityDetailBean);
dbHelper.close();
Log.i("Fragment更新","数据库更新");
}
@Override
public void onFailed(String reason) {
Log.i(TAG+"onFailed()\t",reason);
if(retryCount<2){
retryCount++;
refreshView();
}
}
});
helper.doAsyncRequest(updateLink);
}
}
| false | 1,991 | 10 | 2,630 | 14 | 2,704 | 11 | 2,630 | 14 | 3,208 | 25 | false | false | false | false | false | true |
51529_5 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
public class HttpPost {
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("encoding", "utf-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static void main(String[] args){
//发送 POST 请求
String sr=HttpPost.sendPost("http://localhost:8088/getProductById", "id=123");
System.out.println(sr);
}
}
| bestzhi/hello-world | src/HttpPost.java | 563 | // 发送请求参数
| line_comment | zh-cn | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
public class HttpPost {
/**
* 向指定 URL 发送POST方法的请求
*
* @param url
* 发送请求的 URL
* @param param
* 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
* @return 所代表远程资源的响应结果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("encoding", "utf-8");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送 <SUF>
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
public static void main(String[] args){
//发送 POST 请求
String sr=HttpPost.sendPost("http://localhost:8088/getProductById", "id=123");
System.out.println(sr);
}
}
| false | 512 | 6 | 557 | 6 | 606 | 5 | 557 | 6 | 736 | 9 | false | false | false | false | false | true |
45998_13 | package org.itcast.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Business {
private Long id; // 商机id
private String name; // 客户姓名
private String phone; // 手机号
private String channel; // 渠道
private Long activityId; // 活动id
private String provinces; // 省
private String city; // 城市
private String sex; // 性别
private Integer age; // 年龄
private String weixin; // 微信
private String qq; // qq
private String level; // 意向等级
private String subject; // 意向学科
private Long courseId; // 课程
private String createBy; // 创建人
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime; // 创建时间
private String occupation; // 职业
private String education; // 学历
private String job; // 在职情况
private String salary; // 当前薪资
private String major; // 专业
private String expectedSalary; // 目标薪资
private String reasons; // 学习原因
private String plan; // 职业计划
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime planTime; // 时间计划
private String otherIntention; // 其他意向
private String status; // 状态
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime lastUpdateTime; // 最后更新时间
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime endTime; // 回收时间
private String remark; // 备注
private String transfer; // 是否转派
private String clueId; // 线索
private String owner; // 归属人
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime ownerTime; // 归属时间
private String keyItems; // 沟通重点
private String record; // 沟通纪要
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime nextTime; // 下次跟进时间
private String trackStatus; // 跟进状态
}
| beta-z/kdtx | kdtx-pojo/src/main/java/org/itcast/entity/Business.java | 723 | // 时间计划 | line_comment | zh-cn | package org.itcast.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import java.time.LocalDateTime;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Business {
private Long id; // 商机id
private String name; // 客户姓名
private String phone; // 手机号
private String channel; // 渠道
private Long activityId; // 活动id
private String provinces; // 省
private String city; // 城市
private String sex; // 性别
private Integer age; // 年龄
private String weixin; // 微信
private String qq; // qq
private String level; // 意向等级
private String subject; // 意向学科
private Long courseId; // 课程
private String createBy; // 创建人
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime; // 创建时间
private String occupation; // 职业
private String education; // 学历
private String job; // 在职情况
private String salary; // 当前薪资
private String major; // 专业
private String expectedSalary; // 目标薪资
private String reasons; // 学习原因
private String plan; // 职业计划
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime planTime; // 时间 <SUF>
private String otherIntention; // 其他意向
private String status; // 状态
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime lastUpdateTime; // 最后更新时间
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime endTime; // 回收时间
private String remark; // 备注
private String transfer; // 是否转派
private String clueId; // 线索
private String owner; // 归属人
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime ownerTime; // 归属时间
private String keyItems; // 沟通重点
private String record; // 沟通纪要
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime nextTime; // 下次跟进时间
private String trackStatus; // 跟进状态
}
| false | 666 | 3 | 723 | 4 | 713 | 3 | 723 | 4 | 896 | 8 | false | false | false | false | false | true |
16907_2 |
import redis.clients.jedis.Jedis;
/**
* 使用redis实现分布式锁(推荐)
*
* @author beyond
* @version 1.0
* @date 2016/12/1
*/
public class JedLock {
private static final String LOCK_KEY = "jedis_lock";
private static final int RETRY_TIME = 10 * 1000; //等待锁的时间
private static final int EXPIRE_TIME = 60 * 1000;//锁超时的时间
private boolean locked;
private long lockValue;
public synchronized boolean lock(Jedis jedis){
int retryTime = RETRY_TIME;
try {
while (retryTime > 0) {
lockValue = System.nanoTime();
if ("OK".equalsIgnoreCase(jedis.set(LOCK_KEY, String.valueOf(lockValue), "NX", "PX", EXPIRE_TIME))) {
locked = true;
return locked;
}
retryTime -= 100;
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public synchronized void unlock(Jedis jedis){
if(locked) {
String currLockVal = jedis.get(LOCK_KEY);
if(currLockVal!=null && Long.valueOf(currLockVal) == lockValue){
jedis.del(LOCK_KEY);
locked = false;
}
}
}
public static void main(String[] args) throws InterruptedException {
Jedis jedis = new Jedis("192.168.75.129", 6379);
JedLock redLock = new JedLock();
if(redLock.lock(jedis)) {
System.out.println(Thread.currentThread().getName() + ": 获得锁!");
Thread.sleep(25000);
System.out.println(Thread.currentThread().getName() + ": 处理完成!");
redLock.unlock(jedis);
System.out.println(Thread.currentThread().getName() + ": 释放锁!");
}else {
System.out.println("get lock fail!!!");
}
}
}
| beyondfengyu/DistributedLock | JedLock.java | 517 | //锁超时的时间
| line_comment | zh-cn |
import redis.clients.jedis.Jedis;
/**
* 使用redis实现分布式锁(推荐)
*
* @author beyond
* @version 1.0
* @date 2016/12/1
*/
public class JedLock {
private static final String LOCK_KEY = "jedis_lock";
private static final int RETRY_TIME = 10 * 1000; //等待锁的时间
private static final int EXPIRE_TIME = 60 * 1000;//锁超 <SUF>
private boolean locked;
private long lockValue;
public synchronized boolean lock(Jedis jedis){
int retryTime = RETRY_TIME;
try {
while (retryTime > 0) {
lockValue = System.nanoTime();
if ("OK".equalsIgnoreCase(jedis.set(LOCK_KEY, String.valueOf(lockValue), "NX", "PX", EXPIRE_TIME))) {
locked = true;
return locked;
}
retryTime -= 100;
Thread.sleep(100);
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public synchronized void unlock(Jedis jedis){
if(locked) {
String currLockVal = jedis.get(LOCK_KEY);
if(currLockVal!=null && Long.valueOf(currLockVal) == lockValue){
jedis.del(LOCK_KEY);
locked = false;
}
}
}
public static void main(String[] args) throws InterruptedException {
Jedis jedis = new Jedis("192.168.75.129", 6379);
JedLock redLock = new JedLock();
if(redLock.lock(jedis)) {
System.out.println(Thread.currentThread().getName() + ": 获得锁!");
Thread.sleep(25000);
System.out.println(Thread.currentThread().getName() + ": 处理完成!");
redLock.unlock(jedis);
System.out.println(Thread.currentThread().getName() + ": 释放锁!");
}else {
System.out.println("get lock fail!!!");
}
}
}
| false | 451 | 6 | 514 | 5 | 532 | 5 | 514 | 5 | 619 | 10 | false | false | false | false | false | true |
16080_5 |
/**
* twitter的snowflake算法 -- java实现
*
* @author beyond
* @date 2016/11/26
*/
public class SnowFlake {
/**
* 起始的时间戳
*/
private final static long START_STMP = 1480166465631L;
/**
* 每一部分占用的位数
*/
private final static long SEQUENCE_BIT = 12; //序列号占用的位数
private final static long MACHINE_BIT = 5; //机器标识占用的位数
private final static long DATACENTER_BIT = 5;//数据中心占用的位数
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; //数据中心
private long machineId; //机器标识
private long sequence = 0L; //序列号
private long lastStmp = -1L;//上一次时间戳
public SnowFlake(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
/**
* 产生下一个ID
*
* @return
*/
public synchronized long nextId() {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
//相同毫秒内,序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列数已经达到最大
if (sequence == 0L) {
currStmp = getNextMill();
}
} else {
//不同毫秒内,序列号置为0
sequence = 0L;
}
lastStmp = currStmp;
return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
| datacenterId << DATACENTER_LEFT //数据中心部分
| machineId << MACHINE_LEFT //机器标识部分
| sequence; //序列号部分
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private long getNewstmp() {
return System.currentTimeMillis();
}
public static void main(String[] args) {
SnowFlake snowFlake = new SnowFlake(2, 3);
for (int i = 0; i < (1 << 12); i++) {
System.out.println(snowFlake.nextId());
}
}
}
| beyondfengyu/SnowFlake | SnowFlake.java | 869 | //数据中心占用的位数
| line_comment | zh-cn |
/**
* twitter的snowflake算法 -- java实现
*
* @author beyond
* @date 2016/11/26
*/
public class SnowFlake {
/**
* 起始的时间戳
*/
private final static long START_STMP = 1480166465631L;
/**
* 每一部分占用的位数
*/
private final static long SEQUENCE_BIT = 12; //序列号占用的位数
private final static long MACHINE_BIT = 5; //机器标识占用的位数
private final static long DATACENTER_BIT = 5;//数据 <SUF>
/**
* 每一部分的最大值
*/
private final static long MAX_DATACENTER_NUM = -1L ^ (-1L << DATACENTER_BIT);
private final static long MAX_MACHINE_NUM = -1L ^ (-1L << MACHINE_BIT);
private final static long MAX_SEQUENCE = -1L ^ (-1L << SEQUENCE_BIT);
/**
* 每一部分向左的位移
*/
private final static long MACHINE_LEFT = SEQUENCE_BIT;
private final static long DATACENTER_LEFT = SEQUENCE_BIT + MACHINE_BIT;
private final static long TIMESTMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT;
private long datacenterId; //数据中心
private long machineId; //机器标识
private long sequence = 0L; //序列号
private long lastStmp = -1L;//上一次时间戳
public SnowFlake(long datacenterId, long machineId) {
if (datacenterId > MAX_DATACENTER_NUM || datacenterId < 0) {
throw new IllegalArgumentException("datacenterId can't be greater than MAX_DATACENTER_NUM or less than 0");
}
if (machineId > MAX_MACHINE_NUM || machineId < 0) {
throw new IllegalArgumentException("machineId can't be greater than MAX_MACHINE_NUM or less than 0");
}
this.datacenterId = datacenterId;
this.machineId = machineId;
}
/**
* 产生下一个ID
*
* @return
*/
public synchronized long nextId() {
long currStmp = getNewstmp();
if (currStmp < lastStmp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
if (currStmp == lastStmp) {
//相同毫秒内,序列号自增
sequence = (sequence + 1) & MAX_SEQUENCE;
//同一毫秒的序列数已经达到最大
if (sequence == 0L) {
currStmp = getNextMill();
}
} else {
//不同毫秒内,序列号置为0
sequence = 0L;
}
lastStmp = currStmp;
return (currStmp - START_STMP) << TIMESTMP_LEFT //时间戳部分
| datacenterId << DATACENTER_LEFT //数据中心部分
| machineId << MACHINE_LEFT //机器标识部分
| sequence; //序列号部分
}
private long getNextMill() {
long mill = getNewstmp();
while (mill <= lastStmp) {
mill = getNewstmp();
}
return mill;
}
private long getNewstmp() {
return System.currentTimeMillis();
}
public static void main(String[] args) {
SnowFlake snowFlake = new SnowFlake(2, 3);
for (int i = 0; i < (1 << 12); i++) {
System.out.println(snowFlake.nextId());
}
}
}
| false | 823 | 7 | 866 | 8 | 925 | 8 | 866 | 8 | 1,102 | 13 | false | false | false | false | false | true |
38237_10 | package ink.on.central.bot;
/**
* 常量存放类
* <p>
* Create Time: 2024-04-08 Last Update:
*
* @author BGLuminous
* @since 1.0.0
*/
public class Constant {
public static final String PRIVATE = "private";
public static final String GROUP = "group";
/** API Action */
public static class API {
/** 发送消息 合并了 [send_private_msg 发送私聊消息] 和 [send_group_msg 发送群消息] */
public static final String SEND_MSG = "send_msg";
/** 撤回消息 */
public static final String DELETE_MSG = "delete_msg";
/** 获取消息 */
public static final String GET_MSG = "get_msg";
/** 获取合并转发消息 */
public static final String GET_FORWARD_MSG = "get_forward_msg";
/** 发送好友赞 */
public static final String SEND_LIKE = "send_like";
/** 群组踢人 */
public static final String SET_GROUP_KICK = "set_group_kick";
/** 群组单人禁言 */
public static final String SET_GROUP_BAN = "set_group_ban";
/** 群组匿名用户禁言 */
public static final String SET_GROUP_ANONYMOUS_BAN = "set_group_anonymous_ban";
/** 群组全员禁言 */
public static final String SET_GROUP_WHOLE_BAN = "set_group_whole_ban";
/** 群组设置管理员 */
public static final String SET_GROUP_ADMIN = "set_group_admin";
/** 群组匿名 */
public static final String SET_GROUP_ANONYMOUS = "set_group_anonymous";
/** 设置群名片(群备注) */
public static final String SET_GROUP_CARD = "set_group_card";
/** 设置群名 */
public static final String SET_GROUP_NAME = "set_group_name";
/** 退出群组 */
public static final String SET_GROUP_LEAVE = "set_group_leave";
/** 设置群组专属头衔 */
public static final String SET_GROUP_SPECIAL_TITLE = "set_group_special_title";
/** 处理加好友请求 */
public static final String SET_FRIEND_ADD_REQUEST = "set_friend_add_request";
/** 处理加群请求/邀请 */
public static final String SET_GROUP_ADD_REQUEST = "set_group_add_request";
/** 获取登录号信息 */
public static final String GET_LOGIN_INFO = "get_login_info";
/** 获取陌生人信息 */
public static final String GET_STRANGER_INFO = "get_stranger_info";
/** 获取好友列表 */
public static final String GET_FRIEND_LIST = "get_friend_list";
/** 获取群信息 */
public static final String GET_GROUP_INFO = "get_group_info";
/** 获取群列表 */
public static final String GET_GROUP_LIST = "get_group_list";
/** 获取群成员信息 */
public static final String GET_GROUP_MEMBER_INFO = "get_group_member_info";
/** 获取群成员列表 */
public static final String GET_GROUP_MEMBER_LIST = "get_group_member_list";
/** 获取群荣誉信息 */
public static final String GET_GROUP_HONOR_INFO = "get_group_honor_info";
/** 获取 QQ 相关接口凭证 */
public static final String GET_CREDENTIAL = "get_credentials";
/** 获取语音 */
public static final String GET_RECORD = "get_record";
/** 获取图片 */
public static final String GET_IMAGE = "get_image";
/** 检查是否可以发送图片 */
public static final String CAN_SEND_IMAGE = "can_send_image";
/** 检查是否可以发送语音 */
public static final String CAN_SEND_VOICE = "can_send_voice";
/** 获取运行状态 */
public static final String GET_STATUS = "get_status";
/** 获取版本信息 */
public static final String GET_VERSION_INFO = "get_version_info";
/** 重启 OneBot 实现 */
public static final String SET_RESTART = "set_restart";
/** 清理缓存 */
public static final String CLEAN_CACHE = "clean_cache";
/** 私有构造方法 */
private API() {
}
}
/** 私有构造方法 */
private Constant() {
}
}
| bgluminous/mira-bot-rebirth-ntqq | src/main/java/ink/on/central/bot/Constant.java | 1,074 | /** 群组全员禁言 */ | block_comment | zh-cn | package ink.on.central.bot;
/**
* 常量存放类
* <p>
* Create Time: 2024-04-08 Last Update:
*
* @author BGLuminous
* @since 1.0.0
*/
public class Constant {
public static final String PRIVATE = "private";
public static final String GROUP = "group";
/** API Action */
public static class API {
/** 发送消息 合并了 [send_private_msg 发送私聊消息] 和 [send_group_msg 发送群消息] */
public static final String SEND_MSG = "send_msg";
/** 撤回消息 */
public static final String DELETE_MSG = "delete_msg";
/** 获取消息 */
public static final String GET_MSG = "get_msg";
/** 获取合并转发消息 */
public static final String GET_FORWARD_MSG = "get_forward_msg";
/** 发送好友赞 */
public static final String SEND_LIKE = "send_like";
/** 群组踢人 */
public static final String SET_GROUP_KICK = "set_group_kick";
/** 群组单人禁言 */
public static final String SET_GROUP_BAN = "set_group_ban";
/** 群组匿名用户禁言 */
public static final String SET_GROUP_ANONYMOUS_BAN = "set_group_anonymous_ban";
/** 群组全 <SUF>*/
public static final String SET_GROUP_WHOLE_BAN = "set_group_whole_ban";
/** 群组设置管理员 */
public static final String SET_GROUP_ADMIN = "set_group_admin";
/** 群组匿名 */
public static final String SET_GROUP_ANONYMOUS = "set_group_anonymous";
/** 设置群名片(群备注) */
public static final String SET_GROUP_CARD = "set_group_card";
/** 设置群名 */
public static final String SET_GROUP_NAME = "set_group_name";
/** 退出群组 */
public static final String SET_GROUP_LEAVE = "set_group_leave";
/** 设置群组专属头衔 */
public static final String SET_GROUP_SPECIAL_TITLE = "set_group_special_title";
/** 处理加好友请求 */
public static final String SET_FRIEND_ADD_REQUEST = "set_friend_add_request";
/** 处理加群请求/邀请 */
public static final String SET_GROUP_ADD_REQUEST = "set_group_add_request";
/** 获取登录号信息 */
public static final String GET_LOGIN_INFO = "get_login_info";
/** 获取陌生人信息 */
public static final String GET_STRANGER_INFO = "get_stranger_info";
/** 获取好友列表 */
public static final String GET_FRIEND_LIST = "get_friend_list";
/** 获取群信息 */
public static final String GET_GROUP_INFO = "get_group_info";
/** 获取群列表 */
public static final String GET_GROUP_LIST = "get_group_list";
/** 获取群成员信息 */
public static final String GET_GROUP_MEMBER_INFO = "get_group_member_info";
/** 获取群成员列表 */
public static final String GET_GROUP_MEMBER_LIST = "get_group_member_list";
/** 获取群荣誉信息 */
public static final String GET_GROUP_HONOR_INFO = "get_group_honor_info";
/** 获取 QQ 相关接口凭证 */
public static final String GET_CREDENTIAL = "get_credentials";
/** 获取语音 */
public static final String GET_RECORD = "get_record";
/** 获取图片 */
public static final String GET_IMAGE = "get_image";
/** 检查是否可以发送图片 */
public static final String CAN_SEND_IMAGE = "can_send_image";
/** 检查是否可以发送语音 */
public static final String CAN_SEND_VOICE = "can_send_voice";
/** 获取运行状态 */
public static final String GET_STATUS = "get_status";
/** 获取版本信息 */
public static final String GET_VERSION_INFO = "get_version_info";
/** 重启 OneBot 实现 */
public static final String SET_RESTART = "set_restart";
/** 清理缓存 */
public static final String CLEAN_CACHE = "clean_cache";
/** 私有构造方法 */
private API() {
}
}
/** 私有构造方法 */
private Constant() {
}
}
| false | 913 | 9 | 1,074 | 9 | 1,088 | 8 | 1,074 | 9 | 1,337 | 11 | false | false | false | false | false | true |
40430_0 | package com.huagu.vcoin.main.service.admin;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huagu.vcoin.main.Enum.MessageStatusEnum;
import com.huagu.vcoin.main.Enum.OperationlogEnum;
import com.huagu.vcoin.main.dao.FmessageDAO;
import com.huagu.vcoin.main.dao.FoperationlogDAO;
import com.huagu.vcoin.main.dao.FvirtualwalletDAO;
import com.huagu.vcoin.main.model.Fadmin;
import com.huagu.vcoin.main.model.Fmessage;
import com.huagu.vcoin.main.model.Foperationlog;
import com.huagu.vcoin.main.model.Fvirtualwallet;
import com.huagu.vcoin.util.Utils;
@Service
public class OperationLogService {
@Autowired
private FoperationlogDAO operationlogDAO;
@Autowired
private FmessageDAO messageDAO;
@Autowired
private FvirtualwalletDAO virtualwalletDAO;
public Foperationlog findById(int id) {
Foperationlog operationLog = this.operationlogDAO.findById(id);
;
return operationLog;
}
public void saveObj(Foperationlog obj) {
this.operationlogDAO.save(obj);
}
public void deleteObj(int id) {
Foperationlog obj = this.operationlogDAO.findById(id);
this.operationlogDAO.delete(obj);
}
public void updateObj(Foperationlog obj) {
this.operationlogDAO.attachDirty(obj);
}
public List<Foperationlog> findByProperty(String name, Object value) {
return this.operationlogDAO.findByProperty(name, value);
}
public List<Foperationlog> findAll() {
return this.operationlogDAO.findAll();
}
public List<Foperationlog> list(int firstResult, int maxResults, String filter, boolean isFY) {
List<Foperationlog> all = this.operationlogDAO.list(firstResult, maxResults, filter, isFY);
for (Foperationlog foperationlog : all) {
foperationlog.getFuser().getFemail();
}
return all;
}
public boolean updateOperationLog(int operationId, Fadmin auditor) throws RuntimeException {
// 判断能否找到记录
try {
Foperationlog operationLog = findById(operationId);
if (operationLog == null) {
return false;
} else if (operationLog.getFstatus() != OperationlogEnum.SAVE) {
return false;
}
double amount = operationLog.getFamount();
Fvirtualwallet wallet = this.virtualwalletDAO.findWallet(operationLog.getFuser().getFid());
wallet.setFtotal(wallet.getFtotal() + amount);
wallet.setFlastUpdateTime(Utils.getTimestamp());
this.virtualwalletDAO.attachDirty(wallet);
operationLog.setFlastUpdateTime(Utils.getTimestamp());
operationLog.setFstatus(OperationlogEnum.AUDIT);
operationLog.setFkey1(auditor.getFname());
this.operationlogDAO.attachDirty(operationLog);
String title = "管理员向您充值" + amount + "人民币,请注意查收";
Fmessage msg = new Fmessage();
msg.setFcreateTime(Utils.getTimestamp());
msg.setFcontent(title);
msg.setFreceiver(operationLog.getFuser());
msg.setFcreator(auditor);
msg.setFtitle(title);
msg.setFstatus(MessageStatusEnum.NOREAD_VALUE);
this.messageDAO.save(msg);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
return true;
}
public double getTotalAmt(int userid) {
return this.operationlogDAO.getTotalAmt1(userid) + this.operationlogDAO.getTotalAmt2(userid);
}
} | biecology/dpom | OperationLogService.java | 956 | // 判断能否找到记录
| line_comment | zh-cn | package com.huagu.vcoin.main.service.admin;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huagu.vcoin.main.Enum.MessageStatusEnum;
import com.huagu.vcoin.main.Enum.OperationlogEnum;
import com.huagu.vcoin.main.dao.FmessageDAO;
import com.huagu.vcoin.main.dao.FoperationlogDAO;
import com.huagu.vcoin.main.dao.FvirtualwalletDAO;
import com.huagu.vcoin.main.model.Fadmin;
import com.huagu.vcoin.main.model.Fmessage;
import com.huagu.vcoin.main.model.Foperationlog;
import com.huagu.vcoin.main.model.Fvirtualwallet;
import com.huagu.vcoin.util.Utils;
@Service
public class OperationLogService {
@Autowired
private FoperationlogDAO operationlogDAO;
@Autowired
private FmessageDAO messageDAO;
@Autowired
private FvirtualwalletDAO virtualwalletDAO;
public Foperationlog findById(int id) {
Foperationlog operationLog = this.operationlogDAO.findById(id);
;
return operationLog;
}
public void saveObj(Foperationlog obj) {
this.operationlogDAO.save(obj);
}
public void deleteObj(int id) {
Foperationlog obj = this.operationlogDAO.findById(id);
this.operationlogDAO.delete(obj);
}
public void updateObj(Foperationlog obj) {
this.operationlogDAO.attachDirty(obj);
}
public List<Foperationlog> findByProperty(String name, Object value) {
return this.operationlogDAO.findByProperty(name, value);
}
public List<Foperationlog> findAll() {
return this.operationlogDAO.findAll();
}
public List<Foperationlog> list(int firstResult, int maxResults, String filter, boolean isFY) {
List<Foperationlog> all = this.operationlogDAO.list(firstResult, maxResults, filter, isFY);
for (Foperationlog foperationlog : all) {
foperationlog.getFuser().getFemail();
}
return all;
}
public boolean updateOperationLog(int operationId, Fadmin auditor) throws RuntimeException {
// 判断 <SUF>
try {
Foperationlog operationLog = findById(operationId);
if (operationLog == null) {
return false;
} else if (operationLog.getFstatus() != OperationlogEnum.SAVE) {
return false;
}
double amount = operationLog.getFamount();
Fvirtualwallet wallet = this.virtualwalletDAO.findWallet(operationLog.getFuser().getFid());
wallet.setFtotal(wallet.getFtotal() + amount);
wallet.setFlastUpdateTime(Utils.getTimestamp());
this.virtualwalletDAO.attachDirty(wallet);
operationLog.setFlastUpdateTime(Utils.getTimestamp());
operationLog.setFstatus(OperationlogEnum.AUDIT);
operationLog.setFkey1(auditor.getFname());
this.operationlogDAO.attachDirty(operationLog);
String title = "管理员向您充值" + amount + "人民币,请注意查收";
Fmessage msg = new Fmessage();
msg.setFcreateTime(Utils.getTimestamp());
msg.setFcontent(title);
msg.setFreceiver(operationLog.getFuser());
msg.setFcreator(auditor);
msg.setFtitle(title);
msg.setFstatus(MessageStatusEnum.NOREAD_VALUE);
this.messageDAO.save(msg);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
return true;
}
public double getTotalAmt(int userid) {
return this.operationlogDAO.getTotalAmt1(userid) + this.operationlogDAO.getTotalAmt2(userid);
}
} | false | 772 | 7 | 945 | 7 | 991 | 6 | 945 | 7 | 1,131 | 13 | false | false | false | false | false | true |
38659_14 | package com.itellyou.service.event;
import com.itellyou.model.common.DataUpdateQueueModel;
import com.itellyou.model.common.IndexQueueModel;
import com.itellyou.model.common.OperationalModel;
import com.itellyou.model.event.QuestionCommentEvent;
import com.itellyou.model.event.QuestionEvent;
import com.itellyou.model.question.QuestionUpdateStepModel;
import com.itellyou.model.sys.EntityAction;
import com.itellyou.model.sys.EntityType;
import com.itellyou.model.user.UserActivityModel;
import com.itellyou.service.common.DataUpdateManageService;
import com.itellyou.service.common.IndexManagerService;
import com.itellyou.service.user.UserActivityService;
import com.itellyou.util.DateUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class QuestionEventListener {
private final UserActivityService activityService;
private final IndexManagerService indexManagerService;
private final DataUpdateManageService dataUpdateManageService;
public QuestionEventListener(UserActivityService activityService, IndexManagerService indexManagerService, DataUpdateManageService dataUpdateManageService) {
this.activityService = activityService;
this.indexManagerService = indexManagerService;
this.dataUpdateManageService = dataUpdateManageService;
}
@EventListener
@Async
public void questionEvent(QuestionEvent event){
OperationalModel model = event.getOperationalModel();
if(model == null) return;
switch (model.getAction()){
case LIKE:// 点赞
case UNLIKE:// 取消点赞
case DISLIKE:// 反对
case UNDISLIKE:// 取消反对
case FOLLOW:// 关注
case UNFOLLOW:// 取消关注
case PUBLISH:// 发布
case UPDATE:// 更新
case COMMENT:// 评论
case VIEW:// 查看
case REVERT:// 撤销删除
// 更新索引
indexManagerService.put(new IndexQueueModel(model.getType(),model.getTargetId()));
break;
case DELETE:// 删除回答
// 删除索引
indexManagerService.put(new IndexQueueModel(model.getType(),true,model.getTargetId()));
break;
}
// 写入用户活动记录
switch (model.getAction()){
case LIKE:// 点赞,当前问题没有点赞功能
case FOLLOW:// 关注
case PUBLISH:// 发布
// 有相同操作则更新用户活动时间
activityService.insert(new UserActivityModel(model.getAction(),model.getType(),model.getTargetId(),model.getTargetUserId(),model.getCreatedUserId(),model.getCreatedTime(),model.getCreatedIp()));
break;
case UNFOLLOW:// 取消关注 删除用户活动记录
activityService.delete(EntityAction.FOLLOW,model.getType(),model.getTargetId(),model.getCreatedUserId());
break;
case UNLIKE:// 取消点赞 删除用户活动记录
activityService.delete(EntityAction.LIKE,model.getType(),model.getTargetId(),model.getCreatedUserId());
break;
}
// 统计信息
Long date = DateUtils.getTimestamp(model.getCreatedTime().toLocalDate());
QuestionUpdateStepModel stepModel = new QuestionUpdateStepModel();
stepModel.setId(model.getTargetId());
switch (model.getAction()){
case LIKE:
case UNLIKE:// 取消点赞
stepModel.setSupportStep(model.getAction().equals(EntityAction.UNLIKE) ? -1 : 1);
break;
case DISLIKE:
case UNDISLIKE:// 取消反对
stepModel.setOpposeStep(model.getAction().equals(EntityAction.UNDISLIKE) ? -1 : 1);
break;
case FOLLOW:
case UNFOLLOW:
stepModel.setStarStep(model.getAction().equals(EntityAction.UNFOLLOW) ? -1 : 1);
break;
case VIEW:
stepModel.setViewStep(1);
break;
case COMMENT:
stepModel.setId(Long.valueOf(event.getArgs().get("question_id").toString()));
stepModel.setCommentStep(1);
break;
default:
stepModel = null;
}
if(stepModel != null){
DataUpdateQueueModel<QuestionUpdateStepModel> queueModel = new DataUpdateQueueModel(model.getTargetUserId(), EntityType.QUESTION,date,stepModel);
dataUpdateManageService.put(queueModel,(sModel,nModel) -> {
dataUpdateManageService.cumulative(sModel,nModel);
sModel.setAnswerStep(sModel.getAnswerStep() + nModel.getAnswerStep());
});
}
}
@EventListener
@Async
public void commentEvent(QuestionCommentEvent event){
OperationalModel model = event.getOperationalModel();
// 问题有新评论的时候更新索引
switch (model.getAction()){
case PUBLISH:// 新增评论
case COMMENT:// 评论已有的评论
// 统计信息
Long date = DateUtils.getTimestamp(model.getCreatedTime().toLocalDate());
QuestionUpdateStepModel stepModel = new QuestionUpdateStepModel();
stepModel.setId(Long.valueOf(event.getArgs().get("question_id").toString()));
stepModel.setCommentStep(1);
DataUpdateQueueModel<QuestionUpdateStepModel> queueModel = new DataUpdateQueueModel(model.getTargetUserId(), EntityType.QUESTION,date,stepModel);
dataUpdateManageService.put(queueModel,(sModel,nModel) -> {
dataUpdateManageService.cumulative(sModel,nModel);
sModel.setAnswerStep(sModel.getAnswerStep() + nModel.getAnswerStep());
});
indexManagerService.put(new IndexQueueModel(model.getType(),model.getTargetId()));
break;
}
}
}
| big-camel/itellyou-api | service/src/main/java/com/itellyou/service/event/QuestionEventListener.java | 1,363 | // 取消反对 | line_comment | zh-cn | package com.itellyou.service.event;
import com.itellyou.model.common.DataUpdateQueueModel;
import com.itellyou.model.common.IndexQueueModel;
import com.itellyou.model.common.OperationalModel;
import com.itellyou.model.event.QuestionCommentEvent;
import com.itellyou.model.event.QuestionEvent;
import com.itellyou.model.question.QuestionUpdateStepModel;
import com.itellyou.model.sys.EntityAction;
import com.itellyou.model.sys.EntityType;
import com.itellyou.model.user.UserActivityModel;
import com.itellyou.service.common.DataUpdateManageService;
import com.itellyou.service.common.IndexManagerService;
import com.itellyou.service.user.UserActivityService;
import com.itellyou.util.DateUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
@Service
public class QuestionEventListener {
private final UserActivityService activityService;
private final IndexManagerService indexManagerService;
private final DataUpdateManageService dataUpdateManageService;
public QuestionEventListener(UserActivityService activityService, IndexManagerService indexManagerService, DataUpdateManageService dataUpdateManageService) {
this.activityService = activityService;
this.indexManagerService = indexManagerService;
this.dataUpdateManageService = dataUpdateManageService;
}
@EventListener
@Async
public void questionEvent(QuestionEvent event){
OperationalModel model = event.getOperationalModel();
if(model == null) return;
switch (model.getAction()){
case LIKE:// 点赞
case UNLIKE:// 取消点赞
case DISLIKE:// 反对
case UNDISLIKE:// 取消反对
case FOLLOW:// 关注
case UNFOLLOW:// 取消关注
case PUBLISH:// 发布
case UPDATE:// 更新
case COMMENT:// 评论
case VIEW:// 查看
case REVERT:// 撤销删除
// 更新索引
indexManagerService.put(new IndexQueueModel(model.getType(),model.getTargetId()));
break;
case DELETE:// 删除回答
// 删除索引
indexManagerService.put(new IndexQueueModel(model.getType(),true,model.getTargetId()));
break;
}
// 写入用户活动记录
switch (model.getAction()){
case LIKE:// 点赞,当前问题没有点赞功能
case FOLLOW:// 关注
case PUBLISH:// 发布
// 有相同操作则更新用户活动时间
activityService.insert(new UserActivityModel(model.getAction(),model.getType(),model.getTargetId(),model.getTargetUserId(),model.getCreatedUserId(),model.getCreatedTime(),model.getCreatedIp()));
break;
case UNFOLLOW:// 取消关注 删除用户活动记录
activityService.delete(EntityAction.FOLLOW,model.getType(),model.getTargetId(),model.getCreatedUserId());
break;
case UNLIKE:// 取消点赞 删除用户活动记录
activityService.delete(EntityAction.LIKE,model.getType(),model.getTargetId(),model.getCreatedUserId());
break;
}
// 统计信息
Long date = DateUtils.getTimestamp(model.getCreatedTime().toLocalDate());
QuestionUpdateStepModel stepModel = new QuestionUpdateStepModel();
stepModel.setId(model.getTargetId());
switch (model.getAction()){
case LIKE:
case UNLIKE:// 取消点赞
stepModel.setSupportStep(model.getAction().equals(EntityAction.UNLIKE) ? -1 : 1);
break;
case DISLIKE:
case UNDISLIKE:// 取消 <SUF>
stepModel.setOpposeStep(model.getAction().equals(EntityAction.UNDISLIKE) ? -1 : 1);
break;
case FOLLOW:
case UNFOLLOW:
stepModel.setStarStep(model.getAction().equals(EntityAction.UNFOLLOW) ? -1 : 1);
break;
case VIEW:
stepModel.setViewStep(1);
break;
case COMMENT:
stepModel.setId(Long.valueOf(event.getArgs().get("question_id").toString()));
stepModel.setCommentStep(1);
break;
default:
stepModel = null;
}
if(stepModel != null){
DataUpdateQueueModel<QuestionUpdateStepModel> queueModel = new DataUpdateQueueModel(model.getTargetUserId(), EntityType.QUESTION,date,stepModel);
dataUpdateManageService.put(queueModel,(sModel,nModel) -> {
dataUpdateManageService.cumulative(sModel,nModel);
sModel.setAnswerStep(sModel.getAnswerStep() + nModel.getAnswerStep());
});
}
}
@EventListener
@Async
public void commentEvent(QuestionCommentEvent event){
OperationalModel model = event.getOperationalModel();
// 问题有新评论的时候更新索引
switch (model.getAction()){
case PUBLISH:// 新增评论
case COMMENT:// 评论已有的评论
// 统计信息
Long date = DateUtils.getTimestamp(model.getCreatedTime().toLocalDate());
QuestionUpdateStepModel stepModel = new QuestionUpdateStepModel();
stepModel.setId(Long.valueOf(event.getArgs().get("question_id").toString()));
stepModel.setCommentStep(1);
DataUpdateQueueModel<QuestionUpdateStepModel> queueModel = new DataUpdateQueueModel(model.getTargetUserId(), EntityType.QUESTION,date,stepModel);
dataUpdateManageService.put(queueModel,(sModel,nModel) -> {
dataUpdateManageService.cumulative(sModel,nModel);
sModel.setAnswerStep(sModel.getAnswerStep() + nModel.getAnswerStep());
});
indexManagerService.put(new IndexQueueModel(model.getType(),model.getTargetId()));
break;
}
}
}
| false | 1,196 | 5 | 1,363 | 5 | 1,414 | 3 | 1,363 | 5 | 1,682 | 6 | false | false | false | false | false | true |
43653_6 | package com.liu;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyInfo extends Activity implements OnClickListener{
StringBuilder strLog;
StringBuilder phoneInfo;
public Button getinfo;
public Button basicinfo;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.myinfo);
getinfo=(Button)findViewById(R.id.getinfo);
basicinfo=(Button)findViewById(R.id.basicinfo);
getinfo.setOnClickListener(this);
basicinfo.setOnClickListener(this);
getbasiclist();
getSensorList();
}
//获取手机基本信息
private void getbasiclist() {
phoneInfo = new StringBuilder();
phoneInfo.append("Product: " + android.os.Build.PRODUCT + System.getProperty("line.separator"));
phoneInfo.append( "CPU_ABI: " + android.os.Build.CPU_ABI + System.getProperty("line.separator"));
phoneInfo.append( "TAGS: " + android.os.Build.TAGS + System.getProperty("line.separator"));
phoneInfo.append( "VERSION_CODES.BASE: " + android.os.Build.VERSION_CODES.BASE + System.getProperty("line.separator"));
phoneInfo.append( "MODEL: " + android.os.Build.MODEL + System.getProperty("line.separator"));
phoneInfo.append( "SDK: " + android.os.Build.VERSION.SDK + System.getProperty("line.separator"));
phoneInfo.append( "VERSION.RELEASE: " + android.os.Build.VERSION.RELEASE + System.getProperty("line.separator"));
phoneInfo.append( "DEVICE: " + android.os.Build.DEVICE + System.getProperty("line.separator"));
phoneInfo.append( "DISPLAY: " + android.os.Build.DISPLAY + System.getProperty("line.separator"));
phoneInfo.append( "BRAND: " + android.os.Build.BRAND + System.getProperty("line.separator"));
phoneInfo.append( "BOARD: " + android.os.Build.BOARD + System.getProperty("line.separator"));
phoneInfo.append( "FINGERPRINT: " + android.os.Build.FINGERPRINT + System.getProperty("line.separator"));
phoneInfo.append( "ID: " + android.os.Build.ID + System.getProperty("line.separator"));
phoneInfo.append( "MANUFACTURER: " + android.os.Build.MANUFACTURER + System.getProperty("line.separator"));
phoneInfo.append( "USER: " + android.os.Build.USER + System.getProperty("line.separator"));
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phoneInfo.append("DeviceId(IMEI) = " + tm.getDeviceId() + System.getProperty("line.separator"));
phoneInfo.append("DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + System.getProperty("line.separator"));
phoneInfo.append("Line1Number = " + tm.getLine1Number() + System.getProperty("line.separator"));
phoneInfo.append("NetworkCountryIso = " + tm.getNetworkCountryIso() + System.getProperty("line.separator"));
phoneInfo.append("NetworkOperator = " + tm.getNetworkOperator() + System.getProperty("line.separator"));
phoneInfo.append("NetworkOperatorName = " + tm.getNetworkOperatorName() + System.getProperty("line.separator"));
phoneInfo.append("NetworkType = " + tm.getNetworkType() + System.getProperty("line.separator"));
phoneInfo.append("PhoneType = " + tm.getPhoneType() + System.getProperty("line.separator"));
phoneInfo.append("SimCountryIso = " + tm.getSimCountryIso() + System.getProperty("line.separator"));
phoneInfo.append("SimOperator = " + tm.getSimOperator() + System.getProperty("line.separator"));
phoneInfo.append("SimOperatorName = " + tm.getSimOperatorName() + System.getProperty("line.separator"));
phoneInfo.append("SimSerialNumber = " + tm.getSimSerialNumber() + System.getProperty("line.separator"));
phoneInfo.append("SimState = " + tm.getSimState() + System.getProperty("line.separator"));
phoneInfo.append("SubscriberId(IMSI) = " + tm.getSubscriberId() + System.getProperty("line.separator"));
phoneInfo.append("VoiceMailNumber = " + tm.getVoiceMailNumber() + System.getProperty("line.separator"));
}
private void getSensorList() {
// 获取传感器管理器
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
// 获取全部传感器列表
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
// 打印每个传感器信息
strLog = new StringBuilder();
int iIndex = 1;
for (Sensor item : sensors) {
strLog.append(iIndex + ".");
strLog.append(" Sensor Type - " + item.getType() + "\r\n");
strLog.append(" Sensor Name - " + item.getName() + "\r\n");
strLog.append(" Sensor Version - " + item.getVersion() + "\r\n");
strLog.append(" Sensor Vendor - " + item.getVendor() + "\r\n");
strLog.append(" Maximum Range - " + item.getMaximumRange() + "\r\n");
strLog.append(" Minimum Delay - " + item.getMinDelay() + "\r\n");
strLog.append(" Power - " + item.getPower() + "\r\n");
strLog.append(" Resolution - " + item.getResolution() + "\r\n");
strLog.append("\r\n");
iIndex++;
}
//System.out.println(strLog.toString());
}
//弹出对话框1
public void dialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MyInfo.this);
builder.setMessage(strLog.toString());
builder.setTitle("所有传感器信息");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
//弹出对话框2
public void dialog2() {
AlertDialog.Builder builder2 = new AlertDialog.Builder(MyInfo.this);
builder2.setMessage(phoneInfo.toString());
builder2.setTitle("手机基本信息");
builder2.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder2.create().show();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.getinfo:
dialog();
break;
case R.id.basicinfo:
dialog2();
break;
default:
break;
}
}
}
| bigbigbigbigbig/MyCarRecorder | Liu/src/com/liu/MyInfo.java | 1,850 | //弹出对话框2 | line_comment | zh-cn | package com.liu;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MyInfo extends Activity implements OnClickListener{
StringBuilder strLog;
StringBuilder phoneInfo;
public Button getinfo;
public Button basicinfo;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.myinfo);
getinfo=(Button)findViewById(R.id.getinfo);
basicinfo=(Button)findViewById(R.id.basicinfo);
getinfo.setOnClickListener(this);
basicinfo.setOnClickListener(this);
getbasiclist();
getSensorList();
}
//获取手机基本信息
private void getbasiclist() {
phoneInfo = new StringBuilder();
phoneInfo.append("Product: " + android.os.Build.PRODUCT + System.getProperty("line.separator"));
phoneInfo.append( "CPU_ABI: " + android.os.Build.CPU_ABI + System.getProperty("line.separator"));
phoneInfo.append( "TAGS: " + android.os.Build.TAGS + System.getProperty("line.separator"));
phoneInfo.append( "VERSION_CODES.BASE: " + android.os.Build.VERSION_CODES.BASE + System.getProperty("line.separator"));
phoneInfo.append( "MODEL: " + android.os.Build.MODEL + System.getProperty("line.separator"));
phoneInfo.append( "SDK: " + android.os.Build.VERSION.SDK + System.getProperty("line.separator"));
phoneInfo.append( "VERSION.RELEASE: " + android.os.Build.VERSION.RELEASE + System.getProperty("line.separator"));
phoneInfo.append( "DEVICE: " + android.os.Build.DEVICE + System.getProperty("line.separator"));
phoneInfo.append( "DISPLAY: " + android.os.Build.DISPLAY + System.getProperty("line.separator"));
phoneInfo.append( "BRAND: " + android.os.Build.BRAND + System.getProperty("line.separator"));
phoneInfo.append( "BOARD: " + android.os.Build.BOARD + System.getProperty("line.separator"));
phoneInfo.append( "FINGERPRINT: " + android.os.Build.FINGERPRINT + System.getProperty("line.separator"));
phoneInfo.append( "ID: " + android.os.Build.ID + System.getProperty("line.separator"));
phoneInfo.append( "MANUFACTURER: " + android.os.Build.MANUFACTURER + System.getProperty("line.separator"));
phoneInfo.append( "USER: " + android.os.Build.USER + System.getProperty("line.separator"));
TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phoneInfo.append("DeviceId(IMEI) = " + tm.getDeviceId() + System.getProperty("line.separator"));
phoneInfo.append("DeviceSoftwareVersion = " + tm.getDeviceSoftwareVersion() + System.getProperty("line.separator"));
phoneInfo.append("Line1Number = " + tm.getLine1Number() + System.getProperty("line.separator"));
phoneInfo.append("NetworkCountryIso = " + tm.getNetworkCountryIso() + System.getProperty("line.separator"));
phoneInfo.append("NetworkOperator = " + tm.getNetworkOperator() + System.getProperty("line.separator"));
phoneInfo.append("NetworkOperatorName = " + tm.getNetworkOperatorName() + System.getProperty("line.separator"));
phoneInfo.append("NetworkType = " + tm.getNetworkType() + System.getProperty("line.separator"));
phoneInfo.append("PhoneType = " + tm.getPhoneType() + System.getProperty("line.separator"));
phoneInfo.append("SimCountryIso = " + tm.getSimCountryIso() + System.getProperty("line.separator"));
phoneInfo.append("SimOperator = " + tm.getSimOperator() + System.getProperty("line.separator"));
phoneInfo.append("SimOperatorName = " + tm.getSimOperatorName() + System.getProperty("line.separator"));
phoneInfo.append("SimSerialNumber = " + tm.getSimSerialNumber() + System.getProperty("line.separator"));
phoneInfo.append("SimState = " + tm.getSimState() + System.getProperty("line.separator"));
phoneInfo.append("SubscriberId(IMSI) = " + tm.getSubscriberId() + System.getProperty("line.separator"));
phoneInfo.append("VoiceMailNumber = " + tm.getVoiceMailNumber() + System.getProperty("line.separator"));
}
private void getSensorList() {
// 获取传感器管理器
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
// 获取全部传感器列表
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
// 打印每个传感器信息
strLog = new StringBuilder();
int iIndex = 1;
for (Sensor item : sensors) {
strLog.append(iIndex + ".");
strLog.append(" Sensor Type - " + item.getType() + "\r\n");
strLog.append(" Sensor Name - " + item.getName() + "\r\n");
strLog.append(" Sensor Version - " + item.getVersion() + "\r\n");
strLog.append(" Sensor Vendor - " + item.getVendor() + "\r\n");
strLog.append(" Maximum Range - " + item.getMaximumRange() + "\r\n");
strLog.append(" Minimum Delay - " + item.getMinDelay() + "\r\n");
strLog.append(" Power - " + item.getPower() + "\r\n");
strLog.append(" Resolution - " + item.getResolution() + "\r\n");
strLog.append("\r\n");
iIndex++;
}
//System.out.println(strLog.toString());
}
//弹出对话框1
public void dialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(MyInfo.this);
builder.setMessage(strLog.toString());
builder.setTitle("所有传感器信息");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
//弹出 <SUF>
public void dialog2() {
AlertDialog.Builder builder2 = new AlertDialog.Builder(MyInfo.this);
builder2.setMessage(phoneInfo.toString());
builder2.setTitle("手机基本信息");
builder2.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder2.create().show();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.getinfo:
dialog();
break;
case R.id.basicinfo:
dialog2();
break;
default:
break;
}
}
}
| false | 1,518 | 6 | 1,850 | 7 | 1,910 | 4 | 1,850 | 7 | 2,218 | 11 | false | false | false | false | false | true |
15818_21 | package chapter4_3_Minimum_Spanning_Tree;
import algs4.StdIn;
import algs4.StdOut;
public class UF {
private int[] id; // 分量id(以触点作为索引)
private int count; // 分量数量
public UF(int N) {
// 初始化分量 id 数组
count = N;
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public int count() {
return count;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
/* quick-find 算法 */
// public int find(int p) {
// return id[p];
// }
//
// public void union(int p, int q) {
// // 将 p 和 q 归并到同样的分量中
// int pID = find(p);
// int qID = find(q);
//
// // 如果 p 和 q 已经在相同的分量之中则不需要采取任何行动
// if(pID == qID)
// return;
//
// // 将 p 的分量重命名为 q 的名称
// for(int i = 0; i < id.length; i++)
// if(id[i] == pID)
// id[i] = qID;
// count--;
// }
/* quick-union 算法 */
private int find(int p) {
// 找出分量的名称
while(p != id[p])
p = id[p];
return p;
}
public void union(int p, int q) {
// 将 p 和 q 的根节点统一
int pRoot = find(p);
int qRoot = find(q);
if(pRoot == qRoot)
return;
id[pRoot] = qRoot;
count--;
}
public static void main(String[] args) {
// 解决由StdIn得到的动态连通性问题
int N = StdIn.readInt(); // 读取触点数量
UF uf = new UF(N); // 初始化 N 个分量
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt(); // 读取整数对
if (uf.connected(p, q)) // 如果已经连通则忽略
continue;
uf.union(p, q); // 归并分量
StdOut.println(p + " " + q); // 打印连接
}
StdOut.println(uf.count + "components");
}
}
| bighuang624/Algorithms-notes | code/chapter4_3_Minimum_Spanning_Tree/UF.java | 643 | // 解决由StdIn得到的动态连通性问题 | line_comment | zh-cn | package chapter4_3_Minimum_Spanning_Tree;
import algs4.StdIn;
import algs4.StdOut;
public class UF {
private int[] id; // 分量id(以触点作为索引)
private int count; // 分量数量
public UF(int N) {
// 初始化分量 id 数组
count = N;
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i;
}
public int count() {
return count;
}
public boolean connected(int p, int q) {
return find(p) == find(q);
}
/* quick-find 算法 */
// public int find(int p) {
// return id[p];
// }
//
// public void union(int p, int q) {
// // 将 p 和 q 归并到同样的分量中
// int pID = find(p);
// int qID = find(q);
//
// // 如果 p 和 q 已经在相同的分量之中则不需要采取任何行动
// if(pID == qID)
// return;
//
// // 将 p 的分量重命名为 q 的名称
// for(int i = 0; i < id.length; i++)
// if(id[i] == pID)
// id[i] = qID;
// count--;
// }
/* quick-union 算法 */
private int find(int p) {
// 找出分量的名称
while(p != id[p])
p = id[p];
return p;
}
public void union(int p, int q) {
// 将 p 和 q 的根节点统一
int pRoot = find(p);
int qRoot = find(q);
if(pRoot == qRoot)
return;
id[pRoot] = qRoot;
count--;
}
public static void main(String[] args) {
// 解决 <SUF>
int N = StdIn.readInt(); // 读取触点数量
UF uf = new UF(N); // 初始化 N 个分量
while (!StdIn.isEmpty()) {
int p = StdIn.readInt();
int q = StdIn.readInt(); // 读取整数对
if (uf.connected(p, q)) // 如果已经连通则忽略
continue;
uf.union(p, q); // 归并分量
StdOut.println(p + " " + q); // 打印连接
}
StdOut.println(uf.count + "components");
}
}
| false | 592 | 13 | 643 | 13 | 676 | 11 | 643 | 13 | 793 | 20 | false | false | false | false | false | true |
5632_3 | package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.minidev.json.JSONObject;
@WebServlet(urlPatterns="/servlet/getInfo",loadOnStartup=1)
public class mainServlet extends HttpServlet {
private static final long serialVersionUID = -1643121334640537359L;
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("正在调用获取信息的接口");
//将过滤器中存入的payload数据取出来
HashMap<String, String> data=(HashMap<String, String>) request.getAttribute("data");
//payload中的数据可以用来做查询,比如我们在登陆成功时将用户ID存到了payload中,我们可以将它取出来,去数据库查询这个用户的所有信息;
//而不是用request.getParameter("uid")方法来获取前端传给我们的uid,因为前端的参数时可篡改的不完全可信的,而我们从payload中取出来的数据是从token中
//解密取出来的,在秘钥没有被破解的情况下,它是绝对可信的;这样可以避免别人用这个接口查询非自己用户ID的相关信息
JSONObject resp=new JSONObject();
resp.put("success", true);
resp.put("msg", "成功");
resp.put("data", data);
output(resp.toJSONString(), response);
}
public void output(String jsonStr,HttpServletResponse response) throws IOException{
response.setContentType("text/html;charset=UTF-8;");
PrintWriter out = response.getWriter();
out.println(jsonStr);
out.flush();
out.close();
}
}
| bigmeow/JWT | src/com/servlet/mainServlet.java | 483 | //解密取出来的,在秘钥没有被破解的情况下,它是绝对可信的;这样可以避免别人用这个接口查询非自己用户ID的相关信息 | line_comment | zh-cn | package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.minidev.json.JSONObject;
@WebServlet(urlPatterns="/servlet/getInfo",loadOnStartup=1)
public class mainServlet extends HttpServlet {
private static final long serialVersionUID = -1643121334640537359L;
@SuppressWarnings("unchecked")
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("正在调用获取信息的接口");
//将过滤器中存入的payload数据取出来
HashMap<String, String> data=(HashMap<String, String>) request.getAttribute("data");
//payload中的数据可以用来做查询,比如我们在登陆成功时将用户ID存到了payload中,我们可以将它取出来,去数据库查询这个用户的所有信息;
//而不是用request.getParameter("uid")方法来获取前端传给我们的uid,因为前端的参数时可篡改的不完全可信的,而我们从payload中取出来的数据是从token中
//解密 <SUF>
JSONObject resp=new JSONObject();
resp.put("success", true);
resp.put("msg", "成功");
resp.put("data", data);
output(resp.toJSONString(), response);
}
public void output(String jsonStr,HttpServletResponse response) throws IOException{
response.setContentType("text/html;charset=UTF-8;");
PrintWriter out = response.getWriter();
out.println(jsonStr);
out.flush();
out.close();
}
}
| false | 383 | 32 | 483 | 42 | 469 | 33 | 483 | 42 | 644 | 77 | false | false | false | false | false | true |
23912_5 | package com.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* 获取国内天气
* @author running@vip.163.com
* @since 数据接口抓取来源:中国气象频道(http://3g.tianqi.cn/)
* @version 1.0
*/
public final class WeatherUtil {
/**
* 城市编码映射表,默认放src目录下,编码表目录来源:http://3g.tianqi.cn/getAllCitys.do
*/
private static final String codeFileName = "cityCode.json";
/**
* 接口地址
*/
private static final String apiURL="http://3g.tianqi.cn/loginSk.do";
private static WeatherUtil me;
private JSONArray jsonArray = null;
private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
private WeatherUtil() {
initEnv();
}
/**
* 配置管理器构造工厂(单例)
* @return 天气工具类实例或者null
*/
public static WeatherUtil getInstance() {
try {
return me==null?new WeatherUtil():me;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
private void initEnv() {
//加载城市编码映射表
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream input = classLoader.getResourceAsStream(WeatherUtil.codeFileName);
if (null == input) {
throw new RuntimeException("未找到文件:"+WeatherUtil.codeFileName);
}
try {
//映射表解析为JSONArray对象
String configContent = IOUtils.toString(input);
JSONArray jsonArray = JSONArray.parseArray(this.filter(configContent));
this.jsonArray = jsonArray;
} catch (Exception e) {
this.jsonArray = null;
}
}
/**
*过滤输入字符串, 剔除多行注释以及替换掉反斜杠
*/
private String filter(String input) {
return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
}
/**
* 检查字符串是否为null或者空字符串
* @param str
* @return
*/
private boolean checkIsEmpty(String str){
return str==null||str.isEmpty();
}
/**
* 遍历获取城市code,
* @param province 省名(比如"湖南","上海")
* @param city 城市名(比如"长沙","上海")
* @param district 区县名(比如"浦东",可为null或空字符串)
* @return 城市code
*/
private String getCode(String province,String city,String district){
String code=null;
Iterator<Object> iter = this.jsonArray.iterator();
flag:
while (iter.hasNext()) {
JSONObject json = (JSONObject) iter.next();
//System.out.println("省"+json.get("ch"));
//匹配省
if(json.getString("ch").indexOf(province)>-1){
//向下匹配市
Iterator<Object> iter2=json.getJSONArray("beans").iterator();
while(iter2.hasNext()){
JSONObject json2 = (JSONObject) iter2.next();
//System.out.println("市"+json2.getString("ch"));
if(json2.getString("ch").indexOf(city)>-1){
//若区县参数为空或者未匹配到,则取城市的code
code=json2.getString("id");
System.out.println("城市["+city+"]的code是:"+code);
if(checkIsEmpty(district)){
break flag;
}
//向下匹配区县
Iterator<Object> iter3=json2.getJSONArray("beans").iterator();
while(iter3.hasNext()){
JSONObject json3 = (JSONObject) iter3.next();
//System.out.println("区县:"+json3.getString("ch"));
if(json3.getString("ch").indexOf(district)>-1){
code=json3.getString("id");
System.out.println("区县["+district+"]的code是:"+code);
break flag;
}
}
}
}
}
}
return code;
}
/**
*
* @param strUrl 请求地址
* @param params 请求参数
* @param method 请求方法
* @return 网络请求字符串
* @throws Exception
*/
private String net(String strUrl, Map<String, String> params, String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if (method == null || method.equals("GET")) {
strUrl += params == null ? "" : ((strUrl.indexOf("?") > -1 ? "&" : "?") + urlencode(params));
}
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
if (method == null || method.equals("GET")) {
conn.setRequestMethod("GET");
} else {
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params != null && method.equals("POST")) {
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(params));
} catch (Exception e) {
e.printStackTrace();
}
}
// 如果遇到重定向状态码,则调用重定向后的地址
if (conn.getResponseCode() == 302) {
return net(conn.getHeaderField("Location"), null, method);
}
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
// 将map型转为请求参数型
private String urlencode(Map<String, String> data) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=")
.append(URLEncoder.encode(i.getValue() + "", "UTF-8"))
.append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* 抓取指定地点的天气数据(省、市、区、县后缀可省略)
* @param province 省名(比如"湖南","上海")
* @param city 城市名(比如"长沙","上海")
* @param district 区县名(比如"浦东",可为null或空字符串)
* @return json字符串
*/
public String fetchWeatherInfo(String province,String city,String district){
String result = null;
if(checkIsEmpty(province)||checkIsEmpty(city)){
throw new RuntimeException("省名、城市名参数必填");
}
province=province.replaceAll("省", "");
city=city.replaceAll("市|区", "");
if(!checkIsEmpty(district)){
district=district.replaceAll("县", "");
}
String code=this.getCode(province, city, district);
Map<String, String> params = new HashMap<String, String>();// 请求参数
params.put("cityCode", code);
try {
result = net(apiURL, params, "GET");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 抓取指定地点的天气数据
* @param province 省名(比如"湖南","上海")
* @param city 城市名(比如"长沙","上海")
* @return json字符串
*/
public String fetchWeatherInfo(String province,String city){
return fetchWeatherInfo(province,city,null);
}
public static void main(String[] args) {
String province = "上海";
String city = "上海";
String district = "普陀";
WeatherUtil weather = WeatherUtil.getInstance();
String info=weather.fetchWeatherInfo(province, city, district);
System.out.println("天气数据:"+info);;
}
}
| bigmeow/Weather | src/com/util/WeatherUtil.java | 2,413 | //加载城市编码映射表 | line_comment | zh-cn | package com.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
/**
* 获取国内天气
* @author running@vip.163.com
* @since 数据接口抓取来源:中国气象频道(http://3g.tianqi.cn/)
* @version 1.0
*/
public final class WeatherUtil {
/**
* 城市编码映射表,默认放src目录下,编码表目录来源:http://3g.tianqi.cn/getAllCitys.do
*/
private static final String codeFileName = "cityCode.json";
/**
* 接口地址
*/
private static final String apiURL="http://3g.tianqi.cn/loginSk.do";
private static WeatherUtil me;
private JSONArray jsonArray = null;
private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
private WeatherUtil() {
initEnv();
}
/**
* 配置管理器构造工厂(单例)
* @return 天气工具类实例或者null
*/
public static WeatherUtil getInstance() {
try {
return me==null?new WeatherUtil():me;
} catch (Exception e) {
System.out.println(e);
return null;
}
}
private void initEnv() {
//加载 <SUF>
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream input = classLoader.getResourceAsStream(WeatherUtil.codeFileName);
if (null == input) {
throw new RuntimeException("未找到文件:"+WeatherUtil.codeFileName);
}
try {
//映射表解析为JSONArray对象
String configContent = IOUtils.toString(input);
JSONArray jsonArray = JSONArray.parseArray(this.filter(configContent));
this.jsonArray = jsonArray;
} catch (Exception e) {
this.jsonArray = null;
}
}
/**
*过滤输入字符串, 剔除多行注释以及替换掉反斜杠
*/
private String filter(String input) {
return input.replaceAll("/\\*[\\s\\S]*?\\*/", "");
}
/**
* 检查字符串是否为null或者空字符串
* @param str
* @return
*/
private boolean checkIsEmpty(String str){
return str==null||str.isEmpty();
}
/**
* 遍历获取城市code,
* @param province 省名(比如"湖南","上海")
* @param city 城市名(比如"长沙","上海")
* @param district 区县名(比如"浦东",可为null或空字符串)
* @return 城市code
*/
private String getCode(String province,String city,String district){
String code=null;
Iterator<Object> iter = this.jsonArray.iterator();
flag:
while (iter.hasNext()) {
JSONObject json = (JSONObject) iter.next();
//System.out.println("省"+json.get("ch"));
//匹配省
if(json.getString("ch").indexOf(province)>-1){
//向下匹配市
Iterator<Object> iter2=json.getJSONArray("beans").iterator();
while(iter2.hasNext()){
JSONObject json2 = (JSONObject) iter2.next();
//System.out.println("市"+json2.getString("ch"));
if(json2.getString("ch").indexOf(city)>-1){
//若区县参数为空或者未匹配到,则取城市的code
code=json2.getString("id");
System.out.println("城市["+city+"]的code是:"+code);
if(checkIsEmpty(district)){
break flag;
}
//向下匹配区县
Iterator<Object> iter3=json2.getJSONArray("beans").iterator();
while(iter3.hasNext()){
JSONObject json3 = (JSONObject) iter3.next();
//System.out.println("区县:"+json3.getString("ch"));
if(json3.getString("ch").indexOf(district)>-1){
code=json3.getString("id");
System.out.println("区县["+district+"]的code是:"+code);
break flag;
}
}
}
}
}
}
return code;
}
/**
*
* @param strUrl 请求地址
* @param params 请求参数
* @param method 请求方法
* @return 网络请求字符串
* @throws Exception
*/
private String net(String strUrl, Map<String, String> params, String method) throws Exception {
HttpURLConnection conn = null;
BufferedReader reader = null;
String rs = null;
try {
StringBuffer sb = new StringBuffer();
if (method == null || method.equals("GET")) {
strUrl += params == null ? "" : ((strUrl.indexOf("?") > -1 ? "&" : "?") + urlencode(params));
}
URL url = new URL(strUrl);
conn = (HttpURLConnection) url.openConnection();
if (method == null || method.equals("GET")) {
conn.setRequestMethod("GET");
} else {
conn.setRequestMethod("POST");
conn.setDoOutput(true);
}
conn.setRequestProperty("User-agent", userAgent);
conn.setUseCaches(false);
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(false);
conn.connect();
if (params != null && method.equals("POST")) {
try {
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.writeBytes(urlencode(params));
} catch (Exception e) {
e.printStackTrace();
}
}
// 如果遇到重定向状态码,则调用重定向后的地址
if (conn.getResponseCode() == 302) {
return net(conn.getHeaderField("Location"), null, method);
}
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sb.append(strRead);
}
rs = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (conn != null) {
conn.disconnect();
}
}
return rs;
}
// 将map型转为请求参数型
private String urlencode(Map<String, String> data) {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> i : data.entrySet()) {
try {
sb.append(i.getKey()).append("=")
.append(URLEncoder.encode(i.getValue() + "", "UTF-8"))
.append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return sb.toString();
}
/**
* 抓取指定地点的天气数据(省、市、区、县后缀可省略)
* @param province 省名(比如"湖南","上海")
* @param city 城市名(比如"长沙","上海")
* @param district 区县名(比如"浦东",可为null或空字符串)
* @return json字符串
*/
public String fetchWeatherInfo(String province,String city,String district){
String result = null;
if(checkIsEmpty(province)||checkIsEmpty(city)){
throw new RuntimeException("省名、城市名参数必填");
}
province=province.replaceAll("省", "");
city=city.replaceAll("市|区", "");
if(!checkIsEmpty(district)){
district=district.replaceAll("县", "");
}
String code=this.getCode(province, city, district);
Map<String, String> params = new HashMap<String, String>();// 请求参数
params.put("cityCode", code);
try {
result = net(apiURL, params, "GET");
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 抓取指定地点的天气数据
* @param province 省名(比如"湖南","上海")
* @param city 城市名(比如"长沙","上海")
* @return json字符串
*/
public String fetchWeatherInfo(String province,String city){
return fetchWeatherInfo(province,city,null);
}
public static void main(String[] args) {
String province = "上海";
String city = "上海";
String district = "普陀";
WeatherUtil weather = WeatherUtil.getInstance();
String info=weather.fetchWeatherInfo(province, city, district);
System.out.println("天气数据:"+info);;
}
}
| false | 2,026 | 7 | 2,410 | 7 | 2,385 | 6 | 2,413 | 7 | 3,119 | 14 | false | false | false | false | false | true |
51113_1 | package LinkedQuestion.JosephusKill;
import LinkedQuestion.Node.Node;
/**
* 环形单链表的约瑟夫问题
* <p>
* 据说著名的犹太历史学家Josephus有过以下故事:在罗马人占领桥塔帕特后,
* 39个犹太人与Josephus 及他的朋友躲到一个洞中,39个犹太人宁愿死也不要被敌人抓到,
* 于是决定了一个自杀方式,41个人排成一个圆圈,由第一个人开始报数,报数到3的人就自杀,
* 然后再有下一个人重新报1,报数到3的人再自杀。这样依次下去,直到剩下最后一个人时,
* 那个人可以自由选择自己的命运。这就是著名的约瑟夫问题。
* 现在请用单向环形链表描述该结构并呈现整个自杀过程。
* 输入:一个环形单向链表的头节点head 和报数的值m。
* 返回:最后生存下来的节点,且这个节点自己组成环形单向链表,其他节点都删掉。
*/
public class Solution {
public Node josephusKillOne(Node head, int m) {
if (head == null || head.next == head || m < 1) {
return head;
}
Node last = head;
while (last.next != head) {
last = last.next;
}
int count = 0;
while (head != last) {
if (++count == m) {
System.out.println(last.next.value);
last.next = head.next;
count = 0;
} else {
last = last.next;
}
head = last.next;
}
return head;
}
/**
* 进阶:
* 如果链表节点数为N,想在时间复杂度为O(N)时完成原问题的要求。
*/
public Node josephusKillTwo(Node head, int m) {
if (head == null || head.next == head || m < 1) {
return head;
}
Node cur = head.next;
int tmp = 1;
while (cur != head) {
tmp++;
cur = cur.next;
}
tmp = getLive(tmp, m);
while (--tmp != 0) {
head = head.next;
}
head.next = head;
return head;
}
private int getLive(int i, int m) {
if (i == 1) {
return 1;
}
return (getLive(i - 1, m) + m - 1) % i + 1;
}
}
| bigpeng93/CodingInterviewGuide | src/LinkedQuestion/JosephusKill/Solution.java | 667 | /**
* 进阶:
* 如果链表节点数为N,想在时间复杂度为O(N)时完成原问题的要求。
*/ | block_comment | zh-cn | package LinkedQuestion.JosephusKill;
import LinkedQuestion.Node.Node;
/**
* 环形单链表的约瑟夫问题
* <p>
* 据说著名的犹太历史学家Josephus有过以下故事:在罗马人占领桥塔帕特后,
* 39个犹太人与Josephus 及他的朋友躲到一个洞中,39个犹太人宁愿死也不要被敌人抓到,
* 于是决定了一个自杀方式,41个人排成一个圆圈,由第一个人开始报数,报数到3的人就自杀,
* 然后再有下一个人重新报1,报数到3的人再自杀。这样依次下去,直到剩下最后一个人时,
* 那个人可以自由选择自己的命运。这就是著名的约瑟夫问题。
* 现在请用单向环形链表描述该结构并呈现整个自杀过程。
* 输入:一个环形单向链表的头节点head 和报数的值m。
* 返回:最后生存下来的节点,且这个节点自己组成环形单向链表,其他节点都删掉。
*/
public class Solution {
public Node josephusKillOne(Node head, int m) {
if (head == null || head.next == head || m < 1) {
return head;
}
Node last = head;
while (last.next != head) {
last = last.next;
}
int count = 0;
while (head != last) {
if (++count == m) {
System.out.println(last.next.value);
last.next = head.next;
count = 0;
} else {
last = last.next;
}
head = last.next;
}
return head;
}
/**
* 进阶: <SUF>*/
public Node josephusKillTwo(Node head, int m) {
if (head == null || head.next == head || m < 1) {
return head;
}
Node cur = head.next;
int tmp = 1;
while (cur != head) {
tmp++;
cur = cur.next;
}
tmp = getLive(tmp, m);
while (--tmp != 0) {
head = head.next;
}
head.next = head;
return head;
}
private int getLive(int i, int m) {
if (i == 1) {
return 1;
}
return (getLive(i - 1, m) + m - 1) % i + 1;
}
}
| false | 581 | 34 | 667 | 35 | 651 | 36 | 667 | 35 | 876 | 53 | false | false | false | false | false | true |
63548_0 | package leetcode;
import java.util.Arrays;
/**
* 救生艇
* https://leetcode-cn.com/problems/boats-to-save-people/description/
* @author bwt
*
* 思路:
* 贪心算法,因为最多能够承受两个人,所以比较简单;排序之后,使用双指针,假如 最重的人 与 最轻的人
*相加后大于 limit,那么最重的人只能单独一次运载(后面的指针前移,运载数++),否则的话就可加上当前
*最轻的人,然后两个指针都向中间靠拢。
*/
public class NumRescueBoats {
public static int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int res = 0;
int p = 0, q = people.length - 1;
while(p <= q) {
if (people[q] + people[p] <= limit)
p++;
res++;
q--;
}
return res;
}
public static void main(String[] args) {
int[] people = new int[] {
1,2
};
System.err.println(numRescueBoats(people, 3));
}
}
| bigwolftime/leetcode | src/leetcode/NumRescueBoats.java | 317 | /**
* 救生艇
* https://leetcode-cn.com/problems/boats-to-save-people/description/
* @author bwt
*
* 思路:
* 贪心算法,因为最多能够承受两个人,所以比较简单;排序之后,使用双指针,假如 最重的人 与 最轻的人
*相加后大于 limit,那么最重的人只能单独一次运载(后面的指针前移,运载数++),否则的话就可加上当前
*最轻的人,然后两个指针都向中间靠拢。
*/ | block_comment | zh-cn | package leetcode;
import java.util.Arrays;
/**
* 救生艇 <SUF>*/
public class NumRescueBoats {
public static int numRescueBoats(int[] people, int limit) {
Arrays.sort(people);
int res = 0;
int p = 0, q = people.length - 1;
while(p <= q) {
if (people[q] + people[p] <= limit)
p++;
res++;
q--;
}
return res;
}
public static void main(String[] args) {
int[] people = new int[] {
1,2
};
System.err.println(numRescueBoats(people, 3));
}
}
| false | 265 | 118 | 317 | 142 | 307 | 125 | 317 | 142 | 415 | 205 | false | false | false | false | false | true |
6978_1 | package com.example.demo;
import com.example.demo.entity.ArcAddParam;
import com.example.demo.util.ArchiveUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
public class Demo {
private final static String clientId = "这里填入您的 client_id";
private final static String secret = "这里填入对应的 client_secret";
// 视频文件名
private final static String fileName = "video_test.MP4";
// 视频文件路径
private final static String filePath = "/Users/bilibili/files/video_test.MP4";
// 稿件封面图片路径
private final static String coverPath = "/Users/bilibili/files/cover_test.png";
public static void main(String[] args) throws Exception {
ArchiveUtil arcUtil = new ArchiveUtil(clientId, secret);
// 通过临时 code 获取 access_token,详见账号授权文档:
// https://openhome.bilibili.com/doc/4/eaf0e2b5-bde9-b9a0-9be1-019bb455701c
String accessToken = arcUtil.getAccessToken("这里填入您获取的code");
System.out.println("access_token: " + accessToken);
// 文件上传预处理
// https://openhome.bilibili.com/doc/4/0c532c6a-e6fb-0aff-8021-905ae2409095
String uploadToken = arcUtil.arcInit(accessToken, fileName);
System.out.println("arcInit success: " + uploadToken);
// 文件分片上传
// https://openhome.bilibili.com/doc/4/733a520a-c50f-7bb4-17cb-35338ba20500
File file = new File(filePath);
InputStream is = new FileInputStream(file);
int partSize = 8 * 1024 * 1024;
byte[] part = new byte[partSize];
int len;
int partNum = 1;
// 可适当使用并发上传,线程数不宜过大
while ((len = is.read(part)) != -1) {
if (len < partSize) {
part = Arrays.copyOf(part, len);
}
arcUtil.arcUp(uploadToken, partNum, part);
System.out.println("arcUpload success: " + partNum);
partNum++;
}
// 文件分片合片
// https://openhome.bilibili.com/doc/4/0828e499-38d8-9e58-2a70-a7eaebf9dd64
arcUtil.arcComplete(uploadToken);
System.out.println("arcComplete success");
// 上传封面
// https://openhome.bilibili.com/doc/4/8243399e-50e3-4058-7f01-1ebe4c632cf8
String coverUrl = arcUtil.uploadCover(accessToken, new File(coverPath));
System.out.println("uploadCover success: " + coverUrl);
// 构造稿件提交参数,提交稿件
// https://openhome.bilibili.com/doc/4/f7fc57dd-55a1-5cb1-cba4-61fb2994bf0f
ArcAddParam arcAddParam = new ArcAddParam();
arcAddParam.setTitle("测试投稿-" + System.currentTimeMillis());
arcAddParam.setCover(coverUrl);
// 调用分区查询接口获取,选择合适的分区
// https://openhome.bilibili.com/doc/4/4f13299b-5316-142f-df6a-87313eaf85a9
arcAddParam.setTid(75);
arcAddParam.setNoReprint(1);
arcAddParam.setDesc("测试投稿-描述");
arcAddParam.setTag("生活,搞笑,游戏");
arcAddParam.setCopyright(1);
arcAddParam.setSource("");
String resourceId = arcUtil.arcSubmit(accessToken, uploadToken, arcAddParam);
System.out.println("arcSubmit success: " + resourceId);
}
}
| bilibili-openplatform/demo | java/Demo.java | 1,056 | // 视频文件路径 | line_comment | zh-cn | package com.example.demo;
import com.example.demo.entity.ArcAddParam;
import com.example.demo.util.ArchiveUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Arrays;
public class Demo {
private final static String clientId = "这里填入您的 client_id";
private final static String secret = "这里填入对应的 client_secret";
// 视频文件名
private final static String fileName = "video_test.MP4";
// 视频 <SUF>
private final static String filePath = "/Users/bilibili/files/video_test.MP4";
// 稿件封面图片路径
private final static String coverPath = "/Users/bilibili/files/cover_test.png";
public static void main(String[] args) throws Exception {
ArchiveUtil arcUtil = new ArchiveUtil(clientId, secret);
// 通过临时 code 获取 access_token,详见账号授权文档:
// https://openhome.bilibili.com/doc/4/eaf0e2b5-bde9-b9a0-9be1-019bb455701c
String accessToken = arcUtil.getAccessToken("这里填入您获取的code");
System.out.println("access_token: " + accessToken);
// 文件上传预处理
// https://openhome.bilibili.com/doc/4/0c532c6a-e6fb-0aff-8021-905ae2409095
String uploadToken = arcUtil.arcInit(accessToken, fileName);
System.out.println("arcInit success: " + uploadToken);
// 文件分片上传
// https://openhome.bilibili.com/doc/4/733a520a-c50f-7bb4-17cb-35338ba20500
File file = new File(filePath);
InputStream is = new FileInputStream(file);
int partSize = 8 * 1024 * 1024;
byte[] part = new byte[partSize];
int len;
int partNum = 1;
// 可适当使用并发上传,线程数不宜过大
while ((len = is.read(part)) != -1) {
if (len < partSize) {
part = Arrays.copyOf(part, len);
}
arcUtil.arcUp(uploadToken, partNum, part);
System.out.println("arcUpload success: " + partNum);
partNum++;
}
// 文件分片合片
// https://openhome.bilibili.com/doc/4/0828e499-38d8-9e58-2a70-a7eaebf9dd64
arcUtil.arcComplete(uploadToken);
System.out.println("arcComplete success");
// 上传封面
// https://openhome.bilibili.com/doc/4/8243399e-50e3-4058-7f01-1ebe4c632cf8
String coverUrl = arcUtil.uploadCover(accessToken, new File(coverPath));
System.out.println("uploadCover success: " + coverUrl);
// 构造稿件提交参数,提交稿件
// https://openhome.bilibili.com/doc/4/f7fc57dd-55a1-5cb1-cba4-61fb2994bf0f
ArcAddParam arcAddParam = new ArcAddParam();
arcAddParam.setTitle("测试投稿-" + System.currentTimeMillis());
arcAddParam.setCover(coverUrl);
// 调用分区查询接口获取,选择合适的分区
// https://openhome.bilibili.com/doc/4/4f13299b-5316-142f-df6a-87313eaf85a9
arcAddParam.setTid(75);
arcAddParam.setNoReprint(1);
arcAddParam.setDesc("测试投稿-描述");
arcAddParam.setTag("生活,搞笑,游戏");
arcAddParam.setCopyright(1);
arcAddParam.setSource("");
String resourceId = arcUtil.arcSubmit(accessToken, uploadToken, arcAddParam);
System.out.println("arcSubmit success: " + resourceId);
}
}
| false | 956 | 6 | 1,056 | 5 | 1,078 | 4 | 1,056 | 5 | 1,276 | 12 | false | false | false | false | false | true |
20907_4 | package com.code.LinkedList;
/**
* @author 小六六
* @version 1.0
* @date 2020/4/27 20:21
*
*
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3. */
public class SwapPairs {
//这边定义的是链表的Node
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
//非递归的写法
public static ListNode swapPairs1(ListNode head){
//定一个要返回的链表结构
ListNode pre = new ListNode(0);
pre.next=head;
//定义一个要去移动的链表
ListNode temp=pre;
//while循环
while (temp.next!=null&&temp.next.next!=null){
//想想循环退出的条件为啥是这个。因为就是只要不是连续成一组节点,就可以直接不用把临时节点,继续往下移动了
//定义每组的第一和第二
ListNode start = temp.next;
ListNode end = temp.next.next;
temp.next = end;
start.next = end.next;
end.next = start;
temp = start;
}
return pre.next;
}
//写一个打印的方法看看
public static String print(ListNode listNode){
StringBuffer stringBuffer=new StringBuffer();
while (listNode!=null){
stringBuffer.append(listNode.val);
listNode=listNode.next;
}
return stringBuffer.toString();
}
public static void main(String[] args) {
ListNode listNode=new ListNode(1);
listNode.next=new ListNode(2);
listNode.next.next=new ListNode(3);
System.out.println(print(swapPairs1(listNode)));
}
}
| bin392328206/six-finger | src/力扣/code/src/main/java/com.code/LinkedList/SwapPairs.java | 554 | //定义一个要去移动的链表 | line_comment | zh-cn | package com.code.LinkedList;
/**
* @author 小六六
* @version 1.0
* @date 2020/4/27 20:21
*
*
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3. */
public class SwapPairs {
//这边定义的是链表的Node
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
//非递归的写法
public static ListNode swapPairs1(ListNode head){
//定一个要返回的链表结构
ListNode pre = new ListNode(0);
pre.next=head;
//定义 <SUF>
ListNode temp=pre;
//while循环
while (temp.next!=null&&temp.next.next!=null){
//想想循环退出的条件为啥是这个。因为就是只要不是连续成一组节点,就可以直接不用把临时节点,继续往下移动了
//定义每组的第一和第二
ListNode start = temp.next;
ListNode end = temp.next.next;
temp.next = end;
start.next = end.next;
end.next = start;
temp = start;
}
return pre.next;
}
//写一个打印的方法看看
public static String print(ListNode listNode){
StringBuffer stringBuffer=new StringBuffer();
while (listNode!=null){
stringBuffer.append(listNode.val);
listNode=listNode.next;
}
return stringBuffer.toString();
}
public static void main(String[] args) {
ListNode listNode=new ListNode(1);
listNode.next=new ListNode(2);
listNode.next.next=new ListNode(3);
System.out.println(print(swapPairs1(listNode)));
}
}
| false | 485 | 8 | 554 | 8 | 579 | 7 | 554 | 8 | 741 | 14 | false | false | false | false | false | true |
40497_0 | package cn.binarywang.tools.generator.bank;
import java.util.Random;
import org.apache.commons.lang3.StringUtils;
import cn.binarywang.tools.generator.base.GenericGenerator;
import cn.binarywang.tools.generator.util.LuhnUtils;
/**
* <pre>
* 生成随机银行卡号:
*
* 参考:效验是否为银行卡,用于验证:
* 现行 16 位银联卡现行卡号开头 6 位是 622126~622925 之间的,7 到 15 位是银行自定义的,
* 可能是发卡分行,发卡网点,发卡序号,第 16 位是校验码。
* 16 位卡号校验位采用 Luhm 校验方法计算:
* 1,将未带校验位的 15 位卡号从右依次编号 1 到 15,位于奇数位号上的数字乘以 2
* 2,将奇位乘积的个十位全部相加,再加上所有偶数位上的数字
* 3,将加法和加上校验位能被 10 整除。
* </pre>
*/
public class BankCardNumberGenerator extends GenericGenerator {
private static GenericGenerator instance = new BankCardNumberGenerator();
private BankCardNumberGenerator() {
}
public static GenericGenerator getInstance() {
return instance;
}
@Override
public String generate() {
Random random = getRandomInstance();
// ContiguousSet<Integer> sets = ContiguousSet
// .create(Range.closed(622126, 622925), DiscreteDomain.integers());
// ImmutableList<Integer> list = sets.asList();
Integer prev = 622126 + random.nextInt(925 + 1 - 126);
return generateByPrefix(prev);
}
/**
* <pre>
* 根据给定前六位生成卡号
* </pre>
*/
public static String generateByPrefix(Integer prefix) {
Random random = new Random(System.currentTimeMillis());
String bardNo = prefix
+ StringUtils.leftPad(random.nextInt(999999999) + "", 9, "0");
char[] chs = bardNo.trim().toCharArray();
int luhnSum = LuhnUtils.getLuhnSum(chs);
char checkCode = luhnSum % 10 == 0 ? '0' : (char) (10 - luhnSum % 10 + '0');
return bardNo + checkCode;
}
/**
* 根据银行名称 及银行卡类型生成对应卡号
*
* @param bankName 银行名称
* @param cardType 银行卡类型
* @return 银行卡号
*/
public static String generate(BankNameEnum bankName, BankCardTypeEnum cardType) {
Integer[] candidatePrefixes = null;
if (cardType == null) {
candidatePrefixes = bankName.getAllCardPrefixes();
} else {
switch (cardType) {
case DEBIT:
candidatePrefixes = bankName.getDebitCardPrefixes();
break;
case CREDIT:
candidatePrefixes = bankName.getCreditCardPrefixes();
break;
default:
}
}
if (candidatePrefixes == null || candidatePrefixes.length == 0) {
throw new RuntimeException("没有该银行的相关卡号信息");
}
Integer prefix = candidatePrefixes[new Random().nextInt(candidatePrefixes.length)];
return generateByPrefix(prefix);
}
}
| binarywang/java-testdata-generator | src/main/java/cn/binarywang/tools/generator/bank/BankCardNumberGenerator.java | 861 | /**
* <pre>
* 生成随机银行卡号:
*
* 参考:效验是否为银行卡,用于验证:
* 现行 16 位银联卡现行卡号开头 6 位是 622126~622925 之间的,7 到 15 位是银行自定义的,
* 可能是发卡分行,发卡网点,发卡序号,第 16 位是校验码。
* 16 位卡号校验位采用 Luhm 校验方法计算:
* 1,将未带校验位的 15 位卡号从右依次编号 1 到 15,位于奇数位号上的数字乘以 2
* 2,将奇位乘积的个十位全部相加,再加上所有偶数位上的数字
* 3,将加法和加上校验位能被 10 整除。
* </pre>
*/ | block_comment | zh-cn | package cn.binarywang.tools.generator.bank;
import java.util.Random;
import org.apache.commons.lang3.StringUtils;
import cn.binarywang.tools.generator.base.GenericGenerator;
import cn.binarywang.tools.generator.util.LuhnUtils;
/**
* <pr <SUF>*/
public class BankCardNumberGenerator extends GenericGenerator {
private static GenericGenerator instance = new BankCardNumberGenerator();
private BankCardNumberGenerator() {
}
public static GenericGenerator getInstance() {
return instance;
}
@Override
public String generate() {
Random random = getRandomInstance();
// ContiguousSet<Integer> sets = ContiguousSet
// .create(Range.closed(622126, 622925), DiscreteDomain.integers());
// ImmutableList<Integer> list = sets.asList();
Integer prev = 622126 + random.nextInt(925 + 1 - 126);
return generateByPrefix(prev);
}
/**
* <pre>
* 根据给定前六位生成卡号
* </pre>
*/
public static String generateByPrefix(Integer prefix) {
Random random = new Random(System.currentTimeMillis());
String bardNo = prefix
+ StringUtils.leftPad(random.nextInt(999999999) + "", 9, "0");
char[] chs = bardNo.trim().toCharArray();
int luhnSum = LuhnUtils.getLuhnSum(chs);
char checkCode = luhnSum % 10 == 0 ? '0' : (char) (10 - luhnSum % 10 + '0');
return bardNo + checkCode;
}
/**
* 根据银行名称 及银行卡类型生成对应卡号
*
* @param bankName 银行名称
* @param cardType 银行卡类型
* @return 银行卡号
*/
public static String generate(BankNameEnum bankName, BankCardTypeEnum cardType) {
Integer[] candidatePrefixes = null;
if (cardType == null) {
candidatePrefixes = bankName.getAllCardPrefixes();
} else {
switch (cardType) {
case DEBIT:
candidatePrefixes = bankName.getDebitCardPrefixes();
break;
case CREDIT:
candidatePrefixes = bankName.getCreditCardPrefixes();
break;
default:
}
}
if (candidatePrefixes == null || candidatePrefixes.length == 0) {
throw new RuntimeException("没有该银行的相关卡号信息");
}
Integer prefix = candidatePrefixes[new Random().nextInt(candidatePrefixes.length)];
return generateByPrefix(prefix);
}
}
| false | 807 | 228 | 861 | 243 | 879 | 217 | 861 | 243 | 1,095 | 325 | false | false | false | false | false | true |
12259_7 | package com.github.binarywang.demo.wx.mp.config;
import com.github.binarywang.demo.wx.mp.handler.*;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.redis.JedisWxRedisOps;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import me.chanjar.weixin.mp.config.impl.WxMpRedisConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.List;
import java.util.stream.Collectors;
import static me.chanjar.weixin.common.api.WxConsts.EventType;
import static me.chanjar.weixin.common.api.WxConsts.EventType.SUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.EventType.UNSUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType.EVENT;
import static me.chanjar.weixin.mp.constant.WxMpEventConstants.CustomerService.*;
import static me.chanjar.weixin.mp.constant.WxMpEventConstants.POI_CHECK_NOTIFY;
/**
* wechat mp configuration
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpConfiguration {
private final LogHandler logHandler;
private final NullHandler nullHandler;
private final KfSessionHandler kfSessionHandler;
private final StoreCheckNotifyHandler storeCheckNotifyHandler;
private final LocationHandler locationHandler;
private final MenuHandler menuHandler;
private final MsgHandler msgHandler;
private final UnsubscribeHandler unsubscribeHandler;
private final SubscribeHandler subscribeHandler;
private final ScanHandler scanHandler;
private final WxMpProperties properties;
@Bean
public WxMpService wxMpService() {
// 代码里 getConfigs()处报错的同学,请注意仔细阅读项目说明,你的IDE需要引入lombok插件!!!!
final List<WxMpProperties.MpConfig> configs = this.properties.getConfigs();
if (configs == null) {
throw new RuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
}
WxMpService service = new WxMpServiceImpl();
service.setMultiConfigStorages(configs
.stream().map(a -> {
WxMpDefaultConfigImpl configStorage;
if (this.properties.isUseRedis()) {
final WxMpProperties.RedisConfig redisConfig = this.properties.getRedisConfig();
JedisPoolConfig poolConfig = new JedisPoolConfig();
JedisPool jedisPool = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
redisConfig.getTimeout(), redisConfig.getPassword());
configStorage = new WxMpRedisConfigImpl(new JedisWxRedisOps(jedisPool), a.getAppId());
} else {
configStorage = new WxMpDefaultConfigImpl();
}
configStorage.setAppId(a.getAppId());
configStorage.setSecret(a.getSecret());
configStorage.setToken(a.getToken());
configStorage.setAesKey(a.getAesKey());
return configStorage;
}).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o)));
return service;
}
@Bean
public WxMpMessageRouter messageRouter(WxMpService wxMpService) {
final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);
// 记录所有事件的日志 (异步执行)
newRouter.rule().handler(this.logHandler).next();
// 接收客服会话管理事件
newRouter.rule().async(false).msgType(EVENT).event(KF_CREATE_SESSION)
.handler(this.kfSessionHandler).end();
newRouter.rule().async(false).msgType(EVENT).event(KF_CLOSE_SESSION)
.handler(this.kfSessionHandler).end();
newRouter.rule().async(false).msgType(EVENT).event(KF_SWITCH_SESSION)
.handler(this.kfSessionHandler).end();
// 门店审核事件
newRouter.rule().async(false).msgType(EVENT).event(POI_CHECK_NOTIFY).handler(this.storeCheckNotifyHandler).end();
// 自定义菜单事件
newRouter.rule().async(false).msgType(EVENT).event(EventType.CLICK).handler(this.menuHandler).end();
// 点击菜单连接事件
newRouter.rule().async(false).msgType(EVENT).event(EventType.VIEW).handler(this.nullHandler).end();
// 关注事件
newRouter.rule().async(false).msgType(EVENT).event(SUBSCRIBE).handler(this.subscribeHandler).end();
// 取消关注事件
newRouter.rule().async(false).msgType(EVENT).event(UNSUBSCRIBE).handler(this.unsubscribeHandler).end();
// 上报地理位置事件
newRouter.rule().async(false).msgType(EVENT).event(EventType.LOCATION).handler(this.locationHandler).end();
// 接收地理位置消息
newRouter.rule().async(false).msgType(XmlMsgType.LOCATION).handler(this.locationHandler).end();
// 扫码事件
newRouter.rule().async(false).msgType(EVENT).event(EventType.SCAN).handler(this.scanHandler).end();
// 默认
newRouter.rule().async(false).handler(this.msgHandler).end();
return newRouter;
}
}
| binarywang/weixin-java-mp-demo | src/main/java/com/github/binarywang/demo/wx/mp/config/WxMpConfiguration.java | 1,442 | // 关注事件 | line_comment | zh-cn | package com.github.binarywang.demo.wx.mp.config;
import com.github.binarywang.demo.wx.mp.handler.*;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.redis.JedisWxRedisOps;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.config.impl.WxMpDefaultConfigImpl;
import me.chanjar.weixin.mp.config.impl.WxMpRedisConfigImpl;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.util.List;
import java.util.stream.Collectors;
import static me.chanjar.weixin.common.api.WxConsts.EventType;
import static me.chanjar.weixin.common.api.WxConsts.EventType.SUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.EventType.UNSUBSCRIBE;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;
import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType.EVENT;
import static me.chanjar.weixin.mp.constant.WxMpEventConstants.CustomerService.*;
import static me.chanjar.weixin.mp.constant.WxMpEventConstants.POI_CHECK_NOTIFY;
/**
* wechat mp configuration
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
*/
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMpProperties.class)
public class WxMpConfiguration {
private final LogHandler logHandler;
private final NullHandler nullHandler;
private final KfSessionHandler kfSessionHandler;
private final StoreCheckNotifyHandler storeCheckNotifyHandler;
private final LocationHandler locationHandler;
private final MenuHandler menuHandler;
private final MsgHandler msgHandler;
private final UnsubscribeHandler unsubscribeHandler;
private final SubscribeHandler subscribeHandler;
private final ScanHandler scanHandler;
private final WxMpProperties properties;
@Bean
public WxMpService wxMpService() {
// 代码里 getConfigs()处报错的同学,请注意仔细阅读项目说明,你的IDE需要引入lombok插件!!!!
final List<WxMpProperties.MpConfig> configs = this.properties.getConfigs();
if (configs == null) {
throw new RuntimeException("大哥,拜托先看下项目首页的说明(readme文件),添加下相关配置,注意别配错了!");
}
WxMpService service = new WxMpServiceImpl();
service.setMultiConfigStorages(configs
.stream().map(a -> {
WxMpDefaultConfigImpl configStorage;
if (this.properties.isUseRedis()) {
final WxMpProperties.RedisConfig redisConfig = this.properties.getRedisConfig();
JedisPoolConfig poolConfig = new JedisPoolConfig();
JedisPool jedisPool = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
redisConfig.getTimeout(), redisConfig.getPassword());
configStorage = new WxMpRedisConfigImpl(new JedisWxRedisOps(jedisPool), a.getAppId());
} else {
configStorage = new WxMpDefaultConfigImpl();
}
configStorage.setAppId(a.getAppId());
configStorage.setSecret(a.getSecret());
configStorage.setToken(a.getToken());
configStorage.setAesKey(a.getAesKey());
return configStorage;
}).collect(Collectors.toMap(WxMpDefaultConfigImpl::getAppId, a -> a, (o, n) -> o)));
return service;
}
@Bean
public WxMpMessageRouter messageRouter(WxMpService wxMpService) {
final WxMpMessageRouter newRouter = new WxMpMessageRouter(wxMpService);
// 记录所有事件的日志 (异步执行)
newRouter.rule().handler(this.logHandler).next();
// 接收客服会话管理事件
newRouter.rule().async(false).msgType(EVENT).event(KF_CREATE_SESSION)
.handler(this.kfSessionHandler).end();
newRouter.rule().async(false).msgType(EVENT).event(KF_CLOSE_SESSION)
.handler(this.kfSessionHandler).end();
newRouter.rule().async(false).msgType(EVENT).event(KF_SWITCH_SESSION)
.handler(this.kfSessionHandler).end();
// 门店审核事件
newRouter.rule().async(false).msgType(EVENT).event(POI_CHECK_NOTIFY).handler(this.storeCheckNotifyHandler).end();
// 自定义菜单事件
newRouter.rule().async(false).msgType(EVENT).event(EventType.CLICK).handler(this.menuHandler).end();
// 点击菜单连接事件
newRouter.rule().async(false).msgType(EVENT).event(EventType.VIEW).handler(this.nullHandler).end();
// 关注 <SUF>
newRouter.rule().async(false).msgType(EVENT).event(SUBSCRIBE).handler(this.subscribeHandler).end();
// 取消关注事件
newRouter.rule().async(false).msgType(EVENT).event(UNSUBSCRIBE).handler(this.unsubscribeHandler).end();
// 上报地理位置事件
newRouter.rule().async(false).msgType(EVENT).event(EventType.LOCATION).handler(this.locationHandler).end();
// 接收地理位置消息
newRouter.rule().async(false).msgType(XmlMsgType.LOCATION).handler(this.locationHandler).end();
// 扫码事件
newRouter.rule().async(false).msgType(EVENT).event(EventType.SCAN).handler(this.scanHandler).end();
// 默认
newRouter.rule().async(false).handler(this.msgHandler).end();
return newRouter;
}
}
| false | 1,228 | 4 | 1,442 | 4 | 1,459 | 4 | 1,442 | 4 | 1,803 | 6 | false | false | false | false | false | true |
14258_6 | package com.example.janusgraph.Example;
import lombok.extern.log4j.Log4j2;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.Cardinality;
import org.janusgraph.core.attribute.Geoshape;
import org.janusgraph.core.schema.JanusGraphManagement;
import org.springframework.stereotype.Service;
import static org.janusgraph.core.Multiplicity.MANY2ONE;
/**
* @author 李兵
* @version V1.0
* @description TODO: 定义schema,这里的业务模型为,一个人,一个公司,
* @date 2019/9/5 19:21
*/
@Service
@Log4j2
public class CreateSchema {
protected boolean useMixedIndex = true;
protected String mixedIndexConfigName = "search";
/**
* 定义schema图的顶点(我喜欢叫这个为所属类型); 人:person,公司:company,地点:localhost 三个顶点
*
* @param management
*/
public void createVertexLabels(JanusGraphManagement management) {
management.makeVertexLabel(SchemaVertex.PERSON).make();
management.makeVertexLabel(SchemaVertex.LOCALHOST).make();
management.makeVertexLabel(SchemaVertex.COMPANY).make();
}
/**
* 定义属性,及图中的属性属性,可以为边,点,进行引用。
* 使用基数(基数)来定义与任何给定顶点上的键相关联的值的允许基数。
* SINGLE:对于此类密钥,每个元素最多允许一个值。换句话说,键→值映射对于图中的所有元素都是唯一的。
* 属性键birthDate是具有SINGLE基数的示例,因为每个人只有一个出生日期。
* LIST:允许每个元素的任意数量的值用于此类键。换句话说,密钥与允许重复值的值列表相关联。
* 假设我们将传感器建模为图形中的顶点,则属性键sensorReading是LIST基数的示例,允许记录大量(可能重复的)传感器读数。
* SET:允许多个值,但每个元素没有重复值用于此类键。换句话说,密钥与一组值相关联。
* 如果我们想要捕获个人的所有姓名(包括昵称,婚前姓名等),则属性键名称具有SET基数。
* <p>
* 默认基数设置为SINGLE。请注意,边和属性上使用的属性键具有基数SINGLE。不支持为边或属性上的单个键附加多个值。
*
* @param management
*/
public void createProperties(JanusGraphManagement management) {
//名称,可以由多个名称
management.makePropertyKey(SchemaProperties.NAME).dataType(String.class).cardinality(Cardinality.SET).make();
//年龄,
management.makePropertyKey(SchemaProperties.AGE).dataType(Integer.class).make();
//身份证号
management.makePropertyKey(SchemaProperties.NO).dataType(String.class).make();
//时间,可以为公司成立时间,人员的入职时间的这是一个笼统的定义
management.makePropertyKey(SchemaProperties.TIME).dataType(String.class).make();
//手机/电话
management.makePropertyKey(SchemaProperties.PHONE).dataType(String.class).make();
//关系型数据库的主键
management.makePropertyKey(SchemaProperties.ID).dataType(String.class).make();
//地方
management.makePropertyKey(SchemaProperties.ADDRESS).dataType(String.class).make();
//公司坐标
management.makePropertyKey(SchemaProperties.PLACE).dataType(Geoshape.class).make();
}
/**
* 定义schema图的边;
* <p>
* MULTI: 允许任何顶点对之间的同一标签的多个边。换句话说,该图是关于这种边缘标签的多图。边缘多重性没有约束。
* SIMPLE:在任何一对顶点之间最多允许此类标签的一个边缘。换句话说,该图是关于标签的简单图。确保边缘对于给定标签和顶点对是唯一的
* MANY2ONE:在图形中的任何顶点上最多允许此标签的一个输出,但不对入射边缘施加约束。
* 边缘标签母亲是MANY2ONE多样性的一个例子,因为每个人最多只有一个母亲,但母亲可以有多个孩子。
* ONE2MANY:在图形中的任何顶点上最多允许此类标签的一个输入边缘,但不对输出边缘施加约束。
* 边缘标签winnerOf是具有ONE2MANY多样性的示例,因为每个比赛最多只能赢得一个人,但是一个人可以赢得多个比赛.
* ONE2ONE:在图中的任何顶点上最多允许此标签的一个输入边和一个输出边。边缘标签结婚是一个具有ONE2ONE多样性的例子,因为一个人与另一个人结婚。
* todo:默认设置为 MULTI。
* todo:具体参考这位同学写的链接:https://www.cnblogs.com/jiyuqi/p/7127178.html?utm_source=itdadao&utm_medium=referral
*
* @param management
*/
public void createEdgeLabels(JanusGraphManagement management) {
//父亲,注意这里的 Multiplicity常量,
management.makeEdgeLabel("father").multiplicity(MANY2ONE).make();
//母亲
management.makeEdgeLabel("mother").multiplicity(MANY2ONE).make();
//兄弟或平辈
management.makeEdgeLabel("brother").make();
//归属,人属于哪个公司,公司中都有谁 公司地点在哪里
management.makeEdgeLabel("belong").make();
}
/**
* 复合索引
*
* @param management
*/
public void createCompositeIndexes(JanusGraphManagement management) {
/**创建顶点 单个索引**/
management.buildIndex("byNameIndex", Vertex.class)
.addKey(management.getPropertyKey("name"))
.buildCompositeIndex();
management.buildIndex("byAgeIndex", Vertex.class)
.addKey(management.getPropertyKey("age"))
.buildCompositeIndex();
management.buildIndex("byIdIndex", Vertex.class)
.addKey(management.getPropertyKey("id"))
.buildCompositeIndex();
management.buildIndex("byNoIndex", Vertex.class)
.addKey(management.getPropertyKey("no"))
.buildCompositeIndex();
management.buildIndex("byAddressIndex", Vertex.class)
.addKey(management.getPropertyKey("address"))
.buildCompositeIndex();
management.buildIndex("byPlaceIndex", Vertex.class)
.addKey(management.getPropertyKey("place"))
.buildCompositeIndex();
}
/**
* 创建混合索引
*
* @param management
*/
public void createMixedIndexes(JanusGraphManagement management) {
if (this.useMixedIndex) {
management.buildIndex("nameAndAgeAndNoAndId", Vertex.class)
.addKey(management.getPropertyKey("name"))
.addKey(management.getPropertyKey("age"))
.addKey(management.getPropertyKey("no"))
.addKey(management.getPropertyKey("id"))
.buildMixedIndex(this.mixedIndexConfigName);
management.buildIndex("byNANIP", Edge.class)
.addKey(management.getPropertyKey("name"))
.addKey(management.getPropertyKey("age"))
.addKey(management.getPropertyKey("no"))
.addKey(management.getPropertyKey("id"))
.addKey(management.getPropertyKey("place"))
.buildMixedIndex(this.mixedIndexConfigName);
}
}
}
| bingbingll/janusgraph-example | src/main/java/com/example/janusgraph/Example/CreateSchema.java | 1,874 | //时间,可以为公司成立时间,人员的入职时间的这是一个笼统的定义 | line_comment | zh-cn | package com.example.janusgraph.Example;
import lombok.extern.log4j.Log4j2;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.Cardinality;
import org.janusgraph.core.attribute.Geoshape;
import org.janusgraph.core.schema.JanusGraphManagement;
import org.springframework.stereotype.Service;
import static org.janusgraph.core.Multiplicity.MANY2ONE;
/**
* @author 李兵
* @version V1.0
* @description TODO: 定义schema,这里的业务模型为,一个人,一个公司,
* @date 2019/9/5 19:21
*/
@Service
@Log4j2
public class CreateSchema {
protected boolean useMixedIndex = true;
protected String mixedIndexConfigName = "search";
/**
* 定义schema图的顶点(我喜欢叫这个为所属类型); 人:person,公司:company,地点:localhost 三个顶点
*
* @param management
*/
public void createVertexLabels(JanusGraphManagement management) {
management.makeVertexLabel(SchemaVertex.PERSON).make();
management.makeVertexLabel(SchemaVertex.LOCALHOST).make();
management.makeVertexLabel(SchemaVertex.COMPANY).make();
}
/**
* 定义属性,及图中的属性属性,可以为边,点,进行引用。
* 使用基数(基数)来定义与任何给定顶点上的键相关联的值的允许基数。
* SINGLE:对于此类密钥,每个元素最多允许一个值。换句话说,键→值映射对于图中的所有元素都是唯一的。
* 属性键birthDate是具有SINGLE基数的示例,因为每个人只有一个出生日期。
* LIST:允许每个元素的任意数量的值用于此类键。换句话说,密钥与允许重复值的值列表相关联。
* 假设我们将传感器建模为图形中的顶点,则属性键sensorReading是LIST基数的示例,允许记录大量(可能重复的)传感器读数。
* SET:允许多个值,但每个元素没有重复值用于此类键。换句话说,密钥与一组值相关联。
* 如果我们想要捕获个人的所有姓名(包括昵称,婚前姓名等),则属性键名称具有SET基数。
* <p>
* 默认基数设置为SINGLE。请注意,边和属性上使用的属性键具有基数SINGLE。不支持为边或属性上的单个键附加多个值。
*
* @param management
*/
public void createProperties(JanusGraphManagement management) {
//名称,可以由多个名称
management.makePropertyKey(SchemaProperties.NAME).dataType(String.class).cardinality(Cardinality.SET).make();
//年龄,
management.makePropertyKey(SchemaProperties.AGE).dataType(Integer.class).make();
//身份证号
management.makePropertyKey(SchemaProperties.NO).dataType(String.class).make();
//时间 <SUF>
management.makePropertyKey(SchemaProperties.TIME).dataType(String.class).make();
//手机/电话
management.makePropertyKey(SchemaProperties.PHONE).dataType(String.class).make();
//关系型数据库的主键
management.makePropertyKey(SchemaProperties.ID).dataType(String.class).make();
//地方
management.makePropertyKey(SchemaProperties.ADDRESS).dataType(String.class).make();
//公司坐标
management.makePropertyKey(SchemaProperties.PLACE).dataType(Geoshape.class).make();
}
/**
* 定义schema图的边;
* <p>
* MULTI: 允许任何顶点对之间的同一标签的多个边。换句话说,该图是关于这种边缘标签的多图。边缘多重性没有约束。
* SIMPLE:在任何一对顶点之间最多允许此类标签的一个边缘。换句话说,该图是关于标签的简单图。确保边缘对于给定标签和顶点对是唯一的
* MANY2ONE:在图形中的任何顶点上最多允许此标签的一个输出,但不对入射边缘施加约束。
* 边缘标签母亲是MANY2ONE多样性的一个例子,因为每个人最多只有一个母亲,但母亲可以有多个孩子。
* ONE2MANY:在图形中的任何顶点上最多允许此类标签的一个输入边缘,但不对输出边缘施加约束。
* 边缘标签winnerOf是具有ONE2MANY多样性的示例,因为每个比赛最多只能赢得一个人,但是一个人可以赢得多个比赛.
* ONE2ONE:在图中的任何顶点上最多允许此标签的一个输入边和一个输出边。边缘标签结婚是一个具有ONE2ONE多样性的例子,因为一个人与另一个人结婚。
* todo:默认设置为 MULTI。
* todo:具体参考这位同学写的链接:https://www.cnblogs.com/jiyuqi/p/7127178.html?utm_source=itdadao&utm_medium=referral
*
* @param management
*/
public void createEdgeLabels(JanusGraphManagement management) {
//父亲,注意这里的 Multiplicity常量,
management.makeEdgeLabel("father").multiplicity(MANY2ONE).make();
//母亲
management.makeEdgeLabel("mother").multiplicity(MANY2ONE).make();
//兄弟或平辈
management.makeEdgeLabel("brother").make();
//归属,人属于哪个公司,公司中都有谁 公司地点在哪里
management.makeEdgeLabel("belong").make();
}
/**
* 复合索引
*
* @param management
*/
public void createCompositeIndexes(JanusGraphManagement management) {
/**创建顶点 单个索引**/
management.buildIndex("byNameIndex", Vertex.class)
.addKey(management.getPropertyKey("name"))
.buildCompositeIndex();
management.buildIndex("byAgeIndex", Vertex.class)
.addKey(management.getPropertyKey("age"))
.buildCompositeIndex();
management.buildIndex("byIdIndex", Vertex.class)
.addKey(management.getPropertyKey("id"))
.buildCompositeIndex();
management.buildIndex("byNoIndex", Vertex.class)
.addKey(management.getPropertyKey("no"))
.buildCompositeIndex();
management.buildIndex("byAddressIndex", Vertex.class)
.addKey(management.getPropertyKey("address"))
.buildCompositeIndex();
management.buildIndex("byPlaceIndex", Vertex.class)
.addKey(management.getPropertyKey("place"))
.buildCompositeIndex();
}
/**
* 创建混合索引
*
* @param management
*/
public void createMixedIndexes(JanusGraphManagement management) {
if (this.useMixedIndex) {
management.buildIndex("nameAndAgeAndNoAndId", Vertex.class)
.addKey(management.getPropertyKey("name"))
.addKey(management.getPropertyKey("age"))
.addKey(management.getPropertyKey("no"))
.addKey(management.getPropertyKey("id"))
.buildMixedIndex(this.mixedIndexConfigName);
management.buildIndex("byNANIP", Edge.class)
.addKey(management.getPropertyKey("name"))
.addKey(management.getPropertyKey("age"))
.addKey(management.getPropertyKey("no"))
.addKey(management.getPropertyKey("id"))
.addKey(management.getPropertyKey("place"))
.buildMixedIndex(this.mixedIndexConfigName);
}
}
}
| false | 1,643 | 19 | 1,874 | 23 | 1,842 | 19 | 1,874 | 23 | 2,590 | 35 | false | false | false | false | false | true |
29223_5 | /**
* Copyright 2020-9999 the original author or authors.
* <p>
* 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 io.binghe.chess.piece.impl;
import io.binghe.chess.piece.Chess;
import io.binghe.chess.utils.ImageTools;
import javax.swing.*;
import java.awt.*;
/**
* @author binghe
* @version 1.0.0
* @description 炮
*/
public class CannonChess implements Chess {
@Override
public boolean check(int[][] map, int currentRow, int currentColumn, int toRow, int toColumn, boolean isBlack) {
int columnDistance = Math.abs(toColumn - currentColumn);
int rowDistance = Math.abs(toRow - currentRow);
//为 0 说明炮与目标之间没有棋子
//为 1 说明炮与目标之间有 1个 棋子
//为 2 说明炮与目标之间有 2个 棋子
boolean success = (columnDistance == 0 && rowDistance != 0) || (columnDistance != 0 && rowDistance == 0);
//如果当前走的不是直线,则返回false
if(!success){
return false;
}
int count = 0;
int from, to;
//如果当前棋子横着走
if(rowDistance == 0){
//当前棋子向右走
if(currentColumn < toColumn){
from = currentColumn + 1;
to = toColumn;
}else{ //向左走
from = toColumn + 1;
to = currentColumn;
}
for(int i = from; i < to; i++){
if(map[currentRow][i] != 0){
count ++;
}
}
if(map[toRow][toColumn] == 0 && count == 0){
return true;
}
if(map[toRow][toColumn] == 0 && count == 1){
return false;
}
//黑方对面是红方,红方对面是黑方
if(map[toRow][toColumn] != 0 && ((isBlack && map[toRow][toColumn] < 1000) || (!isBlack && map[toRow][toColumn] > 1000)) && count == 1){
//将军
if(isBlack && map[toRow][toColumn] == 'G'){
JOptionPane.showMessageDialog(null, "黑方胜利!");
return true;
}
if(!isBlack && map[toRow][toColumn] == 1000 + 'G'){
JOptionPane.showMessageDialog(null, "红方胜利!");
return true;
}
return true;
}else{
return false;
}
}else{ //竖向行走
if(currentRow < toRow){ //向下走
from = currentRow + 1;
to = toRow;
}else{ //向上走
from = toRow + 1;
to = currentRow;
}
for(int i = from; i < to; i++){
if(map[i][currentColumn] != 0){
count++;
}
}
if(map[toRow][toColumn] == 0 && count == 0){
return true;
}
if(map[toRow][toColumn] == 0 && count == 1){
return false;
}
if(map[toRow][toColumn] != 0 && ((isBlack && map[toRow][toColumn] < 1000) || (!isBlack && map[toRow][toColumn] > 1000)) && count ==1){
if(isBlack && map[toRow][toColumn] == 'G'){
JOptionPane.showMessageDialog(null, "黑方胜利!");
return true;
}
if(!isBlack && map[toRow][toColumn] == 1000+'G'){
JOptionPane.showMessageDialog(null, "红方胜利!");
return true;
}
}else{
return false;
}
}
return true;
}
@Override
public int getType() {
return 'P';
}
@Override
public String getName() {
return "炮";
}
@Override
public Image getImage(boolean isBlack) {
return ImageTools.loadImage(isBlack?"black_cannon.gif":"red_cannon.gif");
}
}
| binghe001/binghe-chess | src/main/java/io/binghe/chess/piece/impl/CannonChess.java | 1,176 | //如果当前走的不是直线,则返回false | line_comment | zh-cn | /**
* Copyright 2020-9999 the original author or authors.
* <p>
* 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 io.binghe.chess.piece.impl;
import io.binghe.chess.piece.Chess;
import io.binghe.chess.utils.ImageTools;
import javax.swing.*;
import java.awt.*;
/**
* @author binghe
* @version 1.0.0
* @description 炮
*/
public class CannonChess implements Chess {
@Override
public boolean check(int[][] map, int currentRow, int currentColumn, int toRow, int toColumn, boolean isBlack) {
int columnDistance = Math.abs(toColumn - currentColumn);
int rowDistance = Math.abs(toRow - currentRow);
//为 0 说明炮与目标之间没有棋子
//为 1 说明炮与目标之间有 1个 棋子
//为 2 说明炮与目标之间有 2个 棋子
boolean success = (columnDistance == 0 && rowDistance != 0) || (columnDistance != 0 && rowDistance == 0);
//如果 <SUF>
if(!success){
return false;
}
int count = 0;
int from, to;
//如果当前棋子横着走
if(rowDistance == 0){
//当前棋子向右走
if(currentColumn < toColumn){
from = currentColumn + 1;
to = toColumn;
}else{ //向左走
from = toColumn + 1;
to = currentColumn;
}
for(int i = from; i < to; i++){
if(map[currentRow][i] != 0){
count ++;
}
}
if(map[toRow][toColumn] == 0 && count == 0){
return true;
}
if(map[toRow][toColumn] == 0 && count == 1){
return false;
}
//黑方对面是红方,红方对面是黑方
if(map[toRow][toColumn] != 0 && ((isBlack && map[toRow][toColumn] < 1000) || (!isBlack && map[toRow][toColumn] > 1000)) && count == 1){
//将军
if(isBlack && map[toRow][toColumn] == 'G'){
JOptionPane.showMessageDialog(null, "黑方胜利!");
return true;
}
if(!isBlack && map[toRow][toColumn] == 1000 + 'G'){
JOptionPane.showMessageDialog(null, "红方胜利!");
return true;
}
return true;
}else{
return false;
}
}else{ //竖向行走
if(currentRow < toRow){ //向下走
from = currentRow + 1;
to = toRow;
}else{ //向上走
from = toRow + 1;
to = currentRow;
}
for(int i = from; i < to; i++){
if(map[i][currentColumn] != 0){
count++;
}
}
if(map[toRow][toColumn] == 0 && count == 0){
return true;
}
if(map[toRow][toColumn] == 0 && count == 1){
return false;
}
if(map[toRow][toColumn] != 0 && ((isBlack && map[toRow][toColumn] < 1000) || (!isBlack && map[toRow][toColumn] > 1000)) && count ==1){
if(isBlack && map[toRow][toColumn] == 'G'){
JOptionPane.showMessageDialog(null, "黑方胜利!");
return true;
}
if(!isBlack && map[toRow][toColumn] == 1000+'G'){
JOptionPane.showMessageDialog(null, "红方胜利!");
return true;
}
}else{
return false;
}
}
return true;
}
@Override
public int getType() {
return 'P';
}
@Override
public String getName() {
return "炮";
}
@Override
public Image getImage(boolean isBlack) {
return ImageTools.loadImage(isBlack?"black_cannon.gif":"red_cannon.gif");
}
}
| false | 1,076 | 10 | 1,176 | 12 | 1,233 | 11 | 1,176 | 12 | 1,399 | 18 | false | false | false | false | false | true |
60185_4 | /**
* Copyright 2020-9999 the original author or authors.
* <p>
* 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 io.mykit.data.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author binghe
* @version 1.0.0
* @description 任务池配置
*/
@Configuration
public class TaskPoolConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
//注意这一行日志:2. do submit,taskCount [101], completedTaskCount [87], activeCount [5], queueSize [9]
//这说明提交任务到线程池的时候,调用的是submit(Callable task)这个方法,当前已经提交了101个任务,完成了87个,当前有5个线程在处理任务,还剩9个任务在队列中等待,线程池的基本情况一路了然;
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心线程数10:线程池创建时候初始化的线程数
executor.setCorePoolSize(10);
//最大线程数20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
//maxPoolSize 当系统负载大道最大值时,核心线程数已无法按时处理完所有任务,这是就需要增加线程.每秒200个任务需要20个线程,那么当每秒1000个任务时,则需要(1000-queueCapacity)*(20/200),即60个线程,可将maxPoolSize设置为60;
executor.setMaxPoolSize(20);
//缓冲队列100:用来缓冲执行任务的队列
executor.setQueueCapacity(100);
//允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(60);
//线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
executor.setThreadNamePrefix("taskExecutor");
//理线程池对拒绝任务的处策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
/*CallerRunsPolicy:线程调用运行该任务的 execute 本身。此策略提供简单的反馈控制机制,能够减缓新任务的提交速度。
这个策略显然不想放弃执行任务。但是由于池中已经没有任何资源了,那么就直接使用调用该execute的线程本身来执行。(开始我总不想丢弃任务的执行,但是对某些应用场景来讲,很有可能造成当前线程也被阻塞。如果所有线程都是不能执行的,很可能导致程序没法继续跑了。需要视业务情景而定吧。)
AbortPolicy:处理程序遭到拒绝将抛出运行时 RejectedExecutionException
这种策略直接抛出异常,丢弃任务。(jdk默认策略,队列满并线程满时直接拒绝添加新任务,并抛出异常,所以说有时候放弃也是一种勇气,为了保证后续任务的正常进行,丢弃一些也是可以接收的,记得做好记录)
DiscardPolicy:不能执行的任务将被删除
这种策略和AbortPolicy几乎一样,也是丢弃任务,只不过他不抛出异常。
DiscardOldestPolicy:如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程)
该策略就稍微复杂一些,在pool没有关闭的前提下首先丢掉缓存在队列中的最早的任务,然后重新尝试运行该任务。这个策略需要适当小心*/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(5);
taskScheduler.setRemoveOnCancelPolicy(true);
taskScheduler.setThreadNamePrefix("taskScheduler");
taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
taskScheduler.setAwaitTerminationSeconds(60);
return taskScheduler;
}
}
| binghe001/mykit-data | mykit-data-starter/src/main/java/io/mykit/data/config/TaskPoolConfig.java | 1,250 | //核心线程数10:线程池创建时候初始化的线程数 | line_comment | zh-cn | /**
* Copyright 2020-9999 the original author or authors.
* <p>
* 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 io.mykit.data.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author binghe
* @version 1.0.0
* @description 任务池配置
*/
@Configuration
public class TaskPoolConfig {
@Bean("taskExecutor")
public Executor taskExecutor() {
//注意这一行日志:2. do submit,taskCount [101], completedTaskCount [87], activeCount [5], queueSize [9]
//这说明提交任务到线程池的时候,调用的是submit(Callable task)这个方法,当前已经提交了101个任务,完成了87个,当前有5个线程在处理任务,还剩9个任务在队列中等待,线程池的基本情况一路了然;
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
//核心 <SUF>
executor.setCorePoolSize(10);
//最大线程数20:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
//maxPoolSize 当系统负载大道最大值时,核心线程数已无法按时处理完所有任务,这是就需要增加线程.每秒200个任务需要20个线程,那么当每秒1000个任务时,则需要(1000-queueCapacity)*(20/200),即60个线程,可将maxPoolSize设置为60;
executor.setMaxPoolSize(20);
//缓冲队列100:用来缓冲执行任务的队列
executor.setQueueCapacity(100);
//允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(60);
//线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
executor.setThreadNamePrefix("taskExecutor");
//理线程池对拒绝任务的处策略:这里采用了CallerRunsPolicy策略,当线程池没有处理能力的时候,该策略会直接在 execute 方法的调用线程中运行被拒绝的任务;如果执行程序已关闭,则会丢弃该任务
/*CallerRunsPolicy:线程调用运行该任务的 execute 本身。此策略提供简单的反馈控制机制,能够减缓新任务的提交速度。
这个策略显然不想放弃执行任务。但是由于池中已经没有任何资源了,那么就直接使用调用该execute的线程本身来执行。(开始我总不想丢弃任务的执行,但是对某些应用场景来讲,很有可能造成当前线程也被阻塞。如果所有线程都是不能执行的,很可能导致程序没法继续跑了。需要视业务情景而定吧。)
AbortPolicy:处理程序遭到拒绝将抛出运行时 RejectedExecutionException
这种策略直接抛出异常,丢弃任务。(jdk默认策略,队列满并线程满时直接拒绝添加新任务,并抛出异常,所以说有时候放弃也是一种勇气,为了保证后续任务的正常进行,丢弃一些也是可以接收的,记得做好记录)
DiscardPolicy:不能执行的任务将被删除
这种策略和AbortPolicy几乎一样,也是丢弃任务,只不过他不抛出异常。
DiscardOldestPolicy:如果执行程序尚未关闭,则位于工作队列头部的任务将被删除,然后重试执行程序(如果再次失败,则重复此过程)
该策略就稍微复杂一些,在pool没有关闭的前提下首先丢掉缓存在队列中的最早的任务,然后重新尝试运行该任务。这个策略需要适当小心*/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
@Bean
public TaskScheduler taskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.setPoolSize(5);
taskScheduler.setRemoveOnCancelPolicy(true);
taskScheduler.setThreadNamePrefix("taskScheduler");
taskScheduler.setWaitForTasksToCompleteOnShutdown(true);
taskScheduler.setAwaitTerminationSeconds(60);
return taskScheduler;
}
}
| false | 1,148 | 18 | 1,250 | 15 | 1,198 | 15 | 1,250 | 15 | 1,886 | 25 | false | false | false | false | false | true |
22682_1 |
/**
* 封装就是用private来修饰属性或者方法
* 限定你只能在类中使用
* 为什么要封装?
*如果没有特殊要求 那么属性都设置为私有的
*
* 关键字:
* this:代表对当前对象的引用
* 要习惯使用this
* 如果没有特殊要求 一定要习惯使用this 用来体现封装
*/
class Student{
private String name;//
public int age;
//如果已经进行过封装 那么需要提供一个公开的接口
//使用Ait+Lnsert快速创建
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重新 实现了一下Object类的 toString方法
//object是所有方法的父类
@Override//注解:这个注解指的是 这个方法是重新写的
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
/* public String MyName(){//调用返回name内容
return this.name;
}
public void getname(String name1){//调用修改name值
this.name=name1;
}
public void getname1(String name){//如果发生以上这种情况 是因为名称一样 局部变量优先 等于自己给自己赋值了
this.name=name;//this代表对当前对象的引用
}*/
public void func1(){
System.out.println("func1()");
}
}
//以上是类的实现者写的代码
//以下是类的使用者写的代码
public class Dome {
public static void main1(String[] args) {
Student student=new Student();
student.setName("guobinglin");
student.setAge(20);
System.out.println(student);
}
}
| binglinguo/Java_Demo | src/Dome.java | 456 | //如果已经进行过封装 那么需要提供一个公开的接口 | line_comment | zh-cn |
/**
* 封装就是用private来修饰属性或者方法
* 限定你只能在类中使用
* 为什么要封装?
*如果没有特殊要求 那么属性都设置为私有的
*
* 关键字:
* this:代表对当前对象的引用
* 要习惯使用this
* 如果没有特殊要求 一定要习惯使用this 用来体现封装
*/
class Student{
private String name;//
public int age;
//如果 <SUF>
//使用Ait+Lnsert快速创建
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//重新 实现了一下Object类的 toString方法
//object是所有方法的父类
@Override//注解:这个注解指的是 这个方法是重新写的
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
/* public String MyName(){//调用返回name内容
return this.name;
}
public void getname(String name1){//调用修改name值
this.name=name1;
}
public void getname1(String name){//如果发生以上这种情况 是因为名称一样 局部变量优先 等于自己给自己赋值了
this.name=name;//this代表对当前对象的引用
}*/
public void func1(){
System.out.println("func1()");
}
}
//以上是类的实现者写的代码
//以下是类的使用者写的代码
public class Dome {
public static void main1(String[] args) {
Student student=new Student();
student.setName("guobinglin");
student.setAge(20);
System.out.println(student);
}
}
| false | 436 | 17 | 456 | 16 | 471 | 14 | 456 | 16 | 657 | 28 | false | false | false | false | false | true |
33876_1 | package com.bingoogol.mobilesafe;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import android.app.Application;
import android.os.Build;
import android.os.Environment;
/**
* 基类 记录维护应用程序全局的状态
* @author Administrator
*
*/
public class MobileSafeAppliction extends Application {
/**
* 在应用程序创建的时候 被调用.
* 当应用程序的进程创建的时候
* 在被的对象创建之前调用的方法.
* 相当于整个应用初始化的操作
*/
@Override
public void onCreate() {
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
super.onCreate();
}
private class MyExceptionHandler implements UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread thread, Throwable ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
try {
StringBuffer sb = new StringBuffer();
sb.append("错误时间: "+System.currentTimeMillis()+"\n");
//收集设备的信息 时间
Field[] fields = Build.class.getFields();
for(Field field: fields){
String value = field.get(null).toString();
String name = field.getName();
sb.append(name+":"+value+"\n");
}
String errormsg = sw.toString();
sb.append(errormsg);
File file = new File(Environment.getExternalStorageDirectory(),"mobilesafeerror.log");
FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("产生了异常,但是被哥给捕获了.");
//原地复活不可能.
//自杀
android.os.Process.killProcess(android.os.Process.myPid());
}
}
}
| bingoogolapple/AndroidNote-PartOne | IDEA/mobilesafe/src/com/bingoogol/mobilesafe/MobileSafeAppliction.java | 521 | /**
* 在应用程序创建的时候 被调用.
* 当应用程序的进程创建的时候
* 在被的对象创建之前调用的方法.
* 相当于整个应用初始化的操作
*/ | block_comment | zh-cn | package com.bingoogol.mobilesafe;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import android.app.Application;
import android.os.Build;
import android.os.Environment;
/**
* 基类 记录维护应用程序全局的状态
* @author Administrator
*
*/
public class MobileSafeAppliction extends Application {
/**
* 在应用 <SUF>*/
@Override
public void onCreate() {
Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler());
super.onCreate();
}
private class MyExceptionHandler implements UncaughtExceptionHandler{
@Override
public void uncaughtException(Thread thread, Throwable ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
try {
StringBuffer sb = new StringBuffer();
sb.append("错误时间: "+System.currentTimeMillis()+"\n");
//收集设备的信息 时间
Field[] fields = Build.class.getFields();
for(Field field: fields){
String value = field.get(null).toString();
String name = field.getName();
sb.append(name+":"+value+"\n");
}
String errormsg = sw.toString();
sb.append(errormsg);
File file = new File(Environment.getExternalStorageDirectory(),"mobilesafeerror.log");
FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("产生了异常,但是被哥给捕获了.");
//原地复活不可能.
//自杀
android.os.Process.killProcess(android.os.Process.myPid());
}
}
}
| false | 414 | 47 | 521 | 43 | 513 | 47 | 521 | 43 | 732 | 80 | false | false | false | false | false | true |
3828_0 | package cn.bingoogolapple.bgabanner.demo.ui.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.bingoogolapple.bgabanner.BGALocalImageSize;
import cn.bingoogolapple.bgabanner.demo.R;
public class GuideActivity extends Activity {
private static final String TAG = GuideActivity.class.getSimpleName();
private BGABanner mBackgroundBanner;
private BGABanner mForegroundBanner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
setListener();
processLogic();
}
private void initView() {
setContentView(R.layout.activity_guide);
mBackgroundBanner = findViewById(R.id.banner_guide_background);
mForegroundBanner = findViewById(R.id.banner_guide_foreground);
}
private void setListener() {
/**
* 设置进入按钮和跳过按钮控件资源 id 及其点击事件
* 如果进入按钮和跳过按钮有一个不存在的话就传 0
* 在 BGABanner 里已经帮开发者处理了防止重复点击事件
* 在 BGABanner 里已经帮开发者处理了「跳过按钮」和「进入按钮」的显示与隐藏
*/
mForegroundBanner.setEnterSkipViewIdAndDelegate(R.id.btn_guide_enter, R.id.tv_guide_skip, new BGABanner.GuideDelegate() {
@Override
public void onClickEnterOrSkip() {
startActivity(new Intent(GuideActivity.this, MainActivity.class));
finish();
}
});
}
private void processLogic() {
// Bitmap 的宽高在 maxWidth maxHeight 和 minWidth minHeight 之间
BGALocalImageSize localImageSize = new BGALocalImageSize(720, 1280, 320, 640);
// 设置数据源
mBackgroundBanner.setData(localImageSize, ImageView.ScaleType.CENTER_CROP,
R.drawable.uoko_guide_background_1,
R.drawable.uoko_guide_background_2,
R.drawable.uoko_guide_background_3);
mForegroundBanner.setData(localImageSize, ImageView.ScaleType.CENTER_CROP,
R.drawable.uoko_guide_foreground_1,
R.drawable.uoko_guide_foreground_2,
R.drawable.uoko_guide_foreground_3);
}
@Override
protected void onResume() {
super.onResume();
// 如果开发者的引导页主题是透明的,需要在界面可见时给背景 Banner 设置一个白色背景,避免滑动过程中两个 Banner 都设置透明度后能看到 Launcher
mBackgroundBanner.setBackgroundResource(android.R.color.white);
}
} | bingoogolapple/BGABanner-Android | demo/src/main/java/cn/bingoogolapple/bgabanner/demo/ui/activity/GuideActivity.java | 676 | /**
* 设置进入按钮和跳过按钮控件资源 id 及其点击事件
* 如果进入按钮和跳过按钮有一个不存在的话就传 0
* 在 BGABanner 里已经帮开发者处理了防止重复点击事件
* 在 BGABanner 里已经帮开发者处理了「跳过按钮」和「进入按钮」的显示与隐藏
*/ | block_comment | zh-cn | package cn.bingoogolapple.bgabanner.demo.ui.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;
import cn.bingoogolapple.bgabanner.BGABanner;
import cn.bingoogolapple.bgabanner.BGALocalImageSize;
import cn.bingoogolapple.bgabanner.demo.R;
public class GuideActivity extends Activity {
private static final String TAG = GuideActivity.class.getSimpleName();
private BGABanner mBackgroundBanner;
private BGABanner mForegroundBanner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
setListener();
processLogic();
}
private void initView() {
setContentView(R.layout.activity_guide);
mBackgroundBanner = findViewById(R.id.banner_guide_background);
mForegroundBanner = findViewById(R.id.banner_guide_foreground);
}
private void setListener() {
/**
* 设置进 <SUF>*/
mForegroundBanner.setEnterSkipViewIdAndDelegate(R.id.btn_guide_enter, R.id.tv_guide_skip, new BGABanner.GuideDelegate() {
@Override
public void onClickEnterOrSkip() {
startActivity(new Intent(GuideActivity.this, MainActivity.class));
finish();
}
});
}
private void processLogic() {
// Bitmap 的宽高在 maxWidth maxHeight 和 minWidth minHeight 之间
BGALocalImageSize localImageSize = new BGALocalImageSize(720, 1280, 320, 640);
// 设置数据源
mBackgroundBanner.setData(localImageSize, ImageView.ScaleType.CENTER_CROP,
R.drawable.uoko_guide_background_1,
R.drawable.uoko_guide_background_2,
R.drawable.uoko_guide_background_3);
mForegroundBanner.setData(localImageSize, ImageView.ScaleType.CENTER_CROP,
R.drawable.uoko_guide_foreground_1,
R.drawable.uoko_guide_foreground_2,
R.drawable.uoko_guide_foreground_3);
}
@Override
protected void onResume() {
super.onResume();
// 如果开发者的引导页主题是透明的,需要在界面可见时给背景 Banner 设置一个白色背景,避免滑动过程中两个 Banner 都设置透明度后能看到 Launcher
mBackgroundBanner.setBackgroundResource(android.R.color.white);
}
} | false | 574 | 85 | 676 | 83 | 713 | 84 | 676 | 83 | 902 | 153 | false | false | false | false | false | true |
14538_5 | /*
* Copyright 2016 bingoogolapple
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.bingoogolapple.swipebacklayout;
import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.view.View;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.FloatRange;
/**
* 作者:王浩 邮件:bingoogolapple@gmail.com
* 创建时间:17/1/4 下午3:44
* 描述:滑动返回帮助类
*/
public class BGASwipeBackHelper {
private Activity mActivity;
private Delegate mDelegate;
private BGASwipeBackLayout mSwipeBackLayout;
/**
* 必须在 Application 的 onCreate 方法中调用
*
* @param application 应用程序上下文
* @param problemViewClassList 如果发现滑动返回后立即触摸界面时应用崩溃,
* 请把该界面里比较特殊的 View 的 class 添加到该集合中,
* 目前在库中已经添加了 WebView 和 SurfaceView
*/
public static void init(Application application, List<Class<? extends View>> problemViewClassList) {
BGASwipeBackManager.getInstance().init(application, problemViewClassList);
}
/**
* @param activity
* @param delegate
*/
public BGASwipeBackHelper(Activity activity, Delegate delegate) {
mActivity = activity;
mDelegate = delegate;
initSwipeBackFinish();
}
/**
* 初始化滑动返回
*/
private void initSwipeBackFinish() {
if (mDelegate.isSupportSwipeBack()) {
mSwipeBackLayout = new BGASwipeBackLayout(mActivity);
mSwipeBackLayout.attachToActivity(mActivity);
mSwipeBackLayout.setPanelSlideListener(new BGASwipeBackLayout.PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
// 开始滑动返回时关闭软键盘
if (slideOffset < 0.03) {
BGAKeyboardUtil.closeKeyboard(mActivity);
}
mDelegate.onSwipeBackLayoutSlide(slideOffset);
}
@Override
public void onPanelOpened(View panel) {
mDelegate.onSwipeBackLayoutExecuted();
}
@Override
public void onPanelClosed(View panel) {
mDelegate.onSwipeBackLayoutCancel();
}
});
}
}
/**
* 设置滑动返回是否可用。默认值为 true
*
* @param swipeBackEnable
* @return
*/
public BGASwipeBackHelper setSwipeBackEnable(boolean swipeBackEnable) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setSwipeBackEnable(swipeBackEnable);
}
return this;
}
/**
* 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
*
* @param isOnlyTrackingLeftEdge
* @return
*/
public BGASwipeBackHelper setIsOnlyTrackingLeftEdge(boolean isOnlyTrackingLeftEdge) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsOnlyTrackingLeftEdge(isOnlyTrackingLeftEdge);
}
return this;
}
/**
* 设置是否是微信滑动返回样式。默认值为 true
*
* @param isWeChatStyle
* @return
*/
public BGASwipeBackHelper setIsWeChatStyle(boolean isWeChatStyle) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsWeChatStyle(isWeChatStyle);
}
return this;
}
/**
* 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
*
* @param shadowResId
* @return
*/
public BGASwipeBackHelper setShadowResId(@DrawableRes int shadowResId) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setShadowResId(shadowResId);
}
return this;
}
/**
* 设置是否显示滑动返回的阴影效果。默认值为 true
*
* @param isNeedShowShadow
* @return
*/
public BGASwipeBackHelper setIsNeedShowShadow(boolean isNeedShowShadow) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsNeedShowShadow(isNeedShowShadow);
}
return this;
}
/**
* 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
*
* @param isShadowAlphaGradient
* @return
*/
public BGASwipeBackHelper setIsShadowAlphaGradient(boolean isShadowAlphaGradient) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsShadowAlphaGradient(isShadowAlphaGradient);
}
return this;
}
/**
* 设置触发释放后自动滑动返回的阈值,默认值为 0.3f
*
* @param threshold
*/
public BGASwipeBackHelper setSwipeBackThreshold(@FloatRange(from = 0.0f, to = 1.0f) float threshold) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setSwipeBackThreshold(threshold);
}
return this;
}
/**
* 设置底部导航条是否悬浮在内容上
*
* @param overlap
*/
public BGASwipeBackHelper setIsNavigationBarOverlap(boolean overlap) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsNavigationBarOverlap(overlap);
}
return this;
}
/**
* 是否正在滑动
*
* @return
*/
public boolean isSliding() {
if (mSwipeBackLayout != null) {
return mSwipeBackLayout.isSliding();
}
return false;
}
/**
* 执行跳转到下一个 Activity 的动画
*/
public void executeForwardAnim() {
executeForwardAnim(mActivity);
}
/**
* 执行回到到上一个 Activity 的动画
*/
public void executeBackwardAnim() {
executeBackwardAnim(mActivity);
}
/**
* 执行滑动返回到到上一个 Activity 的动画
*/
public void executeSwipeBackAnim() {
executeSwipeBackAnim(mActivity);
}
/**
* 执行跳转到下一个 Activity 的动画。这里弄成静态方法,方便在 Fragment 中调用
*/
public static void executeForwardAnim(Activity activity) {
activity.overridePendingTransition(R.anim.bga_sbl_activity_forward_enter, R.anim.bga_sbl_activity_forward_exit);
}
/**
* 执行回到到上一个 Activity 的动画。这里弄成静态方法,方便在 Fragment 中调用
*/
public static void executeBackwardAnim(Activity activity) {
activity.overridePendingTransition(R.anim.bga_sbl_activity_backward_enter, R.anim.bga_sbl_activity_backward_exit);
}
/**
* 执行滑动返回到到上一个 Activity 的动画。这里弄成静态方法,方便在 Fragment 中调用
*/
public static void executeSwipeBackAnim(Activity activity) {
activity.overridePendingTransition(R.anim.bga_sbl_activity_swipeback_enter, R.anim.bga_sbl_activity_swipeback_exit);
}
/**
* 跳转到下一个 Activity,并且销毁当前 Activity
*
* @param cls 下一个 Activity 的 Class
*/
public void forwardAndFinish(Class<?> cls) {
forward(cls);
mActivity.finish();
}
/**
* 跳转到下一个 Activity,不销毁当前 Activity
*
* @param cls 下一个 Activity 的 Class
*/
public void forward(Class<?> cls) {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.startActivity(new Intent(mActivity, cls));
executeForwardAnim();
}
/**
* 跳转到下一个 Activity,不销毁当前 Activity
*
* @param cls 下一个 Activity 的 Class
* @param requestCode 请求码
*/
public void forward(Class<?> cls, int requestCode) {
forward(new Intent(mActivity, cls), requestCode);
}
/**
* 跳转到下一个 Activity,销毁当前 Activity
*
* @param intent 下一个 Activity 的意图对象
*/
public void forwardAndFinish(Intent intent) {
forward(intent);
mActivity.finish();
}
/**
* 跳转到下一个 Activity,不销毁当前 Activity
*
* @param intent 下一个 Activity 的意图对象
*/
public void forward(Intent intent) {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.startActivity(intent);
executeForwardAnim();
}
/**
* 跳转到下一个 Activity,不销毁当前 Activity
*
* @param intent 下一个 Activity 的意图对象
* @param requestCode 请求码
*/
public void forward(Intent intent, int requestCode) {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.startActivityForResult(intent, requestCode);
executeForwardAnim();
}
/**
* 回到上一个 Activity,并销毁当前 Activity
*/
public void backward() {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.finish();
executeBackwardAnim();
}
/**
* 滑动返回上一个 Activity,并销毁当前 Activity
*/
public void swipeBackward() {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.finish();
executeSwipeBackAnim();
}
/**
* 回到上一个 Activity,并销毁当前 Activity(应用场景:欢迎、登录、注册这三个界面)
*
* @param cls 上一个 Activity 的 Class
*/
public void backwardAndFinish(Class<?> cls) {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.startActivity(new Intent(mActivity, cls));
mActivity.finish();
executeBackwardAnim();
}
public interface Delegate {
/**
* 是否支持滑动返回
*
* @return
*/
boolean isSupportSwipeBack();
/**
* 正在滑动返回
*
* @param slideOffset 从 0 到 1
*/
void onSwipeBackLayoutSlide(float slideOffset);
/**
* 没达到滑动返回的阈值,取消滑动返回动作,回到默认状态
*/
void onSwipeBackLayoutCancel();
/**
* 滑动返回执行完毕,销毁当前 Activity
*/
void onSwipeBackLayoutExecuted();
}
}
| bingoogolapple/BGASwipeBackLayout-Android | library/src/main/java/cn/bingoogolapple/swipebacklayout/BGASwipeBackHelper.java | 2,582 | // 开始滑动返回时关闭软键盘 | line_comment | zh-cn | /*
* Copyright 2016 bingoogolapple
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.bingoogolapple.swipebacklayout;
import android.app.Activity;
import android.app.Application;
import android.content.Intent;
import android.view.View;
import java.util.List;
import androidx.annotation.DrawableRes;
import androidx.annotation.FloatRange;
/**
* 作者:王浩 邮件:bingoogolapple@gmail.com
* 创建时间:17/1/4 下午3:44
* 描述:滑动返回帮助类
*/
public class BGASwipeBackHelper {
private Activity mActivity;
private Delegate mDelegate;
private BGASwipeBackLayout mSwipeBackLayout;
/**
* 必须在 Application 的 onCreate 方法中调用
*
* @param application 应用程序上下文
* @param problemViewClassList 如果发现滑动返回后立即触摸界面时应用崩溃,
* 请把该界面里比较特殊的 View 的 class 添加到该集合中,
* 目前在库中已经添加了 WebView 和 SurfaceView
*/
public static void init(Application application, List<Class<? extends View>> problemViewClassList) {
BGASwipeBackManager.getInstance().init(application, problemViewClassList);
}
/**
* @param activity
* @param delegate
*/
public BGASwipeBackHelper(Activity activity, Delegate delegate) {
mActivity = activity;
mDelegate = delegate;
initSwipeBackFinish();
}
/**
* 初始化滑动返回
*/
private void initSwipeBackFinish() {
if (mDelegate.isSupportSwipeBack()) {
mSwipeBackLayout = new BGASwipeBackLayout(mActivity);
mSwipeBackLayout.attachToActivity(mActivity);
mSwipeBackLayout.setPanelSlideListener(new BGASwipeBackLayout.PanelSlideListener() {
@Override
public void onPanelSlide(View panel, float slideOffset) {
// 开始 <SUF>
if (slideOffset < 0.03) {
BGAKeyboardUtil.closeKeyboard(mActivity);
}
mDelegate.onSwipeBackLayoutSlide(slideOffset);
}
@Override
public void onPanelOpened(View panel) {
mDelegate.onSwipeBackLayoutExecuted();
}
@Override
public void onPanelClosed(View panel) {
mDelegate.onSwipeBackLayoutCancel();
}
});
}
}
/**
* 设置滑动返回是否可用。默认值为 true
*
* @param swipeBackEnable
* @return
*/
public BGASwipeBackHelper setSwipeBackEnable(boolean swipeBackEnable) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setSwipeBackEnable(swipeBackEnable);
}
return this;
}
/**
* 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
*
* @param isOnlyTrackingLeftEdge
* @return
*/
public BGASwipeBackHelper setIsOnlyTrackingLeftEdge(boolean isOnlyTrackingLeftEdge) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsOnlyTrackingLeftEdge(isOnlyTrackingLeftEdge);
}
return this;
}
/**
* 设置是否是微信滑动返回样式。默认值为 true
*
* @param isWeChatStyle
* @return
*/
public BGASwipeBackHelper setIsWeChatStyle(boolean isWeChatStyle) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsWeChatStyle(isWeChatStyle);
}
return this;
}
/**
* 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
*
* @param shadowResId
* @return
*/
public BGASwipeBackHelper setShadowResId(@DrawableRes int shadowResId) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setShadowResId(shadowResId);
}
return this;
}
/**
* 设置是否显示滑动返回的阴影效果。默认值为 true
*
* @param isNeedShowShadow
* @return
*/
public BGASwipeBackHelper setIsNeedShowShadow(boolean isNeedShowShadow) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsNeedShowShadow(isNeedShowShadow);
}
return this;
}
/**
* 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
*
* @param isShadowAlphaGradient
* @return
*/
public BGASwipeBackHelper setIsShadowAlphaGradient(boolean isShadowAlphaGradient) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsShadowAlphaGradient(isShadowAlphaGradient);
}
return this;
}
/**
* 设置触发释放后自动滑动返回的阈值,默认值为 0.3f
*
* @param threshold
*/
public BGASwipeBackHelper setSwipeBackThreshold(@FloatRange(from = 0.0f, to = 1.0f) float threshold) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setSwipeBackThreshold(threshold);
}
return this;
}
/**
* 设置底部导航条是否悬浮在内容上
*
* @param overlap
*/
public BGASwipeBackHelper setIsNavigationBarOverlap(boolean overlap) {
if (mSwipeBackLayout != null) {
mSwipeBackLayout.setIsNavigationBarOverlap(overlap);
}
return this;
}
/**
* 是否正在滑动
*
* @return
*/
public boolean isSliding() {
if (mSwipeBackLayout != null) {
return mSwipeBackLayout.isSliding();
}
return false;
}
/**
* 执行跳转到下一个 Activity 的动画
*/
public void executeForwardAnim() {
executeForwardAnim(mActivity);
}
/**
* 执行回到到上一个 Activity 的动画
*/
public void executeBackwardAnim() {
executeBackwardAnim(mActivity);
}
/**
* 执行滑动返回到到上一个 Activity 的动画
*/
public void executeSwipeBackAnim() {
executeSwipeBackAnim(mActivity);
}
/**
* 执行跳转到下一个 Activity 的动画。这里弄成静态方法,方便在 Fragment 中调用
*/
public static void executeForwardAnim(Activity activity) {
activity.overridePendingTransition(R.anim.bga_sbl_activity_forward_enter, R.anim.bga_sbl_activity_forward_exit);
}
/**
* 执行回到到上一个 Activity 的动画。这里弄成静态方法,方便在 Fragment 中调用
*/
public static void executeBackwardAnim(Activity activity) {
activity.overridePendingTransition(R.anim.bga_sbl_activity_backward_enter, R.anim.bga_sbl_activity_backward_exit);
}
/**
* 执行滑动返回到到上一个 Activity 的动画。这里弄成静态方法,方便在 Fragment 中调用
*/
public static void executeSwipeBackAnim(Activity activity) {
activity.overridePendingTransition(R.anim.bga_sbl_activity_swipeback_enter, R.anim.bga_sbl_activity_swipeback_exit);
}
/**
* 跳转到下一个 Activity,并且销毁当前 Activity
*
* @param cls 下一个 Activity 的 Class
*/
public void forwardAndFinish(Class<?> cls) {
forward(cls);
mActivity.finish();
}
/**
* 跳转到下一个 Activity,不销毁当前 Activity
*
* @param cls 下一个 Activity 的 Class
*/
public void forward(Class<?> cls) {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.startActivity(new Intent(mActivity, cls));
executeForwardAnim();
}
/**
* 跳转到下一个 Activity,不销毁当前 Activity
*
* @param cls 下一个 Activity 的 Class
* @param requestCode 请求码
*/
public void forward(Class<?> cls, int requestCode) {
forward(new Intent(mActivity, cls), requestCode);
}
/**
* 跳转到下一个 Activity,销毁当前 Activity
*
* @param intent 下一个 Activity 的意图对象
*/
public void forwardAndFinish(Intent intent) {
forward(intent);
mActivity.finish();
}
/**
* 跳转到下一个 Activity,不销毁当前 Activity
*
* @param intent 下一个 Activity 的意图对象
*/
public void forward(Intent intent) {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.startActivity(intent);
executeForwardAnim();
}
/**
* 跳转到下一个 Activity,不销毁当前 Activity
*
* @param intent 下一个 Activity 的意图对象
* @param requestCode 请求码
*/
public void forward(Intent intent, int requestCode) {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.startActivityForResult(intent, requestCode);
executeForwardAnim();
}
/**
* 回到上一个 Activity,并销毁当前 Activity
*/
public void backward() {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.finish();
executeBackwardAnim();
}
/**
* 滑动返回上一个 Activity,并销毁当前 Activity
*/
public void swipeBackward() {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.finish();
executeSwipeBackAnim();
}
/**
* 回到上一个 Activity,并销毁当前 Activity(应用场景:欢迎、登录、注册这三个界面)
*
* @param cls 上一个 Activity 的 Class
*/
public void backwardAndFinish(Class<?> cls) {
BGAKeyboardUtil.closeKeyboard(mActivity);
mActivity.startActivity(new Intent(mActivity, cls));
mActivity.finish();
executeBackwardAnim();
}
public interface Delegate {
/**
* 是否支持滑动返回
*
* @return
*/
boolean isSupportSwipeBack();
/**
* 正在滑动返回
*
* @param slideOffset 从 0 到 1
*/
void onSwipeBackLayoutSlide(float slideOffset);
/**
* 没达到滑动返回的阈值,取消滑动返回动作,回到默认状态
*/
void onSwipeBackLayoutCancel();
/**
* 滑动返回执行完毕,销毁当前 Activity
*/
void onSwipeBackLayoutExecuted();
}
}
| false | 2,413 | 10 | 2,582 | 11 | 2,707 | 8 | 2,582 | 11 | 3,595 | 24 | false | false | false | false | false | true |
60121_1 | package com.bingoabin.createtable;
import lombok.Data;
/**
* @author bingoabin
* @date 2021/6/15 1:45
*/
public class BuilderPattern {
//建造者模式:也叫作生成器模式,是一种创建型设计模式,可以使得我们分步骤创建复杂对象
//比如:创建一个房子,需要创建四面墙 地板等 房门 窗户 地板等
public static void main(String[] args) {
House build = new House.Builder().setWindow(new Window()).setDoor(new Door()).setWall(new Wall()).build();
}
}
@Data
//或者使用 @Builder
class House {
private Window window;
private Door door;
private Wall wall;
public House(Builder builder) {
this.window = builder.window;
this.door = builder.door;
this.wall = builder.wall;
}
static final class Builder {
private Window window;
private Door door;
private Wall wall;
public Builder setWindow(Window window) {
this.window = window;
return this;
}
public Builder setDoor(Door door) {
this.door = door;
return this;
}
public Builder setWall(Wall wall) {
this.wall = wall;
return this;
}
public House build() {
return new House(this);
}
}
}
class Window {
}
class Door {
}
class Wall {
}
| bingoxubin/CodeDemo | CodeDemo_DesignPattern/src/main/java/com/bingoabin/createtable/BuilderPattern.java | 390 | //建造者模式:也叫作生成器模式,是一种创建型设计模式,可以使得我们分步骤创建复杂对象 | line_comment | zh-cn | package com.bingoabin.createtable;
import lombok.Data;
/**
* @author bingoabin
* @date 2021/6/15 1:45
*/
public class BuilderPattern {
//建造 <SUF>
//比如:创建一个房子,需要创建四面墙 地板等 房门 窗户 地板等
public static void main(String[] args) {
House build = new House.Builder().setWindow(new Window()).setDoor(new Door()).setWall(new Wall()).build();
}
}
@Data
//或者使用 @Builder
class House {
private Window window;
private Door door;
private Wall wall;
public House(Builder builder) {
this.window = builder.window;
this.door = builder.door;
this.wall = builder.wall;
}
static final class Builder {
private Window window;
private Door door;
private Wall wall;
public Builder setWindow(Window window) {
this.window = window;
return this;
}
public Builder setDoor(Door door) {
this.door = door;
return this;
}
public Builder setWall(Wall wall) {
this.wall = wall;
return this;
}
public House build() {
return new House(this);
}
}
}
class Window {
}
class Door {
}
class Wall {
}
| false | 314 | 26 | 390 | 29 | 368 | 26 | 390 | 29 | 482 | 50 | false | false | false | false | false | true |
55845_0 | innnn/*
在当前序列中,从尾端往前寻找两个相邻元素,
前一个记为first,后一个记为second,
并且满足first 小于 second。
然后再从尾端寻找另一个元素number,
如果满足first 小于number,
即将第first个元素与number元素对调,
并将second元素之后(包括second)
的所有元素颠倒排序,
即求出下一个序列
example:
6,3,4,9,8,7,1
此时 first = 4,second = 9
从尾巴到前找到第一个大于first的数字,就是7
交换4和7,即上面的swap函数,
此时序列变成6,3,7,9,8,4,1
再将second=9以及以后的序列重新排序,
让其从小到大排序,使得整体最小,即reverse一下(因为此时肯定是递减序列)
*/
// time o(n)
// space o(1)
public class Solution{
public void nextPermutation(int[] nums){
// corner case
if(nums.length<=1) return;
int i = nums.length - 1;
for( ; i>=1 ;i--){
if(nums[i] > nums[i-1]) break;
}
if(i!=0) swap(nums,i-1);
reverse(nums,i);
}
private void swap(int[] a,int i){
for(int j = a.length-1;j>i;j--){
if(a[j]>a[i]){
int temp = a[j];
a[j] = a[i];
a[i] = temp;
break;
}
}
}
//reverse the number after the number we have found
//the orignal order is descending for sure
private void reverse(int[] a,int i){
int first = i;
int last = a.length-1;
while(first<last){
int temp = a[first];
a[first] = a[last];
a[last] = temp;
first ++;
last --;
}
}
}
| bingyuhu02/FaceBook-Intern-Leetcode | 31. Next Permutation/Solution.java | 513 | /*
在当前序列中,从尾端往前寻找两个相邻元素,
前一个记为first,后一个记为second,
并且满足first 小于 second。
然后再从尾端寻找另一个元素number,
如果满足first 小于number,
即将第first个元素与number元素对调,
并将second元素之后(包括second)
的所有元素颠倒排序,
即求出下一个序列
example:
6,3,4,9,8,7,1
此时 first = 4,second = 9
从尾巴到前找到第一个大于first的数字,就是7
交换4和7,即上面的swap函数,
此时序列变成6,3,7,9,8,4,1
再将second=9以及以后的序列重新排序,
让其从小到大排序,使得整体最小,即reverse一下(因为此时肯定是递减序列)
*/ | block_comment | zh-cn | innnn/*
在当前 <SUF>*/
// time o(n)
// space o(1)
public class Solution{
public void nextPermutation(int[] nums){
// corner case
if(nums.length<=1) return;
int i = nums.length - 1;
for( ; i>=1 ;i--){
if(nums[i] > nums[i-1]) break;
}
if(i!=0) swap(nums,i-1);
reverse(nums,i);
}
private void swap(int[] a,int i){
for(int j = a.length-1;j>i;j--){
if(a[j]>a[i]){
int temp = a[j];
a[j] = a[i];
a[i] = temp;
break;
}
}
}
//reverse the number after the number we have found
//the orignal order is descending for sure
private void reverse(int[] a,int i){
int first = i;
int last = a.length-1;
while(first<last){
int temp = a[first];
a[first] = a[last];
a[last] = temp;
first ++;
last --;
}
}
}
| false | 433 | 188 | 513 | 227 | 511 | 198 | 513 | 227 | 655 | 325 | false | false | false | false | false | true |
54914_5 | package doublepointers;
import java.util.Arrays;
/**
* LeetCode #1089 (Easy)
* @author binqibang
* @date 2022/6/17
*/
public class DuplicateZeros {
/**
* 暴力解法,碰到`0`后从后到前修改<br>
* Time: O(n^2); Space: O(1)
* @param arr
*/
public static void duplicateZeros1(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
for (int j = n - 1; j > i; j--) {
arr[j] = arr[j - 1];
}
i++;
}
}
}
/**
* 观察发现元素右移位数正是其左边`0`的个数<br>
* Time: O(n); Space: O(1)
* @param arr
*/
public static void duplicateZeros2(int[] arr) {
int n = arr.length;
// 统计`0`的个数
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
count++;
}
}
for (int i = n - 1; i >= 0; i--) {
// 左边`0`个数减1
if (arr[i] == 0) {
count--;
}
// 右移后在数组范围内
if (i + count < n) {
// 右移`count`位
arr[i + count] = arr[i];
// arr[i]为`0`,还需在之后补`0`
if (arr[i] == 0 && (i + count + 1) < n) {
arr[i + count + 1] = 0;
}
}
}
}
public static void main(String[] args) {
int[] test = new int[] {1,0,2,3,0,4,5,0};
int[] test1 = new int[] {0,1,1,7,6,0,0,2};
duplicateZeros1(test);
duplicateZeros2(test1);
System.out.println(Arrays.toString(test));
System.out.println(Arrays.toString(test1));
}
}
| binqibang/my-leetcode-solution | src/main/java/doublepointers/DuplicateZeros.java | 582 | // 右移后在数组范围内 | line_comment | zh-cn | package doublepointers;
import java.util.Arrays;
/**
* LeetCode #1089 (Easy)
* @author binqibang
* @date 2022/6/17
*/
public class DuplicateZeros {
/**
* 暴力解法,碰到`0`后从后到前修改<br>
* Time: O(n^2); Space: O(1)
* @param arr
*/
public static void duplicateZeros1(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
for (int j = n - 1; j > i; j--) {
arr[j] = arr[j - 1];
}
i++;
}
}
}
/**
* 观察发现元素右移位数正是其左边`0`的个数<br>
* Time: O(n); Space: O(1)
* @param arr
*/
public static void duplicateZeros2(int[] arr) {
int n = arr.length;
// 统计`0`的个数
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == 0) {
count++;
}
}
for (int i = n - 1; i >= 0; i--) {
// 左边`0`个数减1
if (arr[i] == 0) {
count--;
}
// 右移 <SUF>
if (i + count < n) {
// 右移`count`位
arr[i + count] = arr[i];
// arr[i]为`0`,还需在之后补`0`
if (arr[i] == 0 && (i + count + 1) < n) {
arr[i + count + 1] = 0;
}
}
}
}
public static void main(String[] args) {
int[] test = new int[] {1,0,2,3,0,4,5,0};
int[] test1 = new int[] {0,1,1,7,6,0,0,2};
duplicateZeros1(test);
duplicateZeros2(test1);
System.out.println(Arrays.toString(test));
System.out.println(Arrays.toString(test1));
}
}
| false | 546 | 8 | 582 | 9 | 619 | 7 | 582 | 9 | 676 | 15 | false | false | false | false | false | true |
63570_0 | package com.binrui.shop.pay.alipay.sign;
import java.io.UnsupportedEncodingException;
import java.security.SignatureException;
import org.apache.commons.codec.digest.DigestUtils;
/**
* 功能:支付宝MD5签名处理核心文件,不需要修改
* 版本:3.3
* 修改日期:2012-08-17
* 说明:
* 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
* 该代码仅供学习和研究支付宝接口使用,只是提供一个
* */
public class MD5 {
/**
* 签名字符串
* @param text 需要签名的字符串
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static String sign(String text, String key, String input_charset) {
text = text + key;
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}
/**
* 签名字符串
* @param text 需要签名的字符串
* @param sign 签名结果
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static boolean verify(String text, String sign, String key, String input_charset) {
text = text + key;
String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
if(mysign.equals(sign)) {
return true;
}
else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
} | binrui/shopping | src/com/binrui/shop/pay/alipay/sign/MD5.java | 520 | /**
* 功能:支付宝MD5签名处理核心文件,不需要修改
* 版本:3.3
* 修改日期:2012-08-17
* 说明:
* 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
* 该代码仅供学习和研究支付宝接口使用,只是提供一个
* */ | block_comment | zh-cn | package com.binrui.shop.pay.alipay.sign;
import java.io.UnsupportedEncodingException;
import java.security.SignatureException;
import org.apache.commons.codec.digest.DigestUtils;
/**
* 功能: <SUF>*/
public class MD5 {
/**
* 签名字符串
* @param text 需要签名的字符串
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static String sign(String text, String key, String input_charset) {
text = text + key;
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}
/**
* 签名字符串
* @param text 需要签名的字符串
* @param sign 签名结果
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static boolean verify(String text, String sign, String key, String input_charset) {
text = text + key;
String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
if(mysign.equals(sign)) {
return true;
}
else {
return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
} | false | 490 | 95 | 511 | 107 | 549 | 96 | 511 | 107 | 731 | 174 | false | false | false | false | false | true |
12302_1 | package com.larkmt.cn.admin.util;
/**
* DBUtilErrorCode
*/
public enum DBUtilErrorCode implements ErrorCode {
//连接错误
MYSQL_CONN_USERPWD_ERROR("MYSQLErrCode-01","数据库用户名或者密码错误,请检查填写的账号密码或者联系DBA确认账号和密码是否正确"),
MYSQL_CONN_IPPORT_ERROR("MYSQLErrCode-02","数据库服务的IP地址或者Port错误,请检查填写的IP地址和Port或者联系DBA确认IP地址和Port是否正确。如果是同步中心用户请联系DBA确认idb上录入的IP和PORT信息和数据库的当前实际信息是一致的"),
MYSQL_CONN_DB_ERROR("MYSQLErrCode-03","数据库名称错误,请检查数据库实例名称或者联系DBA确认该实例是否存在并且在正常服务"),
ORACLE_CONN_USERPWD_ERROR("ORACLEErrCode-01","数据库用户名或者密码错误,请检查填写的账号密码或者联系DBA确认账号和密码是否正确"),
ORACLE_CONN_IPPORT_ERROR("ORACLEErrCode-02","数据库服务的IP地址或者Port错误,请检查填写的IP地址和Port或者联系DBA确认IP地址和Port是否正确。如果是同步中心用户请联系DBA确认idb上录入的IP和PORT信息和数据库的当前实际信息是一致的"),
ORACLE_CONN_DB_ERROR("ORACLEErrCode-03","数据库名称错误,请检查数据库实例名称或者联系DBA确认该实例是否存在并且在正常服务"),
//execute query错误
MYSQL_QUERY_TABLE_NAME_ERROR("MYSQLErrCode-04","表不存在,请检查表名或者联系DBA确认该表是否存在"),
MYSQL_QUERY_SQL_ERROR("MYSQLErrCode-05","SQL语句执行出错,请检查Where条件是否存在拼写或语法错误"),
MYSQL_QUERY_COLUMN_ERROR("MYSQLErrCode-06","Column信息错误,请检查该列是否存在,如果是常量或者变量,请使用英文单引号’包起来"),
MYSQL_QUERY_SELECT_PRI_ERROR("MYSQLErrCode-07","读表数据出错,因为账号没有读表的权限,请联系DBA确认该账号的权限并授权"),
ORACLE_QUERY_TABLE_NAME_ERROR("ORACLEErrCode-04","表不存在,请检查表名或者联系DBA确认该表是否存在"),
ORACLE_QUERY_SQL_ERROR("ORACLEErrCode-05","SQL语句执行出错,原因可能是你填写的列不存在或者where条件不符合要求,1,请检查该列是否存在,如果是常量或者变量,请使用英文单引号’包起来; 2,请检查Where条件是否存在拼写或语法错误"),
ORACLE_QUERY_SELECT_PRI_ERROR("ORACLEErrCode-06","读表数据出错,因为账号没有读表的权限,请联系DBA确认该账号的权限并授权"),
ORACLE_QUERY_SQL_PARSER_ERROR("ORACLEErrCode-07","SQL语法出错,请检查Where条件是否存在拼写或语法错误"),
//PreSql,PostSql错误
MYSQL_PRE_SQL_ERROR("MYSQLErrCode-08","PreSQL语法错误,请检查"),
MYSQL_POST_SQL_ERROR("MYSQLErrCode-09","PostSql语法错误,请检查"),
MYSQL_QUERY_SQL_PARSER_ERROR("MYSQLErrCode-10","SQL语法出错,请检查Where条件是否存在拼写或语法错误"),
ORACLE_PRE_SQL_ERROR("ORACLEErrCode-08", "PreSQL语法错误,请检查"),
ORACLE_POST_SQL_ERROR("ORACLEErrCode-09", "PostSql语法错误,请检查"),
//SplitPK 错误
MYSQL_SPLIT_PK_ERROR("MYSQLErrCode-11","SplitPK错误,请检查"),
ORACLE_SPLIT_PK_ERROR("ORACLEErrCode-10","SplitPK错误,请检查"),
//Insert,Delete 权限错误
MYSQL_INSERT_ERROR("MYSQLErrCode-12","数据库没有写权限,请联系DBA"),
MYSQL_DELETE_ERROR("MYSQLErrCode-13","数据库没有Delete权限,请联系DBA"),
ORACLE_INSERT_ERROR("ORACLEErrCode-11","数据库没有写权限,请联系DBA"),
ORACLE_DELETE_ERROR("ORACLEErrCode-12","数据库没有Delete权限,请联系DBA"),
JDBC_NULL("DBUtilErrorCode-20","JDBC URL为空,请检查配置"),
JDBC_OB10_ADDRESS_ERROR("DBUtilErrorCode-OB10-01","JDBC OB10格式错误,请联系askflinkx"),
CONF_ERROR("DBUtilErrorCode-00", "您的配置错误."),
CONN_DB_ERROR("DBUtilErrorCode-10", "连接数据库失败. 请检查您的 账号、密码、数据库名称、IP、Port或者向 DBA 寻求帮助(注意网络环境)."),
GET_COLUMN_INFO_FAILED("DBUtilErrorCode-01", "获取表字段相关信息失败."),
UNSUPPORTED_TYPE("DBUtilErrorCode-12", "不支持的数据库类型. 请注意查看 FlinkX 已经支持的数据库类型以及数据库版本."),
COLUMN_SPLIT_ERROR("DBUtilErrorCode-13", "根据主键进行切分失败."),
SET_SESSION_ERROR("DBUtilErrorCode-14", "设置 session 失败."),
RS_ASYNC_ERROR("DBUtilErrorCode-15", "异步获取ResultSet next失败."),
REQUIRED_VALUE("DBUtilErrorCode-03", "您缺失了必须填写的参数值."),
ILLEGAL_VALUE("DBUtilErrorCode-02", "您填写的参数值不合法."),
ILLEGAL_SPLIT_PK("DBUtilErrorCode-04", "您填写的主键列不合法, FlinkX 仅支持切分主键为一个,并且类型为整数或者字符串类型."),
SPLIT_FAILED_ILLEGAL_SQL("DBUtilErrorCode-15", "FlinkX尝试切分表时, 执行数据库 Sql 失败. 请检查您的配置 table/splitPk/where 并作出修改."),
SQL_EXECUTE_FAIL("DBUtilErrorCode-06", "执行数据库 Sql 失败, 请检查您的配置的 column/table/where/querySql或者向 DBA 寻求帮助."),
// only for reader
READ_RECORD_FAIL("DBUtilErrorCode-07", "读取数据库数据失败. 请检查您的配置的 column/table/where/querySql或者向 DBA 寻求帮助."),
TABLE_QUERYSQL_MIXED("DBUtilErrorCode-08", "您配置凌乱了. 不能同时既配置table又配置querySql"),
TABLE_QUERYSQL_MISSING("DBUtilErrorCode-09", "您配置错误. table和querySql 应该并且只能配置一个."),
// only for writer
WRITE_DATA_ERROR("DBUtilErrorCode-05", "往您配置的写入表中写入数据时失败."),
NO_INSERT_PRIVILEGE("DBUtilErrorCode-11", "数据库没有写权限,请联系DBA"),
NO_DELETE_PRIVILEGE("DBUtilErrorCode-16", "数据库没有DELETE权限,请联系DBA"),
;
private final String code;
private final String description;
private DBUtilErrorCode(String code, String description) {
this.code = code;
this.description = description;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public String toString() {
return String.format("Code:[%s], Description:[%s]. ", this.code,
this.description);
}
}
| birdLark/LarkMidTable | larkmidtable-web/larkmt-admin/src/main/java/com/larkmt/cn/admin/util/DBUtilErrorCode.java | 1,830 | //连接错误 | line_comment | zh-cn | package com.larkmt.cn.admin.util;
/**
* DBUtilErrorCode
*/
public enum DBUtilErrorCode implements ErrorCode {
//连接 <SUF>
MYSQL_CONN_USERPWD_ERROR("MYSQLErrCode-01","数据库用户名或者密码错误,请检查填写的账号密码或者联系DBA确认账号和密码是否正确"),
MYSQL_CONN_IPPORT_ERROR("MYSQLErrCode-02","数据库服务的IP地址或者Port错误,请检查填写的IP地址和Port或者联系DBA确认IP地址和Port是否正确。如果是同步中心用户请联系DBA确认idb上录入的IP和PORT信息和数据库的当前实际信息是一致的"),
MYSQL_CONN_DB_ERROR("MYSQLErrCode-03","数据库名称错误,请检查数据库实例名称或者联系DBA确认该实例是否存在并且在正常服务"),
ORACLE_CONN_USERPWD_ERROR("ORACLEErrCode-01","数据库用户名或者密码错误,请检查填写的账号密码或者联系DBA确认账号和密码是否正确"),
ORACLE_CONN_IPPORT_ERROR("ORACLEErrCode-02","数据库服务的IP地址或者Port错误,请检查填写的IP地址和Port或者联系DBA确认IP地址和Port是否正确。如果是同步中心用户请联系DBA确认idb上录入的IP和PORT信息和数据库的当前实际信息是一致的"),
ORACLE_CONN_DB_ERROR("ORACLEErrCode-03","数据库名称错误,请检查数据库实例名称或者联系DBA确认该实例是否存在并且在正常服务"),
//execute query错误
MYSQL_QUERY_TABLE_NAME_ERROR("MYSQLErrCode-04","表不存在,请检查表名或者联系DBA确认该表是否存在"),
MYSQL_QUERY_SQL_ERROR("MYSQLErrCode-05","SQL语句执行出错,请检查Where条件是否存在拼写或语法错误"),
MYSQL_QUERY_COLUMN_ERROR("MYSQLErrCode-06","Column信息错误,请检查该列是否存在,如果是常量或者变量,请使用英文单引号’包起来"),
MYSQL_QUERY_SELECT_PRI_ERROR("MYSQLErrCode-07","读表数据出错,因为账号没有读表的权限,请联系DBA确认该账号的权限并授权"),
ORACLE_QUERY_TABLE_NAME_ERROR("ORACLEErrCode-04","表不存在,请检查表名或者联系DBA确认该表是否存在"),
ORACLE_QUERY_SQL_ERROR("ORACLEErrCode-05","SQL语句执行出错,原因可能是你填写的列不存在或者where条件不符合要求,1,请检查该列是否存在,如果是常量或者变量,请使用英文单引号’包起来; 2,请检查Where条件是否存在拼写或语法错误"),
ORACLE_QUERY_SELECT_PRI_ERROR("ORACLEErrCode-06","读表数据出错,因为账号没有读表的权限,请联系DBA确认该账号的权限并授权"),
ORACLE_QUERY_SQL_PARSER_ERROR("ORACLEErrCode-07","SQL语法出错,请检查Where条件是否存在拼写或语法错误"),
//PreSql,PostSql错误
MYSQL_PRE_SQL_ERROR("MYSQLErrCode-08","PreSQL语法错误,请检查"),
MYSQL_POST_SQL_ERROR("MYSQLErrCode-09","PostSql语法错误,请检查"),
MYSQL_QUERY_SQL_PARSER_ERROR("MYSQLErrCode-10","SQL语法出错,请检查Where条件是否存在拼写或语法错误"),
ORACLE_PRE_SQL_ERROR("ORACLEErrCode-08", "PreSQL语法错误,请检查"),
ORACLE_POST_SQL_ERROR("ORACLEErrCode-09", "PostSql语法错误,请检查"),
//SplitPK 错误
MYSQL_SPLIT_PK_ERROR("MYSQLErrCode-11","SplitPK错误,请检查"),
ORACLE_SPLIT_PK_ERROR("ORACLEErrCode-10","SplitPK错误,请检查"),
//Insert,Delete 权限错误
MYSQL_INSERT_ERROR("MYSQLErrCode-12","数据库没有写权限,请联系DBA"),
MYSQL_DELETE_ERROR("MYSQLErrCode-13","数据库没有Delete权限,请联系DBA"),
ORACLE_INSERT_ERROR("ORACLEErrCode-11","数据库没有写权限,请联系DBA"),
ORACLE_DELETE_ERROR("ORACLEErrCode-12","数据库没有Delete权限,请联系DBA"),
JDBC_NULL("DBUtilErrorCode-20","JDBC URL为空,请检查配置"),
JDBC_OB10_ADDRESS_ERROR("DBUtilErrorCode-OB10-01","JDBC OB10格式错误,请联系askflinkx"),
CONF_ERROR("DBUtilErrorCode-00", "您的配置错误."),
CONN_DB_ERROR("DBUtilErrorCode-10", "连接数据库失败. 请检查您的 账号、密码、数据库名称、IP、Port或者向 DBA 寻求帮助(注意网络环境)."),
GET_COLUMN_INFO_FAILED("DBUtilErrorCode-01", "获取表字段相关信息失败."),
UNSUPPORTED_TYPE("DBUtilErrorCode-12", "不支持的数据库类型. 请注意查看 FlinkX 已经支持的数据库类型以及数据库版本."),
COLUMN_SPLIT_ERROR("DBUtilErrorCode-13", "根据主键进行切分失败."),
SET_SESSION_ERROR("DBUtilErrorCode-14", "设置 session 失败."),
RS_ASYNC_ERROR("DBUtilErrorCode-15", "异步获取ResultSet next失败."),
REQUIRED_VALUE("DBUtilErrorCode-03", "您缺失了必须填写的参数值."),
ILLEGAL_VALUE("DBUtilErrorCode-02", "您填写的参数值不合法."),
ILLEGAL_SPLIT_PK("DBUtilErrorCode-04", "您填写的主键列不合法, FlinkX 仅支持切分主键为一个,并且类型为整数或者字符串类型."),
SPLIT_FAILED_ILLEGAL_SQL("DBUtilErrorCode-15", "FlinkX尝试切分表时, 执行数据库 Sql 失败. 请检查您的配置 table/splitPk/where 并作出修改."),
SQL_EXECUTE_FAIL("DBUtilErrorCode-06", "执行数据库 Sql 失败, 请检查您的配置的 column/table/where/querySql或者向 DBA 寻求帮助."),
// only for reader
READ_RECORD_FAIL("DBUtilErrorCode-07", "读取数据库数据失败. 请检查您的配置的 column/table/where/querySql或者向 DBA 寻求帮助."),
TABLE_QUERYSQL_MIXED("DBUtilErrorCode-08", "您配置凌乱了. 不能同时既配置table又配置querySql"),
TABLE_QUERYSQL_MISSING("DBUtilErrorCode-09", "您配置错误. table和querySql 应该并且只能配置一个."),
// only for writer
WRITE_DATA_ERROR("DBUtilErrorCode-05", "往您配置的写入表中写入数据时失败."),
NO_INSERT_PRIVILEGE("DBUtilErrorCode-11", "数据库没有写权限,请联系DBA"),
NO_DELETE_PRIVILEGE("DBUtilErrorCode-16", "数据库没有DELETE权限,请联系DBA"),
;
private final String code;
private final String description;
private DBUtilErrorCode(String code, String description) {
this.code = code;
this.description = description;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getDescription() {
return this.description;
}
@Override
public String toString() {
return String.format("Code:[%s], Description:[%s]. ", this.code,
this.description);
}
}
| false | 1,650 | 3 | 1,830 | 3 | 1,803 | 3 | 1,830 | 3 | 2,731 | 7 | false | false | false | false | false | true |
30297_20 | package PoC;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.PrintWriter;
import java.net.URI;
import java.util.Arrays;
import java.util.Map;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableRowSorter;
import GUI.MainGUI;
import GUI.TextAreaMouseListener;
import GUI.textAreaDocumentListener;
import PoC.search.History;
import PoC.search.LineSearch;
import burp.BurpExtender;
import burp.Commons;
import burp.GlobalConfig;
public class LineTable extends JTable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private TableRowSorter<LineTableModel> rowSorter;//TableRowSorter vs. RowSorter
PrintWriter stdout;
PrintWriter stderr;
private JSplitPane tableAndDetailSplitPane;//table area + detail area
private JTextArea textAreaTarget;
private JTextArea textAreaPoCDetail;
public JSplitPane getTableAndDetailSplitPane() {
return tableAndDetailSplitPane;
}
public JTextArea getTextAreaTarget() {
return textAreaTarget;
}
public void setTextAreaTarget(JTextArea textAreaTarget) {
this.textAreaTarget = textAreaTarget;
}
public JTextArea getTextAreaPoCDetail() {
return textAreaPoCDetail;
}
public void setTextAreaPoCDetail(JTextArea textAreaPoCDetail) {
this.textAreaPoCDetail = textAreaPoCDetail;
}
//将选中的行(图形界面的行)转换为Model中的行数(数据队列中的index).因为图形界面排序等操作会导致图像和数据队列的index不是线性对应的。
public int[] SelectedRowsToModelRows(int[] SelectedRows) {
int[] rows = SelectedRows;
for (int i=0; i < rows.length; i++){
rows[i] = convertRowIndexToModel(rows[i]);//转换为Model的索引,否则排序后索引不对应〿
}
Arrays.sort(rows);//升序
return rows;
}
public LineTable(LineTableModel lineTableModel)
{
//super(lineTableModel);//这个方法创建的表没有header
try{
stdout = new PrintWriter(BurpExtender.getCallbacks().getStdout(), true);
stderr = new PrintWriter(BurpExtender.getCallbacks().getStderr(), true);
}catch (Exception e){
stdout = new PrintWriter(System.out, true);
stderr = new PrintWriter(System.out, true);
}
this.setFillsViewportHeight(true);//在table的空白区域显示右键菜单
//https://stackoverflow.com/questions/8903040/right-click-mouselistener-on-whole-jtable-component
this.setModel(lineTableModel);
tableinit();
//FitTableColumns(this);
addClickSort();
registerListeners();
tableAndDetailSplitPane = tableAndDetailPanel();
}
public LineTableModel getLineTabelModel() {
return (LineTableModel)this.getModel();
}
@Override
public void changeSelection(int row, int col, boolean toggle, boolean extend)
{
// show the log entry for the selected row
LineEntry Entry = getLineTabelModel().getLineEntries().getValueAtIndex(super.convertRowIndexToModel(row));
getLineTabelModel().setCurrentlyDisplayedItem(Entry);
String detail = Entry.getDetail();
textAreaPoCDetail.setText(detail);
super.changeSelection(row, col, toggle, extend);
}
public JSplitPane tableAndDetailPanel(){
JSplitPane splitPane = new JSplitPane();//table area + detail area
splitPane.setResizeWeight(0.4);
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
//TitlePanel.add(splitPane, BorderLayout.CENTER); // getTitlePanel to get it
JScrollPane scrollPaneRequests = new JScrollPane(this,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);//table area
//允许横向滚动条
//scrollPaneRequests.setViewportView(titleTable);//titleTable should lay here.
splitPane.setLeftComponent(scrollPaneRequests);
JSplitPane RequestDetailPanel = new JSplitPane();//request and response
RequestDetailPanel.setResizeWeight(0.4);
splitPane.setRightComponent(RequestDetailPanel);
JTabbedPane RequestPanel = new JTabbedPane();
RequestDetailPanel.setLeftComponent(RequestPanel);
JScrollPane scrollPane = new JScrollPane();
RequestPanel.addTab("targets", null, scrollPane, null);
textAreaTarget = new JTextArea();
scrollPane.setViewportView(textAreaTarget);
textAreaTarget.addMouseListener(new TextAreaMouseListener(textAreaTarget));
GlobalConfig config = MainGUI.getGlobalConfig();
if (config != null) {
textAreaTarget.getDocument().addDocumentListener(new textAreaDocumentListener(textAreaTarget,config));
}
JTabbedPane ResponsePanel = new JTabbedPane();
RequestDetailPanel.setRightComponent(ResponsePanel);
JScrollPane scrollPane1 = new JScrollPane();
ResponsePanel.addTab("detail", null, scrollPane1, null);
textAreaPoCDetail = new JTextArea();
textAreaPoCDetail.setLineWrap(true);
scrollPane1.setViewportView(textAreaPoCDetail);
textAreaPoCDetail.addMouseListener(new TextAreaMouseListener(textAreaPoCDetail));
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);//配合横向滚动条
return splitPane;
}
public void tableinit(){
//Font f = new Font("Arial", Font.PLAIN, 12);
Font f = this.getFont();
FontMetrics fm = this.getFontMetrics(f);
int width = fm.stringWidth("A");//一个字符的宽度
Map<String,Integer> preferredWidths = LineEntry.fetchTableHeaderAndWidth();
for(String header:LineTableModel.getTitletList()){
try{//避免动态删除表字段时,出错
int multiNumber = preferredWidths.get(header);
this.getColumnModel().getColumn(this.getColumnModel().getColumnIndex(header))
.setPreferredWidth(width*multiNumber);
}catch (Exception e){
}
}
//this.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);//配合横向滚动条
}
public void addClickSort() {//双击header头进行排序
rowSorter = new TableRowSorter<LineTableModel>(getLineTabelModel());//排序和搜索
LineTable.this.setRowSorter(rowSorter);
JTableHeader header = this.getTableHeader();
header.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
LineTable.this.getRowSorter().getSortKeys().get(0).getColumn();
////当Jtable中无数据时,jtable.getRowSorter()是nul
} catch (Exception e1) {
e1.printStackTrace(stderr);
}
}
});
}
//搜索功能函数
public void search(String Input) {
History.getInstance().addRecord(Input);//记录搜索历史,单例模式
final RowFilter filter = new RowFilter() {
@Override
public boolean include(Entry entry) {
//entry --- a non-null object that wraps the underlying object from the model
int row = (int) entry.getIdentifier();
LineEntry line = rowSorter.getModel().getLineEntries().getValueAtIndex(row);
//目前只处理&&(and)逻辑的表达式
if (Input.contains("&&")) {
String[] searchConditions = Input.split("&&");
for (String condition:searchConditions) {
if (oneCondition(condition,line)) {
continue;
}else {
return false;
}
}
return true;
}else {
return oneCondition(Input,line);
}
}
public boolean oneCondition(String Input,LineEntry line) {
Input = Input.toLowerCase();
return LineSearch.textFilter(line,Input);
}
};
rowSorter.setRowFilter(filter);
}
public void registerListeners(){
LineTable.this.setRowSelectionAllowed(true);
this.addMouseListener( new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e) {
//双击进行google搜索、双击浏览器打开url、双击切换Check状态
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2){//左键双击
int[] rows = SelectedRowsToModelRows(getSelectedRows());
//int row = ((LineTable) e.getSource()).rowAtPoint(e.getPoint()); // 获得行位置
int col = ((LineTable) e.getSource()).columnAtPoint(e.getPoint()); // 获得列位置
LineEntry selecteEntry = LineTable.this.getLineTabelModel().getLineEntries().getValueAtIndex(rows[0]);
if (col==0) {//双击Index 搜索CVE字段
String cve = selecteEntry.getCVE();
String url= "https://www.google.com/search?q="+cve;
try {
URI uri = new URI(url);
Desktop desktop = Desktop.getDesktop();
if(Desktop.isDesktopSupported()&&desktop.isSupported(Desktop.Action.BROWSE)){
desktop.browse(uri);
}
} catch (Exception e2) {
e2.printStackTrace();
}
}else if(col==1){//双击文件名。打开文件
String path = selecteEntry.getPocFileFullPath();
Commons.editWithVSCode(path);
}else{
String value = LineTable.this.getLineTabelModel().getValueAt(rows[0],col).toString();
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection selection = new StringSelection(value);
clipboard.setContents(selection, null);
}
}
}
@Override//title表格中的鼠标右键菜单
public void mouseReleased(MouseEvent e){
if ( SwingUtilities.isRightMouseButton( e )){
if (e.isPopupTrigger() && e.getComponent() instanceof JTable ) {
//getSelectionModel().setSelectionInterval(rows[0], rows[1]);
int[] rows = getSelectedRows();
int col = ((LineTable) e.getSource()).columnAtPoint(e.getPoint()); // 获得列位置
if (rows.length>0){
rows = SelectedRowsToModelRows(getSelectedRows());
new LineEntryMenu(LineTable.this, rows, col).show(e.getComponent(), e.getX(), e.getY());
}else{//在table的空白处显示右键菜单
//https://stackoverflow.com/questions/8903040/right-click-mouselistener-on-whole-jtable-component
//new LineEntryMenu(_this).show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
@Override
public void mousePressed(MouseEvent e) {
mouseReleased(e);
}
});
}
}
| bit4woo/Fiora | src/PoC/LineTable.java | 2,897 | //配合横向滚动条 | line_comment | zh-cn | package PoC;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.PrintWriter;
import java.net.URI;
import java.util.Arrays;
import java.util.Map;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.RowFilter;
import javax.swing.SwingUtilities;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableRowSorter;
import GUI.MainGUI;
import GUI.TextAreaMouseListener;
import GUI.textAreaDocumentListener;
import PoC.search.History;
import PoC.search.LineSearch;
import burp.BurpExtender;
import burp.Commons;
import burp.GlobalConfig;
public class LineTable extends JTable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private TableRowSorter<LineTableModel> rowSorter;//TableRowSorter vs. RowSorter
PrintWriter stdout;
PrintWriter stderr;
private JSplitPane tableAndDetailSplitPane;//table area + detail area
private JTextArea textAreaTarget;
private JTextArea textAreaPoCDetail;
public JSplitPane getTableAndDetailSplitPane() {
return tableAndDetailSplitPane;
}
public JTextArea getTextAreaTarget() {
return textAreaTarget;
}
public void setTextAreaTarget(JTextArea textAreaTarget) {
this.textAreaTarget = textAreaTarget;
}
public JTextArea getTextAreaPoCDetail() {
return textAreaPoCDetail;
}
public void setTextAreaPoCDetail(JTextArea textAreaPoCDetail) {
this.textAreaPoCDetail = textAreaPoCDetail;
}
//将选中的行(图形界面的行)转换为Model中的行数(数据队列中的index).因为图形界面排序等操作会导致图像和数据队列的index不是线性对应的。
public int[] SelectedRowsToModelRows(int[] SelectedRows) {
int[] rows = SelectedRows;
for (int i=0; i < rows.length; i++){
rows[i] = convertRowIndexToModel(rows[i]);//转换为Model的索引,否则排序后索引不对应〿
}
Arrays.sort(rows);//升序
return rows;
}
public LineTable(LineTableModel lineTableModel)
{
//super(lineTableModel);//这个方法创建的表没有header
try{
stdout = new PrintWriter(BurpExtender.getCallbacks().getStdout(), true);
stderr = new PrintWriter(BurpExtender.getCallbacks().getStderr(), true);
}catch (Exception e){
stdout = new PrintWriter(System.out, true);
stderr = new PrintWriter(System.out, true);
}
this.setFillsViewportHeight(true);//在table的空白区域显示右键菜单
//https://stackoverflow.com/questions/8903040/right-click-mouselistener-on-whole-jtable-component
this.setModel(lineTableModel);
tableinit();
//FitTableColumns(this);
addClickSort();
registerListeners();
tableAndDetailSplitPane = tableAndDetailPanel();
}
public LineTableModel getLineTabelModel() {
return (LineTableModel)this.getModel();
}
@Override
public void changeSelection(int row, int col, boolean toggle, boolean extend)
{
// show the log entry for the selected row
LineEntry Entry = getLineTabelModel().getLineEntries().getValueAtIndex(super.convertRowIndexToModel(row));
getLineTabelModel().setCurrentlyDisplayedItem(Entry);
String detail = Entry.getDetail();
textAreaPoCDetail.setText(detail);
super.changeSelection(row, col, toggle, extend);
}
public JSplitPane tableAndDetailPanel(){
JSplitPane splitPane = new JSplitPane();//table area + detail area
splitPane.setResizeWeight(0.4);
splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
//TitlePanel.add(splitPane, BorderLayout.CENTER); // getTitlePanel to get it
JScrollPane scrollPaneRequests = new JScrollPane(this,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);//table area
//允许横向滚动条
//scrollPaneRequests.setViewportView(titleTable);//titleTable should lay here.
splitPane.setLeftComponent(scrollPaneRequests);
JSplitPane RequestDetailPanel = new JSplitPane();//request and response
RequestDetailPanel.setResizeWeight(0.4);
splitPane.setRightComponent(RequestDetailPanel);
JTabbedPane RequestPanel = new JTabbedPane();
RequestDetailPanel.setLeftComponent(RequestPanel);
JScrollPane scrollPane = new JScrollPane();
RequestPanel.addTab("targets", null, scrollPane, null);
textAreaTarget = new JTextArea();
scrollPane.setViewportView(textAreaTarget);
textAreaTarget.addMouseListener(new TextAreaMouseListener(textAreaTarget));
GlobalConfig config = MainGUI.getGlobalConfig();
if (config != null) {
textAreaTarget.getDocument().addDocumentListener(new textAreaDocumentListener(textAreaTarget,config));
}
JTabbedPane ResponsePanel = new JTabbedPane();
RequestDetailPanel.setRightComponent(ResponsePanel);
JScrollPane scrollPane1 = new JScrollPane();
ResponsePanel.addTab("detail", null, scrollPane1, null);
textAreaPoCDetail = new JTextArea();
textAreaPoCDetail.setLineWrap(true);
scrollPane1.setViewportView(textAreaPoCDetail);
textAreaPoCDetail.addMouseListener(new TextAreaMouseListener(textAreaPoCDetail));
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);//配合横向滚动条
return splitPane;
}
public void tableinit(){
//Font f = new Font("Arial", Font.PLAIN, 12);
Font f = this.getFont();
FontMetrics fm = this.getFontMetrics(f);
int width = fm.stringWidth("A");//一个字符的宽度
Map<String,Integer> preferredWidths = LineEntry.fetchTableHeaderAndWidth();
for(String header:LineTableModel.getTitletList()){
try{//避免动态删除表字段时,出错
int multiNumber = preferredWidths.get(header);
this.getColumnModel().getColumn(this.getColumnModel().getColumnIndex(header))
.setPreferredWidth(width*multiNumber);
}catch (Exception e){
}
}
//this.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
this.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);//配合 <SUF>
}
public void addClickSort() {//双击header头进行排序
rowSorter = new TableRowSorter<LineTableModel>(getLineTabelModel());//排序和搜索
LineTable.this.setRowSorter(rowSorter);
JTableHeader header = this.getTableHeader();
header.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
try {
LineTable.this.getRowSorter().getSortKeys().get(0).getColumn();
////当Jtable中无数据时,jtable.getRowSorter()是nul
} catch (Exception e1) {
e1.printStackTrace(stderr);
}
}
});
}
//搜索功能函数
public void search(String Input) {
History.getInstance().addRecord(Input);//记录搜索历史,单例模式
final RowFilter filter = new RowFilter() {
@Override
public boolean include(Entry entry) {
//entry --- a non-null object that wraps the underlying object from the model
int row = (int) entry.getIdentifier();
LineEntry line = rowSorter.getModel().getLineEntries().getValueAtIndex(row);
//目前只处理&&(and)逻辑的表达式
if (Input.contains("&&")) {
String[] searchConditions = Input.split("&&");
for (String condition:searchConditions) {
if (oneCondition(condition,line)) {
continue;
}else {
return false;
}
}
return true;
}else {
return oneCondition(Input,line);
}
}
public boolean oneCondition(String Input,LineEntry line) {
Input = Input.toLowerCase();
return LineSearch.textFilter(line,Input);
}
};
rowSorter.setRowFilter(filter);
}
public void registerListeners(){
LineTable.this.setRowSelectionAllowed(true);
this.addMouseListener( new MouseAdapter()
{
@Override
public void mouseClicked(MouseEvent e) {
//双击进行google搜索、双击浏览器打开url、双击切换Check状态
if (SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2){//左键双击
int[] rows = SelectedRowsToModelRows(getSelectedRows());
//int row = ((LineTable) e.getSource()).rowAtPoint(e.getPoint()); // 获得行位置
int col = ((LineTable) e.getSource()).columnAtPoint(e.getPoint()); // 获得列位置
LineEntry selecteEntry = LineTable.this.getLineTabelModel().getLineEntries().getValueAtIndex(rows[0]);
if (col==0) {//双击Index 搜索CVE字段
String cve = selecteEntry.getCVE();
String url= "https://www.google.com/search?q="+cve;
try {
URI uri = new URI(url);
Desktop desktop = Desktop.getDesktop();
if(Desktop.isDesktopSupported()&&desktop.isSupported(Desktop.Action.BROWSE)){
desktop.browse(uri);
}
} catch (Exception e2) {
e2.printStackTrace();
}
}else if(col==1){//双击文件名。打开文件
String path = selecteEntry.getPocFileFullPath();
Commons.editWithVSCode(path);
}else{
String value = LineTable.this.getLineTabelModel().getValueAt(rows[0],col).toString();
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection selection = new StringSelection(value);
clipboard.setContents(selection, null);
}
}
}
@Override//title表格中的鼠标右键菜单
public void mouseReleased(MouseEvent e){
if ( SwingUtilities.isRightMouseButton( e )){
if (e.isPopupTrigger() && e.getComponent() instanceof JTable ) {
//getSelectionModel().setSelectionInterval(rows[0], rows[1]);
int[] rows = getSelectedRows();
int col = ((LineTable) e.getSource()).columnAtPoint(e.getPoint()); // 获得列位置
if (rows.length>0){
rows = SelectedRowsToModelRows(getSelectedRows());
new LineEntryMenu(LineTable.this, rows, col).show(e.getComponent(), e.getX(), e.getY());
}else{//在table的空白处显示右键菜单
//https://stackoverflow.com/questions/8903040/right-click-mouselistener-on-whole-jtable-component
//new LineEntryMenu(_this).show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
@Override
public void mousePressed(MouseEvent e) {
mouseReleased(e);
}
});
}
}
| false | 2,455 | 5 | 2,897 | 9 | 2,792 | 6 | 2,897 | 9 | 3,808 | 12 | false | false | false | false | false | true |
20407_0 | package custom;
import javax.swing.*;
public class Ctest {
/**
* 创建并显示GUI。 出于线程安全的考虑,
* 这个方法在事件调用线程中调用。
*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
} | bit4woo/GUI_Burp_Extender_para_encrypter | src/custom/Ctest.java | 241 | /**
* 创建并显示GUI。 出于线程安全的考虑,
* 这个方法在事件调用线程中调用。
*/ | block_comment | zh-cn | package custom;
import javax.swing.*;
public class Ctest {
/**
* 创建并 <SUF>*/
private static void createAndShowGUI() {
//Make sure we have nice window decorations.
JFrame.setDefaultLookAndFeelDecorated(true);
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
} | false | 220 | 35 | 241 | 30 | 259 | 30 | 241 | 30 | 315 | 50 | false | false | false | false | false | true |
19605_16 | package Step2;
import java.lang.reflect.Method;
public class reflectionTest {
public static void main(String[] args){
try {
//Class获取类的方法一:实例对象的getClass()方法;
User testObject = new User("zhangshan",19);
Class Method1Class = testObject.getClass();
//Class获取类的方法二:类的.class(最安全/性能最好)属性;有点类似python的getattr()。java中每个类型都有class 属性.
Class Method2Class = User.class;
//Class对象的获取方法三:运用Class.forName(String className)动态加载类,className需要是类的全限定名(最常用).
//这种方法也最容易理解,通过类名(jar包中的完整namespace)就可以调用其中的方法,也最符合我们需要的使用场景.
//j2eeScan burp 插件就使用了这种反射机制。
String path = "Step2.User";
Class Method3Class = Class.forName(path);
Method[] methods = Method3Class.getMethods();
//Method[] methods = Method2Class.getMethods();
//Method[] methods = Method3Class.getMethods();
//通过类的class属性获取对应的Class类的对象,通过这个Class类的对象获取test类中的方法集合
/* String name = Method3Class.getName();
* int modifiers = Method3Class.getModifiers();
* .....还有很多方法
* 也就是说,对于一个任意的可以访问到的类,我们都能够通过以上这些方法来知道它的所有的方法和属性;
* 知道了它的方法和属性,就可以调用这些方法和属性。
*/
//调用User类中的方法
for(Method method : methods){
if(method.getName().equals("getName")) {
System.out.println("method = " + method.getName());
Class[] parameterTypes = method.getParameterTypes();//获取方法的参数
Class returnType = method.getReturnType();//获取方法的返回类型
try {
User user = (User)Method3Class.newInstance();
Object x = method.invoke(user);//user.getName();
//Object x = method.invoke(new test(1), 666);
//new关键字能调用任何构造方法,newInstance()只能调用无参构造方法。但反射的场景中是不应该有机会使用new关键词的。
System.out.println(x);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Method method = Method3Class.getMethod("setName",String.class);
User user1 = (User)Method3Class.getConstructor(String.class,Integer.class).newInstance("lisi",19);
//调用自定义构造器的方法
Object x = method.invoke(user1,"李四");//第一个参数是类的对象。第二参数是函数的参数
System.out.println(user1.getName());
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
class User{
private Integer age;
private String name;
public User() {}
public User(String name,Integer age){ //构造函数,初始化时执行
this.age = age;
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | bit4woo/Java_deserialize_vuln_lab | src/Step2/reflectionTest.java | 853 | //第一个参数是类的对象。第二参数是函数的参数 | line_comment | zh-cn | package Step2;
import java.lang.reflect.Method;
public class reflectionTest {
public static void main(String[] args){
try {
//Class获取类的方法一:实例对象的getClass()方法;
User testObject = new User("zhangshan",19);
Class Method1Class = testObject.getClass();
//Class获取类的方法二:类的.class(最安全/性能最好)属性;有点类似python的getattr()。java中每个类型都有class 属性.
Class Method2Class = User.class;
//Class对象的获取方法三:运用Class.forName(String className)动态加载类,className需要是类的全限定名(最常用).
//这种方法也最容易理解,通过类名(jar包中的完整namespace)就可以调用其中的方法,也最符合我们需要的使用场景.
//j2eeScan burp 插件就使用了这种反射机制。
String path = "Step2.User";
Class Method3Class = Class.forName(path);
Method[] methods = Method3Class.getMethods();
//Method[] methods = Method2Class.getMethods();
//Method[] methods = Method3Class.getMethods();
//通过类的class属性获取对应的Class类的对象,通过这个Class类的对象获取test类中的方法集合
/* String name = Method3Class.getName();
* int modifiers = Method3Class.getModifiers();
* .....还有很多方法
* 也就是说,对于一个任意的可以访问到的类,我们都能够通过以上这些方法来知道它的所有的方法和属性;
* 知道了它的方法和属性,就可以调用这些方法和属性。
*/
//调用User类中的方法
for(Method method : methods){
if(method.getName().equals("getName")) {
System.out.println("method = " + method.getName());
Class[] parameterTypes = method.getParameterTypes();//获取方法的参数
Class returnType = method.getReturnType();//获取方法的返回类型
try {
User user = (User)Method3Class.newInstance();
Object x = method.invoke(user);//user.getName();
//Object x = method.invoke(new test(1), 666);
//new关键字能调用任何构造方法,newInstance()只能调用无参构造方法。但反射的场景中是不应该有机会使用new关键词的。
System.out.println(x);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Method method = Method3Class.getMethod("setName",String.class);
User user1 = (User)Method3Class.getConstructor(String.class,Integer.class).newInstance("lisi",19);
//调用自定义构造器的方法
Object x = method.invoke(user1,"李四");//第一 <SUF>
System.out.println(user1.getName());
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
class User{
private Integer age;
private String name;
public User() {}
public User(String name,Integer age){ //构造函数,初始化时执行
this.age = age;
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
} | false | 755 | 13 | 853 | 12 | 892 | 12 | 853 | 12 | 1,249 | 22 | false | false | false | false | false | true |
23423_1 | package burp;
import java.io.PrintWriter;
//!!!要使用这个文件中的代码,需要先将文件名改为BurpExtender.java
public class BurpExtender implements IBurpExtender
{
@Override
public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks)
{
// 设置插件的名称
callbacks.setExtensionName("Hello world extension");
// 获取burp提供的标准输出流和错误输出流
PrintWriter stdout = new PrintWriter(callbacks.getStdout(), true);
PrintWriter stderr = new PrintWriter(callbacks.getStderr(), true);
// 打印到标准输出流
stdout.println("Hello output");
// 答应到错误输出流
stderr.println("Hello errors");
// 写一个报警信息到burp的报警面板
callbacks.issueAlert("Hello alerts");
// 抛出一个异常,将会在错误输出流中显示
throw new RuntimeException("Hello exceptions");
}
} | bit4woo/burp-api-drops | src/burp/Lession2.java | 219 | // 设置插件的名称 | line_comment | zh-cn | package burp;
import java.io.PrintWriter;
//!!!要使用这个文件中的代码,需要先将文件名改为BurpExtender.java
public class BurpExtender implements IBurpExtender
{
@Override
public void registerExtenderCallbacks(IBurpExtenderCallbacks callbacks)
{
// 设置 <SUF>
callbacks.setExtensionName("Hello world extension");
// 获取burp提供的标准输出流和错误输出流
PrintWriter stdout = new PrintWriter(callbacks.getStdout(), true);
PrintWriter stderr = new PrintWriter(callbacks.getStderr(), true);
// 打印到标准输出流
stdout.println("Hello output");
// 答应到错误输出流
stderr.println("Hello errors");
// 写一个报警信息到burp的报警面板
callbacks.issueAlert("Hello alerts");
// 抛出一个异常,将会在错误输出流中显示
throw new RuntimeException("Hello exceptions");
}
} | false | 214 | 6 | 219 | 5 | 232 | 5 | 219 | 5 | 328 | 11 | false | false | false | false | false | true |
56733_23 | package burp;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.text.StringEscapeUtils;
/**
* @author bit4woo
* @github https://github.com/bit4woo
* @version CreateTime:2021年3月27日 下午3:32:27
*/
public class DomainProducer extends Thread {//Producer do
private final BlockingQueue<IHttpRequestResponse> inputQueue;//use to store messageInfo
private final BlockingQueue<String> subDomainQueue;
private final BlockingQueue<String> similarDomainQueue;
private final BlockingQueue<String> relatedDomainQueue;
private BlockingQueue<String> httpsQueue = new LinkedBlockingQueue<>();//temp variable to identify checked https
private int threadNo;
private boolean stopflag = false;
private static IBurpExtenderCallbacks callbacks = BurpExtender.getCallbacks();//静态变量,burp插件的逻辑中,是可以保证它被初始化的。;
public PrintWriter stdout = new PrintWriter(callbacks.getStdout(), true);
public PrintWriter stderr = new PrintWriter(callbacks.getStderr(), true);
public IExtensionHelpers helpers = callbacks.getHelpers();
public DomainProducer(BlockingQueue<IHttpRequestResponse> inputQueue,
BlockingQueue<String> subDomainQueue,
BlockingQueue<String> similarDomainQueue,
BlockingQueue<String> relatedDomainQueue,
int threadNo) {
this.threadNo = threadNo;
this.inputQueue = inputQueue;
this.subDomainQueue = subDomainQueue;
this.similarDomainQueue = similarDomainQueue;
this.relatedDomainQueue = relatedDomainQueue;
stopflag= false;
}
public void stopThread() {
stopflag = true;
}
@Override
public void run() {
while(true){
try {
if (threadNo != 9999) {
if (inputQueue.isEmpty() || stopflag) {
//stdout.println("Producer break");
break;
}
}
IHttpRequestResponse messageinfo = inputQueue.take();
searchDomain(messageinfo);
} catch (Throwable error) {//java.lang.RuntimeException can't been catched, why?
}
}
}
public void searchDomain(IHttpRequestResponse messageinfo) throws Exception {
IHttpService httpservice = messageinfo.getHttpService();
String urlString = helpers.analyzeRequest(messageinfo).getUrl().toString();
String shortURL = httpservice.toString();
String protocol = httpservice.getProtocol();
String Host = httpservice.getHost();
//callbacks.printOutput(rootdomains.toString());
//callbacks.printOutput(keywords.toString());
addToQueue(Host);
int type = GUI.domainResult.domainType(Host);
if (threadNo != 9999) {//用这个方法简单区分是否为搜索线程 还是流量分析线程。
//流量分析线程不处理证书。
if (type !=DomainObject.USELESS && protocol.equalsIgnoreCase("https")){//get related domains
if (!httpsQueue.contains(shortURL)) {//httpService checked or not
Set<String> tmpDomains = CertInfo.getSANs(shortURL,GUI.domainResult.fetchKeywordSet());
for (String domain:tmpDomains) {
if (!relatedDomainQueue.contains(domain)) {
relatedDomainQueue.add(domain);
}
}
httpsQueue.add(shortURL);
}
}
}
if (type != DomainObject.USELESS && !Commons.uselessExtension(urlString)) {//grep domains from response and classify
grepResponse(messageinfo);
}
}
public void addToQueue(String domain) {
int type = GUI.domainResult.domainType(domain);
if (type == DomainObject.SUB_DOMAIN)
{
if (!subDomainQueue.contains(domain)) {
subDomainQueue.add(domain);
stdout.println("new domain found: "+ domain);
}
}else if (type == DomainObject.SIMILAR_DOMAIN) {
if (!similarDomainQueue.contains(domain)){
similarDomainQueue.add(domain);
}
}
}
public void grepResponse(IHttpRequestResponse messageinfo) {
byte[] response = messageinfo.getResponse();
if (response != null) {
Set<String> domains = DomainProducer.grepDomain(new String(response));
for (String domain:domains) {
addToQueue(domain);
}
}
}
public static Set<String> grepDomain(String httpResponse) {
httpResponse = httpResponse.toLowerCase();
//httpResponse = cleanResponse(httpResponse);
Set<String> domains = new HashSet<>();
//"^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$"
final String DOMAIN_NAME_PATTERN = "([A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}";
String[] lines = httpResponse.split("\r\n");
for (String line:lines) {//分行进行提取,似乎可以提高成功率?
line = line.trim();
int counter =0;
while (needURLConvert(line) && counter<3) {// %对应的URL编码
try {
line = URLDecoder.decode(line);
counter++;
}catch(Exception e) {
//e.printStackTrace(BurpExtender.getStderr());
break;//即使出错,也要进行后续的查找
}
}
//保险起见,再做一层处理
if (line.toLowerCase().contains("%2f")) {
line.replace("%2f"," ");
}
if (line.toLowerCase().contains("%3a")) {
line.replace("%3a"," ");
}
counter = 0;
while (needUnicodeConvert(line) && counter<3) {//unicode解码
try {
line = StringEscapeUtils.unescapeJava(line);
counter++;
}catch(Exception e) {
//e.printStackTrace(BurpExtender.getStderr());
break;//即使出错,也要进行后续的查找
}
}
Pattern pDomainNameOnly = Pattern.compile(DOMAIN_NAME_PATTERN);
Matcher matcher = pDomainNameOnly.matcher(line);
while (matcher.find()) {//多次查找
domains.add(matcher.group());
}
}
return domains;
}
public static boolean needUnicodeConvert(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
//Pattern pattern = Pattern.compile("(\\\\u([A-Fa-f0-9]{4}))");//和上面的效果一样
Matcher matcher = pattern.matcher(str.toLowerCase());
if (matcher.find() ){
return true;
}else {
return false;
}
}
public static boolean needURLConvert(String str) {
Pattern pattern = Pattern.compile("(%(\\p{XDigit}{2}))");
Matcher matcher = pattern.matcher(str.toLowerCase());
if (matcher.find() ){
return true;
}else {
return false;
}
}
public static void main(String args[]){}
} | bit4woo/domain_hunter | src/burp/DomainProducer.java | 1,832 | //即使出错,也要进行后续的查找 | line_comment | zh-cn | package burp;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.text.StringEscapeUtils;
/**
* @author bit4woo
* @github https://github.com/bit4woo
* @version CreateTime:2021年3月27日 下午3:32:27
*/
public class DomainProducer extends Thread {//Producer do
private final BlockingQueue<IHttpRequestResponse> inputQueue;//use to store messageInfo
private final BlockingQueue<String> subDomainQueue;
private final BlockingQueue<String> similarDomainQueue;
private final BlockingQueue<String> relatedDomainQueue;
private BlockingQueue<String> httpsQueue = new LinkedBlockingQueue<>();//temp variable to identify checked https
private int threadNo;
private boolean stopflag = false;
private static IBurpExtenderCallbacks callbacks = BurpExtender.getCallbacks();//静态变量,burp插件的逻辑中,是可以保证它被初始化的。;
public PrintWriter stdout = new PrintWriter(callbacks.getStdout(), true);
public PrintWriter stderr = new PrintWriter(callbacks.getStderr(), true);
public IExtensionHelpers helpers = callbacks.getHelpers();
public DomainProducer(BlockingQueue<IHttpRequestResponse> inputQueue,
BlockingQueue<String> subDomainQueue,
BlockingQueue<String> similarDomainQueue,
BlockingQueue<String> relatedDomainQueue,
int threadNo) {
this.threadNo = threadNo;
this.inputQueue = inputQueue;
this.subDomainQueue = subDomainQueue;
this.similarDomainQueue = similarDomainQueue;
this.relatedDomainQueue = relatedDomainQueue;
stopflag= false;
}
public void stopThread() {
stopflag = true;
}
@Override
public void run() {
while(true){
try {
if (threadNo != 9999) {
if (inputQueue.isEmpty() || stopflag) {
//stdout.println("Producer break");
break;
}
}
IHttpRequestResponse messageinfo = inputQueue.take();
searchDomain(messageinfo);
} catch (Throwable error) {//java.lang.RuntimeException can't been catched, why?
}
}
}
public void searchDomain(IHttpRequestResponse messageinfo) throws Exception {
IHttpService httpservice = messageinfo.getHttpService();
String urlString = helpers.analyzeRequest(messageinfo).getUrl().toString();
String shortURL = httpservice.toString();
String protocol = httpservice.getProtocol();
String Host = httpservice.getHost();
//callbacks.printOutput(rootdomains.toString());
//callbacks.printOutput(keywords.toString());
addToQueue(Host);
int type = GUI.domainResult.domainType(Host);
if (threadNo != 9999) {//用这个方法简单区分是否为搜索线程 还是流量分析线程。
//流量分析线程不处理证书。
if (type !=DomainObject.USELESS && protocol.equalsIgnoreCase("https")){//get related domains
if (!httpsQueue.contains(shortURL)) {//httpService checked or not
Set<String> tmpDomains = CertInfo.getSANs(shortURL,GUI.domainResult.fetchKeywordSet());
for (String domain:tmpDomains) {
if (!relatedDomainQueue.contains(domain)) {
relatedDomainQueue.add(domain);
}
}
httpsQueue.add(shortURL);
}
}
}
if (type != DomainObject.USELESS && !Commons.uselessExtension(urlString)) {//grep domains from response and classify
grepResponse(messageinfo);
}
}
public void addToQueue(String domain) {
int type = GUI.domainResult.domainType(domain);
if (type == DomainObject.SUB_DOMAIN)
{
if (!subDomainQueue.contains(domain)) {
subDomainQueue.add(domain);
stdout.println("new domain found: "+ domain);
}
}else if (type == DomainObject.SIMILAR_DOMAIN) {
if (!similarDomainQueue.contains(domain)){
similarDomainQueue.add(domain);
}
}
}
public void grepResponse(IHttpRequestResponse messageinfo) {
byte[] response = messageinfo.getResponse();
if (response != null) {
Set<String> domains = DomainProducer.grepDomain(new String(response));
for (String domain:domains) {
addToQueue(domain);
}
}
}
public static Set<String> grepDomain(String httpResponse) {
httpResponse = httpResponse.toLowerCase();
//httpResponse = cleanResponse(httpResponse);
Set<String> domains = new HashSet<>();
//"^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$"
final String DOMAIN_NAME_PATTERN = "([A-Za-z0-9-]{1,63}(?<!-)\\.)+[A-Za-z]{2,6}";
String[] lines = httpResponse.split("\r\n");
for (String line:lines) {//分行进行提取,似乎可以提高成功率?
line = line.trim();
int counter =0;
while (needURLConvert(line) && counter<3) {// %对应的URL编码
try {
line = URLDecoder.decode(line);
counter++;
}catch(Exception e) {
//e.printStackTrace(BurpExtender.getStderr());
break;//即使出错,也要进行后续的查找
}
}
//保险起见,再做一层处理
if (line.toLowerCase().contains("%2f")) {
line.replace("%2f"," ");
}
if (line.toLowerCase().contains("%3a")) {
line.replace("%3a"," ");
}
counter = 0;
while (needUnicodeConvert(line) && counter<3) {//unicode解码
try {
line = StringEscapeUtils.unescapeJava(line);
counter++;
}catch(Exception e) {
//e.printStackTrace(BurpExtender.getStderr());
break;//即使 <SUF>
}
}
Pattern pDomainNameOnly = Pattern.compile(DOMAIN_NAME_PATTERN);
Matcher matcher = pDomainNameOnly.matcher(line);
while (matcher.find()) {//多次查找
domains.add(matcher.group());
}
}
return domains;
}
public static boolean needUnicodeConvert(String str) {
Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{4}))");
//Pattern pattern = Pattern.compile("(\\\\u([A-Fa-f0-9]{4}))");//和上面的效果一样
Matcher matcher = pattern.matcher(str.toLowerCase());
if (matcher.find() ){
return true;
}else {
return false;
}
}
public static boolean needURLConvert(String str) {
Pattern pattern = Pattern.compile("(%(\\p{XDigit}{2}))");
Matcher matcher = pattern.matcher(str.toLowerCase());
if (matcher.find() ){
return true;
}else {
return false;
}
}
public static void main(String args[]){}
} | false | 1,545 | 10 | 1,832 | 13 | 1,807 | 9 | 1,832 | 13 | 2,370 | 21 | false | false | false | false | false | true |
10863_4 | package title.search;
import java.net.URL;
import java.util.ArrayList;
import title.LineEntry;
import title.TitlePanel;
public class SearchManager {
private TitlePanel titlePanel;
public SearchManager(TitlePanel panel){
this.titlePanel = panel;
}
public boolean include(LineEntry line,String searchInput,boolean caseSensitive) {
//第一层判断,根据按钮状态进行判断,如果为true,进行后面的逻辑判断,false直接返回。
if (!entryNeedToShow(line)) {
return false;
}
//目前只处理&&(and)逻辑的表达式
if (searchInput.contains("&&")) {
String[] searchConditions = searchInput.split("&&");
for (String condition:searchConditions) {
if (oneCondition(condition,line,caseSensitive)) {
continue;
}else {
return false;
}
}
return true;
}else {
return oneCondition(searchInput,line,caseSensitive);
}
}
public boolean oneCondition(String Input,LineEntry line,boolean caseSensitive) {
Input = Input.trim();//应该去除空格,符合java代码编写习惯
if (SearchStringDork.isStringDork(Input)) {
//stdout.println("do dork search,dork:"+dork+" keyword:"+keyword);
return SearchStringDork.doFilter(line,Input,caseSensitive);
}else if (SearchNumbericDork.isNumbericDork(Input)) {
return SearchNumbericDork.doFilter(line,Input);
}else if (SearchRegex.isRegexSearch(Input)) {
return SearchRegex.doFilter(line,Input);
}else {
return SearchManager.textFilter(line,Input,caseSensitive);
}
}
//根据状态过滤
public boolean entryNeedToShow(LineEntry entry) {
if (!(titlePanel.getRdbtnUnCheckedItems().isSelected()||titlePanel.getRdbtnCheckingItems().isSelected()||
titlePanel.getRdbtnCheckedItems().isSelected()||titlePanel.getRdbtnMoreActionItems().isSelected())) {
//全部未选中时,全部返回。一来为了满足用户习惯全部未选择时全部返回,
//二来是为了解决之前乱改CheckStatus常理带来的bug,之前CheckStatus_Checked == "Checked",现在CheckStatus_Checked== "done"导致选中checked的时候,Checked的那部分就不会被显示出来。
return true;
}
if (titlePanel.getRdbtnCheckedItems().isSelected()&& entry.getCheckStatus().equals(LineEntry.CheckStatus_Checked)) {
return true;
}
if (titlePanel.getRdbtnCheckingItems().isSelected()&& entry.getCheckStatus().equals(LineEntry.CheckStatus_Checking)) {
return true;//小心 == 和 equals的区别,之前这里使用 ==就导致了checking状态的条目的消失。
}
if (titlePanel.getRdbtnUnCheckedItems().isSelected()&& entry.getCheckStatus().equals(LineEntry.CheckStatus_UnChecked)) {
return true;
}
if (titlePanel.getRdbtnMoreActionItems().isSelected()&& entry.getCheckStatus().equals(LineEntry.CheckStatus_MoreAction)) {
return true;
}
return false;
}
/**
* 关键词和搜索内容都进行了小写转换,尽量多得返回内容
* @param line
* @param keyword
* @return
*/
public static boolean textFilter(LineEntry line,String keyword,boolean caseSensitive) {
if (keyword.length() == 0) {
return true;
}else {//全局搜索
ArrayList<String> contentList = new ArrayList<String>();
contentList.add(new String(line.getRequest()));
contentList.add(new String(line.getResponse()));
if (line.getEntryType().equals(LineEntry.EntryType_Web)) {
contentList.add(line.fetchUrlWithCommonFormate());
//之前这里有个bug,如果用了上面这段代码,数据库更新就会失败!why?
//因为之前的fetchUrlWithCommonFormate()实现修改了URL的格式导致,where条件无法匹配。
}else {
contentList.add(line.getUrl());//本质是domain name
}
contentList.add(line.getIPSet().toString());
contentList.add(line.getCNAMESet().toString());
contentList.add(line.getCertDomainSet().toString());
contentList.add(line.getComments().toString());
contentList.add(line.getTitle());
contentList.add(line.getIcon_hash());
contentList.add(line.getASNInfo());
if (caseSensitive) {
for(String item:contentList) {
if (item == null) continue;
if (item.contains(keyword)) {
return true;
}
}
}else {
keyword = keyword.toLowerCase();
for(String item:contentList) {
if (item == null) continue;
if (item.toLowerCase().contains(keyword)) {
return true;
}
}
}
return false;
}
}
public static void test(){
String title = "标题";
System.out.println(title.toLowerCase().contains("标题"));
// String webpack_PATTERN = "app\\.([0-9a-z])*\\.js";//后文有小写转换
// System.out.println(webpack_PATTERN);
//
// System.out.println("regex:app\\.([0-9a-z])*\\.js");
//
// System.out.println(SearchDork.REGEX.toString()+":"+webpack_PATTERN);
}
public static void test1() throws Exception {
System.out.println(new URL("https://partner.airpay.in.th/").equals(new URL("https://partner.airpay.in.th:443/")));
}
public static void main(String[] args) throws Exception {
test1();
}
}
| bit4woo/domain_hunter_pro | src/title/search/SearchManager.java | 1,487 | //根据状态过滤 | line_comment | zh-cn | package title.search;
import java.net.URL;
import java.util.ArrayList;
import title.LineEntry;
import title.TitlePanel;
public class SearchManager {
private TitlePanel titlePanel;
public SearchManager(TitlePanel panel){
this.titlePanel = panel;
}
public boolean include(LineEntry line,String searchInput,boolean caseSensitive) {
//第一层判断,根据按钮状态进行判断,如果为true,进行后面的逻辑判断,false直接返回。
if (!entryNeedToShow(line)) {
return false;
}
//目前只处理&&(and)逻辑的表达式
if (searchInput.contains("&&")) {
String[] searchConditions = searchInput.split("&&");
for (String condition:searchConditions) {
if (oneCondition(condition,line,caseSensitive)) {
continue;
}else {
return false;
}
}
return true;
}else {
return oneCondition(searchInput,line,caseSensitive);
}
}
public boolean oneCondition(String Input,LineEntry line,boolean caseSensitive) {
Input = Input.trim();//应该去除空格,符合java代码编写习惯
if (SearchStringDork.isStringDork(Input)) {
//stdout.println("do dork search,dork:"+dork+" keyword:"+keyword);
return SearchStringDork.doFilter(line,Input,caseSensitive);
}else if (SearchNumbericDork.isNumbericDork(Input)) {
return SearchNumbericDork.doFilter(line,Input);
}else if (SearchRegex.isRegexSearch(Input)) {
return SearchRegex.doFilter(line,Input);
}else {
return SearchManager.textFilter(line,Input,caseSensitive);
}
}
//根据 <SUF>
public boolean entryNeedToShow(LineEntry entry) {
if (!(titlePanel.getRdbtnUnCheckedItems().isSelected()||titlePanel.getRdbtnCheckingItems().isSelected()||
titlePanel.getRdbtnCheckedItems().isSelected()||titlePanel.getRdbtnMoreActionItems().isSelected())) {
//全部未选中时,全部返回。一来为了满足用户习惯全部未选择时全部返回,
//二来是为了解决之前乱改CheckStatus常理带来的bug,之前CheckStatus_Checked == "Checked",现在CheckStatus_Checked== "done"导致选中checked的时候,Checked的那部分就不会被显示出来。
return true;
}
if (titlePanel.getRdbtnCheckedItems().isSelected()&& entry.getCheckStatus().equals(LineEntry.CheckStatus_Checked)) {
return true;
}
if (titlePanel.getRdbtnCheckingItems().isSelected()&& entry.getCheckStatus().equals(LineEntry.CheckStatus_Checking)) {
return true;//小心 == 和 equals的区别,之前这里使用 ==就导致了checking状态的条目的消失。
}
if (titlePanel.getRdbtnUnCheckedItems().isSelected()&& entry.getCheckStatus().equals(LineEntry.CheckStatus_UnChecked)) {
return true;
}
if (titlePanel.getRdbtnMoreActionItems().isSelected()&& entry.getCheckStatus().equals(LineEntry.CheckStatus_MoreAction)) {
return true;
}
return false;
}
/**
* 关键词和搜索内容都进行了小写转换,尽量多得返回内容
* @param line
* @param keyword
* @return
*/
public static boolean textFilter(LineEntry line,String keyword,boolean caseSensitive) {
if (keyword.length() == 0) {
return true;
}else {//全局搜索
ArrayList<String> contentList = new ArrayList<String>();
contentList.add(new String(line.getRequest()));
contentList.add(new String(line.getResponse()));
if (line.getEntryType().equals(LineEntry.EntryType_Web)) {
contentList.add(line.fetchUrlWithCommonFormate());
//之前这里有个bug,如果用了上面这段代码,数据库更新就会失败!why?
//因为之前的fetchUrlWithCommonFormate()实现修改了URL的格式导致,where条件无法匹配。
}else {
contentList.add(line.getUrl());//本质是domain name
}
contentList.add(line.getIPSet().toString());
contentList.add(line.getCNAMESet().toString());
contentList.add(line.getCertDomainSet().toString());
contentList.add(line.getComments().toString());
contentList.add(line.getTitle());
contentList.add(line.getIcon_hash());
contentList.add(line.getASNInfo());
if (caseSensitive) {
for(String item:contentList) {
if (item == null) continue;
if (item.contains(keyword)) {
return true;
}
}
}else {
keyword = keyword.toLowerCase();
for(String item:contentList) {
if (item == null) continue;
if (item.toLowerCase().contains(keyword)) {
return true;
}
}
}
return false;
}
}
public static void test(){
String title = "标题";
System.out.println(title.toLowerCase().contains("标题"));
// String webpack_PATTERN = "app\\.([0-9a-z])*\\.js";//后文有小写转换
// System.out.println(webpack_PATTERN);
//
// System.out.println("regex:app\\.([0-9a-z])*\\.js");
//
// System.out.println(SearchDork.REGEX.toString()+":"+webpack_PATTERN);
}
public static void test1() throws Exception {
System.out.println(new URL("https://partner.airpay.in.th/").equals(new URL("https://partner.airpay.in.th:443/")));
}
public static void main(String[] args) throws Exception {
test1();
}
}
| false | 1,240 | 4 | 1,487 | 4 | 1,459 | 4 | 1,487 | 4 | 1,926 | 9 | false | false | false | false | false | true |
16675_4 | package knife;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintWriter;
import java.net.URL;
import javax.swing.JMenuItem;
import com.bit4woo.utilbox.burp.HelperPlus;
import com.bit4woo.utilbox.utils.CharsetUtils;
import com.bit4woo.utilbox.utils.SystemUtils;
import burp.BurpExtender;
import burp.IBurpExtenderCallbacks;
import burp.IContextMenuInvocation;
import burp.IExtensionHelpers;
import burp.IHttpRequestResponse;
public class OpenWithBrowserMenu extends JMenuItem {
/**
*
*/
private static final long serialVersionUID = 1L;
//JMenuItem vs. JMenu
public OpenWithBrowserMenu(BurpExtender burp){
this.setText("^_^ Open With Browser");
this.addActionListener(new OpenWithBrowser_Action(burp,burp.invocation));
}
}
class OpenWithBrowser_Action implements ActionListener{
private IContextMenuInvocation invocation;
public IExtensionHelpers helpers;
public PrintWriter stdout;
public PrintWriter stderr;
public IBurpExtenderCallbacks callbacks;
public BurpExtender burp;
public OpenWithBrowser_Action(BurpExtender burp,IContextMenuInvocation invocation) {
this.burp = burp;
this.invocation = invocation;
this.helpers = burp.helpers;
this.callbacks = burp.callbacks;
this.stderr = burp.stderr;
this.stdout = burp.stdout;
}
@Override
public void actionPerformed(ActionEvent event) {
try{
String browserPath = burp.getConfigTableModel().getConfigValueByKey("browserPath");
if (browserPath!=null && new File(browserPath).exists() && new File(browserPath).isFile()) {
}else {//when no browserPath in config, the value will be null
browserPath = "default";
}
IHttpRequestResponse[] messages = invocation.getSelectedMessages();
if (messages == null ) {
return;
}
if (messages.length == 1) {
String selectedUrl = getSelectedStringByBurp();
//String selectedUrl = new RobotInput().getSelectedString();//为了解决burp API中的bug,尝试用复制粘贴方法获取选中的内容。
//不知道为什么这里获取到的结果始终是上一次复制的内容。
//难道是因为,当用鼠标点击右键菜单时,当前的选中内容不是burp数据表中的字符串,而是当前菜单项?所以这个方法走不通了?
//stderr.println("selected URL: "+selectedUrl);
//stderr.println("selected URL old: "+getSelectedStringByBurpOld());
if (selectedUrl.length()>10) {// http://a.cn
stdout.println();
stdout.println("//////////open URL: "+selectedUrl+" //////////");
SystemUtils.browserOpen(selectedUrl,browserPath);
//stdout.println(selectedUrl);
}else {
String hosturl =helpers.analyzeRequest(messages[0]).getUrl().toString();
SystemUtils.browserOpen(hosturl,browserPath);
}
}else if (messages.length > 1 && messages.length <=50) {
for(IHttpRequestResponse message:messages) {
HelperPlus getter = new HelperPlus(helpers);
URL targetShortUrl = getter.getFullURL(message);
SystemUtils.browserOpen(targetShortUrl,browserPath);
}
}else {
stderr.println("Please Select Less URLs to Open");
}
}
catch (Exception e1)
{
e1.printStackTrace(stderr);
}
}
//只适用于GBK编码格式,UTF-8的格式中的结果是它的结果除以3???
public static int ChineseCount(byte[] input) {
int num = 0;
for (int i = 0; i < input.length; i++) {
if (input[i] < 0) {
num++;
i = i + 1;
}
}
return num;
}
@Deprecated
public String getSelectedStringByBurpOld(){
String result = "";
IHttpRequestResponse[] messages = invocation.getSelectedMessages();
if (messages == null ) {
return result;
}
if (messages.length == 1) {
IHttpRequestResponse message = messages[0];
/////////////selected url/////////////////
byte[] source = null;
int context = invocation.getInvocationContext();
if (context==IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST
|| context ==IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST
|| context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY
|| context == IContextMenuInvocation.CONTEXT_INTRUDER_ATTACK_RESULTS
|| context == IContextMenuInvocation.CONTEXT_SEARCH_RESULTS
|| context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE
|| context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TREE) {
source = message.getRequest();
}else {
source = message.getResponse();
}
int[] selectedIndex = invocation.getSelectionBounds();//当数据包中有中文或其他宽字符的时候,这里的返回值不正确。已报bug。
//获得的index根据选中内容前面中文字数的个数*2 的值前移了。
//stdout.println(selectedIndex[0]+":"+selectedIndex[1]);
if(source!=null && selectedIndex !=null && selectedIndex[1]-selectedIndex[0]>=3) {
int selectedLength = selectedIndex[1]-selectedIndex[0];
byte[] selectedBytes = new byte[selectedLength];
System.arraycopy(source, selectedIndex[0], selectedBytes, 0, selectedLength);//新的内容替换选中内容
stderr.println("11--->"+burp.callbacks.getHelpers().bytesToString(selectedBytes));
stderr.println("22--->"+ new String(selectedBytes));
result = new String(selectedBytes).trim();
}
result = getFullUrl(result,message);
}
return result;
}
public String getSelectedStringByBurp(){
String result = "";
IHttpRequestResponse[] messages = invocation.getSelectedMessages();
if (messages == null ) {
return result;
}
if (messages.length == 1) {
IHttpRequestResponse message = messages[0];
/////////////selected url/////////////////
byte[] source = null;
int context = invocation.getInvocationContext();
if (context==IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST
|| context ==IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST
|| context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY
|| context == IContextMenuInvocation.CONTEXT_INTRUDER_ATTACK_RESULTS
|| context == IContextMenuInvocation.CONTEXT_SEARCH_RESULTS
|| context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE
|| context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TREE) {
source = message.getRequest();
}else {
source = message.getResponse();
}
int[] selectedIndex = invocation.getSelectionBounds();//当数据包中有中文或其他宽字符的时候,这里的返回值不正确。已报bug。
//stdout.println(selectedIndex[0]+":"+selectedIndex[1]);
//这里的index应该是字符串的index,进行选中操作时对象应该是字符文本内容,无论是一个中文还是一个字母,都是一个文本字符。这就是我们通常的文本操作啊,之前是想多了。
//burp进行的byte和string之间的转换,没有考虑特定的编码,是一刀切的方式,所以将index用于byte序列上,就不能正确对应。
if(source!=null && selectedIndex !=null && selectedIndex[1]-selectedIndex[0]>=3) {
String originalCharSet = CharsetUtils.detectCharset(source);
String text;
try {
text = new String(source,originalCharSet);
}catch(Exception e) {
text = new String(source);
}
result = text.substring(selectedIndex[0], selectedIndex[1]);
result = getFullUrl(result,message);
}
}
return result;
}
//<script src="http://lbs.sf-express.com/api/map?v=2.0&ak=b1cfb18ca6864e46b3ed4cb18f12c0f8">
//<script type=text/javascript src=./static/js/manifest.c7ad14f4845199970dcb.js>
//<link rel="stylesheet" type="text/css" href="/cat/assets/css/bootstrap.min.css">
//<link href=static/css/chunk-03d2ee16.a3503987.css rel=prefetch>
//<link href="www.microsoft.com">这只会被当成目标,不会被当成域名
//<link href="//www.microsoft.com">会被当成域名,协议会使用当前页面所使用的协议
public static String getFullUrl(String url,IHttpRequestResponse message) {
if (url.startsWith("http://") || url.startsWith("https://")) {
//都是带有host的完整URL,直接访问即可
return url;
}else if(url.startsWith("//")) {//使用当前web的请求协议
return message.getHttpService().getProtocol()+":"+url;
}else if (url.startsWith("../") || url.startsWith("./") ) {
return message.getHttpService().toString()+"/"+url;
}else if(url.startsWith("/")){
return message.getHttpService().toString()+url;
}else{//没有斜杠的情况。<link href="www.microsoft.com">这只会被当成目标,不会被当成域名
HelperPlus getter = new HelperPlus(BurpExtender.callbacks.getHelpers());
String fullUrl = getter.getFullURL(message).toString().split("\\?")[0];
int indexOfLastSlash = fullUrl.lastIndexOf("/");//截取的内容不不包含当前index对应的元素
return fullUrl.substring(0,indexOfLastSlash+1)+url;
}
}
}
| bit4woo/knife | src/knife/OpenWithBrowserMenu.java | 2,503 | //难道是因为,当用鼠标点击右键菜单时,当前的选中内容不是burp数据表中的字符串,而是当前菜单项?所以这个方法走不通了? | line_comment | zh-cn | package knife;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.PrintWriter;
import java.net.URL;
import javax.swing.JMenuItem;
import com.bit4woo.utilbox.burp.HelperPlus;
import com.bit4woo.utilbox.utils.CharsetUtils;
import com.bit4woo.utilbox.utils.SystemUtils;
import burp.BurpExtender;
import burp.IBurpExtenderCallbacks;
import burp.IContextMenuInvocation;
import burp.IExtensionHelpers;
import burp.IHttpRequestResponse;
public class OpenWithBrowserMenu extends JMenuItem {
/**
*
*/
private static final long serialVersionUID = 1L;
//JMenuItem vs. JMenu
public OpenWithBrowserMenu(BurpExtender burp){
this.setText("^_^ Open With Browser");
this.addActionListener(new OpenWithBrowser_Action(burp,burp.invocation));
}
}
class OpenWithBrowser_Action implements ActionListener{
private IContextMenuInvocation invocation;
public IExtensionHelpers helpers;
public PrintWriter stdout;
public PrintWriter stderr;
public IBurpExtenderCallbacks callbacks;
public BurpExtender burp;
public OpenWithBrowser_Action(BurpExtender burp,IContextMenuInvocation invocation) {
this.burp = burp;
this.invocation = invocation;
this.helpers = burp.helpers;
this.callbacks = burp.callbacks;
this.stderr = burp.stderr;
this.stdout = burp.stdout;
}
@Override
public void actionPerformed(ActionEvent event) {
try{
String browserPath = burp.getConfigTableModel().getConfigValueByKey("browserPath");
if (browserPath!=null && new File(browserPath).exists() && new File(browserPath).isFile()) {
}else {//when no browserPath in config, the value will be null
browserPath = "default";
}
IHttpRequestResponse[] messages = invocation.getSelectedMessages();
if (messages == null ) {
return;
}
if (messages.length == 1) {
String selectedUrl = getSelectedStringByBurp();
//String selectedUrl = new RobotInput().getSelectedString();//为了解决burp API中的bug,尝试用复制粘贴方法获取选中的内容。
//不知道为什么这里获取到的结果始终是上一次复制的内容。
//难道 <SUF>
//stderr.println("selected URL: "+selectedUrl);
//stderr.println("selected URL old: "+getSelectedStringByBurpOld());
if (selectedUrl.length()>10) {// http://a.cn
stdout.println();
stdout.println("//////////open URL: "+selectedUrl+" //////////");
SystemUtils.browserOpen(selectedUrl,browserPath);
//stdout.println(selectedUrl);
}else {
String hosturl =helpers.analyzeRequest(messages[0]).getUrl().toString();
SystemUtils.browserOpen(hosturl,browserPath);
}
}else if (messages.length > 1 && messages.length <=50) {
for(IHttpRequestResponse message:messages) {
HelperPlus getter = new HelperPlus(helpers);
URL targetShortUrl = getter.getFullURL(message);
SystemUtils.browserOpen(targetShortUrl,browserPath);
}
}else {
stderr.println("Please Select Less URLs to Open");
}
}
catch (Exception e1)
{
e1.printStackTrace(stderr);
}
}
//只适用于GBK编码格式,UTF-8的格式中的结果是它的结果除以3???
public static int ChineseCount(byte[] input) {
int num = 0;
for (int i = 0; i < input.length; i++) {
if (input[i] < 0) {
num++;
i = i + 1;
}
}
return num;
}
@Deprecated
public String getSelectedStringByBurpOld(){
String result = "";
IHttpRequestResponse[] messages = invocation.getSelectedMessages();
if (messages == null ) {
return result;
}
if (messages.length == 1) {
IHttpRequestResponse message = messages[0];
/////////////selected url/////////////////
byte[] source = null;
int context = invocation.getInvocationContext();
if (context==IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST
|| context ==IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST
|| context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY
|| context == IContextMenuInvocation.CONTEXT_INTRUDER_ATTACK_RESULTS
|| context == IContextMenuInvocation.CONTEXT_SEARCH_RESULTS
|| context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE
|| context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TREE) {
source = message.getRequest();
}else {
source = message.getResponse();
}
int[] selectedIndex = invocation.getSelectionBounds();//当数据包中有中文或其他宽字符的时候,这里的返回值不正确。已报bug。
//获得的index根据选中内容前面中文字数的个数*2 的值前移了。
//stdout.println(selectedIndex[0]+":"+selectedIndex[1]);
if(source!=null && selectedIndex !=null && selectedIndex[1]-selectedIndex[0]>=3) {
int selectedLength = selectedIndex[1]-selectedIndex[0];
byte[] selectedBytes = new byte[selectedLength];
System.arraycopy(source, selectedIndex[0], selectedBytes, 0, selectedLength);//新的内容替换选中内容
stderr.println("11--->"+burp.callbacks.getHelpers().bytesToString(selectedBytes));
stderr.println("22--->"+ new String(selectedBytes));
result = new String(selectedBytes).trim();
}
result = getFullUrl(result,message);
}
return result;
}
public String getSelectedStringByBurp(){
String result = "";
IHttpRequestResponse[] messages = invocation.getSelectedMessages();
if (messages == null ) {
return result;
}
if (messages.length == 1) {
IHttpRequestResponse message = messages[0];
/////////////selected url/////////////////
byte[] source = null;
int context = invocation.getInvocationContext();
if (context==IContextMenuInvocation.CONTEXT_MESSAGE_EDITOR_REQUEST
|| context ==IContextMenuInvocation.CONTEXT_MESSAGE_VIEWER_REQUEST
|| context == IContextMenuInvocation.CONTEXT_PROXY_HISTORY
|| context == IContextMenuInvocation.CONTEXT_INTRUDER_ATTACK_RESULTS
|| context == IContextMenuInvocation.CONTEXT_SEARCH_RESULTS
|| context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TABLE
|| context == IContextMenuInvocation.CONTEXT_TARGET_SITE_MAP_TREE) {
source = message.getRequest();
}else {
source = message.getResponse();
}
int[] selectedIndex = invocation.getSelectionBounds();//当数据包中有中文或其他宽字符的时候,这里的返回值不正确。已报bug。
//stdout.println(selectedIndex[0]+":"+selectedIndex[1]);
//这里的index应该是字符串的index,进行选中操作时对象应该是字符文本内容,无论是一个中文还是一个字母,都是一个文本字符。这就是我们通常的文本操作啊,之前是想多了。
//burp进行的byte和string之间的转换,没有考虑特定的编码,是一刀切的方式,所以将index用于byte序列上,就不能正确对应。
if(source!=null && selectedIndex !=null && selectedIndex[1]-selectedIndex[0]>=3) {
String originalCharSet = CharsetUtils.detectCharset(source);
String text;
try {
text = new String(source,originalCharSet);
}catch(Exception e) {
text = new String(source);
}
result = text.substring(selectedIndex[0], selectedIndex[1]);
result = getFullUrl(result,message);
}
}
return result;
}
//<script src="http://lbs.sf-express.com/api/map?v=2.0&ak=b1cfb18ca6864e46b3ed4cb18f12c0f8">
//<script type=text/javascript src=./static/js/manifest.c7ad14f4845199970dcb.js>
//<link rel="stylesheet" type="text/css" href="/cat/assets/css/bootstrap.min.css">
//<link href=static/css/chunk-03d2ee16.a3503987.css rel=prefetch>
//<link href="www.microsoft.com">这只会被当成目标,不会被当成域名
//<link href="//www.microsoft.com">会被当成域名,协议会使用当前页面所使用的协议
public static String getFullUrl(String url,IHttpRequestResponse message) {
if (url.startsWith("http://") || url.startsWith("https://")) {
//都是带有host的完整URL,直接访问即可
return url;
}else if(url.startsWith("//")) {//使用当前web的请求协议
return message.getHttpService().getProtocol()+":"+url;
}else if (url.startsWith("../") || url.startsWith("./") ) {
return message.getHttpService().toString()+"/"+url;
}else if(url.startsWith("/")){
return message.getHttpService().toString()+url;
}else{//没有斜杠的情况。<link href="www.microsoft.com">这只会被当成目标,不会被当成域名
HelperPlus getter = new HelperPlus(BurpExtender.callbacks.getHelpers());
String fullUrl = getter.getFullURL(message).toString().split("\\?")[0];
int indexOfLastSlash = fullUrl.lastIndexOf("/");//截取的内容不不包含当前index对应的元素
return fullUrl.substring(0,indexOfLastSlash+1)+url;
}
}
}
| false | 2,125 | 38 | 2,503 | 44 | 2,450 | 37 | 2,503 | 44 | 3,349 | 66 | false | false | false | false | false | true |
33784_8 | package deprecated;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import httpbase.MyX509TrustManager;
@Deprecated
public class HttpUtil {
/**
* 发起http请求并获取结果
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据 格式(例子:"name=name&age=age") // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
* @return json字符串(json格式不确定 可能是JSONObject,也可能是JSONArray,这里用字符串,在controller里再转化)
*/
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
String resultStr = "";
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
//HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行
httpUrlConn.setConnectTimeout(30*1000);//30s超时
httpUrlConn.setReadTimeout(10*1000);//10s超时
/*
//设置请求属性
httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
*/
//HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
//get方式需要显式连接
if ("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
}
//这种post方式,隐式自动连接
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
resultStr = buffer.toString();
} catch (ConnectException ce) {
System.out.println("server connection timed out.");
} catch (Exception e) {
System.out.println(requestUrl+" request error:\n"+e);
}
return resultStr;
}
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据 格式(例子:"name=name&age=age") // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
* @return json字符串(json格式不确定 可能是JSONObject,也可能是JSONArray,这里用字符串,在controller里再转化)
*/
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
String resultStr = "";
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
//HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行
httpUrlConn.setConnectTimeout(30*1000);//30s超时
httpUrlConn.setReadTimeout(10*1000);//10s超时
/*
//设置请求属性
httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
*/
//HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
//get方式需要显式连接
if ("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
}
//这种post方式,隐式自动连接
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
resultStr = buffer.toString();
} catch (ConnectException ce) {
System.out.println("server connection timed out.");
} catch (Exception e) {
System.out.println(requestUrl+" request error:\n"+e);
}
return resultStr;
}
public static void main(String[] args) {
System.out.println(httpRequest("https://www.zhihu.com/", "GET", null));
}
} | bit4woo/reCAPTCHA | src/deprecated/HttpUtil.java | 1,728 | //这种post方式,隐式自动连接 | line_comment | zh-cn | package deprecated;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import httpbase.MyX509TrustManager;
@Deprecated
public class HttpUtil {
/**
* 发起http请求并获取结果
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据 格式(例子:"name=name&age=age") // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
* @return json字符串(json格式不确定 可能是JSONObject,也可能是JSONArray,这里用字符串,在controller里再转化)
*/
public static String httpRequest(String requestUrl, String requestMethod, String outputStr) {
String resultStr = "";
StringBuffer buffer = new StringBuffer();
try {
URL url = new URL(requestUrl);
HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
//HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行
httpUrlConn.setConnectTimeout(30*1000);//30s超时
httpUrlConn.setReadTimeout(10*1000);//10s超时
/*
//设置请求属性
httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
*/
//HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
//get方式需要显式连接
if ("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
}
//这种 <SUF>
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
resultStr = buffer.toString();
} catch (ConnectException ce) {
System.out.println("server connection timed out.");
} catch (Exception e) {
System.out.println(requestUrl+" request error:\n"+e);
}
return resultStr;
}
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据 格式(例子:"name=name&age=age") // 正文,正文内容其实跟get的URL中 '? '后的参数字符串一致
* @return json字符串(json格式不确定 可能是JSONObject,也可能是JSONArray,这里用字符串,在controller里再转化)
*/
public static String httpsRequest(String requestUrl, String requestMethod, String outputStr) {
String resultStr = "";
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
//HttpURLConnection是基于HTTP协议的,其底层通过socket通信实现。如果不设置超时(timeout),在网络异常的情况下,可能会导致程序僵死而不继续往下执行
httpUrlConn.setConnectTimeout(30*1000);//30s超时
httpUrlConn.setReadTimeout(10*1000);//10s超时
/*
//设置请求属性
httpUrlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpUrlConn.setRequestProperty("Charset", "UTF-8");
*/
//HttpURLConnection的connect()函数,实际上只是建立了一个与服务器的tcp连接,并没有实际发送http请求。
//get方式需要显式连接
if ("GET".equalsIgnoreCase(requestMethod)){
httpUrlConn.connect();
}
//这种post方式,隐式自动连接
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
resultStr = buffer.toString();
} catch (ConnectException ce) {
System.out.println("server connection timed out.");
} catch (Exception e) {
System.out.println(requestUrl+" request error:\n"+e);
}
return resultStr;
}
public static void main(String[] args) {
System.out.println(httpRequest("https://www.zhihu.com/", "GET", null));
}
} | false | 1,525 | 9 | 1,728 | 9 | 1,711 | 9 | 1,728 | 9 | 2,428 | 15 | false | false | false | false | false | true |
10566_5 | package cc.bitky.webserver.controller;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Supplier;
/**
* 假想敌服务
*
* @author limingliang
*/
@Controller
@RestController
@Slf4j
public class ImaginaryEnemyController {
/**
* 胡同
*/
@Setter
private static String alley = "";
/**
* 伙计刺探
*/
@GetMapping("/spyGuy/" + "**")
public ResponseEntity<Resource> spyElement(@RequestParam String guy) {
return run(() -> createResourceResponseEntity(searchGuy(alley, guy)));
}
/**
* 刺探医生
*/
@GetMapping("/spy/doc")
public ResponseEntity<Resource> spyDoc() {
return run(() -> createResourceResponseEntity(searchGuy(alley, "doc")));
}
/**
* 刺探德芙
*/
@GetMapping("/spy/dev")
public ResponseEntity<Resource> spyDev() {
return run(() -> createResourceResponseEntity(searchGuy(alley, "dev")));
}
/**
* 查找指定的伙计
*/
private Path searchGuy(String alley, String guy) {
Path houseNumber = Paths.get(alley, guy);
File house = houseNumber.toFile();
if (!house.exists()) {
throw new RuntimeException("伙计不在家:" + houseNumber);
}
if (!house.canRead()) {
throw new RuntimeException("伙计拒绝见面:" + houseNumber);
}
return houseNumber;
}
private ResponseEntity run(Supplier<ResponseEntity> runnable) {
try {
return runnable.get();
} catch (Exception e) {
return ResponseEntity.status(400)
.contentType(MediaType.parseMediaType("text/plain; charset=utf-8"))
.body(e.getMessage());
}
}
private ResponseEntity<Resource> createResourceResponseEntity(Path filePath) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentDisposition(ContentDisposition.attachment()
.filename(filePath.getFileName().toString(), StandardCharsets.UTF_8)
.build());
Resource resource = new UrlResource(filePath.toUri());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.headers(headers)
.body(resource);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
}
| bitkylin/featureLab | bitkylin-webserver/src/main/java/cc/bitky/webserver/controller/ImaginaryEnemyController.java | 711 | /**
* 查找指定的伙计
*/ | block_comment | zh-cn | package cc.bitky.webserver.controller;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Supplier;
/**
* 假想敌服务
*
* @author limingliang
*/
@Controller
@RestController
@Slf4j
public class ImaginaryEnemyController {
/**
* 胡同
*/
@Setter
private static String alley = "";
/**
* 伙计刺探
*/
@GetMapping("/spyGuy/" + "**")
public ResponseEntity<Resource> spyElement(@RequestParam String guy) {
return run(() -> createResourceResponseEntity(searchGuy(alley, guy)));
}
/**
* 刺探医生
*/
@GetMapping("/spy/doc")
public ResponseEntity<Resource> spyDoc() {
return run(() -> createResourceResponseEntity(searchGuy(alley, "doc")));
}
/**
* 刺探德芙
*/
@GetMapping("/spy/dev")
public ResponseEntity<Resource> spyDev() {
return run(() -> createResourceResponseEntity(searchGuy(alley, "dev")));
}
/**
* 查找指 <SUF>*/
private Path searchGuy(String alley, String guy) {
Path houseNumber = Paths.get(alley, guy);
File house = houseNumber.toFile();
if (!house.exists()) {
throw new RuntimeException("伙计不在家:" + houseNumber);
}
if (!house.canRead()) {
throw new RuntimeException("伙计拒绝见面:" + houseNumber);
}
return houseNumber;
}
private ResponseEntity run(Supplier<ResponseEntity> runnable) {
try {
return runnable.get();
} catch (Exception e) {
return ResponseEntity.status(400)
.contentType(MediaType.parseMediaType("text/plain; charset=utf-8"))
.body(e.getMessage());
}
}
private ResponseEntity<Resource> createResourceResponseEntity(Path filePath) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentDisposition(ContentDisposition.attachment()
.filename(filePath.getFileName().toString(), StandardCharsets.UTF_8)
.build());
Resource resource = new UrlResource(filePath.toUri());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_OCTET_STREAM)
.headers(headers)
.body(resource);
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
}
}
}
| false | 577 | 12 | 711 | 11 | 739 | 12 | 711 | 11 | 898 | 19 | false | false | false | false | false | true |
40350_3 | package com.yuncheng.china.Fanju.db.domain.user;
/**
* Created by agonyice on 09/09/14.
*/
public class UserData extends User {
private int userId;
private String phone;
private int inCome;//收入
private String cityName;
private int cityId;
private int professional;//职业
private int marriage;//感情
private int smoking;//是否喝酒
private int drinking;//是否吸烟
private int remark;//个人备注
public int getRemark() {
return remark;
}
public void setRemark(int remark) {
this.remark = remark;
}
public int getDrinking() {
return drinking;
}
public void setDrinking(int drinking) {
this.drinking = drinking;
}
public int getSmoking() {
return smoking;
}
public void setSmoking(int smoking) {
this.smoking = smoking;
}
public int getMarriage() {
return marriage;
}
public void setMarriage(int marriage) {
this.marriage = marriage;
}
public int getProfessional() {
return professional;
}
public void setProfessional(int professional) {
this.professional = professional;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getInCome() {
return inCome;
}
public void setInCome(int inCome) {
this.inCome = inCome;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
| biztrology-kd/FanJu | src/com/yuncheng/china/Fanju/db/domain/user/UserData.java | 494 | //个人备注 | line_comment | zh-cn | package com.yuncheng.china.Fanju.db.domain.user;
/**
* Created by agonyice on 09/09/14.
*/
public class UserData extends User {
private int userId;
private String phone;
private int inCome;//收入
private String cityName;
private int cityId;
private int professional;//职业
private int marriage;//感情
private int smoking;//是否喝酒
private int drinking;//是否吸烟
private int remark;//个人 <SUF>
public int getRemark() {
return remark;
}
public void setRemark(int remark) {
this.remark = remark;
}
public int getDrinking() {
return drinking;
}
public void setDrinking(int drinking) {
this.drinking = drinking;
}
public int getSmoking() {
return smoking;
}
public void setSmoking(int smoking) {
this.smoking = smoking;
}
public int getMarriage() {
return marriage;
}
public void setMarriage(int marriage) {
this.marriage = marriage;
}
public int getProfessional() {
return professional;
}
public void setProfessional(int professional) {
this.professional = professional;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getInCome() {
return inCome;
}
public void setInCome(int inCome) {
this.inCome = inCome;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
| false | 431 | 3 | 494 | 4 | 515 | 3 | 494 | 4 | 613 | 7 | false | false | false | false | false | true |
10031_1 | package com.mashibing.dp.Iterator.v7;
/**
* 相比数组,这个容器不用考虑边界问题,可以动态扩展
*/
class ArrayList_<E> implements Collection_<E> {
E[] objects = (E[])new Object[10];
//objects中下一个空的位置在哪儿,或者说,目前容器中有多少个元素
private int index = 0;
public void add(E o) {
if(index == objects.length) {
E[] newObjects = (E[])new Object[objects.length*2];
System.arraycopy(objects, 0, newObjects, 0, objects.length);
objects = newObjects;
}
objects[index] = o;
index ++;
}
public int size() {
return index;
}
@Override
public Iterator_<E> iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator<E> implements Iterator_<E> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
if(currentIndex >= index) return false;
return true;
}
@Override
public E next() {
E o = (E)objects[currentIndex];
currentIndex ++;
return o;
}
}
} | bjmashibing/DesignPatterns | src/main/java/com/mashibing/dp/Iterator/v7/ArrayList_.java | 288 | //objects中下一个空的位置在哪儿,或者说,目前容器中有多少个元素 | line_comment | zh-cn | package com.mashibing.dp.Iterator.v7;
/**
* 相比数组,这个容器不用考虑边界问题,可以动态扩展
*/
class ArrayList_<E> implements Collection_<E> {
E[] objects = (E[])new Object[10];
//ob <SUF>
private int index = 0;
public void add(E o) {
if(index == objects.length) {
E[] newObjects = (E[])new Object[objects.length*2];
System.arraycopy(objects, 0, newObjects, 0, objects.length);
objects = newObjects;
}
objects[index] = o;
index ++;
}
public int size() {
return index;
}
@Override
public Iterator_<E> iterator() {
return new ArrayListIterator();
}
private class ArrayListIterator<E> implements Iterator_<E> {
private int currentIndex = 0;
@Override
public boolean hasNext() {
if(currentIndex >= index) return false;
return true;
}
@Override
public E next() {
E o = (E)objects[currentIndex];
currentIndex ++;
return o;
}
}
} | false | 265 | 17 | 288 | 22 | 310 | 18 | 288 | 22 | 368 | 33 | false | false | false | false | false | true |
2774_7 | package org.ormtest.step010;
import org.ormtest.step010.entity.UserEntity;
import org.ormtest.step010.entity.UserEntity_Helper;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* 主应用程序类
*/
public class App010 {
/**
* 应用程序主函数
*
* @param argvArray 参数数组
* @throws Exception
*/
static public void main(String[] argvArray) throws Exception {
(new App010()).start();
}
/**
* 测试开始
*/
private void start() throws Exception {
// 加载 Mysql 驱动
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
// 数据库连接地址
String dbConnStr = "jdbc:mysql://localhost:3306/ormtest?user=root&password=root";
// 创建数据库连接
Connection conn = DriverManager.getConnection(dbConnStr);
// 简历陈述对象
Statement stmt = conn.createStatement();
// 创建 SQL 查询
String sql = "select * from t_user limit 200000";
// 执行查询
ResultSet rs = stmt.executeQuery(sql);
// 创建助手类
UserEntity_Helper helper = new UserEntity_Helper();
// 获取开始时间
long t0 = System.currentTimeMillis();
while (rs.next()) {
// 创建新的实体对象,
// 这里已经把创建过程封装到助手类中了...
// 这么做的好处 step000 中已经提到过了
UserEntity ue = helper.create(rs);
}
// 获取结束时间
long t1 = System.currentTimeMillis();
// 关闭数据库连接
stmt.close();
conn.close();
// 打印实例化花费时间
System.out.println("实例化花费时间 = " + (t1 - t0) + "ms");
}
}
| bjmashibing/InternetArchitect | 14二期英雄传说/Java_游戏开发入门-第四课/ormtest/src/main/java/org/ormtest/step010/App010.java | 469 | // 简历陈述对象 | line_comment | zh-cn | package org.ormtest.step010;
import org.ormtest.step010.entity.UserEntity;
import org.ormtest.step010.entity.UserEntity_Helper;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* 主应用程序类
*/
public class App010 {
/**
* 应用程序主函数
*
* @param argvArray 参数数组
* @throws Exception
*/
static public void main(String[] argvArray) throws Exception {
(new App010()).start();
}
/**
* 测试开始
*/
private void start() throws Exception {
// 加载 Mysql 驱动
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
// 数据库连接地址
String dbConnStr = "jdbc:mysql://localhost:3306/ormtest?user=root&password=root";
// 创建数据库连接
Connection conn = DriverManager.getConnection(dbConnStr);
// 简历 <SUF>
Statement stmt = conn.createStatement();
// 创建 SQL 查询
String sql = "select * from t_user limit 200000";
// 执行查询
ResultSet rs = stmt.executeQuery(sql);
// 创建助手类
UserEntity_Helper helper = new UserEntity_Helper();
// 获取开始时间
long t0 = System.currentTimeMillis();
while (rs.next()) {
// 创建新的实体对象,
// 这里已经把创建过程封装到助手类中了...
// 这么做的好处 step000 中已经提到过了
UserEntity ue = helper.create(rs);
}
// 获取结束时间
long t1 = System.currentTimeMillis();
// 关闭数据库连接
stmt.close();
conn.close();
// 打印实例化花费时间
System.out.println("实例化花费时间 = " + (t1 - t0) + "ms");
}
}
| false | 422 | 7 | 469 | 7 | 487 | 6 | 469 | 7 | 636 | 14 | false | false | false | false | false | true |
20915_6 | /**
* 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法,
* 能够支持2个生产者线程以及10个消费者线程的阻塞调用
*
* 使用wait和notify/notifyAll来实现
*
* 使用Lock和Condition来实现
* 对比两种方式,Condition的方式可以更加精确的指定哪些线程被唤醒
*
* @author mashibing
*/
package com.mashibing.juc.c_021_01_interview;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyContainer2<T> {
final private LinkedList<T> lists = new LinkedList<>();
final private int MAX = 10; //最多10个元素
private int count = 0;
private Lock lock = new ReentrantLock();
private Condition producer = lock.newCondition();
private Condition consumer = lock.newCondition();
public void put(T t) {
try {
lock.lock();
while(lists.size() == MAX) { //想想为什么用while而不是用if?
producer.await();
}
lists.add(t);
++count;
consumer.signalAll(); //通知消费者线程进行消费
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public T get() {
T t = null;
try {
lock.lock();
while(lists.size() == 0) {
consumer.await();
}
t = lists.removeFirst();
count --;
producer.signalAll(); //通知生产者进行生产
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return t;
}
public static void main(String[] args) {
MyContainer2<String> c = new MyContainer2<>();
//启动消费者线程
for(int i=0; i<10; i++) {
new Thread(()->{
for(int j=0; j<5; j++) System.out.println(c.get());
}, "c" + i).start();
}
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
//启动生产者线程
for(int i=0; i<2; i++) {
new Thread(()->{
for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j);
}, "p" + i).start();
}
}
}
| bjmashibing/JUC | src/main/java/com/mashibing/juc/c_021_01_interview/MyContainer2.java | 703 | //启动生产者线程 | line_comment | zh-cn | /**
* 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法,
* 能够支持2个生产者线程以及10个消费者线程的阻塞调用
*
* 使用wait和notify/notifyAll来实现
*
* 使用Lock和Condition来实现
* 对比两种方式,Condition的方式可以更加精确的指定哪些线程被唤醒
*
* @author mashibing
*/
package com.mashibing.juc.c_021_01_interview;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MyContainer2<T> {
final private LinkedList<T> lists = new LinkedList<>();
final private int MAX = 10; //最多10个元素
private int count = 0;
private Lock lock = new ReentrantLock();
private Condition producer = lock.newCondition();
private Condition consumer = lock.newCondition();
public void put(T t) {
try {
lock.lock();
while(lists.size() == MAX) { //想想为什么用while而不是用if?
producer.await();
}
lists.add(t);
++count;
consumer.signalAll(); //通知消费者线程进行消费
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public T get() {
T t = null;
try {
lock.lock();
while(lists.size() == 0) {
consumer.await();
}
t = lists.removeFirst();
count --;
producer.signalAll(); //通知生产者进行生产
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return t;
}
public static void main(String[] args) {
MyContainer2<String> c = new MyContainer2<>();
//启动消费者线程
for(int i=0; i<10; i++) {
new Thread(()->{
for(int j=0; j<5; j++) System.out.println(c.get());
}, "c" + i).start();
}
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
//启动 <SUF>
for(int i=0; i<2; i++) {
new Thread(()->{
for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j);
}, "p" + i).start();
}
}
}
| false | 599 | 6 | 703 | 5 | 700 | 5 | 703 | 5 | 918 | 12 | false | false | false | false | false | true |
7159_8 | package com.mashibing.pc3;
/**
* @author: 马士兵教育
* @create: 2019-09-29 16:16
*/
public class Goods {
private String brand;
private String name;
//默认是不存在商品的,如果值等于true的话,代表有商品
private boolean flag = false;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//消费者获取商品
public synchronized void get(){
/*
* 如果flag等于false的话,意味着生产者没有生产商品,此时消费者无法消费,需要让消费者线程进入到阻塞状态,等待生产者生产,当
* 有商品之后,再开始消费
* */
if (!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者取走了"+this.getBrand()+"----"+this.getName());
flag = false;
//唤醒生产者去进行生产
notify();
}
//生产者生产商品
public synchronized void set(String brand,String name){
//当生产者抢占到cpu资源之后会判断当前对象是否有值,如果有的话,以为着消费者还没有消费,需要提醒消费者消费,同时
//当前线程进入阻塞状态,等待消费者取走商品之后,再次生产,如果没有的话,不需要等待,不需要进入阻塞状态,直接生产即可
if(flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setBrand(brand);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setName(name);
System.out.println("生产者生产了" + this.getBrand() + "--" + this.getName());
//如果代码执行到此处,意味着已经生产完成,需要将flag设置为true
flag = true;
//唤醒消费者去进行消费
notify();
}
}
| bjmashibing/java | javase/code/java_thread/src/com/mashibing/pc3/Goods.java | 557 | //如果代码执行到此处,意味着已经生产完成,需要将flag设置为true | line_comment | zh-cn | package com.mashibing.pc3;
/**
* @author: 马士兵教育
* @create: 2019-09-29 16:16
*/
public class Goods {
private String brand;
private String name;
//默认是不存在商品的,如果值等于true的话,代表有商品
private boolean flag = false;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//消费者获取商品
public synchronized void get(){
/*
* 如果flag等于false的话,意味着生产者没有生产商品,此时消费者无法消费,需要让消费者线程进入到阻塞状态,等待生产者生产,当
* 有商品之后,再开始消费
* */
if (!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("消费者取走了"+this.getBrand()+"----"+this.getName());
flag = false;
//唤醒生产者去进行生产
notify();
}
//生产者生产商品
public synchronized void set(String brand,String name){
//当生产者抢占到cpu资源之后会判断当前对象是否有值,如果有的话,以为着消费者还没有消费,需要提醒消费者消费,同时
//当前线程进入阻塞状态,等待消费者取走商品之后,再次生产,如果没有的话,不需要等待,不需要进入阻塞状态,直接生产即可
if(flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.setBrand(brand);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.setName(name);
System.out.println("生产者生产了" + this.getBrand() + "--" + this.getName());
//如果 <SUF>
flag = true;
//唤醒消费者去进行消费
notify();
}
}
| false | 504 | 18 | 557 | 20 | 586 | 17 | 557 | 20 | 841 | 37 | false | false | false | false | false | true |
25431_16 | package chapter6.part4;
import java.util.ArrayList;
import java.util.List;
public class AStar {
//迷宫地图
public static final int[][] MAZE = {
{ 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0 }
};
/**
* A星寻路主逻辑
* @param start 迷宫起点
* @param end 迷宫终点
*/
public static Grid aStarSearch(Grid start, Grid end) {
ArrayList<Grid> openList = new ArrayList<Grid>();
ArrayList<Grid> closeList = new ArrayList<Grid>();
//把起点加入 openList
openList.add(start);
//主循环,每一轮检查一个当前方格节点
while (openList.size() > 0) {
// 在openList中查找 F值最小的节点作为当前方格节点
Grid currentGrid = findMinGird(openList);
// 当前方格节点从openList中移除
openList.remove(currentGrid);
// 当前方格节点进入 closeList
closeList.add(currentGrid);
// 找到所有邻近节点
List<Grid> neighbors = findNeighbors(currentGrid, openList, closeList);
for (Grid grid : neighbors) {
//邻近节点不在openList中,标记父亲、G、H、F,并放入openList
grid.initGrid(currentGrid, end);
openList.add(grid);
}
//如果终点在openList中,直接返回终点格子
for (Grid grid : openList){
if ((grid.x == end.x) && (grid.y == end.y)) {
return grid;
}
}
}
//openList用尽,仍然找不到终点,说明终点不可到达,返回空
return null;
}
private static Grid findMinGird(ArrayList<Grid> openList) {
Grid tempGrid = openList.get(0);
for (Grid grid : openList) {
if (grid.f < tempGrid.f) {
tempGrid = grid;
}
}
return tempGrid;
}
private static ArrayList<Grid> findNeighbors(Grid grid, List<Grid> openList, List<Grid> closeList) {
ArrayList<Grid> gridList = new ArrayList<Grid>();
if (isValidGrid(grid.x, grid.y-1, openList, closeList)) {
gridList.add(new Grid(grid.x, grid.y - 1));
}
if (isValidGrid(grid.x, grid.y+1, openList, closeList)) {
gridList.add(new Grid(grid.x, grid.y + 1));
}
if (isValidGrid(grid.x-1, grid.y, openList, closeList)) {
gridList.add(new Grid(grid.x - 1, grid.y));
}
if (isValidGrid(grid.x+1, grid.y, openList, closeList)) {
gridList.add(new Grid(grid.x + 1, grid.y));
}
return gridList;
}
private static boolean isValidGrid(int x, int y, List<Grid> openList, List<Grid> closeList) {
//是否超过边界
if (x < 0 || x >= MAZE.length || y < 0 || y >= MAZE[0].length) {
return false;
}
//是否有障碍物
if(MAZE[x][y] == 1){
return false;
}
//是否已经在openList中
if(containGrid(openList, x, y)){
return false;
}
//是否已经在closeList中
if(containGrid(closeList, x, y)){
return false;
}
return true;
}
private static boolean containGrid(List<Grid> grids, int x, int y) {
for (Grid grid : grids) {
if ((grid.x == x) && (grid.y == y)) {
return true;
}
}
return false;
}
static class Grid {
public int x;
public int y;
public int f;
public int g;
public int h;
public Grid parent;
public Grid(int x, int y) {
this.x = x;
this.y = y;
}
public void initGrid(Grid parent, Grid end){
this.parent = parent;
this.g = parent.g + 1;
this.h = Math.abs(this.x - end.x) + Math.abs(this.y - end.y);
this.f = this.g + this.h;
}
}
public static void main(String[] args) {
//设置起点和终点
Grid startGrid = new Grid(2, 1);
Grid endGrid = new Grid(2, 5);
//搜索迷宫终点
Grid resultGrid = aStarSearch(startGrid, endGrid);
//回溯迷宫路径
ArrayList<Grid> path = new ArrayList<Grid>();
while (resultGrid != null) {
path.add(new Grid(resultGrid.x, resultGrid.y));
resultGrid = resultGrid.parent;
}
//输出迷宫和路径,路径用星号表示
for (int i = 0; i < MAZE.length; i++) {
for (int j = 0; j < MAZE[0].length; j++) {
if (containGrid(path, i, j)) {
System.out.print("*, ");
} else {
System.out.print(MAZE[i][j] + ", ");
}
}
System.out.println();
}
}
} | bjweimengshu/ProgrammerXiaohui | src/chapter6/part4/AStar.java | 1,431 | //搜索迷宫终点
| line_comment | zh-cn | package chapter6.part4;
import java.util.ArrayList;
import java.util.List;
public class AStar {
//迷宫地图
public static final int[][] MAZE = {
{ 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 1, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0 }
};
/**
* A星寻路主逻辑
* @param start 迷宫起点
* @param end 迷宫终点
*/
public static Grid aStarSearch(Grid start, Grid end) {
ArrayList<Grid> openList = new ArrayList<Grid>();
ArrayList<Grid> closeList = new ArrayList<Grid>();
//把起点加入 openList
openList.add(start);
//主循环,每一轮检查一个当前方格节点
while (openList.size() > 0) {
// 在openList中查找 F值最小的节点作为当前方格节点
Grid currentGrid = findMinGird(openList);
// 当前方格节点从openList中移除
openList.remove(currentGrid);
// 当前方格节点进入 closeList
closeList.add(currentGrid);
// 找到所有邻近节点
List<Grid> neighbors = findNeighbors(currentGrid, openList, closeList);
for (Grid grid : neighbors) {
//邻近节点不在openList中,标记父亲、G、H、F,并放入openList
grid.initGrid(currentGrid, end);
openList.add(grid);
}
//如果终点在openList中,直接返回终点格子
for (Grid grid : openList){
if ((grid.x == end.x) && (grid.y == end.y)) {
return grid;
}
}
}
//openList用尽,仍然找不到终点,说明终点不可到达,返回空
return null;
}
private static Grid findMinGird(ArrayList<Grid> openList) {
Grid tempGrid = openList.get(0);
for (Grid grid : openList) {
if (grid.f < tempGrid.f) {
tempGrid = grid;
}
}
return tempGrid;
}
private static ArrayList<Grid> findNeighbors(Grid grid, List<Grid> openList, List<Grid> closeList) {
ArrayList<Grid> gridList = new ArrayList<Grid>();
if (isValidGrid(grid.x, grid.y-1, openList, closeList)) {
gridList.add(new Grid(grid.x, grid.y - 1));
}
if (isValidGrid(grid.x, grid.y+1, openList, closeList)) {
gridList.add(new Grid(grid.x, grid.y + 1));
}
if (isValidGrid(grid.x-1, grid.y, openList, closeList)) {
gridList.add(new Grid(grid.x - 1, grid.y));
}
if (isValidGrid(grid.x+1, grid.y, openList, closeList)) {
gridList.add(new Grid(grid.x + 1, grid.y));
}
return gridList;
}
private static boolean isValidGrid(int x, int y, List<Grid> openList, List<Grid> closeList) {
//是否超过边界
if (x < 0 || x >= MAZE.length || y < 0 || y >= MAZE[0].length) {
return false;
}
//是否有障碍物
if(MAZE[x][y] == 1){
return false;
}
//是否已经在openList中
if(containGrid(openList, x, y)){
return false;
}
//是否已经在closeList中
if(containGrid(closeList, x, y)){
return false;
}
return true;
}
private static boolean containGrid(List<Grid> grids, int x, int y) {
for (Grid grid : grids) {
if ((grid.x == x) && (grid.y == y)) {
return true;
}
}
return false;
}
static class Grid {
public int x;
public int y;
public int f;
public int g;
public int h;
public Grid parent;
public Grid(int x, int y) {
this.x = x;
this.y = y;
}
public void initGrid(Grid parent, Grid end){
this.parent = parent;
this.g = parent.g + 1;
this.h = Math.abs(this.x - end.x) + Math.abs(this.y - end.y);
this.f = this.g + this.h;
}
}
public static void main(String[] args) {
//设置起点和终点
Grid startGrid = new Grid(2, 1);
Grid endGrid = new Grid(2, 5);
//搜索 <SUF>
Grid resultGrid = aStarSearch(startGrid, endGrid);
//回溯迷宫路径
ArrayList<Grid> path = new ArrayList<Grid>();
while (resultGrid != null) {
path.add(new Grid(resultGrid.x, resultGrid.y));
resultGrid = resultGrid.parent;
}
//输出迷宫和路径,路径用星号表示
for (int i = 0; i < MAZE.length; i++) {
for (int j = 0; j < MAZE[0].length; j++) {
if (containGrid(path, i, j)) {
System.out.print("*, ");
} else {
System.out.print(MAZE[i][j] + ", ");
}
}
System.out.println();
}
}
} | false | 1,299 | 6 | 1,428 | 9 | 1,528 | 7 | 1,428 | 9 | 1,712 | 16 | false | false | false | false | false | true |
6081_4 | package com.lijiaqi.bedrock;
import com.lijiaqi.bedrock.protect.AndroidPlatformProtect;
import com.lijiaqi.bedrock.protect.handler.DefaultActivityExceptionHandler;
import io.flutter.app.FlutterApplication;
/**
* @author LiJiaqi
* @date 2020/12/12
* Description:
*
* Tip 1:
* 如果你有闪屏页优化需求,可以参考这篇文章,也许对你有所帮助。
* https://juejin.cn/post/6913360134429376525
*/
public class BaseApp extends FlutterApplication {
@Override
public void onCreate() {
super.onCreate();
// 如果是纯flutter项目,
// 可以考虑注释掉这两个保护[protectUIThread]和[protectActivityStart]
// 混合项目的话,可以考虑开启
AndroidPlatformProtect.initProtect(new DefaultActivityExceptionHandler())
///处理UI线程的异常
//.protectUIThread()
///处理 activity生命周期的异常
//注释原因: <activity启动保护> 功能,使用了反射。
// 在混淆下可能会无效或者出现无法预知的问题,建议开启后反复测试
//.protectActivityStart()
///处理子线程异常
.protectChildThread()
.init(this);
}
}
| bladeofgod/Bedrock | android/app/src/main/java/com/lijiaqi/bedrock/BaseApp.java | 329 | ///处理UI线程的异常 | line_comment | zh-cn | package com.lijiaqi.bedrock;
import com.lijiaqi.bedrock.protect.AndroidPlatformProtect;
import com.lijiaqi.bedrock.protect.handler.DefaultActivityExceptionHandler;
import io.flutter.app.FlutterApplication;
/**
* @author LiJiaqi
* @date 2020/12/12
* Description:
*
* Tip 1:
* 如果你有闪屏页优化需求,可以参考这篇文章,也许对你有所帮助。
* https://juejin.cn/post/6913360134429376525
*/
public class BaseApp extends FlutterApplication {
@Override
public void onCreate() {
super.onCreate();
// 如果是纯flutter项目,
// 可以考虑注释掉这两个保护[protectUIThread]和[protectActivityStart]
// 混合项目的话,可以考虑开启
AndroidPlatformProtect.initProtect(new DefaultActivityExceptionHandler())
///处理 <SUF>
//.protectUIThread()
///处理 activity生命周期的异常
//注释原因: <activity启动保护> 功能,使用了反射。
// 在混淆下可能会无效或者出现无法预知的问题,建议开启后反复测试
//.protectActivityStart()
///处理子线程异常
.protectChildThread()
.init(this);
}
}
| false | 297 | 7 | 329 | 6 | 323 | 6 | 329 | 6 | 466 | 11 | false | false | false | false | false | true |
23424_1 | package com.blossom.backend.base.auth.enums;
/**
* 打印请求日志的类型
*
* @author xzzz
*/
public enum LogTypeEnum {
/**
* 不打印请求日志
*/
none,
/**
* 打印简单的请求日志, 只有请求地址
*/
simple,
/**
* 答应详细的请求日志, 包含请求头, 请求参数, application/json 类型的请求体
*/
detail;
}
| blossom-editor/blossom | blossom-backend/backend/src/main/java/com/blossom/backend/base/auth/enums/LogTypeEnum.java | 110 | /**
* 不打印请求日志
*/ | block_comment | zh-cn | package com.blossom.backend.base.auth.enums;
/**
* 打印请求日志的类型
*
* @author xzzz
*/
public enum LogTypeEnum {
/**
* 不打印 <SUF>*/
none,
/**
* 打印简单的请求日志, 只有请求地址
*/
simple,
/**
* 答应详细的请求日志, 包含请求头, 请求参数, application/json 类型的请求体
*/
detail;
}
| false | 109 | 11 | 110 | 9 | 115 | 11 | 110 | 9 | 167 | 17 | false | false | false | false | false | true |
22551_3 | package com.capacity.smartglass.setup;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import com.capacity.smartglass.BaseSetupActivity;
import com.capacity.smartglass.R;
public class Setup2Activity extends BaseSetupActivity {
private static final String TAG = "HomeActivity";
private GridView gv_setup_gridview;
private MyAdapter adapter;
private String names[] = { "性别", "生日", "身高", "体重", "场景", "体质" };
private String contents[] = { "男", "15-8-24", "180cm", "68kg", "办公室", "良好" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup2);
gv_setup_gridview = (GridView) findViewById(R.id.gv_setup_gridview);
adapter = new MyAdapter();
gv_setup_gridview.setAdapter(adapter);
// 为gridview添加监听器
gv_setup_gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
// 性别选项(单选框)
checkDialog("性别选择", new String[] { "男", "女" });
break;
case 1:
// 生日选项(日期控件)
dateDialog();
break;
case 2:
// 身高选项(输入框)
inputDialog(R.layout.dialog_height, "请输入身高数值(cm)");
break;
case 3:
// 体重选项(输入框)
inputDialog(R.layout.dialog_height, "请输入体重数值(kg)");
break;
case 4:
// 场景设置(单选框)
checkDialog("场景设置", new String[] { "办公室", "家", "室外" });
break;
case 5:
// 体质设置(单选框)
checkDialog("体质设置", new String[] { "良好", "优秀", "较弱" });
default:
break;
}
}
/**
* 输入框
*/
private void inputDialog(int view, String title) {
View v = View.inflate(getApplicationContext(), view, null);
AlertDialog.Builder input = new AlertDialog.Builder(
Setup2Activity.this);
input.setTitle(title);
input.setView(v);
input.setPositiveButton("确定", null);
input.show();
}
/**
* 日期控件
*/
private void dateDialog() {
View v = View.inflate(getApplicationContext(),
R.layout.dialog_date, null);
AlertDialog.Builder dateDialog = new AlertDialog.Builder(
Setup2Activity.this);
dateDialog.setTitle("日期选择");
dateDialog.setView(v);
dateDialog.setPositiveButton("确定", null);
dateDialog.show();
}
/**
* 单选框
*/
private void checkDialog(String title, String[] strs) {
AlertDialog.Builder sexDialog = new AlertDialog.Builder(
Setup2Activity.this);
sexDialog.setTitle(title);
sexDialog.setSingleChoiceItems(strs, 0, null);
sexDialog.setPositiveButton("确定", null);
sexDialog.setNegativeButton("取消", null);
sexDialog.show();
}
});
}
public void next(View view) {
showNext();
}
/**
* 配置GridView的适配器
*
* @author master
*
*/
private class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return names.length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(getApplicationContext(),
R.layout.list_item_setup2, null);
}
TextView textViewName = (TextView) convertView
.findViewById(R.id.tv_top_item);
TextView textViewContent = (TextView) convertView
.findViewById(R.id.tv_center_item);
textViewName.setText(names[position]);
textViewContent.setText(contents[position]);
return convertView;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
@Override
public void showPref() {
Intent i = new Intent(Setup2Activity.this, Setup1Activity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.page_pref, R.anim.page_exit2);
}
@Override
public void showNext() {
Intent i = new Intent(Setup2Activity.this, Setup3Activity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.page_next, R.anim.page_exit);
}
}
| blue-fly/smartglass | src/com/capacity/smartglass/setup/Setup2Activity.java | 1,358 | // 身高选项(输入框) | line_comment | zh-cn | package com.capacity.smartglass.setup;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;
import com.capacity.smartglass.BaseSetupActivity;
import com.capacity.smartglass.R;
public class Setup2Activity extends BaseSetupActivity {
private static final String TAG = "HomeActivity";
private GridView gv_setup_gridview;
private MyAdapter adapter;
private String names[] = { "性别", "生日", "身高", "体重", "场景", "体质" };
private String contents[] = { "男", "15-8-24", "180cm", "68kg", "办公室", "良好" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup2);
gv_setup_gridview = (GridView) findViewById(R.id.gv_setup_gridview);
adapter = new MyAdapter();
gv_setup_gridview.setAdapter(adapter);
// 为gridview添加监听器
gv_setup_gridview.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch (position) {
case 0:
// 性别选项(单选框)
checkDialog("性别选择", new String[] { "男", "女" });
break;
case 1:
// 生日选项(日期控件)
dateDialog();
break;
case 2:
// 身高 <SUF>
inputDialog(R.layout.dialog_height, "请输入身高数值(cm)");
break;
case 3:
// 体重选项(输入框)
inputDialog(R.layout.dialog_height, "请输入体重数值(kg)");
break;
case 4:
// 场景设置(单选框)
checkDialog("场景设置", new String[] { "办公室", "家", "室外" });
break;
case 5:
// 体质设置(单选框)
checkDialog("体质设置", new String[] { "良好", "优秀", "较弱" });
default:
break;
}
}
/**
* 输入框
*/
private void inputDialog(int view, String title) {
View v = View.inflate(getApplicationContext(), view, null);
AlertDialog.Builder input = new AlertDialog.Builder(
Setup2Activity.this);
input.setTitle(title);
input.setView(v);
input.setPositiveButton("确定", null);
input.show();
}
/**
* 日期控件
*/
private void dateDialog() {
View v = View.inflate(getApplicationContext(),
R.layout.dialog_date, null);
AlertDialog.Builder dateDialog = new AlertDialog.Builder(
Setup2Activity.this);
dateDialog.setTitle("日期选择");
dateDialog.setView(v);
dateDialog.setPositiveButton("确定", null);
dateDialog.show();
}
/**
* 单选框
*/
private void checkDialog(String title, String[] strs) {
AlertDialog.Builder sexDialog = new AlertDialog.Builder(
Setup2Activity.this);
sexDialog.setTitle(title);
sexDialog.setSingleChoiceItems(strs, 0, null);
sexDialog.setPositiveButton("确定", null);
sexDialog.setNegativeButton("取消", null);
sexDialog.show();
}
});
}
public void next(View view) {
showNext();
}
/**
* 配置GridView的适配器
*
* @author master
*
*/
private class MyAdapter extends BaseAdapter {
@Override
public int getCount() {
return names.length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = View.inflate(getApplicationContext(),
R.layout.list_item_setup2, null);
}
TextView textViewName = (TextView) convertView
.findViewById(R.id.tv_top_item);
TextView textViewContent = (TextView) convertView
.findViewById(R.id.tv_center_item);
textViewName.setText(names[position]);
textViewContent.setText(contents[position]);
return convertView;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
}
@Override
public void showPref() {
Intent i = new Intent(Setup2Activity.this, Setup1Activity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.page_pref, R.anim.page_exit2);
}
@Override
public void showNext() {
Intent i = new Intent(Setup2Activity.this, Setup3Activity.class);
startActivity(i);
finish();
overridePendingTransition(R.anim.page_next, R.anim.page_exit);
}
}
| false | 1,082 | 9 | 1,358 | 9 | 1,327 | 8 | 1,358 | 9 | 1,824 | 13 | false | false | false | false | false | true |
35828_0 | package com.client;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.feign.api.Product;
import com.feign.api.User;
import com.feign.core.EurakeServer;
import com.feign.core.Feign;
import com.feign.logger.Logger;
import com.feign.logger.LoggerFactory;
import com.feign.service.PersonClient;
import com.feign.service.ProductClient;
public class FeignTester {
private static Logger log = LoggerFactory.getLogger(FeignTester.class);
private static Map<String, EurakeServer> eurakeServerMaps = null;
static {
eurakeServerMaps = new HashMap<String, EurakeServer>() {
private static final long serialVersionUID = 1L;
{
put("feign-server",
EurakeServer.builder().serverName("feign-server").serverURL("127.0.0.1:80").build());
put("feign-server02",
EurakeServer.builder().serverName("feign-server02").serverURL("127.0.0.1:81").build());
}
};
}
public static void main(String[] args) {
// 1.简单字符串返回值
Product para = Product.builder().name("ipad").price(new BigDecimal(10000)).build();
ProductClient client = Feign.builder().target(ProductClient.class);
Product p = client.saveProduct(para);
User upara = User.builder().name("李斯").desc("宰相").salary(new BigDecimal(10000)).build();
PersonClient PersonClient = Feign.builder().target(PersonClient.class);
User u = PersonClient.toHello3(upara);
log.info(JSONObject.toJSONString(p) + ">>>>>" + JSONObject.toJSONString(u));
}
public static void testCase2() {
// 1.简单字符串返回值
Product para = Product.builder().name("ipad").price(new BigDecimal(10000)).build();
ProductClient client = Feign.builder(eurakeServerMaps).target(ProductClient.class);
Product p = client.saveProduct(para);
User upara = User.builder().name("李斯").desc("宰相").salary(new BigDecimal(10000)).build();
PersonClient PersonClient = Feign.builder(eurakeServerMaps).target(PersonClient.class);
User u = PersonClient.toHello3(upara);
log.info(JSONObject.toJSONString(p) + ">>>>>" + JSONObject.toJSONString(u));
}
public static void testCase1() {
// 1.简单字符串返回值
User para = User.builder().name("李斯").desc("宰相").salary(new BigDecimal(10000)).build();
PersonClient client = Feign.builder().target(PersonClient.class);
// String result = client.toHello("张三");
// String result = client.toHello1(para);
// User result = client.toHello2("张三", "好人");
User result = client.toHello3(para);
log.info(JSONObject.toJSONString(result));
// User postUser = client.postUser("张三", "好人");
// log.info(JSONObject.toJSONString(postUser));
// User u = client.postUser("李斯","宰相");
// String u = client.postUser1(para);
// User u = client.postUser2("李斯","宰相");
// User u = client.postUser3(para);
// String u = client.postUser4("李斯","宰相");
// log.info(u);
}
}
| blue19demon/open-feign | feign-action/feign-client/src/main/java/com/client/FeignTester.java | 952 | // 1.简单字符串返回值 | line_comment | zh-cn | package com.client;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSONObject;
import com.feign.api.Product;
import com.feign.api.User;
import com.feign.core.EurakeServer;
import com.feign.core.Feign;
import com.feign.logger.Logger;
import com.feign.logger.LoggerFactory;
import com.feign.service.PersonClient;
import com.feign.service.ProductClient;
public class FeignTester {
private static Logger log = LoggerFactory.getLogger(FeignTester.class);
private static Map<String, EurakeServer> eurakeServerMaps = null;
static {
eurakeServerMaps = new HashMap<String, EurakeServer>() {
private static final long serialVersionUID = 1L;
{
put("feign-server",
EurakeServer.builder().serverName("feign-server").serverURL("127.0.0.1:80").build());
put("feign-server02",
EurakeServer.builder().serverName("feign-server02").serverURL("127.0.0.1:81").build());
}
};
}
public static void main(String[] args) {
// 1. <SUF>
Product para = Product.builder().name("ipad").price(new BigDecimal(10000)).build();
ProductClient client = Feign.builder().target(ProductClient.class);
Product p = client.saveProduct(para);
User upara = User.builder().name("李斯").desc("宰相").salary(new BigDecimal(10000)).build();
PersonClient PersonClient = Feign.builder().target(PersonClient.class);
User u = PersonClient.toHello3(upara);
log.info(JSONObject.toJSONString(p) + ">>>>>" + JSONObject.toJSONString(u));
}
public static void testCase2() {
// 1.简单字符串返回值
Product para = Product.builder().name("ipad").price(new BigDecimal(10000)).build();
ProductClient client = Feign.builder(eurakeServerMaps).target(ProductClient.class);
Product p = client.saveProduct(para);
User upara = User.builder().name("李斯").desc("宰相").salary(new BigDecimal(10000)).build();
PersonClient PersonClient = Feign.builder(eurakeServerMaps).target(PersonClient.class);
User u = PersonClient.toHello3(upara);
log.info(JSONObject.toJSONString(p) + ">>>>>" + JSONObject.toJSONString(u));
}
public static void testCase1() {
// 1.简单字符串返回值
User para = User.builder().name("李斯").desc("宰相").salary(new BigDecimal(10000)).build();
PersonClient client = Feign.builder().target(PersonClient.class);
// String result = client.toHello("张三");
// String result = client.toHello1(para);
// User result = client.toHello2("张三", "好人");
User result = client.toHello3(para);
log.info(JSONObject.toJSONString(result));
// User postUser = client.postUser("张三", "好人");
// log.info(JSONObject.toJSONString(postUser));
// User u = client.postUser("李斯","宰相");
// String u = client.postUser1(para);
// User u = client.postUser2("李斯","宰相");
// User u = client.postUser3(para);
// String u = client.postUser4("李斯","宰相");
// log.info(u);
}
}
| false | 778 | 8 | 952 | 8 | 930 | 7 | 952 | 8 | 1,077 | 14 | false | false | false | false | false | true |
46959_4 | package integerArray;
import java.util.Arrays;
import java.util.Comparator;
/**
* Created by Lenovo on 2017/6/12.
* http://www.lintcode.com/en/problem/subarray-sum-closest/
* https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/72950
* http://www.jiuzhang.com/solution/subarray-sum-closest
*/
/*
*
*
* 1. 首先遍历一次数组求得子串和Prefix Sum。
2. 对子串和排序。
3. 逐个比较相邻两项差值的绝对值,返回差值绝对值最小的两项。
问:为什么需要一个 (0,0) 的初始 Pair?
答:
我们首先需要回顾一下,在 subarray 这节课里,我们讲过一个重要的知识点,叫做 Prefix Sum
比如对于数组 [1,2,3,4],他的 Prefix Sum 是 [1,3,6,10]
分别表示 前1个数之和,前2个数之和,前3个数之和,前4个数之和
这个时候如果你想要知道 子数组 从下标 1 到下标 2 的这一段的和(2+3),就用前 3个数之和 减去 前1个数之和 = PrefixSum[2] - PrefixSum[0] = 6 - 1 = 5
你可以看到这里的 前 x 个数,和具体对应的下标之间,存在 +-1 的问题
第 x 个数的下标是 x - 1,反之 下标 x 是第 x + 1 个数
那么问题来了,如果要计算 下标从 0~2 这一段呢?也就是第1个数到第3个数,因为那样会访问到 PrefixSum[-1]
所以我们把 PrefixSum 整体往后面移动一位,把第0位空出来表示前0个数之和,也就是0. => [0,1,3,6,10]
那么此时就用 PrefixSum[3] - PrefixSum[0] ,这样计算就更方便了。
此时,PrefixSum[i] 代表 前i个数之和,也就是 下标区间在 0 ~ i-1 这一段的和
那么回过头来看看,为什么我们需要一个 (0,0) 的 pair 呢?
因为 这个 0,0 代表的就是前0个数之和为0
一个 n 个数的数组, 变成了 prefix Sum 数组之后,会多一个数出来
*/
class Pair {
int sum;
int index;
public Pair(int s, int i) {
sum = s;
index = i;
}
}
public class SubarraySumClosest {
public static int[] subarraySumClosest(int[] nums) {
// write your code here
int[] res = new int[2];
if (nums == null || nums.length == 0) {
return res;
}
int len = nums.length;
if(len == 1) {
res[0] = res[1] = 0;
return res;
}
// Prefix Sum 数组
Pair[] sums = new Pair[len+1];
int prev = 0;
sums[0] = new Pair(0, 0);
for (int i = 1; i <= len; i++) {
sums[i] = new Pair(prev + nums[i-1], i);
prev = sums[i].sum;
}
// 对子串和排序
Arrays.sort(sums, new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
return a.sum - b.sum;
}
});
int ans = Integer.MAX_VALUE;
for (int i = 1; i <= len; i++) {
if (ans > sums[i].sum - sums[i-1].sum) {
ans = sums[i].sum - sums[i-1].sum;
int[] temp = new int[]{sums[i].index - 1, sums[i - 1].index - 1};
Arrays.sort(temp);
res[0] = temp[0] + 1;
res[1] = temp[1];
}
}
return res;
}
public static void main(String[] args){
int[] A = {-3, 1, 1, -3, 5};
subarraySumClosest(A);
}
}
| bluedusk/lintCode_Java | src/integerArray/SubarraySumClosest.java | 1,061 | // 对子串和排序 | line_comment | zh-cn | package integerArray;
import java.util.Arrays;
import java.util.Comparator;
/**
* Created by Lenovo on 2017/6/12.
* http://www.lintcode.com/en/problem/subarray-sum-closest/
* https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/72950
* http://www.jiuzhang.com/solution/subarray-sum-closest
*/
/*
*
*
* 1. 首先遍历一次数组求得子串和Prefix Sum。
2. 对子串和排序。
3. 逐个比较相邻两项差值的绝对值,返回差值绝对值最小的两项。
问:为什么需要一个 (0,0) 的初始 Pair?
答:
我们首先需要回顾一下,在 subarray 这节课里,我们讲过一个重要的知识点,叫做 Prefix Sum
比如对于数组 [1,2,3,4],他的 Prefix Sum 是 [1,3,6,10]
分别表示 前1个数之和,前2个数之和,前3个数之和,前4个数之和
这个时候如果你想要知道 子数组 从下标 1 到下标 2 的这一段的和(2+3),就用前 3个数之和 减去 前1个数之和 = PrefixSum[2] - PrefixSum[0] = 6 - 1 = 5
你可以看到这里的 前 x 个数,和具体对应的下标之间,存在 +-1 的问题
第 x 个数的下标是 x - 1,反之 下标 x 是第 x + 1 个数
那么问题来了,如果要计算 下标从 0~2 这一段呢?也就是第1个数到第3个数,因为那样会访问到 PrefixSum[-1]
所以我们把 PrefixSum 整体往后面移动一位,把第0位空出来表示前0个数之和,也就是0. => [0,1,3,6,10]
那么此时就用 PrefixSum[3] - PrefixSum[0] ,这样计算就更方便了。
此时,PrefixSum[i] 代表 前i个数之和,也就是 下标区间在 0 ~ i-1 这一段的和
那么回过头来看看,为什么我们需要一个 (0,0) 的 pair 呢?
因为 这个 0,0 代表的就是前0个数之和为0
一个 n 个数的数组, 变成了 prefix Sum 数组之后,会多一个数出来
*/
class Pair {
int sum;
int index;
public Pair(int s, int i) {
sum = s;
index = i;
}
}
public class SubarraySumClosest {
public static int[] subarraySumClosest(int[] nums) {
// write your code here
int[] res = new int[2];
if (nums == null || nums.length == 0) {
return res;
}
int len = nums.length;
if(len == 1) {
res[0] = res[1] = 0;
return res;
}
// Prefix Sum 数组
Pair[] sums = new Pair[len+1];
int prev = 0;
sums[0] = new Pair(0, 0);
for (int i = 1; i <= len; i++) {
sums[i] = new Pair(prev + nums[i-1], i);
prev = sums[i].sum;
}
// 对子 <SUF>
Arrays.sort(sums, new Comparator<Pair>() {
public int compare(Pair a, Pair b) {
return a.sum - b.sum;
}
});
int ans = Integer.MAX_VALUE;
for (int i = 1; i <= len; i++) {
if (ans > sums[i].sum - sums[i-1].sum) {
ans = sums[i].sum - sums[i-1].sum;
int[] temp = new int[]{sums[i].index - 1, sums[i - 1].index - 1};
Arrays.sort(temp);
res[0] = temp[0] + 1;
res[1] = temp[1];
}
}
return res;
}
public static void main(String[] args){
int[] A = {-3, 1, 1, -3, 5};
subarraySumClosest(A);
}
}
| false | 987 | 6 | 1,061 | 6 | 1,060 | 6 | 1,061 | 6 | 1,328 | 10 | false | false | false | false | false | true |
48396_8 | package org.ssssssss.script.parsing;
import org.ssssssss.script.MagicScriptError;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 对List<Token>进行封装,提供匹配相关方法,方便语法解析
*/
public class TokenStream {
private final List<Token> tokens;
private final int end;
private int index;
public TokenStream(List<Token> tokens) {
this.tokens = tokens;
this.index = 0;
this.end = tokens.size();
}
/**
* 当前是否可读
**/
public boolean hasMore() {
return index < end;
}
/**
* 是否有下一个Token
*/
public boolean hasNext() {
return index + 1 < end;
}
/**
* 是否有前一个Token
*/
public boolean hasPrev() {
return index > 0;
}
/**
* 标记当前位置,和resetIndex搭配使用。
*/
public int makeIndex() {
return index;
}
/**
* 重置当前位置,和makeIndex搭配使用
*/
public void resetIndex(int index) {
this.index = index;
}
/**
* 无条件消耗掉当前Token
**/
public Token consume() {
if (!hasMore()) {
throw new RuntimeException("流已经遍历完毕");
}
return tokens.get(index++);
}
/**
* 获取下一个Token并改变当前位置
*/
public Token next() {
if (!hasMore()) {
throw new RuntimeException("流已经遍历完毕");
}
return tokens.get(++index);
}
/**
* 获取前一个Token并改变当前位置
*/
public Token prev() {
if (index == 0) {
throw new RuntimeException("流已经遍历完毕");
}
return tokens.get(--index);
}
/**
* 获取前一个Token,不改变当前位置
*/
public Token getPrev() {
if (index == 0) {
throw new RuntimeException("流已经遍历完毕");
}
return tokens.get(index - 1);
}
/**
* 期待下一个Token是给定的类型中之一
*/
public Token expect(TokenType ... types) {
if (!match(true, types)) {
Token token = index < tokens.size() ? tokens.get(index) : null;
Span span = token != null ? token.getSpan() : null;
if (span == null) {
MagicScriptError.error("期待 '" + Stream.of(types).map(TokenType::getError).collect(Collectors.joining("','")) + "', 但是流已经遍历完毕", this);
} else {
MagicScriptError.error("期待 '" + Stream.of(types).map(TokenType::getError).collect(Collectors.joining("','")) + "', 获得 '" + token.getText() + "'", span);
}
return null; // 执行不到这里
} else {
return tokens.get(index - 1);
}
}
/**
* 获取全部注释
*/
public List<Span> comments(){
return tokens.stream().filter(it -> it.getType() == TokenType.Comment).map(Token::getSpan).collect(Collectors.toList());
}
/**
* 期待下一个Token为指定类型
*/
public Token expect(TokenType type) {
if (!match(type, true)) {
Token token = index < tokens.size() ? tokens.get(index) : null;
Span span = token != null ? token.getSpan() : null;
if (span == null) {
MagicScriptError.error("期待 '" + type.getError() + "', 但是流已经遍历完毕", this);
} else {
MagicScriptError.error("期待 '" + type.getError() + "', 获得 '" + token.getText() + "'", span);
}
return null; // 执行不到这里
} else {
return tokens.get(index - 1);
}
}
/**
* 期待匹配字符串
*/
public Token expect(String text) {
return expect(text, false);
}
/**
* 期待匹配字符串
* @param ignoreCase 是否忽略大小写
*/
public Token expect(String text, boolean ignoreCase) {
boolean result = match(text, true, ignoreCase);
if (!result) {
Token token = index < tokens.size() ? tokens.get(index) : null;
Span span = token != null ? token.getSpan() : null;
if (span == null) {
MagicScriptError.error("期待 '" + text + "', 但是流已经遍历完毕", this);
} else {
MagicScriptError.error("期待 '" + text + "', 获得 '" + token.getText() + "'", span);
}
return null; // never reached
} else {
return tokens.get(index - 1);
}
}
/**
* 匹配指定类型Token
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(TokenType type, boolean consume) {
if (index >= end) {
return false;
}
if (tokens.get(index).getType() == type) {
if (consume) {
index++;
}
return true;
}
return false;
}
/**
* 匹配指定类型Token
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(List<String> texts, boolean consume) {
return match(texts, consume, false);
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
* @param ignoreCase 是否忽略大小写
*/
public boolean match(List<String> texts, boolean consume, boolean ignoreCase) {
for (String text : texts) {
if (match(text, consume, ignoreCase)) {
return true;
}
}
return false;
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
* @param ignoreCase 是否忽略大小写
*/
public boolean match(String text, boolean consume, boolean ignoreCase) {
if (index >= end) {
return false;
}
String matchText = tokens.get(index).getText();
if (ignoreCase ? matchText.equalsIgnoreCase(text) : matchText.equals(text)) {
if (consume) {
index++;
}
return true;
}
return false;
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(String text, boolean consume) {
return match(text, consume, false);
}
/**
* 匹配指定Token
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(boolean consume, TokenType... types) {
for (TokenType type : types) {
if (match(type, consume)) {
return true;
}
}
return false;
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(boolean consume, String... tokenTexts) {
return match(consume, false, tokenTexts);
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
* @param ignoreCase 是否忽略大小写
*/
public boolean match(boolean consume, boolean ignoreCase, String... tokenTexts) {
for (String text : tokenTexts) {
if (match(text, consume, ignoreCase)) {
return true;
}
}
return false;
}
}
| bluegitter/magic-script | src/main/java/org/ssssssss/script/parsing/TokenStream.java | 1,920 | /**
* 获取前一个Token并改变当前位置
*/ | block_comment | zh-cn | package org.ssssssss.script.parsing;
import org.ssssssss.script.MagicScriptError;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 对List<Token>进行封装,提供匹配相关方法,方便语法解析
*/
public class TokenStream {
private final List<Token> tokens;
private final int end;
private int index;
public TokenStream(List<Token> tokens) {
this.tokens = tokens;
this.index = 0;
this.end = tokens.size();
}
/**
* 当前是否可读
**/
public boolean hasMore() {
return index < end;
}
/**
* 是否有下一个Token
*/
public boolean hasNext() {
return index + 1 < end;
}
/**
* 是否有前一个Token
*/
public boolean hasPrev() {
return index > 0;
}
/**
* 标记当前位置,和resetIndex搭配使用。
*/
public int makeIndex() {
return index;
}
/**
* 重置当前位置,和makeIndex搭配使用
*/
public void resetIndex(int index) {
this.index = index;
}
/**
* 无条件消耗掉当前Token
**/
public Token consume() {
if (!hasMore()) {
throw new RuntimeException("流已经遍历完毕");
}
return tokens.get(index++);
}
/**
* 获取下一个Token并改变当前位置
*/
public Token next() {
if (!hasMore()) {
throw new RuntimeException("流已经遍历完毕");
}
return tokens.get(++index);
}
/**
* 获取前 <SUF>*/
public Token prev() {
if (index == 0) {
throw new RuntimeException("流已经遍历完毕");
}
return tokens.get(--index);
}
/**
* 获取前一个Token,不改变当前位置
*/
public Token getPrev() {
if (index == 0) {
throw new RuntimeException("流已经遍历完毕");
}
return tokens.get(index - 1);
}
/**
* 期待下一个Token是给定的类型中之一
*/
public Token expect(TokenType ... types) {
if (!match(true, types)) {
Token token = index < tokens.size() ? tokens.get(index) : null;
Span span = token != null ? token.getSpan() : null;
if (span == null) {
MagicScriptError.error("期待 '" + Stream.of(types).map(TokenType::getError).collect(Collectors.joining("','")) + "', 但是流已经遍历完毕", this);
} else {
MagicScriptError.error("期待 '" + Stream.of(types).map(TokenType::getError).collect(Collectors.joining("','")) + "', 获得 '" + token.getText() + "'", span);
}
return null; // 执行不到这里
} else {
return tokens.get(index - 1);
}
}
/**
* 获取全部注释
*/
public List<Span> comments(){
return tokens.stream().filter(it -> it.getType() == TokenType.Comment).map(Token::getSpan).collect(Collectors.toList());
}
/**
* 期待下一个Token为指定类型
*/
public Token expect(TokenType type) {
if (!match(type, true)) {
Token token = index < tokens.size() ? tokens.get(index) : null;
Span span = token != null ? token.getSpan() : null;
if (span == null) {
MagicScriptError.error("期待 '" + type.getError() + "', 但是流已经遍历完毕", this);
} else {
MagicScriptError.error("期待 '" + type.getError() + "', 获得 '" + token.getText() + "'", span);
}
return null; // 执行不到这里
} else {
return tokens.get(index - 1);
}
}
/**
* 期待匹配字符串
*/
public Token expect(String text) {
return expect(text, false);
}
/**
* 期待匹配字符串
* @param ignoreCase 是否忽略大小写
*/
public Token expect(String text, boolean ignoreCase) {
boolean result = match(text, true, ignoreCase);
if (!result) {
Token token = index < tokens.size() ? tokens.get(index) : null;
Span span = token != null ? token.getSpan() : null;
if (span == null) {
MagicScriptError.error("期待 '" + text + "', 但是流已经遍历完毕", this);
} else {
MagicScriptError.error("期待 '" + text + "', 获得 '" + token.getText() + "'", span);
}
return null; // never reached
} else {
return tokens.get(index - 1);
}
}
/**
* 匹配指定类型Token
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(TokenType type, boolean consume) {
if (index >= end) {
return false;
}
if (tokens.get(index).getType() == type) {
if (consume) {
index++;
}
return true;
}
return false;
}
/**
* 匹配指定类型Token
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(List<String> texts, boolean consume) {
return match(texts, consume, false);
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
* @param ignoreCase 是否忽略大小写
*/
public boolean match(List<String> texts, boolean consume, boolean ignoreCase) {
for (String text : texts) {
if (match(text, consume, ignoreCase)) {
return true;
}
}
return false;
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
* @param ignoreCase 是否忽略大小写
*/
public boolean match(String text, boolean consume, boolean ignoreCase) {
if (index >= end) {
return false;
}
String matchText = tokens.get(index).getText();
if (ignoreCase ? matchText.equalsIgnoreCase(text) : matchText.equals(text)) {
if (consume) {
index++;
}
return true;
}
return false;
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(String text, boolean consume) {
return match(text, consume, false);
}
/**
* 匹配指定Token
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(boolean consume, TokenType... types) {
for (TokenType type : types) {
if (match(type, consume)) {
return true;
}
}
return false;
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
*/
public boolean match(boolean consume, String... tokenTexts) {
return match(consume, false, tokenTexts);
}
/**
* 匹配指定字符串
* @param consume 匹配成功后是否改变当前位置
* @param ignoreCase 是否忽略大小写
*/
public boolean match(boolean consume, boolean ignoreCase, String... tokenTexts) {
for (String text : tokenTexts) {
if (match(text, consume, ignoreCase)) {
return true;
}
}
return false;
}
}
| false | 1,664 | 13 | 1,920 | 13 | 1,932 | 15 | 1,920 | 13 | 2,552 | 21 | false | false | false | false | false | true |
29153_10 | package top.qianxinyao.main;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import top.qianxinyao.UserBasedCollaborativeRecommender.MahoutUserBasedCollaborativeRecommender;
import top.qianxinyao.UserBasedCollaborativeRecommender.quartz.CFCronTriggerRunner;
import top.qianxinyao.algorithms.PropGetKit;
import top.qianxinyao.algorithms.RecommendKit;
import top.qianxinyao.contentbasedrecommend.ContentBasedRecommender;
import top.qianxinyao.contentbasedrecommend.quartz.CBCronTriggerRunner;
import top.qianxinyao.dbconnection.DBKit;
import top.qianxinyao.hotrecommend.HotRecommender;
import top.qianxinyao.hotrecommend.quartz.HRCronTriggerRunner;
/**
* @author Tom Qian
* @email tomqianmaple@outlook.com
* @github https://github.com/bluemapleman
* @date 2017年12月11日
* 设定/启动推荐任务的类
*/
public class JobSetter
{
public static final Logger logger=Logger.getLogger(JobSetter.class);
boolean enableCF,enableCB,enableHR;
/**
*
* @param enableCF 是否启用协同过滤(Collaborative Filtering)
* @param enableCB 是否启用基于内容的推荐(Content-Based Recommendation)
* @param enableHR 是否启用热点新闻推荐(Hot News Recommendation)
*/
public JobSetter(boolean enableCF,boolean enableCB,boolean enableHR) {
//加载系统配置文件
PropGetKit.loadProperties("paraConfig");
//初始化操作:主要是数据库的连接
DBKit.initalize();
this.enableCF=enableCF;
this.enableCB=enableCB;
this.enableHR=enableHR;
}
/**
* 使用Quartz的表达式进行时间设定(默认为每天0点开始工作),详情请参照:http://www.quartz-scheduler.org/api/2.2.1/index.html(CronExpression)
* 当启用该方法时,推荐系统可以保持运行,直到被强制关闭。
* @param userList
*/
private void executeQuartzJob(List<Long> userList) {
//设定推荐任务每天的执行时间
String cronExpression=PropGetKit.getString("startAt");
try
{
if(enableCF)
new CFCronTriggerRunner().task(userList,cronExpression);
if(enableCB)
new CBCronTriggerRunner().task(userList,cronExpression);
if(enableHR)
new HRCronTriggerRunner().task(userList,cronExpression);
}
catch (SchedulerException e)
{
e.printStackTrace();
}
System.out.println("本次推荐结束于"+new Date());
}
/**
* 为指定用户执行定时新闻推荐
* @param goalUserList 目标用户的id列表
*/
public void executeQuartzJobForCertainUsers(List<Long> goalUserList) {
executeQuartzJob(goalUserList);
}
/**
* 为所有用户执行定时新闻推荐
*/
public void executeQuartzJobForAllUsers() {
executeQuartzJob(RecommendKit.getAllUsers());
}
/**
* 为活跃用户进行定时新闻推荐。
* @param goalUserList
*/
public void executeQuartzJobForActiveUsers() {
executeQuartzJob(RecommendKit.getActiveUsers());
}
/**
* 执行一次新闻推荐
* 参数forActiveUsers表示是否只针对活跃用户进行新闻推荐,true为是,false为否。
* @param forActiveUsers
*/
private void executeInstantJob(List<Long> userIDList) {
//让热点新闻推荐器预先生成今日的热点新闻
HotRecommender.formTodayTopHotNewsList();
if(enableCF)
new MahoutUserBasedCollaborativeRecommender().recommend(userIDList);
if(enableCB)
new ContentBasedRecommender().recommend(userIDList);
if(enableHR)
new HotRecommender().recommend(userIDList);
System.out.println("本次推荐结束于"+new Date());
}
/**
* 执行一次新闻推荐
* 参数forActiveUsers表示是否只针对活跃用户进行新闻推荐,true为是,false为否。
* @param forActiveUsers
*/
public void executeInstantJobForCertainUsers(List<Long> goalUserList) {
executeInstantJob(goalUserList);
}
/**
* 为所用有用户执行一次新闻推荐
*/
public void executeInstantJobForAllUsers() {
executeInstantJob(RecommendKit.getAllUsers());
}
/**
* 为活跃用户进行一次推荐。
* @param goalUserList
*/
public void executeInstantJobForActiveUsers() {
executeInstantJob(RecommendKit.getActiveUsers());
}
}
| bluemapleman/NewsRecommendSystem | src/top/qianxinyao/Main/JobSetter.java | 1,234 | //让热点新闻推荐器预先生成今日的热点新闻 | line_comment | zh-cn | package top.qianxinyao.main;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.quartz.SchedulerException;
import top.qianxinyao.UserBasedCollaborativeRecommender.MahoutUserBasedCollaborativeRecommender;
import top.qianxinyao.UserBasedCollaborativeRecommender.quartz.CFCronTriggerRunner;
import top.qianxinyao.algorithms.PropGetKit;
import top.qianxinyao.algorithms.RecommendKit;
import top.qianxinyao.contentbasedrecommend.ContentBasedRecommender;
import top.qianxinyao.contentbasedrecommend.quartz.CBCronTriggerRunner;
import top.qianxinyao.dbconnection.DBKit;
import top.qianxinyao.hotrecommend.HotRecommender;
import top.qianxinyao.hotrecommend.quartz.HRCronTriggerRunner;
/**
* @author Tom Qian
* @email tomqianmaple@outlook.com
* @github https://github.com/bluemapleman
* @date 2017年12月11日
* 设定/启动推荐任务的类
*/
public class JobSetter
{
public static final Logger logger=Logger.getLogger(JobSetter.class);
boolean enableCF,enableCB,enableHR;
/**
*
* @param enableCF 是否启用协同过滤(Collaborative Filtering)
* @param enableCB 是否启用基于内容的推荐(Content-Based Recommendation)
* @param enableHR 是否启用热点新闻推荐(Hot News Recommendation)
*/
public JobSetter(boolean enableCF,boolean enableCB,boolean enableHR) {
//加载系统配置文件
PropGetKit.loadProperties("paraConfig");
//初始化操作:主要是数据库的连接
DBKit.initalize();
this.enableCF=enableCF;
this.enableCB=enableCB;
this.enableHR=enableHR;
}
/**
* 使用Quartz的表达式进行时间设定(默认为每天0点开始工作),详情请参照:http://www.quartz-scheduler.org/api/2.2.1/index.html(CronExpression)
* 当启用该方法时,推荐系统可以保持运行,直到被强制关闭。
* @param userList
*/
private void executeQuartzJob(List<Long> userList) {
//设定推荐任务每天的执行时间
String cronExpression=PropGetKit.getString("startAt");
try
{
if(enableCF)
new CFCronTriggerRunner().task(userList,cronExpression);
if(enableCB)
new CBCronTriggerRunner().task(userList,cronExpression);
if(enableHR)
new HRCronTriggerRunner().task(userList,cronExpression);
}
catch (SchedulerException e)
{
e.printStackTrace();
}
System.out.println("本次推荐结束于"+new Date());
}
/**
* 为指定用户执行定时新闻推荐
* @param goalUserList 目标用户的id列表
*/
public void executeQuartzJobForCertainUsers(List<Long> goalUserList) {
executeQuartzJob(goalUserList);
}
/**
* 为所有用户执行定时新闻推荐
*/
public void executeQuartzJobForAllUsers() {
executeQuartzJob(RecommendKit.getAllUsers());
}
/**
* 为活跃用户进行定时新闻推荐。
* @param goalUserList
*/
public void executeQuartzJobForActiveUsers() {
executeQuartzJob(RecommendKit.getActiveUsers());
}
/**
* 执行一次新闻推荐
* 参数forActiveUsers表示是否只针对活跃用户进行新闻推荐,true为是,false为否。
* @param forActiveUsers
*/
private void executeInstantJob(List<Long> userIDList) {
//让热 <SUF>
HotRecommender.formTodayTopHotNewsList();
if(enableCF)
new MahoutUserBasedCollaborativeRecommender().recommend(userIDList);
if(enableCB)
new ContentBasedRecommender().recommend(userIDList);
if(enableHR)
new HotRecommender().recommend(userIDList);
System.out.println("本次推荐结束于"+new Date());
}
/**
* 执行一次新闻推荐
* 参数forActiveUsers表示是否只针对活跃用户进行新闻推荐,true为是,false为否。
* @param forActiveUsers
*/
public void executeInstantJobForCertainUsers(List<Long> goalUserList) {
executeInstantJob(goalUserList);
}
/**
* 为所用有用户执行一次新闻推荐
*/
public void executeInstantJobForAllUsers() {
executeInstantJob(RecommendKit.getAllUsers());
}
/**
* 为活跃用户进行一次推荐。
* @param goalUserList
*/
public void executeInstantJobForActiveUsers() {
executeInstantJob(RecommendKit.getActiveUsers());
}
}
| false | 1,094 | 12 | 1,234 | 18 | 1,220 | 13 | 1,234 | 18 | 1,734 | 36 | false | false | false | false | false | true |
46091_7 | package com.benmu.widget.view.calendar;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.RectShape;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckedTextView;
import com.benmu.R;
import com.benmu.widget.utils.ColorUtils;
import com.benmu.widget.view.calendar.format.DayFormatter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static com.benmu.widget.view.calendar.MaterialCalendarView.showDecoratedDisabled;
import static com.benmu.widget.view.calendar.MaterialCalendarView.showOtherMonths;
import static com.benmu.widget.view.calendar.MaterialCalendarView.showOutOfRange;
/**
* Display one day of a {@linkplain MaterialCalendarView}
*/
@SuppressLint("ViewConstructor")
class DayView extends CheckedTextView {
private CalendarDay date;
private int selectionColor = Color.GRAY;
private final int fadeTime;
private Drawable customBackground = null;
private Drawable selectionDrawable;
private Drawable mCircleDrawable;
private DayFormatter formatter = DayFormatter.DEFAULT;
private boolean isInRange = true;
private boolean isInMonth = true;
private boolean isDecoratedDisabled = false;
@MaterialCalendarView.ShowOtherDates
private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS;
public DayView(Context context, CalendarDay day) {
super(context);
fadeTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
setSelectionColor(this.selectionColor);
setGravity(Gravity.CENTER);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
setTextAlignment(TEXT_ALIGNMENT_CENTER);
}
setDay(day);
}
public void setDay(CalendarDay date) {
this.date = date;
String s = getLabel();
setText(getLabel());
setTextSize(18);
}
/**
* Set the new label formatter and reformat the current label. This preserves current spans.
*
* @param formatter new label formatter
*/
public void setDayFormatter(DayFormatter formatter) {
this.formatter = formatter == null ? DayFormatter.DEFAULT : formatter;
CharSequence currentLabel = getText();
Object[] spans = null;
if (currentLabel instanceof Spanned) {
spans = ((Spanned) currentLabel).getSpans(0, currentLabel.length(), Object.class);
}
SpannableString newLabel = new SpannableString(getLabel());
if (spans != null) {
for (Object span : spans) {
newLabel.setSpan(span, 0, newLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
setText(newLabel);
setTextSize(20);
}
@NonNull
public String getLabel() {
if (!isEnabled()) {
setTextColor(Color.parseColor("#b2b2b2"));
} else {
setWeekend(getDate().toString());
}
if (CalendarDay.today().equals(getDate())) {
return "今";
}
return formatter.format(date);
}
public void setSelectionColor(int color) {
this.selectionColor = color;
regenerateBackground();
}
private void setWeekend(String dateString) {
DateFormat weekFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = weekFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
Calendar instance = Calendar.getInstance();
instance.setTime(date);
if (instance.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || instance.get(Calendar
.DAY_OF_WEEK) == Calendar.SUNDAY) {
//周末
if (!TextUtils.isEmpty(CustomerStyle.WEEKEND_COLOR)) {
setTextColor(Color.parseColor(CustomerStyle.WEEKEND_COLOR));
}
} else {
//非周末
if (!TextUtils.isEmpty(CustomerStyle.WEEKDAY_COLOR)) {
setTextColor(Color.parseColor(CustomerStyle.WEEKDAY_COLOR));
}
}
}
}
/**
* @param drawable custom selection drawable
*/
public void setSelectionDrawable(Drawable drawable) {
if (drawable == null) {
this.selectionDrawable = null;
} else {
this.selectionDrawable = drawable.getConstantState().newDrawable(getResources());
}
regenerateBackground();
}
/**
* @param drawable background to draw behind everything else
*/
public void setCustomBackground(Drawable drawable) {
if (drawable == null) {
this.customBackground = null;
} else {
this.customBackground = drawable.getConstantState().newDrawable(getResources());
}
invalidate();
}
public CalendarDay getDate() {
return date;
}
private void setEnabled() {
boolean enabled = isInMonth && isInRange && !isDecoratedDisabled;
super.setEnabled(isInRange && !isDecoratedDisabled);
boolean showOtherMonths = showOtherMonths(showOtherDates);
boolean showOutOfRange = showOutOfRange(showOtherDates) || showOtherMonths;
boolean showDecoratedDisabled = showDecoratedDisabled(showOtherDates);
boolean shouldBeVisible = enabled;
if (!isInMonth && showOtherMonths) {
shouldBeVisible = true;
}
if (!isInRange && showOutOfRange) {
shouldBeVisible |= isInMonth;
}
if (isDecoratedDisabled && showDecoratedDisabled) {
shouldBeVisible |= isInMonth && isInRange;
}
if (!isInMonth && shouldBeVisible) {
setTextColor(getTextColors().getColorForState(
new int[]{-android.R.attr.state_enabled}, Color.GRAY));
}
setVisibility(isInMonth ? View.VISIBLE : View.INVISIBLE);
// setVisibility(shouldBeVisible ? View.VISIBLE : View.INVISIBLE);
}
protected void setupSelection(@MaterialCalendarView.ShowOtherDates int showOtherDates,
boolean inRange, boolean
inMonth) {
this.showOtherDates = showOtherDates;
this.isInMonth = inMonth;
this.isInRange = inRange;
setEnabled();
}
private final Rect tempRect = new Rect();
private final Rect circleDrawableRect = new Rect();
@Override
protected void onDraw(@NonNull Canvas canvas) {
if (customBackground != null) {
customBackground.setBounds(tempRect);
customBackground.setState(getDrawableState());
customBackground.draw(canvas);
}
mCircleDrawable.setBounds(circleDrawableRect);
super.onDraw(canvas);
}
private void regenerateBackground() {
if (selectionDrawable != null) {
setBackgroundDrawable(selectionDrawable);
} else {
mCircleDrawable = generateBackground(selectionColor, fadeTime, circleDrawableRect);
setBackgroundDrawable(mCircleDrawable);
}
}
private int[] STATE_EXCALTY_CHECKED = {R.attr.exactly_checked};
private boolean mIsExcatlyChecked;
@Override
protected int[] onCreateDrawableState(int extraSpace) {
if (mIsExcatlyChecked) {
int[] ints = super.onCreateDrawableState(extraSpace + 1);
mergeDrawableStates(ints, STATE_EXCALTY_CHECKED);
return ints;
} else {
return super.onCreateDrawableState(extraSpace);
}
}
public void setExactlyDaySelected(boolean exactly) {
Log.e("exactly", getDate().getDay() + "ex" + exactly);
if (this.mIsExcatlyChecked != exactly) {
// this.date.setExacyltSameDay(exactly);
this.mIsExcatlyChecked = exactly;
refreshDrawableState();
}
}
private static Drawable generateBackground(int color, int fadeTime, Rect bounds) {
StateListDrawable drawable = new StateListDrawable();
drawable.setExitFadeDuration(fadeTime);
drawable.addState(new int[]{R.attr.exactly_checked}, generateRectDrawable(ColorUtils.getColor(CustomerStyle.CHECKED_COLOR)));
drawable.addState(new int[]{android.R.attr.state_checked}, generateRectDrawable(color));
//按压时的状态
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// drawable.addState(new int[]{android.R.attr.state_pressed}, generateRectDrawable
// (color));
// } else {
// drawable.addState(new int[]{android.R.attr.state_pressed}, generateRectDrawable
// (color));
// }
drawable.addState(new int[]{}, generateCircleDrawable(Color.TRANSPARENT));
return drawable;
}
private static Drawable generateRectDrawable(final int color) {
ShapeDrawable drawable = new ShapeDrawable(new RectShape());
drawable.getPaint().setColor(color);
return drawable;
}
private static Drawable generateCircleDrawable(final int color) {
ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
drawable.getPaint().setColor(color);
return drawable;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Drawable generateRippleDrawable(final int color, Rect bounds) {
ColorStateList list = ColorStateList.valueOf(color);
Drawable mask = generateCircleDrawable(Color.WHITE);
RippleDrawable rippleDrawable = new RippleDrawable(list, null, mask);
// API 21
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
rippleDrawable.setBounds(bounds);
}
// API 22. Technically harmless to leave on for API 21 and 23, but not worth risking for 23+
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
int center = (bounds.left + bounds.right) / 2;
rippleDrawable.setHotspotBounds(center, bounds.top, center, bounds.bottom);
}
return rippleDrawable;
}
/**
* @param facade apply the facade to us
*/
void applyFacade(DayViewFacade facade) {
this.isDecoratedDisabled = facade.areDaysDisabled();
setEnabled();
setCustomBackground(facade.getBackgroundDrawable());
setSelectionDrawable(facade.getSelectionDrawable());
// Facade has spans
List<DayViewFacade.Span> spans = facade.getSpans();
if (!spans.isEmpty()) {
String label = getLabel();
SpannableString formattedLabel = new SpannableString(getLabel());
for (DayViewFacade.Span span : spans) {
formattedLabel.setSpan(span.span, 0, label.length(), Spanned
.SPAN_EXCLUSIVE_EXCLUSIVE);
}
setText(formattedLabel);
}
// Reset in case it was customized previously
else {
setText(getLabel());
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
calculateBounds(right - left, bottom - top);
regenerateBackground();
}
private void calculateBounds(int width, int height) {
final int radius = Math.min(height, width);
final int offset = Math.abs(height - width) / 2;
// Lollipop platform bug. Circle drawable offset needs to be half of normal offset
final int circleOffset = Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP ? offset /
2 : offset;
if (width >= height) {
tempRect.set(offset, 0, radius + offset, height);
circleDrawableRect.set(circleOffset, 0, radius + circleOffset, height);
} else {
tempRect.set(0, offset, width, radius + offset);
circleDrawableRect.set(0, circleOffset, width, radius + circleOffset);
}
}
}
| bmfe/eros-nexus | src/main/java/com/benmu/widget/view/calendar/DayView.java | 2,967 | //按压时的状态 | line_comment | zh-cn | package com.benmu.widget.view.calendar;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.RippleDrawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.StateListDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.RectShape;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.CheckedTextView;
import com.benmu.R;
import com.benmu.widget.utils.ColorUtils;
import com.benmu.widget.view.calendar.format.DayFormatter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import static com.benmu.widget.view.calendar.MaterialCalendarView.showDecoratedDisabled;
import static com.benmu.widget.view.calendar.MaterialCalendarView.showOtherMonths;
import static com.benmu.widget.view.calendar.MaterialCalendarView.showOutOfRange;
/**
* Display one day of a {@linkplain MaterialCalendarView}
*/
@SuppressLint("ViewConstructor")
class DayView extends CheckedTextView {
private CalendarDay date;
private int selectionColor = Color.GRAY;
private final int fadeTime;
private Drawable customBackground = null;
private Drawable selectionDrawable;
private Drawable mCircleDrawable;
private DayFormatter formatter = DayFormatter.DEFAULT;
private boolean isInRange = true;
private boolean isInMonth = true;
private boolean isDecoratedDisabled = false;
@MaterialCalendarView.ShowOtherDates
private int showOtherDates = MaterialCalendarView.SHOW_DEFAULTS;
public DayView(Context context, CalendarDay day) {
super(context);
fadeTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
setSelectionColor(this.selectionColor);
setGravity(Gravity.CENTER);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
setTextAlignment(TEXT_ALIGNMENT_CENTER);
}
setDay(day);
}
public void setDay(CalendarDay date) {
this.date = date;
String s = getLabel();
setText(getLabel());
setTextSize(18);
}
/**
* Set the new label formatter and reformat the current label. This preserves current spans.
*
* @param formatter new label formatter
*/
public void setDayFormatter(DayFormatter formatter) {
this.formatter = formatter == null ? DayFormatter.DEFAULT : formatter;
CharSequence currentLabel = getText();
Object[] spans = null;
if (currentLabel instanceof Spanned) {
spans = ((Spanned) currentLabel).getSpans(0, currentLabel.length(), Object.class);
}
SpannableString newLabel = new SpannableString(getLabel());
if (spans != null) {
for (Object span : spans) {
newLabel.setSpan(span, 0, newLabel.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
setText(newLabel);
setTextSize(20);
}
@NonNull
public String getLabel() {
if (!isEnabled()) {
setTextColor(Color.parseColor("#b2b2b2"));
} else {
setWeekend(getDate().toString());
}
if (CalendarDay.today().equals(getDate())) {
return "今";
}
return formatter.format(date);
}
public void setSelectionColor(int color) {
this.selectionColor = color;
regenerateBackground();
}
private void setWeekend(String dateString) {
DateFormat weekFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = weekFormat.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (date != null) {
Calendar instance = Calendar.getInstance();
instance.setTime(date);
if (instance.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY || instance.get(Calendar
.DAY_OF_WEEK) == Calendar.SUNDAY) {
//周末
if (!TextUtils.isEmpty(CustomerStyle.WEEKEND_COLOR)) {
setTextColor(Color.parseColor(CustomerStyle.WEEKEND_COLOR));
}
} else {
//非周末
if (!TextUtils.isEmpty(CustomerStyle.WEEKDAY_COLOR)) {
setTextColor(Color.parseColor(CustomerStyle.WEEKDAY_COLOR));
}
}
}
}
/**
* @param drawable custom selection drawable
*/
public void setSelectionDrawable(Drawable drawable) {
if (drawable == null) {
this.selectionDrawable = null;
} else {
this.selectionDrawable = drawable.getConstantState().newDrawable(getResources());
}
regenerateBackground();
}
/**
* @param drawable background to draw behind everything else
*/
public void setCustomBackground(Drawable drawable) {
if (drawable == null) {
this.customBackground = null;
} else {
this.customBackground = drawable.getConstantState().newDrawable(getResources());
}
invalidate();
}
public CalendarDay getDate() {
return date;
}
private void setEnabled() {
boolean enabled = isInMonth && isInRange && !isDecoratedDisabled;
super.setEnabled(isInRange && !isDecoratedDisabled);
boolean showOtherMonths = showOtherMonths(showOtherDates);
boolean showOutOfRange = showOutOfRange(showOtherDates) || showOtherMonths;
boolean showDecoratedDisabled = showDecoratedDisabled(showOtherDates);
boolean shouldBeVisible = enabled;
if (!isInMonth && showOtherMonths) {
shouldBeVisible = true;
}
if (!isInRange && showOutOfRange) {
shouldBeVisible |= isInMonth;
}
if (isDecoratedDisabled && showDecoratedDisabled) {
shouldBeVisible |= isInMonth && isInRange;
}
if (!isInMonth && shouldBeVisible) {
setTextColor(getTextColors().getColorForState(
new int[]{-android.R.attr.state_enabled}, Color.GRAY));
}
setVisibility(isInMonth ? View.VISIBLE : View.INVISIBLE);
// setVisibility(shouldBeVisible ? View.VISIBLE : View.INVISIBLE);
}
protected void setupSelection(@MaterialCalendarView.ShowOtherDates int showOtherDates,
boolean inRange, boolean
inMonth) {
this.showOtherDates = showOtherDates;
this.isInMonth = inMonth;
this.isInRange = inRange;
setEnabled();
}
private final Rect tempRect = new Rect();
private final Rect circleDrawableRect = new Rect();
@Override
protected void onDraw(@NonNull Canvas canvas) {
if (customBackground != null) {
customBackground.setBounds(tempRect);
customBackground.setState(getDrawableState());
customBackground.draw(canvas);
}
mCircleDrawable.setBounds(circleDrawableRect);
super.onDraw(canvas);
}
private void regenerateBackground() {
if (selectionDrawable != null) {
setBackgroundDrawable(selectionDrawable);
} else {
mCircleDrawable = generateBackground(selectionColor, fadeTime, circleDrawableRect);
setBackgroundDrawable(mCircleDrawable);
}
}
private int[] STATE_EXCALTY_CHECKED = {R.attr.exactly_checked};
private boolean mIsExcatlyChecked;
@Override
protected int[] onCreateDrawableState(int extraSpace) {
if (mIsExcatlyChecked) {
int[] ints = super.onCreateDrawableState(extraSpace + 1);
mergeDrawableStates(ints, STATE_EXCALTY_CHECKED);
return ints;
} else {
return super.onCreateDrawableState(extraSpace);
}
}
public void setExactlyDaySelected(boolean exactly) {
Log.e("exactly", getDate().getDay() + "ex" + exactly);
if (this.mIsExcatlyChecked != exactly) {
// this.date.setExacyltSameDay(exactly);
this.mIsExcatlyChecked = exactly;
refreshDrawableState();
}
}
private static Drawable generateBackground(int color, int fadeTime, Rect bounds) {
StateListDrawable drawable = new StateListDrawable();
drawable.setExitFadeDuration(fadeTime);
drawable.addState(new int[]{R.attr.exactly_checked}, generateRectDrawable(ColorUtils.getColor(CustomerStyle.CHECKED_COLOR)));
drawable.addState(new int[]{android.R.attr.state_checked}, generateRectDrawable(color));
//按压 <SUF>
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// drawable.addState(new int[]{android.R.attr.state_pressed}, generateRectDrawable
// (color));
// } else {
// drawable.addState(new int[]{android.R.attr.state_pressed}, generateRectDrawable
// (color));
// }
drawable.addState(new int[]{}, generateCircleDrawable(Color.TRANSPARENT));
return drawable;
}
private static Drawable generateRectDrawable(final int color) {
ShapeDrawable drawable = new ShapeDrawable(new RectShape());
drawable.getPaint().setColor(color);
return drawable;
}
private static Drawable generateCircleDrawable(final int color) {
ShapeDrawable drawable = new ShapeDrawable(new OvalShape());
drawable.getPaint().setColor(color);
return drawable;
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static Drawable generateRippleDrawable(final int color, Rect bounds) {
ColorStateList list = ColorStateList.valueOf(color);
Drawable mask = generateCircleDrawable(Color.WHITE);
RippleDrawable rippleDrawable = new RippleDrawable(list, null, mask);
// API 21
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
rippleDrawable.setBounds(bounds);
}
// API 22. Technically harmless to leave on for API 21 and 23, but not worth risking for 23+
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP_MR1) {
int center = (bounds.left + bounds.right) / 2;
rippleDrawable.setHotspotBounds(center, bounds.top, center, bounds.bottom);
}
return rippleDrawable;
}
/**
* @param facade apply the facade to us
*/
void applyFacade(DayViewFacade facade) {
this.isDecoratedDisabled = facade.areDaysDisabled();
setEnabled();
setCustomBackground(facade.getBackgroundDrawable());
setSelectionDrawable(facade.getSelectionDrawable());
// Facade has spans
List<DayViewFacade.Span> spans = facade.getSpans();
if (!spans.isEmpty()) {
String label = getLabel();
SpannableString formattedLabel = new SpannableString(getLabel());
for (DayViewFacade.Span span : spans) {
formattedLabel.setSpan(span.span, 0, label.length(), Spanned
.SPAN_EXCLUSIVE_EXCLUSIVE);
}
setText(formattedLabel);
}
// Reset in case it was customized previously
else {
setText(getLabel());
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
calculateBounds(right - left, bottom - top);
regenerateBackground();
}
private void calculateBounds(int width, int height) {
final int radius = Math.min(height, width);
final int offset = Math.abs(height - width) / 2;
// Lollipop platform bug. Circle drawable offset needs to be half of normal offset
final int circleOffset = Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP ? offset /
2 : offset;
if (width >= height) {
tempRect.set(offset, 0, radius + offset, height);
circleDrawableRect.set(circleOffset, 0, radius + circleOffset, height);
} else {
tempRect.set(0, offset, width, radius + offset);
circleDrawableRect.set(0, circleOffset, width, radius + circleOffset);
}
}
}
| false | 2,561 | 5 | 2,967 | 5 | 3,137 | 5 | 2,967 | 5 | 3,583 | 9 | false | false | false | false | false | true |
36410_8 | package cn.bmob.zuqiu.ui;
import cn.bmob.zuqiu.R;
import cn.bmob.zuqiu.ui.base.BaseActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class InputActivity extends BaseActivity{
private int inputType = -1;
private EditText mInputEditText ;
private String inputContent;
private TextView mHintTextView;
private int MAX_COUNT = 80; // 球队简介80字、球队名8字
private TextWatcher mTextWatcher = new TextWatcher() {
private int editStart;
private int editEnd;
public void afterTextChanged(Editable s) {
editStart = mInputEditText.getSelectionStart();
editEnd = mInputEditText.getSelectionEnd();
// 先去掉监听器,否则会出现栈溢出
mInputEditText.removeTextChangedListener(mTextWatcher);
// 注意这里只能每次都对整个EditText的内容求长度,不能对删除的单个字符求长度
// 因为是中英文混合,单个字符而言,calculateLength函数都会返回1
while (calculateLength(s.toString()) > MAX_COUNT) { // 当输入字符个数超过限制的大小时,进行截断操作
s.delete(editStart - 1, editEnd);
editStart--;
editEnd--;
}
// mEditText.setText(s);将这行代码注释掉就不会出现后面所说的输入法在数字界面自动跳转回主界面的问题了,多谢@ainiyidiandian的提醒
mInputEditText.setSelection(editStart);
// 恢复监听器
mInputEditText.addTextChangedListener(mTextWatcher);
setLeftCount();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};
/**
* 刷新剩余输入字数,最大值新浪微博是140个字,人人网是200个字
*/
private void setLeftCount() {
mHintTextView.setText(String.valueOf((MAX_COUNT - getInputCount())));
}
/**
* 获取用户输入的分享内容字数
*
* @return
*/
private long getInputCount() {
return calculateLength(mInputEditText.getText().toString());
}
/**
* 计算分享内容的字数,一个汉字=两个英文字母,一个中文标点=两个英文标点 注意:该函数的不适用于对单个字符进行计算,因为单个字符四舍五入后都是1
*
* @param c
* @return
*/
private long calculateLength(CharSequence c) {
double len = 0;
for (int i = 0; i < c.length(); i++) {
int tmp = (int) c.charAt(i);
if (tmp > 0 && tmp < 127) {
len += 0.5;
} else {
len++;
}
}
return Math.round(len);
}
@Override
protected void onCreate(Bundle bundle) {
// TODO Auto-generated method stub
super.onCreate(bundle);
setViewContent(R.layout.activity_input);
setUpAction(mActionBarLeftMenu, "", R.drawable.back_actionbar, View.VISIBLE);
setUpAction(mActionBarRightMenu, "", R.drawable.commit_actionbar, View.VISIBLE);
inputType = getIntent().getIntExtra("input_type", -1);
switch (inputType) {
case 1://队名
setUpAction(mActionBarTitle, "队名", 0, View.VISIBLE);
mHintTextView.setText("8");
mHintTextView.setVisibility(View.VISIBLE);
mInputEditText.addTextChangedListener(mTextWatcher);
MAX_COUNT = 8;
break;
case 2://注册码
setUpAction(mActionBarTitle, "注册码", 0, View.VISIBLE);
mInputEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
break;
case 3://简介
setUpAction(mActionBarTitle, "球队简介", 0, View.VISIBLE);
mHintTextView.setText("80");
mHintTextView.setVisibility(View.VISIBLE);
mInputEditText.addTextChangedListener(mTextWatcher);
MAX_COUNT = 80;
break;
default:
finish();
break;
}
}
@Override
protected void findViews(View contentView) {
// TODO Auto-generated method stub
mInputEditText = (EditText)contentView.findViewById(R.id.input_content);
mHintTextView = (TextView) contentView.findViewById(R.id.tv_hint);
}
@Override
protected void onLeftMenuClick() {
// TODO Auto-generated method stub
super.onLeftMenuClick();
finish();
}
@Override
protected void onRightMenuClick() {
// TODO Auto-generated method stub
super.onRightMenuClick();
inputContent = mInputEditText.getText().toString().trim();
if(TextUtils.isEmpty(inputContent)){
showToast("输入内容不能为空");
return;
}
Bundle bundle = new Bundle();
bundle.putString("data", inputContent);
setResult(RESULT_OK, getIntent().putExtras(bundle));
finish();
}
}
| bmob/BmobTiQiuBa | Android/ZuQiuBa/app/src/main/java/cn/bmob/zuqiu/ui/InputActivity.java | 1,333 | /**
* 获取用户输入的分享内容字数
*
* @return
*/ | block_comment | zh-cn | package cn.bmob.zuqiu.ui;
import cn.bmob.zuqiu.R;
import cn.bmob.zuqiu.ui.base.BaseActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class InputActivity extends BaseActivity{
private int inputType = -1;
private EditText mInputEditText ;
private String inputContent;
private TextView mHintTextView;
private int MAX_COUNT = 80; // 球队简介80字、球队名8字
private TextWatcher mTextWatcher = new TextWatcher() {
private int editStart;
private int editEnd;
public void afterTextChanged(Editable s) {
editStart = mInputEditText.getSelectionStart();
editEnd = mInputEditText.getSelectionEnd();
// 先去掉监听器,否则会出现栈溢出
mInputEditText.removeTextChangedListener(mTextWatcher);
// 注意这里只能每次都对整个EditText的内容求长度,不能对删除的单个字符求长度
// 因为是中英文混合,单个字符而言,calculateLength函数都会返回1
while (calculateLength(s.toString()) > MAX_COUNT) { // 当输入字符个数超过限制的大小时,进行截断操作
s.delete(editStart - 1, editEnd);
editStart--;
editEnd--;
}
// mEditText.setText(s);将这行代码注释掉就不会出现后面所说的输入法在数字界面自动跳转回主界面的问题了,多谢@ainiyidiandian的提醒
mInputEditText.setSelection(editStart);
// 恢复监听器
mInputEditText.addTextChangedListener(mTextWatcher);
setLeftCount();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};
/**
* 刷新剩余输入字数,最大值新浪微博是140个字,人人网是200个字
*/
private void setLeftCount() {
mHintTextView.setText(String.valueOf((MAX_COUNT - getInputCount())));
}
/**
* 获取用 <SUF>*/
private long getInputCount() {
return calculateLength(mInputEditText.getText().toString());
}
/**
* 计算分享内容的字数,一个汉字=两个英文字母,一个中文标点=两个英文标点 注意:该函数的不适用于对单个字符进行计算,因为单个字符四舍五入后都是1
*
* @param c
* @return
*/
private long calculateLength(CharSequence c) {
double len = 0;
for (int i = 0; i < c.length(); i++) {
int tmp = (int) c.charAt(i);
if (tmp > 0 && tmp < 127) {
len += 0.5;
} else {
len++;
}
}
return Math.round(len);
}
@Override
protected void onCreate(Bundle bundle) {
// TODO Auto-generated method stub
super.onCreate(bundle);
setViewContent(R.layout.activity_input);
setUpAction(mActionBarLeftMenu, "", R.drawable.back_actionbar, View.VISIBLE);
setUpAction(mActionBarRightMenu, "", R.drawable.commit_actionbar, View.VISIBLE);
inputType = getIntent().getIntExtra("input_type", -1);
switch (inputType) {
case 1://队名
setUpAction(mActionBarTitle, "队名", 0, View.VISIBLE);
mHintTextView.setText("8");
mHintTextView.setVisibility(View.VISIBLE);
mInputEditText.addTextChangedListener(mTextWatcher);
MAX_COUNT = 8;
break;
case 2://注册码
setUpAction(mActionBarTitle, "注册码", 0, View.VISIBLE);
mInputEditText.setInputType(InputType.TYPE_CLASS_NUMBER);
break;
case 3://简介
setUpAction(mActionBarTitle, "球队简介", 0, View.VISIBLE);
mHintTextView.setText("80");
mHintTextView.setVisibility(View.VISIBLE);
mInputEditText.addTextChangedListener(mTextWatcher);
MAX_COUNT = 80;
break;
default:
finish();
break;
}
}
@Override
protected void findViews(View contentView) {
// TODO Auto-generated method stub
mInputEditText = (EditText)contentView.findViewById(R.id.input_content);
mHintTextView = (TextView) contentView.findViewById(R.id.tv_hint);
}
@Override
protected void onLeftMenuClick() {
// TODO Auto-generated method stub
super.onLeftMenuClick();
finish();
}
@Override
protected void onRightMenuClick() {
// TODO Auto-generated method stub
super.onRightMenuClick();
inputContent = mInputEditText.getText().toString().trim();
if(TextUtils.isEmpty(inputContent)){
showToast("输入内容不能为空");
return;
}
Bundle bundle = new Bundle();
bundle.putString("data", inputContent);
setResult(RESULT_OK, getIntent().putExtras(bundle));
finish();
}
}
| false | 1,156 | 21 | 1,333 | 19 | 1,366 | 24 | 1,333 | 19 | 1,709 | 32 | false | false | false | false | false | true |
32633_5 | public static void onRequest(final Request request, final Response response, final Modules modules) throws Throwable {
final int Version = 1; // vue项目版本号
// index.html文件需要包含 <!-- VERSION[Version] -->
// 如版本为1时,包含 <!-- VERSION[1] -->
boolean isGZiped = true; // 是否已将.css、.js、.html文件进行过gzip压缩
// 数据库中,项目对应的表名和下载地址、版本号的字段名
final String ProjectTable = "WebProject", DownloadAttrName = "project", VersionAttrName = "version";
String path = request.getPath(); // 获取请求地址
// 避免后面参数的影响
int index = path.indexOf("?");
if (index != -1)
path = path.substring(0, index);
if (path.length() == 17) {
response.send("Go homepage", 302, "Redirect",
JSON.toJson("Location", path + "/homepage"));
return;
}
if (path.length() > 16
&& path.substring(0, 17).matches("/[0-9a-f]{16}"))
path = path.substring(17);
// 判断是否为首页
final boolean isHomepage = path.equals("/homepage");
if (isHomepage) {
path = "index.html"; // vue首页html文件名
isGZiped = false;
}
// 获取持久化项
PersistenceItem perItem = modules.oPersistence == null ? null
: modules.oPersistence.get(path);
if (perItem == null) { // 本应用不支持持久化,或者无法读写
response.send("Cannot load project, sorry.", 404, "NOTFOUND");
return;
}
// 读取持久化内容
long size = perItem.size();
byte[] body = new byte[(int) size];
if (size != 0 && !perItem.read(body)) { // 读取失败
response.send("Cannot read project, sorry.", 404, "NOTFOUND");
return;
}
// 如果是首页,顺便看看云端保存的项目是否最新版
if (size == 0
|| isHomepage
&& !new String(body).contains("<!-- VERSION[" + Version
+ "] -->")) {
HttpResponse res = modules.oData.find(new Querier(ProjectTable)
.addWhereEqualTo(VersionAttrName, Version)
.order("-createdAt").limit(1));
if (res.queryResults == null) { // 查询失败,可能是没建表
response.send("Cannot find in bmob:" + res.stringData, 404,
"NOTFOUND");
return;
}
if (res.queryResults.size() == 0) { // 没有这个版本号的项目
response.send("No project match version:" + Version, 404,
"NOTFOUND");
return;
}
// 获取项目下载地址,必须以.zip为后缀
String url = null;
try {
url = res.queryResults.getJSONObject(0)
.getJSONObject(DownloadAttrName).getString("url");
if (url == null || !url.endsWith(".zip"))
throw new NullPointerException();
} catch (Throwable e) {
response.send("No project to download:" + Version, 404,
"NOTFOUND");
return;
}
res = modules.oHttp.get(url);
if (res.res.code != 200)
response.send("Failed to download:" + url, 404, "NOTFOUND");// 下载失败
else {
modules.oPersistence.clean();
if (modules.oPersistence.unzip(res.data))
response.send(
"<html><script type='text/javascript'>setTimeout(function(){window.location.reload();},1000);</script><body>正在升级中,请稍等...</body></html>",
200, "OK", JSON.toJson(ZConstant.Header_CType,
"text/html; charset=utf-8")); // 下载并解压成功,刷新网页
else
response.send("Failed to unzip:" + url, 404, "NOTFOUND"); // 解压失败
}
return;
}
// 根据文件类型,确定Content-Type
JSONObject responseHeaders = new JSONObject();
String cType = "text/html";
if (path.endsWith(".css"))
cType = "text/css";
else if (path.endsWith(".js"))
cType = "application/javascript";
else if (!path.endsWith(".html"))
isGZiped = false; // 其它类型,没有进行gzip压缩
responseHeaders.put(ZConstant.Header_CType, cType + "; charset=utf-8");
if (isGZiped)
responseHeaders.put("Content-Encoding", "gzip"); // 如果是已压缩的
response.send(body, 200, "OK", responseHeaders);
} | bmob/CloudFunction | vue/NotFound.java | 1,238 | // 获取请求地址 | line_comment | zh-cn | public static void onRequest(final Request request, final Response response, final Modules modules) throws Throwable {
final int Version = 1; // vue项目版本号
// index.html文件需要包含 <!-- VERSION[Version] -->
// 如版本为1时,包含 <!-- VERSION[1] -->
boolean isGZiped = true; // 是否已将.css、.js、.html文件进行过gzip压缩
// 数据库中,项目对应的表名和下载地址、版本号的字段名
final String ProjectTable = "WebProject", DownloadAttrName = "project", VersionAttrName = "version";
String path = request.getPath(); // 获取 <SUF>
// 避免后面参数的影响
int index = path.indexOf("?");
if (index != -1)
path = path.substring(0, index);
if (path.length() == 17) {
response.send("Go homepage", 302, "Redirect",
JSON.toJson("Location", path + "/homepage"));
return;
}
if (path.length() > 16
&& path.substring(0, 17).matches("/[0-9a-f]{16}"))
path = path.substring(17);
// 判断是否为首页
final boolean isHomepage = path.equals("/homepage");
if (isHomepage) {
path = "index.html"; // vue首页html文件名
isGZiped = false;
}
// 获取持久化项
PersistenceItem perItem = modules.oPersistence == null ? null
: modules.oPersistence.get(path);
if (perItem == null) { // 本应用不支持持久化,或者无法读写
response.send("Cannot load project, sorry.", 404, "NOTFOUND");
return;
}
// 读取持久化内容
long size = perItem.size();
byte[] body = new byte[(int) size];
if (size != 0 && !perItem.read(body)) { // 读取失败
response.send("Cannot read project, sorry.", 404, "NOTFOUND");
return;
}
// 如果是首页,顺便看看云端保存的项目是否最新版
if (size == 0
|| isHomepage
&& !new String(body).contains("<!-- VERSION[" + Version
+ "] -->")) {
HttpResponse res = modules.oData.find(new Querier(ProjectTable)
.addWhereEqualTo(VersionAttrName, Version)
.order("-createdAt").limit(1));
if (res.queryResults == null) { // 查询失败,可能是没建表
response.send("Cannot find in bmob:" + res.stringData, 404,
"NOTFOUND");
return;
}
if (res.queryResults.size() == 0) { // 没有这个版本号的项目
response.send("No project match version:" + Version, 404,
"NOTFOUND");
return;
}
// 获取项目下载地址,必须以.zip为后缀
String url = null;
try {
url = res.queryResults.getJSONObject(0)
.getJSONObject(DownloadAttrName).getString("url");
if (url == null || !url.endsWith(".zip"))
throw new NullPointerException();
} catch (Throwable e) {
response.send("No project to download:" + Version, 404,
"NOTFOUND");
return;
}
res = modules.oHttp.get(url);
if (res.res.code != 200)
response.send("Failed to download:" + url, 404, "NOTFOUND");// 下载失败
else {
modules.oPersistence.clean();
if (modules.oPersistence.unzip(res.data))
response.send(
"<html><script type='text/javascript'>setTimeout(function(){window.location.reload();},1000);</script><body>正在升级中,请稍等...</body></html>",
200, "OK", JSON.toJson(ZConstant.Header_CType,
"text/html; charset=utf-8")); // 下载并解压成功,刷新网页
else
response.send("Failed to unzip:" + url, 404, "NOTFOUND"); // 解压失败
}
return;
}
// 根据文件类型,确定Content-Type
JSONObject responseHeaders = new JSONObject();
String cType = "text/html";
if (path.endsWith(".css"))
cType = "text/css";
else if (path.endsWith(".js"))
cType = "application/javascript";
else if (!path.endsWith(".html"))
isGZiped = false; // 其它类型,没有进行gzip压缩
responseHeaders.put(ZConstant.Header_CType, cType + "; charset=utf-8");
if (isGZiped)
responseHeaders.put("Content-Encoding", "gzip"); // 如果是已压缩的
response.send(body, 200, "OK", responseHeaders);
} | false | 1,080 | 4 | 1,238 | 4 | 1,219 | 4 | 1,238 | 4 | 1,565 | 8 | false | false | false | false | false | true |
21024_14 | package com.xgr.wonderful.ui;
import net.youmi.android.offers.OffersManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnOpenListener;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.xgr.wonderful.MyApplication;
import com.xgr.wonderful.R;
import com.xgr.wonderful.utils.ActivityUtil;
import com.xgr.wonderful.utils.Constant;
import com.xgr.wonderful.utils.LogUtils;
public class MainActivity extends SlidingFragmentActivity implements OnClickListener{
public static final String TAG = "MainActivity";
private NaviFragment naviFragment;
private ImageView leftMenu;
private ImageView rightMenu;
private SlidingMenu mSlidingMenu;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.center_frame);
leftMenu = (ImageView)findViewById(R.id.topbar_menu_left);
rightMenu = (ImageView)findViewById(R.id.topbar_menu_right);
leftMenu.setOnClickListener(this);
rightMenu.setOnClickListener(this);
initFragment();
//显示提示对话框
// showDialog();
}
Dialog dialog ;
private void showDialog(){
dialog=new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage(R.string.dialog_tips)
.setPositiveButton("确实", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}).create();
dialog.show();
}
private void initFragment() {
mSlidingMenu = getSlidingMenu();
setBehindContentView(R.layout.frame_navi); // 给滑出的slidingmenu的fragment制定layout
naviFragment = new NaviFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_navi, naviFragment).commit();
// 设置slidingmenu的属性
mSlidingMenu.setMode(SlidingMenu.LEFT);// 设置slidingmeni从哪侧出现
mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);// 只有在边上才可以打开
mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);// 偏移量
mSlidingMenu.setFadeEnabled(true);
mSlidingMenu.setFadeDegree(0.5f);
mSlidingMenu.setMenu(R.layout.frame_navi);
Bundle mBundle = null;
// 导航打开监听事件
mSlidingMenu.setOnOpenListener(new OnOpenListener() {
@Override
public void onOpen() {
}
});
// 导航关闭监听事件
mSlidingMenu.setOnClosedListener(new OnClosedListener() {
@Override
public void onClosed() {
}
});
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.topbar_menu_left:
mSlidingMenu.toggle();
break;
case R.id.topbar_menu_right:
//当前用户登录
BmobUser currentUser = BmobUser.getCurrentUser(MainActivity.this);
if (currentUser != null) {
// 允许用户使用应用,即有了用户的唯一标识符,可以作为发布内容的字段
String name = currentUser.getUsername();
String email = currentUser.getEmail();
LogUtils.i(TAG,"username:"+name+",email:"+email);
Intent intent = new Intent();
intent.setClass(MainActivity.this, EditActivity.class);
startActivity(intent);
} else {
// 缓存用户对象为空时, 可打开用户注册界面…
Toast.makeText(MainActivity.this, "请先登录。",
Toast.LENGTH_SHORT).show();
// redictToActivity(mContext, RegisterAndLoginActivity.class, null);
Intent intent = new Intent();
intent.setClass(MainActivity.this, RegisterAndLoginActivity.class);
startActivity(intent);
}
break;
default:
break;
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
OffersManager.getInstance(MainActivity.this).onAppExit();
}
private static long firstTime;
/**
* 连续按两次返回键就退出
*/
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (firstTime + 2000 > System.currentTimeMillis()) {
MyApplication.getInstance().exit();
super.onBackPressed();
} else {
ActivityUtil.show(MainActivity.this, "再按一次退出程序");
}
firstTime = System.currentTimeMillis();
}
}
| bmob/Wonderful2 | src/com/xgr/wonderful/ui/MainActivity.java | 1,444 | // 允许用户使用应用,即有了用户的唯一标识符,可以作为发布内容的字段
| line_comment | zh-cn | package com.xgr.wonderful.ui;
import net.youmi.android.offers.OffersManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnClosedListener;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu.OnOpenListener;
import com.jeremyfeinstein.slidingmenu.lib.app.SlidingFragmentActivity;
import com.xgr.wonderful.MyApplication;
import com.xgr.wonderful.R;
import com.xgr.wonderful.utils.ActivityUtil;
import com.xgr.wonderful.utils.Constant;
import com.xgr.wonderful.utils.LogUtils;
public class MainActivity extends SlidingFragmentActivity implements OnClickListener{
public static final String TAG = "MainActivity";
private NaviFragment naviFragment;
private ImageView leftMenu;
private ImageView rightMenu;
private SlidingMenu mSlidingMenu;
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.center_frame);
leftMenu = (ImageView)findViewById(R.id.topbar_menu_left);
rightMenu = (ImageView)findViewById(R.id.topbar_menu_right);
leftMenu.setOnClickListener(this);
rightMenu.setOnClickListener(this);
initFragment();
//显示提示对话框
// showDialog();
}
Dialog dialog ;
private void showDialog(){
dialog=new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage(R.string.dialog_tips)
.setPositiveButton("确实", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}).setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
dialog.dismiss();
}
}).create();
dialog.show();
}
private void initFragment() {
mSlidingMenu = getSlidingMenu();
setBehindContentView(R.layout.frame_navi); // 给滑出的slidingmenu的fragment制定layout
naviFragment = new NaviFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.frame_navi, naviFragment).commit();
// 设置slidingmenu的属性
mSlidingMenu.setMode(SlidingMenu.LEFT);// 设置slidingmeni从哪侧出现
mSlidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);// 只有在边上才可以打开
mSlidingMenu.setBehindOffsetRes(R.dimen.slidingmenu_offset);// 偏移量
mSlidingMenu.setFadeEnabled(true);
mSlidingMenu.setFadeDegree(0.5f);
mSlidingMenu.setMenu(R.layout.frame_navi);
Bundle mBundle = null;
// 导航打开监听事件
mSlidingMenu.setOnOpenListener(new OnOpenListener() {
@Override
public void onOpen() {
}
});
// 导航关闭监听事件
mSlidingMenu.setOnClosedListener(new OnClosedListener() {
@Override
public void onClosed() {
}
});
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.topbar_menu_left:
mSlidingMenu.toggle();
break;
case R.id.topbar_menu_right:
//当前用户登录
BmobUser currentUser = BmobUser.getCurrentUser(MainActivity.this);
if (currentUser != null) {
// 允许 <SUF>
String name = currentUser.getUsername();
String email = currentUser.getEmail();
LogUtils.i(TAG,"username:"+name+",email:"+email);
Intent intent = new Intent();
intent.setClass(MainActivity.this, EditActivity.class);
startActivity(intent);
} else {
// 缓存用户对象为空时, 可打开用户注册界面…
Toast.makeText(MainActivity.this, "请先登录。",
Toast.LENGTH_SHORT).show();
// redictToActivity(mContext, RegisterAndLoginActivity.class, null);
Intent intent = new Intent();
intent.setClass(MainActivity.this, RegisterAndLoginActivity.class);
startActivity(intent);
}
break;
default:
break;
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
OffersManager.getInstance(MainActivity.this).onAppExit();
}
private static long firstTime;
/**
* 连续按两次返回键就退出
*/
@Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (firstTime + 2000 > System.currentTimeMillis()) {
MyApplication.getInstance().exit();
super.onBackPressed();
} else {
ActivityUtil.show(MainActivity.this, "再按一次退出程序");
}
firstTime = System.currentTimeMillis();
}
}
| false | 1,154 | 22 | 1,420 | 23 | 1,374 | 21 | 1,420 | 23 | 1,750 | 45 | false | false | false | false | false | true |
44410_2 | package com.bmob.demo.third;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.BmobUser.BmobThirdUserAuth;
import cn.bmob.v3.listener.UpdateListener;
import com.bmob.demo.third.net.NetUtils;
@SuppressLint("HandlerLeak")
public class MainActivity extends Activity implements OnClickListener {
String json = "";
String from = "";
TextView tv_info;
Button btn_relation_qq, btn_relation_weibo,btn_relation_weixin, btn_logout;
Button btn_remove_qq, btn_remove_weibo,btn_remove_weixin;
ImageView iv_back;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
json = getIntent().getStringExtra("json");
from = getIntent().getStringExtra("from");
iv_back = (ImageView) findViewById(R.id.iv_back);
tv_info = (TextView) findViewById(R.id.tv_info);
btn_relation_qq = (Button) findViewById(R.id.btn_relation_qq);
btn_relation_qq.setOnClickListener(this);
btn_relation_weibo = (Button) findViewById(R.id.btn_relation_weibo);
btn_relation_weibo.setOnClickListener(this);
btn_relation_weixin = (Button) findViewById(R.id.btn_relation_weixin);
btn_relation_weixin.setOnClickListener(this);
btn_logout = (Button) findViewById(R.id.btn_logout);
btn_logout.setOnClickListener(this);
// 取消关联
btn_remove_weibo = (Button) findViewById(R.id.btn_remove_weibo);
btn_remove_weibo.setOnClickListener(this);
btn_remove_qq = (Button) findViewById(R.id.btn_remove_qq);
btn_remove_qq.setOnClickListener(this);
btn_remove_weixin = (Button) findViewById(R.id.btn_remove_weixin);
btn_remove_weixin.setOnClickListener(this);
iv_back.setOnClickListener(this);
if (json != null && !json.equals("")) {
btn_relation_qq.setVisibility(View.GONE);
btn_relation_weibo.setVisibility(View.GONE);
btn_relation_weixin.setVisibility(View.GONE);
tv_info.setVisibility(View.VISIBLE);
} else {
btn_relation_qq.setVisibility(View.VISIBLE);
btn_relation_weibo.setVisibility(View.VISIBLE);
btn_relation_weixin.setVisibility(View.VISIBLE);
tv_info.setVisibility(View.GONE);
}
// 请求个人信息
if (from != null) {
if (from.equals("weibo")) {
btn_remove_qq.setVisibility(View.GONE);
btn_remove_weixin.setVisibility(View.GONE);
getWeiboInfo();
} else if (from.equals("qq")) {
btn_remove_weixin.setVisibility(View.GONE);
btn_remove_weibo.setVisibility(View.GONE);
getQQInfo();
}else if(from.equals("weixin")){
btn_remove_qq.setVisibility(View.GONE);
btn_remove_weibo.setVisibility(View.GONE);
}
}
BmobUser user = BmobUser.getCurrentUser(this);
Log.i("life", ""+user.getUsername()+","+user.getSessionToken());
}
// 依次类推,想要获取QQ或者新浪微博其他的信息,开发者可自行根据官方提供的API文档,传入对应的参数即可
// QQ的API文档地址:http://wiki.open.qq.com/wiki/website/API%E5%88%97%E8%A1%A8
// 微博的API文档地址:http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI
JSONObject obj;
/**
* 获取微博的资料
*
* @Title: getWeiboInfo
* @Description: TODO
* @param
* @return void
* @throws
*/
public void getWeiboInfo() {
// 根据http://open.weibo.com/wiki/2/users/show提供的API文档
new Thread() {
@Override
public void run() {
try {
obj = new JSONObject(json);
Map<String, String> params = new HashMap<String, String>();
if (obj != null) {
params.put("access_token", obj.getJSONObject("weibo").getString("access_token"));// 此为微博登陆成功之后返回的access_token
params.put("uid",obj.getJSONObject("weibo").getString("uid"));// 此为微博登陆成功之后返回的uid
}
String result = NetUtils.getRequest("https://api.weibo.com/2/users/show.json", params);
Log.d("login", "微博的个人信息:" + result);
Message msg = new Message();
msg.obj = result;
handler.sendMessage(msg);
} catch (Exception e) {
// TODO: handle exception
}
}
}.start();
}
/**
* 获取QQ的信息:具体可查看QQ的官方Demo,最新的QQ登录sdk已提供获取用户资料的接口并提供相应示例,可忽略此方式
* @Title: getQQInfo
* @Description: TODO
* @param
* @return void
* @throws
*/
public void getQQInfo() {
// 若更换为自己的APPID后,仍然获取不到自己的用户信息,则需要
// 根据(http://wiki.open.qq.com/wiki/website/get_user_info)提供的API文档,想要获取QQ用户的信息,则需要自己调用接口,传入对应的参数
new Thread() {
@Override
public void run() {
Map<String, String> params = new HashMap<String, String>();
params.put("access_token", "05636ED97BAB7F173CB237BA143AF7C9");// 此为QQ登陆成功之后返回access_token
params.put("openid", "B4F5ABAD717CCC93ABF3BF28D4BCB03A");
params.put("oauth_consumer_key", "222222");// oauth_consumer_key为申请QQ登录成功后,分配给应用的appid
params.put("format", "json");// 格式--非必填项
String result = NetUtils.getRequest("https://graph.qq.com/user/get_user_info", params);
Log.d("login", "QQ的个人信息:" + result);
Message msg = new Message();
msg.obj = result;
handler.sendMessage(msg);
}
}.start();
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
String result = (String) msg.obj;
if (result != null) {
tv_info.setText((String) msg.obj);
} else {
tv_info.setText("暂无个人信息");
}
};
};
/**和第三方账号进行关联
* @method associateThirdParty
* @param snsType
* @param accessToken
* @param expiresIn
* @param userId
* @return void
* @exception
*/
private void associateThirdParty(String snsType,String accessToken, String expiresIn,String userId){
BmobThirdUserAuth authInfo = new BmobThirdUserAuth(snsType,accessToken, expiresIn, userId);
BmobUser.associateWithAuthData(this, authInfo, new UpdateListener() {
@Override
public void onSuccess() {
// TODO Auto-generated method stub
toast("关联成功");
}
@Override
public void onFailure(int code, String msg) {
// TODO Auto-generated method stub
toast("关联失败:code =" + code + ",msg = " + msg);
}
});
}
/**取消关联
* @method dissociateAuth
* @param type:只能是三种值:qq、weibo、weixin
* @return void
* @exception
*/
public void dissociateAuth(final String type){
BmobUser.dissociateAuthData(this,type,new UpdateListener() {
@Override
public void onSuccess() {
// TODO Auto-generated method stub
toast("取消"+type+"关联成功");
}
@Override
public void onFailure(int code, String msg) {
// TODO Auto-generated method stub
if (code == 208) {// 208错误指的是没有绑定相应账户的授权信息
toast("你没有关联该账号");
} else {
toast("取消"+type+"关联失败:code =" + code + ",msg = " + msg);
}
}
});
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0 == btn_relation_weibo) {
associateThirdParty(BmobThirdUserAuth.SNS_TYPE_WEIBO, "2.00htoVwCV9DWcB02e14b7fa50vUwjg", "1410548398554", "2696876973");
} else if (arg0 == btn_relation_qq) {
associateThirdParty(BmobThirdUserAuth.SNS_TYPE_QQ, "A5DAEFCA1946AFE9FE35CD16B76F0FD1", "7776000", "2F848CC297DCD3C0494E99DC71CECB16");
} else if (arg0 == btn_relation_weixin) {
String accessToken = "OezXcEiiBSKSxW0eoylIePpsffIY64CyrRvrHWMWj_KdKD1OBKwfw-WsAlYVRjYCdhwIO8SfvzG24Id5owKp3LNJAzxgb_8vtZcQ4cVPJH_V9-W-j8bk5EcC93nIBMOJhqcOGYFlBfEUErQRGwvmKw";
String openId = "oyXO2uEQP44TM-P0mNwwnzV6atZo";
String expiresIn ="7200";
associateThirdParty(BmobThirdUserAuth.SNS_TYPE_WEIXIN, accessToken, expiresIn, openId);
} else if (arg0 == btn_remove_qq) {
dissociateAuth("qq");
} else if (arg0 == btn_remove_weibo) {
dissociateAuth("weibo");
} else if (arg0 == btn_remove_weixin) {
dissociateAuth("weixin");
}else if (arg0 == iv_back) {
finish();
} else if (arg0 == btn_logout) {//退出登陆,根据不同的第三方平台调用不同的退出API,此处省略
//...
BmobUser.logOut(this);
finish();
}
}
private void toast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
| bmob/bmob-android-demo-thirdpartylogin | src/com/bmob/demo/third/MainActivity.java | 2,903 | // 请求个人信息 | line_comment | zh-cn | package com.bmob.demo.third;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.BmobUser.BmobThirdUserAuth;
import cn.bmob.v3.listener.UpdateListener;
import com.bmob.demo.third.net.NetUtils;
@SuppressLint("HandlerLeak")
public class MainActivity extends Activity implements OnClickListener {
String json = "";
String from = "";
TextView tv_info;
Button btn_relation_qq, btn_relation_weibo,btn_relation_weixin, btn_logout;
Button btn_remove_qq, btn_remove_weibo,btn_remove_weixin;
ImageView iv_back;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
json = getIntent().getStringExtra("json");
from = getIntent().getStringExtra("from");
iv_back = (ImageView) findViewById(R.id.iv_back);
tv_info = (TextView) findViewById(R.id.tv_info);
btn_relation_qq = (Button) findViewById(R.id.btn_relation_qq);
btn_relation_qq.setOnClickListener(this);
btn_relation_weibo = (Button) findViewById(R.id.btn_relation_weibo);
btn_relation_weibo.setOnClickListener(this);
btn_relation_weixin = (Button) findViewById(R.id.btn_relation_weixin);
btn_relation_weixin.setOnClickListener(this);
btn_logout = (Button) findViewById(R.id.btn_logout);
btn_logout.setOnClickListener(this);
// 取消关联
btn_remove_weibo = (Button) findViewById(R.id.btn_remove_weibo);
btn_remove_weibo.setOnClickListener(this);
btn_remove_qq = (Button) findViewById(R.id.btn_remove_qq);
btn_remove_qq.setOnClickListener(this);
btn_remove_weixin = (Button) findViewById(R.id.btn_remove_weixin);
btn_remove_weixin.setOnClickListener(this);
iv_back.setOnClickListener(this);
if (json != null && !json.equals("")) {
btn_relation_qq.setVisibility(View.GONE);
btn_relation_weibo.setVisibility(View.GONE);
btn_relation_weixin.setVisibility(View.GONE);
tv_info.setVisibility(View.VISIBLE);
} else {
btn_relation_qq.setVisibility(View.VISIBLE);
btn_relation_weibo.setVisibility(View.VISIBLE);
btn_relation_weixin.setVisibility(View.VISIBLE);
tv_info.setVisibility(View.GONE);
}
// 请求 <SUF>
if (from != null) {
if (from.equals("weibo")) {
btn_remove_qq.setVisibility(View.GONE);
btn_remove_weixin.setVisibility(View.GONE);
getWeiboInfo();
} else if (from.equals("qq")) {
btn_remove_weixin.setVisibility(View.GONE);
btn_remove_weibo.setVisibility(View.GONE);
getQQInfo();
}else if(from.equals("weixin")){
btn_remove_qq.setVisibility(View.GONE);
btn_remove_weibo.setVisibility(View.GONE);
}
}
BmobUser user = BmobUser.getCurrentUser(this);
Log.i("life", ""+user.getUsername()+","+user.getSessionToken());
}
// 依次类推,想要获取QQ或者新浪微博其他的信息,开发者可自行根据官方提供的API文档,传入对应的参数即可
// QQ的API文档地址:http://wiki.open.qq.com/wiki/website/API%E5%88%97%E8%A1%A8
// 微博的API文档地址:http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI
JSONObject obj;
/**
* 获取微博的资料
*
* @Title: getWeiboInfo
* @Description: TODO
* @param
* @return void
* @throws
*/
public void getWeiboInfo() {
// 根据http://open.weibo.com/wiki/2/users/show提供的API文档
new Thread() {
@Override
public void run() {
try {
obj = new JSONObject(json);
Map<String, String> params = new HashMap<String, String>();
if (obj != null) {
params.put("access_token", obj.getJSONObject("weibo").getString("access_token"));// 此为微博登陆成功之后返回的access_token
params.put("uid",obj.getJSONObject("weibo").getString("uid"));// 此为微博登陆成功之后返回的uid
}
String result = NetUtils.getRequest("https://api.weibo.com/2/users/show.json", params);
Log.d("login", "微博的个人信息:" + result);
Message msg = new Message();
msg.obj = result;
handler.sendMessage(msg);
} catch (Exception e) {
// TODO: handle exception
}
}
}.start();
}
/**
* 获取QQ的信息:具体可查看QQ的官方Demo,最新的QQ登录sdk已提供获取用户资料的接口并提供相应示例,可忽略此方式
* @Title: getQQInfo
* @Description: TODO
* @param
* @return void
* @throws
*/
public void getQQInfo() {
// 若更换为自己的APPID后,仍然获取不到自己的用户信息,则需要
// 根据(http://wiki.open.qq.com/wiki/website/get_user_info)提供的API文档,想要获取QQ用户的信息,则需要自己调用接口,传入对应的参数
new Thread() {
@Override
public void run() {
Map<String, String> params = new HashMap<String, String>();
params.put("access_token", "05636ED97BAB7F173CB237BA143AF7C9");// 此为QQ登陆成功之后返回access_token
params.put("openid", "B4F5ABAD717CCC93ABF3BF28D4BCB03A");
params.put("oauth_consumer_key", "222222");// oauth_consumer_key为申请QQ登录成功后,分配给应用的appid
params.put("format", "json");// 格式--非必填项
String result = NetUtils.getRequest("https://graph.qq.com/user/get_user_info", params);
Log.d("login", "QQ的个人信息:" + result);
Message msg = new Message();
msg.obj = result;
handler.sendMessage(msg);
}
}.start();
}
Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
String result = (String) msg.obj;
if (result != null) {
tv_info.setText((String) msg.obj);
} else {
tv_info.setText("暂无个人信息");
}
};
};
/**和第三方账号进行关联
* @method associateThirdParty
* @param snsType
* @param accessToken
* @param expiresIn
* @param userId
* @return void
* @exception
*/
private void associateThirdParty(String snsType,String accessToken, String expiresIn,String userId){
BmobThirdUserAuth authInfo = new BmobThirdUserAuth(snsType,accessToken, expiresIn, userId);
BmobUser.associateWithAuthData(this, authInfo, new UpdateListener() {
@Override
public void onSuccess() {
// TODO Auto-generated method stub
toast("关联成功");
}
@Override
public void onFailure(int code, String msg) {
// TODO Auto-generated method stub
toast("关联失败:code =" + code + ",msg = " + msg);
}
});
}
/**取消关联
* @method dissociateAuth
* @param type:只能是三种值:qq、weibo、weixin
* @return void
* @exception
*/
public void dissociateAuth(final String type){
BmobUser.dissociateAuthData(this,type,new UpdateListener() {
@Override
public void onSuccess() {
// TODO Auto-generated method stub
toast("取消"+type+"关联成功");
}
@Override
public void onFailure(int code, String msg) {
// TODO Auto-generated method stub
if (code == 208) {// 208错误指的是没有绑定相应账户的授权信息
toast("你没有关联该账号");
} else {
toast("取消"+type+"关联失败:code =" + code + ",msg = " + msg);
}
}
});
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (arg0 == btn_relation_weibo) {
associateThirdParty(BmobThirdUserAuth.SNS_TYPE_WEIBO, "2.00htoVwCV9DWcB02e14b7fa50vUwjg", "1410548398554", "2696876973");
} else if (arg0 == btn_relation_qq) {
associateThirdParty(BmobThirdUserAuth.SNS_TYPE_QQ, "A5DAEFCA1946AFE9FE35CD16B76F0FD1", "7776000", "2F848CC297DCD3C0494E99DC71CECB16");
} else if (arg0 == btn_relation_weixin) {
String accessToken = "OezXcEiiBSKSxW0eoylIePpsffIY64CyrRvrHWMWj_KdKD1OBKwfw-WsAlYVRjYCdhwIO8SfvzG24Id5owKp3LNJAzxgb_8vtZcQ4cVPJH_V9-W-j8bk5EcC93nIBMOJhqcOGYFlBfEUErQRGwvmKw";
String openId = "oyXO2uEQP44TM-P0mNwwnzV6atZo";
String expiresIn ="7200";
associateThirdParty(BmobThirdUserAuth.SNS_TYPE_WEIXIN, accessToken, expiresIn, openId);
} else if (arg0 == btn_remove_qq) {
dissociateAuth("qq");
} else if (arg0 == btn_remove_weibo) {
dissociateAuth("weibo");
} else if (arg0 == btn_remove_weixin) {
dissociateAuth("weixin");
}else if (arg0 == iv_back) {
finish();
} else if (arg0 == btn_logout) {//退出登陆,根据不同的第三方平台调用不同的退出API,此处省略
//...
BmobUser.logOut(this);
finish();
}
}
private void toast(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
}
| false | 2,450 | 3 | 2,903 | 4 | 2,886 | 4 | 2,903 | 4 | 3,764 | 8 | false | false | false | false | false | true |
24952_9 | package cn.bmob.im.task;
import java.io.Serializable;
import java.util.List;
/**
* 查询对象
*
* @ClassName: BQuery
* @Description: TODO
* @author smile
* @date 2014-6-26 下午5:15:06
*/
public class BQuery implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 查询类型
*/
private int type;
/**
* 该类型下的查询条件集合:有可能这个查询类型下有多个查询条件:比如想查询username等于A和查询username等于B的
*/
private List<BTable> table;
public BQuery(int type,List<BTable> table){
this.type = type;
this.table = table;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<BTable> getTable() {
return table;
}
public void setTable(List<BTable> table) {
this.table = table;
}
/**
* Supported 查询类型:
*/
public interface QueryType {
int EQUALTO = 0;//相等
int NOTEQUALTO = 1;//不相等
int CONTAINS = 2;//不包含
int NOTCONTAINEDIN = 3;//不包含
int RELATEDTO = 4;//关联对象:查询某关联字段
int NEAR = 5;//附近的人
int WITHINKILOMETERS = 6;//指定范围内的人
}
}
| bmob/bmob-android-im-sdk | BmobIM_V1.1.9/src/cn/bmob/im/task/BQuery.java | 407 | //指定范围内的人 | line_comment | zh-cn | package cn.bmob.im.task;
import java.io.Serializable;
import java.util.List;
/**
* 查询对象
*
* @ClassName: BQuery
* @Description: TODO
* @author smile
* @date 2014-6-26 下午5:15:06
*/
public class BQuery implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* 查询类型
*/
private int type;
/**
* 该类型下的查询条件集合:有可能这个查询类型下有多个查询条件:比如想查询username等于A和查询username等于B的
*/
private List<BTable> table;
public BQuery(int type,List<BTable> table){
this.type = type;
this.table = table;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public List<BTable> getTable() {
return table;
}
public void setTable(List<BTable> table) {
this.table = table;
}
/**
* Supported 查询类型:
*/
public interface QueryType {
int EQUALTO = 0;//相等
int NOTEQUALTO = 1;//不相等
int CONTAINS = 2;//不包含
int NOTCONTAINEDIN = 3;//不包含
int RELATEDTO = 4;//关联对象:查询某关联字段
int NEAR = 5;//附近的人
int WITHINKILOMETERS = 6;//指定 <SUF>
}
}
| false | 341 | 4 | 407 | 5 | 407 | 4 | 407 | 5 | 535 | 12 | false | false | false | false | false | true |
42247_0 | package cn.edu.bnu.land.web;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import cn.edu.bnu.land.model.Noticement;
import cn.edu.bnu.land.model.Suggestion;
import cn.edu.bnu.land.service.NoticementService;
import cn.edu.bnu.land.service.SuggestionService;
@Controller
public class SuggestAction{
SuggestionService ss;
NoticementService ns;
int start;
int limit;
String id;
String content;
String publisher;
String category;
String date;
String grade;
String count;
String noticeID;
String projectID;
List<Suggestion> datas;
protected HttpServletRequest request;
protected HttpServletResponse response;
private String jsonString;//这个就是中转站了
private int totalCount;//这个是extjs用来分页
public String getProjectID() {
return projectID;
}
public void setProjectID(String projectID) {
this.projectID = projectID;
}
public NoticementService getNs() {
return ns;
}
@Autowired
public void setNs(NoticementService ns) {
this.ns = ns;
}
public String getNoticeID() {
return noticeID;
}
public void setNoticeID(String noticeID) {
this.noticeID = noticeID;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public SuggestionService getSs() {
return ss;
}
@Autowired
public void setSs(SuggestionService ss) {
this.ss = ss;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public List<Suggestion> getDatas() {
return datas;
}
public void setDatas(List<Suggestion> datas) {
this.datas = datas;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public String getJsonString() {
return jsonString;
}
public void setJsonString(String jsonString) {
this.jsonString = jsonString;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
//日期转换函数
public static JsonConfig configJson(){
JsonConfig jcf = new JsonConfig();
jcf.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
jcf.setExcludes(new String[]{"notice"});
return jcf;
}
@RequestMapping(value = "/deleteSuggest.action")
@ResponseBody
public Map<String, Object> deleteSuggestion(@RequestParam("id") String id)
throws IOException {
ss.deleteSuggestion(Integer.valueOf(id));
Map<String, Object> results = new HashMap<String, Object>();
results.put("success", true);
results.put("msg", "1"
+ ",successfully saved");
return (results);
}
public Date traslateDate(Date d)
{
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String tempDate = format.format(d);
Date newDate = null;
try {
newDate = format.parse(tempDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newDate;
}
@RequestMapping(value = "/showStatistic.action", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String showStatistic()
throws IOException {
String gh = "{\"category\":" + "\"规划意见\"" + "," + ss.Statistic("规划意见") + "}";
String az = "{\"category\":" + "\"安置意见\"" + "," + ss.Statistic("安置意见") + "}";
String bc = "{\"category\":" + "\"补偿意见\"" + "," + ss.Statistic("补偿意见") + "}";
String fk = "{\"category\":" + "\"拆迁意见\"" + "," + ss.Statistic("拆迁意见") + "}";
jsonString = "{\"totalCount\":" + "4" + ",\"results\":[" + gh + ","
+ az + "," + bc + "," + fk +"]}";
System.out.println(jsonString);
Map<String, Object> results = new HashMap<String, Object>();
results.put("success", true);
results.put("msg", "1"
+ ",successfully saved");
results.put("results", jsonString);
return (jsonString);
}
@RequestMapping(value = "/showSuggest.action", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String showSuggestion(
@RequestParam(value = "date", required = false) String date,
@RequestParam(value = "noticeID", required = false) String noticeID,
@RequestParam("limit") int limit,
@RequestParam("start") int start
)
throws IOException {
if (noticeID != null) {
this.noticeID = noticeID;
}else{
noticeID = this.noticeID;
}
if (date != null) {
this.date = date;
}else{
date = this.date;
}
// System.out.println("limit:" + limit);
if (date.isEmpty()) {
// System.out.println("进入if");
datas = ss.showSuggestion();
}else {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date newDate = null;
try {
newDate = format.parse(date);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
datas = ss.filterSuggestion(newDate);
}
List<Suggestion> finalData = new ArrayList<Suggestion>();
JSONArray array;
if (!noticeID.equals("1")) {
for (Suggestion sug : datas) {
if (noticeID.equals(
sug.getNotice().getId().toString().trim())) {
finalData.add(sug);
}
}
totalCount = finalData.size();
array = JSONArray.fromObject(finalData, configJson());
}else {
totalCount = datas.size();
array = JSONArray.fromObject(datas, configJson());
}
System.out.println(array);
System.out.println("意见日期是:" + date);
jsonString = "{\"totalCount\":" + this.getTotalCount() + ",\"success\":" + "true"+
",\"results\":[";
if (limit == -1) {
limit = totalCount;
}
for (int i = start; i < limit+start &&i <totalCount; i++)
{
JSONObject oj = array.getJSONObject(i);
jsonString += oj.toString() + ",";
}
jsonString += "]}";
jsonString = jsonString.replace(",]}", "]}");
System.out.println(jsonString);
// System.out.println("进入show");
// System.out.println(jsonString);
return jsonString;
}
@RequestMapping(value = "/addSuggest.action")
@ResponseBody
public Map<String, Object> addSuggestion(@RequestParam("count") String count,
@RequestParam("noticeID") String noticeID,
@RequestParam(value = "category", required = false) String category,
@RequestParam("content") String content,
@RequestParam("grade") String grade,
@RequestParam("publisher") String publisher
)
throws IOException {
if (ss.getNoticeByID(1) == null) {
Noticement notice = new Noticement();
notice.setCategory("");
notice.setDate(traslateDate(new Date()));
notice.setContent("");
notice.setPublisher("");
notice.setTitle("");
notice.setProjectID("");
notice.setEnclosureFlag("无附件");
notice.setEnclosurePath("");
ns.addNoticement(notice);
}
if (noticeID.equals("1")) {
String[] newCategory = category.split(",");
String[] newContent = content.split("#");
String[] newGrade = grade.split(",");
Noticement notice = ss.getNoticeByID(1);
for (int i = 0; i < Integer.valueOf(count); i++) {
Suggestion suggest = new Suggestion();
// System.out.println(newCategory[i]);
suggest.setCategory(newCategory[i]);
suggest.setDate(traslateDate(new Date()));
suggest.setContent(newContent[i]);
suggest.setPublisher(publisher);
suggest.setProjectID(projectID);
suggest.setGrade(Float.valueOf(newGrade[i]));
suggest.setNotice(notice);
ss.addSuggestion(suggest);
}
}else
{
String[] newContent = content.split("#");
String[] newGrade = grade.split(",");
Noticement notice = ss.getNoticeByID(Integer.valueOf(noticeID));
for (int i = 0; i < Integer.valueOf(count); i++) {
Suggestion suggest = new Suggestion();
suggest.setCategory(notice.getCategory().replaceAll("方案", "意见"));
suggest.setDate(traslateDate(new Date()));
suggest.setContent(newContent[i]);
suggest.setPublisher(publisher);
suggest.setProjectID(projectID);
suggest.setGrade(Float.valueOf(newGrade[i]));
suggest.setNotice(notice);
ss.addSuggestion(suggest);
}
}
Map<String, Object> results = new HashMap<String, Object>();
results.put("success", true);
results.put("msg", "1"
+ ",successfully saved");
return (results);
}
}
| bnu-land/tdlz | src/cn/edu/bnu/land/web/SuggestAction.java | 2,996 | //这个就是中转站了 | line_comment | zh-cn | package cn.edu.bnu.land.web;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import cn.edu.bnu.land.model.Noticement;
import cn.edu.bnu.land.model.Suggestion;
import cn.edu.bnu.land.service.NoticementService;
import cn.edu.bnu.land.service.SuggestionService;
@Controller
public class SuggestAction{
SuggestionService ss;
NoticementService ns;
int start;
int limit;
String id;
String content;
String publisher;
String category;
String date;
String grade;
String count;
String noticeID;
String projectID;
List<Suggestion> datas;
protected HttpServletRequest request;
protected HttpServletResponse response;
private String jsonString;//这个 <SUF>
private int totalCount;//这个是extjs用来分页
public String getProjectID() {
return projectID;
}
public void setProjectID(String projectID) {
this.projectID = projectID;
}
public NoticementService getNs() {
return ns;
}
@Autowired
public void setNs(NoticementService ns) {
this.ns = ns;
}
public String getNoticeID() {
return noticeID;
}
public void setNoticeID(String noticeID) {
this.noticeID = noticeID;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public SuggestionService getSs() {
return ss;
}
@Autowired
public void setSs(SuggestionService ss) {
this.ss = ss;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getLimit() {
return limit;
}
public void setLimit(int limit) {
this.limit = limit;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public List<Suggestion> getDatas() {
return datas;
}
public void setDatas(List<Suggestion> datas) {
this.datas = datas;
}
public HttpServletRequest getRequest() {
return request;
}
public void setRequest(HttpServletRequest request) {
this.request = request;
}
public HttpServletResponse getResponse() {
return response;
}
public void setResponse(HttpServletResponse response) {
this.response = response;
}
public String getJsonString() {
return jsonString;
}
public void setJsonString(String jsonString) {
this.jsonString = jsonString;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
//日期转换函数
public static JsonConfig configJson(){
JsonConfig jcf = new JsonConfig();
jcf.registerJsonValueProcessor(Date.class, new JsonDateValueProcessor());
jcf.setExcludes(new String[]{"notice"});
return jcf;
}
@RequestMapping(value = "/deleteSuggest.action")
@ResponseBody
public Map<String, Object> deleteSuggestion(@RequestParam("id") String id)
throws IOException {
ss.deleteSuggestion(Integer.valueOf(id));
Map<String, Object> results = new HashMap<String, Object>();
results.put("success", true);
results.put("msg", "1"
+ ",successfully saved");
return (results);
}
public Date traslateDate(Date d)
{
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String tempDate = format.format(d);
Date newDate = null;
try {
newDate = format.parse(tempDate);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newDate;
}
@RequestMapping(value = "/showStatistic.action", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String showStatistic()
throws IOException {
String gh = "{\"category\":" + "\"规划意见\"" + "," + ss.Statistic("规划意见") + "}";
String az = "{\"category\":" + "\"安置意见\"" + "," + ss.Statistic("安置意见") + "}";
String bc = "{\"category\":" + "\"补偿意见\"" + "," + ss.Statistic("补偿意见") + "}";
String fk = "{\"category\":" + "\"拆迁意见\"" + "," + ss.Statistic("拆迁意见") + "}";
jsonString = "{\"totalCount\":" + "4" + ",\"results\":[" + gh + ","
+ az + "," + bc + "," + fk +"]}";
System.out.println(jsonString);
Map<String, Object> results = new HashMap<String, Object>();
results.put("success", true);
results.put("msg", "1"
+ ",successfully saved");
results.put("results", jsonString);
return (jsonString);
}
@RequestMapping(value = "/showSuggest.action", produces = {"application/json;charset=UTF-8"})
@ResponseBody
public String showSuggestion(
@RequestParam(value = "date", required = false) String date,
@RequestParam(value = "noticeID", required = false) String noticeID,
@RequestParam("limit") int limit,
@RequestParam("start") int start
)
throws IOException {
if (noticeID != null) {
this.noticeID = noticeID;
}else{
noticeID = this.noticeID;
}
if (date != null) {
this.date = date;
}else{
date = this.date;
}
// System.out.println("limit:" + limit);
if (date.isEmpty()) {
// System.out.println("进入if");
datas = ss.showSuggestion();
}else {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date newDate = null;
try {
newDate = format.parse(date);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
datas = ss.filterSuggestion(newDate);
}
List<Suggestion> finalData = new ArrayList<Suggestion>();
JSONArray array;
if (!noticeID.equals("1")) {
for (Suggestion sug : datas) {
if (noticeID.equals(
sug.getNotice().getId().toString().trim())) {
finalData.add(sug);
}
}
totalCount = finalData.size();
array = JSONArray.fromObject(finalData, configJson());
}else {
totalCount = datas.size();
array = JSONArray.fromObject(datas, configJson());
}
System.out.println(array);
System.out.println("意见日期是:" + date);
jsonString = "{\"totalCount\":" + this.getTotalCount() + ",\"success\":" + "true"+
",\"results\":[";
if (limit == -1) {
limit = totalCount;
}
for (int i = start; i < limit+start &&i <totalCount; i++)
{
JSONObject oj = array.getJSONObject(i);
jsonString += oj.toString() + ",";
}
jsonString += "]}";
jsonString = jsonString.replace(",]}", "]}");
System.out.println(jsonString);
// System.out.println("进入show");
// System.out.println(jsonString);
return jsonString;
}
@RequestMapping(value = "/addSuggest.action")
@ResponseBody
public Map<String, Object> addSuggestion(@RequestParam("count") String count,
@RequestParam("noticeID") String noticeID,
@RequestParam(value = "category", required = false) String category,
@RequestParam("content") String content,
@RequestParam("grade") String grade,
@RequestParam("publisher") String publisher
)
throws IOException {
if (ss.getNoticeByID(1) == null) {
Noticement notice = new Noticement();
notice.setCategory("");
notice.setDate(traslateDate(new Date()));
notice.setContent("");
notice.setPublisher("");
notice.setTitle("");
notice.setProjectID("");
notice.setEnclosureFlag("无附件");
notice.setEnclosurePath("");
ns.addNoticement(notice);
}
if (noticeID.equals("1")) {
String[] newCategory = category.split(",");
String[] newContent = content.split("#");
String[] newGrade = grade.split(",");
Noticement notice = ss.getNoticeByID(1);
for (int i = 0; i < Integer.valueOf(count); i++) {
Suggestion suggest = new Suggestion();
// System.out.println(newCategory[i]);
suggest.setCategory(newCategory[i]);
suggest.setDate(traslateDate(new Date()));
suggest.setContent(newContent[i]);
suggest.setPublisher(publisher);
suggest.setProjectID(projectID);
suggest.setGrade(Float.valueOf(newGrade[i]));
suggest.setNotice(notice);
ss.addSuggestion(suggest);
}
}else
{
String[] newContent = content.split("#");
String[] newGrade = grade.split(",");
Noticement notice = ss.getNoticeByID(Integer.valueOf(noticeID));
for (int i = 0; i < Integer.valueOf(count); i++) {
Suggestion suggest = new Suggestion();
suggest.setCategory(notice.getCategory().replaceAll("方案", "意见"));
suggest.setDate(traslateDate(new Date()));
suggest.setContent(newContent[i]);
suggest.setPublisher(publisher);
suggest.setProjectID(projectID);
suggest.setGrade(Float.valueOf(newGrade[i]));
suggest.setNotice(notice);
ss.addSuggestion(suggest);
}
}
Map<String, Object> results = new HashMap<String, Object>();
results.put("success", true);
results.put("msg", "1"
+ ",successfully saved");
return (results);
}
}
| false | 2,388 | 7 | 2,996 | 7 | 3,013 | 7 | 2,996 | 7 | 3,891 | 9 | false | false | false | false | false | true |
57809_13 | package com.boatrain.tree;
import java.util.*;
/**
* https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
*/
public class ZigzagLevelOrderTree {
public static void main(String[] args) {
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null)
return res;
//创建队列,保存节点
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);//先把节点加入到队列中
boolean leftToRight = true;//第一步先从左边开始打印
while (!queue.isEmpty()) {
//双端队列
Deque<Integer> levelList = new LinkedList<>();
//统计这一层有多少个节点
int count = queue.size();
//遍历这一层的所有节点,把他们全部从队列中移出来,顺便
//把他们的值加入到集合level中,接着再把他们的子节点(如果有)
//加入到队列中
for (int i = 0; i < count; i++) {
//poll移除队列头部元素(队列在头部移除,尾部添加)
TreeNode node = queue.poll();
//判断是从左往右打印还是从右往左打印。
if (leftToRight) {
//如果从左边打印,直接把访问的节点值加入到列表level的末尾即可
levelList.addLast(node.val);
} else {
//如果是从右边开始打印,每次要把访问的节点值加入到列表的最前面
levelList.addFirst(node.val);
}
//左右子节点如果不为空会被加入到队列中
if (node.left != null)
queue.add(node.left);
if (node.right != null)
queue.add(node.right);
}
//把这一层的节点值加入到集合res中
res.add(new ArrayList<>(levelList));
//改变下次访问的方向
leftToRight = !leftToRight;
}
return res;
}
}
| boatrainlsz/leetcode | src/com/boatrain/tree/ZigzagLevelOrderTree.java | 496 | //左右子节点如果不为空会被加入到队列中 | line_comment | zh-cn | package com.boatrain.tree;
import java.util.*;
/**
* https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
*/
public class ZigzagLevelOrderTree {
public static void main(String[] args) {
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null)
return res;
//创建队列,保存节点
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);//先把节点加入到队列中
boolean leftToRight = true;//第一步先从左边开始打印
while (!queue.isEmpty()) {
//双端队列
Deque<Integer> levelList = new LinkedList<>();
//统计这一层有多少个节点
int count = queue.size();
//遍历这一层的所有节点,把他们全部从队列中移出来,顺便
//把他们的值加入到集合level中,接着再把他们的子节点(如果有)
//加入到队列中
for (int i = 0; i < count; i++) {
//poll移除队列头部元素(队列在头部移除,尾部添加)
TreeNode node = queue.poll();
//判断是从左往右打印还是从右往左打印。
if (leftToRight) {
//如果从左边打印,直接把访问的节点值加入到列表level的末尾即可
levelList.addLast(node.val);
} else {
//如果是从右边开始打印,每次要把访问的节点值加入到列表的最前面
levelList.addFirst(node.val);
}
//左右 <SUF>
if (node.left != null)
queue.add(node.left);
if (node.right != null)
queue.add(node.right);
}
//把这一层的节点值加入到集合res中
res.add(new ArrayList<>(levelList));
//改变下次访问的方向
leftToRight = !leftToRight;
}
return res;
}
}
| false | 447 | 12 | 496 | 14 | 506 | 11 | 496 | 14 | 709 | 21 | false | false | false | false | false | true |
59114_12 | package com.robotium.solo;
import java.lang.reflect.Field;
/**
* 反射操作工具类
* A reflection utility class.
*
* @author Per-Erik Bergman, bergman@uncle.se
*
*/
class Reflect {
private Object object;
/**
* 构造函数,禁止传入空值
* Constructs this object
*
* @param object the object to reflect on
*/
public Reflect(Object object) {
// 传入空值报异常
if (object == null)
throw new IllegalArgumentException("Object can not be null.");
this.object = object;
}
/**
* 获取对应属性字段
* Get a field from the object
*
* @param name the name of the field
*
* @return a field reference
*/
public FieldRf field(String name) {
return new FieldRf(object, name);
}
/**
* 定义一个字段属性类
* A field reference.
*/
public class FieldRf {
// 对应的 Class
private Class<?> clazz;
// 获取字段属性的对象
private Object object;
// 属性名
private String name;
/**构造函数
*
* Constructs this object
*
* @param object the object to reflect on
* @param name the name of the field
*/
public FieldRf(Object object, String name) {
this.object = object;
this.name = name;
}
/**
* 构造指定class类型的对象
* Constructs this object
*
* @param outclazz the output type
*
* @return <T> T
*/
public <T> T out(Class<T> outclazz) {
Field field = getField();
Object obj = getValue(field);
return outclazz.cast(obj);
}
/**
* 设置字段的值
* Set a value to a field
*
* @param value the value to set
*/
public void in(Object value) {
Field field = getField();
try {
// 设置属性为传入的值
field.set(object, value);
// 无效参数异常
} catch (IllegalArgumentException e) {
e.printStackTrace();
// 权限异常
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* 设置class类型,并返回对象本身
* Set the class type
*
* @param clazz the type
*
* @return a field reference
*/
public FieldRf type(Class<?> clazz) {
this.clazz = clazz;
return this;
}
// 获取字段
private Field getField() {
// 如未设置class类型,那么使用对象自身class作为class类型
if (clazz == null) {
clazz = object.getClass();
}
// 获取name执行的属性字段
Field field = null;
try {
field = clazz.getDeclaredField(name);
// 字段属性设置为运行赋值
field.setAccessible(true);
} catch (NoSuchFieldException ignored) {}
return field;
}
// 获取字段属性值
private Object getValue(Field field) {
// 如果字段为null那么返回null
if (field == null) {
return null;
}
// 获取字段对应的值,对象类型
Object obj = null;
try {
obj = field.get(object);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
}
}
| bobotiger2/robotium | com/robotium/solo/Reflect.java | 871 | // 无效参数异常 | line_comment | zh-cn | package com.robotium.solo;
import java.lang.reflect.Field;
/**
* 反射操作工具类
* A reflection utility class.
*
* @author Per-Erik Bergman, bergman@uncle.se
*
*/
class Reflect {
private Object object;
/**
* 构造函数,禁止传入空值
* Constructs this object
*
* @param object the object to reflect on
*/
public Reflect(Object object) {
// 传入空值报异常
if (object == null)
throw new IllegalArgumentException("Object can not be null.");
this.object = object;
}
/**
* 获取对应属性字段
* Get a field from the object
*
* @param name the name of the field
*
* @return a field reference
*/
public FieldRf field(String name) {
return new FieldRf(object, name);
}
/**
* 定义一个字段属性类
* A field reference.
*/
public class FieldRf {
// 对应的 Class
private Class<?> clazz;
// 获取字段属性的对象
private Object object;
// 属性名
private String name;
/**构造函数
*
* Constructs this object
*
* @param object the object to reflect on
* @param name the name of the field
*/
public FieldRf(Object object, String name) {
this.object = object;
this.name = name;
}
/**
* 构造指定class类型的对象
* Constructs this object
*
* @param outclazz the output type
*
* @return <T> T
*/
public <T> T out(Class<T> outclazz) {
Field field = getField();
Object obj = getValue(field);
return outclazz.cast(obj);
}
/**
* 设置字段的值
* Set a value to a field
*
* @param value the value to set
*/
public void in(Object value) {
Field field = getField();
try {
// 设置属性为传入的值
field.set(object, value);
// 无效 <SUF>
} catch (IllegalArgumentException e) {
e.printStackTrace();
// 权限异常
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* 设置class类型,并返回对象本身
* Set the class type
*
* @param clazz the type
*
* @return a field reference
*/
public FieldRf type(Class<?> clazz) {
this.clazz = clazz;
return this;
}
// 获取字段
private Field getField() {
// 如未设置class类型,那么使用对象自身class作为class类型
if (clazz == null) {
clazz = object.getClass();
}
// 获取name执行的属性字段
Field field = null;
try {
field = clazz.getDeclaredField(name);
// 字段属性设置为运行赋值
field.setAccessible(true);
} catch (NoSuchFieldException ignored) {}
return field;
}
// 获取字段属性值
private Object getValue(Field field) {
// 如果字段为null那么返回null
if (field == null) {
return null;
}
// 获取字段对应的值,对象类型
Object obj = null;
try {
obj = field.get(object);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
}
}
| false | 831 | 5 | 868 | 6 | 921 | 5 | 871 | 6 | 1,265 | 10 | false | false | false | false | false | true |
61197_0 | // 宠物类的使用示例(使用方法的参数来验证多态)
class PetTester02 {
// 让p引用的实例进行自我介绍
static void intro(Pet p) {
p.introduce();
}
public static void main(String[] args) {
Pet[] a = {
new Pet("Kurt", "艾一"),
new RobotPet("R2D2", "卢克"),
new Pet("迈克尔", "英男"),
};
for (Pet p : a) {
intro(p);
System.out.println();
}
/*
for (int i = 0; i < a.length; i++) {
intro(a[i]);
System.out.println();
}
*/
}
}
| bodii/test-code | java/explain_java/chapter12/PetTester02.java | 197 | // 宠物类的使用示例(使用方法的参数来验证多态) | line_comment | zh-cn | // 宠物 <SUF>
class PetTester02 {
// 让p引用的实例进行自我介绍
static void intro(Pet p) {
p.introduce();
}
public static void main(String[] args) {
Pet[] a = {
new Pet("Kurt", "艾一"),
new RobotPet("R2D2", "卢克"),
new Pet("迈克尔", "英男"),
};
for (Pet p : a) {
intro(p);
System.out.println();
}
/*
for (int i = 0; i < a.length; i++) {
intro(a[i]);
System.out.println();
}
*/
}
}
| false | 168 | 19 | 197 | 17 | 189 | 14 | 197 | 17 | 258 | 30 | false | false | false | false | false | true |
57640_7 | package com.lizhou.service;
import java.sql.Connection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.lizhou.bean.Page;
import com.lizhou.bean.Student;
import com.lizhou.bean.User;
import com.lizhou.dao.impl.StudentDaoImpl;
import com.lizhou.dao.inter.StudentDaoInter;
import com.lizhou.tools.MysqlTool;
import com.lizhou.tools.StringTool;
import net.sf.json.JSONObject;
/**
* 学生信息服务层
* @author bojiangzhou
*
*/
public class StudentService {
private StudentDaoInter dao;
public StudentService(){
dao = new StudentDaoImpl();
}
/**
* 修改学生信息
* @param student
*/
public void editStudent(Student student){
String sql = "";
List<Object> params = new LinkedList<>();
params.add(student.getName());
params.add(student.getSex());
params.add(student.getPhone());
params.add(student.getQq());
if(student.getGrade() == null || student.getClazz() == null){
sql = "UPDATE student SET name=?, sex=?, phone=?, qq=? WHERE number=?";
} else{
sql = "UPDATE student SET name=?, sex=?, phone=?, qq=?, clazzid=?, gradeid=? WHERE number=?";
params.add(student.getClazzid());
params.add(student.getGradeid());
}
params.add(student.getNumber());
//更新学生信息
dao.update(sql, params);
//修改系统用户名
dao.update("UPDATE user SET name=? WHERE account=?",
new Object[]{student.getName(), student.getNumber()});
}
/**
* 删除学生
* @param ids 学生id集合
* @param numbers 学生学号集合
* @throws Exception
*/
public void deleteStudent(String[] ids, String[] numbers) throws Exception{
//获取占位符
String mark = StringTool.getMark(numbers.length);
Integer sid[] = new Integer[ids.length];
for(int i =0 ;i < ids.length;i++){
sid[i] = Integer.parseInt(ids[i]);
}
//获取连接
Connection conn = MysqlTool.getConnection();
//开启事务
MysqlTool.startTransaction();
try {
//删除成绩表
dao.deleteTransaction(conn, "DELETE FROM escore WHERE studentid IN("+mark+")", sid);
//删除学生
dao.deleteTransaction(conn, "DELETE FROM student WHERE id IN("+mark+")", sid);
//删除系统用户
dao.deleteTransaction(conn, "DELETE FROM user WHERE account IN("+mark+")", numbers);
//提交事务
MysqlTool.commit();
} catch (Exception e) {
//回滚事务
MysqlTool.rollback();
e.printStackTrace();
throw e;
} finally {
MysqlTool.closeConnection();
}
}
/**
* 添加学生
* @param student
*/
public void addStudent(Student student){
//添加学生记录
dao.insert("INSERT INTO student(number, name, sex, phone, qq, clazzid, gradeid) value(?,?,?,?,?,?,?)",
new Object[]{
student.getNumber(),
student.getName(),
student.getSex(),
student.getPhone(),
student.getQq(),
student.getClazzid(),
student.getGradeid()
});
//添加用户记录
dao.insert("INSERT INTO user(account, name, type) value(?,?,?)", new Object[]{
student.getNumber(),
student.getName(),
User.USER_STUDENT
});
}
/**
* 分页获取学生
* @param student 学生信息
* @param page 分页
* @return
*/
public String getStudentList(Student student, Page page){
//sql语句
StringBuffer sb = new StringBuffer("SELECT * FROM student ");
//参数
List<Object> param = new LinkedList<>();
//判断条件
if(student != null){
if(student.getGrade() != null){//条件:年级
int gradeid = student.getGrade().getId();
param.add(gradeid);
sb.append("AND gradeid=? ");
}
if(student.getClazz() != null){
int clazzid = student.getClazz().getId();
param.add(clazzid);
sb.append("AND clazzid=? ");
}
}
//添加排序
sb.append("ORDER BY id DESC ");
//分页
if(page != null){
param.add(page.getStart());
param.add(page.getSize());
sb.append("limit ?,?");
}
String sql = sb.toString().replaceFirst("AND", "WHERE");
//获取数据
List<Student> list = dao.getStudentList(sql, param);
//获取总记录数
long total = getCount(student);
//定义Map
Map<String, Object> jsonMap = new HashMap<String, Object>();
//total键 存放总记录数,必须的
jsonMap.put("total", total);
//rows键 存放每页记录 list
jsonMap.put("rows", list);
//格式化Map,以json格式返回数据
String result = JSONObject.fromObject(jsonMap).toString();
//返回
return result;
}
/**
* 获取记录数
* @param student
* @param page
* @return
*/
private long getCount(Student student){
//sql语句
StringBuffer sb = new StringBuffer("SELECT COUNT(*) FROM student ");
//参数
List<Object> param = new LinkedList<>();
//判断条件
if(student != null){
if(student.getGrade() != null){//条件:年级
int gradeid = student.getGrade().getId();
param.add(gradeid);
sb.append("AND gradeid=? ");
}
if(student.getClazz() != null){
int clazzid = student.getClazz().getId();
param.add(clazzid);
sb.append("AND clazzid=? ");
}
}
String sql = sb.toString().replaceFirst("AND", "WHERE");
long count = dao.count(sql, param).intValue();
return count;
}
/**
* 获取跟学生一个班的班级同学
* @param account
* @param page
* @return
*/
public String getStudentList(String account, Page page) {
Student student = (Student) dao.getObject(Student.class, "SELECT * FROM student WHERE number=?", new Object[]{account});
return getStudentList(student, page);
}
/**
* 获取学生详细信息
* @param account
* @return
*/
public Student getStudent(String account) {
Student student = dao.getStudentList("SELECT * FROM student WHERE number="+account, null).get(0);
return student;
}
/**
* 设置照片
* @param number
* @param fileName
*/
public void setPhoto(String number, String fileName) {
String photo = "photo/"+fileName;
dao.update("UPDATE student SET photo=? WHERE number=?", new Object[]{photo, number});
}
}
| bojiangzhou/lyyzoo-ssms | src/com/lizhou/service/StudentService.java | 1,816 | //开启事务 | line_comment | zh-cn | package com.lizhou.service;
import java.sql.Connection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.lizhou.bean.Page;
import com.lizhou.bean.Student;
import com.lizhou.bean.User;
import com.lizhou.dao.impl.StudentDaoImpl;
import com.lizhou.dao.inter.StudentDaoInter;
import com.lizhou.tools.MysqlTool;
import com.lizhou.tools.StringTool;
import net.sf.json.JSONObject;
/**
* 学生信息服务层
* @author bojiangzhou
*
*/
public class StudentService {
private StudentDaoInter dao;
public StudentService(){
dao = new StudentDaoImpl();
}
/**
* 修改学生信息
* @param student
*/
public void editStudent(Student student){
String sql = "";
List<Object> params = new LinkedList<>();
params.add(student.getName());
params.add(student.getSex());
params.add(student.getPhone());
params.add(student.getQq());
if(student.getGrade() == null || student.getClazz() == null){
sql = "UPDATE student SET name=?, sex=?, phone=?, qq=? WHERE number=?";
} else{
sql = "UPDATE student SET name=?, sex=?, phone=?, qq=?, clazzid=?, gradeid=? WHERE number=?";
params.add(student.getClazzid());
params.add(student.getGradeid());
}
params.add(student.getNumber());
//更新学生信息
dao.update(sql, params);
//修改系统用户名
dao.update("UPDATE user SET name=? WHERE account=?",
new Object[]{student.getName(), student.getNumber()});
}
/**
* 删除学生
* @param ids 学生id集合
* @param numbers 学生学号集合
* @throws Exception
*/
public void deleteStudent(String[] ids, String[] numbers) throws Exception{
//获取占位符
String mark = StringTool.getMark(numbers.length);
Integer sid[] = new Integer[ids.length];
for(int i =0 ;i < ids.length;i++){
sid[i] = Integer.parseInt(ids[i]);
}
//获取连接
Connection conn = MysqlTool.getConnection();
//开启 <SUF>
MysqlTool.startTransaction();
try {
//删除成绩表
dao.deleteTransaction(conn, "DELETE FROM escore WHERE studentid IN("+mark+")", sid);
//删除学生
dao.deleteTransaction(conn, "DELETE FROM student WHERE id IN("+mark+")", sid);
//删除系统用户
dao.deleteTransaction(conn, "DELETE FROM user WHERE account IN("+mark+")", numbers);
//提交事务
MysqlTool.commit();
} catch (Exception e) {
//回滚事务
MysqlTool.rollback();
e.printStackTrace();
throw e;
} finally {
MysqlTool.closeConnection();
}
}
/**
* 添加学生
* @param student
*/
public void addStudent(Student student){
//添加学生记录
dao.insert("INSERT INTO student(number, name, sex, phone, qq, clazzid, gradeid) value(?,?,?,?,?,?,?)",
new Object[]{
student.getNumber(),
student.getName(),
student.getSex(),
student.getPhone(),
student.getQq(),
student.getClazzid(),
student.getGradeid()
});
//添加用户记录
dao.insert("INSERT INTO user(account, name, type) value(?,?,?)", new Object[]{
student.getNumber(),
student.getName(),
User.USER_STUDENT
});
}
/**
* 分页获取学生
* @param student 学生信息
* @param page 分页
* @return
*/
public String getStudentList(Student student, Page page){
//sql语句
StringBuffer sb = new StringBuffer("SELECT * FROM student ");
//参数
List<Object> param = new LinkedList<>();
//判断条件
if(student != null){
if(student.getGrade() != null){//条件:年级
int gradeid = student.getGrade().getId();
param.add(gradeid);
sb.append("AND gradeid=? ");
}
if(student.getClazz() != null){
int clazzid = student.getClazz().getId();
param.add(clazzid);
sb.append("AND clazzid=? ");
}
}
//添加排序
sb.append("ORDER BY id DESC ");
//分页
if(page != null){
param.add(page.getStart());
param.add(page.getSize());
sb.append("limit ?,?");
}
String sql = sb.toString().replaceFirst("AND", "WHERE");
//获取数据
List<Student> list = dao.getStudentList(sql, param);
//获取总记录数
long total = getCount(student);
//定义Map
Map<String, Object> jsonMap = new HashMap<String, Object>();
//total键 存放总记录数,必须的
jsonMap.put("total", total);
//rows键 存放每页记录 list
jsonMap.put("rows", list);
//格式化Map,以json格式返回数据
String result = JSONObject.fromObject(jsonMap).toString();
//返回
return result;
}
/**
* 获取记录数
* @param student
* @param page
* @return
*/
private long getCount(Student student){
//sql语句
StringBuffer sb = new StringBuffer("SELECT COUNT(*) FROM student ");
//参数
List<Object> param = new LinkedList<>();
//判断条件
if(student != null){
if(student.getGrade() != null){//条件:年级
int gradeid = student.getGrade().getId();
param.add(gradeid);
sb.append("AND gradeid=? ");
}
if(student.getClazz() != null){
int clazzid = student.getClazz().getId();
param.add(clazzid);
sb.append("AND clazzid=? ");
}
}
String sql = sb.toString().replaceFirst("AND", "WHERE");
long count = dao.count(sql, param).intValue();
return count;
}
/**
* 获取跟学生一个班的班级同学
* @param account
* @param page
* @return
*/
public String getStudentList(String account, Page page) {
Student student = (Student) dao.getObject(Student.class, "SELECT * FROM student WHERE number=?", new Object[]{account});
return getStudentList(student, page);
}
/**
* 获取学生详细信息
* @param account
* @return
*/
public Student getStudent(String account) {
Student student = dao.getStudentList("SELECT * FROM student WHERE number="+account, null).get(0);
return student;
}
/**
* 设置照片
* @param number
* @param fileName
*/
public void setPhoto(String number, String fileName) {
String photo = "photo/"+fileName;
dao.update("UPDATE student SET photo=? WHERE number=?", new Object[]{photo, number});
}
}
| false | 1,595 | 3 | 1,816 | 3 | 1,864 | 3 | 1,816 | 3 | 2,391 | 7 | false | false | false | false | false | true |
31765_0 | package com.ooooor.basic.safePoint;
/**
*
* JVM 中一条特殊线程 VM Threads, 执行特殊的 VM Operation (分派GC的STW, thread dump), 这些任务,都需要整个Heap,以及所有线程的状态是静止的,一致的才能进行.
* 所以JVM引入了安全点(Safe Point)的概念,想办法在需要进行VM Operation时,通知所有的线程进入一个静止的安全点。
*
* -XX:+PrintGCApplicationStoppedTime 很重要,一定要打开。全部的JVM停顿时间(不只是GC),打印在GC日志里
* 那些很多但又很短的安全点,全都是RevokeBias,"-XX:-UseBiasedLocking"取消掉它.
*
* 轻量级锁通过CAS避免开销大的互斥操作, 偏向锁无cas;
*偏向锁,顾名思义,它会偏向于第一个访问锁的线程,如果在接下来的运行过程中,该锁没有被其他的线程访问,则持有偏向锁的线程将永远不需要触发同步。
如果在运行过程中,遇到了其他线程抢占锁,则持有偏向锁的线程会被挂起,JVM会尝试消除它身上的偏向锁,将锁恢复到标准的轻量级锁。(偏向锁只能在单线程下起作用);
在JDK6中,偏向锁是默认启用的。它提高了单线程访问同步资源的性能。
但试想一下,如果你的同步资源或代码一直都是多线程访问的,那么消除偏向锁这一步骤对你来说就是多余的。事实上,消除偏向锁的开销还是蛮大的。
所以在你非常熟悉自己的代码前提下,大可禁用偏向锁 -XX:-UseBiasedLocking 。
偏向锁替换mark word中threadID为当前线程(偏向);
偏向模式和非偏向模式,在下面的mark word表中,主要体现在thread ID字段是否为空。
???轻量级锁lock record;
*
*
*
*/
public class SafePoint {
}
| boostarea/hyperion | src/main/java/com/ooooor/basic/safePoint/SafePoint.java | 509 | /**
*
* JVM 中一条特殊线程 VM Threads, 执行特殊的 VM Operation (分派GC的STW, thread dump), 这些任务,都需要整个Heap,以及所有线程的状态是静止的,一致的才能进行.
* 所以JVM引入了安全点(Safe Point)的概念,想办法在需要进行VM Operation时,通知所有的线程进入一个静止的安全点。
*
* -XX:+PrintGCApplicationStoppedTime 很重要,一定要打开。全部的JVM停顿时间(不只是GC),打印在GC日志里
* 那些很多但又很短的安全点,全都是RevokeBias,"-XX:-UseBiasedLocking"取消掉它.
*
* 轻量级锁通过CAS避免开销大的互斥操作, 偏向锁无cas;
*偏向锁,顾名思义,它会偏向于第一个访问锁的线程,如果在接下来的运行过程中,该锁没有被其他的线程访问,则持有偏向锁的线程将永远不需要触发同步。
如果在运行过程中,遇到了其他线程抢占锁,则持有偏向锁的线程会被挂起,JVM会尝试消除它身上的偏向锁,将锁恢复到标准的轻量级锁。(偏向锁只能在单线程下起作用);
在JDK6中,偏向锁是默认启用的。它提高了单线程访问同步资源的性能。
但试想一下,如果你的同步资源或代码一直都是多线程访问的,那么消除偏向锁这一步骤对你来说就是多余的。事实上,消除偏向锁的开销还是蛮大的。
所以在你非常熟悉自己的代码前提下,大可禁用偏向锁 -XX:-UseBiasedLocking 。
偏向锁替换mark word中threadID为当前线程(偏向);
偏向模式和非偏向模式,在下面的mark word表中,主要体现在thread ID字段是否为空。
???轻量级锁lock record;
*
*
*
*/ | block_comment | zh-cn | package com.ooooor.basic.safePoint;
/**
*
* JVM <SUF>*/
public class SafePoint {
}
| false | 454 | 439 | 509 | 487 | 459 | 438 | 509 | 487 | 841 | 817 | true | true | true | true | true | false |
55328_13 | import java.util.HashMap;
import java.util.Map;
/**
* 演示HashMap的内存泄漏产生过程, 参考test()方法
*/
public class HashMapMemoryLeak {
public static void main(String[] args) {
// test1();
test2();
}
private static void test1() {
Map<Person, Integer> map = new HashMap<Person, Integer>();
Person p = new Person("zhangsan", 12);
System.out.println("step1 p=" + p);
System.out.println("System.identityHashCode(p)=" + System.identityHashCode(p));
map.put(p, 1);
p.setName("lisi"); // 因为p.name参与了hash值的计算,修改了之后hash值发生了变化,所以下面删除不掉
System.out.println("System.identityHashCode(p)=" + System.identityHashCode(p));
map.remove(p);
System.out.println("step2 p=" + p);
System.out.println("hashCOde" + p.hashCode());
System.out.println("---------After remove()-------");
System.out.println("map.size() " + map.size());
System.out.println("map.containsKey(p) " + map.containsKey(p));
System.out.println("map.get(p) " + map.get(p));
}
private static void test2() {
Map<Person, Integer> map = new HashMap<Person, Integer>();
Person p = new Person("zhangsan", 12);
map.put(p, 1);
System.out.println("map.get(p)="+ map.get(p));
Person p2 = new Person("zhangsan", 13);
System.out.println("p.hashCode() == p2.hashCode() ? " + (p.hashCode() == p2.hashCode()));
System.out.println("p.equals(p2) " + p.equals(p2));
System.out.println("map.size() " + map.size());
System.out.println("map.get(p)="+ map.get(p));
System.out.println("map.get(p2)="+ map.get(p2));
// 在setName之前,假设p对应的KV对存放的位置是X
p.setName("lisi"); // 这里造成p2这个key的数据内存泄漏。导致后面无法被删除掉
// p.setName("lisi")后, 这个Node存放的Entry的未知不变,但是,里面Node里面的Key的name变里,导致key的hashCode()变了。
// 后面通过map.get(p)去检索数据的时候,p.hashCode()变了,经过hash计算后得到位置是Y(Y此时为空)
// 所以这时候map.get(p)返回null, map.containsKey(p)返回false
// 所以位置X处的Node数据已经无法进行get() ,put(),containsKey(), remove()的操作了
// 这个内存因为被HashMap引用,也无法GC,
// 这快内存不能被删也不能鄂博查询,也不能被GC回收,称之为内存泄漏(memory leak)
// 这才几个字节的内存泄漏,还不会出事故, 大量的内存泄漏,会浪费很多内存,降低系统性能。最终浪费大量的堆内存,
// 最终导致内存溢出(Out of memory, OutOfMemoryException, 或者报错Heap Space...)
// 结论: 大量的内存泄漏会最终导致内存溢出。 如果出现了内存溢出的报错,我们可以去查看代码,是否有内存泄漏,
// 或者到map里查看是否有一些无意义的垃圾数据(极有可能是内存溢出的数据)
map.remove(p);
// map.remove(p2);
System.out.println("---------After map.remove(p)-------------");
System.out.println("map.size() " + map.size());
System.out.println("map.get(p)="+ map.get(p));
System.out.println("map.get(p2)="+ map.get(p2));
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// @Override
// public boolean equals(Object obj) {
// return super.equals(obj);
// }
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof Person) {
Person personValue = (Person)obj;
if (personValue.getName() == null && name ==null) {
return true;
}
if (personValue.getName() != null && personValue.getName().equals(name)){
return true;
}
}
return false;
}
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
//
// if (obj instanceof Person) {
// Person personValue = (Person)obj;
//
// if (personValue.getName() == null && name ==null && personValue.getAge() ==age) {
// return true;
// }
//
// if (personValue.getName() != null && personValue.getName().equals(name) && personValue.getAge() ==age){
// return true;
// }
// }
//
// return false;
// }
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
//
// return hashCode() == obj.hashCode();
// }
@Override
public int hashCode() {
return name.hashCode() * 123;
}
}
| bootsrc/java-interview | code/HashMapMemoryLeak.java | 1,486 | // 结论: 大量的内存泄漏会最终导致内存溢出。 如果出现了内存溢出的报错,我们可以去查看代码,是否有内存泄漏, | line_comment | zh-cn | import java.util.HashMap;
import java.util.Map;
/**
* 演示HashMap的内存泄漏产生过程, 参考test()方法
*/
public class HashMapMemoryLeak {
public static void main(String[] args) {
// test1();
test2();
}
private static void test1() {
Map<Person, Integer> map = new HashMap<Person, Integer>();
Person p = new Person("zhangsan", 12);
System.out.println("step1 p=" + p);
System.out.println("System.identityHashCode(p)=" + System.identityHashCode(p));
map.put(p, 1);
p.setName("lisi"); // 因为p.name参与了hash值的计算,修改了之后hash值发生了变化,所以下面删除不掉
System.out.println("System.identityHashCode(p)=" + System.identityHashCode(p));
map.remove(p);
System.out.println("step2 p=" + p);
System.out.println("hashCOde" + p.hashCode());
System.out.println("---------After remove()-------");
System.out.println("map.size() " + map.size());
System.out.println("map.containsKey(p) " + map.containsKey(p));
System.out.println("map.get(p) " + map.get(p));
}
private static void test2() {
Map<Person, Integer> map = new HashMap<Person, Integer>();
Person p = new Person("zhangsan", 12);
map.put(p, 1);
System.out.println("map.get(p)="+ map.get(p));
Person p2 = new Person("zhangsan", 13);
System.out.println("p.hashCode() == p2.hashCode() ? " + (p.hashCode() == p2.hashCode()));
System.out.println("p.equals(p2) " + p.equals(p2));
System.out.println("map.size() " + map.size());
System.out.println("map.get(p)="+ map.get(p));
System.out.println("map.get(p2)="+ map.get(p2));
// 在setName之前,假设p对应的KV对存放的位置是X
p.setName("lisi"); // 这里造成p2这个key的数据内存泄漏。导致后面无法被删除掉
// p.setName("lisi")后, 这个Node存放的Entry的未知不变,但是,里面Node里面的Key的name变里,导致key的hashCode()变了。
// 后面通过map.get(p)去检索数据的时候,p.hashCode()变了,经过hash计算后得到位置是Y(Y此时为空)
// 所以这时候map.get(p)返回null, map.containsKey(p)返回false
// 所以位置X处的Node数据已经无法进行get() ,put(),containsKey(), remove()的操作了
// 这个内存因为被HashMap引用,也无法GC,
// 这快内存不能被删也不能鄂博查询,也不能被GC回收,称之为内存泄漏(memory leak)
// 这才几个字节的内存泄漏,还不会出事故, 大量的内存泄漏,会浪费很多内存,降低系统性能。最终浪费大量的堆内存,
// 最终导致内存溢出(Out of memory, OutOfMemoryException, 或者报错Heap Space...)
// 结论 <SUF>
// 或者到map里查看是否有一些无意义的垃圾数据(极有可能是内存溢出的数据)
map.remove(p);
// map.remove(p2);
System.out.println("---------After map.remove(p)-------------");
System.out.println("map.size() " + map.size());
System.out.println("map.get(p)="+ map.get(p));
System.out.println("map.get(p2)="+ map.get(p2));
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
// @Override
// public boolean equals(Object obj) {
// return super.equals(obj);
// }
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof Person) {
Person personValue = (Person)obj;
if (personValue.getName() == null && name ==null) {
return true;
}
if (personValue.getName() != null && personValue.getName().equals(name)){
return true;
}
}
return false;
}
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
//
// if (obj instanceof Person) {
// Person personValue = (Person)obj;
//
// if (personValue.getName() == null && name ==null && personValue.getAge() ==age) {
// return true;
// }
//
// if (personValue.getName() != null && personValue.getName().equals(name) && personValue.getAge() ==age){
// return true;
// }
// }
//
// return false;
// }
// @Override
// public boolean equals(Object obj) {
// if (obj == null) {
// return false;
// }
//
// return hashCode() == obj.hashCode();
// }
@Override
public int hashCode() {
return name.hashCode() * 123;
}
}
| false | 1,257 | 36 | 1,486 | 43 | 1,495 | 34 | 1,486 | 43 | 1,830 | 75 | false | false | false | false | false | true |
49677_16 | package com.liushaoming.jseckill.backend.service.impl;
import com.alibaba.fastjson.JSON;
import com.liushaoming.jseckill.backend.constant.RedisKey;
import com.liushaoming.jseckill.backend.constant.RedisKeyPrefix;
import com.liushaoming.jseckill.backend.dao.SeckillDAO;
import com.liushaoming.jseckill.backend.dao.SuccessKilledDAO;
import com.liushaoming.jseckill.backend.dao.cache.RedisDAO;
import com.liushaoming.jseckill.backend.dto.Exposer;
import com.liushaoming.jseckill.backend.dto.SeckillExecution;
import com.liushaoming.jseckill.backend.dto.SeckillMsgBody;
import com.liushaoming.jseckill.backend.entity.Seckill;
import com.liushaoming.jseckill.backend.entity.SuccessKilled;
import com.liushaoming.jseckill.backend.enums.SeckillStateEnum;
import com.liushaoming.jseckill.backend.exception.SeckillException;
import com.liushaoming.jseckill.backend.mq.MQProducer;
import com.liushaoming.jseckill.backend.service.AccessLimitService;
import com.liushaoming.jseckill.backend.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/**
* @author liushaoming
*/
@Service
public class SeckillServiceImpl implements SeckillService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
//md5盐值字符串,用于混淆MD5
private final String salt = "aksksks*&&^%%aaaa&^^%%*";
//注入Service依赖
@Autowired
private SeckillDAO seckillDAO;
@Autowired
private SuccessKilledDAO successKilledDAO;
@Autowired
private RedisDAO redisDAO;
@Autowired
private AccessLimitService accessLimitService;
@Autowired
private MQProducer mqProducer;
@Resource(name = "initJedisPool")
private JedisPool jedisPool;
@Override
public List<Seckill> getSeckillList() {
return seckillDAO.queryAll(0, 10);
}
@Override
public Seckill getById(long seckillId) {
return seckillDAO.queryById(seckillId);
}
@Override
public Exposer exportSeckillUrl(long seckillId) {
// 优化点:缓存优化:超时的基础上维护一致性
//1.访问Redis
Seckill seckill = redisDAO.getSeckill(seckillId);
if (seckill == null) {
//2.访问数据库
seckill = seckillDAO.queryById(seckillId);
if (seckill == null) {
return new Exposer(false, seckillId);
} else {
//3.存入Redis
redisDAO.putSeckill(seckill);
}
}
Date startTime = seckill.getStartTime();
Date endTime = seckill.getEndTime();
//系统当前时间
Date nowTime = new Date();
if (nowTime.getTime() < startTime.getTime()
|| nowTime.getTime() > endTime.getTime()) {
return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(),
endTime.getTime());
}
//转化特定字符串的过程,不可逆
String md5 = getMD5(seckillId);
return new Exposer(true, md5, seckillId);
}
private String getMD5(long seckillId) {
String base = seckillId + "/" + salt;
String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
return md5;
}
@Override
/**
* 执行秒杀
*/
public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException {
if (accessLimitService.tryAcquireSeckill()) { // 如果没有被限流器限制,则执行秒杀处理
// return handleSeckill(seckillId, userPhone, md5);
return handleSeckillAsync(seckillId, userPhone, md5);
} else { //如果被限流器限制,直接抛出访问限制的异常
logger.info("--->ACCESS_LIMITED-->seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.ACCESS_LIMIT);
}
}
/**
* @param seckillId
* @param userPhone
* @param md5
* @return
* @throws SeckillException
* @TODO 先在redis里处理,然后发送到mq,最后减库存到数据库
*/
private SeckillExecution handleSeckillAsync(long seckillId, long userPhone, String md5)
throws SeckillException {
if (md5 == null || !md5.equals(getMD5(seckillId))) {
logger.info("seckill_DATA_REWRITE!!!. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.DATA_REWRITE);
}
Jedis jedis = jedisPool.getResource();
String inventoryKey = RedisKeyPrefix.SECKILL_INVENTORY + seckillId;
if (jedis.sismember(RedisKey.SECKILLED_USER, String.valueOf(userPhone))) {
//重复秒杀
logger.info("seckill REPEATED. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.REPEAT_KILL);
} else {
String inventoryStr = jedis.get(inventoryKey);
int inventory = Integer.valueOf(inventoryStr);
if (inventory <= 0) {
throw new SeckillException(SeckillStateEnum.SOLD_OUT);
}
jedis.watch(inventoryKey);
Transaction tx = jedis.multi();
tx.decr(inventoryKey);
tx.sadd(RedisKey.SECKILLED_USER, String.valueOf(userPhone));
List<Object> resultList = tx.exec();
jedis.unwatch();
if (resultList != null && resultList.size() == 2) {
// 秒杀成功,后面异步更新到数据库中
// 发送消息到消息队列
SeckillMsgBody msgBody = new SeckillMsgBody();
msgBody.setSeckillId(seckillId);
msgBody.setUserPhone(userPhone);
mqProducer.send(JSON.toJSONString(msgBody));
// 立即返回给客户端,说明秒杀成功了
SuccessKilled successKilled = new SuccessKilled();
successKilled.setUserPhone(userPhone);
successKilled.setSeckillId(seckillId);
successKilled.setState(SeckillStateEnum.SUCCESS.getState());
return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
} else {
throw new SeckillException(SeckillStateEnum.RUSH_FAILED);
}
}
}
/**
* 直接在数据库里减库存
*
* @param seckillId
* @param userPhone
* @param md5
* @return
* @throws SeckillException
*/
@Deprecated // 通过redis+mq的形式更能应对高并发,这里的传统方法,舍弃掉
// #handleSeckillAsync(seckillId, userPhone, md5)
/**
* 请使用 {@link SeckillServiceImpl#handleSeckillAsync(long, long, String)} }
*/
private SeckillExecution handleSeckill(long seckillId, long userPhone, String md5)
throws SeckillException {
if (md5 == null || !md5.equals(getMD5(seckillId))) {
logger.info("seckill_DATA_REWRITE!!!. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.DATA_REWRITE);
}
return doUpdateStock(seckillId, userPhone);
}
/**
* 先插入秒杀记录再减库存
*/
@Override
@Transactional
public SeckillExecution doUpdateStock(long seckillId, long userPhone)
throws SeckillException {
//执行秒杀逻辑:减库存 + 记录购买行为
Date nowTime = new Date();
try {
//插入秒杀记录(记录购买行为)
//这处, seckill_record的id等于这个特定id的行被启用了行锁, 但是其他的事务可以insert另外一行, 不会阻止其他事务里对这个表的insert操作
int insertCount = successKilledDAO.insertSuccessKilled(seckillId, userPhone, nowTime);
//唯一:seckillId,userPhone
if (insertCount <= 0) {
//重复秒杀
logger.info("seckill REPEATED. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.REPEAT_KILL);
} else {
//减库存,热点商品竞争
// reduceNumber是update操作,开启作用在表seckill上的行锁
Seckill currentSeckill = seckillDAO.queryById(seckillId);
boolean validTime = false;
if (currentSeckill != null) {
long nowStamp = nowTime.getTime();
if (nowStamp > currentSeckill.getStartTime().getTime() && nowStamp < currentSeckill.getEndTime().getTime()
&& currentSeckill.getInventory() > 0 && currentSeckill.getVersion() > -1) {
validTime = true;
}
}
if (validTime) {
long oldVersion = currentSeckill.getVersion();
// update操作开始,表seckill的seckill_id等于seckillId的行被启用了行锁, 其他的事务无法update这一行, 可以update其他行
int updateCount = seckillDAO.reduceInventory(seckillId, oldVersion, oldVersion + 1);
if (updateCount <= 0) {
//没有更新到记录,秒杀结束,rollback
logger.info("seckill_DATABASE_CONCURRENCY_ERROR!!!. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.DB_CONCURRENCY_ERROR);
} else {
//秒杀成功 commit
SuccessKilled successKilled = successKilledDAO.queryByIdWithSeckill(seckillId, userPhone);
logger.info("seckill SUCCESS->>>. seckillId={},userPhone={}", seckillId, userPhone);
return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
//return后,事务结束,关闭作用在表seckill上的行锁
// update结束,行锁被取消 。reduceInventory()被执行前后数据行被锁定, 其他的事务无法写这一行。
}
} else {
logger.info("seckill_END. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.END);
}
}
} catch (SeckillException e1) {
throw e1;
} catch (Exception e) {
logger.error(e.getMessage(), e);
// 所有编译期异常 转化为运行期异常
throw new SeckillException(SeckillStateEnum.INNER_ERROR);
}
}
}
| bootsrc/jseckill | doc/codesegment/SeckillServiceImpl.java | 2,969 | // 发送消息到消息队列 | line_comment | zh-cn | package com.liushaoming.jseckill.backend.service.impl;
import com.alibaba.fastjson.JSON;
import com.liushaoming.jseckill.backend.constant.RedisKey;
import com.liushaoming.jseckill.backend.constant.RedisKeyPrefix;
import com.liushaoming.jseckill.backend.dao.SeckillDAO;
import com.liushaoming.jseckill.backend.dao.SuccessKilledDAO;
import com.liushaoming.jseckill.backend.dao.cache.RedisDAO;
import com.liushaoming.jseckill.backend.dto.Exposer;
import com.liushaoming.jseckill.backend.dto.SeckillExecution;
import com.liushaoming.jseckill.backend.dto.SeckillMsgBody;
import com.liushaoming.jseckill.backend.entity.Seckill;
import com.liushaoming.jseckill.backend.entity.SuccessKilled;
import com.liushaoming.jseckill.backend.enums.SeckillStateEnum;
import com.liushaoming.jseckill.backend.exception.SeckillException;
import com.liushaoming.jseckill.backend.mq.MQProducer;
import com.liushaoming.jseckill.backend.service.AccessLimitService;
import com.liushaoming.jseckill.backend.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Transaction;
import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
/**
* @author liushaoming
*/
@Service
public class SeckillServiceImpl implements SeckillService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
//md5盐值字符串,用于混淆MD5
private final String salt = "aksksks*&&^%%aaaa&^^%%*";
//注入Service依赖
@Autowired
private SeckillDAO seckillDAO;
@Autowired
private SuccessKilledDAO successKilledDAO;
@Autowired
private RedisDAO redisDAO;
@Autowired
private AccessLimitService accessLimitService;
@Autowired
private MQProducer mqProducer;
@Resource(name = "initJedisPool")
private JedisPool jedisPool;
@Override
public List<Seckill> getSeckillList() {
return seckillDAO.queryAll(0, 10);
}
@Override
public Seckill getById(long seckillId) {
return seckillDAO.queryById(seckillId);
}
@Override
public Exposer exportSeckillUrl(long seckillId) {
// 优化点:缓存优化:超时的基础上维护一致性
//1.访问Redis
Seckill seckill = redisDAO.getSeckill(seckillId);
if (seckill == null) {
//2.访问数据库
seckill = seckillDAO.queryById(seckillId);
if (seckill == null) {
return new Exposer(false, seckillId);
} else {
//3.存入Redis
redisDAO.putSeckill(seckill);
}
}
Date startTime = seckill.getStartTime();
Date endTime = seckill.getEndTime();
//系统当前时间
Date nowTime = new Date();
if (nowTime.getTime() < startTime.getTime()
|| nowTime.getTime() > endTime.getTime()) {
return new Exposer(false, seckillId, nowTime.getTime(), startTime.getTime(),
endTime.getTime());
}
//转化特定字符串的过程,不可逆
String md5 = getMD5(seckillId);
return new Exposer(true, md5, seckillId);
}
private String getMD5(long seckillId) {
String base = seckillId + "/" + salt;
String md5 = DigestUtils.md5DigestAsHex(base.getBytes());
return md5;
}
@Override
/**
* 执行秒杀
*/
public SeckillExecution executeSeckill(long seckillId, long userPhone, String md5) throws SeckillException {
if (accessLimitService.tryAcquireSeckill()) { // 如果没有被限流器限制,则执行秒杀处理
// return handleSeckill(seckillId, userPhone, md5);
return handleSeckillAsync(seckillId, userPhone, md5);
} else { //如果被限流器限制,直接抛出访问限制的异常
logger.info("--->ACCESS_LIMITED-->seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.ACCESS_LIMIT);
}
}
/**
* @param seckillId
* @param userPhone
* @param md5
* @return
* @throws SeckillException
* @TODO 先在redis里处理,然后发送到mq,最后减库存到数据库
*/
private SeckillExecution handleSeckillAsync(long seckillId, long userPhone, String md5)
throws SeckillException {
if (md5 == null || !md5.equals(getMD5(seckillId))) {
logger.info("seckill_DATA_REWRITE!!!. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.DATA_REWRITE);
}
Jedis jedis = jedisPool.getResource();
String inventoryKey = RedisKeyPrefix.SECKILL_INVENTORY + seckillId;
if (jedis.sismember(RedisKey.SECKILLED_USER, String.valueOf(userPhone))) {
//重复秒杀
logger.info("seckill REPEATED. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.REPEAT_KILL);
} else {
String inventoryStr = jedis.get(inventoryKey);
int inventory = Integer.valueOf(inventoryStr);
if (inventory <= 0) {
throw new SeckillException(SeckillStateEnum.SOLD_OUT);
}
jedis.watch(inventoryKey);
Transaction tx = jedis.multi();
tx.decr(inventoryKey);
tx.sadd(RedisKey.SECKILLED_USER, String.valueOf(userPhone));
List<Object> resultList = tx.exec();
jedis.unwatch();
if (resultList != null && resultList.size() == 2) {
// 秒杀成功,后面异步更新到数据库中
// 发送 <SUF>
SeckillMsgBody msgBody = new SeckillMsgBody();
msgBody.setSeckillId(seckillId);
msgBody.setUserPhone(userPhone);
mqProducer.send(JSON.toJSONString(msgBody));
// 立即返回给客户端,说明秒杀成功了
SuccessKilled successKilled = new SuccessKilled();
successKilled.setUserPhone(userPhone);
successKilled.setSeckillId(seckillId);
successKilled.setState(SeckillStateEnum.SUCCESS.getState());
return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
} else {
throw new SeckillException(SeckillStateEnum.RUSH_FAILED);
}
}
}
/**
* 直接在数据库里减库存
*
* @param seckillId
* @param userPhone
* @param md5
* @return
* @throws SeckillException
*/
@Deprecated // 通过redis+mq的形式更能应对高并发,这里的传统方法,舍弃掉
// #handleSeckillAsync(seckillId, userPhone, md5)
/**
* 请使用 {@link SeckillServiceImpl#handleSeckillAsync(long, long, String)} }
*/
private SeckillExecution handleSeckill(long seckillId, long userPhone, String md5)
throws SeckillException {
if (md5 == null || !md5.equals(getMD5(seckillId))) {
logger.info("seckill_DATA_REWRITE!!!. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.DATA_REWRITE);
}
return doUpdateStock(seckillId, userPhone);
}
/**
* 先插入秒杀记录再减库存
*/
@Override
@Transactional
public SeckillExecution doUpdateStock(long seckillId, long userPhone)
throws SeckillException {
//执行秒杀逻辑:减库存 + 记录购买行为
Date nowTime = new Date();
try {
//插入秒杀记录(记录购买行为)
//这处, seckill_record的id等于这个特定id的行被启用了行锁, 但是其他的事务可以insert另外一行, 不会阻止其他事务里对这个表的insert操作
int insertCount = successKilledDAO.insertSuccessKilled(seckillId, userPhone, nowTime);
//唯一:seckillId,userPhone
if (insertCount <= 0) {
//重复秒杀
logger.info("seckill REPEATED. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.REPEAT_KILL);
} else {
//减库存,热点商品竞争
// reduceNumber是update操作,开启作用在表seckill上的行锁
Seckill currentSeckill = seckillDAO.queryById(seckillId);
boolean validTime = false;
if (currentSeckill != null) {
long nowStamp = nowTime.getTime();
if (nowStamp > currentSeckill.getStartTime().getTime() && nowStamp < currentSeckill.getEndTime().getTime()
&& currentSeckill.getInventory() > 0 && currentSeckill.getVersion() > -1) {
validTime = true;
}
}
if (validTime) {
long oldVersion = currentSeckill.getVersion();
// update操作开始,表seckill的seckill_id等于seckillId的行被启用了行锁, 其他的事务无法update这一行, 可以update其他行
int updateCount = seckillDAO.reduceInventory(seckillId, oldVersion, oldVersion + 1);
if (updateCount <= 0) {
//没有更新到记录,秒杀结束,rollback
logger.info("seckill_DATABASE_CONCURRENCY_ERROR!!!. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.DB_CONCURRENCY_ERROR);
} else {
//秒杀成功 commit
SuccessKilled successKilled = successKilledDAO.queryByIdWithSeckill(seckillId, userPhone);
logger.info("seckill SUCCESS->>>. seckillId={},userPhone={}", seckillId, userPhone);
return new SeckillExecution(seckillId, SeckillStateEnum.SUCCESS, successKilled);
//return后,事务结束,关闭作用在表seckill上的行锁
// update结束,行锁被取消 。reduceInventory()被执行前后数据行被锁定, 其他的事务无法写这一行。
}
} else {
logger.info("seckill_END. seckillId={},userPhone={}", seckillId, userPhone);
throw new SeckillException(SeckillStateEnum.END);
}
}
} catch (SeckillException e1) {
throw e1;
} catch (Exception e) {
logger.error(e.getMessage(), e);
// 所有编译期异常 转化为运行期异常
throw new SeckillException(SeckillStateEnum.INNER_ERROR);
}
}
}
| false | 2,509 | 8 | 2,969 | 7 | 2,872 | 6 | 2,969 | 7 | 3,662 | 13 | false | false | false | false | false | true |
17049_3 | package dp;
import java.util.List;
/**
* dp[i] 表示以i-1结尾的子串能否被成功拆分
*
* 注意注意!!:
* 这道本质上来说,和走楼梯是一样的!!
* @see LC746_MinCostClimbingStairs
* 对于走楼梯来说,我们不是走到了某一阶台阶,然后回看其下面的2阶吗?
*
* 这道题就是走到了某一阶台阶,回看后面的LongestWordInDict 阶 台阶 而已
* 本质上是没啥不一样的!!!
*
*/
public class LC139_WordBreak {
public boolean wordBreak(String s, List<String> wordDict) {
if (s.length() == 0) {
return false;
}
if (wordDict.size() == 0) {
return false;
}
int maxWordLen = 0;
for (int i = 0; i < wordDict.size(); i++) {
maxWordLen = Math.max(maxWordLen, wordDict.get(i).length());
}
boolean[] dp = new boolean[s.length()+1];
// 如果s中啥也没有,那么当然可以被拆分?
dp[0] = true;
// 这里的界很有意思 i是从(1~s.length)这个很好理解,因为要遍历整条串
for (int i = 1; i <= s.length(); i++) {
// j是从0到i,或者i-1,其实都一样,因为substring方法是左闭右开的,所以j<=i的时候仅仅是取到空集。。
int tmp = Math.max((i - maxWordLen), 0);
for (int j = tmp; j < i; j++) {
if(dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
| boqigao/rea_leetcode | src/dp/LC139_WordBreak.java | 495 | // j是从0到i,或者i-1,其实都一样,因为substring方法是左闭右开的,所以j<=i的时候仅仅是取到空集。。 | line_comment | zh-cn | package dp;
import java.util.List;
/**
* dp[i] 表示以i-1结尾的子串能否被成功拆分
*
* 注意注意!!:
* 这道本质上来说,和走楼梯是一样的!!
* @see LC746_MinCostClimbingStairs
* 对于走楼梯来说,我们不是走到了某一阶台阶,然后回看其下面的2阶吗?
*
* 这道题就是走到了某一阶台阶,回看后面的LongestWordInDict 阶 台阶 而已
* 本质上是没啥不一样的!!!
*
*/
public class LC139_WordBreak {
public boolean wordBreak(String s, List<String> wordDict) {
if (s.length() == 0) {
return false;
}
if (wordDict.size() == 0) {
return false;
}
int maxWordLen = 0;
for (int i = 0; i < wordDict.size(); i++) {
maxWordLen = Math.max(maxWordLen, wordDict.get(i).length());
}
boolean[] dp = new boolean[s.length()+1];
// 如果s中啥也没有,那么当然可以被拆分?
dp[0] = true;
// 这里的界很有意思 i是从(1~s.length)这个很好理解,因为要遍历整条串
for (int i = 1; i <= s.length(); i++) {
// j是 <SUF>
int tmp = Math.max((i - maxWordLen), 0);
for (int j = tmp; j < i; j++) {
if(dp[j] && wordDict.contains(s.substring(j, i))) {
dp[i] = true;
break;
}
}
}
return dp[s.length()];
}
}
| false | 430 | 37 | 495 | 40 | 485 | 37 | 495 | 40 | 640 | 55 | false | false | false | false | false | true |
57242_4 | package com.riversoft.weixin.common.event;
/**
* Created by exizhai on 9/30/2015.
*/
public enum EventType {
subscribe,
unsubscribe,
LOCATION,
/**
* 忍不住骂人
*/
click,//企业号
CLICK,//服务号,订阅号
view,//企业号
VIEW,//服务号,订阅号
scancode_push,
scancode_waitmsg,
pic_sysphoto,
pic_photo_or_album,
pic_weixin,
location_select,
enter_agent,
batch_job_result,
media_id,
view_limited,
/**
* 多客服接口特有
*/
kf_create_session,
kf_close_session,
kf_switch_session,
/**
* 群发消息结果
*/
MASSSENDJOBFINISH,
/**
* 服务号,订阅号:扫描带参数二维码事件, 用户已关注时的事件推送
*/
SCAN,
/**
* 模板消息下发结果通知事件
*/
TEMPLATESENDJOBFINISH,
/**
* 订单事件
*/
ORDER,
/**
* 小程序:进入会话事件
*/
user_enter_tempsession
}
| borball/weixin-sdk | weixin-common/src/main/java/com/riversoft/weixin/common/event/EventType.java | 305 | //企业号
| line_comment | zh-cn | package com.riversoft.weixin.common.event;
/**
* Created by exizhai on 9/30/2015.
*/
public enum EventType {
subscribe,
unsubscribe,
LOCATION,
/**
* 忍不住骂人
*/
click,//企业号
CLICK,//服务号,订阅号
view,//企业 <SUF>
VIEW,//服务号,订阅号
scancode_push,
scancode_waitmsg,
pic_sysphoto,
pic_photo_or_album,
pic_weixin,
location_select,
enter_agent,
batch_job_result,
media_id,
view_limited,
/**
* 多客服接口特有
*/
kf_create_session,
kf_close_session,
kf_switch_session,
/**
* 群发消息结果
*/
MASSSENDJOBFINISH,
/**
* 服务号,订阅号:扫描带参数二维码事件, 用户已关注时的事件推送
*/
SCAN,
/**
* 模板消息下发结果通知事件
*/
TEMPLATESENDJOBFINISH,
/**
* 订单事件
*/
ORDER,
/**
* 小程序:进入会话事件
*/
user_enter_tempsession
}
| false | 269 | 4 | 303 | 4 | 318 | 4 | 303 | 4 | 442 | 7 | false | false | false | false | false | true |
35035_2 | package utils;
import java.util.Locale;
public class StringUtils {
/**
* 将string按需要格式化,前面加缩进符,后面加换行符
* @param tabNum 缩进量
* @param srcString
* @return
*/
public static String formatSingleLine(int tabNum, String srcString) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<tabNum; i++) {
sb.append("\t");
}
sb.append(srcString);
sb.append("\n");
return sb.toString();
}
public static String firstToUpperCase(String key) {
return key.substring(0, 1).toUpperCase(Locale.getDefault()) + key.substring(1);
}
/**
* 驼峰转下划线命名
*/
public static String camel2underline(String src) {
StringBuilder sb = new StringBuilder();
StringBuilder sbWord = new StringBuilder();
char[] chars = src.trim().toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if(c >= 'A' && c <= 'Z') {
// 一旦遇到大写单词,保存之前已有字符组成的单词
if(sbWord.length() > 0) {
if(sb.length() > 0) {
sb.append("_");
}
sb.append(sbWord.toString());
}
sbWord = new StringBuilder();
}
sbWord.append(c);
}
if(sbWord.length() > 0) {
if(sb.length() > 0) {
sb.append("_");
}
sb.append(sbWord.toString());
}
return sb.toString();
}
}
| boredream/BorePlugin | LayoutCreator/src/utils/StringUtils.java | 451 | // 一旦遇到大写单词,保存之前已有字符组成的单词 | line_comment | zh-cn | package utils;
import java.util.Locale;
public class StringUtils {
/**
* 将string按需要格式化,前面加缩进符,后面加换行符
* @param tabNum 缩进量
* @param srcString
* @return
*/
public static String formatSingleLine(int tabNum, String srcString) {
StringBuilder sb = new StringBuilder();
for(int i=0; i<tabNum; i++) {
sb.append("\t");
}
sb.append(srcString);
sb.append("\n");
return sb.toString();
}
public static String firstToUpperCase(String key) {
return key.substring(0, 1).toUpperCase(Locale.getDefault()) + key.substring(1);
}
/**
* 驼峰转下划线命名
*/
public static String camel2underline(String src) {
StringBuilder sb = new StringBuilder();
StringBuilder sbWord = new StringBuilder();
char[] chars = src.trim().toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
if(c >= 'A' && c <= 'Z') {
// 一旦 <SUF>
if(sbWord.length() > 0) {
if(sb.length() > 0) {
sb.append("_");
}
sb.append(sbWord.toString());
}
sbWord = new StringBuilder();
}
sbWord.append(c);
}
if(sbWord.length() > 0) {
if(sb.length() > 0) {
sb.append("_");
}
sb.append(sbWord.toString());
}
return sb.toString();
}
}
| false | 372 | 14 | 451 | 21 | 450 | 15 | 451 | 21 | 567 | 32 | false | false | false | false | false | true |