file_id
stringlengths 5
8
| content
stringlengths 131
14.4k
| repo
stringlengths 9
59
| path
stringlengths 8
120
| token_length
int64 36
3.49k
| original_comment
stringlengths 5
791
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 135
14.3k
| excluded
float64 0
0
| file-tokens-Qwen/Qwen2-7B
int64 30
3.27k
| comment-tokens-Qwen/Qwen2-7B
int64 2
459
| file-tokens-bigcode/starcoder2-7b
int64 35
3.49k
| comment-tokens-bigcode/starcoder2-7b
int64 3
483
| file-tokens-google/codegemma-7b
int64 36
3.61k
| comment-tokens-google/codegemma-7b
int64 3
465
| file-tokens-ibm-granite/granite-8b-code-base
int64 35
3.49k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 3
483
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 44
4.13k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
592
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
56954_1 | package View;
import Configure.ViewConfigure;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* @author dmrfcoder
* @date 2019-04-17
*/
public class SwichButton extends JLabel {
//0代表开始/绿色(停止中),1代表结束/红色(运行中)
private int curState;
private int D;
interface StateChangeListener {
void changeToRunning();
void changeToStop();
}
private StateChangeListener stateChangeListener;
public void setStateChangeListener(StateChangeListener stateChangeListener) {
this.stateChangeListener = stateChangeListener;
}
public SwichButton(int D) {
curState = 0;
this.D = D;
initListener();
}
private void initListener() {
addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (curState == 0) {
curState = 1;
stateChangeListener.changeToRunning();
} else {
curState = 0;
stateChangeListener.changeToStop();
}
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (curState == 0) {
g.setColor(ViewConfigure.defaultTextColor);
} else {
g.setColor(Color.red);
}
g.fillOval((getWidth() - D) / 2, (getHeight() - D) / 2, D, D);
String text = "";
g.setColor(Color.BLACK);
if (curState == 0) {
text = "开始";
} else {
text = "结束";
}
g.drawString(text, (getWidth() - 25) / 2, 5 + getHeight() / 2);
}
}
| DmrfCoder/SimulationRouter | src/View/SwichButton.java | 524 | //0代表开始/绿色(停止中),1代表结束/红色(运行中) | line_comment | zh-cn | package View;
import Configure.ViewConfigure;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* @author dmrfcoder
* @date 2019-04-17
*/
public class SwichButton extends JLabel {
//0代 <SUF>
private int curState;
private int D;
interface StateChangeListener {
void changeToRunning();
void changeToStop();
}
private StateChangeListener stateChangeListener;
public void setStateChangeListener(StateChangeListener stateChangeListener) {
this.stateChangeListener = stateChangeListener;
}
public SwichButton(int D) {
curState = 0;
this.D = D;
initListener();
}
private void initListener() {
addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (curState == 0) {
curState = 1;
stateChangeListener.changeToRunning();
} else {
curState = 0;
stateChangeListener.changeToStop();
}
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (curState == 0) {
g.setColor(ViewConfigure.defaultTextColor);
} else {
g.setColor(Color.red);
}
g.fillOval((getWidth() - D) / 2, (getHeight() - D) / 2, D, D);
String text = "";
g.setColor(Color.BLACK);
if (curState == 0) {
text = "开始";
} else {
text = "结束";
}
g.drawString(text, (getWidth() - 25) / 2, 5 + getHeight() / 2);
}
}
| 0 | 463 | 19 | 524 | 22 | 569 | 19 | 524 | 22 | 669 | 34 | false | false | false | false | false | true |
56936_1 | package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class GameFrame extends JFrame implements ActionListener{
static boolean judge = true;
static String name;
public GameFrame() {
setSize(288, 512);//设置窗口大小(288,512);
setLocationRelativeTo(null);//窗口位于电脑的正中间;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按键
setResizable(false);
setTitle("Flappy Bird终极豪华版");
init();
}
public static void main(String[] args){
GameFrame frame = new GameFrame();
GamePanel panel = new GamePanel();
frame.add(panel);//添加到界面
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {}
void init() {
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("菜单");
JMenu birdcolor = new JMenu("小鸟颜色");
JMenu bgcolor = new JMenu("背景主题");
JMenu column = new JMenu("柱子颜色");
menubar.add(menu);
JMenuItem itembc1 = new JMenuItem("黄色");
JMenuItem itembc2 = new JMenuItem("蓝色");
JMenuItem itembc3 = new JMenuItem("红色");
menu.add(birdcolor);
birdcolor.add(itembc1);
birdcolor.add(itembc2);
birdcolor.add(itembc3);
JMenuItem itembg1 = new JMenuItem("白天");
JMenuItem itembg2 = new JMenuItem("黑夜");
menu.add(bgcolor);
bgcolor.add(itembg1);
bgcolor.add(itembg2);
JMenuItem itemc1 = new JMenuItem("绿色");
JMenuItem itemc2 = new JMenuItem("橙色");
menu.add(column);
column.add(itemc1);
column.add(itemc2);
setJMenuBar(menubar);
itembc1.addActionListener(this);
itembc2.addActionListener(this);
itembc3.addActionListener(this);
itembg1.addActionListener(this);
itembg2.addActionListener(this);
itemc1.addActionListener(this);
itemc2.addActionListener(this);
itembc1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 0;
}
});
itembc2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 1;
}
});
itembc3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 2;
}
});
itemc1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Column.j = 0;
}
});
itemc2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Column.j = 1;
}
});
itembg1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GamePanel.j = 1;
}
});
itembg2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GamePanel.j = 0;
}
});
}
}
| DmuFreeCoding/DMU-cs-course | Java/MrLeea/src/game/GameFrame.java | 884 | //窗口位于电脑的正中间; | line_comment | zh-cn | package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class GameFrame extends JFrame implements ActionListener{
static boolean judge = true;
static String name;
public GameFrame() {
setSize(288, 512);//设置窗口大小(288,512);
setLocationRelativeTo(null);//窗口 <SUF>
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按键
setResizable(false);
setTitle("Flappy Bird终极豪华版");
init();
}
public static void main(String[] args){
GameFrame frame = new GameFrame();
GamePanel panel = new GamePanel();
frame.add(panel);//添加到界面
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {}
void init() {
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("菜单");
JMenu birdcolor = new JMenu("小鸟颜色");
JMenu bgcolor = new JMenu("背景主题");
JMenu column = new JMenu("柱子颜色");
menubar.add(menu);
JMenuItem itembc1 = new JMenuItem("黄色");
JMenuItem itembc2 = new JMenuItem("蓝色");
JMenuItem itembc3 = new JMenuItem("红色");
menu.add(birdcolor);
birdcolor.add(itembc1);
birdcolor.add(itembc2);
birdcolor.add(itembc3);
JMenuItem itembg1 = new JMenuItem("白天");
JMenuItem itembg2 = new JMenuItem("黑夜");
menu.add(bgcolor);
bgcolor.add(itembg1);
bgcolor.add(itembg2);
JMenuItem itemc1 = new JMenuItem("绿色");
JMenuItem itemc2 = new JMenuItem("橙色");
menu.add(column);
column.add(itemc1);
column.add(itemc2);
setJMenuBar(menubar);
itembc1.addActionListener(this);
itembc2.addActionListener(this);
itembc3.addActionListener(this);
itembg1.addActionListener(this);
itembg2.addActionListener(this);
itemc1.addActionListener(this);
itemc2.addActionListener(this);
itembc1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 0;
}
});
itembc2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 1;
}
});
itembc3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 2;
}
});
itemc1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Column.j = 0;
}
});
itemc2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Column.j = 1;
}
});
itembg1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GamePanel.j = 1;
}
});
itembg2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GamePanel.j = 0;
}
});
}
}
| 0 | 688 | 8 | 884 | 10 | 843 | 8 | 884 | 10 | 1,132 | 16 | false | false | false | false | false | true |
45653_7 | package com.dnake.panel;
import com.dnake.misc.SysTalk;
import com.dnake.misc.sCaller;
import com.dnake.misc.Sound;
import com.dnake.v700.dmsg;
import com.dnake.v700.dxml;
import com.dnake.v700.sys;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
@SuppressLint({ "DefaultLocale", "SetJavaScriptEnabled", "NewApi" })
public class TalkLabel extends BaseLabel {
public static Intent mIntent = null;
public static TalkLabel mContext = null;
public static int build = 0;
public static int unit = 0;
public static int id;
public static int OUT = 0;
public static int IN = 1;
public static int mMode = 0; // 0:呼出, 1:呼入
private MediaPlayer mPlayer = null;
private TextView mText;
private long mAutoTs = 0;
private long mEndTs = 0;
private String mPstnDtmf = null; // 语音网关拨号DTMF
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.talk);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility();
if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
mContext = this;
mPeriod = 300;
mText = (TextView) this.findViewById(R.id.prompt_text);
if (mMode == OUT) {
mText.setText(R.string.sCaller_call);
} else if (mMode == IN) {
mText.setText(R.string.sCaller_monitor);
}
}
@Override
public void onStart() {
super.onStart();
mContext = this;
this.onStart2();
}
public void onStart2() {
sCaller.refresh();
if (mMode == OUT) {
String s;
if (id == 0) { // 呼叫管理机,使用固定ID
id = 10001;
s = "10001";
} else {
s = String.format("%d%02d%04d", build, unit, id);
}
sCaller.query(s);
OnCompletionListener listener = new OnCompletionListener() {
public void onCompletion(MediaPlayer p) {
p.stop();
p.reset();
p.release();
mPlayer = null;
}
};
mPlayer = Sound.play(Sound.ringback, true, listener);
} else {
mAutoTs = System.currentTimeMillis();
}
}
@Override
public void onStop() {
super.onStop();
if (sCaller.running != sCaller.NONE)
this.stop(true);
mIntent = null;
mAutoTs = 0;
mContext = null;
}
@Override
public void onTimer() {
super.onTimer();
WakeTask.acquire();
int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility();
if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
if (mMode == OUT) {// 呼叫
if (sCaller.running == sCaller.QUERY) {
if (sys.qResult.sip.url != null) {
sCaller.start(sys.qResult.sip.url);
sCaller.logger(sCaller.logger.CALL);
sys.qResult.sip.url = null;
} else if (sys.qResult.d600.ip != null) {
System.out.println("ip: " + sys.qResult.d600.ip);
sCaller.s600(sys.qResult.d600.host, sys.qResult.d600.ip);
} else if (sCaller.timeout() >= sCaller.Time.QUERY)
this.forward();
} else if (sCaller.running == sCaller.CALL) {
if (sCaller.timeout() >= sCaller.Time.CALL || sys.qResult.result >= 400)
this.forward();
} else if (sCaller.running == sCaller.RINGING) {
// 有转呼25秒超时,其他按系统设置
int timeout = sys.panel.ringing * 1000;
if (sCaller.timeout() >= timeout) { // 振铃超时
if (!this.forward()) { // 转呼失败
mText.setText(R.string.sCaller_no_answer);
}
}
} else if (sCaller.running == sCaller.TALK) {
if (sCaller.timeout() >= sys.talk.timeout * 1000) {// 对讲结束
mText.setText(R.string.sCaller_finish);
this.stop(true);
}
if (mPstnDtmf != null && sCaller.timeout() > 1000) {
char d = mPstnDtmf.charAt(0);
mPstnDtmf = mPstnDtmf.substring(1);
if (mPstnDtmf.length() <= 0)
mPstnDtmf = null;
dxml p = new dxml();
dmsg req = new dmsg();
p.setText("/params/dtmf", String.valueOf(d));
req.to("/talk/send_dtmf", p.toString());
}
}
} else if (mMode == IN) {// 监视
if (mAutoTs != 0 && Math.abs(System.currentTimeMillis() - mAutoTs) > 500) {
mAutoTs = 0;
sCaller.running = sCaller.TALK;
dmsg req = new dmsg();
req.to("/talk/start", null);
}
if (sCaller.timeout() >= sCaller.Time.MONITOR) {// 监视超时
this.stop(true);
if (!this.isFinishing())
this.finish();
}
}
if (mEndTs != 0) {
if (Math.abs(System.currentTimeMillis() - mEndTs) >= 1000) {
if (!this.isFinishing())
this.finish();
mEndTs = 0;
}
} else {
if (sCaller.bStop) { // 挂断
this.stop(true);
mText.setText(R.string.sCaller_finish);
}
}
}
@Override
public void onKey(String key) {
super.onKey(key);
if (key.charAt(0) == '*' || key.charAt(0) == 'X') {
if (!this.isFinishing()) {
this.finish();
this.stop(true);
}
}
}
private Boolean forward() {
mText.setText(R.string.sCaller_call_err);
Sound.play(Sound.call_err, false);
this.stop(true);
return false;
}
public void play() {
if (mPlayer != null) {
Sound.stop(mPlayer);
mPlayer = null;
}
mText.setText(R.string.sCaller_talk);
sCaller.logger(sCaller.logger.ANSWER);
}
public void stop(Boolean mode) {
if (mMode == OUT) {
if (sCaller.running == sCaller.RINGING)
sCaller.logger(sCaller.logger.FAILED);
else if (sCaller.running == sCaller.TALK)
sCaller.logger(sCaller.logger.END);
}
dmsg req = new dmsg();
req.to("/talk/stop", null);
sCaller.reset();
if (mode) {
if (mPlayer != null) {
Sound.stop(mPlayer);
mPlayer = null;
}
mEndTs = System.currentTimeMillis();
} else {
mEndTs = 0;
}
}
public static void start(int b, int u, int r) {
build = b;
unit = u;
id = r;
mMode = OUT;
SysTalk.start();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
return true;
return super.onKeyDown(keyCode, event);
}
}
| DnakeFace/Face | ui/talk/src/com/dnake/panel/TalkLabel.java | 2,408 | // 对讲结束
| line_comment | zh-cn | package com.dnake.panel;
import com.dnake.misc.SysTalk;
import com.dnake.misc.sCaller;
import com.dnake.misc.Sound;
import com.dnake.v700.dmsg;
import com.dnake.v700.dxml;
import com.dnake.v700.sys;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
@SuppressLint({ "DefaultLocale", "SetJavaScriptEnabled", "NewApi" })
public class TalkLabel extends BaseLabel {
public static Intent mIntent = null;
public static TalkLabel mContext = null;
public static int build = 0;
public static int unit = 0;
public static int id;
public static int OUT = 0;
public static int IN = 1;
public static int mMode = 0; // 0:呼出, 1:呼入
private MediaPlayer mPlayer = null;
private TextView mText;
private long mAutoTs = 0;
private long mEndTs = 0;
private String mPstnDtmf = null; // 语音网关拨号DTMF
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.talk);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility();
if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
mContext = this;
mPeriod = 300;
mText = (TextView) this.findViewById(R.id.prompt_text);
if (mMode == OUT) {
mText.setText(R.string.sCaller_call);
} else if (mMode == IN) {
mText.setText(R.string.sCaller_monitor);
}
}
@Override
public void onStart() {
super.onStart();
mContext = this;
this.onStart2();
}
public void onStart2() {
sCaller.refresh();
if (mMode == OUT) {
String s;
if (id == 0) { // 呼叫管理机,使用固定ID
id = 10001;
s = "10001";
} else {
s = String.format("%d%02d%04d", build, unit, id);
}
sCaller.query(s);
OnCompletionListener listener = new OnCompletionListener() {
public void onCompletion(MediaPlayer p) {
p.stop();
p.reset();
p.release();
mPlayer = null;
}
};
mPlayer = Sound.play(Sound.ringback, true, listener);
} else {
mAutoTs = System.currentTimeMillis();
}
}
@Override
public void onStop() {
super.onStop();
if (sCaller.running != sCaller.NONE)
this.stop(true);
mIntent = null;
mAutoTs = 0;
mContext = null;
}
@Override
public void onTimer() {
super.onTimer();
WakeTask.acquire();
int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility();
if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
if (mMode == OUT) {// 呼叫
if (sCaller.running == sCaller.QUERY) {
if (sys.qResult.sip.url != null) {
sCaller.start(sys.qResult.sip.url);
sCaller.logger(sCaller.logger.CALL);
sys.qResult.sip.url = null;
} else if (sys.qResult.d600.ip != null) {
System.out.println("ip: " + sys.qResult.d600.ip);
sCaller.s600(sys.qResult.d600.host, sys.qResult.d600.ip);
} else if (sCaller.timeout() >= sCaller.Time.QUERY)
this.forward();
} else if (sCaller.running == sCaller.CALL) {
if (sCaller.timeout() >= sCaller.Time.CALL || sys.qResult.result >= 400)
this.forward();
} else if (sCaller.running == sCaller.RINGING) {
// 有转呼25秒超时,其他按系统设置
int timeout = sys.panel.ringing * 1000;
if (sCaller.timeout() >= timeout) { // 振铃超时
if (!this.forward()) { // 转呼失败
mText.setText(R.string.sCaller_no_answer);
}
}
} else if (sCaller.running == sCaller.TALK) {
if (sCaller.timeout() >= sys.talk.timeout * 1000) {// 对讲 <SUF>
mText.setText(R.string.sCaller_finish);
this.stop(true);
}
if (mPstnDtmf != null && sCaller.timeout() > 1000) {
char d = mPstnDtmf.charAt(0);
mPstnDtmf = mPstnDtmf.substring(1);
if (mPstnDtmf.length() <= 0)
mPstnDtmf = null;
dxml p = new dxml();
dmsg req = new dmsg();
p.setText("/params/dtmf", String.valueOf(d));
req.to("/talk/send_dtmf", p.toString());
}
}
} else if (mMode == IN) {// 监视
if (mAutoTs != 0 && Math.abs(System.currentTimeMillis() - mAutoTs) > 500) {
mAutoTs = 0;
sCaller.running = sCaller.TALK;
dmsg req = new dmsg();
req.to("/talk/start", null);
}
if (sCaller.timeout() >= sCaller.Time.MONITOR) {// 监视超时
this.stop(true);
if (!this.isFinishing())
this.finish();
}
}
if (mEndTs != 0) {
if (Math.abs(System.currentTimeMillis() - mEndTs) >= 1000) {
if (!this.isFinishing())
this.finish();
mEndTs = 0;
}
} else {
if (sCaller.bStop) { // 挂断
this.stop(true);
mText.setText(R.string.sCaller_finish);
}
}
}
@Override
public void onKey(String key) {
super.onKey(key);
if (key.charAt(0) == '*' || key.charAt(0) == 'X') {
if (!this.isFinishing()) {
this.finish();
this.stop(true);
}
}
}
private Boolean forward() {
mText.setText(R.string.sCaller_call_err);
Sound.play(Sound.call_err, false);
this.stop(true);
return false;
}
public void play() {
if (mPlayer != null) {
Sound.stop(mPlayer);
mPlayer = null;
}
mText.setText(R.string.sCaller_talk);
sCaller.logger(sCaller.logger.ANSWER);
}
public void stop(Boolean mode) {
if (mMode == OUT) {
if (sCaller.running == sCaller.RINGING)
sCaller.logger(sCaller.logger.FAILED);
else if (sCaller.running == sCaller.TALK)
sCaller.logger(sCaller.logger.END);
}
dmsg req = new dmsg();
req.to("/talk/stop", null);
sCaller.reset();
if (mode) {
if (mPlayer != null) {
Sound.stop(mPlayer);
mPlayer = null;
}
mEndTs = System.currentTimeMillis();
} else {
mEndTs = 0;
}
}
public static void start(int b, int u, int r) {
build = b;
unit = u;
id = r;
mMode = OUT;
SysTalk.start();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
return true;
return super.onKeyDown(keyCode, event);
}
}
| 0 | 1,925 | 5 | 2,393 | 5 | 2,344 | 5 | 2,393 | 5 | 3,012 | 11 | false | false | false | false | false | true |
53010_2 | package com.randian.win.model;
import java.io.Serializable;
import java.util.List;
/**
* Created by lily on 15-6-24.
*/
public class Coach implements Serializable {
private int id;
private int level;//等级 1:中级 2:高级 3:特级 4:专家
private int distance;
private int order_num;
private int comment_num;
private int reputation_num;
private float score;
private float coach_price;
private String sex;
private String name;
private String city;
private String location;
private String verified;
private String created_at;
private String updated_at;
private String description;
private String hours_class;
private String available_areas;
private String profile_image_url;
private String positive_reputation;
private String categoriesStr;
private List<Sport> sports;//教练对应的课程列表
private List<Category> categories; //category的结构 [{"name":"瑜伽"},{"name":"健身"}]
public class Category implements Serializable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public List<Category> getCategoriesList() {
return categories;
}
public void setCategoriesList(List<Category> categories) {
this.categories = categories;
}
public String getCategories() {
return categoriesStr;
}
public void setCategories(String categoriesStr) {
this.categoriesStr = categoriesStr;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOrder_num() {
return order_num;
}
public void setOrder_num(int order_num) {
this.order_num = order_num;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public int getReputation_num() {
return reputation_num;
}
public void setReputation_num(int reputation_num) {
this.reputation_num = reputation_num;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPositive_reputation() {
return positive_reputation;
}
public void setPositive_reputation(String positive_reputation) {
this.positive_reputation = positive_reputation;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVerified() {
return verified;
}
public void setVerified(String verified) {
this.verified = verified;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHours_class() {
return hours_class;
}
public void setHours_class(String hours_class) {
this.hours_class = hours_class;
}
public String getAvailable_areas() {
return available_areas;
}
public void setAvailable_areas(String available_areas) {
this.available_areas = available_areas;
}
public List<Sport> getSports() {
return sports;
}
public void setSports(List<Sport> sports) {
this.sports = sports;
}
public int getComment_num() {
return comment_num;
}
public void setComment_num(int comment_num) {
this.comment_num = comment_num;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public float getCoach_price() {
return coach_price;
}
public void setCoach_price(float coach_price) {
this.coach_price = coach_price;
}
}
| DoTalkLily/AppKit | app/src/main/java/com/randian/win/model/Coach.java | 1,205 | //教练对应的课程列表 | line_comment | zh-cn | package com.randian.win.model;
import java.io.Serializable;
import java.util.List;
/**
* Created by lily on 15-6-24.
*/
public class Coach implements Serializable {
private int id;
private int level;//等级 1:中级 2:高级 3:特级 4:专家
private int distance;
private int order_num;
private int comment_num;
private int reputation_num;
private float score;
private float coach_price;
private String sex;
private String name;
private String city;
private String location;
private String verified;
private String created_at;
private String updated_at;
private String description;
private String hours_class;
private String available_areas;
private String profile_image_url;
private String positive_reputation;
private String categoriesStr;
private List<Sport> sports;//教练 <SUF>
private List<Category> categories; //category的结构 [{"name":"瑜伽"},{"name":"健身"}]
public class Category implements Serializable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public List<Category> getCategoriesList() {
return categories;
}
public void setCategoriesList(List<Category> categories) {
this.categories = categories;
}
public String getCategories() {
return categoriesStr;
}
public void setCategories(String categoriesStr) {
this.categoriesStr = categoriesStr;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOrder_num() {
return order_num;
}
public void setOrder_num(int order_num) {
this.order_num = order_num;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public int getReputation_num() {
return reputation_num;
}
public void setReputation_num(int reputation_num) {
this.reputation_num = reputation_num;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPositive_reputation() {
return positive_reputation;
}
public void setPositive_reputation(String positive_reputation) {
this.positive_reputation = positive_reputation;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVerified() {
return verified;
}
public void setVerified(String verified) {
this.verified = verified;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHours_class() {
return hours_class;
}
public void setHours_class(String hours_class) {
this.hours_class = hours_class;
}
public String getAvailable_areas() {
return available_areas;
}
public void setAvailable_areas(String available_areas) {
this.available_areas = available_areas;
}
public List<Sport> getSports() {
return sports;
}
public void setSports(List<Sport> sports) {
this.sports = sports;
}
public int getComment_num() {
return comment_num;
}
public void setComment_num(int comment_num) {
this.comment_num = comment_num;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public float getCoach_price() {
return coach_price;
}
public void setCoach_price(float coach_price) {
this.coach_price = coach_price;
}
}
| 0 | 1,033 | 5 | 1,205 | 6 | 1,338 | 5 | 1,205 | 6 | 1,473 | 14 | false | false | false | false | false | true |
11898_0 | package xyz.doikki.dkplayer.widget.component;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import xyz.doikki.dkplayer.R;
import xyz.doikki.videoplayer.controller.IControlComponent;
import xyz.doikki.videoplayer.controller.ControlWrapper;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.PlayerUtils;
public class AdControlView extends FrameLayout implements IControlComponent, View.OnClickListener {
protected TextView mAdTime, mAdDetail;
protected ImageView mBack, mVolume, mFullScreen, mPlayButton;
protected AdControlListener mListener;
private ControlWrapper mControlWrapper;
public AdControlView(@NonNull Context context) {
super(context);
}
public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
{
LayoutInflater.from(getContext()).inflate(R.layout.layout_ad_control_view, this, true);
mAdTime = findViewById(R.id.ad_time);
mAdDetail = findViewById(R.id.ad_detail);
mAdDetail.setText("了解详情>");
mBack = findViewById(R.id.back);
mBack.setVisibility(GONE);
mVolume = findViewById(R.id.iv_volume);
mFullScreen = findViewById(R.id.fullscreen);
mPlayButton = findViewById(R.id.iv_play);
mPlayButton.setOnClickListener(this);
mAdTime.setOnClickListener(this);
mAdDetail.setOnClickListener(this);
mBack.setOnClickListener(this);
mVolume.setOnClickListener(this);
mFullScreen.setOnClickListener(this);
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) mListener.onAdClick();
}
});
}
@Override
public void attach(@NonNull ControlWrapper controlWrapper) {
mControlWrapper = controlWrapper;
}
@Override
public View getView() {
return this;
}
@Override
public void onVisibilityChanged(boolean isVisible, Animation anim) {
}
@Override
public void onPlayStateChanged(int playState) {
switch (playState) {
case VideoView.STATE_PLAYING:
mControlWrapper.startProgress();
mPlayButton.setSelected(true);
break;
case VideoView.STATE_PAUSED:
mPlayButton.setSelected(false);
break;
}
}
@Override
public void onPlayerStateChanged(int playerState) {
switch (playerState) {
case VideoView.PLAYER_NORMAL:
mBack.setVisibility(GONE);
mFullScreen.setSelected(false);
break;
case VideoView.PLAYER_FULL_SCREEN:
mBack.setVisibility(VISIBLE);
mFullScreen.setSelected(true);
break;
}
//暂未实现全面屏适配逻辑,需要你自己补全
}
@Override
public void setProgress(int duration, int position) {
if (mAdTime != null)
mAdTime.setText(String.format("%s | 跳过", (duration - position) / 1000));
}
@Override
public void onLockStateChanged(boolean isLocked) {
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.back | id == R.id.fullscreen) {
toggleFullScreen();
} else if (id == R.id.iv_volume) {
doMute();
} else if (id == R.id.ad_detail) {
if (mListener != null) mListener.onAdClick();
} else if (id == R.id.ad_time) {
if (mListener != null) mListener.onSkipAd();
} else if (id == R.id.iv_play) {
mControlWrapper.togglePlay();
}
}
private void doMute() {
mControlWrapper.setMute(!mControlWrapper.isMute());
mVolume.setImageResource(mControlWrapper.isMute() ? R.drawable.dkplayer_ic_action_volume_up : R.drawable.dkplayer_ic_action_volume_off);
}
/**
* 横竖屏切换
*/
private void toggleFullScreen() {
Activity activity = PlayerUtils.scanForActivity(getContext());
mControlWrapper.toggleFullScreen(activity);
}
public void setListener(AdControlListener listener) {
this.mListener = listener;
}
public interface AdControlListener {
void onAdClick();
void onSkipAd();
}
}
| Doikki/DKVideoPlayer | dkplayer-sample/src/main/java/xyz/doikki/dkplayer/widget/component/AdControlView.java | 1,178 | //暂未实现全面屏适配逻辑,需要你自己补全 | line_comment | zh-cn | package xyz.doikki.dkplayer.widget.component;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import xyz.doikki.dkplayer.R;
import xyz.doikki.videoplayer.controller.IControlComponent;
import xyz.doikki.videoplayer.controller.ControlWrapper;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.PlayerUtils;
public class AdControlView extends FrameLayout implements IControlComponent, View.OnClickListener {
protected TextView mAdTime, mAdDetail;
protected ImageView mBack, mVolume, mFullScreen, mPlayButton;
protected AdControlListener mListener;
private ControlWrapper mControlWrapper;
public AdControlView(@NonNull Context context) {
super(context);
}
public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
{
LayoutInflater.from(getContext()).inflate(R.layout.layout_ad_control_view, this, true);
mAdTime = findViewById(R.id.ad_time);
mAdDetail = findViewById(R.id.ad_detail);
mAdDetail.setText("了解详情>");
mBack = findViewById(R.id.back);
mBack.setVisibility(GONE);
mVolume = findViewById(R.id.iv_volume);
mFullScreen = findViewById(R.id.fullscreen);
mPlayButton = findViewById(R.id.iv_play);
mPlayButton.setOnClickListener(this);
mAdTime.setOnClickListener(this);
mAdDetail.setOnClickListener(this);
mBack.setOnClickListener(this);
mVolume.setOnClickListener(this);
mFullScreen.setOnClickListener(this);
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) mListener.onAdClick();
}
});
}
@Override
public void attach(@NonNull ControlWrapper controlWrapper) {
mControlWrapper = controlWrapper;
}
@Override
public View getView() {
return this;
}
@Override
public void onVisibilityChanged(boolean isVisible, Animation anim) {
}
@Override
public void onPlayStateChanged(int playState) {
switch (playState) {
case VideoView.STATE_PLAYING:
mControlWrapper.startProgress();
mPlayButton.setSelected(true);
break;
case VideoView.STATE_PAUSED:
mPlayButton.setSelected(false);
break;
}
}
@Override
public void onPlayerStateChanged(int playerState) {
switch (playerState) {
case VideoView.PLAYER_NORMAL:
mBack.setVisibility(GONE);
mFullScreen.setSelected(false);
break;
case VideoView.PLAYER_FULL_SCREEN:
mBack.setVisibility(VISIBLE);
mFullScreen.setSelected(true);
break;
}
//暂未 <SUF>
}
@Override
public void setProgress(int duration, int position) {
if (mAdTime != null)
mAdTime.setText(String.format("%s | 跳过", (duration - position) / 1000));
}
@Override
public void onLockStateChanged(boolean isLocked) {
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.back | id == R.id.fullscreen) {
toggleFullScreen();
} else if (id == R.id.iv_volume) {
doMute();
} else if (id == R.id.ad_detail) {
if (mListener != null) mListener.onAdClick();
} else if (id == R.id.ad_time) {
if (mListener != null) mListener.onSkipAd();
} else if (id == R.id.iv_play) {
mControlWrapper.togglePlay();
}
}
private void doMute() {
mControlWrapper.setMute(!mControlWrapper.isMute());
mVolume.setImageResource(mControlWrapper.isMute() ? R.drawable.dkplayer_ic_action_volume_up : R.drawable.dkplayer_ic_action_volume_off);
}
/**
* 横竖屏切换
*/
private void toggleFullScreen() {
Activity activity = PlayerUtils.scanForActivity(getContext());
mControlWrapper.toggleFullScreen(activity);
}
public void setListener(AdControlListener listener) {
this.mListener = listener;
}
public interface AdControlListener {
void onAdClick();
void onSkipAd();
}
}
| 0 | 986 | 14 | 1,178 | 16 | 1,264 | 13 | 1,178 | 16 | 1,430 | 34 | false | false | false | false | false | true |
43668_5 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* 显示帮助信息的对话框
*/
public class HelpDialog extends JDialog implements ActionListener {
// 确认按钮
private JButton okay;
// 取消按钮
private JButton cancel;
public HelpDialog(Frame parent,String title) {
super(parent,title,true); //不可缺少true
addText();
okay.addActionListener(this);
cancel.addActionListener(this);
pack();
show();
}
// 显示面板
public void addText() {
setLocation(300, 210);
okay = new JButton("确认");
cancel = new JButton("取消");
Panel button = new Panel();
button.setLayout(new FlowLayout());
button.add(okay);
button.add(cancel);
setLayout(new GridLayout(5,1));
add(new Label("传教士野人过河问题是一个经典的人工智能问题,问题描述如下:"));
add(new Label("有N个传教士和N个野人过河,只有一条能装下K个人(包括野人)的船,K<N,"));
add(new Label("在河的任何一方或者船上,如果有野人和传教士在一起,必须要求传教士的人数多于或等于野人的人数。"));
add(new Label("本程序使用A*搜索算法实现求解传教士野人过河问题,对任意N、K有解时给出其解决方案。"));
add(button);
}
// 监听事件
public void actionPerformed(ActionEvent ae) {
//隐藏对话框
dispose();
}
}; | DolphinHome/java-mc-astar | src/HelpDialog.java | 397 | // 监听事件 | line_comment | zh-cn | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* 显示帮助信息的对话框
*/
public class HelpDialog extends JDialog implements ActionListener {
// 确认按钮
private JButton okay;
// 取消按钮
private JButton cancel;
public HelpDialog(Frame parent,String title) {
super(parent,title,true); //不可缺少true
addText();
okay.addActionListener(this);
cancel.addActionListener(this);
pack();
show();
}
// 显示面板
public void addText() {
setLocation(300, 210);
okay = new JButton("确认");
cancel = new JButton("取消");
Panel button = new Panel();
button.setLayout(new FlowLayout());
button.add(okay);
button.add(cancel);
setLayout(new GridLayout(5,1));
add(new Label("传教士野人过河问题是一个经典的人工智能问题,问题描述如下:"));
add(new Label("有N个传教士和N个野人过河,只有一条能装下K个人(包括野人)的船,K<N,"));
add(new Label("在河的任何一方或者船上,如果有野人和传教士在一起,必须要求传教士的人数多于或等于野人的人数。"));
add(new Label("本程序使用A*搜索算法实现求解传教士野人过河问题,对任意N、K有解时给出其解决方案。"));
add(button);
}
// 监听 <SUF>
public void actionPerformed(ActionEvent ae) {
//隐藏对话框
dispose();
}
}; | 0 | 350 | 5 | 397 | 4 | 400 | 4 | 397 | 4 | 525 | 10 | false | false | false | false | false | true |
38345_5 | import java.util.HashMap;
/**
* LRU算法 最近最常使用算法,内存加载
*/
public class LRU {
public static class Node<V> {
public Node<V> pre;
public Node<V> next;
public V value;
public Node(V value) {
this.value = value;
}
}
public static class MyCache<K, V> {
//map可保证为(1)的查询对应关系
private HashMap<K, Node<V>> keyNodeMap;
private NodeDoubleLinkedList<V> nodeList;
private int capacity;
public MyCache(int capacity) {
if (capacity < 1) {
new RuntimeException("should be more than 1 ");
}
this.capacity = capacity;
this.keyNodeMap = new HashMap<>();
this.nodeList = new NodeDoubleLinkedList<>();
}
public V get(K key) {
if (this.keyNodeMap.containsKey(key)) {
Node<V> res = this.keyNodeMap.get(key);
this.nodeList.moveNodeToTail(res);
return res.value;
}
return null;
}
public void set(K key, V value) {
if (keyNodeMap.containsKey(key)) {
Node<V> res = this.keyNodeMap.get(key);
res.value = value;
this.nodeList.moveNodeToTail(res);
} else {
Node<V> res = new Node<>(value);
this.nodeList.addNode(res);
this.keyNodeMap.put(key, res);
//大于指定容量移除掉头部,为最不经常使用的节点,同时移除掉map集合中的元素
if (this.keyNodeMap.size() == capacity + 1) {
Node<V> removeNode = this.nodeList.removeHead();
keyNodeMap.remove(removeNode.value);
}
}
}
}
/**
* 双向链表 ,有头尾指针,头指针为最不经常使用的节点,尾指针为刚使用完的节点
*
* @param <V>
*/
public static class NodeDoubleLinkedList<V> {
private Node<V> head;
private Node<V> tail;
public NodeDoubleLinkedList() {
this.head = null;
this.tail = null;
}
public void addNode(Node<V> newNode) {
if (newNode == null) {
return;
}
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
//双向链表
this.tail.next = newNode;
newNode.pre = this.tail;
this.tail = newNode;
}
}
public void moveNodeToTail(Node<V> node) {
if (this.tail == null) {
return;
}
//先断开之前的位置
if (this.head == node) {
head = node.next;
this.head.pre = null;
} else {
node.pre.next = node.next;
node.next.pre = node.pre;
}
//移动到最后的位置
node.pre = this.tail;
node.next = null;
this.tail.next = node;
this.tail = node;
}
public Node<V> removeHead() {
if (head == null) {
return null;
}
Node removeNode = this.head;
if (this.head == this.tail) {
this.head = null;
this.tail = null;
} else {
this.head = removeNode.next;
this.head.pre = null;
removeNode.next = null;
}
return removeNode;
}
}
}
| Dongyang666/leetcode | src/LRU.java | 967 | //先断开之前的位置 | line_comment | zh-cn | import java.util.HashMap;
/**
* LRU算法 最近最常使用算法,内存加载
*/
public class LRU {
public static class Node<V> {
public Node<V> pre;
public Node<V> next;
public V value;
public Node(V value) {
this.value = value;
}
}
public static class MyCache<K, V> {
//map可保证为(1)的查询对应关系
private HashMap<K, Node<V>> keyNodeMap;
private NodeDoubleLinkedList<V> nodeList;
private int capacity;
public MyCache(int capacity) {
if (capacity < 1) {
new RuntimeException("should be more than 1 ");
}
this.capacity = capacity;
this.keyNodeMap = new HashMap<>();
this.nodeList = new NodeDoubleLinkedList<>();
}
public V get(K key) {
if (this.keyNodeMap.containsKey(key)) {
Node<V> res = this.keyNodeMap.get(key);
this.nodeList.moveNodeToTail(res);
return res.value;
}
return null;
}
public void set(K key, V value) {
if (keyNodeMap.containsKey(key)) {
Node<V> res = this.keyNodeMap.get(key);
res.value = value;
this.nodeList.moveNodeToTail(res);
} else {
Node<V> res = new Node<>(value);
this.nodeList.addNode(res);
this.keyNodeMap.put(key, res);
//大于指定容量移除掉头部,为最不经常使用的节点,同时移除掉map集合中的元素
if (this.keyNodeMap.size() == capacity + 1) {
Node<V> removeNode = this.nodeList.removeHead();
keyNodeMap.remove(removeNode.value);
}
}
}
}
/**
* 双向链表 ,有头尾指针,头指针为最不经常使用的节点,尾指针为刚使用完的节点
*
* @param <V>
*/
public static class NodeDoubleLinkedList<V> {
private Node<V> head;
private Node<V> tail;
public NodeDoubleLinkedList() {
this.head = null;
this.tail = null;
}
public void addNode(Node<V> newNode) {
if (newNode == null) {
return;
}
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
//双向链表
this.tail.next = newNode;
newNode.pre = this.tail;
this.tail = newNode;
}
}
public void moveNodeToTail(Node<V> node) {
if (this.tail == null) {
return;
}
//先断 <SUF>
if (this.head == node) {
head = node.next;
this.head.pre = null;
} else {
node.pre.next = node.next;
node.next.pre = node.pre;
}
//移动到最后的位置
node.pre = this.tail;
node.next = null;
this.tail.next = node;
this.tail = node;
}
public Node<V> removeHead() {
if (head == null) {
return null;
}
Node removeNode = this.head;
if (this.head == this.tail) {
this.head = null;
this.tail = null;
} else {
this.head = removeNode.next;
this.head.pre = null;
removeNode.next = null;
}
return removeNode;
}
}
}
| 0 | 788 | 6 | 967 | 7 | 956 | 6 | 967 | 7 | 1,264 | 9 | false | false | false | false | false | true |
53109_2 | /**
* MIT License
*
* Copyright (c) 2017 CaiDongyu
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.axe.helper.aop;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.axe.annotation.aop.Aspect;
import org.axe.helper.ioc.BeanHelper;
import org.axe.helper.ioc.ClassHelper;
import org.axe.interface_.base.Helper;
import org.axe.interface_.proxy.Proxy;
import org.axe.proxy.base.ProxyManger;
import org.axe.util.ReflectionUtil;
/**
* 方法拦截助手类
* @author CaiDongyu on 2016/4/14.
*/
public final class AopHelper implements Helper{
@Override
public void init() throws Exception{
synchronized (this) {
Map<Class<?>,Set<Class<?>>> proxyMap = createProxyMap();
Map<Class<?>,List<Proxy>> targetMap = createTargetMap(proxyMap);
for (Map.Entry<Class<?>,List<Proxy>> targetEntry:targetMap.entrySet()){
Class<?> targetClass = targetEntry.getKey();
List<Proxy> proxyList = targetEntry.getValue();
//真正的创建目标类的代理对象
Object proxy = ProxyManger.createProxy(targetClass,proxyList);
BeanHelper.setBean(targetClass,proxy);
}
}
}
/**
* 返回代理类与目标类集合的映射
* 比如代理类A,代理了B、C、D三个类
* 通过A类上的注解Aspect指定一个目标注解比如叫M
* B、C、D类都拥有这个注解M,就可以了。
*/
private static Map<Class<?>,Set<Class<?>>> createProxyMap() throws Exception {
Map<Class<?>,Set<Class<?>>> proxyMap = new HashMap<>();
//找到切面抽象类的实现类,就是说,都是切面类
Set<Class<?>> proxyClassSet = ClassHelper.getClassSetBySuper(Proxy.class);
for(Class<?> proxyClass : proxyClassSet){
//继承了 AspectProxy 不算,还得是有指定了切面目标类
if(proxyClass.isAnnotationPresent(Aspect.class)){
Aspect aspect = proxyClass.getAnnotation(Aspect.class);
//TODO:目前AOP实现,还只是针对有目标注解的类做切面,不能细化到方法,这样一旦拦截,会拦截所有方法
//比如事务切面,实际上是切了整个Server类所有方法,但是在切面加强的时候会判断,判断这个方法开不开事务。
Set<Class<?>> targetClassSet = createTargetClassSet(aspect);
proxyMap.put(proxyClass,targetClassSet);
}
}
return proxyMap;
}
private static Set<Class<?>> createTargetClassSet(Aspect aspect) throws Exception{
Set<Class<?>> targetClassSet = new HashSet<>();
//切面目标的指定,依然是通过注解来匹配
Class<? extends Annotation>[] annotations = aspect.value();
//排除Aspect注解本身,因为Aspect注解就是用来指定目标切面注解的
if(annotations != null){
for(Class<? extends Annotation> annotation:annotations){
if(!annotation.equals(Aspect.class)){
//取出含有目标注解的类,作为目标类
targetClassSet.addAll(ClassHelper.getClassSetByAnnotation(annotation));
}
}
}
return targetClassSet;
}
/**
* 将proxy -> targetClassSet 映射关系逆转
* 变成 targetClass -> proxyList 关系
* 也就是说现在是 一个类,对应有多少个proxy去处理
*/
private static Map<Class<?>,List<Proxy>> createTargetMap(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception{
Map<Class<?>,List<Proxy>> targetMap = new HashMap<>();
for (Map.Entry<Class<?>,Set<Class<?>>> proxyEntry:proxyMap.entrySet()){
Class<?> proxyClass = proxyEntry.getKey();
Set<Class<?>> targetClassSet = proxyEntry.getValue();
Proxy proxy = ReflectionUtil.newInstance(proxyClass);
for (Class<?> targetClass : targetClassSet){
if (targetMap.containsKey(targetClass)){
targetMap.get(targetClass).add(proxy);
} else {
List<Proxy> proxyList = new ArrayList<Proxy>();
proxyList.add(proxy);
targetMap.put(targetClass,proxyList);
}
}
}
return targetMap;
}
@Override
public void onStartUp() throws Exception {}
}
| DongyuCai/Axe | axe/src/main/java/org/axe/helper/aop/AopHelper.java | 1,335 | //真正的创建目标类的代理对象 | line_comment | zh-cn | /**
* MIT License
*
* Copyright (c) 2017 CaiDongyu
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.axe.helper.aop;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.axe.annotation.aop.Aspect;
import org.axe.helper.ioc.BeanHelper;
import org.axe.helper.ioc.ClassHelper;
import org.axe.interface_.base.Helper;
import org.axe.interface_.proxy.Proxy;
import org.axe.proxy.base.ProxyManger;
import org.axe.util.ReflectionUtil;
/**
* 方法拦截助手类
* @author CaiDongyu on 2016/4/14.
*/
public final class AopHelper implements Helper{
@Override
public void init() throws Exception{
synchronized (this) {
Map<Class<?>,Set<Class<?>>> proxyMap = createProxyMap();
Map<Class<?>,List<Proxy>> targetMap = createTargetMap(proxyMap);
for (Map.Entry<Class<?>,List<Proxy>> targetEntry:targetMap.entrySet()){
Class<?> targetClass = targetEntry.getKey();
List<Proxy> proxyList = targetEntry.getValue();
//真正 <SUF>
Object proxy = ProxyManger.createProxy(targetClass,proxyList);
BeanHelper.setBean(targetClass,proxy);
}
}
}
/**
* 返回代理类与目标类集合的映射
* 比如代理类A,代理了B、C、D三个类
* 通过A类上的注解Aspect指定一个目标注解比如叫M
* B、C、D类都拥有这个注解M,就可以了。
*/
private static Map<Class<?>,Set<Class<?>>> createProxyMap() throws Exception {
Map<Class<?>,Set<Class<?>>> proxyMap = new HashMap<>();
//找到切面抽象类的实现类,就是说,都是切面类
Set<Class<?>> proxyClassSet = ClassHelper.getClassSetBySuper(Proxy.class);
for(Class<?> proxyClass : proxyClassSet){
//继承了 AspectProxy 不算,还得是有指定了切面目标类
if(proxyClass.isAnnotationPresent(Aspect.class)){
Aspect aspect = proxyClass.getAnnotation(Aspect.class);
//TODO:目前AOP实现,还只是针对有目标注解的类做切面,不能细化到方法,这样一旦拦截,会拦截所有方法
//比如事务切面,实际上是切了整个Server类所有方法,但是在切面加强的时候会判断,判断这个方法开不开事务。
Set<Class<?>> targetClassSet = createTargetClassSet(aspect);
proxyMap.put(proxyClass,targetClassSet);
}
}
return proxyMap;
}
private static Set<Class<?>> createTargetClassSet(Aspect aspect) throws Exception{
Set<Class<?>> targetClassSet = new HashSet<>();
//切面目标的指定,依然是通过注解来匹配
Class<? extends Annotation>[] annotations = aspect.value();
//排除Aspect注解本身,因为Aspect注解就是用来指定目标切面注解的
if(annotations != null){
for(Class<? extends Annotation> annotation:annotations){
if(!annotation.equals(Aspect.class)){
//取出含有目标注解的类,作为目标类
targetClassSet.addAll(ClassHelper.getClassSetByAnnotation(annotation));
}
}
}
return targetClassSet;
}
/**
* 将proxy -> targetClassSet 映射关系逆转
* 变成 targetClass -> proxyList 关系
* 也就是说现在是 一个类,对应有多少个proxy去处理
*/
private static Map<Class<?>,List<Proxy>> createTargetMap(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception{
Map<Class<?>,List<Proxy>> targetMap = new HashMap<>();
for (Map.Entry<Class<?>,Set<Class<?>>> proxyEntry:proxyMap.entrySet()){
Class<?> proxyClass = proxyEntry.getKey();
Set<Class<?>> targetClassSet = proxyEntry.getValue();
Proxy proxy = ReflectionUtil.newInstance(proxyClass);
for (Class<?> targetClass : targetClassSet){
if (targetMap.containsKey(targetClass)){
targetMap.get(targetClass).add(proxy);
} else {
List<Proxy> proxyList = new ArrayList<Proxy>();
proxyList.add(proxy);
targetMap.put(targetClass,proxyList);
}
}
}
return targetMap;
}
@Override
public void onStartUp() throws Exception {}
}
| 0 | 1,204 | 8 | 1,335 | 9 | 1,381 | 7 | 1,335 | 9 | 1,749 | 14 | false | false | false | false | false | true |
22120_2 | package com.software.job.vo;
import java.sql.Date;
import com.software.job.po.Users;
/*
* 此javaBean为了方便展示页面数据,故和数据库类型不一样
*/
public class UserInfo {
private int id;
private String uname;
private String pwd;
private String email;
private String phone;
private int age;
private String gender;//数据类型改变
private String address;
private String degree;//数据类型改变
private Date joinTime;
private String ip;
public UserInfo() {
}
public UserInfo(Users users) {
super();
this.id = users.getId();
this.uname = users.getUname();
this.pwd = users.getPwd();
this.email = users.getEmail();
this.phone = users.getPhone();
this.age = users.getAge();
setGender(users.getGender());
this.address = users.getAddress();
setDegree(users.getDegree());
this.joinTime = users.getJoinTime();
this.ip = users.getIp();
}
public UserInfo(int id, String uname, String pwd, String email, String phone, int age, int gender, String address,
int degree, Date joinTime, String ip) {
super();
this.id = id;
this.uname = uname;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.age = age;
setGender(gender);
this.address = address;
setDegree(degree);
this.joinTime = joinTime;
this.ip = ip;
}
public UserInfo(String uname, String pwd, String email, String phone, int age, int gender, String address, int degree,
Date joinTime, String ip) {
super();
this.uname = uname;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.age = age;
setGender(gender);
this.address = address;
setDegree(degree);
this.joinTime = joinTime;
this.ip = ip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(int gender) {
if(gender==0) {
this.gender = "男";
}else {
this.gender="女";
}
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDegree() {
return degree;
}
public void setDegree(int degree) {
switch (degree) {
case 0:
this.degree = "高中";
break;
case 1:
this.degree = "专科";
break;
case 2:
this.degree = "本科";
break;
case 3:
this.degree = "硕士";
break;
case 4:
this.degree = "博士";
break;
}
}
public Date getJoinTime() {
return joinTime;
}
public void setJoinTime(Date joinTime) {
this.joinTime = joinTime;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
| DonkeyHu/TypicalWebProject | src/com/software/job/vo/UserInfo.java | 1,100 | //数据类型改变 | line_comment | zh-cn | package com.software.job.vo;
import java.sql.Date;
import com.software.job.po.Users;
/*
* 此javaBean为了方便展示页面数据,故和数据库类型不一样
*/
public class UserInfo {
private int id;
private String uname;
private String pwd;
private String email;
private String phone;
private int age;
private String gender;//数据类型改变
private String address;
private String degree;//数据 <SUF>
private Date joinTime;
private String ip;
public UserInfo() {
}
public UserInfo(Users users) {
super();
this.id = users.getId();
this.uname = users.getUname();
this.pwd = users.getPwd();
this.email = users.getEmail();
this.phone = users.getPhone();
this.age = users.getAge();
setGender(users.getGender());
this.address = users.getAddress();
setDegree(users.getDegree());
this.joinTime = users.getJoinTime();
this.ip = users.getIp();
}
public UserInfo(int id, String uname, String pwd, String email, String phone, int age, int gender, String address,
int degree, Date joinTime, String ip) {
super();
this.id = id;
this.uname = uname;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.age = age;
setGender(gender);
this.address = address;
setDegree(degree);
this.joinTime = joinTime;
this.ip = ip;
}
public UserInfo(String uname, String pwd, String email, String phone, int age, int gender, String address, int degree,
Date joinTime, String ip) {
super();
this.uname = uname;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.age = age;
setGender(gender);
this.address = address;
setDegree(degree);
this.joinTime = joinTime;
this.ip = ip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(int gender) {
if(gender==0) {
this.gender = "男";
}else {
this.gender="女";
}
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDegree() {
return degree;
}
public void setDegree(int degree) {
switch (degree) {
case 0:
this.degree = "高中";
break;
case 1:
this.degree = "专科";
break;
case 2:
this.degree = "本科";
break;
case 3:
this.degree = "硕士";
break;
case 4:
this.degree = "博士";
break;
}
}
public Date getJoinTime() {
return joinTime;
}
public void setJoinTime(Date joinTime) {
this.joinTime = joinTime;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
| 0 | 835 | 4 | 1,100 | 4 | 1,090 | 4 | 1,100 | 4 | 1,283 | 7 | false | false | false | false | false | true |
63609_7 | package priv.fruits.controller.web;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import priv.fruits.pojo.ResultMessage;
import priv.fruits.pojo.User;
import priv.fruits.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @Author 冶生华
* @Description 果蔬超市
*/
@Controller
@RequestMapping("email")
public class EmailController {
// 创建配置好的邮箱对象
@Autowired
private MailAccount mailAccount;
@Autowired
private UserService userService;
/**
* 发送邮箱验证码
* @param userEmail 邮件接收人
* @return
*/
@GetMapping("sendVerifyCode")
@ResponseBody
public ResultMessage sendVerifyCode(String userEmail, String type, HttpServletRequest request) {
try {
// 查询该邮箱是否已注册
User user = userService.getUserInfoByEmail(userEmail);
if("register".equals(type) && user != null && user.getId() != null) {
return new ResultMessage(207, "该邮箱已被注册!");
}
// 生成验证码(随机10000 - 99999的数字)
String code = RandomUtil.randomInt(10000, 99999)+"";
// 将生成的验证码保存到session中, 用于后期验证
HttpSession session = request.getSession();
// 保存前将之前保存过的记录删除一遍, 防止之前有记录
session.removeAttribute("webEditPassVerifyCode");
session.removeAttribute("webRegisterVerifyCode");
// 判断是注册还是修改密码, 保存不同的名字
if("register".equals(type)) {
session.setAttribute("webRegisterVerifyCode", code);
} else if("editPassword".equals(type)) {
session.setAttribute("webEditPassVerifyCode", code);
}
// 利用Hutool封装的邮箱工具类发送邮件
String send = MailUtil.send(mailAccount, CollectionUtil.newArrayList(userEmail),
"您正在注册果蔬超市账户……", "打死都不要告诉别人!!验证码是:" +
"<span style='color:#1E9FFF;font-size:16px;font-weight:800;'>" +
code + "</span>", true);
System.out.println("邮件发送结果:" + send);
return new ResultMessage(0, "邮件已发送!请查收");
} catch (Exception e) {
e.printStackTrace();
return new ResultMessage(500, "出现异常:" + e.getMessage());
}
}
}
| DouFoUncle/daily-fruits | src/main/java/priv/fruits/controller/web/EmailController.java | 733 | // 判断是注册还是修改密码, 保存不同的名字 | line_comment | zh-cn | package priv.fruits.controller.web;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import priv.fruits.pojo.ResultMessage;
import priv.fruits.pojo.User;
import priv.fruits.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @Author 冶生华
* @Description 果蔬超市
*/
@Controller
@RequestMapping("email")
public class EmailController {
// 创建配置好的邮箱对象
@Autowired
private MailAccount mailAccount;
@Autowired
private UserService userService;
/**
* 发送邮箱验证码
* @param userEmail 邮件接收人
* @return
*/
@GetMapping("sendVerifyCode")
@ResponseBody
public ResultMessage sendVerifyCode(String userEmail, String type, HttpServletRequest request) {
try {
// 查询该邮箱是否已注册
User user = userService.getUserInfoByEmail(userEmail);
if("register".equals(type) && user != null && user.getId() != null) {
return new ResultMessage(207, "该邮箱已被注册!");
}
// 生成验证码(随机10000 - 99999的数字)
String code = RandomUtil.randomInt(10000, 99999)+"";
// 将生成的验证码保存到session中, 用于后期验证
HttpSession session = request.getSession();
// 保存前将之前保存过的记录删除一遍, 防止之前有记录
session.removeAttribute("webEditPassVerifyCode");
session.removeAttribute("webRegisterVerifyCode");
// 判断 <SUF>
if("register".equals(type)) {
session.setAttribute("webRegisterVerifyCode", code);
} else if("editPassword".equals(type)) {
session.setAttribute("webEditPassVerifyCode", code);
}
// 利用Hutool封装的邮箱工具类发送邮件
String send = MailUtil.send(mailAccount, CollectionUtil.newArrayList(userEmail),
"您正在注册果蔬超市账户……", "打死都不要告诉别人!!验证码是:" +
"<span style='color:#1E9FFF;font-size:16px;font-weight:800;'>" +
code + "</span>", true);
System.out.println("邮件发送结果:" + send);
return new ResultMessage(0, "邮件已发送!请查收");
} catch (Exception e) {
e.printStackTrace();
return new ResultMessage(500, "出现异常:" + e.getMessage());
}
}
}
| 0 | 625 | 13 | 733 | 12 | 740 | 11 | 733 | 12 | 984 | 24 | false | false | false | false | false | true |
43767_3 | package controllers.admin;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import models.mag_article;
import models.mag_banner;
import models.mag_works;
import models.mag_worksclass;
import play.Play;
import play.libs.Files;
import play.mvc.Controller;
import com.alibaba.fastjson.JSON;
public class Banner extends Controller{
public static void allBanner(){
mag_banner banner = new mag_banner();
renderJSON("{\"data\":"+banner.allBanner()+"}");
}
public static void addBanner(String title,String remark,File image,String artclass ,String ardid){
System.out.println(title);
System.out.println(remark);
System.out.println(image);
System.out.println(artclass);
System.out.println(ardid);
//文件保存目录路径
String savePath = Play.applicationPath.toString()+Play.configuration.getProperty("newsImg.savePath", "/public/upload/");
//文件保存目录URL
String saveUrl = Play.configuration.getProperty("newsImg.savePath", "/public/upload/");
if (image != null) {
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
renderJSON("{\"state\":\"上传目录不存在。\"}");
return;
}
//检查目录写权限
if(!uploadDir.canWrite()){
renderJSON("{\"state\":\"上传目录没有写权限。\"}");
return;
}
String ymd = "banner";
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
//检查扩展名
String fileExt = image.getName().substring(image.getName().lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
File f = new File(savePath,newFileName);
try {
Files.copy(image,f);
System.out.println(saveUrl + newFileName);
java.text.DateFormat format1 = new java.text.SimpleDateFormat(
"yyyy-MM-dd hh:mm");
String timeStr = format1.format(new Date()).toString();
if(artclass == "作品"){
mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "作品");
banner.save();
}else{
mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "文章");
banner.save();
}
renderJSON("{\"state\":\"操作成功\"}");
} catch (Exception e) {
e.printStackTrace();
renderJSON("{\"state\":\"上传失败\"}");
}
}else{
renderJSON("{\"state\":\"请选择文件。\"}");
}
renderJSON("{\"status\":\"操作成功\"}");
}
public static void getBanner(){
}
public static void delBanner(){
}
public static void allBannerList(){
List<mag_article> artlist = mag_article.find("order by id desc").fetch();
List<mag_works> worklist = mag_works.find("order by id desc").fetch();
String artStr = JSON.toJSONString(artlist);
String worksStr = JSON.toJSONString(worklist);
renderJSON("{\"artlist\":"+artStr+",\"worklist\":"+worksStr+"}");
}
}
| DreamCoord/DreamCMS | app/controllers/admin/Banner.java | 959 | //检查目录写权限 | line_comment | zh-cn | package controllers.admin;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import models.mag_article;
import models.mag_banner;
import models.mag_works;
import models.mag_worksclass;
import play.Play;
import play.libs.Files;
import play.mvc.Controller;
import com.alibaba.fastjson.JSON;
public class Banner extends Controller{
public static void allBanner(){
mag_banner banner = new mag_banner();
renderJSON("{\"data\":"+banner.allBanner()+"}");
}
public static void addBanner(String title,String remark,File image,String artclass ,String ardid){
System.out.println(title);
System.out.println(remark);
System.out.println(image);
System.out.println(artclass);
System.out.println(ardid);
//文件保存目录路径
String savePath = Play.applicationPath.toString()+Play.configuration.getProperty("newsImg.savePath", "/public/upload/");
//文件保存目录URL
String saveUrl = Play.configuration.getProperty("newsImg.savePath", "/public/upload/");
if (image != null) {
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
renderJSON("{\"state\":\"上传目录不存在。\"}");
return;
}
//检查 <SUF>
if(!uploadDir.canWrite()){
renderJSON("{\"state\":\"上传目录没有写权限。\"}");
return;
}
String ymd = "banner";
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
//检查扩展名
String fileExt = image.getName().substring(image.getName().lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
File f = new File(savePath,newFileName);
try {
Files.copy(image,f);
System.out.println(saveUrl + newFileName);
java.text.DateFormat format1 = new java.text.SimpleDateFormat(
"yyyy-MM-dd hh:mm");
String timeStr = format1.format(new Date()).toString();
if(artclass == "作品"){
mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "作品");
banner.save();
}else{
mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "文章");
banner.save();
}
renderJSON("{\"state\":\"操作成功\"}");
} catch (Exception e) {
e.printStackTrace();
renderJSON("{\"state\":\"上传失败\"}");
}
}else{
renderJSON("{\"state\":\"请选择文件。\"}");
}
renderJSON("{\"status\":\"操作成功\"}");
}
public static void getBanner(){
}
public static void delBanner(){
}
public static void allBannerList(){
List<mag_article> artlist = mag_article.find("order by id desc").fetch();
List<mag_works> worklist = mag_works.find("order by id desc").fetch();
String artStr = JSON.toJSONString(artlist);
String worksStr = JSON.toJSONString(worklist);
renderJSON("{\"artlist\":"+artStr+",\"worklist\":"+worksStr+"}");
}
}
| 0 | 773 | 5 | 959 | 5 | 970 | 5 | 959 | 5 | 1,252 | 12 | false | false | false | false | false | true |
36160_53 | package cwp.moneycharge.dao;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.cwp.cmoneycharge.R;
import java.util.ArrayList;
import java.util.List;
import cwp.moneycharge.model.Tb_ptype;
//收入类型的数据库
public class PtypeDAO {
// (_id INTEGER NOT NULL PRIMARY KEY,no not null integer ,typename
// varchar(50)
private DBOpenHelper helper;// 创建DBOpenHelper对象
private SQLiteDatabase db;// 创建SQLiteDatabase对象
int[] imageId = new int[] { R.drawable.icon_spjs_zwwc,
R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc,
R.drawable.icon_spjs_zwwc, R.drawable.icon_jjwy_rcyp,
R.drawable.icon_xxyl_wg, R.drawable.icon_yfsp,
R.drawable.icon_rqwl_slqk, R.drawable.icon_jltx_sjf,
R.drawable.icon_spjs, R.drawable.icon_jrbx_ajhk,
R.drawable.icon_jrbx, R.drawable.icon_xcjt_dczc,
R.drawable.icon_qtzx, R.drawable.icon_jrbx_lxzc, R.drawable.yysb };
public PtypeDAO(Context context) {
// TODO Auto-generated constructor stub
helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象
}
/**
* 新增收入类型
*
* @param tb_ptype
*/
public void add(Tb_ptype tb_ptype) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL(
"insert into tb_ptype (_id,no,typename) values (?,?,?)",
new Object[] { tb_ptype.get_id(), tb_ptype.getNo(),
tb_ptype.getTypename() });// 执行添加支出类型操作
}
/**
* 修改收入类型
*
* @param tb_ptype
*/
public void modify(Tb_ptype tb_ptype) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL(
"update Tb_ptype set typename = ? where _id = ? and no=?",
new Object[] { tb_ptype.get_id(), tb_ptype.getNo(),
tb_ptype.getTypename() });// 执行修改支出类型操作
}
public void modifyByName(int id, String old, String now) {
db = helper.getWritableDatabase();
db.execSQL(
"update Tb_ptype set typename = ? where _id = ? and typename=?",
new Object[] { id, now, old });// 执行修改收入类型操作
}
/**
* 删除收入类型
*
* @param ids
*/
public void delete(Integer... ids) {
if (ids.length > 0)// 判断是否存在要删除的id
{
StringBuffer sb = new StringBuffer();// 创建StringBuffer对象
for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合
{
sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中
}
sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id in (?) and no in (" + sb
+ ")", (Object[]) ids);
}
}
public void deleteByName(int id, String typename) {
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id =? and typename=?",
new Object[] { id, typename });
}
public void deleteById(int id) {
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id =? ", new Object[] { id });
}
/**
* 获取收入类型信息
*
* @param start
* 起始位置
* @param count
* 每页显示数量
* @return
*/
public List<Tb_ptype> getScrollData(int id, int start, int count) {
List<Tb_ptype> lisTb_ptype = new ArrayList<Tb_ptype>();// 创建集合对象
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
// 获取所有便签信息
Cursor cursor = db.rawQuery(
"select * from tb_ptype where _id=? order by no limit ?,?",
new String[] { String.valueOf(id), String.valueOf(start),
String.valueOf(count) });
while (cursor.moveToNext())// 遍历所有的便签信息
{
// 将遍历到的便签信息添加到集合中
lisTb_ptype.add(new Tb_ptype(cursor.getInt(cursor
.getColumnIndex("_id")), cursor.getInt(cursor
.getColumnIndex("no")), cursor.getString(cursor
.getColumnIndex("typename"))));
}
return lisTb_ptype;// 返回集合
}
/**
* 获取总记录数
*
* @return
*/
public long getCount() {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery("select count(no) from tb_ptype", null);// 获取支出类型的记录数
if (cursor.moveToNext())// 判断Cursor中是否有数据
{
return cursor.getLong(0);// 返回总记录数
}
return 0;// 如果没有数据,则返回0
}
public long getCount(int id) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select count(no) from tb_ptype where _id=?",
new String[] { String.valueOf(id) });// 获取收入信息的记录数
if (cursor.moveToNext())// 判断Cursor中是否有数据
{
return cursor.getLong(0);// 返回总记录数
}
return 0;// 如果没有数据,则返回0
}
/**
* 获取便签最大编号
*
* @return
*/
public int getMaxId() {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery("select max(no) from tb_ptype", null);// 获取收入类型表中的最大编号
while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据
return cursor.getInt(0);// 获取访问到的数据,即最大编号
}
return 0;// 如果没有数据,则返回0
}
/**
* 获取类型名数组 param id
*
* @return
* */
public List<String> getPtypeName(int id) {
List<String> lisCharSequence = new ArrayList<String>();// 创建集合对象
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select typename from tb_ptype where _id=?",
new String[] { String.valueOf(id) });// 获取收入类型表中的最大编号
while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据
lisCharSequence.add(cursor.getString(cursor
.getColumnIndex("typename")));
}
return lisCharSequence;// 如果没有数据,则返回0
}
public String getOneName(int id, int no) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select typename from tb_ptype where _id=? and no=?",
new String[] { String.valueOf(id), String.valueOf(no) });
if (cursor.moveToNext()) {
return cursor.getString(cursor.getColumnIndex("typename"));
}
return "";
}
public int getOneImg(int id, int no) {
if (imageId.length < no) {
return imageId[14];
}
return imageId[no - 1];
}
public void initData(int id) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL("delete from tb_ptype where _id=?",
new String[] { String.valueOf(id) }); // 确保无该id
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "1", "早餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "2", "午餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "3", "晚餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "4", "夜宵" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "5", "生活用品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "6", "工作用品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "7", "衣服" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "8", "应酬" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "9", "电子产品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "10", "食品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "11", "租金" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "12", "股票" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "13", "打的" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "14", "基金" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "15", "其他" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "16", "语音识别" });
}
}
| Dreamer206602/QuickMoney | app/src/main/java/cwp/moneycharge/dao/PtypeDAO.java | 2,796 | // 获取收入类型表中的最大编号 | line_comment | zh-cn | package cwp.moneycharge.dao;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.cwp.cmoneycharge.R;
import java.util.ArrayList;
import java.util.List;
import cwp.moneycharge.model.Tb_ptype;
//收入类型的数据库
public class PtypeDAO {
// (_id INTEGER NOT NULL PRIMARY KEY,no not null integer ,typename
// varchar(50)
private DBOpenHelper helper;// 创建DBOpenHelper对象
private SQLiteDatabase db;// 创建SQLiteDatabase对象
int[] imageId = new int[] { R.drawable.icon_spjs_zwwc,
R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc,
R.drawable.icon_spjs_zwwc, R.drawable.icon_jjwy_rcyp,
R.drawable.icon_xxyl_wg, R.drawable.icon_yfsp,
R.drawable.icon_rqwl_slqk, R.drawable.icon_jltx_sjf,
R.drawable.icon_spjs, R.drawable.icon_jrbx_ajhk,
R.drawable.icon_jrbx, R.drawable.icon_xcjt_dczc,
R.drawable.icon_qtzx, R.drawable.icon_jrbx_lxzc, R.drawable.yysb };
public PtypeDAO(Context context) {
// TODO Auto-generated constructor stub
helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象
}
/**
* 新增收入类型
*
* @param tb_ptype
*/
public void add(Tb_ptype tb_ptype) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL(
"insert into tb_ptype (_id,no,typename) values (?,?,?)",
new Object[] { tb_ptype.get_id(), tb_ptype.getNo(),
tb_ptype.getTypename() });// 执行添加支出类型操作
}
/**
* 修改收入类型
*
* @param tb_ptype
*/
public void modify(Tb_ptype tb_ptype) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL(
"update Tb_ptype set typename = ? where _id = ? and no=?",
new Object[] { tb_ptype.get_id(), tb_ptype.getNo(),
tb_ptype.getTypename() });// 执行修改支出类型操作
}
public void modifyByName(int id, String old, String now) {
db = helper.getWritableDatabase();
db.execSQL(
"update Tb_ptype set typename = ? where _id = ? and typename=?",
new Object[] { id, now, old });// 执行修改收入类型操作
}
/**
* 删除收入类型
*
* @param ids
*/
public void delete(Integer... ids) {
if (ids.length > 0)// 判断是否存在要删除的id
{
StringBuffer sb = new StringBuffer();// 创建StringBuffer对象
for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合
{
sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中
}
sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id in (?) and no in (" + sb
+ ")", (Object[]) ids);
}
}
public void deleteByName(int id, String typename) {
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id =? and typename=?",
new Object[] { id, typename });
}
public void deleteById(int id) {
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id =? ", new Object[] { id });
}
/**
* 获取收入类型信息
*
* @param start
* 起始位置
* @param count
* 每页显示数量
* @return
*/
public List<Tb_ptype> getScrollData(int id, int start, int count) {
List<Tb_ptype> lisTb_ptype = new ArrayList<Tb_ptype>();// 创建集合对象
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
// 获取所有便签信息
Cursor cursor = db.rawQuery(
"select * from tb_ptype where _id=? order by no limit ?,?",
new String[] { String.valueOf(id), String.valueOf(start),
String.valueOf(count) });
while (cursor.moveToNext())// 遍历所有的便签信息
{
// 将遍历到的便签信息添加到集合中
lisTb_ptype.add(new Tb_ptype(cursor.getInt(cursor
.getColumnIndex("_id")), cursor.getInt(cursor
.getColumnIndex("no")), cursor.getString(cursor
.getColumnIndex("typename"))));
}
return lisTb_ptype;// 返回集合
}
/**
* 获取总记录数
*
* @return
*/
public long getCount() {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery("select count(no) from tb_ptype", null);// 获取支出类型的记录数
if (cursor.moveToNext())// 判断Cursor中是否有数据
{
return cursor.getLong(0);// 返回总记录数
}
return 0;// 如果没有数据,则返回0
}
public long getCount(int id) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select count(no) from tb_ptype where _id=?",
new String[] { String.valueOf(id) });// 获取收入信息的记录数
if (cursor.moveToNext())// 判断Cursor中是否有数据
{
return cursor.getLong(0);// 返回总记录数
}
return 0;// 如果没有数据,则返回0
}
/**
* 获取便签最大编号
*
* @return
*/
public int getMaxId() {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery("select max(no) from tb_ptype", null);// 获取收入类型表中的最大编号
while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据
return cursor.getInt(0);// 获取访问到的数据,即最大编号
}
return 0;// 如果没有数据,则返回0
}
/**
* 获取类型名数组 param id
*
* @return
* */
public List<String> getPtypeName(int id) {
List<String> lisCharSequence = new ArrayList<String>();// 创建集合对象
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select typename from tb_ptype where _id=?",
new String[] { String.valueOf(id) });// 获取 <SUF>
while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据
lisCharSequence.add(cursor.getString(cursor
.getColumnIndex("typename")));
}
return lisCharSequence;// 如果没有数据,则返回0
}
public String getOneName(int id, int no) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select typename from tb_ptype where _id=? and no=?",
new String[] { String.valueOf(id), String.valueOf(no) });
if (cursor.moveToNext()) {
return cursor.getString(cursor.getColumnIndex("typename"));
}
return "";
}
public int getOneImg(int id, int no) {
if (imageId.length < no) {
return imageId[14];
}
return imageId[no - 1];
}
public void initData(int id) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL("delete from tb_ptype where _id=?",
new String[] { String.valueOf(id) }); // 确保无该id
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "1", "早餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "2", "午餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "3", "晚餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "4", "夜宵" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "5", "生活用品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "6", "工作用品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "7", "衣服" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "8", "应酬" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "9", "电子产品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "10", "食品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "11", "租金" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "12", "股票" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "13", "打的" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "14", "基金" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "15", "其他" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "16", "语音识别" });
}
}
| 0 | 2,374 | 8 | 2,796 | 9 | 2,756 | 8 | 2,796 | 9 | 3,683 | 15 | false | false | false | false | false | true |
34101_19 |
package net.paoding.analysis;
import java.io.StringReader;
import junit.framework.TestCase;
import net.paoding.analysis.analyzer.PaodingAnalyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
public class AnalyzerTest extends TestCase {
protected PaodingAnalyzer analyzer = new PaodingAnalyzer();
protected StringBuilder sb = new StringBuilder();
protected String dissect(String input) {
try {
TokenStream ts = analyzer.tokenStream("", new StringReader(input));
Token token;
sb.setLength(0);
while ((token = ts.next()) != null) {
sb.append(token.termText()).append('/');
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
/**
*
*/
public void test000() {
String result = dissect("a");
assertEquals("", result);
}
/**
*
*/
public void test001() {
String result = dissect("空格 a 空格");
assertEquals("空格/空格", result);
}
/**
*
*/
public void test002() {
String result = dissect("A座");
assertEquals("a座", result);
}
/**
*
*/
public void test003() {
String result = dissect("u盘");
assertEquals("u盘", result);
}
public void test004() {
String result = dissect("刚买的u盘的容量");
assertEquals("刚/买的/u盘/容量", result);
}
public void test005() {
String result = dissect("K歌之王很好听");
assertEquals("k歌之王/很好/好听", result);
}
// --------------------------------------------------------------
// 仅包含词语的句子分词策略
// --------------------------------------------------------------
/**
* 句子全由词典词语组成,但词语之间没有包含、交叉关系
*/
public void test100() {
String result = dissect("台北中文国际");
assertEquals("台北/中文/国际", result);
}
/**
* 句子全由词典词语组成,但词语之间有包含关系
*/
public void test101() {
String result = dissect("北京首都机场");
assertEquals("北京/首都/机场", result);
}
/**
* 句子全由词典词语组成,但词语之间有交叉关系
*/
public void test102() {
String result = dissect("东西已经拍卖了");
assertEquals("东西/已经/拍卖/卖了", result);
}
/**
* 句子全由词典词语组成,但词语之间有包含、交叉等复杂关系
*/
public void test103() {
String result = dissect("羽毛球拍");
assertEquals("羽毛/羽毛球/球拍", result);
}
// --------------------------------------------------------------
// noise词汇和单字的分词策略
// --------------------------------------------------------------
/**
* 词语之间有一个noise字(的)
*/
public void test200() {
String result = dissect("足球的魅力");
assertEquals("足球/魅力", result);
}
/**
* 词语之间有一个noise词语(因之)
*/
public void test201() {
String result = dissect("主人因之生气");
assertEquals("主人/生气", result);
}
/**
* 词语前后分别有单字和双字的noise词语(与,有关)
*/
public void test202() {
String result = dissect("与谋杀有关");
assertEquals("谋杀", result);
}
/**
* 前有noise词语(哪怕),后面跟随了连续的noise单字(了,你)
*/
public void test203() {
String result = dissect("哪怕朋友背叛了你");
assertEquals("朋友/背叛", result);
}
/**
* 前后连续的noise词汇(虽然,某些),词语中有noise单字(很)
*/
public void test204() {
String result = dissect("虽然某些动物很凶恶");
assertEquals("动物/凶恶", result);
}
// --------------------------------------------------------------
// 词典没有收录的字符串的分词策略
// --------------------------------------------------------------
/**
* 仅1个字的非词汇串(东,西,南,北)
*/
public void test300() {
String result = dissect("东&&西&&南&&北");
assertEquals("东/西/南/北", result);
}
/**
* 仅两个字的非词汇串(古哥,谷歌,收狗,搜狗)
*/
public void test302() {
String result = dissect("古哥&&谷歌&&收狗&&搜狗");
assertEquals("古哥/谷歌/收狗/搜狗", result);
}
/**
* 多个字的非词汇串
*/
public void test303() {
String result = dissect("这是鸟语:玉鱼遇欲雨");
assertEquals("这是/鸟语/玉鱼/鱼遇/遇欲/欲雨", result);
}
/**
* 两个词语之间有一个非词汇的字(真)
*/
public void test304() {
String result = dissect("朋友真背叛了你了!");
assertEquals("朋友/真/背叛", result);
}
/**
* 两个词语之间有一个非词汇的字符串(盒蟹)
*/
public void test305() {
String result = dissect("建设盒蟹社会");
assertEquals("建设/盒蟹/社会", result);
}
/**
* 两个词语之间有多个非词汇的字符串(盒少蟹)
*/
public void test306() {
String result = dissect("建设盒少蟹社会");
assertEquals("建设/盒少/少蟹/社会", result);
}
// --------------------------------------------------------------
// 不包含小数点的汉字数字
// --------------------------------------------------------------
/**
* 单个汉字数字
*/
public void test400() {
String result = dissect("二");
assertEquals("2", result);
}
/**
* 两个汉字数字
*/
public void test61() {
String result = dissect("五六");
assertEquals("56", result);
}
/**
* 多个汉字数字
*/
public void test62() {
String result = dissect("三四五六");
assertEquals("3456", result);
}
/**
* 十三
*/
public void test63() {
String result = dissect("十三");
assertEquals("13", result);
}
/**
* 二千
*/
public void test65() {
String result = dissect("二千");
assertEquals("2000", result);
}
/**
* 两千
*/
public void test651() {
String result = dissect("两千");
assertEquals("2000", result);
}
/**
* 两千
*/
public void test6511() {
String result = dissect("两千个");
assertEquals("2000/个", result);
}
/**
* 2千
*/
public void test652() {
String result = dissect("2千");
assertEquals("2000", result);
}
/**
*
*/
public void test653() {
String result = dissect("3千万");
assertEquals("30000000", result);
}
/**
*
*/
public void test654() {
String result = dissect("3千万个案例");
assertEquals("30000000/个/案例", result);
}
/**
*
*/
public void test64() {
String result = dissect("千万");
assertEquals("千万", result);
}
public void test66() {
String result = dissect("两两");
assertEquals("两两", result);
}
public void test67() {
String result = dissect("二二");
assertEquals("22", result);
}
public void test68() {
String result = dissect("2.2两");
assertEquals("2.2/两", result);
}
public void test69() {
String result = dissect("二两");
assertEquals("2/两", result);
}
public void test690() {
String result = dissect("2两");
assertEquals("2/两", result);
}
public void test691() {
String result = dissect("2千克");
assertEquals("2000/克", result);
}
public void test692() {
String result = dissect("2公斤");
assertEquals("2/公斤", result);
}
public void test693() {
String result = dissect("2世纪");
assertEquals("2/世纪", result);
}
public void test7() {
String result = dissect("哪怕二");
assertEquals("2", result);
}
} | DrizztLei/code | work/java/ROBOT/src/net/paoding/analysis/AnalyzerTest.java | 2,518 | /**
* 仅两个字的非词汇串(古哥,谷歌,收狗,搜狗)
*/ | block_comment | zh-cn |
package net.paoding.analysis;
import java.io.StringReader;
import junit.framework.TestCase;
import net.paoding.analysis.analyzer.PaodingAnalyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
public class AnalyzerTest extends TestCase {
protected PaodingAnalyzer analyzer = new PaodingAnalyzer();
protected StringBuilder sb = new StringBuilder();
protected String dissect(String input) {
try {
TokenStream ts = analyzer.tokenStream("", new StringReader(input));
Token token;
sb.setLength(0);
while ((token = ts.next()) != null) {
sb.append(token.termText()).append('/');
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
/**
*
*/
public void test000() {
String result = dissect("a");
assertEquals("", result);
}
/**
*
*/
public void test001() {
String result = dissect("空格 a 空格");
assertEquals("空格/空格", result);
}
/**
*
*/
public void test002() {
String result = dissect("A座");
assertEquals("a座", result);
}
/**
*
*/
public void test003() {
String result = dissect("u盘");
assertEquals("u盘", result);
}
public void test004() {
String result = dissect("刚买的u盘的容量");
assertEquals("刚/买的/u盘/容量", result);
}
public void test005() {
String result = dissect("K歌之王很好听");
assertEquals("k歌之王/很好/好听", result);
}
// --------------------------------------------------------------
// 仅包含词语的句子分词策略
// --------------------------------------------------------------
/**
* 句子全由词典词语组成,但词语之间没有包含、交叉关系
*/
public void test100() {
String result = dissect("台北中文国际");
assertEquals("台北/中文/国际", result);
}
/**
* 句子全由词典词语组成,但词语之间有包含关系
*/
public void test101() {
String result = dissect("北京首都机场");
assertEquals("北京/首都/机场", result);
}
/**
* 句子全由词典词语组成,但词语之间有交叉关系
*/
public void test102() {
String result = dissect("东西已经拍卖了");
assertEquals("东西/已经/拍卖/卖了", result);
}
/**
* 句子全由词典词语组成,但词语之间有包含、交叉等复杂关系
*/
public void test103() {
String result = dissect("羽毛球拍");
assertEquals("羽毛/羽毛球/球拍", result);
}
// --------------------------------------------------------------
// noise词汇和单字的分词策略
// --------------------------------------------------------------
/**
* 词语之间有一个noise字(的)
*/
public void test200() {
String result = dissect("足球的魅力");
assertEquals("足球/魅力", result);
}
/**
* 词语之间有一个noise词语(因之)
*/
public void test201() {
String result = dissect("主人因之生气");
assertEquals("主人/生气", result);
}
/**
* 词语前后分别有单字和双字的noise词语(与,有关)
*/
public void test202() {
String result = dissect("与谋杀有关");
assertEquals("谋杀", result);
}
/**
* 前有noise词语(哪怕),后面跟随了连续的noise单字(了,你)
*/
public void test203() {
String result = dissect("哪怕朋友背叛了你");
assertEquals("朋友/背叛", result);
}
/**
* 前后连续的noise词汇(虽然,某些),词语中有noise单字(很)
*/
public void test204() {
String result = dissect("虽然某些动物很凶恶");
assertEquals("动物/凶恶", result);
}
// --------------------------------------------------------------
// 词典没有收录的字符串的分词策略
// --------------------------------------------------------------
/**
* 仅1个字的非词汇串(东,西,南,北)
*/
public void test300() {
String result = dissect("东&&西&&南&&北");
assertEquals("东/西/南/北", result);
}
/**
* 仅两个 <SUF>*/
public void test302() {
String result = dissect("古哥&&谷歌&&收狗&&搜狗");
assertEquals("古哥/谷歌/收狗/搜狗", result);
}
/**
* 多个字的非词汇串
*/
public void test303() {
String result = dissect("这是鸟语:玉鱼遇欲雨");
assertEquals("这是/鸟语/玉鱼/鱼遇/遇欲/欲雨", result);
}
/**
* 两个词语之间有一个非词汇的字(真)
*/
public void test304() {
String result = dissect("朋友真背叛了你了!");
assertEquals("朋友/真/背叛", result);
}
/**
* 两个词语之间有一个非词汇的字符串(盒蟹)
*/
public void test305() {
String result = dissect("建设盒蟹社会");
assertEquals("建设/盒蟹/社会", result);
}
/**
* 两个词语之间有多个非词汇的字符串(盒少蟹)
*/
public void test306() {
String result = dissect("建设盒少蟹社会");
assertEquals("建设/盒少/少蟹/社会", result);
}
// --------------------------------------------------------------
// 不包含小数点的汉字数字
// --------------------------------------------------------------
/**
* 单个汉字数字
*/
public void test400() {
String result = dissect("二");
assertEquals("2", result);
}
/**
* 两个汉字数字
*/
public void test61() {
String result = dissect("五六");
assertEquals("56", result);
}
/**
* 多个汉字数字
*/
public void test62() {
String result = dissect("三四五六");
assertEquals("3456", result);
}
/**
* 十三
*/
public void test63() {
String result = dissect("十三");
assertEquals("13", result);
}
/**
* 二千
*/
public void test65() {
String result = dissect("二千");
assertEquals("2000", result);
}
/**
* 两千
*/
public void test651() {
String result = dissect("两千");
assertEquals("2000", result);
}
/**
* 两千
*/
public void test6511() {
String result = dissect("两千个");
assertEquals("2000/个", result);
}
/**
* 2千
*/
public void test652() {
String result = dissect("2千");
assertEquals("2000", result);
}
/**
*
*/
public void test653() {
String result = dissect("3千万");
assertEquals("30000000", result);
}
/**
*
*/
public void test654() {
String result = dissect("3千万个案例");
assertEquals("30000000/个/案例", result);
}
/**
*
*/
public void test64() {
String result = dissect("千万");
assertEquals("千万", result);
}
public void test66() {
String result = dissect("两两");
assertEquals("两两", result);
}
public void test67() {
String result = dissect("二二");
assertEquals("22", result);
}
public void test68() {
String result = dissect("2.2两");
assertEquals("2.2/两", result);
}
public void test69() {
String result = dissect("二两");
assertEquals("2/两", result);
}
public void test690() {
String result = dissect("2两");
assertEquals("2/两", result);
}
public void test691() {
String result = dissect("2千克");
assertEquals("2000/克", result);
}
public void test692() {
String result = dissect("2公斤");
assertEquals("2/公斤", result);
}
public void test693() {
String result = dissect("2世纪");
assertEquals("2/世纪", result);
}
public void test7() {
String result = dissect("哪怕二");
assertEquals("2", result);
}
} | 0 | 1,982 | 25 | 2,515 | 33 | 2,355 | 27 | 2,515 | 33 | 3,181 | 44 | false | false | false | false | false | true |
13765_40 | package com.d.greendao;
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;
/**
* GreenDaoGenerator
* Created by D on 2017/4/27.
*/
public class GreenDaoGenerator {
public static void main(String[] args) throws Exception {
// 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。
// 两个参数分别代表:数据库版本号与自动生成代码的包路径。
// Schema schema = new Schema(1, "com.d.music.data.database.greendao.music");
// 当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示:
Schema schema = new Schema(1, "com.d.music.data.database.greendao.bean");
schema.setDefaultJavaPackageDao("com.d.music.data.database.greendao.dao");
// 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。
// schema2.enableActiveEntitiesByDefault();
// schema2.enableKeepSectionsByDefault();
// 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。
addMusic(schema);
addLocalAllMusic(schema);
addCollectionMusic(schema);
addCustomList(schema);
addCustomMusics(schema);
addTransferModel(schema);
// 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录。
// 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。
// 重新运行GreenDaoGenerator时,将此路径更改为本地src路径
new DaoGenerator().generateAll(schema, "D:\\AndroidStudioProjects\\DMusic\\app\\src\\main\\java");
}
/**
* Music - 歌曲
*/
private static void addMusic(Schema schema) {
Entity entity = schema.addEntity("MusicModel"); // 表名
addProperty(entity);
}
/**
* LocalAllMusic - 本地歌曲
*/
private static void addLocalAllMusic(Schema schema) {
Entity entity = schema.addEntity("LocalAllMusic"); // 表名
addProperty(entity);
}
/**
* CollectionMusic - 收藏歌曲
*/
private static void addCollectionMusic(Schema schema) {
Entity entity = schema.addEntity("CollectionMusic"); // 表名
addProperty(entity);
}
/**
* CustomList - 自定义列表
*/
private static void addCustomList(Schema schema) {
Entity entity = schema.addEntity("CustomListModel"); // 表名
entity.addIdProperty().autoincrement(); // id主键自增
entity.addStringProperty("name"); // 歌曲列表名
entity.addLongProperty("count"); // 包含歌曲数
entity.addIntProperty("seq"); // 排序显示序号
entity.addIntProperty("sortType"); // 排序方式(1:按名称排序,2:按时间排序,3:自定义排序)
entity.addIntProperty("pointer"); // 指针:指向数据库相应表
}
/**
* CustomMusic - 自定义歌曲(创建20张)
*/
private static void addCustomMusics(Schema schema) {
for (int i = 0; i < 20; i++) {
Entity entity = schema.addEntity("CustomMusic" + i); // 表名
addProperty(entity);
}
}
/**
* TransferModel - 传输
*/
private static void addTransferModel(Schema schema) {
Entity entity = schema.addEntity("TransferModel"); // 表名
entity.addStringProperty("transferId").primaryKey(); // 文件完整路径---主键
entity.addIntProperty("transferType");
entity.addIntProperty("transferState");
entity.addLongProperty("transferCurrentLength");
entity.addLongProperty("transferTotalLength");
entity.addStringProperty("id"); // 文件完整路径
entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等
entity.addIntProperty("seq"); // 自定义序号
entity.addStringProperty("songId"); // 歌曲ID
entity.addStringProperty("songName"); // 歌曲名
entity.addStringProperty("songUrl"); // 歌曲url
entity.addStringProperty("artistId"); // 艺术家ID
entity.addStringProperty("artistName"); // 歌手名
entity.addStringProperty("albumId"); // 专辑ID
entity.addStringProperty("albumName"); // 专辑
entity.addStringProperty("albumUrl"); // 专辑url
entity.addStringProperty("lrcName"); // 歌词名称
entity.addStringProperty("lrcUrl"); // 歌词路径
entity.addLongProperty("fileDuration"); // 歌曲时长
entity.addLongProperty("fileSize"); // 文件大小
entity.addStringProperty("filePostfix"); // 文件后缀类型
entity.addStringProperty("fileFolder"); // 父文件夹绝对路径
entity.addBooleanProperty("isCollected"); // 是否收藏
entity.addLongProperty("timeStamp"); // 时间戳,插入时间
}
/**
* 添加公共字段
*/
private static void addProperty(Entity entity) {
entity.addStringProperty("id").primaryKey(); // 文件完整路径---主键
entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等
entity.addIntProperty("seq"); // 自定义序号
entity.addStringProperty("songId"); // 歌曲ID
entity.addStringProperty("songName"); // 歌曲名
entity.addStringProperty("songUrl"); // 歌曲url
entity.addStringProperty("artistId"); // 艺术家ID
entity.addStringProperty("artistName"); // 歌手名
entity.addStringProperty("albumId"); // 专辑ID
entity.addStringProperty("albumName"); // 专辑
entity.addStringProperty("albumUrl"); // 专辑url
entity.addStringProperty("lrcName"); // 歌词名称
entity.addStringProperty("lrcUrl"); // 歌词路径
entity.addLongProperty("fileDuration"); // 歌曲时长
entity.addLongProperty("fileSize"); // 文件大小
entity.addStringProperty("filePostfix"); // 文件后缀类型
entity.addStringProperty("fileFolder"); // 父文件夹绝对路径
entity.addBooleanProperty("isCollected"); // 是否收藏
entity.addLongProperty("timeStamp"); // 时间戳,插入时间
}
}
| Dsiner/DMusic | lib_greendao_generator/src/main/java/com/d/greendao/GreenDaoGenerator.java | 1,588 | // 父文件夹绝对路径 | line_comment | zh-cn | package com.d.greendao;
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;
/**
* GreenDaoGenerator
* Created by D on 2017/4/27.
*/
public class GreenDaoGenerator {
public static void main(String[] args) throws Exception {
// 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。
// 两个参数分别代表:数据库版本号与自动生成代码的包路径。
// Schema schema = new Schema(1, "com.d.music.data.database.greendao.music");
// 当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示:
Schema schema = new Schema(1, "com.d.music.data.database.greendao.bean");
schema.setDefaultJavaPackageDao("com.d.music.data.database.greendao.dao");
// 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。
// schema2.enableActiveEntitiesByDefault();
// schema2.enableKeepSectionsByDefault();
// 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。
addMusic(schema);
addLocalAllMusic(schema);
addCollectionMusic(schema);
addCustomList(schema);
addCustomMusics(schema);
addTransferModel(schema);
// 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录。
// 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。
// 重新运行GreenDaoGenerator时,将此路径更改为本地src路径
new DaoGenerator().generateAll(schema, "D:\\AndroidStudioProjects\\DMusic\\app\\src\\main\\java");
}
/**
* Music - 歌曲
*/
private static void addMusic(Schema schema) {
Entity entity = schema.addEntity("MusicModel"); // 表名
addProperty(entity);
}
/**
* LocalAllMusic - 本地歌曲
*/
private static void addLocalAllMusic(Schema schema) {
Entity entity = schema.addEntity("LocalAllMusic"); // 表名
addProperty(entity);
}
/**
* CollectionMusic - 收藏歌曲
*/
private static void addCollectionMusic(Schema schema) {
Entity entity = schema.addEntity("CollectionMusic"); // 表名
addProperty(entity);
}
/**
* CustomList - 自定义列表
*/
private static void addCustomList(Schema schema) {
Entity entity = schema.addEntity("CustomListModel"); // 表名
entity.addIdProperty().autoincrement(); // id主键自增
entity.addStringProperty("name"); // 歌曲列表名
entity.addLongProperty("count"); // 包含歌曲数
entity.addIntProperty("seq"); // 排序显示序号
entity.addIntProperty("sortType"); // 排序方式(1:按名称排序,2:按时间排序,3:自定义排序)
entity.addIntProperty("pointer"); // 指针:指向数据库相应表
}
/**
* CustomMusic - 自定义歌曲(创建20张)
*/
private static void addCustomMusics(Schema schema) {
for (int i = 0; i < 20; i++) {
Entity entity = schema.addEntity("CustomMusic" + i); // 表名
addProperty(entity);
}
}
/**
* TransferModel - 传输
*/
private static void addTransferModel(Schema schema) {
Entity entity = schema.addEntity("TransferModel"); // 表名
entity.addStringProperty("transferId").primaryKey(); // 文件完整路径---主键
entity.addIntProperty("transferType");
entity.addIntProperty("transferState");
entity.addLongProperty("transferCurrentLength");
entity.addLongProperty("transferTotalLength");
entity.addStringProperty("id"); // 文件完整路径
entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等
entity.addIntProperty("seq"); // 自定义序号
entity.addStringProperty("songId"); // 歌曲ID
entity.addStringProperty("songName"); // 歌曲名
entity.addStringProperty("songUrl"); // 歌曲url
entity.addStringProperty("artistId"); // 艺术家ID
entity.addStringProperty("artistName"); // 歌手名
entity.addStringProperty("albumId"); // 专辑ID
entity.addStringProperty("albumName"); // 专辑
entity.addStringProperty("albumUrl"); // 专辑url
entity.addStringProperty("lrcName"); // 歌词名称
entity.addStringProperty("lrcUrl"); // 歌词路径
entity.addLongProperty("fileDuration"); // 歌曲时长
entity.addLongProperty("fileSize"); // 文件大小
entity.addStringProperty("filePostfix"); // 文件后缀类型
entity.addStringProperty("fileFolder"); // 父文 <SUF>
entity.addBooleanProperty("isCollected"); // 是否收藏
entity.addLongProperty("timeStamp"); // 时间戳,插入时间
}
/**
* 添加公共字段
*/
private static void addProperty(Entity entity) {
entity.addStringProperty("id").primaryKey(); // 文件完整路径---主键
entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等
entity.addIntProperty("seq"); // 自定义序号
entity.addStringProperty("songId"); // 歌曲ID
entity.addStringProperty("songName"); // 歌曲名
entity.addStringProperty("songUrl"); // 歌曲url
entity.addStringProperty("artistId"); // 艺术家ID
entity.addStringProperty("artistName"); // 歌手名
entity.addStringProperty("albumId"); // 专辑ID
entity.addStringProperty("albumName"); // 专辑
entity.addStringProperty("albumUrl"); // 专辑url
entity.addStringProperty("lrcName"); // 歌词名称
entity.addStringProperty("lrcUrl"); // 歌词路径
entity.addLongProperty("fileDuration"); // 歌曲时长
entity.addLongProperty("fileSize"); // 文件大小
entity.addStringProperty("filePostfix"); // 文件后缀类型
entity.addStringProperty("fileFolder"); // 父文件夹绝对路径
entity.addBooleanProperty("isCollected"); // 是否收藏
entity.addLongProperty("timeStamp"); // 时间戳,插入时间
}
}
| 0 | 1,513 | 8 | 1,588 | 7 | 1,572 | 5 | 1,588 | 7 | 2,073 | 18 | false | false | false | false | false | true |
64189_9 | package xu.problem.mc;
import java.util.ArrayList;
import core.problem.Action;
import core.problem.Problem;
import core.problem.State;
public class McProblem extends Problem {
@Override
public State result(State parent, Action action) {
int m = ((McState) parent).getM();
int c = ((McState) parent).getC();
int m1 = ((McAction) action).getM();
int c1 = ((McAction) action).getC();
int d = ((McAction) action).getD();
if (d == 1) { //从左岸划到右岸
return new McState(m - m1, c - c1, 0).setSize(size); //左岸人数减少,船到了右岸
}
else { //从右岸划到左岸
return new McState(m + m1, c + c1, 1).setSize(size); //左岸人数增多,船到了左岸
}
}
@Override
public int stepCost(State parent, Action action) {
// TODO Auto-generated method stub
return 1;
}
@Override
public int heuristic(State state) {
// TODO Auto-generated method stub
McState s = (McState) state;
return s.heuristic();
}
//左右岸,船上的任意情况下,传教士野人个数分别为m和c时,是否安全
private boolean isSafe(int m, int c) {
return m == 0 || m >= c;
}
@Override
public ArrayList<Action> Actions(State state) {
// TODO Auto-generated method stub
ArrayList<Action> actions = new ArrayList<>();
int m = ((McState) state).getM();
int c = ((McState) state).getC();
int b = ((McState) state).getB(); //在左岸还是右岸?
//如果船在右岸,计算出右岸的人数
if (b == 0) {
m = size - m;
c = size - c;
}
for (int i = 0; i <= m; i++)
for (int j = 0; j <= c; j++) {
if (i + j > 0 && i + j <= k && isSafe(i, j) &&
isSafe(m - i, c - j) &&
isSafe(size - m + i, size - c + j))
{
McAction action = new McAction(i, j, b); //划船方向,从所在岸划向对岸
actions.add(action);
}
}
return actions;
}
//帮助自己检查是否正确的复写了父类中已有的方法
//告诉读代码的人,这是一个复写的方法
@Override
public void drawWorld() {
// TODO Auto-generated method stub
this.getInitialState().draw();
}
@Override
public void simulateResult(State parent, Action action) {
// TODO Auto-generated method stub
State child = result(parent, action);
action.draw();
child.draw();
}
public McProblem(McState initialState, McState goal, int size, int k) {
super(initialState, goal);
this.size = size;
this.k = k;
}
public McProblem(int size, int k) {
super(new McState(size, size, 1).setSize(size), new McState(0, 0, 0).setSize(size));
this.size = size;
this.k = k;
}
private int size; //传教士和野人的个数,问题的规模
private int k; //船上可载人数的上限
@Override
public boolean solvable() {
// TODO Auto-generated method stub
return true;
}
}
| Du-Sen-Lin/AI | Searching_student/src/xu/problem/mc/McProblem.java | 984 | //如果船在右岸,计算出右岸的人数 | line_comment | zh-cn | package xu.problem.mc;
import java.util.ArrayList;
import core.problem.Action;
import core.problem.Problem;
import core.problem.State;
public class McProblem extends Problem {
@Override
public State result(State parent, Action action) {
int m = ((McState) parent).getM();
int c = ((McState) parent).getC();
int m1 = ((McAction) action).getM();
int c1 = ((McAction) action).getC();
int d = ((McAction) action).getD();
if (d == 1) { //从左岸划到右岸
return new McState(m - m1, c - c1, 0).setSize(size); //左岸人数减少,船到了右岸
}
else { //从右岸划到左岸
return new McState(m + m1, c + c1, 1).setSize(size); //左岸人数增多,船到了左岸
}
}
@Override
public int stepCost(State parent, Action action) {
// TODO Auto-generated method stub
return 1;
}
@Override
public int heuristic(State state) {
// TODO Auto-generated method stub
McState s = (McState) state;
return s.heuristic();
}
//左右岸,船上的任意情况下,传教士野人个数分别为m和c时,是否安全
private boolean isSafe(int m, int c) {
return m == 0 || m >= c;
}
@Override
public ArrayList<Action> Actions(State state) {
// TODO Auto-generated method stub
ArrayList<Action> actions = new ArrayList<>();
int m = ((McState) state).getM();
int c = ((McState) state).getC();
int b = ((McState) state).getB(); //在左岸还是右岸?
//如果 <SUF>
if (b == 0) {
m = size - m;
c = size - c;
}
for (int i = 0; i <= m; i++)
for (int j = 0; j <= c; j++) {
if (i + j > 0 && i + j <= k && isSafe(i, j) &&
isSafe(m - i, c - j) &&
isSafe(size - m + i, size - c + j))
{
McAction action = new McAction(i, j, b); //划船方向,从所在岸划向对岸
actions.add(action);
}
}
return actions;
}
//帮助自己检查是否正确的复写了父类中已有的方法
//告诉读代码的人,这是一个复写的方法
@Override
public void drawWorld() {
// TODO Auto-generated method stub
this.getInitialState().draw();
}
@Override
public void simulateResult(State parent, Action action) {
// TODO Auto-generated method stub
State child = result(parent, action);
action.draw();
child.draw();
}
public McProblem(McState initialState, McState goal, int size, int k) {
super(initialState, goal);
this.size = size;
this.k = k;
}
public McProblem(int size, int k) {
super(new McState(size, size, 1).setSize(size), new McState(0, 0, 0).setSize(size));
this.size = size;
this.k = k;
}
private int size; //传教士和野人的个数,问题的规模
private int k; //船上可载人数的上限
@Override
public boolean solvable() {
// TODO Auto-generated method stub
return true;
}
}
| 0 | 844 | 13 | 983 | 16 | 971 | 13 | 984 | 16 | 1,209 | 22 | false | false | false | false | false | true |
669_2 | package cn.itcast_03;
import java.util.ArrayList;
import java.util.Collections;
/*
* 模拟斗地主洗牌和发牌
*
* 扑克牌:54
* 小王
* 大王
* 黑桃A,黑桃2,黑桃3,黑桃4,黑桃...,黑桃10,黑桃J,黑桃Q,黑桃K
* 红桃...
* 梅花...
* 方块...
*
* 分析:
* A:造一个牌盒(集合)
* B:造每一张牌,然后存储到牌盒里面去
* C:洗牌
* D:发牌
* E:看牌
*/
public class PokerDemo {
public static void main(String[] args) {
// 造一个牌盒(集合)
ArrayList<String> array = new ArrayList<String>();
// 造每一张牌,然后存储到牌盒里面去
// 定义花色数组
String[] colors = { "♠", "♥", "♣", "♦" };
// 定义点数数组
String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"J", "Q", "K" };
for (String color : colors) {
for (String number : numbers) {
array.add(color.concat(number));
}
}
array.add("小王");
array.add("大王");
// 看牌
// System.out.println(array);
// 洗牌
Collections.shuffle(array);
// 发牌
// 三个选手
ArrayList<String> linQingXia = new ArrayList<String>();
ArrayList<String> fengQingYang = new ArrayList<String>();
ArrayList<String> liuYi = new ArrayList<String>();
// 底牌
ArrayList<String> diPai = new ArrayList<String>();
for (int x = 0; x < array.size(); x++) {
if (x >= array.size() - 3) {
diPai.add(array.get(x));
} else if (x % 3 == 0) {
linQingXia.add(array.get(x));
} else if (x % 3 == 1) {
fengQingYang.add(array.get(x));
} else if (x % 3 == 2) {
liuYi.add(array.get(x));
}
}
// 看牌
lookPoker("林青霞", linQingXia);
lookPoker("风清扬", fengQingYang);
lookPoker("刘意", liuYi);
lookPoker("底牌", diPai);
}
// 写一个功能实现遍历
public static void lookPoker(String name, ArrayList<String> array) {
System.out.print(name + "的牌是:");
for (String s : array) {
System.out.print(s + " ");
}
System.out.println();
}
}
| DuGuQiuBai/Java | day18/code/day18_Collections/src/cn/itcast_03/PokerDemo.java | 813 | // 造每一张牌,然后存储到牌盒里面去 | line_comment | zh-cn | package cn.itcast_03;
import java.util.ArrayList;
import java.util.Collections;
/*
* 模拟斗地主洗牌和发牌
*
* 扑克牌:54
* 小王
* 大王
* 黑桃A,黑桃2,黑桃3,黑桃4,黑桃...,黑桃10,黑桃J,黑桃Q,黑桃K
* 红桃...
* 梅花...
* 方块...
*
* 分析:
* A:造一个牌盒(集合)
* B:造每一张牌,然后存储到牌盒里面去
* C:洗牌
* D:发牌
* E:看牌
*/
public class PokerDemo {
public static void main(String[] args) {
// 造一个牌盒(集合)
ArrayList<String> array = new ArrayList<String>();
// 造每 <SUF>
// 定义花色数组
String[] colors = { "♠", "♥", "♣", "♦" };
// 定义点数数组
String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"J", "Q", "K" };
for (String color : colors) {
for (String number : numbers) {
array.add(color.concat(number));
}
}
array.add("小王");
array.add("大王");
// 看牌
// System.out.println(array);
// 洗牌
Collections.shuffle(array);
// 发牌
// 三个选手
ArrayList<String> linQingXia = new ArrayList<String>();
ArrayList<String> fengQingYang = new ArrayList<String>();
ArrayList<String> liuYi = new ArrayList<String>();
// 底牌
ArrayList<String> diPai = new ArrayList<String>();
for (int x = 0; x < array.size(); x++) {
if (x >= array.size() - 3) {
diPai.add(array.get(x));
} else if (x % 3 == 0) {
linQingXia.add(array.get(x));
} else if (x % 3 == 1) {
fengQingYang.add(array.get(x));
} else if (x % 3 == 2) {
liuYi.add(array.get(x));
}
}
// 看牌
lookPoker("林青霞", linQingXia);
lookPoker("风清扬", fengQingYang);
lookPoker("刘意", liuYi);
lookPoker("底牌", diPai);
}
// 写一个功能实现遍历
public static void lookPoker(String name, ArrayList<String> array) {
System.out.print(name + "的牌是:");
for (String s : array) {
System.out.print(s + " ");
}
System.out.println();
}
}
| 0 | 710 | 14 | 813 | 16 | 747 | 13 | 813 | 16 | 1,025 | 26 | false | false | false | false | false | true |
51009_11 | package com.duan.musicoco.modle;
import android.provider.MediaStore;
/**
* Created by DuanJiaNing on 2017/5/24.
*/
final public class SongInfo implements MediaStore.Audio.AudioColumns {
//用于搜索、排序、分类
private String title_key;
private String artist_key;
private String album_key;
private int id;
//时间 ms
private long duration;
//艺术家
private String artist;
//所属专辑
private String album;
//专辑 ID
private String album_id;
//专辑图片路径
private String album_path;
//专辑录制时间
private long year;
//磁盘上的保存路径
//与服务端的 path 域对应,对于同一首歌曲(文件路径相同),两者应该相同
private String data;
//文件大小 bytes
private long size;
//显示的名字
private String display_name;
//内容标题
private String title;
//文件被加入媒体库的时间
private long date_added;
//文件最后修改时间
private long date_modified;
//MIME type
private String mime_type;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SongInfo songInfo = (SongInfo) o;
return data.equals(songInfo.data);
}
@Override
public int hashCode() {
return data.hashCode();
}
public void setAlbum_id(String album_id) {
this.album_id = album_id;
}
public void setAlbum_path(String album_path) {
this.album_path = album_path;
}
public void setTitle_key(String title_key) {
this.title_key = title_key;
}
public void setArtist_key(String artist_key) {
this.artist_key = artist_key;
}
public void setAlbum_key(String album_key) {
this.album_key = album_key;
}
public void setArtist(String artist) {
this.artist = artist;
}
public void setAlbum(String album) {
this.album = album;
}
public void setData(String data) {
this.data = data;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public void setTitle(String title) {
this.title = title;
}
public void setMime_type(String mime_type) {
this.mime_type = mime_type;
}
public void setYear(long year) {
this.year = year;
}
public void setDuration(long duration) {
this.duration = duration;
}
public void setSize(long size) {
this.size = size;
}
public void setDate_added(long date_added) {
this.date_added = date_added;
}
public void setDate_modified(long date_modified) {
this.date_modified = date_modified;
}
public String getTitle_key() {
return title_key;
}
public String getArtist_key() {
return artist_key;
}
public String getAlbum_key() {
return album_key;
}
public long getDuration() {
return duration;
}
public String getArtist() {
return artist;
}
public String getAlbum() {
return album;
}
public long getYear() {
return year;
}
public String getData() {
return data;
}
public long getSize() {
return size;
}
public String getDisplay_name() {
return display_name;
}
public String getTitle() {
return title;
}
public long getDate_added() {
return date_added;
}
public long getDate_modified() {
return date_modified;
}
public String getMime_type() {
return mime_type;
}
public String getAlbum_id() {
return album_id;
}
public String getAlbum_path() {
return album_path;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| DuanJiaNing/Musicoco | app/src/main/java/com/duan/musicoco/modle/SongInfo.java | 1,007 | //显示的名字 | line_comment | zh-cn | package com.duan.musicoco.modle;
import android.provider.MediaStore;
/**
* Created by DuanJiaNing on 2017/5/24.
*/
final public class SongInfo implements MediaStore.Audio.AudioColumns {
//用于搜索、排序、分类
private String title_key;
private String artist_key;
private String album_key;
private int id;
//时间 ms
private long duration;
//艺术家
private String artist;
//所属专辑
private String album;
//专辑 ID
private String album_id;
//专辑图片路径
private String album_path;
//专辑录制时间
private long year;
//磁盘上的保存路径
//与服务端的 path 域对应,对于同一首歌曲(文件路径相同),两者应该相同
private String data;
//文件大小 bytes
private long size;
//显示 <SUF>
private String display_name;
//内容标题
private String title;
//文件被加入媒体库的时间
private long date_added;
//文件最后修改时间
private long date_modified;
//MIME type
private String mime_type;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SongInfo songInfo = (SongInfo) o;
return data.equals(songInfo.data);
}
@Override
public int hashCode() {
return data.hashCode();
}
public void setAlbum_id(String album_id) {
this.album_id = album_id;
}
public void setAlbum_path(String album_path) {
this.album_path = album_path;
}
public void setTitle_key(String title_key) {
this.title_key = title_key;
}
public void setArtist_key(String artist_key) {
this.artist_key = artist_key;
}
public void setAlbum_key(String album_key) {
this.album_key = album_key;
}
public void setArtist(String artist) {
this.artist = artist;
}
public void setAlbum(String album) {
this.album = album;
}
public void setData(String data) {
this.data = data;
}
public void setDisplay_name(String display_name) {
this.display_name = display_name;
}
public void setTitle(String title) {
this.title = title;
}
public void setMime_type(String mime_type) {
this.mime_type = mime_type;
}
public void setYear(long year) {
this.year = year;
}
public void setDuration(long duration) {
this.duration = duration;
}
public void setSize(long size) {
this.size = size;
}
public void setDate_added(long date_added) {
this.date_added = date_added;
}
public void setDate_modified(long date_modified) {
this.date_modified = date_modified;
}
public String getTitle_key() {
return title_key;
}
public String getArtist_key() {
return artist_key;
}
public String getAlbum_key() {
return album_key;
}
public long getDuration() {
return duration;
}
public String getArtist() {
return artist;
}
public String getAlbum() {
return album;
}
public long getYear() {
return year;
}
public String getData() {
return data;
}
public long getSize() {
return size;
}
public String getDisplay_name() {
return display_name;
}
public String getTitle() {
return title;
}
public long getDate_added() {
return date_added;
}
public long getDate_modified() {
return date_modified;
}
public String getMime_type() {
return mime_type;
}
public String getAlbum_id() {
return album_id;
}
public String getAlbum_path() {
return album_path;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
| 0 | 885 | 3 | 1,007 | 4 | 1,122 | 3 | 1,007 | 4 | 1,317 | 6 | false | false | false | false | false | true |
11959_6 | package com.fuckwzxy.util;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fuckwzxy.bean.ApiInfo;
import com.fuckwzxy.bean.SignMessage;
import com.fuckwzxy.bean.UserInfo;
import com.fuckwzxy.common.ApiConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.sound.midi.Soundbank;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author wzh
* 2020/9/23 19:15
*/
@Component
@Slf4j
public class SendUtil {
@Async
public void sendCheckRequest(UserInfo userInfo, ApiInfo apiInfo, int seq) {
HttpRequest request = createHttpRequest(apiInfo,userInfo);
//body
request.body(apiInfo.getBody().replace("seq=3", "seq=" + seq));
//return body
request.execute();
}
/**
* 获取签到的id和logId
*
* @param userInfo user
* @param getSignMessageApiInfo 接口
*/
public SignMessage getSignMessage(UserInfo userInfo, ApiInfo getSignMessageApiInfo) {
HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo);
//参数
request.form("page", 1);
request.form("size", 5);
//得到返回的JSON并解析
String body = request.execute().body();
JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(0);
return new SignMessage((String) data.getObj("id"), (String) data.get("logId"));
}
@Async
public void sendSignRequest(UserInfo userInfo, ApiInfo signApiInfo, SignMessage signMessage) {
HttpRequest request = createHttpRequest(signApiInfo,userInfo);
//JSON data
JSONObject data = new JSONObject();
data.set("id", signMessage.getLogId());
data.set("signId", signMessage.getId());
data.set("latitude", "23.090164");
data.set("longitude", "113.354053");
data.set("country", "中国");
data.set("province", "广东省");
data.set("district", "海珠区");
data.set("township", "官洲街道");
data.set("city", "广州市");
request.body(data.toString());
request.execute();
}
public String GetJSON(UserInfo userInfo, ApiInfo getSignMessageApiInfo) {
HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo);
//参数
request.form("page", 1);
request.form("size", 5);
//得到返回的JSON并解析
String body = request.execute().body();
return body;
}
public boolean needCheck(ApiInfo apiInfo,UserInfo userInfo, int seq){
HttpRequest request = createHttpRequest(apiInfo,userInfo);
HttpResponse response = request.execute();
String body = response.body();
if(!JSONUtil.parseObj(body).containsKey("data")) return false;
JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(seq-1);
return Integer.parseInt(data.get("type").toString()) == 0;
}
public List<String> getAllNoSign(ApiInfo apiInfo,UserInfo userInfo, int seq){
HttpRequest request = createHttpRequest(apiInfo,userInfo);
//body
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式
String date = df.format(new Date());
String httpbody = apiInfo.getBody().replace("seq=3", "seq=" + seq);
httpbody = httpbody.replace("date=20201030","date="+date);
request.body(httpbody);
String body = request.execute().body();
if(!JSONUtil.parseObj(body).containsKey("data") ){
return null;
}else{
List<String> list = new ArrayList<>();
JSONArray arr = (JSONArray) JSONUtil.parseObj(body).get("data");
for (int i = 0; i < arr.size() ; i++) {
JSONObject stu = (JSONObject) arr.get(i);
list.add((String) stu.get("userId"));
}
return list;
}
}
public void replaceSign(ApiInfo apiInfo,UserInfo userInfo, int seq,String userId){
HttpRequest request = createHttpRequest(apiInfo,userInfo);
//body
String httpbody = apiInfo.getBody().replace("seq=", "seq=" + seq);
httpbody = httpbody.replace("userId=","userId="+userId);
request.body(httpbody);
//return body
request.execute();
}
public boolean JudgeTokenIsValid(ApiInfo apiInfo,UserInfo userInfo){
HttpRequest request = createHttpRequest(apiInfo,userInfo);
//得到返回的JSON并解析
String body = request.execute().body();
if(JSONUtil.parseObj(body).containsKey("data")) return true;
else return false;
}
/**
* 创建HttpRequest对象
*/
private HttpRequest createHttpRequest(ApiInfo apiInfo,UserInfo userInfo) {
//请求方法和请求url
HttpRequest request = request = apiInfo.getMethod().equals(ApiConstant.METHOD_GET)?HttpRequest.get(apiInfo.getUrl()):HttpRequest.post(apiInfo.getUrl());
//报文头
request.contentType(apiInfo.getContenttype());
//token
request.header("token", userInfo.getToken().trim());//总有混蛋 带空格存进来
return request;
}
}
| Duangdi/fuck-wozaixiaoyuan | src/main/java/com/fuckwzxy/util/SendUtil.java | 1,384 | //得到返回的JSON并解析 | line_comment | zh-cn | package com.fuckwzxy.util;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fuckwzxy.bean.ApiInfo;
import com.fuckwzxy.bean.SignMessage;
import com.fuckwzxy.bean.UserInfo;
import com.fuckwzxy.common.ApiConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import javax.sound.midi.Soundbank;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author wzh
* 2020/9/23 19:15
*/
@Component
@Slf4j
public class SendUtil {
@Async
public void sendCheckRequest(UserInfo userInfo, ApiInfo apiInfo, int seq) {
HttpRequest request = createHttpRequest(apiInfo,userInfo);
//body
request.body(apiInfo.getBody().replace("seq=3", "seq=" + seq));
//return body
request.execute();
}
/**
* 获取签到的id和logId
*
* @param userInfo user
* @param getSignMessageApiInfo 接口
*/
public SignMessage getSignMessage(UserInfo userInfo, ApiInfo getSignMessageApiInfo) {
HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo);
//参数
request.form("page", 1);
request.form("size", 5);
//得到返回的JSON并解析
String body = request.execute().body();
JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(0);
return new SignMessage((String) data.getObj("id"), (String) data.get("logId"));
}
@Async
public void sendSignRequest(UserInfo userInfo, ApiInfo signApiInfo, SignMessage signMessage) {
HttpRequest request = createHttpRequest(signApiInfo,userInfo);
//JSON data
JSONObject data = new JSONObject();
data.set("id", signMessage.getLogId());
data.set("signId", signMessage.getId());
data.set("latitude", "23.090164");
data.set("longitude", "113.354053");
data.set("country", "中国");
data.set("province", "广东省");
data.set("district", "海珠区");
data.set("township", "官洲街道");
data.set("city", "广州市");
request.body(data.toString());
request.execute();
}
public String GetJSON(UserInfo userInfo, ApiInfo getSignMessageApiInfo) {
HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo);
//参数
request.form("page", 1);
request.form("size", 5);
//得到 <SUF>
String body = request.execute().body();
return body;
}
public boolean needCheck(ApiInfo apiInfo,UserInfo userInfo, int seq){
HttpRequest request = createHttpRequest(apiInfo,userInfo);
HttpResponse response = request.execute();
String body = response.body();
if(!JSONUtil.parseObj(body).containsKey("data")) return false;
JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(seq-1);
return Integer.parseInt(data.get("type").toString()) == 0;
}
public List<String> getAllNoSign(ApiInfo apiInfo,UserInfo userInfo, int seq){
HttpRequest request = createHttpRequest(apiInfo,userInfo);
//body
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式
String date = df.format(new Date());
String httpbody = apiInfo.getBody().replace("seq=3", "seq=" + seq);
httpbody = httpbody.replace("date=20201030","date="+date);
request.body(httpbody);
String body = request.execute().body();
if(!JSONUtil.parseObj(body).containsKey("data") ){
return null;
}else{
List<String> list = new ArrayList<>();
JSONArray arr = (JSONArray) JSONUtil.parseObj(body).get("data");
for (int i = 0; i < arr.size() ; i++) {
JSONObject stu = (JSONObject) arr.get(i);
list.add((String) stu.get("userId"));
}
return list;
}
}
public void replaceSign(ApiInfo apiInfo,UserInfo userInfo, int seq,String userId){
HttpRequest request = createHttpRequest(apiInfo,userInfo);
//body
String httpbody = apiInfo.getBody().replace("seq=", "seq=" + seq);
httpbody = httpbody.replace("userId=","userId="+userId);
request.body(httpbody);
//return body
request.execute();
}
public boolean JudgeTokenIsValid(ApiInfo apiInfo,UserInfo userInfo){
HttpRequest request = createHttpRequest(apiInfo,userInfo);
//得到返回的JSON并解析
String body = request.execute().body();
if(JSONUtil.parseObj(body).containsKey("data")) return true;
else return false;
}
/**
* 创建HttpRequest对象
*/
private HttpRequest createHttpRequest(ApiInfo apiInfo,UserInfo userInfo) {
//请求方法和请求url
HttpRequest request = request = apiInfo.getMethod().equals(ApiConstant.METHOD_GET)?HttpRequest.get(apiInfo.getUrl()):HttpRequest.post(apiInfo.getUrl());
//报文头
request.contentType(apiInfo.getContenttype());
//token
request.header("token", userInfo.getToken().trim());//总有混蛋 带空格存进来
return request;
}
}
| 0 | 1,236 | 7 | 1,384 | 7 | 1,466 | 7 | 1,384 | 7 | 1,673 | 12 | false | false | false | false | false | true |
36283_1 | package com.boring.duanqifeng.tku;
/* 段其沣于2017年10月9日
在四川大学江安校区创建
*/
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class Leibie extends AppCompatActivity {
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leibie);
//每种类别的题目数
sharedPreferences = getSharedPreferences("TMS",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("gjs_danx",79);
editor.putInt("gjs_dx",102);
editor.putInt("gjs_pd",191);
editor.putInt("jbz_danx",60);
editor.putInt("jbz_dx",54);
editor.putInt("jbz_lw",3);
editor.putInt("jbz_pd",124);
editor.putInt("jcjs_danx",47);
editor.putInt("jcjs_dx",31);
editor.putInt("jcjs_pd",58);
editor.putInt("jl_danx",91);
editor.putInt("jl_dx",21);
editor.putInt("jl_pd",110);
editor.putInt("jsll_danx",386);
editor.putInt("jsll_dx",41);
editor.putInt("jsll_pd",42);
editor.putInt("nw_danx",84);
editor.putInt("nw_dx",111);
editor.putInt("nw_pd",18);
editor.putInt("nw_lw",262);
editor.putInt("xljc_danx",39);
editor.putInt("xljc_dx",45);
editor.putInt("xljc_pd",29);
editor.putInt("zzjc_danx",24);
editor.putInt("zzjc_dx",37);
editor.putInt("zzjc_pd",42);
editor.putInt("dl_danx",91);
editor.putInt("dl_dx",18);
editor.putInt("dl_pd",394);
editor.apply();
Button 内务 = (Button) findViewById(R.id.内务);
Button 队列 = (Button) findViewById(R.id.队列);
Button 纪律 = (Button) findViewById(R.id.纪律);
Button 军兵种 = (Button) findViewById(R.id.军兵种);
Button 军事理论 = (Button) findViewById(R.id.军事理论);
Button 军事高技术 = (Button) findViewById(R.id.军事高技术);
Button 军队基层建设 = (Button) findViewById(R.id.军队基层建设);
Button 训练基础理论 = (Button) findViewById(R.id.训练基础理论);
Button 作战基础知识 = (Button) findViewById(R.id.作战基础知识);
Button 模拟考试 = (Button) findViewById(R.id.kaoShi);
Button 错题集 = (Button) findViewById(R.id.cuoTi);
内务.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Neiwu.class));
}
});
队列.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Duilie.class));
}
});
纪律.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Jilv.class));
}
});
军兵种.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Jbz.class));
}
});
军事理论.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Jsll.class));
}
});
军事高技术.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Gjs.class));
}
});
军队基层建设.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Jcjs.class));
}
});
训练基础理论.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Xljc.class));
}
});
作战基础知识.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Zzjc.class));
}
});
模拟考试.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Moni.class));
}
});
错题集.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Cuotiji.class));
}
});
}
}
| Duanxiaoer/Android_TKU | app/src/main/java/com/boring/duanqifeng/tku/Leibie.java | 1,362 | //每种类别的题目数 | line_comment | zh-cn | package com.boring.duanqifeng.tku;
/* 段其沣于2017年10月9日
在四川大学江安校区创建
*/
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
public class Leibie extends AppCompatActivity {
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_leibie);
//每种 <SUF>
sharedPreferences = getSharedPreferences("TMS",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("gjs_danx",79);
editor.putInt("gjs_dx",102);
editor.putInt("gjs_pd",191);
editor.putInt("jbz_danx",60);
editor.putInt("jbz_dx",54);
editor.putInt("jbz_lw",3);
editor.putInt("jbz_pd",124);
editor.putInt("jcjs_danx",47);
editor.putInt("jcjs_dx",31);
editor.putInt("jcjs_pd",58);
editor.putInt("jl_danx",91);
editor.putInt("jl_dx",21);
editor.putInt("jl_pd",110);
editor.putInt("jsll_danx",386);
editor.putInt("jsll_dx",41);
editor.putInt("jsll_pd",42);
editor.putInt("nw_danx",84);
editor.putInt("nw_dx",111);
editor.putInt("nw_pd",18);
editor.putInt("nw_lw",262);
editor.putInt("xljc_danx",39);
editor.putInt("xljc_dx",45);
editor.putInt("xljc_pd",29);
editor.putInt("zzjc_danx",24);
editor.putInt("zzjc_dx",37);
editor.putInt("zzjc_pd",42);
editor.putInt("dl_danx",91);
editor.putInt("dl_dx",18);
editor.putInt("dl_pd",394);
editor.apply();
Button 内务 = (Button) findViewById(R.id.内务);
Button 队列 = (Button) findViewById(R.id.队列);
Button 纪律 = (Button) findViewById(R.id.纪律);
Button 军兵种 = (Button) findViewById(R.id.军兵种);
Button 军事理论 = (Button) findViewById(R.id.军事理论);
Button 军事高技术 = (Button) findViewById(R.id.军事高技术);
Button 军队基层建设 = (Button) findViewById(R.id.军队基层建设);
Button 训练基础理论 = (Button) findViewById(R.id.训练基础理论);
Button 作战基础知识 = (Button) findViewById(R.id.作战基础知识);
Button 模拟考试 = (Button) findViewById(R.id.kaoShi);
Button 错题集 = (Button) findViewById(R.id.cuoTi);
内务.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Neiwu.class));
}
});
队列.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Duilie.class));
}
});
纪律.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Jilv.class));
}
});
军兵种.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Jbz.class));
}
});
军事理论.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Jsll.class));
}
});
军事高技术.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Gjs.class));
}
});
军队基层建设.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Jcjs.class));
}
});
训练基础理论.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Xljc.class));
}
});
作战基础知识.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Zzjc.class));
}
});
模拟考试.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Moni.class));
}
});
错题集.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Leibie.this,Cuotiji.class));
}
});
}
}
| 0 | 1,129 | 6 | 1,362 | 9 | 1,410 | 6 | 1,362 | 9 | 1,663 | 11 | false | false | false | false | false | true |
33092_8 | package net.messi.early.controller;
import net.messi.early.request.ProductInventoryCacheRefreshRequest;
import net.messi.early.request.ProductInventoryDBUpdateRequest;
import net.messi.early.request.Request;
import net.messi.early.service.GoodsService;
import net.messi.early.service.ProductInventoryService;
import net.messi.early.service.RequestAsyncProcessService;
import net.messi.early.utils.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("inventory")
public class ProductInventoryController {
@Autowired
private GoodsService goodsService;
@Autowired
private RequestAsyncProcessService requestAsyncProcessService;
@Autowired
private ProductInventoryService productInventoryService;
/**
* 更新缓存
*
* @param goodsId
* @param inventoryCnt
* @return
*/
@ResponseBody
@RequestMapping("/updateInventory")
public JSONResult updateInventory(Integer goodsId) {
try {
Request request = new ProductInventoryDBUpdateRequest(goodsId, goodsService);
requestAsyncProcessService.process(request);
} catch (Exception e) {
e.printStackTrace();
}
return JSONResult.ok();
}
/**
* 获取商品库存的缓存
*
* @param goodsId
* @return
*/
@ResponseBody
@RequestMapping("/getInventory")
public JSONResult getInventory(Integer goodsId) {
try {
Request request = new ProductInventoryCacheRefreshRequest(goodsId, goodsService);
requestAsyncProcessService.process(request);
long startTime = System.currentTimeMillis();
long endTime = 0L;
long waitTime = 0L;
Integer inventoryCnt = 0;
//将请求仍给service异步处理以后,就需要while(true)一会儿,在这里hang住
//去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中
while (true) {
if (waitTime > 200) {
break;
}
//尝试去redis中读取一次商品库存的缓存
inventoryCnt = productInventoryService.getProductInventoryCache(goodsId);
//如果读取到了结果,那么就返回
if (inventoryCnt != null) {
return new JSONResult(inventoryCnt);
} else {
//如果没有读取到
Thread.sleep(20);
endTime = System.currentTimeMillis();
waitTime = endTime - startTime;
}
}
//直接从数据库查询
inventoryCnt = goodsService.lasteInventory(goodsId);
if (inventoryCnt != null)
return new JSONResult(inventoryCnt);
} catch (Exception e) {
e.printStackTrace();
}
//没有查到
return JSONResult.ok(new Long(-1L));
}
}
| DuncanPlayer/quickearly | controller/ProductInventoryController.java | 684 | //没有查到 | line_comment | zh-cn | package net.messi.early.controller;
import net.messi.early.request.ProductInventoryCacheRefreshRequest;
import net.messi.early.request.ProductInventoryDBUpdateRequest;
import net.messi.early.request.Request;
import net.messi.early.service.GoodsService;
import net.messi.early.service.ProductInventoryService;
import net.messi.early.service.RequestAsyncProcessService;
import net.messi.early.utils.JSONResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("inventory")
public class ProductInventoryController {
@Autowired
private GoodsService goodsService;
@Autowired
private RequestAsyncProcessService requestAsyncProcessService;
@Autowired
private ProductInventoryService productInventoryService;
/**
* 更新缓存
*
* @param goodsId
* @param inventoryCnt
* @return
*/
@ResponseBody
@RequestMapping("/updateInventory")
public JSONResult updateInventory(Integer goodsId) {
try {
Request request = new ProductInventoryDBUpdateRequest(goodsId, goodsService);
requestAsyncProcessService.process(request);
} catch (Exception e) {
e.printStackTrace();
}
return JSONResult.ok();
}
/**
* 获取商品库存的缓存
*
* @param goodsId
* @return
*/
@ResponseBody
@RequestMapping("/getInventory")
public JSONResult getInventory(Integer goodsId) {
try {
Request request = new ProductInventoryCacheRefreshRequest(goodsId, goodsService);
requestAsyncProcessService.process(request);
long startTime = System.currentTimeMillis();
long endTime = 0L;
long waitTime = 0L;
Integer inventoryCnt = 0;
//将请求仍给service异步处理以后,就需要while(true)一会儿,在这里hang住
//去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中
while (true) {
if (waitTime > 200) {
break;
}
//尝试去redis中读取一次商品库存的缓存
inventoryCnt = productInventoryService.getProductInventoryCache(goodsId);
//如果读取到了结果,那么就返回
if (inventoryCnt != null) {
return new JSONResult(inventoryCnt);
} else {
//如果没有读取到
Thread.sleep(20);
endTime = System.currentTimeMillis();
waitTime = endTime - startTime;
}
}
//直接从数据库查询
inventoryCnt = goodsService.lasteInventory(goodsId);
if (inventoryCnt != null)
return new JSONResult(inventoryCnt);
} catch (Exception e) {
e.printStackTrace();
}
//没有 <SUF>
return JSONResult.ok(new Long(-1L));
}
}
| 0 | 628 | 4 | 684 | 4 | 731 | 4 | 684 | 4 | 923 | 5 | false | false | false | false | false | true |
64649_2 | package org.lanqiao.algo.elementary._03sort;
import org.assertj.core.api.Assertions;
import org.lanqiao.algo.util.Util;
import java.util.Arrays;
/**
* 思路:首先要知道大顶堆和小顶堆,数组就是一个堆,每个i节点的左右孩子是2i+1和2i+2<br />
* 有了堆,将其堆化:从n/2-1个元素开始向下修复,将每个节点修复为小(大)顶堆<br />
* 修复完成后,数组具有小(大)顶堆的性质<br />
* 按序输出:小顶堆可以对数组逆序排序,每次交换栈顶和末尾元素,对栈顶进行向下修复,这样次小元素又到堆顶了<br />
*
* 时间复杂度: 堆化:一半的元素修复,修复是单分支的,所以整体堆化为nlgn/2<br />
* 排序:n个元素都要取出,因此调整n次,每次调整修复同上是lgn的,整体为nlgn
* 空间复杂度:不需要开辟辅助空间<br />
* 原址排序<br />
* 稳定性:<br />
*/
public class _7HeapSort {
static void makeMinHeap(int[] A) {
int n = A.length;
for (int i = n / 2 - 1; i >= 0; i--) {
MinHeapFixDown(A, i, n);
}
}
static void MinHeapFixDown(int[] A, int i, int n) {
// 找到左右孩子
int left = 2 * i + 1;
int right = 2 * i + 2;
//左孩子已经越界,i就是叶子节点
if (left >= n) {
return;
}
int min = left;
if (right >= n) {
min = left;
} else {
if (A[right] < A[left]) {
min = right;
}
}
//min指向了左右孩子中较小的那个
// 如果A[i]比两个孩子都要小,不用调整
if (A[i] <= A[min]) {
return;
}
//否则,找到两个孩子中较小的,和i交换
int temp = A[i];
A[i] = A[min];
A[min] = temp;
//小孩子那个位置的值发生了变化,i变更为小孩子那个位置,递归调整
MinHeapFixDown(A, min, n);
}
//
// public static void sortDesc(int[] arr) {
// makeMinHeap( arr ); // 1.建立小顶堆
// int length = arr.length;
// for (int i = length - 1; i >= 1; i--) {
// Util.swap( arr, i, 0 ); // 堆顶(最小)元素换到元素末尾,末尾元素到了堆顶
// MinHeapFixDown( arr, 0, i );// 调整堆顶,边界递减
// }
// }
static void sort(int[] A) {
//先对A进行堆化
makeMinHeap(A);
for (int x = A.length - 1; x >= 0; x--) {
//把堆顶,0号元素和最后一个元素对调
Util.swap(A, 0, x);
//缩小堆的范围,对堆顶元素进行向下调整
MinHeapFixDown(A, 0, x);
}
}
public static void main(String[] args) {
int[] arr = Util.getRandomArr(10, 1, 100);
System.out.println( "begin..." + Arrays.toString( arr ) );
sort(arr);
System.out.println( "final..." + Arrays.toString( arr ) );
Assertions.assertThat( Util.checkOrdered( arr, false ) ).isTrue();
}
}
| Dxoca/Algorithm_LanQiao | src/main/java/org/lanqiao/algo/elementary/_03sort/_7HeapSort.java | 982 | //左孩子已经越界,i就是叶子节点 | line_comment | zh-cn | package org.lanqiao.algo.elementary._03sort;
import org.assertj.core.api.Assertions;
import org.lanqiao.algo.util.Util;
import java.util.Arrays;
/**
* 思路:首先要知道大顶堆和小顶堆,数组就是一个堆,每个i节点的左右孩子是2i+1和2i+2<br />
* 有了堆,将其堆化:从n/2-1个元素开始向下修复,将每个节点修复为小(大)顶堆<br />
* 修复完成后,数组具有小(大)顶堆的性质<br />
* 按序输出:小顶堆可以对数组逆序排序,每次交换栈顶和末尾元素,对栈顶进行向下修复,这样次小元素又到堆顶了<br />
*
* 时间复杂度: 堆化:一半的元素修复,修复是单分支的,所以整体堆化为nlgn/2<br />
* 排序:n个元素都要取出,因此调整n次,每次调整修复同上是lgn的,整体为nlgn
* 空间复杂度:不需要开辟辅助空间<br />
* 原址排序<br />
* 稳定性:<br />
*/
public class _7HeapSort {
static void makeMinHeap(int[] A) {
int n = A.length;
for (int i = n / 2 - 1; i >= 0; i--) {
MinHeapFixDown(A, i, n);
}
}
static void MinHeapFixDown(int[] A, int i, int n) {
// 找到左右孩子
int left = 2 * i + 1;
int right = 2 * i + 2;
//左孩 <SUF>
if (left >= n) {
return;
}
int min = left;
if (right >= n) {
min = left;
} else {
if (A[right] < A[left]) {
min = right;
}
}
//min指向了左右孩子中较小的那个
// 如果A[i]比两个孩子都要小,不用调整
if (A[i] <= A[min]) {
return;
}
//否则,找到两个孩子中较小的,和i交换
int temp = A[i];
A[i] = A[min];
A[min] = temp;
//小孩子那个位置的值发生了变化,i变更为小孩子那个位置,递归调整
MinHeapFixDown(A, min, n);
}
//
// public static void sortDesc(int[] arr) {
// makeMinHeap( arr ); // 1.建立小顶堆
// int length = arr.length;
// for (int i = length - 1; i >= 1; i--) {
// Util.swap( arr, i, 0 ); // 堆顶(最小)元素换到元素末尾,末尾元素到了堆顶
// MinHeapFixDown( arr, 0, i );// 调整堆顶,边界递减
// }
// }
static void sort(int[] A) {
//先对A进行堆化
makeMinHeap(A);
for (int x = A.length - 1; x >= 0; x--) {
//把堆顶,0号元素和最后一个元素对调
Util.swap(A, 0, x);
//缩小堆的范围,对堆顶元素进行向下调整
MinHeapFixDown(A, 0, x);
}
}
public static void main(String[] args) {
int[] arr = Util.getRandomArr(10, 1, 100);
System.out.println( "begin..." + Arrays.toString( arr ) );
sort(arr);
System.out.println( "final..." + Arrays.toString( arr ) );
Assertions.assertThat( Util.checkOrdered( arr, false ) ).isTrue();
}
}
| 0 | 879 | 11 | 982 | 14 | 969 | 11 | 982 | 14 | 1,301 | 20 | false | false | false | false | false | true |
16805_4 | package comm;
import java.sql.*;
import java.util.Objects;
import static comm.DBConfig.*;
public class Card {
private String cardID;
private String userName;
private String passWord;
private int balance;
private boolean exist;
public int getBalance() {
return balance;
}
// public void setBanlance(float banlance) {this.banlance = banlance;}
public String getUserName() {return userName;}
public void setUserName(String userName) {this.userName = userName; }
public String getCardID() {
return cardID;
}
public void setCardID(String cardID) {
this.cardID = cardID;
}
public String getPassWord() {
return passWord;
}
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
public Card(String cardID, String passWord, int balance){
this.cardID = cardID;
this.passWord = passWord;
this.balance = balance;
getInfo(cardID);
}
public Card(String cardID){
getInfo(cardID);
}
//从数据库获取信息
public void getInfo(String cardID){
exist = false;
Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
stmt = conn.createStatement();
String sql;
sql = "SELECT CardID, UserName, PassWord, Balance FROM user where CardID =" + cardID;
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
while(rs.next()){
// 通过字段检索
String id = rs.getString("CardID");
String name = rs.getString("UserName");
String pwd = rs.getString("PassWord");
int balance = rs.getInt("Balance");
// 输出数据
System.out.print("CardID: " + id);
System.out.print(" UserName: " + name);
System.out.print(" PassWord: " + pwd);
System.out.print(" Balance: " + balance);
System.out.print("\n");
this.cardID = id;
this.userName = name;
this.balance = balance;
this.passWord=pwd;
if(!Objects.equals(id, "")) exist=true;
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
// 判断账号是否存在
public boolean exist(){
System.out.println(exist);
return exist;
}
// 判断密码是否正确
public boolean judgePwd(String pwd){
return Objects.equals(pwd, this.passWord);
}
// 改密
public boolean setPassWord(String pwd){
if(exist()){
Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行修改
stmt = conn.createStatement();
String sql;
sql = "UPDATE user SET Password=? where CardID =?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1,pwd);
pst.setString(2,cardID);
pst.executeUpdate();
// 完成后关闭
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
passWord=pwd;
}
return true;
}
//修改余额
public boolean setBanlance(int balance){
if(exist()){
Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行修改
stmt = conn.createStatement();
String sql;
sql = "UPDATE user SET Balance=? where CardID =?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1,balance);
pst.setString(2,cardID);
pst.executeUpdate();
// 完成后关闭
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
this.balance=balance;
}
return true;
}
}
| Dycley/ATM | src/comm/Card.java | 1,527 | // 注册 JDBC 驱动 | line_comment | zh-cn | package comm;
import java.sql.*;
import java.util.Objects;
import static comm.DBConfig.*;
public class Card {
private String cardID;
private String userName;
private String passWord;
private int balance;
private boolean exist;
public int getBalance() {
return balance;
}
// public void setBanlance(float banlance) {this.banlance = banlance;}
public String getUserName() {return userName;}
public void setUserName(String userName) {this.userName = userName; }
public String getCardID() {
return cardID;
}
public void setCardID(String cardID) {
this.cardID = cardID;
}
public String getPassWord() {
return passWord;
}
// public void setPassWord(String passWord) {
// this.passWord = passWord;
// }
public Card(String cardID, String passWord, int balance){
this.cardID = cardID;
this.passWord = passWord;
this.balance = balance;
getInfo(cardID);
}
public Card(String cardID){
getInfo(cardID);
}
//从数据库获取信息
public void getInfo(String cardID){
exist = false;
Connection conn = null;
Statement stmt = null;
try{
// 注册 <SUF>
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行查询
stmt = conn.createStatement();
String sql;
sql = "SELECT CardID, UserName, PassWord, Balance FROM user where CardID =" + cardID;
ResultSet rs = stmt.executeQuery(sql);
// 展开结果集数据库
while(rs.next()){
// 通过字段检索
String id = rs.getString("CardID");
String name = rs.getString("UserName");
String pwd = rs.getString("PassWord");
int balance = rs.getInt("Balance");
// 输出数据
System.out.print("CardID: " + id);
System.out.print(" UserName: " + name);
System.out.print(" PassWord: " + pwd);
System.out.print(" Balance: " + balance);
System.out.print("\n");
this.cardID = id;
this.userName = name;
this.balance = balance;
this.passWord=pwd;
if(!Objects.equals(id, "")) exist=true;
}
// 完成后关闭
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
// 判断账号是否存在
public boolean exist(){
System.out.println(exist);
return exist;
}
// 判断密码是否正确
public boolean judgePwd(String pwd){
return Objects.equals(pwd, this.passWord);
}
// 改密
public boolean setPassWord(String pwd){
if(exist()){
Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行修改
stmt = conn.createStatement();
String sql;
sql = "UPDATE user SET Password=? where CardID =?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1,pwd);
pst.setString(2,cardID);
pst.executeUpdate();
// 完成后关闭
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
passWord=pwd;
}
return true;
}
//修改余额
public boolean setBanlance(int balance){
if(exist()){
Connection conn = null;
Statement stmt = null;
try{
// 注册 JDBC 驱动
Class.forName(JDBC_DRIVER);
// 打开链接
System.out.println("连接数据库...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
// 执行修改
stmt = conn.createStatement();
String sql;
sql = "UPDATE user SET Balance=? where CardID =?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setInt(1,balance);
pst.setString(2,cardID);
pst.executeUpdate();
// 完成后关闭
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
this.balance=balance;
}
return true;
}
}
| 0 | 1,278 | 8 | 1,527 | 6 | 1,478 | 5 | 1,527 | 6 | 2,171 | 13 | false | false | false | false | false | true |
34199_18 | package com.aochat.ui;
import com.aochat.ui.module.*;
import com.aochat.ui.module.Labels;
import com.aochat.ui.module.Menu;
import javax.swing.*;
import java.awt.*;
public class Frame {
JPanel rootPanel = new JPanel(); // 新建根窗口
JFrame frame = new JFrame("AoChat"); // 初始化窗口,并命名
Menu menuBar = new Menu(rootPanel, frame); // 新建菜单栏
IPText ipText = new IPText(rootPanel); // 新建IP输入栏
PortTexts portTexts = new PortTexts(rootPanel); // 新建端口输入栏
EnterTextArea enterTextArea = new EnterTextArea(rootPanel); // 新建信息输入栏
public MessageArea messageArea = new MessageArea(rootPanel); // 新建消息输入栏
Labels labels = new Labels(rootPanel); // 新建信息栏
Buttons buttons = new Buttons(rootPanel, menuBar); // 新建按钮组
public Frame(){
panelInit(); // 窗口初始化
setPosition(); // 设置每个组件位置
addActionListener(); // 添加监听器
}
private void panelInit(){
// 窗口初始化
// 设置图标
Toolkit took = Toolkit.getDefaultToolkit();
Image image = took.getImage("src/img/icon.png");
frame.setIconImage(image);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时关闭进程
frame.setContentPane(rootPanel); // 容器添加到面板
frame.setResizable(false); // 不准改大小
frame.setSize(800, 600); // 设置窗口大小
frame.setVisible(true); // 显示窗口
}
private void setPosition(){
// 设置每个组件位置
rootPanel.setLayout(null);// 禁用布局器
menuBar.setPosition();
enterTextArea.setPosition();
ipText.setPosition();
portTexts.setPosition();
messageArea.setPosition();
labels.setPosition();
buttons.setPosition();
}
private void addActionListener(){
// 添加监听器
menuBar.addActionListener();
buttons.addButtonActionListener(enterTextArea, ipText, portTexts, messageArea, labels, menuBar.ipHistorySet);
}
}
| DylanAo/AHU-AI-Repository | 专业选修课/Java/AoChat/com/aochat/ui/Frame.java | 519 | // 显示窗口
| line_comment | zh-cn | package com.aochat.ui;
import com.aochat.ui.module.*;
import com.aochat.ui.module.Labels;
import com.aochat.ui.module.Menu;
import javax.swing.*;
import java.awt.*;
public class Frame {
JPanel rootPanel = new JPanel(); // 新建根窗口
JFrame frame = new JFrame("AoChat"); // 初始化窗口,并命名
Menu menuBar = new Menu(rootPanel, frame); // 新建菜单栏
IPText ipText = new IPText(rootPanel); // 新建IP输入栏
PortTexts portTexts = new PortTexts(rootPanel); // 新建端口输入栏
EnterTextArea enterTextArea = new EnterTextArea(rootPanel); // 新建信息输入栏
public MessageArea messageArea = new MessageArea(rootPanel); // 新建消息输入栏
Labels labels = new Labels(rootPanel); // 新建信息栏
Buttons buttons = new Buttons(rootPanel, menuBar); // 新建按钮组
public Frame(){
panelInit(); // 窗口初始化
setPosition(); // 设置每个组件位置
addActionListener(); // 添加监听器
}
private void panelInit(){
// 窗口初始化
// 设置图标
Toolkit took = Toolkit.getDefaultToolkit();
Image image = took.getImage("src/img/icon.png");
frame.setIconImage(image);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时关闭进程
frame.setContentPane(rootPanel); // 容器添加到面板
frame.setResizable(false); // 不准改大小
frame.setSize(800, 600); // 设置窗口大小
frame.setVisible(true); // 显示 <SUF>
}
private void setPosition(){
// 设置每个组件位置
rootPanel.setLayout(null);// 禁用布局器
menuBar.setPosition();
enterTextArea.setPosition();
ipText.setPosition();
portTexts.setPosition();
messageArea.setPosition();
labels.setPosition();
buttons.setPosition();
}
private void addActionListener(){
// 添加监听器
menuBar.addActionListener();
buttons.addButtonActionListener(enterTextArea, ipText, portTexts, messageArea, labels, menuBar.ipHistorySet);
}
}
| 0 | 482 | 5 | 515 | 5 | 541 | 4 | 515 | 5 | 733 | 9 | false | false | false | false | false | true |
24092_10 | package com.dyman.opencvtest.utils;
import android.graphics.Bitmap;
import android.util.Log;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.RotatedRect;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by dyman on 2017/8/12.
*
* 智能选区帮助类
*/
public class Scanner {
private static final String TAG = "Scanner";
private static int resizeThreshold = 500;
private static float resizeScale = 1.0f;
/** 扫描图片,并返回检测到的矩形的四个顶点的坐标 */
public static android.graphics.Point[] scanPoint(Bitmap srcBitmap) {
Mat srcMat = new Mat();
Utils.bitmapToMat(srcBitmap, srcMat);
// 图像缩放
Mat image = resizeImage(srcMat);
// 图像预处理
Mat scanImage = preProcessImage(image);
List<MatOfPoint> contours = new ArrayList<>(); // 检测到的轮廓
Mat hierarchy = new Mat(); // 各轮廓的继承关系
// 提取边框
Imgproc.findContours(scanImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
// 按面积排序,最后只取面积最大的那个
Collections.sort(contours, new Comparator<MatOfPoint>() {
@Override
public int compare(MatOfPoint matOfPoint1, MatOfPoint matOfPoint2) {
double oneArea = Math.abs(Imgproc.contourArea(matOfPoint1));
double twoArea = Math.abs(Imgproc.contourArea(matOfPoint2));
return Double.compare(twoArea, oneArea);
}
});
Point[] resultArr = new Point[4];
if (contours.size() > 0) {
Log.i(TAG, "scanPoint: -------------contours.size="+contours.size());
// 取面积最大的
MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(0).toArray());
double arc = Imgproc.arcLength(contour2f, true);
MatOfPoint2f outDpMat = new MatOfPoint2f();
Imgproc.approxPolyDP(contour2f, outDpMat, 0.02 * arc, true); // 多边形逼近
// 筛选去除相近的点
MatOfPoint2f selectMat = selectPoint(outDpMat, 1);
if (selectMat.toArray().length != 4) {
// 不是四边形,使用最小矩形包裹
RotatedRect rotatedRect = Imgproc.minAreaRect(selectMat);
rotatedRect.points(resultArr);
} else {
resultArr = selectMat.toArray();
}
// 比例还原
for (Point p : resultArr) {
p.x *= resizeScale;
p.y *= resizeScale;
}
}
// 对最终检测出的四个点进行排序:左上、右上、右下、坐下
Point[] result = sortPointClockwise(resultArr);
android.graphics.Point[] rs = new android.graphics.Point[result.length];
for (int i = 0; i < result.length; i++) {
android.graphics.Point p = new android.graphics.Point((int) result[i].x, (int) result[i].y);
rs[i] = p;
}
return rs;
}
/**
* 为避免处理时间过长,先对图片进行压缩
* @param image
* @return
*/
private static Mat resizeImage(Mat image) {
int width = image.cols();
int height = image.rows();
int maxSize = width > height ? width : height;
if (maxSize > resizeThreshold) {
resizeScale = 1.0f * maxSize / resizeThreshold;
width = (int) (width / resizeScale);
height = (int) (height / resizeScale);
Size size = new Size(width, height);
Mat resizeMat = new Mat();
Imgproc.resize(image, resizeMat, size);
return resizeMat;
}
return image;
}
/**
* 对图像进行预处理:灰度化、高斯模糊、Canny边缘检测
* @param image
* @return
*/
private static Mat preProcessImage(Mat image) {
Mat grayMat = new Mat();
Imgproc.cvtColor(image, grayMat, Imgproc.COLOR_RGB2GRAY); // 注意RGB和BGR,影响很大
Mat blurMat = new Mat();
Imgproc.GaussianBlur(grayMat, blurMat, new Size(5,5), 0);
Mat cannyMat = new Mat();
Imgproc.Canny(blurMat, cannyMat, 0, 5);
Mat thresholdMat = new Mat();
Imgproc.threshold(cannyMat, thresholdMat, 0, 255, Imgproc.THRESH_OTSU);
return cannyMat;
}
/** 过滤掉距离相近的点 */
private static MatOfPoint2f selectPoint(MatOfPoint2f outDpMat, int selectTimes) {
List<Point> pointList = new ArrayList<>();
pointList.addAll(outDpMat.toList());
if (pointList.size() > 4) {
double arc = Imgproc.arcLength(outDpMat, true);
for (int i = pointList.size() - 1; i >= 0; i--) {
if (pointList.size() == 4) {
Point[] resultPoints = new Point[pointList.size()];
for (int j = 0; j < pointList.size(); j++) {
resultPoints[j] = pointList.get(j);
}
return new MatOfPoint2f(resultPoints);
}
if (i != pointList.size() - 1) {
Point itor = pointList.get(i);
Point lastP = pointList.get(i + 1);
double pointLength = Math.sqrt(Math.pow(itor.x-lastP.x, 2) + Math.pow(itor.y - lastP.y, 2));
if (pointLength < arc * 0.01 * selectTimes && pointList.size() > 4) {
pointList.remove(i);
}
}
}
if (pointList.size() > 4) {
// 要手动逐个强转
Point[] againPoints = new Point[pointList.size()];
for (int i = 0; i < pointList.size(); i++) {
againPoints[i] = pointList.get(i);
}
return selectPoint(new MatOfPoint2f(againPoints), selectTimes + 1);
}
}
return outDpMat;
}
/** 对顶点进行排序 */
private static Point[] sortPointClockwise(Point[] points) {
if (points.length != 4) {
return points;
}
Point unFoundPoint = new Point();
Point[] result = {unFoundPoint, unFoundPoint, unFoundPoint, unFoundPoint};
long minDistance = -1;
for (Point point : points) {
long distance = (long) (point.x * point.x + point.y * point.y);
if (minDistance == -1 || distance < minDistance) {
result[0] = point;
minDistance = distance;
}
}
if (result[0] != unFoundPoint) {
Point leftTop = result[0];
Point[] p1 = new Point[3];
int i = 0;
for (Point point : points) {
if (point.x == leftTop.x && point.y == leftTop.y)
continue;
p1[i] = point;
i++;
}
if ((pointSideLine(leftTop, p1[0], p1[1]) * pointSideLine(leftTop, p1[0], p1[2])) < 0) {
result[2] = p1[0];
} else if ((pointSideLine(leftTop, p1[1], p1[0]) * pointSideLine(leftTop, p1[1], p1[2])) < 0) {
result[2] = p1[1];
} else if ((pointSideLine(leftTop, p1[2], p1[0]) * pointSideLine(leftTop, p1[2], p1[1])) < 0) {
result[2] = p1[2];
}
}
if (result[0] != unFoundPoint && result[2] != unFoundPoint) {
Point leftTop = result[0];
Point rightBottom = result[2];
Point[] p1 = new Point[2];
int i = 0;
for (Point point : points) {
if (point.x == leftTop.x && point.y == leftTop.y)
continue;
if (point.x == rightBottom.x && point.y == rightBottom.y)
continue;
p1[i] = point;
i++;
}
if (pointSideLine(leftTop, rightBottom, p1[0]) > 0) {
result[1] = p1[0];
result[3] = p1[1];
} else {
result[1] = p1[1];
result[3] = p1[0];
}
}
if (result[0] != unFoundPoint && result[1] != unFoundPoint && result[2] != unFoundPoint && result[3] != unFoundPoint) {
return result;
}
return points;
}
private static double pointSideLine(Point lineP1, Point lineP2, Point point) {
double x1 = lineP1.x;
double y1 = lineP1.y;
double x2 = lineP2.x;
double y2 = lineP2.y;
double x = point.x;
double y = point.y;
return (x - x1)*(y2 - y1) - (y - y1)*(x2 - x1);
}
}
| DymanZy/OpenCVTest | app/src/main/java/com/dyman/opencvtest/utils/Scanner.java | 2,479 | // 筛选去除相近的点 | line_comment | zh-cn | package com.dyman.opencvtest.utils;
import android.graphics.Bitmap;
import android.util.Log;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.MatOfPoint2f;
import org.opencv.core.Point;
import org.opencv.core.RotatedRect;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by dyman on 2017/8/12.
*
* 智能选区帮助类
*/
public class Scanner {
private static final String TAG = "Scanner";
private static int resizeThreshold = 500;
private static float resizeScale = 1.0f;
/** 扫描图片,并返回检测到的矩形的四个顶点的坐标 */
public static android.graphics.Point[] scanPoint(Bitmap srcBitmap) {
Mat srcMat = new Mat();
Utils.bitmapToMat(srcBitmap, srcMat);
// 图像缩放
Mat image = resizeImage(srcMat);
// 图像预处理
Mat scanImage = preProcessImage(image);
List<MatOfPoint> contours = new ArrayList<>(); // 检测到的轮廓
Mat hierarchy = new Mat(); // 各轮廓的继承关系
// 提取边框
Imgproc.findContours(scanImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE);
// 按面积排序,最后只取面积最大的那个
Collections.sort(contours, new Comparator<MatOfPoint>() {
@Override
public int compare(MatOfPoint matOfPoint1, MatOfPoint matOfPoint2) {
double oneArea = Math.abs(Imgproc.contourArea(matOfPoint1));
double twoArea = Math.abs(Imgproc.contourArea(matOfPoint2));
return Double.compare(twoArea, oneArea);
}
});
Point[] resultArr = new Point[4];
if (contours.size() > 0) {
Log.i(TAG, "scanPoint: -------------contours.size="+contours.size());
// 取面积最大的
MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(0).toArray());
double arc = Imgproc.arcLength(contour2f, true);
MatOfPoint2f outDpMat = new MatOfPoint2f();
Imgproc.approxPolyDP(contour2f, outDpMat, 0.02 * arc, true); // 多边形逼近
// 筛选 <SUF>
MatOfPoint2f selectMat = selectPoint(outDpMat, 1);
if (selectMat.toArray().length != 4) {
// 不是四边形,使用最小矩形包裹
RotatedRect rotatedRect = Imgproc.minAreaRect(selectMat);
rotatedRect.points(resultArr);
} else {
resultArr = selectMat.toArray();
}
// 比例还原
for (Point p : resultArr) {
p.x *= resizeScale;
p.y *= resizeScale;
}
}
// 对最终检测出的四个点进行排序:左上、右上、右下、坐下
Point[] result = sortPointClockwise(resultArr);
android.graphics.Point[] rs = new android.graphics.Point[result.length];
for (int i = 0; i < result.length; i++) {
android.graphics.Point p = new android.graphics.Point((int) result[i].x, (int) result[i].y);
rs[i] = p;
}
return rs;
}
/**
* 为避免处理时间过长,先对图片进行压缩
* @param image
* @return
*/
private static Mat resizeImage(Mat image) {
int width = image.cols();
int height = image.rows();
int maxSize = width > height ? width : height;
if (maxSize > resizeThreshold) {
resizeScale = 1.0f * maxSize / resizeThreshold;
width = (int) (width / resizeScale);
height = (int) (height / resizeScale);
Size size = new Size(width, height);
Mat resizeMat = new Mat();
Imgproc.resize(image, resizeMat, size);
return resizeMat;
}
return image;
}
/**
* 对图像进行预处理:灰度化、高斯模糊、Canny边缘检测
* @param image
* @return
*/
private static Mat preProcessImage(Mat image) {
Mat grayMat = new Mat();
Imgproc.cvtColor(image, grayMat, Imgproc.COLOR_RGB2GRAY); // 注意RGB和BGR,影响很大
Mat blurMat = new Mat();
Imgproc.GaussianBlur(grayMat, blurMat, new Size(5,5), 0);
Mat cannyMat = new Mat();
Imgproc.Canny(blurMat, cannyMat, 0, 5);
Mat thresholdMat = new Mat();
Imgproc.threshold(cannyMat, thresholdMat, 0, 255, Imgproc.THRESH_OTSU);
return cannyMat;
}
/** 过滤掉距离相近的点 */
private static MatOfPoint2f selectPoint(MatOfPoint2f outDpMat, int selectTimes) {
List<Point> pointList = new ArrayList<>();
pointList.addAll(outDpMat.toList());
if (pointList.size() > 4) {
double arc = Imgproc.arcLength(outDpMat, true);
for (int i = pointList.size() - 1; i >= 0; i--) {
if (pointList.size() == 4) {
Point[] resultPoints = new Point[pointList.size()];
for (int j = 0; j < pointList.size(); j++) {
resultPoints[j] = pointList.get(j);
}
return new MatOfPoint2f(resultPoints);
}
if (i != pointList.size() - 1) {
Point itor = pointList.get(i);
Point lastP = pointList.get(i + 1);
double pointLength = Math.sqrt(Math.pow(itor.x-lastP.x, 2) + Math.pow(itor.y - lastP.y, 2));
if (pointLength < arc * 0.01 * selectTimes && pointList.size() > 4) {
pointList.remove(i);
}
}
}
if (pointList.size() > 4) {
// 要手动逐个强转
Point[] againPoints = new Point[pointList.size()];
for (int i = 0; i < pointList.size(); i++) {
againPoints[i] = pointList.get(i);
}
return selectPoint(new MatOfPoint2f(againPoints), selectTimes + 1);
}
}
return outDpMat;
}
/** 对顶点进行排序 */
private static Point[] sortPointClockwise(Point[] points) {
if (points.length != 4) {
return points;
}
Point unFoundPoint = new Point();
Point[] result = {unFoundPoint, unFoundPoint, unFoundPoint, unFoundPoint};
long minDistance = -1;
for (Point point : points) {
long distance = (long) (point.x * point.x + point.y * point.y);
if (minDistance == -1 || distance < minDistance) {
result[0] = point;
minDistance = distance;
}
}
if (result[0] != unFoundPoint) {
Point leftTop = result[0];
Point[] p1 = new Point[3];
int i = 0;
for (Point point : points) {
if (point.x == leftTop.x && point.y == leftTop.y)
continue;
p1[i] = point;
i++;
}
if ((pointSideLine(leftTop, p1[0], p1[1]) * pointSideLine(leftTop, p1[0], p1[2])) < 0) {
result[2] = p1[0];
} else if ((pointSideLine(leftTop, p1[1], p1[0]) * pointSideLine(leftTop, p1[1], p1[2])) < 0) {
result[2] = p1[1];
} else if ((pointSideLine(leftTop, p1[2], p1[0]) * pointSideLine(leftTop, p1[2], p1[1])) < 0) {
result[2] = p1[2];
}
}
if (result[0] != unFoundPoint && result[2] != unFoundPoint) {
Point leftTop = result[0];
Point rightBottom = result[2];
Point[] p1 = new Point[2];
int i = 0;
for (Point point : points) {
if (point.x == leftTop.x && point.y == leftTop.y)
continue;
if (point.x == rightBottom.x && point.y == rightBottom.y)
continue;
p1[i] = point;
i++;
}
if (pointSideLine(leftTop, rightBottom, p1[0]) > 0) {
result[1] = p1[0];
result[3] = p1[1];
} else {
result[1] = p1[1];
result[3] = p1[0];
}
}
if (result[0] != unFoundPoint && result[1] != unFoundPoint && result[2] != unFoundPoint && result[3] != unFoundPoint) {
return result;
}
return points;
}
private static double pointSideLine(Point lineP1, Point lineP2, Point point) {
double x1 = lineP1.x;
double y1 = lineP1.y;
double x2 = lineP2.x;
double y2 = lineP2.y;
double x = point.x;
double y = point.y;
return (x - x1)*(y2 - y1) - (y - y1)*(x2 - x1);
}
}
| 0 | 2,294 | 10 | 2,478 | 12 | 2,611 | 8 | 2,479 | 12 | 2,927 | 12 | false | false | false | false | false | true |
19394_1 | package dynamilize;
/**所有动态对象依赖的接口,描述了动态对象具有的基本行为,关于接口的实现应当由生成器生成。
* <p>实现此接口通常不应该从外部进行,而应当通过{@link DynamicMaker#makeClassInfo(Class, Class[], Class[])}生成,对于生成器生成的实现类应当满足下列行为:
* <ul>
* <li>分配对象保存{@linkplain DataPool 数据池}的字段,字段具有private final修饰符
* <li>分配对象保存{@linkplain DynamicClass 动态类}的字段,字段具有private final修饰符
* <li>对每一个超类构造函数生成相应的构造函数,并正确的调用超类的相应超类构造函数
* 参数前新增两个参数分别传入{@linkplain DataPool 数据池}和{@linkplain DynamicClass 动态类}并分配给成员字段
* <li>按此接口内的方法说明,实现接口的各抽象方法
* </ul>
* 且委托类型的构造函数应当从{@link DynamicMaker}中的几个newInstance调用,否则你必须为之提供合适的构造函数参数
*
* @author EBwilson */
@SuppressWarnings("unchecked")
public interface DynamicObject<Self>{
/**获取对象的动态类型
* <p>生成器实施应当实现此方法返回生成的动态类型字段
*
* @return 此对象的动态类型*/
DynamicClass getDyClass();
/**获得对象的成员变量
* <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#getVariable(String)}方法并返回值
*
* @param name 变量名称
* @return 变量的值*/
IVariable getVariable(String name);
DataPool.ReadOnlyPool baseSuperPointer();
/**设置对象的成员变量
* <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setVariable(IVariable)}方法,自身的参数分别传入
*
* @param variable 将设置的变量*/
void setVariable(IVariable variable);
/**获取对象的某一成员变量的值,若变量尚未定义则会抛出异常
*
* @param name 变量名
* @return 变量值*/
default <T> T getVar(String name){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this);
}
/**为对象的某一变量设置属性值,若在层次结构中未能找到变量则会定义变量
*
* @param name 变量名
* @param value 属性值*/
default <T> void setVar(String name, T value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
<T> T varValueGet(String name);
<T> void varValueSet(String name, T value);
/**使用给出的运算器对指定名称的变量进行处理,并用其计算结果设置变量值
*
* @param name 变量名称
* @param calculator 计算器
* @return 计算结果*/
default <T> T calculateVar(String name, Calculator<T> calculator){
T res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
/**获取对象的函数的匿名函数表示
* <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#select(String, FunctionType)}方法并返回值
*
* @param name 函数名称
* @param type 函数的参数类型
* @return 指定函数的匿名表示*/
IFunctionEntry getFunc(String name, FunctionType type);
default <R> Delegate<R> getFunction(String name, FunctionType type){
IFunctionEntry entry = getFunc(name, type);
if(entry == null)
throw new IllegalHandleException("no such function: " + name + type);
return a -> (R) entry.<Self, R>getFunction().invoke(this, a);
}
default <R> Delegate<R> getFunction(String name, Class<?>... types){
FunctionType type = FunctionType.inst(types);
Delegate<R> f = getFunction(name, type);
type.recycle();
return f;
}
default <R> Function<Self, R> getFunc(String name, Class<?>... types){
FunctionType type = FunctionType.inst(types);
Function<Self, R> f = getFunc(name, type).getFunction();
type.recycle();
return f;
}
/**以lambda模式设置对象的成员函数,lambda模式下对对象的函数变更仅对此对象有效,变更即时生效,
* 若需要使变更对所有实例都生效,则应当对此对象的动态类型引用{@link DynamicClass#visitClass(Class, JavaHandleHelper)}方法变更行为样版
* <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setFunction(String, Function, Class[])}方法,并将参数一一对应传入
* <p><strong>注意,含有泛型的参数,无论类型参数如何,形式参数类型始终为{@link Object}</strong>
*
* @param name 设置的函数名称
* @param func 描述函数行为的匿名函数
* @param argTypes 形式参数的类型列表*/
<R> void setFunc(String name, Function<Self, R> func, Class<?>... argTypes);
<R> void setFunc(String name, Function.SuperGetFunction<Self, R> func, Class<?>... argTypes);
/**与{@link DynamicObject#setFunc(String, Function, Class[])}效果一致,只是传入的函数没有返回值*/
default void setFunc(String name, Function.NonRetFunction<Self> func, Class<?>... argTypes){
setFunc(name, (s, a) -> {
func.invoke(s, a);
return null;
}, argTypes);
}
/**与{@link DynamicObject#setFunc(String, Function.SuperGetFunction, Class[])}效果一致,只是传入的函数没有返回值*/
default void setFunc(String name, Function.NonRetSuperGetFunc<Self> func, Class<?>... argTypes){
setFunc(name, (s, sup, a) -> {
func.invoke(s, sup, a);
return null;
}, argTypes);
}
/**执行对象的指定成员函数
*
* @param name 函数名称
* @param args 传递给函数的实参列表
* @return 函数返回值*/
default <R> R invokeFunc(String name, Object... args){
ArgumentList lis = ArgumentList.as(args);
R r = invokeFunc(name, lis);
lis.type().recycle();
lis.recycle();
return r;
}
/**指明形式参数列表执行对象的指定成员函数,如果参数中有从类型派生的对象或者null值,使用type明确指定形参类型可以有效提升执行效率
*
* @param name 函数名称
* @param args 传递给函数的实参列表
* @return 函数返回值*/
default <R> R invokeFunc(FunctionType type, String name, Object... args){
ArgumentList lis = ArgumentList.asWithType(type, args);
R r = invokeFunc(name, lis);
lis.recycle();
return r;
}
/**直接传入{@link ArgumentList}作为实参列表的函数调用,方法内完成拆箱,便于在匿名函数中对另一函数进行引用而无需拆箱
*
* @param name 函数名称
* @param args 是按列表的封装对象
* @return 函数返回值*/
default <R> R invokeFunc(String name, ArgumentList args){
FunctionType type = args.type();
Function<Self, R> res = getFunc(name, type).getFunction();
if(res == null)
throw new IllegalHandleException("no such method declared: " + name);
return res.invoke( this, args);
}
/**将对象自身经过一次强转换并返回*/
default <T extends Self> T objSelf(){
return (T) this;
}
//primitive getters and setters
//我讨厌装箱类型,是的,相当讨厌......
default boolean getVar(String name, boolean def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default byte getVar(String name, byte def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default short getVar(String name, short def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default int getVar(String name, int def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default long getVar(String name, long def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default float getVar(String name, float def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default double getVar(String name, double def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default void setVar(String name, boolean value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, byte value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, short value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, int value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, long value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, float value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, double value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default boolean calculateVar(String name, Calculator.BoolCalculator calculator){
boolean res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default byte calculateVar(String name, Calculator.ByteCalculator calculator){
byte res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default short calculateVar(String name, Calculator.ShortCalculator calculator){
short res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default int calculateVar(String name, Calculator.IntCalculator calculator){
int res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default long calculateVar(String name, Calculator.LongCalculator calculator){
long res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default float calculateVar(String name, Calculator.FloatCalculator calculator){
float res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default double calculateVar(String name, Calculator.DoubleCalculator calculator){
double res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
}
| EB-wilson/JavaDynamilizer | core/src/main/java/dynamilize/DynamicObject.java | 3,041 | /**获取对象的动态类型
* <p>生成器实施应当实现此方法返回生成的动态类型字段
*
* @return 此对象的动态类型*/ | block_comment | zh-cn | package dynamilize;
/**所有动态对象依赖的接口,描述了动态对象具有的基本行为,关于接口的实现应当由生成器生成。
* <p>实现此接口通常不应该从外部进行,而应当通过{@link DynamicMaker#makeClassInfo(Class, Class[], Class[])}生成,对于生成器生成的实现类应当满足下列行为:
* <ul>
* <li>分配对象保存{@linkplain DataPool 数据池}的字段,字段具有private final修饰符
* <li>分配对象保存{@linkplain DynamicClass 动态类}的字段,字段具有private final修饰符
* <li>对每一个超类构造函数生成相应的构造函数,并正确的调用超类的相应超类构造函数
* 参数前新增两个参数分别传入{@linkplain DataPool 数据池}和{@linkplain DynamicClass 动态类}并分配给成员字段
* <li>按此接口内的方法说明,实现接口的各抽象方法
* </ul>
* 且委托类型的构造函数应当从{@link DynamicMaker}中的几个newInstance调用,否则你必须为之提供合适的构造函数参数
*
* @author EBwilson */
@SuppressWarnings("unchecked")
public interface DynamicObject<Self>{
/**获取对 <SUF>*/
DynamicClass getDyClass();
/**获得对象的成员变量
* <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#getVariable(String)}方法并返回值
*
* @param name 变量名称
* @return 变量的值*/
IVariable getVariable(String name);
DataPool.ReadOnlyPool baseSuperPointer();
/**设置对象的成员变量
* <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setVariable(IVariable)}方法,自身的参数分别传入
*
* @param variable 将设置的变量*/
void setVariable(IVariable variable);
/**获取对象的某一成员变量的值,若变量尚未定义则会抛出异常
*
* @param name 变量名
* @return 变量值*/
default <T> T getVar(String name){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this);
}
/**为对象的某一变量设置属性值,若在层次结构中未能找到变量则会定义变量
*
* @param name 变量名
* @param value 属性值*/
default <T> void setVar(String name, T value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
<T> T varValueGet(String name);
<T> void varValueSet(String name, T value);
/**使用给出的运算器对指定名称的变量进行处理,并用其计算结果设置变量值
*
* @param name 变量名称
* @param calculator 计算器
* @return 计算结果*/
default <T> T calculateVar(String name, Calculator<T> calculator){
T res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
/**获取对象的函数的匿名函数表示
* <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#select(String, FunctionType)}方法并返回值
*
* @param name 函数名称
* @param type 函数的参数类型
* @return 指定函数的匿名表示*/
IFunctionEntry getFunc(String name, FunctionType type);
default <R> Delegate<R> getFunction(String name, FunctionType type){
IFunctionEntry entry = getFunc(name, type);
if(entry == null)
throw new IllegalHandleException("no such function: " + name + type);
return a -> (R) entry.<Self, R>getFunction().invoke(this, a);
}
default <R> Delegate<R> getFunction(String name, Class<?>... types){
FunctionType type = FunctionType.inst(types);
Delegate<R> f = getFunction(name, type);
type.recycle();
return f;
}
default <R> Function<Self, R> getFunc(String name, Class<?>... types){
FunctionType type = FunctionType.inst(types);
Function<Self, R> f = getFunc(name, type).getFunction();
type.recycle();
return f;
}
/**以lambda模式设置对象的成员函数,lambda模式下对对象的函数变更仅对此对象有效,变更即时生效,
* 若需要使变更对所有实例都生效,则应当对此对象的动态类型引用{@link DynamicClass#visitClass(Class, JavaHandleHelper)}方法变更行为样版
* <p>生成器实施应当实现此方法使之调用数据池的{@link DataPool#setFunction(String, Function, Class[])}方法,并将参数一一对应传入
* <p><strong>注意,含有泛型的参数,无论类型参数如何,形式参数类型始终为{@link Object}</strong>
*
* @param name 设置的函数名称
* @param func 描述函数行为的匿名函数
* @param argTypes 形式参数的类型列表*/
<R> void setFunc(String name, Function<Self, R> func, Class<?>... argTypes);
<R> void setFunc(String name, Function.SuperGetFunction<Self, R> func, Class<?>... argTypes);
/**与{@link DynamicObject#setFunc(String, Function, Class[])}效果一致,只是传入的函数没有返回值*/
default void setFunc(String name, Function.NonRetFunction<Self> func, Class<?>... argTypes){
setFunc(name, (s, a) -> {
func.invoke(s, a);
return null;
}, argTypes);
}
/**与{@link DynamicObject#setFunc(String, Function.SuperGetFunction, Class[])}效果一致,只是传入的函数没有返回值*/
default void setFunc(String name, Function.NonRetSuperGetFunc<Self> func, Class<?>... argTypes){
setFunc(name, (s, sup, a) -> {
func.invoke(s, sup, a);
return null;
}, argTypes);
}
/**执行对象的指定成员函数
*
* @param name 函数名称
* @param args 传递给函数的实参列表
* @return 函数返回值*/
default <R> R invokeFunc(String name, Object... args){
ArgumentList lis = ArgumentList.as(args);
R r = invokeFunc(name, lis);
lis.type().recycle();
lis.recycle();
return r;
}
/**指明形式参数列表执行对象的指定成员函数,如果参数中有从类型派生的对象或者null值,使用type明确指定形参类型可以有效提升执行效率
*
* @param name 函数名称
* @param args 传递给函数的实参列表
* @return 函数返回值*/
default <R> R invokeFunc(FunctionType type, String name, Object... args){
ArgumentList lis = ArgumentList.asWithType(type, args);
R r = invokeFunc(name, lis);
lis.recycle();
return r;
}
/**直接传入{@link ArgumentList}作为实参列表的函数调用,方法内完成拆箱,便于在匿名函数中对另一函数进行引用而无需拆箱
*
* @param name 函数名称
* @param args 是按列表的封装对象
* @return 函数返回值*/
default <R> R invokeFunc(String name, ArgumentList args){
FunctionType type = args.type();
Function<Self, R> res = getFunc(name, type).getFunction();
if(res == null)
throw new IllegalHandleException("no such method declared: " + name);
return res.invoke( this, args);
}
/**将对象自身经过一次强转换并返回*/
default <T extends Self> T objSelf(){
return (T) this;
}
//primitive getters and setters
//我讨厌装箱类型,是的,相当讨厌......
default boolean getVar(String name, boolean def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default byte getVar(String name, byte def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default short getVar(String name, short def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default int getVar(String name, int def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default long getVar(String name, long def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default float getVar(String name, float def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default double getVar(String name, double def){
IVariable var = getVariable(name);
if(var == null)
throw new IllegalHandleException("variable " + name + " was not defined");
return var.get(this, def);
}
default void setVar(String name, boolean value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, byte value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, short value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, int value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, long value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, float value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default void setVar(String name, double value){
IVariable var = getVariable(name);
if(var == null){
var = new Variable(name);
setVariable(var);
}
var.set(this, value);
}
default boolean calculateVar(String name, Calculator.BoolCalculator calculator){
boolean res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default byte calculateVar(String name, Calculator.ByteCalculator calculator){
byte res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default short calculateVar(String name, Calculator.ShortCalculator calculator){
short res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default int calculateVar(String name, Calculator.IntCalculator calculator){
int res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default long calculateVar(String name, Calculator.LongCalculator calculator){
long res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default float calculateVar(String name, Calculator.FloatCalculator calculator){
float res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
default double calculateVar(String name, Calculator.DoubleCalculator calculator){
double res;
setVar(name, res = calculator.calculate(getVar(name)));
return res;
}
}
| 0 | 2,824 | 39 | 3,041 | 36 | 3,216 | 36 | 3,041 | 36 | 3,947 | 59 | false | false | false | false | false | true |
29762_1 | package Ai;
import control.GameControl;
import dto.GameInfo;
import dto.Grassman;
import music.Player;
public class Ai {
private GameControl gameControl;
private GameInfo info;
private Grassman aiMan;
private int moveDirection;
private int offendDirection;
public Ai(GameControl gameControl){
this.gameControl = gameControl;
}
/*
* 默认先移动后攻击
*/
public void judgeAction(){
//获取游戏信息
this.info=gameControl.getGameInfo();
//获得当前人物
this.aiMan=gameControl.getGrassman();
//随机移动方向 0 1 2 3 上 下 左 右
moveDirection=(int) (Math.random() * 4);
doAction(moveDirection);
//攻击方向
//随机攻击方向4 5 6 7 上 下 左 右
offendDirection=(int) (Math.random() * 4+4);
//判断四个方向是否有敌人
if(isExistUpEnemy(this.gameControl.judgeWeapon())){
offendDirection=4;
}
if(isExistDownEnemy(this.gameControl.judgeWeapon())){
offendDirection=5;
}
if(isExistLeftEnemy(this.gameControl.judgeWeapon())){
offendDirection=6;
}
if(isExistRightEnemy(this.gameControl.judgeWeapon())){
offendDirection=7;
}
doAction(offendDirection);
}
/*
* 判断攻击范围内是否有敌人
*/
private boolean isExistUpEnemy(int weapon){
//向上有敌人
for (int i = 0; i < 7; i++) {
if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) {
// 该判断为攻击范围是否越界
if (this.aiMan.getXPosition() + aiMan.getOx()[weapon][i] < 0
|| this.aiMan.getXPosition() +aiMan.getOx()[weapon][i] > 9
|| this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] < 0
|| this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] > 9) {
continue;
}
if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] < 4)
&& (info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] > 0))
{
return true;
} else {
return false;
}
}
}
return false;
}
private boolean isExistDownEnemy(int weapon){
//向下有敌人
for (int i = 0; i < 7; i++) {
if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) {
// 该判断为攻击范围是否越界
if (this.aiMan.getXPosition() - aiMan.getOx()[weapon][i] < 0
|| this.aiMan.getXPosition() -aiMan.getOx()[weapon][i] > 9
|| this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] < 0
|| this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] > 9) {
continue;
}
if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] < 4)
&& (info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] > 0))
{
return true;
} else {
return false;
}
}
}
return false;
}
private boolean isExistLeftEnemy(int weapon){
//向左有敌人
for (int i = 0; i < 7; i++) {
if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) {
// 该判断为攻击范围是否越界
if (this.aiMan.getXPosition() - aiMan.getOy()[weapon][i] < 0
|| this.aiMan.getXPosition() -aiMan.getOy()[weapon][i] > 9
|| this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] < 0
|| this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] > 9) {
continue;
}
if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] < 4)
&& (info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] > 0))
{
return true;
} else {
return false;
}
}
}
return false;
}
private boolean isExistRightEnemy(int weapon){
//向右有敌人
for (int i = 0; i < 7; i++) {
if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) {
// 该判断为攻击范围是否越界
if (this.aiMan.getXPosition() + aiMan.getOy()[weapon][i] < 0
|| this.aiMan.getXPosition() +aiMan.getOy()[weapon][i] > 9
|| this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] < 0
|| this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] > 9) {
continue;
}
if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] < 4)
&& (info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] > 0))
{
return true;
} else {
return false;
}
}
}
return false;
}
public void doAction(int cmd){
Player.playSound("攻击");
switch(cmd){
case 0:
if (this.gameControl.canMove()) {
this.gameControl.KeyUp();
// System.out.println(0);
}
break;
case 1:
if (this.gameControl.canMove()) {
this.gameControl.KeyDown();
// System.out.println(1);
}
break;
case 2:
if (this.gameControl.canMove()) {
this.gameControl.KeyLeft();
// System.out.println(2);
}
break;
case 3:
if (this.gameControl.canMove()) {
this.gameControl.KeyRight();
// System.out.println(3);
}
case 4:
if(this.gameControl.canOffend()){
this.gameControl.KeyOffendUp();
// System.out.println(4);
}
break;
case 5:
if(this.gameControl.canOffend()){
this.gameControl.KeyOffendDown();
// System.out.println(5);
}
break;
case 6:
if(this.gameControl.canOffend()){
this.gameControl.KeyOffendLeft();
// System.out.println(6);
}
break;
case 7:
if(this.gameControl.canOffend()){
this.gameControl.KeyOffendRight();
// System.out.println(7);
}
break;
default: System.out.println("出错啦! 你这个大笨蛋!"); break;
}
}
}
| ELCyber/GrassCraft | src/Ai/Ai.java | 2,176 | //获取游戏信息 | line_comment | zh-cn | package Ai;
import control.GameControl;
import dto.GameInfo;
import dto.Grassman;
import music.Player;
public class Ai {
private GameControl gameControl;
private GameInfo info;
private Grassman aiMan;
private int moveDirection;
private int offendDirection;
public Ai(GameControl gameControl){
this.gameControl = gameControl;
}
/*
* 默认先移动后攻击
*/
public void judgeAction(){
//获取 <SUF>
this.info=gameControl.getGameInfo();
//获得当前人物
this.aiMan=gameControl.getGrassman();
//随机移动方向 0 1 2 3 上 下 左 右
moveDirection=(int) (Math.random() * 4);
doAction(moveDirection);
//攻击方向
//随机攻击方向4 5 6 7 上 下 左 右
offendDirection=(int) (Math.random() * 4+4);
//判断四个方向是否有敌人
if(isExistUpEnemy(this.gameControl.judgeWeapon())){
offendDirection=4;
}
if(isExistDownEnemy(this.gameControl.judgeWeapon())){
offendDirection=5;
}
if(isExistLeftEnemy(this.gameControl.judgeWeapon())){
offendDirection=6;
}
if(isExistRightEnemy(this.gameControl.judgeWeapon())){
offendDirection=7;
}
doAction(offendDirection);
}
/*
* 判断攻击范围内是否有敌人
*/
private boolean isExistUpEnemy(int weapon){
//向上有敌人
for (int i = 0; i < 7; i++) {
if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) {
// 该判断为攻击范围是否越界
if (this.aiMan.getXPosition() + aiMan.getOx()[weapon][i] < 0
|| this.aiMan.getXPosition() +aiMan.getOx()[weapon][i] > 9
|| this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] < 0
|| this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] > 9) {
continue;
}
if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] < 4)
&& (info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] > 0))
{
return true;
} else {
return false;
}
}
}
return false;
}
private boolean isExistDownEnemy(int weapon){
//向下有敌人
for (int i = 0; i < 7; i++) {
if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) {
// 该判断为攻击范围是否越界
if (this.aiMan.getXPosition() - aiMan.getOx()[weapon][i] < 0
|| this.aiMan.getXPosition() -aiMan.getOx()[weapon][i] > 9
|| this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] < 0
|| this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] > 9) {
continue;
}
if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] < 4)
&& (info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] > 0))
{
return true;
} else {
return false;
}
}
}
return false;
}
private boolean isExistLeftEnemy(int weapon){
//向左有敌人
for (int i = 0; i < 7; i++) {
if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) {
// 该判断为攻击范围是否越界
if (this.aiMan.getXPosition() - aiMan.getOy()[weapon][i] < 0
|| this.aiMan.getXPosition() -aiMan.getOy()[weapon][i] > 9
|| this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] < 0
|| this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] > 9) {
continue;
}
if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] < 4)
&& (info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] > 0))
{
return true;
} else {
return false;
}
}
}
return false;
}
private boolean isExistRightEnemy(int weapon){
//向右有敌人
for (int i = 0; i < 7; i++) {
if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) {
// 该判断为攻击范围是否越界
if (this.aiMan.getXPosition() + aiMan.getOy()[weapon][i] < 0
|| this.aiMan.getXPosition() +aiMan.getOy()[weapon][i] > 9
|| this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] < 0
|| this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] > 9) {
continue;
}
if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] < 4)
&& (info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] > 0))
{
return true;
} else {
return false;
}
}
}
return false;
}
public void doAction(int cmd){
Player.playSound("攻击");
switch(cmd){
case 0:
if (this.gameControl.canMove()) {
this.gameControl.KeyUp();
// System.out.println(0);
}
break;
case 1:
if (this.gameControl.canMove()) {
this.gameControl.KeyDown();
// System.out.println(1);
}
break;
case 2:
if (this.gameControl.canMove()) {
this.gameControl.KeyLeft();
// System.out.println(2);
}
break;
case 3:
if (this.gameControl.canMove()) {
this.gameControl.KeyRight();
// System.out.println(3);
}
case 4:
if(this.gameControl.canOffend()){
this.gameControl.KeyOffendUp();
// System.out.println(4);
}
break;
case 5:
if(this.gameControl.canOffend()){
this.gameControl.KeyOffendDown();
// System.out.println(5);
}
break;
case 6:
if(this.gameControl.canOffend()){
this.gameControl.KeyOffendLeft();
// System.out.println(6);
}
break;
case 7:
if(this.gameControl.canOffend()){
this.gameControl.KeyOffendRight();
// System.out.println(7);
}
break;
default: System.out.println("出错啦! 你这个大笨蛋!"); break;
}
}
}
| 0 | 1,880 | 4 | 2,176 | 4 | 2,196 | 4 | 2,176 | 4 | 2,911 | 11 | false | false | false | false | false | true |
57884_2 | package io.github.emanual.app.ui;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.io.File;
import java.io.IOException;
import java.util.List;
import butterknife.Bind;
import cz.msebera.android.httpclient.Header;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import io.github.emanual.app.R;
import io.github.emanual.app.api.EmanualAPI;
import io.github.emanual.app.entity.FeedsItemEntity;
import io.github.emanual.app.ui.adapter.FeedsListAdapter;
import io.github.emanual.app.ui.base.activity.SwipeRefreshActivity;
import io.github.emanual.app.ui.event.InterviewDownloadEndEvent;
import io.github.emanual.app.ui.event.InterviewDownloadFaildEvent;
import io.github.emanual.app.ui.event.InterviewDownloadProgressEvent;
import io.github.emanual.app.ui.event.InterviewDownloadStartEvent;
import io.github.emanual.app.ui.event.UnPackFinishEvent;
import io.github.emanual.app.utils.AppPath;
import io.github.emanual.app.utils.SwipeRefreshLayoutUtils;
import io.github.emanual.app.utils.ZipUtils;
import timber.log.Timber;
public class InterviewFeedsActivity extends SwipeRefreshActivity {
ProgressDialog mProgressDialog;
@Bind(R.id.recyclerView) RecyclerView recyclerView;
@Override protected void initData(Bundle savedInstanceState) {
}
@Override protected void initLayout(Bundle savedInstanceState) {
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.acty_feeds_list);
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fetchData();
}
@Override protected int getContentViewId() {
return R.layout.acty_interview_feeds;
}
@Override public void onRefresh() {
// EmanualAPI.getIn
fetchData();
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onDownloadStart(InterviewDownloadStartEvent event) {
mProgressDialog.setTitle("正在下载..");
mProgressDialog.setProgress(0);
mProgressDialog.setMax(100);
mProgressDialog.show();
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onDownloadProgress(InterviewDownloadProgressEvent event) {
Timber.d(event.getBytesWritten() + "/" + event.getTotalSize());
mProgressDialog.setMessage(String.format("大小:%.2f M", 1.0 * event.getTotalSize() / 1024 / 1024));
mProgressDialog.setMax((int) event.getTotalSize());
mProgressDialog.setProgress((int) event.getBytesWritten());
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onDownloadFaild(InterviewDownloadFaildEvent event) {
Toast.makeText(getContext(), "出错了,错误码:" + event.getStatusCode(), Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onDownloadEnd2(InterviewDownloadEndEvent event) {
mProgressDialog.setTitle("正在解压..");
}
/**
* 下载完毕
* @param event
*/
@Subscribe(threadMode = ThreadMode.Async)
public void onDownloadEnd(InterviewDownloadEndEvent event) {
try {
ZipUtils.unZipFiles(event.getFile().getAbsolutePath(), AppPath.getInterviewsPath(getContext()) + File.separator + event.getFeedsItemEntity().getName() + File.separator);
//删除压缩包
if (event.getFile().exists()) {
event.getFile().delete();
}
} catch (IOException e) {
e.printStackTrace();
EventBus.getDefault().post(new UnPackFinishEvent(e));
return;
}
EventBus.getDefault().post(new UnPackFinishEvent(null));
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onUnpackFinishEvent(UnPackFinishEvent event) {
if (event.getException() != null) {
toast(event.getException().getMessage());
return;
}
toast("下载并解压成功");
mProgressDialog.dismiss();
}
private void fetchData() {
EmanualAPI.getInterviewFeeds(new AsyncHttpResponseHandler() {
@Override public void onStart() {
super.onStart();
SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), true);
}
@Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
List<FeedsItemEntity> feeds = FeedsItemEntity.createByJSONArray(new String(responseBody), FeedsItemEntity.class);
Timber.d(feeds.toString());
recyclerView.setAdapter(new FeedsListAdapter(getContext(), feeds, FeedsListAdapter.TYPE_INTERVIEW));
} catch (Exception e) {
toast("哎呀,网络异常!");
}
}
@Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
@Override public void onFinish() {
super.onFinish();
SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), false);
}
@Override public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
}
});
}
}
| EManual/EManual-Android | app/src/main/java/io/github/emanual/app/ui/InterviewFeedsActivity.java | 1,433 | //删除压缩包 | line_comment | zh-cn | package io.github.emanual.app.ui;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpResponseHandler;
import java.io.File;
import java.io.IOException;
import java.util.List;
import butterknife.Bind;
import cz.msebera.android.httpclient.Header;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import io.github.emanual.app.R;
import io.github.emanual.app.api.EmanualAPI;
import io.github.emanual.app.entity.FeedsItemEntity;
import io.github.emanual.app.ui.adapter.FeedsListAdapter;
import io.github.emanual.app.ui.base.activity.SwipeRefreshActivity;
import io.github.emanual.app.ui.event.InterviewDownloadEndEvent;
import io.github.emanual.app.ui.event.InterviewDownloadFaildEvent;
import io.github.emanual.app.ui.event.InterviewDownloadProgressEvent;
import io.github.emanual.app.ui.event.InterviewDownloadStartEvent;
import io.github.emanual.app.ui.event.UnPackFinishEvent;
import io.github.emanual.app.utils.AppPath;
import io.github.emanual.app.utils.SwipeRefreshLayoutUtils;
import io.github.emanual.app.utils.ZipUtils;
import timber.log.Timber;
public class InterviewFeedsActivity extends SwipeRefreshActivity {
ProgressDialog mProgressDialog;
@Bind(R.id.recyclerView) RecyclerView recyclerView;
@Override protected void initData(Bundle savedInstanceState) {
}
@Override protected void initLayout(Bundle savedInstanceState) {
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(R.string.acty_feeds_list);
mProgressDialog = new ProgressDialog(getContext());
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
fetchData();
}
@Override protected int getContentViewId() {
return R.layout.acty_interview_feeds;
}
@Override public void onRefresh() {
// EmanualAPI.getIn
fetchData();
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onDownloadStart(InterviewDownloadStartEvent event) {
mProgressDialog.setTitle("正在下载..");
mProgressDialog.setProgress(0);
mProgressDialog.setMax(100);
mProgressDialog.show();
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onDownloadProgress(InterviewDownloadProgressEvent event) {
Timber.d(event.getBytesWritten() + "/" + event.getTotalSize());
mProgressDialog.setMessage(String.format("大小:%.2f M", 1.0 * event.getTotalSize() / 1024 / 1024));
mProgressDialog.setMax((int) event.getTotalSize());
mProgressDialog.setProgress((int) event.getBytesWritten());
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onDownloadFaild(InterviewDownloadFaildEvent event) {
Toast.makeText(getContext(), "出错了,错误码:" + event.getStatusCode(), Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onDownloadEnd2(InterviewDownloadEndEvent event) {
mProgressDialog.setTitle("正在解压..");
}
/**
* 下载完毕
* @param event
*/
@Subscribe(threadMode = ThreadMode.Async)
public void onDownloadEnd(InterviewDownloadEndEvent event) {
try {
ZipUtils.unZipFiles(event.getFile().getAbsolutePath(), AppPath.getInterviewsPath(getContext()) + File.separator + event.getFeedsItemEntity().getName() + File.separator);
//删除 <SUF>
if (event.getFile().exists()) {
event.getFile().delete();
}
} catch (IOException e) {
e.printStackTrace();
EventBus.getDefault().post(new UnPackFinishEvent(e));
return;
}
EventBus.getDefault().post(new UnPackFinishEvent(null));
}
@Subscribe(threadMode = ThreadMode.MainThread)
public void onUnpackFinishEvent(UnPackFinishEvent event) {
if (event.getException() != null) {
toast(event.getException().getMessage());
return;
}
toast("下载并解压成功");
mProgressDialog.dismiss();
}
private void fetchData() {
EmanualAPI.getInterviewFeeds(new AsyncHttpResponseHandler() {
@Override public void onStart() {
super.onStart();
SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), true);
}
@Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
try {
List<FeedsItemEntity> feeds = FeedsItemEntity.createByJSONArray(new String(responseBody), FeedsItemEntity.class);
Timber.d(feeds.toString());
recyclerView.setAdapter(new FeedsListAdapter(getContext(), feeds, FeedsListAdapter.TYPE_INTERVIEW));
} catch (Exception e) {
toast("哎呀,网络异常!");
}
}
@Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
@Override public void onFinish() {
super.onFinish();
SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), false);
}
@Override public void onProgress(long bytesWritten, long totalSize) {
super.onProgress(bytesWritten, totalSize);
}
});
}
}
| 0 | 1,133 | 4 | 1,433 | 4 | 1,435 | 4 | 1,433 | 4 | 1,712 | 10 | false | false | false | false | false | true |
40957_21 | package com.cn.main;
import com.cn.util.HttpClientUtil;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class nyaPictureMain {
//存放目录
private static String fileSource = "E://nyaManhua//new//";
public static void main(String[] args) throws Exception {
List<String> urlList = new ArrayList<String>();
//地址
urlList.add("https://zha.doghentai.com/g/338012/");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
nyaPictureMain.crawlerNyaUrl(urlList);
String exSite = "cmd /c start " + fileSource ;
Runtime.getRuntime().exec(exSite);
}
public static void crawlerNyaPic(int picSum,String fileUrl,String intputFile,String suffix){
try {
for (int i = 1; i <= picSum; i++) {
// suffix = ".jpg"; //随时替换文件格式
CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例
HttpGet httpGet = new HttpGet(fileUrl+i+suffix); // 创建Httpget实例
//设置Http报文头信息
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");
httpGet.setHeader("accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8");
httpGet.setHeader("accept-encoding", "gzip, deflate, br");
httpGet.setHeader("referer", "https://zha.doghentai.com/");
httpGet.setHeader("sec-fetch-dest", "image");
httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8");
HttpHost proxy = new HttpHost("127.0.0.1", 7890);
//超时时间单位为毫秒
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(1000).setSocketTimeout(30000)
.setProxy(proxy).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
CloseableHttpResponse response = null;
response = httpClient.execute(httpGet); // 执行http get请求
HttpEntity entity = response.getEntity(); // 获取返回实体
if(null != entity){
InputStream inputStream = entity.getContent();//返回一个输入流
//输出图片
FileUtils.copyInputStreamToFile(inputStream, new File(intputFile+i+suffix));//引用org.apache.commons.io.FileUtils
System.out.println(i+suffix);
}
response.close(); // 关闭response
httpClient.close(); // 关闭HttpClient实体
}
}catch (Exception e){
System.out.println(e);
}
}
public static void crawlerNyaUrl(List<String> urlList) throws Exception {
Integer rateDow = 1;
for(String url:urlList){
String html = "";
if(url.length() != 0){
html = HttpClientUtil.getSource(url);
Document document = Jsoup.parse(html);
Element element = document.selectFirst("div.container").selectFirst("a");
String coverImgUrl = element.select("img").attr("data-src");
//获取图片载点
String[] ourStr = coverImgUrl.split("/");
//获取后缀
String[] oursuffix = coverImgUrl.split("\\.");
//获取数量
Elements picSum = document.select("div.thumb-container");
//获取本子名字
String benziName = element.select("img").attr("alt");
benziName = benziName.replaceAll("\\?","").replaceAll(":","").replaceAll(" ","").replaceAll("\\*","");
int count = picSum.size();
int benziN = Integer.parseInt(ourStr[ourStr.length-2]);
String suffix = "."+oursuffix[oursuffix.length-1];
String fileUrl = "https://i0.nyacdn.com/galleries/"+benziN+"/";
String intputFile = fileSource +benziName +"//";
nyaPictureMain.crawlerNyaPic(count,fileUrl,intputFile,suffix);
//缓存完后暂停几秒
Thread.sleep(3000);
}
}
System.out.println("喵变态图片缓存成功!!!!");
}
}
| ERYhua/nyaHentaiCrawler | src/main/java/com/cn/main/nyaPictureMain.java | 1,357 | //缓存完后暂停几秒 | line_comment | zh-cn | package com.cn.main;
import com.cn.util.HttpClientUtil;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class nyaPictureMain {
//存放目录
private static String fileSource = "E://nyaManhua//new//";
public static void main(String[] args) throws Exception {
List<String> urlList = new ArrayList<String>();
//地址
urlList.add("https://zha.doghentai.com/g/338012/");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
urlList.add("");
nyaPictureMain.crawlerNyaUrl(urlList);
String exSite = "cmd /c start " + fileSource ;
Runtime.getRuntime().exec(exSite);
}
public static void crawlerNyaPic(int picSum,String fileUrl,String intputFile,String suffix){
try {
for (int i = 1; i <= picSum; i++) {
// suffix = ".jpg"; //随时替换文件格式
CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例
HttpGet httpGet = new HttpGet(fileUrl+i+suffix); // 创建Httpget实例
//设置Http报文头信息
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36");
httpGet.setHeader("accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8");
httpGet.setHeader("accept-encoding", "gzip, deflate, br");
httpGet.setHeader("referer", "https://zha.doghentai.com/");
httpGet.setHeader("sec-fetch-dest", "image");
httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8");
HttpHost proxy = new HttpHost("127.0.0.1", 7890);
//超时时间单位为毫秒
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(1000).setSocketTimeout(30000)
.setProxy(proxy).build();
httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
CloseableHttpResponse response = null;
response = httpClient.execute(httpGet); // 执行http get请求
HttpEntity entity = response.getEntity(); // 获取返回实体
if(null != entity){
InputStream inputStream = entity.getContent();//返回一个输入流
//输出图片
FileUtils.copyInputStreamToFile(inputStream, new File(intputFile+i+suffix));//引用org.apache.commons.io.FileUtils
System.out.println(i+suffix);
}
response.close(); // 关闭response
httpClient.close(); // 关闭HttpClient实体
}
}catch (Exception e){
System.out.println(e);
}
}
public static void crawlerNyaUrl(List<String> urlList) throws Exception {
Integer rateDow = 1;
for(String url:urlList){
String html = "";
if(url.length() != 0){
html = HttpClientUtil.getSource(url);
Document document = Jsoup.parse(html);
Element element = document.selectFirst("div.container").selectFirst("a");
String coverImgUrl = element.select("img").attr("data-src");
//获取图片载点
String[] ourStr = coverImgUrl.split("/");
//获取后缀
String[] oursuffix = coverImgUrl.split("\\.");
//获取数量
Elements picSum = document.select("div.thumb-container");
//获取本子名字
String benziName = element.select("img").attr("alt");
benziName = benziName.replaceAll("\\?","").replaceAll(":","").replaceAll(" ","").replaceAll("\\*","");
int count = picSum.size();
int benziN = Integer.parseInt(ourStr[ourStr.length-2]);
String suffix = "."+oursuffix[oursuffix.length-1];
String fileUrl = "https://i0.nyacdn.com/galleries/"+benziN+"/";
String intputFile = fileSource +benziName +"//";
nyaPictureMain.crawlerNyaPic(count,fileUrl,intputFile,suffix);
//缓存 <SUF>
Thread.sleep(3000);
}
}
System.out.println("喵变态图片缓存成功!!!!");
}
}
| 0 | 1,160 | 8 | 1,357 | 8 | 1,404 | 7 | 1,357 | 8 | 1,662 | 19 | false | false | false | false | false | true |
50426_10 | package exp.libs.ui.cpt.win;
import exp.libs.utils.concurrent.ThreadUtils;
/**
* <PRE>
* swing右下角通知窗口
* (使用_show方法显示窗体, 可触发自动渐隐消失)
* </PRE>
* <br/><B>PROJECT : </B> exp-libs
* <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a>
* @version 2022-03-06
* @author EXP: exp.lqb@foxmail.com
* @since JDK 1.8+
*/
@SuppressWarnings("serial")
public abstract class NoticeWindow extends PopChildWindow implements Runnable {
private Thread _this;
private boolean isRun = false;
protected NoticeWindow() {
super("NoticeWindow");
}
protected NoticeWindow(String name) {
super(name);
}
protected NoticeWindow(String name, int width, int height) {
super(name, width, height);
}
protected NoticeWindow(String name, int width, int height, boolean relative) {
super(name, width, height, relative);
}
protected NoticeWindow(String name, int width, int height, boolean relative, Object... args) {
super(name, width, height, relative, args);
}
@Override
protected int LOCATION() {
return LOCATION_RB; // 出现坐标为右下角
}
@Override
protected boolean WIN_ON_TOP() {
return true; // 设置窗口置顶
}
/**
* 以渐隐方式显示通知消息
*/
@Override
protected final void AfterView() {
if(isRun == false) {
isRun = true;
_this = new Thread(this);
_this.start(); // 渐隐窗体
}
}
@Deprecated
@Override
protected final void beforeHide() {
// Undo
}
@Override
public void run() {
ThreadUtils.tSleep(2000); // 悬停2秒
// 透明度渐隐(大约持续3秒)
for(float opacity = 100; opacity > 0; opacity -= 2) {
this.setOpacity(opacity / 100); // 设置透明度
ThreadUtils.tSleep(60);
if(isVisible() == false) {
break; // 窗体被提前销毁了(手工点了X)
}
}
_hide(); // 销毁窗体
}
/**
* 阻塞等待渐隐关闭过程
*/
public void _join() {
if(_this == null) {
return;
}
try {
_this.join();
} catch (Exception e) {}
}
}
| EXP-Codes/exp-libs-refactor | exp-libs-ui/src/main/java/exp/libs/ui/cpt/win/NoticeWindow.java | 724 | // 销毁窗体 | line_comment | zh-cn | package exp.libs.ui.cpt.win;
import exp.libs.utils.concurrent.ThreadUtils;
/**
* <PRE>
* swing右下角通知窗口
* (使用_show方法显示窗体, 可触发自动渐隐消失)
* </PRE>
* <br/><B>PROJECT : </B> exp-libs
* <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a>
* @version 2022-03-06
* @author EXP: exp.lqb@foxmail.com
* @since JDK 1.8+
*/
@SuppressWarnings("serial")
public abstract class NoticeWindow extends PopChildWindow implements Runnable {
private Thread _this;
private boolean isRun = false;
protected NoticeWindow() {
super("NoticeWindow");
}
protected NoticeWindow(String name) {
super(name);
}
protected NoticeWindow(String name, int width, int height) {
super(name, width, height);
}
protected NoticeWindow(String name, int width, int height, boolean relative) {
super(name, width, height, relative);
}
protected NoticeWindow(String name, int width, int height, boolean relative, Object... args) {
super(name, width, height, relative, args);
}
@Override
protected int LOCATION() {
return LOCATION_RB; // 出现坐标为右下角
}
@Override
protected boolean WIN_ON_TOP() {
return true; // 设置窗口置顶
}
/**
* 以渐隐方式显示通知消息
*/
@Override
protected final void AfterView() {
if(isRun == false) {
isRun = true;
_this = new Thread(this);
_this.start(); // 渐隐窗体
}
}
@Deprecated
@Override
protected final void beforeHide() {
// Undo
}
@Override
public void run() {
ThreadUtils.tSleep(2000); // 悬停2秒
// 透明度渐隐(大约持续3秒)
for(float opacity = 100; opacity > 0; opacity -= 2) {
this.setOpacity(opacity / 100); // 设置透明度
ThreadUtils.tSleep(60);
if(isVisible() == false) {
break; // 窗体被提前销毁了(手工点了X)
}
}
_hide(); // 销毁 <SUF>
}
/**
* 阻塞等待渐隐关闭过程
*/
public void _join() {
if(_this == null) {
return;
}
try {
_this.join();
} catch (Exception e) {}
}
}
| 0 | 622 | 6 | 724 | 7 | 737 | 5 | 724 | 7 | 921 | 12 | false | false | false | false | false | true |
23210_2 | import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author yangda
* @description:
* @create 2023-05-21-14:53
*/
public class MyTomcat {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
int i = 0;
while (!serverSocket.isClosed()){ // 如果serverSocket 没有关闭
System.out.println("f服务器等待连接、、、" + ++i);
// 等待浏览器/客户端连接,得到socket
// 该socket用于通信
Socket socket = serverSocket.accept();
// 拿到 和socket相关的输出流
OutputStream outputStream = socket.getOutputStream();
FileReader fileReader = new FileReader("src/hello.html");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String buf = "";
while ((buf = bufferedReader.readLine()) != null){
outputStream.write(buf.getBytes());
}
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
// outputStream.write("hello i am server".getBytes());
System.out.println("信息以打入管道" );
outputStream.close();
socket.close();
}
serverSocket.close();
}
}
| EXsYang/mycode | javaweb/tomcat/src/MyTomcat.java | 311 | // 等待浏览器/客户端连接,得到socket | line_comment | zh-cn | import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* @author yangda
* @description:
* @create 2023-05-21-14:53
*/
public class MyTomcat {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(9999);
int i = 0;
while (!serverSocket.isClosed()){ // 如果serverSocket 没有关闭
System.out.println("f服务器等待连接、、、" + ++i);
// 等待 <SUF>
// 该socket用于通信
Socket socket = serverSocket.accept();
// 拿到 和socket相关的输出流
OutputStream outputStream = socket.getOutputStream();
FileReader fileReader = new FileReader("src/hello.html");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String buf = "";
while ((buf = bufferedReader.readLine()) != null){
outputStream.write(buf.getBytes());
}
// BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
// outputStream.write("hello i am server".getBytes());
System.out.println("信息以打入管道" );
outputStream.close();
socket.close();
}
serverSocket.close();
}
}
| 0 | 274 | 12 | 311 | 10 | 315 | 10 | 311 | 10 | 390 | 25 | false | false | false | false | false | true |
36401_4 | package name.ealen.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Set;
/**
* Created by EalenXie on 2018/10/16 16:13.
* 典型的 多层级 分类
* <p>
* :@NamedEntityGraph :注解在实体上 , 解决典型的N+1问题
* name表示实体图名, 与 repository中的注解 @EntityGraph的value属性相对应,
* attributeNodes 表示被标注要懒加载的属性节点 比如此例中 : 要懒加载的子分类集合children
*/
@Entity
@Table(name = "jpa_category")
@NamedEntityGraphs({
@NamedEntityGraph(name = "Category.findAll", attributeNodes = {@NamedAttributeNode("children")}),
@NamedEntityGraph(name = "Category.findByParent",
attributeNodes = {@NamedAttributeNode(value = "children", subgraph = "son")}, //一级延伸
subgraphs = {@NamedSubgraph(name = "son", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "grandson")), //二级延伸
@NamedSubgraph(name = "grandson", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "greatGrandSon")), //三级延伸
@NamedSubgraph(name = "greatGrandSon", attributeNodes = @NamedAttributeNode(value = "children"))}) //四级延伸
// 有多少次延伸,就有多少个联表关系,自身关联的表设计中,子节点是可以无限延伸的,所以关联数可能查询的.....
})
public class Category {
/**
* Id 使用UUID生成策略
*/
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private String id;
/**
* 分类名
*/
private String name;
/**
* 一个商品分类下面可能有多个商品子分类(多级) 比如 分类 : 家用电器 (子)分类 : 电脑 (孙)子分类 : 笔记本电脑
*/
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
@JsonIgnore
private Category parent; //父分类
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private Set<Category> children; //子分类集合
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
public Set<Category> getChildren() {
return children;
}
public void setChildren(Set<Category> children) {
this.children = children;
}
}
| EalenXie/springboot-jpa-N-plus-One | src/main/java/name/ealen/entity/Category.java | 743 | //四级延伸 | line_comment | zh-cn | package name.ealen.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Set;
/**
* Created by EalenXie on 2018/10/16 16:13.
* 典型的 多层级 分类
* <p>
* :@NamedEntityGraph :注解在实体上 , 解决典型的N+1问题
* name表示实体图名, 与 repository中的注解 @EntityGraph的value属性相对应,
* attributeNodes 表示被标注要懒加载的属性节点 比如此例中 : 要懒加载的子分类集合children
*/
@Entity
@Table(name = "jpa_category")
@NamedEntityGraphs({
@NamedEntityGraph(name = "Category.findAll", attributeNodes = {@NamedAttributeNode("children")}),
@NamedEntityGraph(name = "Category.findByParent",
attributeNodes = {@NamedAttributeNode(value = "children", subgraph = "son")}, //一级延伸
subgraphs = {@NamedSubgraph(name = "son", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "grandson")), //二级延伸
@NamedSubgraph(name = "grandson", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "greatGrandSon")), //三级延伸
@NamedSubgraph(name = "greatGrandSon", attributeNodes = @NamedAttributeNode(value = "children"))}) //四级 <SUF>
// 有多少次延伸,就有多少个联表关系,自身关联的表设计中,子节点是可以无限延伸的,所以关联数可能查询的.....
})
public class Category {
/**
* Id 使用UUID生成策略
*/
@Id
@GeneratedValue(generator = "UUID")
@GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator")
private String id;
/**
* 分类名
*/
private String name;
/**
* 一个商品分类下面可能有多个商品子分类(多级) 比如 分类 : 家用电器 (子)分类 : 电脑 (孙)子分类 : 笔记本电脑
*/
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
@JsonIgnore
private Category parent; //父分类
@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private Set<Category> children; //子分类集合
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getParent() {
return parent;
}
public void setParent(Category parent) {
this.parent = parent;
}
public Set<Category> getChildren() {
return children;
}
public void setChildren(Set<Category> children) {
this.children = children;
}
}
| 0 | 658 | 3 | 743 | 6 | 736 | 4 | 743 | 6 | 949 | 11 | false | false | false | false | false | true |
41467_46 | package leetcode.One.Thousand.boxDelivering;
//你有一辆货运卡车,你需要用这一辆车把一些箱子从仓库运送到码头。这辆卡车每次运输有 箱子数目的限制 和 总重量的限制 。
//
// 给你一个箱子数组 boxes 和三个整数 portsCount, maxBoxes 和 maxWeight ,其中 boxes[i] = [portsi,
// weighti] 。
//
//
// portsi 表示第 i 个箱子需要送达的码头, weightsi 是第 i 个箱子的重量。
// portsCount 是码头的数目。
// maxBoxes 和 maxWeight 分别是卡车每趟运输箱子数目和重量的限制。
//
//
// 箱子需要按照 数组顺序 运输,同时每次运输需要遵循以下步骤:
//
//
// 卡车从 boxes 队列中按顺序取出若干个箱子,但不能违反 maxBoxes 和 maxWeight 限制。
// 对于在卡车上的箱子,我们需要 按顺序 处理它们,卡车会通过 一趟行程 将最前面的箱子送到目的地码头并卸货。如果卡车已经在对应的码头,那么不需要 额外行程
//,箱子也会立马被卸货。
// 卡车上所有箱子都被卸货后,卡车需要 一趟行程 回到仓库,从箱子队列里再取出一些箱子。
//
//
// 卡车在将所有箱子运输并卸货后,最后必须回到仓库。
//
// 请你返回将所有箱子送到相应码头的 最少行程 次数。
//
//
//
// 示例 1:
//
// 输入:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
//输出:4
//解释:最优策略如下:
//- 卡车将所有箱子装上车,到达码头 1 ,然后去码头 2 ,然后再回到码头 1 ,最后回到仓库,总共需要 4 趟行程。
//所以总行程数为 4 。
//注意到第一个和第三个箱子不能同时被卸货,因为箱子需要按顺序处理(也就是第二个箱子需要先被送到码头 2 ,然后才能处理第三个箱子)。
//
//
// 示例 2:
//
// 输入:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3,
//maxWeight = 6
//输出:6
//解释:最优策略如下:
//- 卡车首先运输第一个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第二、第三、第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第五个箱子,到达码头 3 ,回到仓库,总共 2 趟行程。
//总行程数为 2 + 2 + 2 = 6 。
//
//
// 示例 3:
//
// 输入:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes =
//6, maxWeight = 7
//输出:6
//解释:最优策略如下:
//- 卡车运输第一和第二个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第三和第四个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第五和第六个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
//总行程数为 2 + 2 + 2 = 6 。
//
//
// 示例 4:
//
// 输入:boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]],
//portsCount = 5, maxBoxes = 5, maxWeight = 7
//输出:14
//解释:最优策略如下:
//- 卡车运输第一个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第二个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第三和第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第五个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第六和第七个箱子,到达码头 3 ,然后去码头 4 ,然后回到仓库,总共 3 趟行程。
//- 卡车运输第八和第九个箱子,到达码头 1 ,然后去码头 5 ,然后回到仓库,总共 3 趟行程。
//总行程数为 2 + 2 + 2 + 2 + 3 + 3 = 14 。
//
//
//
//
// 提示:
//
//
// 1 <= boxes.length <= 10⁵
// 1 <= portsCount, maxBoxes, maxWeight <= 10⁵
// 1 <= portsi <= portsCount
// 1 <= weightsi <= maxWeight
//
// Related Topics 线段树 队列 数组 动态规划 单调队列 堆(优先队列) 👍 106 👎 0
import java.util.ArrayDeque;
import java.util.Deque;
/**
* @Desc:
* @Author: 泽露
* @Date: 2022/12/5 5:22 PM
* @Version: 1.initial version; 2022/12/5 5:22 PM
*/
public class Solution {
public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {
int n = boxes.length;
int[] p = new int[n + 1];
int[] w = new int[n + 1];
int[] neg = new int[n + 1];
long[] W = new long[n + 1];
for (int i = 1; i <= n; ++i) {
p[i] = boxes[i - 1][0];
w[i] = boxes[i - 1][1];
if (i > 1) {
neg[i] = neg[i - 1] + (p[i - 1] != p[i] ? 1 : 0);
}
W[i] = W[i - 1] + w[i];
}
Deque<Integer> opt = new ArrayDeque<Integer>();
opt.offerLast(0);
int[] f = new int[n + 1];
int[] g = new int[n + 1];
for (int i = 1; i <= n; ++i) {
while (i - opt.peekFirst() > maxBoxes || W[i] - W[opt.peekFirst()] > maxWeight) {
opt.pollFirst();
}
f[i] = g[opt.peekFirst()] + neg[i] + 2;
if (i != n) {
g[i] = f[i] - neg[i + 1];
while (!opt.isEmpty() && g[i] <= g[opt.peekLast()]) {
opt.pollLast();
}
opt.offerLast(i);
}
}
return f[n];
}
}
| EarWheat/LeetCode | src/main/java/leetcode/One/Thousand/boxDelivering/Solution.java | 1,965 | //- 卡车运输第五个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 | line_comment | zh-cn | package leetcode.One.Thousand.boxDelivering;
//你有一辆货运卡车,你需要用这一辆车把一些箱子从仓库运送到码头。这辆卡车每次运输有 箱子数目的限制 和 总重量的限制 。
//
// 给你一个箱子数组 boxes 和三个整数 portsCount, maxBoxes 和 maxWeight ,其中 boxes[i] = [portsi,
// weighti] 。
//
//
// portsi 表示第 i 个箱子需要送达的码头, weightsi 是第 i 个箱子的重量。
// portsCount 是码头的数目。
// maxBoxes 和 maxWeight 分别是卡车每趟运输箱子数目和重量的限制。
//
//
// 箱子需要按照 数组顺序 运输,同时每次运输需要遵循以下步骤:
//
//
// 卡车从 boxes 队列中按顺序取出若干个箱子,但不能违反 maxBoxes 和 maxWeight 限制。
// 对于在卡车上的箱子,我们需要 按顺序 处理它们,卡车会通过 一趟行程 将最前面的箱子送到目的地码头并卸货。如果卡车已经在对应的码头,那么不需要 额外行程
//,箱子也会立马被卸货。
// 卡车上所有箱子都被卸货后,卡车需要 一趟行程 回到仓库,从箱子队列里再取出一些箱子。
//
//
// 卡车在将所有箱子运输并卸货后,最后必须回到仓库。
//
// 请你返回将所有箱子送到相应码头的 最少行程 次数。
//
//
//
// 示例 1:
//
// 输入:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3
//输出:4
//解释:最优策略如下:
//- 卡车将所有箱子装上车,到达码头 1 ,然后去码头 2 ,然后再回到码头 1 ,最后回到仓库,总共需要 4 趟行程。
//所以总行程数为 4 。
//注意到第一个和第三个箱子不能同时被卸货,因为箱子需要按顺序处理(也就是第二个箱子需要先被送到码头 2 ,然后才能处理第三个箱子)。
//
//
// 示例 2:
//
// 输入:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3,
//maxWeight = 6
//输出:6
//解释:最优策略如下:
//- 卡车首先运输第一个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第二、第三、第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第五个箱子,到达码头 3 ,回到仓库,总共 2 趟行程。
//总行程数为 2 + 2 + 2 = 6 。
//
//
// 示例 3:
//
// 输入:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes =
//6, maxWeight = 7
//输出:6
//解释:最优策略如下:
//- 卡车运输第一和第二个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第三和第四个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第五和第六个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
//总行程数为 2 + 2 + 2 = 6 。
//
//
// 示例 4:
//
// 输入:boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]],
//portsCount = 5, maxBoxes = 5, maxWeight = 7
//输出:14
//解释:最优策略如下:
//- 卡车运输第一个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第二个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。
//- 卡车运输第三和第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
//- <SUF>
//- 卡车运输第六和第七个箱子,到达码头 3 ,然后去码头 4 ,然后回到仓库,总共 3 趟行程。
//- 卡车运输第八和第九个箱子,到达码头 1 ,然后去码头 5 ,然后回到仓库,总共 3 趟行程。
//总行程数为 2 + 2 + 2 + 2 + 3 + 3 = 14 。
//
//
//
//
// 提示:
//
//
// 1 <= boxes.length <= 10⁵
// 1 <= portsCount, maxBoxes, maxWeight <= 10⁵
// 1 <= portsi <= portsCount
// 1 <= weightsi <= maxWeight
//
// Related Topics 线段树 队列 数组 动态规划 单调队列 堆(优先队列) 👍 106 👎 0
import java.util.ArrayDeque;
import java.util.Deque;
/**
* @Desc:
* @Author: 泽露
* @Date: 2022/12/5 5:22 PM
* @Version: 1.initial version; 2022/12/5 5:22 PM
*/
public class Solution {
public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) {
int n = boxes.length;
int[] p = new int[n + 1];
int[] w = new int[n + 1];
int[] neg = new int[n + 1];
long[] W = new long[n + 1];
for (int i = 1; i <= n; ++i) {
p[i] = boxes[i - 1][0];
w[i] = boxes[i - 1][1];
if (i > 1) {
neg[i] = neg[i - 1] + (p[i - 1] != p[i] ? 1 : 0);
}
W[i] = W[i - 1] + w[i];
}
Deque<Integer> opt = new ArrayDeque<Integer>();
opt.offerLast(0);
int[] f = new int[n + 1];
int[] g = new int[n + 1];
for (int i = 1; i <= n; ++i) {
while (i - opt.peekFirst() > maxBoxes || W[i] - W[opt.peekFirst()] > maxWeight) {
opt.pollFirst();
}
f[i] = g[opt.peekFirst()] + neg[i] + 2;
if (i != n) {
g[i] = f[i] - neg[i + 1];
while (!opt.isEmpty() && g[i] <= g[opt.peekLast()]) {
opt.pollLast();
}
opt.offerLast(i);
}
}
return f[n];
}
}
| 0 | 1,631 | 26 | 1,965 | 35 | 1,797 | 27 | 1,965 | 35 | 2,585 | 49 | false | false | false | false | false | true |
46861_2 | package JavaBasicAPI;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import BrowserDrivers.GetBrowserDriver;
//10.27
public class GetWebElementAttributeTesting {
public WebDriver driver;
@Test
public void getWebElementAttributeTest() throws InterruptedException {
driver.get("http://www.baidu.com");
String text="比利时遭遇恐怖袭击";
WebElement SearchBox = driver.findElement(By.id("kw")); //将搜索框的id实例化
SearchBox.sendKeys(text);
String innerText = SearchBox.getAttribute("value"); //调用attribute方法,并获取搜索框value的值(就是搜索文字的内容)
Thread.sleep(3000);
Assert.assertEquals(innerText, "比利时遭遇恐怖袭击");
}
@BeforeMethod
public void beforeMethod() {
driver = GetBrowserDriver.GetChromeDriver();
}
@AfterMethod
public void afterMethod() {
driver.quit();
}
}
| Eason0731/MySeleniumCases | src/JavaBasicAPI/GetWebElementAttributeTesting.java | 304 | //将搜索框的id实例化 | line_comment | zh-cn | package JavaBasicAPI;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import BrowserDrivers.GetBrowserDriver;
//10.27
public class GetWebElementAttributeTesting {
public WebDriver driver;
@Test
public void getWebElementAttributeTest() throws InterruptedException {
driver.get("http://www.baidu.com");
String text="比利时遭遇恐怖袭击";
WebElement SearchBox = driver.findElement(By.id("kw")); //将搜 <SUF>
SearchBox.sendKeys(text);
String innerText = SearchBox.getAttribute("value"); //调用attribute方法,并获取搜索框value的值(就是搜索文字的内容)
Thread.sleep(3000);
Assert.assertEquals(innerText, "比利时遭遇恐怖袭击");
}
@BeforeMethod
public void beforeMethod() {
driver = GetBrowserDriver.GetChromeDriver();
}
@AfterMethod
public void afterMethod() {
driver.quit();
}
}
| 0 | 238 | 8 | 304 | 8 | 325 | 8 | 304 | 8 | 409 | 14 | false | false | false | false | false | true |
38290_63 | package com.example.woops.cookit.activity;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.woops.cookit.R;
import com.example.woops.cookit.bean.Store;
import com.example.woops.cookit.db.CookitDB;
import com.example.woops.cookit.test.SpliteGenerate;
import com.example.woops.cookit.util.JsonParser;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
/**
* 语音转文字类,根据文字识别
*/
public class ItaActivity extends AppCompatActivity {
//显示框
private EditText mResult;
//设置存储容器
private SharedPreferences mSharedPreferences;
//设置语音识别对象
private SpeechRecognizer mIat;
//迷之Toast,删掉会出现奇怪的错误
private Toast mToast;
//后加的内容
// 语音合成对象
private SpeechSynthesizer mTts;
//缓冲进度
private int mPercentForBuffering = 0;
//播放进度
private int mPercentForPlaying = 0;
private String text;
private CookitDB mCookit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ita);
SpeechUtility.createUtility(this, "appid=570b2ef9");
//初始化语音识别对象
mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
// 初始化合成对象
mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);
mSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE);
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
//初始化UI
initLayout();
//初始化数据库
mCookit = CookitDB.getInstance(this);
}
private void initLayout() {
mResult = (EditText) findViewById(R.id.iat_text);
}
//设置返回值参数
int ret = 0;
//普通的听写功能
public void startClick(View view) {
mResult.setText(null);
setParams();
ret = mIat.startListening(mRecognizerListener);
//貌似没有卵用
if (ret != ErrorCode.SUCCESS) {
showTip("听写失败,错误码:" + ret);
} else {
showTip("请开始BB");
}
}
//设置跳转至发音Activity按钮
public void ttsClick(View view) {
startActivity(new Intent(this, TtsActivity.class));
}
//显示数据库
public void readDB(View view){
mCookit.loadDataBaseTest();
}
//设置参数
private void setParams() {
// 清空参数
mIat.setParameter(SpeechConstant.PARAMS, null);
String lag = mSharedPreferences.getString("iat_language_preference", "mandarin");
// 设置引擎
mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
// 设置返回结果格式
mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
if (lag.equals("en_us")) {
// 设置语言
mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
} else {
// 设置语言
mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
// 设置语言区域
mIat.setParameter(SpeechConstant.ACCENT, lag);
}
// 设置语音前端点:静音超时时间,即用户多长时间不说话则当做超时处理
mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));
// 设置语音后端点:后端点静音检测时间,即用户停止说话多长时间内即认为不再输入, 自动停止录音
mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));
// 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));
// 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
// 注:AUDIO_FORMAT参数语记需要更新版本才能生效
mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav");
// 清空参数
mTts.setParameter(SpeechConstant.PARAMS, null);
//设置合成
//设置使用云端引擎
mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
//设置发音人
mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoqian");
//设置合成语速
mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50"));
//设置合成音调
mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50"));
//设置合成音量
mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50"));
//设置播放器音频流类型
mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3"));
// 设置播放合成音频打断音乐播放,默认为true
mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");
// 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
// 注:AUDIO_FORMAT参数语记需要更新版本才能生效
mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav");
}
/**
* 初始化监听器。
*/
private InitListener mInitListener = new InitListener() {
@Override
public void onInit(int code) {
Log.d("TAG", "SpeechRecognizer init() code = " + code);
if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:" + code);
}
}
};
/**
* 初始化监听。
*/
private InitListener mTtsInitListener = new InitListener() {
@Override
public void onInit(int code) {
Log.d("TAG", "InitListener init() code = " + code);
if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:" + code);
} else {
// 初始化成功,之后可以调用startSpeaking方法
// 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成,
// 正确的做法是将onCreate中的startSpeaking调用移至这里
}
}
};
private void showTip(final String str) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mToast.setText(str);
mToast.show();
}
});
}
/**
* 合成回调监听。
*/
private SynthesizerListener mTtsListener = new SynthesizerListener() {
@Override
public void onSpeakBegin() {
showTip("开始播放");
}
@Override
public void onSpeakPaused() {
showTip("暂停播放");
}
@Override
public void onSpeakResumed() {
showTip("继续播放");
}
@Override
public void onBufferProgress(int percent, int beginPos, int endPos,
String info) {
// 合成进度
mPercentForBuffering = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
}
@Override
public void onSpeakProgress(int percent, int beginPos, int endPos) {
// 播放进度
mPercentForPlaying = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
}
@Override
public void onCompleted(SpeechError error) {
if (error == null) {
showTip("播放完成");
} else if (error != null) {
showTip(error.getPlainDescription(true));
}
}
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因
// 若使用本地能力,会话id为null
// if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid);
// }
}
};
private RecognizerListener mRecognizerListener = new RecognizerListener() {
@Override
public void onBeginOfSpeech() {
// 此回调表示:sdk内部录音机已经准备好了,用户可以开始语音输入
showTip("开始说话");
}
@Override
public void onError(SpeechError error) {
// Tips:
// 错误码:10118(您没有说话),可能是录音机权限被禁,需要提示用户打开应用的录音权限。
showTip(error.getPlainDescription(true));
}
@Override
public void onEndOfSpeech() {
// 此回调表示:检测到了语音的尾端点,已经进入识别过程,不再接受语音输入
showTip("结束说话");
text = mResult.getText().toString();
int num = text.length();
if (num >= 6) {
//调用分割测试类显示结果
SpliteGenerate mSpliteGenerate = new SpliteGenerate(text);
//获取分类处理好的数据实体类
Store mStore = mSpliteGenerate.classification();
if (mStore.getOperate().equals("放入")){
//将数据存入数据库中
mCookit.savaStore(mStore);
}else if (mStore.getOperate().equals("拿走")){
mCookit.deleteDataBaseTest();
}
//mSpliteGenerate.displayStore();
}
Log.d("MY", String.valueOf(num));
mTts.startSpeaking(text, mTtsListener);
}
@Override
public void onResult(RecognizerResult results, boolean isLast) {
text = JsonParser.parseIatResult(results.getResultString());
mResult.append(text);
mResult.setSelection(mResult.length());
if (isLast) {
//TODO 最后的结果
}
}
@Override
public void onVolumeChanged(int volume, byte[] data) {
showTip("当前正在说话,音量大小:" + volume);
Log.d("TAG", "返回音频数据:" + data.length);
}
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因
// 若使用本地能力,会话id为null
// if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid);
// }
}
};
}
| Eccolala/BCCookIt | app/src/main/java/com/example/woops/cookit/activity/ItaActivity.java | 2,987 | // 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因 | line_comment | zh-cn | package com.example.woops.cookit.activity;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.example.woops.cookit.R;
import com.example.woops.cookit.bean.Store;
import com.example.woops.cookit.db.CookitDB;
import com.example.woops.cookit.test.SpliteGenerate;
import com.example.woops.cookit.util.JsonParser;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SpeechUtility;
import com.iflytek.cloud.SynthesizerListener;
/**
* 语音转文字类,根据文字识别
*/
public class ItaActivity extends AppCompatActivity {
//显示框
private EditText mResult;
//设置存储容器
private SharedPreferences mSharedPreferences;
//设置语音识别对象
private SpeechRecognizer mIat;
//迷之Toast,删掉会出现奇怪的错误
private Toast mToast;
//后加的内容
// 语音合成对象
private SpeechSynthesizer mTts;
//缓冲进度
private int mPercentForBuffering = 0;
//播放进度
private int mPercentForPlaying = 0;
private String text;
private CookitDB mCookit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ita);
SpeechUtility.createUtility(this, "appid=570b2ef9");
//初始化语音识别对象
mIat = SpeechRecognizer.createRecognizer(this, mInitListener);
// 初始化合成对象
mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);
mSharedPreferences = getSharedPreferences("com.iflytek.setting", Activity.MODE_PRIVATE);
mToast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
//初始化UI
initLayout();
//初始化数据库
mCookit = CookitDB.getInstance(this);
}
private void initLayout() {
mResult = (EditText) findViewById(R.id.iat_text);
}
//设置返回值参数
int ret = 0;
//普通的听写功能
public void startClick(View view) {
mResult.setText(null);
setParams();
ret = mIat.startListening(mRecognizerListener);
//貌似没有卵用
if (ret != ErrorCode.SUCCESS) {
showTip("听写失败,错误码:" + ret);
} else {
showTip("请开始BB");
}
}
//设置跳转至发音Activity按钮
public void ttsClick(View view) {
startActivity(new Intent(this, TtsActivity.class));
}
//显示数据库
public void readDB(View view){
mCookit.loadDataBaseTest();
}
//设置参数
private void setParams() {
// 清空参数
mIat.setParameter(SpeechConstant.PARAMS, null);
String lag = mSharedPreferences.getString("iat_language_preference", "mandarin");
// 设置引擎
mIat.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
// 设置返回结果格式
mIat.setParameter(SpeechConstant.RESULT_TYPE, "json");
if (lag.equals("en_us")) {
// 设置语言
mIat.setParameter(SpeechConstant.LANGUAGE, "en_us");
} else {
// 设置语言
mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
// 设置语言区域
mIat.setParameter(SpeechConstant.ACCENT, lag);
}
// 设置语音前端点:静音超时时间,即用户多长时间不说话则当做超时处理
mIat.setParameter(SpeechConstant.VAD_BOS, mSharedPreferences.getString("iat_vadbos_preference", "4000"));
// 设置语音后端点:后端点静音检测时间,即用户停止说话多长时间内即认为不再输入, 自动停止录音
mIat.setParameter(SpeechConstant.VAD_EOS, mSharedPreferences.getString("iat_vadeos_preference", "1000"));
// 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
mIat.setParameter(SpeechConstant.ASR_PTT, mSharedPreferences.getString("iat_punc_preference", "1"));
// 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
// 注:AUDIO_FORMAT参数语记需要更新版本才能生效
mIat.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/iat.wav");
// 清空参数
mTts.setParameter(SpeechConstant.PARAMS, null);
//设置合成
//设置使用云端引擎
mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
//设置发音人
mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoqian");
//设置合成语速
mTts.setParameter(SpeechConstant.SPEED, mSharedPreferences.getString("speed_preference", "50"));
//设置合成音调
mTts.setParameter(SpeechConstant.PITCH, mSharedPreferences.getString("pitch_preference", "50"));
//设置合成音量
mTts.setParameter(SpeechConstant.VOLUME, mSharedPreferences.getString("volume_preference", "50"));
//设置播放器音频流类型
mTts.setParameter(SpeechConstant.STREAM_TYPE, mSharedPreferences.getString("stream_preference", "3"));
// 设置播放合成音频打断音乐播放,默认为true
mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");
// 设置音频保存路径,保存音频格式支持pcm、wav,设置路径为sd卡请注意WRITE_EXTERNAL_STORAGE权限
// 注:AUDIO_FORMAT参数语记需要更新版本才能生效
mTts.setParameter(SpeechConstant.AUDIO_FORMAT, "wav");
mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/msc/tts.wav");
}
/**
* 初始化监听器。
*/
private InitListener mInitListener = new InitListener() {
@Override
public void onInit(int code) {
Log.d("TAG", "SpeechRecognizer init() code = " + code);
if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:" + code);
}
}
};
/**
* 初始化监听。
*/
private InitListener mTtsInitListener = new InitListener() {
@Override
public void onInit(int code) {
Log.d("TAG", "InitListener init() code = " + code);
if (code != ErrorCode.SUCCESS) {
showTip("初始化失败,错误码:" + code);
} else {
// 初始化成功,之后可以调用startSpeaking方法
// 注:有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成,
// 正确的做法是将onCreate中的startSpeaking调用移至这里
}
}
};
private void showTip(final String str) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mToast.setText(str);
mToast.show();
}
});
}
/**
* 合成回调监听。
*/
private SynthesizerListener mTtsListener = new SynthesizerListener() {
@Override
public void onSpeakBegin() {
showTip("开始播放");
}
@Override
public void onSpeakPaused() {
showTip("暂停播放");
}
@Override
public void onSpeakResumed() {
showTip("继续播放");
}
@Override
public void onBufferProgress(int percent, int beginPos, int endPos,
String info) {
// 合成进度
mPercentForBuffering = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
}
@Override
public void onSpeakProgress(int percent, int beginPos, int endPos) {
// 播放进度
mPercentForPlaying = percent;
showTip(String.format(getString(R.string.tts_toast_format),
mPercentForBuffering, mPercentForPlaying));
}
@Override
public void onCompleted(SpeechError error) {
if (error == null) {
showTip("播放完成");
} else if (error != null) {
showTip(error.getPlainDescription(true));
}
}
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下代码用于获取与云端的会话id,当业务出错时将会话id提供给技术支持人员,可用于查询会话日志,定位出错原因
// 若使用本地能力,会话id为null
// if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid);
// }
}
};
private RecognizerListener mRecognizerListener = new RecognizerListener() {
@Override
public void onBeginOfSpeech() {
// 此回调表示:sdk内部录音机已经准备好了,用户可以开始语音输入
showTip("开始说话");
}
@Override
public void onError(SpeechError error) {
// Tips:
// 错误码:10118(您没有说话),可能是录音机权限被禁,需要提示用户打开应用的录音权限。
showTip(error.getPlainDescription(true));
}
@Override
public void onEndOfSpeech() {
// 此回调表示:检测到了语音的尾端点,已经进入识别过程,不再接受语音输入
showTip("结束说话");
text = mResult.getText().toString();
int num = text.length();
if (num >= 6) {
//调用分割测试类显示结果
SpliteGenerate mSpliteGenerate = new SpliteGenerate(text);
//获取分类处理好的数据实体类
Store mStore = mSpliteGenerate.classification();
if (mStore.getOperate().equals("放入")){
//将数据存入数据库中
mCookit.savaStore(mStore);
}else if (mStore.getOperate().equals("拿走")){
mCookit.deleteDataBaseTest();
}
//mSpliteGenerate.displayStore();
}
Log.d("MY", String.valueOf(num));
mTts.startSpeaking(text, mTtsListener);
}
@Override
public void onResult(RecognizerResult results, boolean isLast) {
text = JsonParser.parseIatResult(results.getResultString());
mResult.append(text);
mResult.setSelection(mResult.length());
if (isLast) {
//TODO 最后的结果
}
}
@Override
public void onVolumeChanged(int volume, byte[] data) {
showTip("当前正在说话,音量大小:" + volume);
Log.d("TAG", "返回音频数据:" + data.length);
}
@Override
public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
// 以下 <SUF>
// 若使用本地能力,会话id为null
// if (SpeechEvent.EVENT_SESSION_ID == eventType) {
// String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
// Log.d(TAG, "session id =" + sid);
// }
}
};
}
| 0 | 2,679 | 37 | 2,987 | 40 | 3,100 | 34 | 2,987 | 40 | 4,040 | 62 | false | false | false | false | false | true |
55510_2 | class Solution529 {
public char[][] updateBoard(char[][] board, int[] click) {
boolean[][] visited = new boolean[board.length][board[0].length];
if (board[click[0]][click[1]] == 'M') {
// 规则 1,点到雷改为X退出游戏
board[click[0]][click[1]] = 'X';
} else if (board[click[0]][click[1]] == 'E') {
// 只有当点的是未被访问过的格子E才进入递归和判断
dfs(visited, board, click[0], click[1]);
}
return board;
}
public void dfs(boolean[][] visited, char[][] board, int x, int y) {
// 访问当前结点
visited[x][y] = true;
if (count(board, x, y) == 0) {
board[x][y] = 'B';
int[] diff = new int[] {-1, 0, 1};
// 访问周围结点
for (int i = 0; i < diff.length; i++)
for (int j = 0; j < diff.length; j++) {
if (diff[i] == 0 && diff[j] == 0) continue;
if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length || visited[x + diff[i]][y + diff[j]]) continue;
dfs(visited, board, x + diff[i], y + diff[j]);
}
}
else board[x][y] = (char) (count(board, x, y) + '0');
}
public int count(char[][] board, int x, int y) { // 确定周围雷的数量
int res = 0;
int[] diff = new int[] {-1, 0, 1};
for (int i = 0; i < diff.length; i++)
for (int j = 0; j < diff.length; j++) {
if (diff[i] == 0 && diff[j] == 0) continue;
if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length) continue;
if (board[x + diff[i]][y + diff[j]] == 'M') res++;
}
return res;
}
}
/**
* 点击的格子是M,直接改为X并退出游戏
* 点击的格子是是B或者数字,什么也不做退出游戏(题解里其实可以加上这个else if的判断)
* 点击的格子是E才扩展:计算当前格子周围的雷的数量cnt,决定当前格子从E改为B还是改为数字;若改为数字则终止扩展(这也是为什么示例1还剩一个E),若改为B则继续扩展(遇到E才扩展,遇到B或者数字则终止)
*/ | Echlorine/leetcode-solution | Java/Solution529.java | 733 | // 访问当前结点 | line_comment | zh-cn | class Solution529 {
public char[][] updateBoard(char[][] board, int[] click) {
boolean[][] visited = new boolean[board.length][board[0].length];
if (board[click[0]][click[1]] == 'M') {
// 规则 1,点到雷改为X退出游戏
board[click[0]][click[1]] = 'X';
} else if (board[click[0]][click[1]] == 'E') {
// 只有当点的是未被访问过的格子E才进入递归和判断
dfs(visited, board, click[0], click[1]);
}
return board;
}
public void dfs(boolean[][] visited, char[][] board, int x, int y) {
// 访问 <SUF>
visited[x][y] = true;
if (count(board, x, y) == 0) {
board[x][y] = 'B';
int[] diff = new int[] {-1, 0, 1};
// 访问周围结点
for (int i = 0; i < diff.length; i++)
for (int j = 0; j < diff.length; j++) {
if (diff[i] == 0 && diff[j] == 0) continue;
if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length || visited[x + diff[i]][y + diff[j]]) continue;
dfs(visited, board, x + diff[i], y + diff[j]);
}
}
else board[x][y] = (char) (count(board, x, y) + '0');
}
public int count(char[][] board, int x, int y) { // 确定周围雷的数量
int res = 0;
int[] diff = new int[] {-1, 0, 1};
for (int i = 0; i < diff.length; i++)
for (int j = 0; j < diff.length; j++) {
if (diff[i] == 0 && diff[j] == 0) continue;
if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length) continue;
if (board[x + diff[i]][y + diff[j]] == 'M') res++;
}
return res;
}
}
/**
* 点击的格子是M,直接改为X并退出游戏
* 点击的格子是是B或者数字,什么也不做退出游戏(题解里其实可以加上这个else if的判断)
* 点击的格子是E才扩展:计算当前格子周围的雷的数量cnt,决定当前格子从E改为B还是改为数字;若改为数字则终止扩展(这也是为什么示例1还剩一个E),若改为B则继续扩展(遇到E才扩展,遇到B或者数字则终止)
*/ | 0 | 685 | 7 | 733 | 5 | 739 | 6 | 733 | 5 | 911 | 10 | false | false | false | false | false | true |
66465_14 | package alg_02_train_dm._17_day_二叉树二_二刷;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* @Author Wuyj
* @DateTime 2023-08-10 19:10
* @Version 1.0
*/
public class _10_257_binary_tree_paths2 {
// KeyPoint 方法二 BFS => 高性能,打败 100 % => 需要掌握
public List<String> binaryTreePaths(TreeNode root) {
// 输入:
// 1
// / \
// 2 3
// \
// 5
//
// 输出: ["1->2->5", "1->3"]
List<String> res = new ArrayList<String>();
if (root == null) return res;
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
// 在 BFS 过程中,每遍历一个节点,都会有一个 path 与之对应
// 直到遇到叶子节点,将完整 path 加入到 res 中
Queue<String> pathQueue = new LinkedList<String>();
nodeQueue.offer(root);
// KeyPoint 区别:两者 API
// 1.Integer.toString()
// 2.Integer.parseInt()
pathQueue.offer(Integer.toString(root.val));
while (!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.poll();
String path = pathQueue.poll();
// 叶子节点
if (node.left == null && node.right == null) {
res.add(path);
// 结束后面循环
continue;
}
if (node.left != null) {
nodeQueue.offer(node.left);
// KeyPoint 注意事项
// append(node.left.val),不是 node.left,node.left 表示节点
// 同时,因为对 node.left 已经做了判空,不存在空指针异常
pathQueue.offer(new StringBuilder(path).append("->").append(node.left.val).toString());
}
if (node.right != null) {
nodeQueue.offer(node.right);
pathQueue.offer(new StringBuilder(path).append("->").append(node.right.val).toString());
}
}
return res;
}
}
| EchoWuyj/LeetCode | LC_douma/src/main/java/alg_02_train_dm/_17_day_二叉树二_二刷/_10_257_binary_tree_paths2.java | 565 | // 同时,因为对 node.left 已经做了判空,不存在空指针异常 | line_comment | zh-cn | package alg_02_train_dm._17_day_二叉树二_二刷;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* @Author Wuyj
* @DateTime 2023-08-10 19:10
* @Version 1.0
*/
public class _10_257_binary_tree_paths2 {
// KeyPoint 方法二 BFS => 高性能,打败 100 % => 需要掌握
public List<String> binaryTreePaths(TreeNode root) {
// 输入:
// 1
// / \
// 2 3
// \
// 5
//
// 输出: ["1->2->5", "1->3"]
List<String> res = new ArrayList<String>();
if (root == null) return res;
Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
// 在 BFS 过程中,每遍历一个节点,都会有一个 path 与之对应
// 直到遇到叶子节点,将完整 path 加入到 res 中
Queue<String> pathQueue = new LinkedList<String>();
nodeQueue.offer(root);
// KeyPoint 区别:两者 API
// 1.Integer.toString()
// 2.Integer.parseInt()
pathQueue.offer(Integer.toString(root.val));
while (!nodeQueue.isEmpty()) {
TreeNode node = nodeQueue.poll();
String path = pathQueue.poll();
// 叶子节点
if (node.left == null && node.right == null) {
res.add(path);
// 结束后面循环
continue;
}
if (node.left != null) {
nodeQueue.offer(node.left);
// KeyPoint 注意事项
// append(node.left.val),不是 node.left,node.left 表示节点
// 同时 <SUF>
pathQueue.offer(new StringBuilder(path).append("->").append(node.left.val).toString());
}
if (node.right != null) {
nodeQueue.offer(node.right);
pathQueue.offer(new StringBuilder(path).append("->").append(node.right.val).toString());
}
}
return res;
}
}
| 0 | 498 | 21 | 565 | 20 | 584 | 19 | 565 | 20 | 706 | 33 | false | false | false | false | false | true |
24845_2 | package ch12DP;
import java.util.Scanner;
public class Karma46TakeMaterial {
public static void main(String[] args) {
int[] weight = {1,3,4};
int[] value = {15,20,30};
int bagSize = 4;
testWeightBagProblem2(weight,value,bagSize);
}
/**
* 动态规划获得结果
* @param weight 物品的重量
* @param value 物品的价值
* @param bagSize 背包的容量
*/
public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){
// 创建dp数组
int goods = weight.length; // 获取物品的数量
int[][] dp = new int[goods][bagSize + 1];
// 初始化dp数组
// 创建数组后,其中默认的值就是0
/* Arrays.sort(weight);
for (int j = weight[0]; j <= bagSize; j++) {
dp[0][j] = value[0];
}*/
for (int j = 0; j <= bagSize; j++) {
if (j >= weight[0]) {
dp[0][j] = value[0]; // 当背包容量大于等于第一个物品的重量时,可以选择装入该物品
} else {
dp[0][j] = 0; // 否则,背包内无法装入该物品,价值为0
}
}
// 填充dp数组
for (int i = 1; i < weight.length; i++) {
for (int j = 0; j <= bagSize; j++) {
if (j < weight[i]) {
/**
* 当前背包的容量都没有当前物品i大的时候,是不放物品i的
* 那么前i-1个物品能放下的最大价值就是当前情况的最大价值
*/
dp[i][j] = dp[i-1][j];
} else {
/**
* 当前背包的容量可以放下物品i
* 那么此时分两种情况:
* 1、不放物品i
* 2、放物品i
* 比较这两种情况下,哪种背包中物品的最大价值最大
*/
dp[i][j] = Math.max(dp[i-1][j] , dp[i-1][j-weight[i]] + value[i]);
}
}
}
// 打印dp数组
for (int i = 0; i < goods; i++) {
for (int j = 0; j <= bagSize; j++) {
System.out.print(dp[i][j] + "\t");
}
System.out.println("\n");
}
}
/*
* 不能正序可以这么理解:
虽然是一维数组,但是性质和二维背包差不多。
* 我们先来理解倒序遍历,从最后一个元素往前看,看到的都是“上一层的元素”然后每遍历到一个元素,就把当前元素赋值成“当前层”的。
* 这样得到的背包,因为每个元素加上的都是上一层的对应的物品value,所以不会重复。
* 因为二维数组是根据左上元素来求的,一维数组自然就是靠左边来求的。
* 倒序的时候左边元素再刷新前都是上一层的数据,但正序就不一样了,正序的时候,左边的元素刚刚刷新过,也就是左边的元素已经是本层的了,
* 意味着什么 这样会导致一个物品反复加好几次。
* */
public static void testWeightBagProblem2(int[] weight, int[] value, int bagWeight){
int[] dp = new int[bagWeight + 1];
dp[0] = 0;
//本来 应该每个值都赋一个 不影响后面比较max的最小值 敲定为0 但是这里不用赋值为0 默认都是0
/*
* dp[j] = max(dp[j],dp[j - weight[i]] + value[i])
* */
int len = weight.length;
for (int i = 0; i < len; i++) {
for (int j = bagWeight; j >= weight[i] ; j--) {
dp[j] = Math.max(dp[j],dp[j - weight[i]] + value[i]);
}
}
for (int j = 0; j <= bagWeight; j++){
System.out.print(dp[j] + " ");
}
}
}
| EddieAy/Leetcode | ch12DP/Karma46TakeMaterial.java | 1,097 | // 获取物品的数量 | line_comment | zh-cn | package ch12DP;
import java.util.Scanner;
public class Karma46TakeMaterial {
public static void main(String[] args) {
int[] weight = {1,3,4};
int[] value = {15,20,30};
int bagSize = 4;
testWeightBagProblem2(weight,value,bagSize);
}
/**
* 动态规划获得结果
* @param weight 物品的重量
* @param value 物品的价值
* @param bagSize 背包的容量
*/
public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){
// 创建dp数组
int goods = weight.length; // 获取 <SUF>
int[][] dp = new int[goods][bagSize + 1];
// 初始化dp数组
// 创建数组后,其中默认的值就是0
/* Arrays.sort(weight);
for (int j = weight[0]; j <= bagSize; j++) {
dp[0][j] = value[0];
}*/
for (int j = 0; j <= bagSize; j++) {
if (j >= weight[0]) {
dp[0][j] = value[0]; // 当背包容量大于等于第一个物品的重量时,可以选择装入该物品
} else {
dp[0][j] = 0; // 否则,背包内无法装入该物品,价值为0
}
}
// 填充dp数组
for (int i = 1; i < weight.length; i++) {
for (int j = 0; j <= bagSize; j++) {
if (j < weight[i]) {
/**
* 当前背包的容量都没有当前物品i大的时候,是不放物品i的
* 那么前i-1个物品能放下的最大价值就是当前情况的最大价值
*/
dp[i][j] = dp[i-1][j];
} else {
/**
* 当前背包的容量可以放下物品i
* 那么此时分两种情况:
* 1、不放物品i
* 2、放物品i
* 比较这两种情况下,哪种背包中物品的最大价值最大
*/
dp[i][j] = Math.max(dp[i-1][j] , dp[i-1][j-weight[i]] + value[i]);
}
}
}
// 打印dp数组
for (int i = 0; i < goods; i++) {
for (int j = 0; j <= bagSize; j++) {
System.out.print(dp[i][j] + "\t");
}
System.out.println("\n");
}
}
/*
* 不能正序可以这么理解:
虽然是一维数组,但是性质和二维背包差不多。
* 我们先来理解倒序遍历,从最后一个元素往前看,看到的都是“上一层的元素”然后每遍历到一个元素,就把当前元素赋值成“当前层”的。
* 这样得到的背包,因为每个元素加上的都是上一层的对应的物品value,所以不会重复。
* 因为二维数组是根据左上元素来求的,一维数组自然就是靠左边来求的。
* 倒序的时候左边元素再刷新前都是上一层的数据,但正序就不一样了,正序的时候,左边的元素刚刚刷新过,也就是左边的元素已经是本层的了,
* 意味着什么 这样会导致一个物品反复加好几次。
* */
public static void testWeightBagProblem2(int[] weight, int[] value, int bagWeight){
int[] dp = new int[bagWeight + 1];
dp[0] = 0;
//本来 应该每个值都赋一个 不影响后面比较max的最小值 敲定为0 但是这里不用赋值为0 默认都是0
/*
* dp[j] = max(dp[j],dp[j - weight[i]] + value[i])
* */
int len = weight.length;
for (int i = 0; i < len; i++) {
for (int j = bagWeight; j >= weight[i] ; j--) {
dp[j] = Math.max(dp[j],dp[j - weight[i]] + value[i]);
}
}
for (int j = 0; j <= bagWeight; j++){
System.out.print(dp[j] + " ");
}
}
}
| 0 | 1,017 | 4 | 1,097 | 6 | 1,086 | 4 | 1,097 | 6 | 1,468 | 9 | false | false | false | false | false | true |
20918_7 | /**
* 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法,
* 能够支持2个生产者线程以及10个消费者线程的阻塞调用
*
* 使用wait和notify/notifyAll来实现
*
* @author mashibing
*/
package yxxy.c_021;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
public class MyContainer1<T> {
final private LinkedList<T> lists = new LinkedList<>();
final private int MAX = 10; //最多10个元素
private int count = 0;
public synchronized void put(T t) {
while(lists.size() == MAX) { //想想为什么用while而不是用if?
try {
this.wait(); //effective java
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lists.add(t);
++count;
this.notifyAll(); //通知消费者线程进行消费
}
public synchronized T get() {
T t = null;
while(lists.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t = lists.removeFirst();
count --;
this.notifyAll(); //通知生产者进行生产
return t;
}
public static void main(String[] args) {
MyContainer1<String> c = new MyContainer1<>();
//启动消费者线程
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();
}
}
}
| EduMoral/edu | concurrent/src/yxxy/c_021/MyContainer1.java | 562 | //启动生产者线程
| line_comment | zh-cn | /**
* 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法,
* 能够支持2个生产者线程以及10个消费者线程的阻塞调用
*
* 使用wait和notify/notifyAll来实现
*
* @author mashibing
*/
package yxxy.c_021;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;
public class MyContainer1<T> {
final private LinkedList<T> lists = new LinkedList<>();
final private int MAX = 10; //最多10个元素
private int count = 0;
public synchronized void put(T t) {
while(lists.size() == MAX) { //想想为什么用while而不是用if?
try {
this.wait(); //effective java
} catch (InterruptedException e) {
e.printStackTrace();
}
}
lists.add(t);
++count;
this.notifyAll(); //通知消费者线程进行消费
}
public synchronized T get() {
T t = null;
while(lists.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t = lists.removeFirst();
count --;
this.notifyAll(); //通知生产者进行生产
return t;
}
public static void main(String[] args) {
MyContainer1<String> c = new MyContainer1<>();
//启动消费者线程
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();
}
}
}
| 0 | 486 | 7 | 558 | 6 | 561 | 6 | 558 | 6 | 733 | 13 | false | false | false | false | false | true |
17113_2 | package tmall.bean;
/**
* Created by Edward on 2018/7/3
*/
/**
* 属性表
* 商品详情标签下的产品属性
* 不同的商品可能有相同的属性,如能效等级
*/
public class Property {
// 属性的唯一识别的 id
private int id;
// 属性的名称
private String name;
// 和分类表的多对一关系
private Category category;
// Get, Set
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
| EdwardLiu-Aurora/Tmall | src/tmall/bean/Property.java | 205 | // 属性的唯一识别的 id | line_comment | zh-cn | package tmall.bean;
/**
* Created by Edward on 2018/7/3
*/
/**
* 属性表
* 商品详情标签下的产品属性
* 不同的商品可能有相同的属性,如能效等级
*/
public class Property {
// 属性 <SUF>
private int id;
// 属性的名称
private String name;
// 和分类表的多对一关系
private Category category;
// Get, Set
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
| 0 | 190 | 8 | 205 | 7 | 220 | 7 | 205 | 7 | 279 | 17 | false | false | false | false | false | true |
62038_2 | package com.dd.entity;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Id;
import org.nutz.dao.entity.annotation.Table;
import java.util.Date;
/**
* Describe:消息Entity
* Author:蛋蛋
* Age:Eighteen
* Time:2017年4月25日 下午3:10:24
*/
@Table("message")
public class Message {
@Id
private int id;//消息id
@Column("content")
private String content;//消息内容
@Column("uid")
private int uid;//我的id
@Column(wrap=true,value="from")
private Integer from;//发送人,如果此字段为0或者为没有则为系统消息
@Column("from_group")
private int from_group;//分组id
@Column(wrap=true,value="type")
private int type;//1.请求加好友. 2.已拒绝 3.已同意
@Column("remark")
private String remark;//留言
@Column("href")
private String href;
@Column(wrap=true,value="read")
private int read;//是否已读.1.已读.0.未读
@Column(wrap=true,value="time")
private Date time;//消息日期
private User user;//发送人信息
public final static String ID = "id";
public final static String CONTENT = "content";
public final static String UID = "uid";
public final static String FROM = "`from`";
public final static String FROM_GROUP = "from_group";
public final static String TYPE = "`type`";
public final static String REMARK = "remark";
public final static String HREF = "href";
public final static String READ = "`read`";
public final static String TIME = "time";
public static final String TABLE_NAME = "message";
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public Integer getFrom() {
return from;
}
public void setFrom(Integer from) {
this.from = from;
}
public int getFrom_group() {
return from_group;
}
public void setFrom_group(int from_group) {
this.from_group = from_group;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public int getRead() {
return read;
}
public void setRead(int read) {
this.read = read;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Message [id=" + id + ", content=" + content + ", uid=" + uid + ", from=" + from + ", from_group="
+ from_group + ", type=" + type + ", remark=" + remark + ", href=" + href + ", read=" + read + ", time="
+ time + ", user=" + user + "]";
}
}
| EggsBlue/LuliChat | src/main/java/com/dd/entity/Message.java | 998 | //消息内容 | line_comment | zh-cn | package com.dd.entity;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Id;
import org.nutz.dao.entity.annotation.Table;
import java.util.Date;
/**
* Describe:消息Entity
* Author:蛋蛋
* Age:Eighteen
* Time:2017年4月25日 下午3:10:24
*/
@Table("message")
public class Message {
@Id
private int id;//消息id
@Column("content")
private String content;//消息 <SUF>
@Column("uid")
private int uid;//我的id
@Column(wrap=true,value="from")
private Integer from;//发送人,如果此字段为0或者为没有则为系统消息
@Column("from_group")
private int from_group;//分组id
@Column(wrap=true,value="type")
private int type;//1.请求加好友. 2.已拒绝 3.已同意
@Column("remark")
private String remark;//留言
@Column("href")
private String href;
@Column(wrap=true,value="read")
private int read;//是否已读.1.已读.0.未读
@Column(wrap=true,value="time")
private Date time;//消息日期
private User user;//发送人信息
public final static String ID = "id";
public final static String CONTENT = "content";
public final static String UID = "uid";
public final static String FROM = "`from`";
public final static String FROM_GROUP = "from_group";
public final static String TYPE = "`type`";
public final static String REMARK = "remark";
public final static String HREF = "href";
public final static String READ = "`read`";
public final static String TIME = "time";
public static final String TABLE_NAME = "message";
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public Integer getFrom() {
return from;
}
public void setFrom(Integer from) {
this.from = from;
}
public int getFrom_group() {
return from_group;
}
public void setFrom_group(int from_group) {
this.from_group = from_group;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
public int getRead() {
return read;
}
public void setRead(int read) {
this.read = read;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public String toString() {
return "Message [id=" + id + ", content=" + content + ", uid=" + uid + ", from=" + from + ", from_group="
+ from_group + ", type=" + type + ", remark=" + remark + ", href=" + href + ", read=" + read + ", time="
+ time + ", user=" + user + "]";
}
}
| 0 | 770 | 3 | 998 | 3 | 990 | 3 | 998 | 3 | 1,113 | 5 | false | false | false | false | false | true |
20796_7 | package com.mychat.controol;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import com.mychat.dao.ChatMessageDao;
import com.mychat.dao.UserDao;
import com.mychat.entity.InitData;
import com.mychat.entity.JsonMsgModel;
import com.mychat.entity.Message;
import com.mychat.entity.User;
import com.mychat.msg.entity.ChatMessage;
/**
* Describe: User Controll
* Author:陆小不离
* Age:Eighteen
* Time:2017年4月24日 上午11:34:08
*/
@IocBean
@At("/user")
@Ok("json")
public class UserModule {
@Inject(value="userDao")
private UserDao userDao;
@Inject
private Dao dao;
@Inject
private ChatMessageDao chatMessageDao;
/**
* 登陆
* @param u
* @param session
* @return
*/
@At
public Object login(@Param("..")User u,HttpSession session){
NutMap re = new NutMap();
User user = userDao.getByNamPwd(u);
if(user == null){
re.setv("ok", false).setv("msg", "用户名或密码错误!");
return re;
}else{
session.setAttribute("me", user.getId());
session.setAttribute("username", user.getUsername());
re.setv("ok", true).setv("msg", "登陆成功!");
userDao.online(user.getId());
return re;
}
}
/**
* 注册
* @param user
* @param session
* @return
*/
@At
public Object registry(@Param("..") User user,HttpSession session){
NutMap re = new NutMap();
String msg = checkUser(user,true);
if(msg != null){
re.setv("ok", false).setv("msg", msg);
return re;
}
user.setAvatar("/mychat/imgs/user.jpg");
User u = userDao.save(user);
if(u==null){
re.setv("ok", false).setv("msg", "注册失败!");
return re;
}else{
session.setAttribute("me", user.getId());
session.setAttribute("username", user.getUsername());
re.setv("ok", true).setv("msg", "注册成功");
//添加默认分组
userDao.addGroup(u.getId(), "家人");
userDao.addGroup(u.getId(), "朋友");
return re;
}
}
/**
* 查找用户
* @param name
* @return
*/
@At
public Object seachUser(@Param("name") String name){
List<User> users = userDao.getByLikeName(name);
return Json.toJson(users);
}
/**
* 初始化数据
* @param me
* @return
*/
@At
@Ok("raw")
public String getInitData(@Attr("me") int me){
String data = userDao.getInitData(me);
System.out.println(data);
return data;
}
/**
* 获取未读消息数量
* @param me
* @return
*/
@At
public Object unreadMsgCount(@Attr("me") int me){
List<Message> msgs = userDao.getMessages(me);
int count = 0;
for(Message msg : msgs){
if(msg.getRead() == 0){//0未读
count++;
}
}
NutMap nm = new NutMap();
nm.setv("ok", true).setv("count",count);
return nm;
}
/**
* 获取我的消息
* @param me
* @return
*/
@At
public Object getMsg(@Attr("me") int me){
List<Message> msgs = userDao.getMessages(me);
JsonMsgModel jmm = new JsonMsgModel();
jmm.setCode(0);
jmm.setPages(1);
jmm.setData(msgs);
return jmm;
}
/**
* 已读我的消息
* @param me
*/
@At
public void markRead(@Attr("me") int me){
userDao.markRead(me);
}
/**
* 申请添加好友
* @param me 我的id
* @param uid 对方id
* @param from_group 到哪个分组?
* @return
*/
@At
public Object applyFriend(@Attr("me") int me,@Param("uid")int uid,@Param("from_group")int from_group ){
NutMap nm = new NutMap();
int i = userDao.applyFriend(uid, me, from_group);
if(1>0)
nm.setv("ok", 1);
else
nm.setv("ok", 0);
return nm;
}
/**
* 同意添加
* @param me 我的id
* @param uid 对方的id
* @param group 我要添加到的分组id
* @param from_group 对方要添加到的分组id
* @return
*/
@At
public Object addFridend(@Attr("me") int me,@Param("uid") int uid,@Param("group") int group,@Param("from_group") int from_group,@Param("msgid")int msgid){
NutMap nm = new NutMap();
//查出我的所有好友,判断是否已经添加过
List<User> list = userDao.getFriends(me);
if(list!=null && list.size()>0){
for(User u : list){
if(u.getId() == uid)
return nm.setv("code", 1).setv("msg", "不可重复添加!");
}
}
int id = userDao.addFriend(me, uid, group);
int i = userDao.addFriend(uid, me, from_group);
System.out.println("加好友成功!");
//更新消息状态
userDao.updateMsg(msgid, 3); //更新状态为已同意
nm.setv("code", 0);
return nm;
}
/**
* 拒绝添加
* @param me
* @param msgid
* @return
*/
@At
public Object declineApply(@Attr("me") int me,@Param("msgid")int msgid){
NutMap nm = new NutMap();
userDao.updateMsg(msgid, 2);
nm.setv("code", 0);
return nm;
}
/**
* 上线
* @param me
*/
@At
public void online(@Attr("me") int me){
userDao.online(me);
}
/**
* 下线
* @param me
*/
@At
public void hide(@Attr("me") int me){
userDao.hide(me);
}
/**
* 修改签名
* @param me
* @param sign
*/
@At
public void updateSign(@Attr("me") int me,@Param("sign") String sign){
userDao.updateSign(me, sign);
}
/**
* 根据id获取用户信息,可用于查看在线状态
* @param id
* @return
*/
@At
public Object getUser(@Param("id") int id){
User user = userDao.findbyid(id);
return user;
}
/**
* 查询群成员
* @param id
* @return
*/
@At
public Object getMembers(@Param("id") int fid){
List<User> members = userDao.getMembers(fid);
InitData id = new InitData();
id.setCode(0);
id.setMsg("");
Map<String,Object> war = new HashMap<String,Object>();
war.put("list", members);
id.setData(war);
return id;
}
/**
* 分页查询聊天记录
* @param me
* @param pageNo
* @param pageSize
* @param toid
* @param type
* @return
*/
@At
@Ok("json")
public Object getOldMsgs(@Attr("me") int me,@Param("pageNo") int pageNo,@Param("pageSize") int pageSize,@Param("toid") int toid,@Param("type") int type){
/*
username: '纸飞机'
,id: 1
,avatar: 'http://tva3.sinaimg.cn/crop.0.0.512.512.180/8693225ajw8f2rt20ptykj20e80e8weu.jpg'
,timestamp: 1480897882000
,content: 'face[抱抱] face[心] 你好啊小美女'
*/
NutMap nm = chatMessageDao.pageMsg(pageNo, pageSize, me, toid, type);
return nm;
}
/**
* Validate Data
* @param user
* @param create
* @return
*/
protected String checkUser(User user, boolean create) {
if (user == null) {
return "空对象";
}
if (create) {
if (Strings.isBlank(user.getUsername()) || Strings.isBlank(user.getPwd()))
return "用户名/密码不能为空";
} else {
if (Strings.isBlank(user.getPwd()))
return "密码不能为空";
}
String passwd = user.getPwd().trim();
if (6 > passwd.length() || passwd.length() > 12) {
return "密码长度错误";
}
user.setPwd(passwd);
if (create) {
int count = dao.count(User.class, Cnd.where("username", "=", user.getUsername()));
if (count != 0) {
return "用户名已经存在";
}
} else {
if (user.getId() < 1) {
return "用户Id非法";
}
}
if (user.getUsername() != null)
user.setUsername(user.getUsername().trim());
return null;
}
}
| EggsBlue/MyChat | MyChat/src/com/mychat/controol/UserModule.java | 2,702 | //0未读 | line_comment | zh-cn | package com.mychat.controol;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.json.Json;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Attr;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import com.mychat.dao.ChatMessageDao;
import com.mychat.dao.UserDao;
import com.mychat.entity.InitData;
import com.mychat.entity.JsonMsgModel;
import com.mychat.entity.Message;
import com.mychat.entity.User;
import com.mychat.msg.entity.ChatMessage;
/**
* Describe: User Controll
* Author:陆小不离
* Age:Eighteen
* Time:2017年4月24日 上午11:34:08
*/
@IocBean
@At("/user")
@Ok("json")
public class UserModule {
@Inject(value="userDao")
private UserDao userDao;
@Inject
private Dao dao;
@Inject
private ChatMessageDao chatMessageDao;
/**
* 登陆
* @param u
* @param session
* @return
*/
@At
public Object login(@Param("..")User u,HttpSession session){
NutMap re = new NutMap();
User user = userDao.getByNamPwd(u);
if(user == null){
re.setv("ok", false).setv("msg", "用户名或密码错误!");
return re;
}else{
session.setAttribute("me", user.getId());
session.setAttribute("username", user.getUsername());
re.setv("ok", true).setv("msg", "登陆成功!");
userDao.online(user.getId());
return re;
}
}
/**
* 注册
* @param user
* @param session
* @return
*/
@At
public Object registry(@Param("..") User user,HttpSession session){
NutMap re = new NutMap();
String msg = checkUser(user,true);
if(msg != null){
re.setv("ok", false).setv("msg", msg);
return re;
}
user.setAvatar("/mychat/imgs/user.jpg");
User u = userDao.save(user);
if(u==null){
re.setv("ok", false).setv("msg", "注册失败!");
return re;
}else{
session.setAttribute("me", user.getId());
session.setAttribute("username", user.getUsername());
re.setv("ok", true).setv("msg", "注册成功");
//添加默认分组
userDao.addGroup(u.getId(), "家人");
userDao.addGroup(u.getId(), "朋友");
return re;
}
}
/**
* 查找用户
* @param name
* @return
*/
@At
public Object seachUser(@Param("name") String name){
List<User> users = userDao.getByLikeName(name);
return Json.toJson(users);
}
/**
* 初始化数据
* @param me
* @return
*/
@At
@Ok("raw")
public String getInitData(@Attr("me") int me){
String data = userDao.getInitData(me);
System.out.println(data);
return data;
}
/**
* 获取未读消息数量
* @param me
* @return
*/
@At
public Object unreadMsgCount(@Attr("me") int me){
List<Message> msgs = userDao.getMessages(me);
int count = 0;
for(Message msg : msgs){
if(msg.getRead() == 0){//0未 <SUF>
count++;
}
}
NutMap nm = new NutMap();
nm.setv("ok", true).setv("count",count);
return nm;
}
/**
* 获取我的消息
* @param me
* @return
*/
@At
public Object getMsg(@Attr("me") int me){
List<Message> msgs = userDao.getMessages(me);
JsonMsgModel jmm = new JsonMsgModel();
jmm.setCode(0);
jmm.setPages(1);
jmm.setData(msgs);
return jmm;
}
/**
* 已读我的消息
* @param me
*/
@At
public void markRead(@Attr("me") int me){
userDao.markRead(me);
}
/**
* 申请添加好友
* @param me 我的id
* @param uid 对方id
* @param from_group 到哪个分组?
* @return
*/
@At
public Object applyFriend(@Attr("me") int me,@Param("uid")int uid,@Param("from_group")int from_group ){
NutMap nm = new NutMap();
int i = userDao.applyFriend(uid, me, from_group);
if(1>0)
nm.setv("ok", 1);
else
nm.setv("ok", 0);
return nm;
}
/**
* 同意添加
* @param me 我的id
* @param uid 对方的id
* @param group 我要添加到的分组id
* @param from_group 对方要添加到的分组id
* @return
*/
@At
public Object addFridend(@Attr("me") int me,@Param("uid") int uid,@Param("group") int group,@Param("from_group") int from_group,@Param("msgid")int msgid){
NutMap nm = new NutMap();
//查出我的所有好友,判断是否已经添加过
List<User> list = userDao.getFriends(me);
if(list!=null && list.size()>0){
for(User u : list){
if(u.getId() == uid)
return nm.setv("code", 1).setv("msg", "不可重复添加!");
}
}
int id = userDao.addFriend(me, uid, group);
int i = userDao.addFriend(uid, me, from_group);
System.out.println("加好友成功!");
//更新消息状态
userDao.updateMsg(msgid, 3); //更新状态为已同意
nm.setv("code", 0);
return nm;
}
/**
* 拒绝添加
* @param me
* @param msgid
* @return
*/
@At
public Object declineApply(@Attr("me") int me,@Param("msgid")int msgid){
NutMap nm = new NutMap();
userDao.updateMsg(msgid, 2);
nm.setv("code", 0);
return nm;
}
/**
* 上线
* @param me
*/
@At
public void online(@Attr("me") int me){
userDao.online(me);
}
/**
* 下线
* @param me
*/
@At
public void hide(@Attr("me") int me){
userDao.hide(me);
}
/**
* 修改签名
* @param me
* @param sign
*/
@At
public void updateSign(@Attr("me") int me,@Param("sign") String sign){
userDao.updateSign(me, sign);
}
/**
* 根据id获取用户信息,可用于查看在线状态
* @param id
* @return
*/
@At
public Object getUser(@Param("id") int id){
User user = userDao.findbyid(id);
return user;
}
/**
* 查询群成员
* @param id
* @return
*/
@At
public Object getMembers(@Param("id") int fid){
List<User> members = userDao.getMembers(fid);
InitData id = new InitData();
id.setCode(0);
id.setMsg("");
Map<String,Object> war = new HashMap<String,Object>();
war.put("list", members);
id.setData(war);
return id;
}
/**
* 分页查询聊天记录
* @param me
* @param pageNo
* @param pageSize
* @param toid
* @param type
* @return
*/
@At
@Ok("json")
public Object getOldMsgs(@Attr("me") int me,@Param("pageNo") int pageNo,@Param("pageSize") int pageSize,@Param("toid") int toid,@Param("type") int type){
/*
username: '纸飞机'
,id: 1
,avatar: 'http://tva3.sinaimg.cn/crop.0.0.512.512.180/8693225ajw8f2rt20ptykj20e80e8weu.jpg'
,timestamp: 1480897882000
,content: 'face[抱抱] face[心] 你好啊小美女'
*/
NutMap nm = chatMessageDao.pageMsg(pageNo, pageSize, me, toid, type);
return nm;
}
/**
* Validate Data
* @param user
* @param create
* @return
*/
protected String checkUser(User user, boolean create) {
if (user == null) {
return "空对象";
}
if (create) {
if (Strings.isBlank(user.getUsername()) || Strings.isBlank(user.getPwd()))
return "用户名/密码不能为空";
} else {
if (Strings.isBlank(user.getPwd()))
return "密码不能为空";
}
String passwd = user.getPwd().trim();
if (6 > passwd.length() || passwd.length() > 12) {
return "密码长度错误";
}
user.setPwd(passwd);
if (create) {
int count = dao.count(User.class, Cnd.where("username", "=", user.getUsername()));
if (count != 0) {
return "用户名已经存在";
}
} else {
if (user.getId() < 1) {
return "用户Id非法";
}
}
if (user.getUsername() != null)
user.setUsername(user.getUsername().trim());
return null;
}
}
| 0 | 2,353 | 4 | 2,702 | 4 | 2,771 | 4 | 2,702 | 4 | 3,293 | 6 | false | false | false | false | false | true |
60092_10 | package cn.eiden.hsm.enums;
/**
* 多职业组
* @author Eiden J.P Zhou
* @date 2020/8/5 17:22
*/
public enum MultiClassGroup {
/**无效*/
INVALID(0),
/**污手党*/
GRIMY_GOONS(1),
/**玉莲帮*/
JADE_LOTUS(2),
/**暗金教*/
KABAL(3),
/**骑士-牧师*/
PALADIN_PRIEST(4),
/**牧师-术士*/
PRIEST_WARLOCK(5),
/**术士-恶魔猎手*/
WARLOCK_DEMONHUNTER(6),
/**恶魔猎手-猎人*/
HUNTER_DEMONHUNTER(7),
/**猎人-德鲁伊*/
DRUID_HUNTER(8),
/**德鲁伊-萨满*/
DRUID_SHAMAN(9),
/**萨满-法师*/
MAGE_SHAMAN(10),
/**法师-盗贼*/
MAGE_ROGUE(11),
/**盗贼-战士*/
ROGUE_WARRIOR(12),
/**战士-骑士*/
PALADIN_WARRIOR(13)
;
/**代号*/
private int code;
MultiClassGroup(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
| EidenRitto/hearthstone | hearth-core/src/main/java/cn/eiden/hsm/enums/MultiClassGroup.java | 385 | /**德鲁伊-萨满*/ | block_comment | zh-cn | package cn.eiden.hsm.enums;
/**
* 多职业组
* @author Eiden J.P Zhou
* @date 2020/8/5 17:22
*/
public enum MultiClassGroup {
/**无效*/
INVALID(0),
/**污手党*/
GRIMY_GOONS(1),
/**玉莲帮*/
JADE_LOTUS(2),
/**暗金教*/
KABAL(3),
/**骑士-牧师*/
PALADIN_PRIEST(4),
/**牧师-术士*/
PRIEST_WARLOCK(5),
/**术士-恶魔猎手*/
WARLOCK_DEMONHUNTER(6),
/**恶魔猎手-猎人*/
HUNTER_DEMONHUNTER(7),
/**猎人-德鲁伊*/
DRUID_HUNTER(8),
/**德鲁伊 <SUF>*/
DRUID_SHAMAN(9),
/**萨满-法师*/
MAGE_SHAMAN(10),
/**法师-盗贼*/
MAGE_ROGUE(11),
/**盗贼-战士*/
ROGUE_WARRIOR(12),
/**战士-骑士*/
PALADIN_WARRIOR(13)
;
/**代号*/
private int code;
MultiClassGroup(int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
| 0 | 322 | 8 | 385 | 11 | 368 | 8 | 385 | 11 | 476 | 14 | false | false | false | false | false | true |
31992_9 | package top.ysccx.myfirstapp;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class Tab1Fragment extends Fragment {
private GameConf config;
private GameService gameService;
private GameView gameView;
private Button startButton;
private TextView timeTextView;
private AlertDialog.Builder lostDialog;
private AlertDialog.Builder successDialog;
private Timer timer;
private int gameTime;
private boolean isPlaying = false;
private Piece selectedPiece = null;
private AudioAttributes ad =new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
private SoundPool soundPool = new SoundPool.Builder().setMaxStreams(16).setAudioAttributes(ad).build();
private int sdp;
private int wrong;
private DataBaseHelper myDBHelper;
private SQLiteDatabase db;
private EditText et;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1, null);
gameView = view.findViewById(R.id.gameView);
setHasOptionsMenu(true);
timeTextView = view.findViewById(R.id.timeText);
timeTextView.setVisibility(View.INVISIBLE);
startButton = view.findViewById(R.id.startButton);
sdp = soundPool.load(getContext(),R.raw.sdp,1);
wrong = soundPool.load(getContext(),R.raw.wrong,1);
//Toast.makeText(getContext(), sb.toString(), Toast.LENGTH_SHORT).show();
init();
return view;
}
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
menu.add(1,1,1,"排行榜");
menu.add(1,2,1,"打乱重排");
SubMenu grade = menu.addSubMenu("难度");
grade.setHeaderTitle("选择游戏难度");
grade.add(1,11,2,"简单");
grade.add(1,12,3,"容易");
grade.add(1,13,4,"困难");
grade.add(1,14,5,"地狱");
menu.add(1,3,3,"重新开始");
menu.add(1,4,4,"退出");
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
switch (id){
case 1:
//Toast.makeText(getContext(),"打乱重排",Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setClass(getContext(), RankingActivity.class);
startActivity(intent);
break;
case 2:
gameService.shuffle();
gameView.postInvalidate();
break;
case 3:
if(isPlaying) {
startGame(0);
}
else {
Toast.makeText(getContext(), "你还没有开始游戏呢~", Toast.LENGTH_SHORT).show();
}
break;
case 4:
Toast.makeText(getContext(),"不许走,继续玩!",Toast.LENGTH_SHORT).show();
break;
case 11:
config.setxSize(5);
config.setySize(6);
config.setBeginImage();
if(isPlaying){
startGame(0);
}
break;
case 12:
config.setxSize(6);
config.setySize(7);
config.setBeginImage();
if(isPlaying){
startGame(0);
}
break;
case 13:
config.setxSize(7);
config.setySize(8);
config.setBeginImage();
if(isPlaying){
startGame(0);
}
break;
case 14:
config.setxSize(8);
config.setySize(9);
config.setBeginImage();
if(isPlaying){
startGame(0);
}
break;
}
return super.onOptionsItemSelected(item);
}
/**
* 初始化游戏的方法
*/
private void init() {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
config = new GameConf(7, 8, screenWidth, screenHeight, GameConf.DEFAULT_TIME, getContext());
gameService = new GameServiceImpl(this.config);
et = new EditText(getContext());
gameView.setGameService(gameService);
gameView.setSelectImage(ImageUtil.getSelectImage(getContext()));
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View source) {
startGame(0);
startButton.setVisibility(View.INVISIBLE);
gameView.setBackgroundColor(0xFFF9E3);
timeTextView.setVisibility(View.VISIBLE);
}
});
// 为游戏区域的触碰事件绑定监听器
this.gameView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
gameViewTouchDown(e);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
gameViewTouchUp(e);
}
return true;
}
});
// 初始化游戏失败的对话框
lostDialog = createDialog("GAME OVER", "重新开始", R.drawable.lost)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startGame(0);
}
});
// 初始化游戏胜利的对话框
successDialog = createDialog("Success", "你真厉害!请输入你的大名!",
R.drawable.success).setView(et).setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String input = et.getText().toString();
myDBHelper = new DataBaseHelper(getContext(),"ranking",null,1);
db = myDBHelper.getWritableDatabase();
Time t=new Time();
t.setToNow();
int year = t.year;
int month = t.month+1;
int day = t.monthDay;
String date = year+"/"+month+"/"+day;
ContentValues cv = new ContentValues();
cv.put("name",input);
cv.put("time",String.valueOf(gameTime));
cv.put("date",date);
db.insert("users",null,cv);
Intent intent = new Intent();
intent.setAction("top.ysccx.broadcast");
intent.putExtra("name",input);
intent.putExtra("time",String.valueOf(gameTime));
getActivity().sendBroadcast(intent);
startActivity(new Intent(getActivity(),RankingActivity.class));
}
});
}
/**
* Handler类,异步处理
*/
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x123:
timeTextView.setText("倒计时: " + (200-gameTime));
gameTime++; // 游戏剩余时间减少
// 时间小于0, 游戏失败
if (gameTime > 200) {
// 停止计时
stopTimer();
// 更改游戏的状态
isPlaying = false;
// 失败后弹出对话框
lostDialog.show();
return;
}
break;
}
}
};
@Override
public void onPause() {
super.onPause();
// 暂停游戏
stopTimer();
}
@Override
public void onResume() {
super.onResume();
// 如果处于游戏状态中
if(isPlaying) {
startGame(0);
}
}
/**
* 触碰游戏区域的处理方法
*
* @param event
*/
private void gameViewTouchDown(MotionEvent event) {
Piece[][] pieces = gameService.getPieces();
float touchX = event.getX();
Log.i("X",String.valueOf(touchX));
float touchY = event.getY();
Log.i("Y",String.valueOf(touchY));
Piece currentPiece = gameService.findPiece(touchX, touchY);
if (currentPiece == null)
return;
this.gameView.setSelectedPiece(currentPiece);
if (this.selectedPiece == null) {
this.selectedPiece = currentPiece;
this.gameView.postInvalidate();
return;
}
// 表示之前已经选择了一个
if (this.selectedPiece != null) {
LinkInfo linkInfo = this.gameService.link(this.selectedPiece,
currentPiece);
if (linkInfo == null) {
this.selectedPiece = currentPiece;
if(((MainActivity)getActivity()).sound){
soundPool.play(wrong, 0.5f, 0.5f, 0, 0, 1);
}
this.gameView.postInvalidate();
} else {
handleSuccessLink(linkInfo, this.selectedPiece, currentPiece, pieces);
}
}
}
/**
* 触碰游戏区域的处理方法
*
* @param e
*/
private void gameViewTouchUp(MotionEvent e) {
this.gameView.postInvalidate();
}
/**
* 以gameTime作为剩余时间开始或恢复游戏
*
* @param gameTime
* 剩余时间
*/
private void startGame(int gameTime) {
this.gameTime = gameTime;
gameView.startGame();
isPlaying = true;
if(timer==null) {
this.timer = new Timer();
this.timer.schedule(new TimerTask() {
public void run() {
handler.sendEmptyMessage(0x123);
}
}, 0, 1000);
}
this.selectedPiece = null;
}
/**
* 成功连接后处理
*
* @param linkInfo
* 连接信息
* @param prePiece
* 前一个选中方块
* @param currentPiece
* 当前选择方块
* @param pieces
* 系统中还剩的全部方块
*/
private void handleSuccessLink(LinkInfo linkInfo, Piece prePiece,
Piece currentPiece, Piece[][] pieces) {
// 它们可以相连, 让GamePanel处理LinkInfo
this.gameView.setLinkInfo(linkInfo);
// 将gameView中的选中方块设为null
this.gameView.setSelectedPiece(null);
this.gameView.postInvalidate();
// 将两个Piece对象从数组中删除
pieces[prePiece.getIndexX()][prePiece.getIndexY()] = null;
pieces[currentPiece.getIndexX()][currentPiece.getIndexY()] = null;
// 将选中的方块设置null。
this.selectedPiece = null;
if(((MainActivity)getActivity()).sound){
soundPool.play(sdp, 0.5f, 0.5f, 0, 0, 1);
}
// 判断是否还有剩下的方块, 如果没有, 游戏胜利
if (!this.gameService.hasPieces()) {
// 游戏胜利
this.successDialog.show();
// 停止定时器
stopTimer();
// 更改游戏状态
//isPlaying = false;
}
}
/**
* 创建对话框的工具方法
*
* @param title
* 标题
* @param message
* 内容
* @param imageResource
* 图片
* @return
*/
private AlertDialog.Builder createDialog(String title, String message,
int imageResource) {
return new AlertDialog.Builder(getContext()).setTitle(title)
.setMessage(message).setIcon(imageResource);
}
/**
* 停止计时
*/
private void stopTimer() {
// 停止定时器
if(timer!=null) {
this.timer.cancel();
this.timer = null;
}
}
}
| Ellsom1945/lianliankan | app/src/main/java/top/ysccx/myfirstapp/Tab1Fragment.java | 3,057 | // 停止计时 | line_comment | zh-cn | package top.ysccx.myfirstapp;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class Tab1Fragment extends Fragment {
private GameConf config;
private GameService gameService;
private GameView gameView;
private Button startButton;
private TextView timeTextView;
private AlertDialog.Builder lostDialog;
private AlertDialog.Builder successDialog;
private Timer timer;
private int gameTime;
private boolean isPlaying = false;
private Piece selectedPiece = null;
private AudioAttributes ad =new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).build();
private SoundPool soundPool = new SoundPool.Builder().setMaxStreams(16).setAudioAttributes(ad).build();
private int sdp;
private int wrong;
private DataBaseHelper myDBHelper;
private SQLiteDatabase db;
private EditText et;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1, null);
gameView = view.findViewById(R.id.gameView);
setHasOptionsMenu(true);
timeTextView = view.findViewById(R.id.timeText);
timeTextView.setVisibility(View.INVISIBLE);
startButton = view.findViewById(R.id.startButton);
sdp = soundPool.load(getContext(),R.raw.sdp,1);
wrong = soundPool.load(getContext(),R.raw.wrong,1);
//Toast.makeText(getContext(), sb.toString(), Toast.LENGTH_SHORT).show();
init();
return view;
}
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
super.onCreateOptionsMenu(menu, inflater);
menu.add(1,1,1,"排行榜");
menu.add(1,2,1,"打乱重排");
SubMenu grade = menu.addSubMenu("难度");
grade.setHeaderTitle("选择游戏难度");
grade.add(1,11,2,"简单");
grade.add(1,12,3,"容易");
grade.add(1,13,4,"困难");
grade.add(1,14,5,"地狱");
menu.add(1,3,3,"重新开始");
menu.add(1,4,4,"退出");
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
switch (id){
case 1:
//Toast.makeText(getContext(),"打乱重排",Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setClass(getContext(), RankingActivity.class);
startActivity(intent);
break;
case 2:
gameService.shuffle();
gameView.postInvalidate();
break;
case 3:
if(isPlaying) {
startGame(0);
}
else {
Toast.makeText(getContext(), "你还没有开始游戏呢~", Toast.LENGTH_SHORT).show();
}
break;
case 4:
Toast.makeText(getContext(),"不许走,继续玩!",Toast.LENGTH_SHORT).show();
break;
case 11:
config.setxSize(5);
config.setySize(6);
config.setBeginImage();
if(isPlaying){
startGame(0);
}
break;
case 12:
config.setxSize(6);
config.setySize(7);
config.setBeginImage();
if(isPlaying){
startGame(0);
}
break;
case 13:
config.setxSize(7);
config.setySize(8);
config.setBeginImage();
if(isPlaying){
startGame(0);
}
break;
case 14:
config.setxSize(8);
config.setySize(9);
config.setBeginImage();
if(isPlaying){
startGame(0);
}
break;
}
return super.onOptionsItemSelected(item);
}
/**
* 初始化游戏的方法
*/
private void init() {
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int screenWidth = size.x;
int screenHeight = size.y;
config = new GameConf(7, 8, screenWidth, screenHeight, GameConf.DEFAULT_TIME, getContext());
gameService = new GameServiceImpl(this.config);
et = new EditText(getContext());
gameView.setGameService(gameService);
gameView.setSelectImage(ImageUtil.getSelectImage(getContext()));
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View source) {
startGame(0);
startButton.setVisibility(View.INVISIBLE);
gameView.setBackgroundColor(0xFFF9E3);
timeTextView.setVisibility(View.VISIBLE);
}
});
// 为游戏区域的触碰事件绑定监听器
this.gameView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View view, MotionEvent e) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
gameViewTouchDown(e);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
gameViewTouchUp(e);
}
return true;
}
});
// 初始化游戏失败的对话框
lostDialog = createDialog("GAME OVER", "重新开始", R.drawable.lost)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startGame(0);
}
});
// 初始化游戏胜利的对话框
successDialog = createDialog("Success", "你真厉害!请输入你的大名!",
R.drawable.success).setView(et).setPositiveButton("确定",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String input = et.getText().toString();
myDBHelper = new DataBaseHelper(getContext(),"ranking",null,1);
db = myDBHelper.getWritableDatabase();
Time t=new Time();
t.setToNow();
int year = t.year;
int month = t.month+1;
int day = t.monthDay;
String date = year+"/"+month+"/"+day;
ContentValues cv = new ContentValues();
cv.put("name",input);
cv.put("time",String.valueOf(gameTime));
cv.put("date",date);
db.insert("users",null,cv);
Intent intent = new Intent();
intent.setAction("top.ysccx.broadcast");
intent.putExtra("name",input);
intent.putExtra("time",String.valueOf(gameTime));
getActivity().sendBroadcast(intent);
startActivity(new Intent(getActivity(),RankingActivity.class));
}
});
}
/**
* Handler类,异步处理
*/
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x123:
timeTextView.setText("倒计时: " + (200-gameTime));
gameTime++; // 游戏剩余时间减少
// 时间小于0, 游戏失败
if (gameTime > 200) {
// 停止 <SUF>
stopTimer();
// 更改游戏的状态
isPlaying = false;
// 失败后弹出对话框
lostDialog.show();
return;
}
break;
}
}
};
@Override
public void onPause() {
super.onPause();
// 暂停游戏
stopTimer();
}
@Override
public void onResume() {
super.onResume();
// 如果处于游戏状态中
if(isPlaying) {
startGame(0);
}
}
/**
* 触碰游戏区域的处理方法
*
* @param event
*/
private void gameViewTouchDown(MotionEvent event) {
Piece[][] pieces = gameService.getPieces();
float touchX = event.getX();
Log.i("X",String.valueOf(touchX));
float touchY = event.getY();
Log.i("Y",String.valueOf(touchY));
Piece currentPiece = gameService.findPiece(touchX, touchY);
if (currentPiece == null)
return;
this.gameView.setSelectedPiece(currentPiece);
if (this.selectedPiece == null) {
this.selectedPiece = currentPiece;
this.gameView.postInvalidate();
return;
}
// 表示之前已经选择了一个
if (this.selectedPiece != null) {
LinkInfo linkInfo = this.gameService.link(this.selectedPiece,
currentPiece);
if (linkInfo == null) {
this.selectedPiece = currentPiece;
if(((MainActivity)getActivity()).sound){
soundPool.play(wrong, 0.5f, 0.5f, 0, 0, 1);
}
this.gameView.postInvalidate();
} else {
handleSuccessLink(linkInfo, this.selectedPiece, currentPiece, pieces);
}
}
}
/**
* 触碰游戏区域的处理方法
*
* @param e
*/
private void gameViewTouchUp(MotionEvent e) {
this.gameView.postInvalidate();
}
/**
* 以gameTime作为剩余时间开始或恢复游戏
*
* @param gameTime
* 剩余时间
*/
private void startGame(int gameTime) {
this.gameTime = gameTime;
gameView.startGame();
isPlaying = true;
if(timer==null) {
this.timer = new Timer();
this.timer.schedule(new TimerTask() {
public void run() {
handler.sendEmptyMessage(0x123);
}
}, 0, 1000);
}
this.selectedPiece = null;
}
/**
* 成功连接后处理
*
* @param linkInfo
* 连接信息
* @param prePiece
* 前一个选中方块
* @param currentPiece
* 当前选择方块
* @param pieces
* 系统中还剩的全部方块
*/
private void handleSuccessLink(LinkInfo linkInfo, Piece prePiece,
Piece currentPiece, Piece[][] pieces) {
// 它们可以相连, 让GamePanel处理LinkInfo
this.gameView.setLinkInfo(linkInfo);
// 将gameView中的选中方块设为null
this.gameView.setSelectedPiece(null);
this.gameView.postInvalidate();
// 将两个Piece对象从数组中删除
pieces[prePiece.getIndexX()][prePiece.getIndexY()] = null;
pieces[currentPiece.getIndexX()][currentPiece.getIndexY()] = null;
// 将选中的方块设置null。
this.selectedPiece = null;
if(((MainActivity)getActivity()).sound){
soundPool.play(sdp, 0.5f, 0.5f, 0, 0, 1);
}
// 判断是否还有剩下的方块, 如果没有, 游戏胜利
if (!this.gameService.hasPieces()) {
// 游戏胜利
this.successDialog.show();
// 停止定时器
stopTimer();
// 更改游戏状态
//isPlaying = false;
}
}
/**
* 创建对话框的工具方法
*
* @param title
* 标题
* @param message
* 内容
* @param imageResource
* 图片
* @return
*/
private AlertDialog.Builder createDialog(String title, String message,
int imageResource) {
return new AlertDialog.Builder(getContext()).setTitle(title)
.setMessage(message).setIcon(imageResource);
}
/**
* 停止计时
*/
private void stopTimer() {
// 停止定时器
if(timer!=null) {
this.timer.cancel();
this.timer = null;
}
}
}
| 0 | 2,686 | 7 | 3,056 | 5 | 3,244 | 4 | 3,057 | 5 | 3,988 | 8 | false | false | false | false | false | true |
42778_13 | package com.foodClass.model;
import java.util.List;
public class TestFoodClass {
public static void main(String[] args) {
I_FoodClassDAO fdclasstest = new FoodClassJDBCDAO();
FoodClassVO fdvo = new FoodClassVO();
// 新增=====================================
// fdvo.setFd_class_name("好吃");
// fdvo.setFd_class_state(true);
//
// fdclasstest.insertFoodClass(fdvo);
//
// System.out.println("新增成功");
// System.out.println(fdvo);
// 修改=====================================
// fdvo.setFd_class_no(7);
// fdvo.setFd_class_name("很好吃");
// fdvo.setFd_class_state(true);
//
// fdclasstest.updateFoodClass(fdvo);
// System.out.println("修改成功");
// 查詢=====================================
fdvo = fdclasstest.getClassPK(1);
System.out.println(fdvo.getFd_class_no());
System.out.println(fdvo.getFd_class_name());
System.out.println(fdvo.getFd_class_state());
// 查詢=====================================
// List<FoodClassVO> list = fdclasstest.getAllFoodClass();
// for (FoodClassVO fdclass : list) {
// System.out.print(fdclass.getFd_class_no() + ",");
// System.out.print(fdclass.getFd_class_name() + ",");
// System.out.println(fdclass.getFd_class_state());
// }
// System.out.println("查詢成功");
}
}
| EmeryWeng/CFA102G5 | src/com/foodClass/model/TestFoodClass.java | 463 | // 查詢===================================== | line_comment | zh-cn | package com.foodClass.model;
import java.util.List;
public class TestFoodClass {
public static void main(String[] args) {
I_FoodClassDAO fdclasstest = new FoodClassJDBCDAO();
FoodClassVO fdvo = new FoodClassVO();
// 新增=====================================
// fdvo.setFd_class_name("好吃");
// fdvo.setFd_class_state(true);
//
// fdclasstest.insertFoodClass(fdvo);
//
// System.out.println("新增成功");
// System.out.println(fdvo);
// 修改=====================================
// fdvo.setFd_class_no(7);
// fdvo.setFd_class_name("很好吃");
// fdvo.setFd_class_state(true);
//
// fdclasstest.updateFoodClass(fdvo);
// System.out.println("修改成功");
// 查詢=====================================
fdvo = fdclasstest.getClassPK(1);
System.out.println(fdvo.getFd_class_no());
System.out.println(fdvo.getFd_class_name());
System.out.println(fdvo.getFd_class_state());
// 查詢 <SUF>
// List<FoodClassVO> list = fdclasstest.getAllFoodClass();
// for (FoodClassVO fdclass : list) {
// System.out.print(fdclass.getFd_class_no() + ",");
// System.out.print(fdclass.getFd_class_name() + ",");
// System.out.println(fdclass.getFd_class_state());
// }
// System.out.println("查詢成功");
}
}
| 0 | 332 | 5 | 463 | 6 | 447 | 6 | 463 | 6 | 561 | 10 | false | false | false | false | false | true |
17847_1 | package com.zhu56.util;
import cn.hutool.core.util.ReflectUtil;
import com.zhu56.inter.SerFunction;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* λ表达式工具类
*
* @author 朱滔
* @date 2021/10/10 23:42
*/
@UtilityClass
public class LambdaUtil {
/**
* 类型λ缓存
*/
private final Map<Class<?>, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>();
/**
* 返回类型模式
*/
private final Pattern RETURN_TYPE_PATTERN = Pattern.compile("\\(.*\\)L(.*);");
/**
* 获得一个方法引用的lambda实例
*
* @param fun 函数
* @return {@link SerializedLambda}
*/
public <T, R> SerializedLambda getLambda(SerFunction<T, R> fun) {
return getSerializedLambda(fun);
}
/**
* 获取方法的lambda实例
*
* @param fun 有趣
* @return {@link SerializedLambda}
*/
@SneakyThrows
public SerializedLambda getSerializedLambda(Serializable fun) {
Class<?> funClazz = fun.getClass();
return CLASS_LAMBDA_CACHE.computeIfAbsent(funClazz, c -> {
Method method = ReflectUtil.getMethodByName(funClazz, "writeReplace");
return ReflectUtil.invoke(fun, method);
});
}
/**
* 得到返回值的类型
*
* @param fun 有趣
* @return {@link Class}<{@link R}>
*/
@SuppressWarnings("unchecked")
public <T, R> Class<R> getReturnClass(SerFunction<T, R> fun) {
SerializedLambda serializedLambda = getSerializedLambda(fun);
String expr = serializedLambda.getImplMethodSignature();
Matcher matcher = RETURN_TYPE_PATTERN.matcher(expr);
if (!matcher.find() || matcher.groupCount() != 1) {
return null;
}
String className = matcher.group(1).replace("/", ".");
Class<R> clazz;
try {
clazz = (Class<R>) Class.forName(className);
} catch (ClassNotFoundException e) {
return null;
}
return clazz;
}
}
| EmperorZhu56/ztream | src/main/java/com/zhu56/util/LambdaUtil.java | 603 | /**
* 类型λ缓存
*/ | block_comment | zh-cn | package com.zhu56.util;
import cn.hutool.core.util.ReflectUtil;
import com.zhu56.inter.SerFunction;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* λ表达式工具类
*
* @author 朱滔
* @date 2021/10/10 23:42
*/
@UtilityClass
public class LambdaUtil {
/**
* 类型λ <SUF>*/
private final Map<Class<?>, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>();
/**
* 返回类型模式
*/
private final Pattern RETURN_TYPE_PATTERN = Pattern.compile("\\(.*\\)L(.*);");
/**
* 获得一个方法引用的lambda实例
*
* @param fun 函数
* @return {@link SerializedLambda}
*/
public <T, R> SerializedLambda getLambda(SerFunction<T, R> fun) {
return getSerializedLambda(fun);
}
/**
* 获取方法的lambda实例
*
* @param fun 有趣
* @return {@link SerializedLambda}
*/
@SneakyThrows
public SerializedLambda getSerializedLambda(Serializable fun) {
Class<?> funClazz = fun.getClass();
return CLASS_LAMBDA_CACHE.computeIfAbsent(funClazz, c -> {
Method method = ReflectUtil.getMethodByName(funClazz, "writeReplace");
return ReflectUtil.invoke(fun, method);
});
}
/**
* 得到返回值的类型
*
* @param fun 有趣
* @return {@link Class}<{@link R}>
*/
@SuppressWarnings("unchecked")
public <T, R> Class<R> getReturnClass(SerFunction<T, R> fun) {
SerializedLambda serializedLambda = getSerializedLambda(fun);
String expr = serializedLambda.getImplMethodSignature();
Matcher matcher = RETURN_TYPE_PATTERN.matcher(expr);
if (!matcher.find() || matcher.groupCount() != 1) {
return null;
}
String className = matcher.group(1).replace("/", ".");
Class<R> clazz;
try {
clazz = (Class<R>) Class.forName(className);
} catch (ClassNotFoundException e) {
return null;
}
return clazz;
}
}
| 0 | 536 | 11 | 603 | 9 | 642 | 10 | 603 | 9 | 777 | 15 | false | false | false | false | false | true |
53794_6 | package com.ezreal.multiselecttreeview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.ezreal.treevieewlib.AndroidTreeView;
import com.ezreal.treevieewlib.NodeIDFormat;
import com.ezreal.treevieewlib.OnTreeNodeClickListener;
import com.ezreal.treevieewlib.TreeNode;
import java.util.ArrayList;
import java.util.List;
public class SingleSelectActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_sel);
final TextView result = findViewById(R.id.tv_result);
// 通过 findViewById获得控件实例
AndroidTreeView treeView = findViewById(R.id.tree_view);
treeView.setNodeIdFormat(NodeIDFormat.LONG); // 声明 bean 中id pid 字段类型,必选
treeView.setMultiSelEnable(false); // 设置关闭多选,默认关闭,可选
// 在单选状态下,通过监听叶子节点单击事件,得到选中的节点
treeView.setTreeNodeClickListener(new OnTreeNodeClickListener() {
@Override
public void OnLeafNodeClick(TreeNode node, int position) {
result.setText(node.getTitle());
}
});
// 绑定数据,注意:本行需要写在为 treeView 设置属性之后
// 在本行之后任何 setXXX 都不起作用
treeView.bindData(testData());
}
private List<TypeBeanLong> testData(){
// 根据 层级关系,设置好 PID ID 构造测试数据
// 在工作项目中,一般会通过解析 json/xml 来得到个节点数据以及节点间关系
List<TypeBeanLong> list = new ArrayList<>();
list.add(new TypeBeanLong(1,0,"图书"));
list.add(new TypeBeanLong(2,0,"服装"));
list.add(new TypeBeanLong(11,1,"小说"));
list.add(new TypeBeanLong(12,1,"杂志"));
list.add(new TypeBeanLong(21,2,"衣服"));
list.add(new TypeBeanLong(22,2,"裤子"));
list.add(new TypeBeanLong(111,11,"言情小说"));
list.add(new TypeBeanLong(112,11,"科幻小说"));
list.add(new TypeBeanLong(121,12,"军事杂志"));
list.add(new TypeBeanLong(122,12,"娱乐杂志"));
list.add(new TypeBeanLong(211,21,"阿迪"));
list.add(new TypeBeanLong(212,21,"耐克"));
list.add(new TypeBeanLong(221,22,"百斯盾"));
list.add(new TypeBeanLong(222,22,"海澜之家"));
return list;
}
}
| Enjoylone1y/MutiSelectTreeView | app/src/main/java/com/ezreal/multiselecttreeview/SingleSelectActivity.java | 719 | // 根据 层级关系,设置好 PID ID 构造测试数据 | line_comment | zh-cn | package com.ezreal.multiselecttreeview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.ezreal.treevieewlib.AndroidTreeView;
import com.ezreal.treevieewlib.NodeIDFormat;
import com.ezreal.treevieewlib.OnTreeNodeClickListener;
import com.ezreal.treevieewlib.TreeNode;
import java.util.ArrayList;
import java.util.List;
public class SingleSelectActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_sel);
final TextView result = findViewById(R.id.tv_result);
// 通过 findViewById获得控件实例
AndroidTreeView treeView = findViewById(R.id.tree_view);
treeView.setNodeIdFormat(NodeIDFormat.LONG); // 声明 bean 中id pid 字段类型,必选
treeView.setMultiSelEnable(false); // 设置关闭多选,默认关闭,可选
// 在单选状态下,通过监听叶子节点单击事件,得到选中的节点
treeView.setTreeNodeClickListener(new OnTreeNodeClickListener() {
@Override
public void OnLeafNodeClick(TreeNode node, int position) {
result.setText(node.getTitle());
}
});
// 绑定数据,注意:本行需要写在为 treeView 设置属性之后
// 在本行之后任何 setXXX 都不起作用
treeView.bindData(testData());
}
private List<TypeBeanLong> testData(){
// 根据 <SUF>
// 在工作项目中,一般会通过解析 json/xml 来得到个节点数据以及节点间关系
List<TypeBeanLong> list = new ArrayList<>();
list.add(new TypeBeanLong(1,0,"图书"));
list.add(new TypeBeanLong(2,0,"服装"));
list.add(new TypeBeanLong(11,1,"小说"));
list.add(new TypeBeanLong(12,1,"杂志"));
list.add(new TypeBeanLong(21,2,"衣服"));
list.add(new TypeBeanLong(22,2,"裤子"));
list.add(new TypeBeanLong(111,11,"言情小说"));
list.add(new TypeBeanLong(112,11,"科幻小说"));
list.add(new TypeBeanLong(121,12,"军事杂志"));
list.add(new TypeBeanLong(122,12,"娱乐杂志"));
list.add(new TypeBeanLong(211,21,"阿迪"));
list.add(new TypeBeanLong(212,21,"耐克"));
list.add(new TypeBeanLong(221,22,"百斯盾"));
list.add(new TypeBeanLong(222,22,"海澜之家"));
return list;
}
}
| 0 | 613 | 18 | 719 | 15 | 727 | 13 | 719 | 15 | 882 | 27 | false | false | false | false | false | true |
55495_24 | package rip;
import java.util.HashMap;
public class Router {
private final int routerId;
private RouterTable routerTable;
private int[] nearRouter;
private int[] nearNetwork;
public RouterTable getRouterTable() {
return routerTable;
}
public void setRouterTable(RouterTable routerTable) {
this.routerTable = routerTable;
}
public void changeRouterTable(RouterTable otherRouterTable){
// 规则:
// 1. 传入的为其临近路由器的路由表
// 2. 解析路由表
// 3. 如果有自己路由表里有的网络,检查跳数是否为15,不为15进行以下操作
// 4. 如果“跳数+1” 小于 本路由表对应条目的跳数,则修改记录
// 5. 修改记录 “网络号(不变)”,“跳数+1”,“下一跳路由(该路由条目的来源路由)”
// 6. else如果有本自己路由表里没有的网路,检查跳数是否为15,不为15进行以下操作
// 7. 添加记录 “网络号”,“跳数+1”,“下一跳路由(该路由条目的来源路由)”
//将自己的路由表里 所有的网络号建立一个String,所有的跳数建立一个String,
//遍历外来路由表的各个网络号,判断是否存在相同的值
//如果存在 判断跳数(1.是否不等于15,2,是否小于自己对应的跳数+1)
// 如果满足,修改路由表对应数据
// 如果不满足。do nothing
//如果不存在,判断跳数是否不等于15,
// 如果满足,添加该路由条目
HashMap<Integer, String[] > otherList = otherRouterTable.getList();
HashMap<Integer, String[] > selfList = routerTable.getList();
String otherNetnum = "";
String otherTiaonum = "";
String selfNetnum = "";
String selfTiaonum = "";
String selfShouldMod = "";
String otherShouldMod = "";
String shouldAdd = "";
for(int i = 0 ; i < otherList.size(); i++){
otherNetnum += otherList.get(i)[0];
otherTiaonum += otherList.get(i)[1];
}
for(int i = 0; i < selfList.size(); i++){
selfNetnum += selfList.get(i)[0];
selfTiaonum += selfList.get(i)[1];
}
for(int i = 0; i < otherNetnum.length(); i++){
// System.out.println("第"+i+"循环检验========================");
int res = selfNetnum.indexOf(otherNetnum.substring(i,i+1));
int p = Integer.parseInt(otherTiaonum.substring(i, i+1));
if (res != -1) {
int q = Integer.parseInt(selfTiaonum.substring(res, res+1));
if (p < 15) {
if ((p+1) < q ) {
//TODO 修改路由表对应数据
// System.out.println("premod======="+selfNetnum.substring(res, res+1)+"--------"+otherNetnum.substring(i,i+1));
selfShouldMod += String.valueOf(res);
otherShouldMod += String.valueOf(i);
}
}
}else if (res == -1) {
if (p < 15) {
//TODO 添加该条目
// System.out.println("preadd====="+otherNetnum.substring(i,i+1));
shouldAdd += String.valueOf(i);
}
}else {
System.err.println("core change err");
}
}
if (selfShouldMod.length() > 0) {
for(int i = 0; i < selfShouldMod.length(); i++){
// System.out.println("mod");
selfList.remove(selfShouldMod.substring(i,i+1));
String newChange[] = {
otherList.get(Integer.parseInt(otherShouldMod.substring(i, i+1)))[0],
String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(otherShouldMod.substring(i,i+1)))[1])+1),
String.valueOf(otherRouterTable.getRouterID())
};
selfList.put(Integer.parseInt(selfShouldMod.substring(i,i+1)), newChange);
}
}
if (shouldAdd.length() > 0) {
// System.out.println("1111111111111self.size================="+selfList.size());
int len = selfList.size();
for(int i = 0; i < shouldAdd.length(); i++){
// System.out.println("add");
String newChange[] = {
otherList.get(Integer.parseInt(shouldAdd.substring(i, i+1)))[0],
String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(shouldAdd.substring(i,i+1)))[1])+1),
String.valueOf(otherRouterTable.getRouterID())
};
selfList.put(len+i, newChange);
// System.out.println("self.size================="+selfList.size());
}
}
routerTable.setList(selfList);
setRouterTable(routerTable);
}
public int[] getNearRouter() {
return nearRouter;
}
public void setNearRouter(int[] nearRouter) {
this.nearRouter = nearRouter;
}
public int[] getNearNetwork() {
return nearNetwork;
}
public void setNearNetwork(int[] nearNetwork) {
this.nearNetwork = nearNetwork;
}
public int getRouterId() {
return routerId;
}
public void echoRoutertable(){
RouterTable rtTables = getRouterTable();
HashMap<Integer, String[]> list = rtTables.getList();
System.out.println("*******路由器 "+getRouterTable().getRouterID()+" 路由表******");
for (int i = 0; i < list.size(); i++) {
String[] pStrings = list.get(i);
System.out.println("网络:"+pStrings[0]+" | "+"跳数:"+pStrings[1]+" | "+"下一跳路由器: "+pStrings[2]);
}
}
public Router(int routerId, RouterTable routerTable) {
super();
this.routerId = routerId;
this.routerTable = routerTable;
//TODO 记录临近的网络
int[] p = new int[routerTable.getList().size()];
for(int i = 0; i < routerTable.getList().size(); i++){
p[i] = Integer.parseInt(routerTable.getList().get(i)[0]);
}
this.nearNetwork = p;
}
}
| EricLi404/Java-Demos | Rip-Demo/Router.java | 1,763 | //TODO 记录临近的网络
| line_comment | zh-cn | package rip;
import java.util.HashMap;
public class Router {
private final int routerId;
private RouterTable routerTable;
private int[] nearRouter;
private int[] nearNetwork;
public RouterTable getRouterTable() {
return routerTable;
}
public void setRouterTable(RouterTable routerTable) {
this.routerTable = routerTable;
}
public void changeRouterTable(RouterTable otherRouterTable){
// 规则:
// 1. 传入的为其临近路由器的路由表
// 2. 解析路由表
// 3. 如果有自己路由表里有的网络,检查跳数是否为15,不为15进行以下操作
// 4. 如果“跳数+1” 小于 本路由表对应条目的跳数,则修改记录
// 5. 修改记录 “网络号(不变)”,“跳数+1”,“下一跳路由(该路由条目的来源路由)”
// 6. else如果有本自己路由表里没有的网路,检查跳数是否为15,不为15进行以下操作
// 7. 添加记录 “网络号”,“跳数+1”,“下一跳路由(该路由条目的来源路由)”
//将自己的路由表里 所有的网络号建立一个String,所有的跳数建立一个String,
//遍历外来路由表的各个网络号,判断是否存在相同的值
//如果存在 判断跳数(1.是否不等于15,2,是否小于自己对应的跳数+1)
// 如果满足,修改路由表对应数据
// 如果不满足。do nothing
//如果不存在,判断跳数是否不等于15,
// 如果满足,添加该路由条目
HashMap<Integer, String[] > otherList = otherRouterTable.getList();
HashMap<Integer, String[] > selfList = routerTable.getList();
String otherNetnum = "";
String otherTiaonum = "";
String selfNetnum = "";
String selfTiaonum = "";
String selfShouldMod = "";
String otherShouldMod = "";
String shouldAdd = "";
for(int i = 0 ; i < otherList.size(); i++){
otherNetnum += otherList.get(i)[0];
otherTiaonum += otherList.get(i)[1];
}
for(int i = 0; i < selfList.size(); i++){
selfNetnum += selfList.get(i)[0];
selfTiaonum += selfList.get(i)[1];
}
for(int i = 0; i < otherNetnum.length(); i++){
// System.out.println("第"+i+"循环检验========================");
int res = selfNetnum.indexOf(otherNetnum.substring(i,i+1));
int p = Integer.parseInt(otherTiaonum.substring(i, i+1));
if (res != -1) {
int q = Integer.parseInt(selfTiaonum.substring(res, res+1));
if (p < 15) {
if ((p+1) < q ) {
//TODO 修改路由表对应数据
// System.out.println("premod======="+selfNetnum.substring(res, res+1)+"--------"+otherNetnum.substring(i,i+1));
selfShouldMod += String.valueOf(res);
otherShouldMod += String.valueOf(i);
}
}
}else if (res == -1) {
if (p < 15) {
//TODO 添加该条目
// System.out.println("preadd====="+otherNetnum.substring(i,i+1));
shouldAdd += String.valueOf(i);
}
}else {
System.err.println("core change err");
}
}
if (selfShouldMod.length() > 0) {
for(int i = 0; i < selfShouldMod.length(); i++){
// System.out.println("mod");
selfList.remove(selfShouldMod.substring(i,i+1));
String newChange[] = {
otherList.get(Integer.parseInt(otherShouldMod.substring(i, i+1)))[0],
String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(otherShouldMod.substring(i,i+1)))[1])+1),
String.valueOf(otherRouterTable.getRouterID())
};
selfList.put(Integer.parseInt(selfShouldMod.substring(i,i+1)), newChange);
}
}
if (shouldAdd.length() > 0) {
// System.out.println("1111111111111self.size================="+selfList.size());
int len = selfList.size();
for(int i = 0; i < shouldAdd.length(); i++){
// System.out.println("add");
String newChange[] = {
otherList.get(Integer.parseInt(shouldAdd.substring(i, i+1)))[0],
String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(shouldAdd.substring(i,i+1)))[1])+1),
String.valueOf(otherRouterTable.getRouterID())
};
selfList.put(len+i, newChange);
// System.out.println("self.size================="+selfList.size());
}
}
routerTable.setList(selfList);
setRouterTable(routerTable);
}
public int[] getNearRouter() {
return nearRouter;
}
public void setNearRouter(int[] nearRouter) {
this.nearRouter = nearRouter;
}
public int[] getNearNetwork() {
return nearNetwork;
}
public void setNearNetwork(int[] nearNetwork) {
this.nearNetwork = nearNetwork;
}
public int getRouterId() {
return routerId;
}
public void echoRoutertable(){
RouterTable rtTables = getRouterTable();
HashMap<Integer, String[]> list = rtTables.getList();
System.out.println("*******路由器 "+getRouterTable().getRouterID()+" 路由表******");
for (int i = 0; i < list.size(); i++) {
String[] pStrings = list.get(i);
System.out.println("网络:"+pStrings[0]+" | "+"跳数:"+pStrings[1]+" | "+"下一跳路由器: "+pStrings[2]);
}
}
public Router(int routerId, RouterTable routerTable) {
super();
this.routerId = routerId;
this.routerTable = routerTable;
//TO <SUF>
int[] p = new int[routerTable.getList().size()];
for(int i = 0; i < routerTable.getList().size(); i++){
p[i] = Integer.parseInt(routerTable.getList().get(i)[0]);
}
this.nearNetwork = p;
}
}
| 0 | 1,481 | 9 | 1,751 | 9 | 1,726 | 8 | 1,751 | 9 | 2,314 | 16 | false | false | false | false | false | true |
22789_44 | /**
* Copyright(c) Jade Techonologies Co., Ltd.
*/
package cn.eric.jdktools.data;
import java.math.BigDecimal;
/**
* 格式化数字工具类
*/
public class NumUtil
{
/**
* 保留两位小数点
* @param value
* @return
*/
public static double keepTwoPoint(double value)
{
BigDecimal b = new BigDecimal(value);
double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
return result;
}
public static double keepFourPoint(double value)
{
BigDecimal b = new BigDecimal(value);
double result = b.setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue();
return result;
}
public static double keepSixPoint(double value)
{
BigDecimal b = new BigDecimal(value);
double result = b.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();
return result;
}
/**
* 从命令行接收一个数,在其中调用 checkNum() 方法对其进行
* 验证,并返回相应的值
* @return 如果输入合法,返回输入的这个数
*/
public static String getNum(String loanmoney) {
// 判断用户输入是否合法
// 若合法,返回这个值;若非法返回 "0"
if(checkNum(loanmoney)) {
return loanmoney;
} else {
return "";
}
}
/**
* 判断用户输入的数据是否合法,用户只能输入大于零的数字,不能输入其它字符
* @param s String
* @return 如果用户输入数据合法,返回 true,否则返回 false
*/
private static boolean checkNum(String loanmoney) {
// 如果用户输入的数里有非数字字符,则视为非法数据,返回 false
try {
float f = Float.valueOf(loanmoney);
// 如果这个数小于零则视为非法数据,返回 false
if(f < 0) {
System.out.println("非法数据,请检查!");
return false;
}else {
return true;
}
} catch (NumberFormatException s) {
System.out.println("非法数据,请检查!");
return false;
}
}
/**
* 把用户输入的数以小数点为界分割开来,并调用 numFormat() 方法
* 进行相应的中文金额大写形式的转换
* 注:传入的这个数应该是经过 roundString() 方法进行了四舍五入操作的
* @param s String
* @return 转换好的中文金额大写形式的字符串
*/
public static String splitNum(String loanmoney) {
// 如果传入的是空串则继续返回空串
if("".equals(loanmoney)) {
return "";
}
// 以小数点为界分割这个字符串
int index = loanmoney.indexOf(".");
// 截取并转换这个数的整数部分
String intOnly = loanmoney.substring(0, index);
String part1 = numFormat(1, intOnly);
// 截取并转换这个数的小数部分
String smallOnly = loanmoney.substring(index + 1);
String part2 = numFormat(2, smallOnly);
// 把转换好了的整数部分和小数部分重新拼凑一个新的字符串
String newS = part1 + part2;
return newS;
}
/**
* 对传入的数进行四舍五入操作
* @param loanmoney 从命令行输入的那个数
* @return 四舍五入后的新值
*/
public static String roundString(String loanmoney) {
// 如果传入的是空串则继续返回空串
if("".equals(loanmoney)) {
return "";
}
// 将这个数转换成 double 类型,并对其进行四舍五入操作
double d = Double.parseDouble(loanmoney);
// 此操作作用在小数点后两位上
d = (d * 100 + 0.5) / 100;
// 将 d 进行格式化
loanmoney = new java.text.DecimalFormat("##0.000").format(d);
// 以小数点为界分割这个字符串
int index = loanmoney.indexOf(".");
// 这个数的整数部分
String intOnly = loanmoney.substring(0, index);
// 规定数值的最大长度只能到万亿单位,否则返回 "0"
if(intOnly.length() > 13) {
System.out.println("输入数据过大!(整数部分最多13位!)");
return "";
}
// 这个数的小数部分
String smallOnly = loanmoney.substring(index + 1);
// 如果小数部分大于两位,只截取小数点后两位
if(smallOnly.length() > 2) {
String roundSmall = smallOnly.substring(0, 2);
// 把整数部分和新截取的小数部分重新拼凑这个字符串
loanmoney = intOnly + "." + roundSmall;
}
return loanmoney;
}
/**
* 把传入的数转换为中文金额大写形式
* @param flag int 标志位,1 表示转换整数部分,2 表示转换小数部分
* @param s String 要转换的字符串
* @return 转换好的带单位的中文金额大写形式
*/
private static String numFormat(int flag, String loanmoney) {
int sLength = loanmoney.length();
// 货币大写形式
String bigLetter[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
// 货币单位
String unit[] = {"元", "拾", "佰", "仟", "万",
// 拾万位到仟万位
"拾", "佰", "仟",
// 亿位到万亿位
"亿", "拾", "佰", "仟", "万"};
String small[] = {"分", "角"};
// 用来存放转换后的新字符串
String newS = "";
// 逐位替换为中文大写形式
for(int i = 0; i < sLength; i ++) {
if(flag == 1) {
// 转换整数部分为中文大写形式(带单位)
newS = newS + bigLetter[loanmoney.charAt(i) - 48] + unit[sLength - i - 1];
} else if(flag == 2) {
// 转换小数部分(带单位)
newS = newS + bigLetter[loanmoney.charAt(i) - 48] + small[sLength - i - 1];
}
}
return newS;
}
/**
* 把已经转换好的中文金额大写形式加以改进,清理这个字
* 符串里面多余的零,让这个字符串变得更加可观
* 注:传入的这个数应该是经过 splitNum() 方法进行处理,这个字
* 符串应该已经是用中文金额大写形式表示的
* @param s String 已经转换好的字符串
* @return 改进后的字符串
*/
public static String cleanZero(String loanmoney) {
// 如果传入的是空串则继续返回空串
if("".equals(loanmoney)) {
return "";
}
// 如果用户开始输入了很多 0 去掉字符串前面多余的'零',使其看上去更符合习惯
while(loanmoney.charAt(0) == '零') {
// 将字符串中的 "零" 和它对应的单位去掉
loanmoney = loanmoney.substring(2);
// 如果用户当初输入的时候只输入了 0,则只返回一个 "零"
if(loanmoney.length() == 0) {
return "零";
}
}
// 字符串中存在多个'零'在一起的时候只读出一个'零',并省略多余的单位
/* 由于本人对算法的研究太菜了,只能用4个正则表达式去转换了,各位大虾别介意哈... */
String regex1[] = {"零仟", "零佰", "零拾"};
String regex2[] = {"零亿", "零万", "零元"};
String regex3[] = {"亿", "万", "元"};
String regex4[] = {"零角", "零分"};
// 第一轮转换把 "零仟", 零佰","零拾"等字符串替换成一个"零"
for(int i = 0; i < 3; i ++) {
loanmoney = loanmoney.replaceAll(regex1[i], "零");
}
// 第二轮转换考虑 "零亿","零万","零元"等情况
// "亿","万","元"这些单位有些情况是不能省的,需要保留下来
for(int i = 0; i < 3; i ++) {
// 当第一轮转换过后有可能有很多个零叠在一起
// 要把很多个重复的零变成一个零
loanmoney = loanmoney.replaceAll("零零零", "零");
loanmoney = loanmoney.replaceAll("零零", "零");
loanmoney = loanmoney.replaceAll(regex2[i], regex3[i]);
}
// 第三轮转换把"零角","零分"字符串省略
for(int i = 0; i < 2; i ++) {
loanmoney = loanmoney.replaceAll(regex4[i], "");
}
// 当"万"到"亿"之间全部是"零"的时候,忽略"亿万"单位,只保留一个"亿"
loanmoney = loanmoney.replaceAll("亿万", "亿");
return loanmoney;
}
/**
* 测试程序的可行性
* @param args
*/
public static void main(String[] args) {
System.out.println("\n--------将数字转换成中文金额的大写形式------------\n");
NumUtil t2r = new NumUtil();
String money= getNum("bbb600ttt98726a");
System.out.println(money);
String money1= splitNum("17800260026.26");
System.out.println(money1);
String money2 = roundString("3027830056.34426");
System.out.println(money2);
String money3 = numFormat(1, "37356653");
System.out.println(money3);
String money4 = numFormat(2, "34");
System.out.println(money4);
String money5 = cleanZero("零零零零零零壹佰柒拾捌万贰仟陆佰贰拾陆元贰角陆分");
System.out.println(money5);
}
}
| EricLoveMia/JavaTools | src/main/java/cn/eric/jdktools/data/NumUtil.java | 2,585 | // "亿","万","元"这些单位有些情况是不能省的,需要保留下来 | line_comment | zh-cn | /**
* Copyright(c) Jade Techonologies Co., Ltd.
*/
package cn.eric.jdktools.data;
import java.math.BigDecimal;
/**
* 格式化数字工具类
*/
public class NumUtil
{
/**
* 保留两位小数点
* @param value
* @return
*/
public static double keepTwoPoint(double value)
{
BigDecimal b = new BigDecimal(value);
double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
return result;
}
public static double keepFourPoint(double value)
{
BigDecimal b = new BigDecimal(value);
double result = b.setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue();
return result;
}
public static double keepSixPoint(double value)
{
BigDecimal b = new BigDecimal(value);
double result = b.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue();
return result;
}
/**
* 从命令行接收一个数,在其中调用 checkNum() 方法对其进行
* 验证,并返回相应的值
* @return 如果输入合法,返回输入的这个数
*/
public static String getNum(String loanmoney) {
// 判断用户输入是否合法
// 若合法,返回这个值;若非法返回 "0"
if(checkNum(loanmoney)) {
return loanmoney;
} else {
return "";
}
}
/**
* 判断用户输入的数据是否合法,用户只能输入大于零的数字,不能输入其它字符
* @param s String
* @return 如果用户输入数据合法,返回 true,否则返回 false
*/
private static boolean checkNum(String loanmoney) {
// 如果用户输入的数里有非数字字符,则视为非法数据,返回 false
try {
float f = Float.valueOf(loanmoney);
// 如果这个数小于零则视为非法数据,返回 false
if(f < 0) {
System.out.println("非法数据,请检查!");
return false;
}else {
return true;
}
} catch (NumberFormatException s) {
System.out.println("非法数据,请检查!");
return false;
}
}
/**
* 把用户输入的数以小数点为界分割开来,并调用 numFormat() 方法
* 进行相应的中文金额大写形式的转换
* 注:传入的这个数应该是经过 roundString() 方法进行了四舍五入操作的
* @param s String
* @return 转换好的中文金额大写形式的字符串
*/
public static String splitNum(String loanmoney) {
// 如果传入的是空串则继续返回空串
if("".equals(loanmoney)) {
return "";
}
// 以小数点为界分割这个字符串
int index = loanmoney.indexOf(".");
// 截取并转换这个数的整数部分
String intOnly = loanmoney.substring(0, index);
String part1 = numFormat(1, intOnly);
// 截取并转换这个数的小数部分
String smallOnly = loanmoney.substring(index + 1);
String part2 = numFormat(2, smallOnly);
// 把转换好了的整数部分和小数部分重新拼凑一个新的字符串
String newS = part1 + part2;
return newS;
}
/**
* 对传入的数进行四舍五入操作
* @param loanmoney 从命令行输入的那个数
* @return 四舍五入后的新值
*/
public static String roundString(String loanmoney) {
// 如果传入的是空串则继续返回空串
if("".equals(loanmoney)) {
return "";
}
// 将这个数转换成 double 类型,并对其进行四舍五入操作
double d = Double.parseDouble(loanmoney);
// 此操作作用在小数点后两位上
d = (d * 100 + 0.5) / 100;
// 将 d 进行格式化
loanmoney = new java.text.DecimalFormat("##0.000").format(d);
// 以小数点为界分割这个字符串
int index = loanmoney.indexOf(".");
// 这个数的整数部分
String intOnly = loanmoney.substring(0, index);
// 规定数值的最大长度只能到万亿单位,否则返回 "0"
if(intOnly.length() > 13) {
System.out.println("输入数据过大!(整数部分最多13位!)");
return "";
}
// 这个数的小数部分
String smallOnly = loanmoney.substring(index + 1);
// 如果小数部分大于两位,只截取小数点后两位
if(smallOnly.length() > 2) {
String roundSmall = smallOnly.substring(0, 2);
// 把整数部分和新截取的小数部分重新拼凑这个字符串
loanmoney = intOnly + "." + roundSmall;
}
return loanmoney;
}
/**
* 把传入的数转换为中文金额大写形式
* @param flag int 标志位,1 表示转换整数部分,2 表示转换小数部分
* @param s String 要转换的字符串
* @return 转换好的带单位的中文金额大写形式
*/
private static String numFormat(int flag, String loanmoney) {
int sLength = loanmoney.length();
// 货币大写形式
String bigLetter[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
// 货币单位
String unit[] = {"元", "拾", "佰", "仟", "万",
// 拾万位到仟万位
"拾", "佰", "仟",
// 亿位到万亿位
"亿", "拾", "佰", "仟", "万"};
String small[] = {"分", "角"};
// 用来存放转换后的新字符串
String newS = "";
// 逐位替换为中文大写形式
for(int i = 0; i < sLength; i ++) {
if(flag == 1) {
// 转换整数部分为中文大写形式(带单位)
newS = newS + bigLetter[loanmoney.charAt(i) - 48] + unit[sLength - i - 1];
} else if(flag == 2) {
// 转换小数部分(带单位)
newS = newS + bigLetter[loanmoney.charAt(i) - 48] + small[sLength - i - 1];
}
}
return newS;
}
/**
* 把已经转换好的中文金额大写形式加以改进,清理这个字
* 符串里面多余的零,让这个字符串变得更加可观
* 注:传入的这个数应该是经过 splitNum() 方法进行处理,这个字
* 符串应该已经是用中文金额大写形式表示的
* @param s String 已经转换好的字符串
* @return 改进后的字符串
*/
public static String cleanZero(String loanmoney) {
// 如果传入的是空串则继续返回空串
if("".equals(loanmoney)) {
return "";
}
// 如果用户开始输入了很多 0 去掉字符串前面多余的'零',使其看上去更符合习惯
while(loanmoney.charAt(0) == '零') {
// 将字符串中的 "零" 和它对应的单位去掉
loanmoney = loanmoney.substring(2);
// 如果用户当初输入的时候只输入了 0,则只返回一个 "零"
if(loanmoney.length() == 0) {
return "零";
}
}
// 字符串中存在多个'零'在一起的时候只读出一个'零',并省略多余的单位
/* 由于本人对算法的研究太菜了,只能用4个正则表达式去转换了,各位大虾别介意哈... */
String regex1[] = {"零仟", "零佰", "零拾"};
String regex2[] = {"零亿", "零万", "零元"};
String regex3[] = {"亿", "万", "元"};
String regex4[] = {"零角", "零分"};
// 第一轮转换把 "零仟", 零佰","零拾"等字符串替换成一个"零"
for(int i = 0; i < 3; i ++) {
loanmoney = loanmoney.replaceAll(regex1[i], "零");
}
// 第二轮转换考虑 "零亿","零万","零元"等情况
// "亿 <SUF>
for(int i = 0; i < 3; i ++) {
// 当第一轮转换过后有可能有很多个零叠在一起
// 要把很多个重复的零变成一个零
loanmoney = loanmoney.replaceAll("零零零", "零");
loanmoney = loanmoney.replaceAll("零零", "零");
loanmoney = loanmoney.replaceAll(regex2[i], regex3[i]);
}
// 第三轮转换把"零角","零分"字符串省略
for(int i = 0; i < 2; i ++) {
loanmoney = loanmoney.replaceAll(regex4[i], "");
}
// 当"万"到"亿"之间全部是"零"的时候,忽略"亿万"单位,只保留一个"亿"
loanmoney = loanmoney.replaceAll("亿万", "亿");
return loanmoney;
}
/**
* 测试程序的可行性
* @param args
*/
public static void main(String[] args) {
System.out.println("\n--------将数字转换成中文金额的大写形式------------\n");
NumUtil t2r = new NumUtil();
String money= getNum("bbb600ttt98726a");
System.out.println(money);
String money1= splitNum("17800260026.26");
System.out.println(money1);
String money2 = roundString("3027830056.34426");
System.out.println(money2);
String money3 = numFormat(1, "37356653");
System.out.println(money3);
String money4 = numFormat(2, "34");
System.out.println(money4);
String money5 = cleanZero("零零零零零零壹佰柒拾捌万贰仟陆佰贰拾陆元贰角陆分");
System.out.println(money5);
}
}
| 0 | 2,431 | 20 | 2,585 | 23 | 2,619 | 20 | 2,585 | 23 | 3,612 | 34 | false | false | false | false | false | true |
25178_6 | package com.example.guohouxiao.musicalbum.utils;
/**
* Created by guohouxiao on 2017/9/5.
* 表的属性
*/
public class Config {
public static final String USER_TABLE = "_User";//用户表
public static final String AVATAR = "avatar";//用户头像
public static final String NICKNAME = "nickname";//用户昵称
public static final String DESC = "desc";//简介
public static final String BOOKMARKALBUM = "bookmarkalbum";//收藏的相册
public static final String LIKEALBUM = "likealbum";//喜欢的相册
public static final String MUSICALBUM_TABLE = "MusicAlbum";//音乐相册表
public static final String USERID = "userId";//作者的ID
public static final String ALBUMNAME = "albumname";//相册名称
public static final String COVER = "cover";//封面
public static final String PLACE = "place";//地点
public static final String WHERECREATED = "whereCreated";//经纬度
public static final String PLAYMODE = "playmode";//模板
public static final String MUSIC = "music";//音乐
public static final String PHOTOS = "photos";//图片
public static final String SUBTITLES = "subtitles";//字幕
public static final String ISPUBLIC = "ispublic";//是否公开
public static final String LIKENUMBER = "likenumber";//获得的喜欢数
}
| ErisRolo/MusicAlbum | app/src/main/java/com/example/guohouxiao/musicalbum/utils/Config.java | 358 | //音乐相册表 | line_comment | zh-cn | package com.example.guohouxiao.musicalbum.utils;
/**
* Created by guohouxiao on 2017/9/5.
* 表的属性
*/
public class Config {
public static final String USER_TABLE = "_User";//用户表
public static final String AVATAR = "avatar";//用户头像
public static final String NICKNAME = "nickname";//用户昵称
public static final String DESC = "desc";//简介
public static final String BOOKMARKALBUM = "bookmarkalbum";//收藏的相册
public static final String LIKEALBUM = "likealbum";//喜欢的相册
public static final String MUSICALBUM_TABLE = "MusicAlbum";//音乐 <SUF>
public static final String USERID = "userId";//作者的ID
public static final String ALBUMNAME = "albumname";//相册名称
public static final String COVER = "cover";//封面
public static final String PLACE = "place";//地点
public static final String WHERECREATED = "whereCreated";//经纬度
public static final String PLAYMODE = "playmode";//模板
public static final String MUSIC = "music";//音乐
public static final String PHOTOS = "photos";//图片
public static final String SUBTITLES = "subtitles";//字幕
public static final String ISPUBLIC = "ispublic";//是否公开
public static final String LIKENUMBER = "likenumber";//获得的喜欢数
}
| 0 | 322 | 5 | 358 | 6 | 319 | 5 | 358 | 6 | 428 | 8 | false | false | false | false | false | true |
45050_10 | package cn.com.fusio.event.merge;
import cn.com.fusio.event.BaseEvent;
import cn.com.fusio.event.entity.ArticleInfo;
import cn.com.fusio.event.entity.FormInfo;
import cn.com.fusio.event.entity.UserInfo;
import cn.com.fusio.event.raw.PinganBehaviorData;
import org.drools.core.util.StringUtils;
/**
* @Description: 丰富 PinganBehaviorData 类
* @Author : Ernest
* @Date : 2017/8/20 20:07
*/
public class PinganEduPVEnrich extends BaseEvent {
/**
* 用户行为记录
*/
private PinganBehaviorData behaviorData ;
/**
* 用户信息
*/
private UserInfo userInfo ;
/**
* 文章信息,当 bd:contentType=article 时,有值
*/
private ArticleInfo articleInfo ;
/**
* 表单信息,当 bd:contentType=form 时,有值
*/
private FormInfo formInfo ;
public PinganEduPVEnrich() {}
public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, ArticleInfo articleInfo) {
this.behaviorData = behaviorData;
this.userInfo = userInfo;
this.articleInfo = articleInfo;
// 指定 DRL 中的 @timestamp
this.eventTime = behaviorData.getCollector_tstamp() ;
}
/**
* 判断行为数据是否包含某些标签:PinganEduPVEnrich
* @param tags
* @return
*/
public boolean containTags(String... tags){
boolean isValid = false ;
// 1.2.过滤标签条件
// 59effffd48b743bbbf9ff148341b32ee:事业;63dd1d21acfd4452bf72130123cf2f3c:职位
String cntTags = "" ;
String cntType = behaviorData.getContentType();
if("article".equals(cntType)){
cntTags = articleInfo.getCatg_name() ;
}else if("form".equals(cntType)){
// cntTags = formInfo.getForm_tags() ;
cntTags = "心理" ; //暂时 表单 标签都作为 心理。
}
// 判断是否包含标签, 并集
if(!StringUtils.isEmpty(cntTags)){
for(int i = 0 ; i<tags.length ;i++){
if(cntTags.equals(tags[i])) isValid = true ;
}
}
return isValid ;
}
/**
* 判断用户是否属于某个省份:或
* @param city
* @return
*/
public Boolean isBelongToProvince(String... city){
boolean yesOrNo = false ;
String province = null ;
if(userInfo != null ){
province = this.userInfo.getAll_province();
}
if(province !=null && "".equals(province)){
for(int i = 0 ; i < city.length ;i++){
if(province.equals(city[i])){
yesOrNo = true ;
break;
}
}
}
return yesOrNo ;
}
/**
* 年龄大于 age
* @param age
* @return
*/
public Boolean isAgeGtNum(Integer age){
boolean yesOrNo = false ;
Integer userAge = null ;
if(userInfo != null ){
userAge = userInfo.getAge();
}
if( userAge != null ){
if(userInfo.getAge() > age){
yesOrNo = true ;
}
}
return yesOrNo ;
}
/**
* 年龄小于 age
* @param age
* @return
*/
public Boolean isAgeLtNum(Integer age){
boolean yesOrNo = false ;
if(userInfo.getAge() != null ){
if(userInfo.getAge() < age){
yesOrNo = true ;
}
}
return yesOrNo ;
}
public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, FormInfo formInfo) {
this.behaviorData = behaviorData;
this.userInfo = userInfo;
this.formInfo = formInfo;
// 指定 DRL 中的 @timestamp
this.eventTime = behaviorData.getCollector_tstamp() ;
}
public PinganBehaviorData getBehaviorData() {
return behaviorData;
}
public void setBehaviorData(PinganBehaviorData behaviorData) {
this.behaviorData = behaviorData;
}
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
public ArticleInfo getArticleInfo() {
return articleInfo;
}
public void setArticleInfo(ArticleInfo articleInfo) {
this.articleInfo = articleInfo;
}
public FormInfo getFormInfo() {
return formInfo;
}
public void setFormInfo(FormInfo formInfo) {
this.formInfo = formInfo;
}
@Override
public String toString() {
return "PinganEduPVEnrich{" +
"behaviorData=" + behaviorData +
", userInfo=" + userInfo +
", articleInfo=" + articleInfo +
", formInfo=" + formInfo +
'}';
}
}
| ErnestMing/Drools-CEP-EventFlow | src/main/java/cn/com/fusio/event/merge/PinganEduPVEnrich.java | 1,237 | //暂时 表单 标签都作为 心理。 | line_comment | zh-cn | package cn.com.fusio.event.merge;
import cn.com.fusio.event.BaseEvent;
import cn.com.fusio.event.entity.ArticleInfo;
import cn.com.fusio.event.entity.FormInfo;
import cn.com.fusio.event.entity.UserInfo;
import cn.com.fusio.event.raw.PinganBehaviorData;
import org.drools.core.util.StringUtils;
/**
* @Description: 丰富 PinganBehaviorData 类
* @Author : Ernest
* @Date : 2017/8/20 20:07
*/
public class PinganEduPVEnrich extends BaseEvent {
/**
* 用户行为记录
*/
private PinganBehaviorData behaviorData ;
/**
* 用户信息
*/
private UserInfo userInfo ;
/**
* 文章信息,当 bd:contentType=article 时,有值
*/
private ArticleInfo articleInfo ;
/**
* 表单信息,当 bd:contentType=form 时,有值
*/
private FormInfo formInfo ;
public PinganEduPVEnrich() {}
public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, ArticleInfo articleInfo) {
this.behaviorData = behaviorData;
this.userInfo = userInfo;
this.articleInfo = articleInfo;
// 指定 DRL 中的 @timestamp
this.eventTime = behaviorData.getCollector_tstamp() ;
}
/**
* 判断行为数据是否包含某些标签:PinganEduPVEnrich
* @param tags
* @return
*/
public boolean containTags(String... tags){
boolean isValid = false ;
// 1.2.过滤标签条件
// 59effffd48b743bbbf9ff148341b32ee:事业;63dd1d21acfd4452bf72130123cf2f3c:职位
String cntTags = "" ;
String cntType = behaviorData.getContentType();
if("article".equals(cntType)){
cntTags = articleInfo.getCatg_name() ;
}else if("form".equals(cntType)){
// cntTags = formInfo.getForm_tags() ;
cntTags = "心理" ; //暂时 <SUF>
}
// 判断是否包含标签, 并集
if(!StringUtils.isEmpty(cntTags)){
for(int i = 0 ; i<tags.length ;i++){
if(cntTags.equals(tags[i])) isValid = true ;
}
}
return isValid ;
}
/**
* 判断用户是否属于某个省份:或
* @param city
* @return
*/
public Boolean isBelongToProvince(String... city){
boolean yesOrNo = false ;
String province = null ;
if(userInfo != null ){
province = this.userInfo.getAll_province();
}
if(province !=null && "".equals(province)){
for(int i = 0 ; i < city.length ;i++){
if(province.equals(city[i])){
yesOrNo = true ;
break;
}
}
}
return yesOrNo ;
}
/**
* 年龄大于 age
* @param age
* @return
*/
public Boolean isAgeGtNum(Integer age){
boolean yesOrNo = false ;
Integer userAge = null ;
if(userInfo != null ){
userAge = userInfo.getAge();
}
if( userAge != null ){
if(userInfo.getAge() > age){
yesOrNo = true ;
}
}
return yesOrNo ;
}
/**
* 年龄小于 age
* @param age
* @return
*/
public Boolean isAgeLtNum(Integer age){
boolean yesOrNo = false ;
if(userInfo.getAge() != null ){
if(userInfo.getAge() < age){
yesOrNo = true ;
}
}
return yesOrNo ;
}
public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, FormInfo formInfo) {
this.behaviorData = behaviorData;
this.userInfo = userInfo;
this.formInfo = formInfo;
// 指定 DRL 中的 @timestamp
this.eventTime = behaviorData.getCollector_tstamp() ;
}
public PinganBehaviorData getBehaviorData() {
return behaviorData;
}
public void setBehaviorData(PinganBehaviorData behaviorData) {
this.behaviorData = behaviorData;
}
public UserInfo getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfo userInfo) {
this.userInfo = userInfo;
}
public ArticleInfo getArticleInfo() {
return articleInfo;
}
public void setArticleInfo(ArticleInfo articleInfo) {
this.articleInfo = articleInfo;
}
public FormInfo getFormInfo() {
return formInfo;
}
public void setFormInfo(FormInfo formInfo) {
this.formInfo = formInfo;
}
@Override
public String toString() {
return "PinganEduPVEnrich{" +
"behaviorData=" + behaviorData +
", userInfo=" + userInfo +
", articleInfo=" + articleInfo +
", formInfo=" + formInfo +
'}';
}
}
| 0 | 1,167 | 14 | 1,237 | 13 | 1,342 | 10 | 1,237 | 13 | 1,579 | 20 | false | false | false | false | false | true |
32949_5 | package com.eshel.takeout.permission;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import com.eshel.takeout.utils.UIUtils;
/**
* 项目名称: GooglePlay
* 创建人: Eshel
* 创建时间:2017/7/12 19时02分
* 描述: TODO
*/
public class RequestPermissionUtil {
/**
* @param permission Manifest.permission.***
* @return
*/
public static boolean requestPermission(Activity activity,String permission,int requestCode){
//检查权限: 检查用户是不是已经授权
int checkSelfPermission = ContextCompat.checkSelfPermission(UIUtils.getContext(), permission);
//拒绝 : 检查到用户之前拒绝授权
if(checkSelfPermission == PackageManager.PERMISSION_DENIED){
//申请权限
ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode);
}else if(checkSelfPermission == PackageManager.PERMISSION_GRANTED){
//已经授权
return true;
}else {
ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode);
}
return false;
}
}
| EshelGuo/PermissionsUtil | permission/RequestPermissionUtil.java | 322 | //已经授权 | line_comment | zh-cn | package com.eshel.takeout.permission;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import com.eshel.takeout.utils.UIUtils;
/**
* 项目名称: GooglePlay
* 创建人: Eshel
* 创建时间:2017/7/12 19时02分
* 描述: TODO
*/
public class RequestPermissionUtil {
/**
* @param permission Manifest.permission.***
* @return
*/
public static boolean requestPermission(Activity activity,String permission,int requestCode){
//检查权限: 检查用户是不是已经授权
int checkSelfPermission = ContextCompat.checkSelfPermission(UIUtils.getContext(), permission);
//拒绝 : 检查到用户之前拒绝授权
if(checkSelfPermission == PackageManager.PERMISSION_DENIED){
//申请权限
ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode);
}else if(checkSelfPermission == PackageManager.PERMISSION_GRANTED){
//已经 <SUF>
return true;
}else {
ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode);
}
return false;
}
}
| 0 | 251 | 3 | 322 | 3 | 299 | 3 | 322 | 3 | 412 | 9 | false | false | false | false | false | true |
61598_4 | /**
* 创建时间:2016-2-23
*/
package cn.aofeng.demo.httpclient;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
/**
* HttpClient的基本操作。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class HttpClientBasic {
private static Logger _logger = Logger.getLogger(HttpClientBasic.class);
private static String _targetHost = "http://127.0.0.1:8888";
private static String _charset = "utf-8";
public void get() throws URISyntaxException, ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet(_targetHost+"/get");
CloseableHttpResponse response = client.execute(get);
processResponse(response);
}
public void post() throws ClientProtocolException, IOException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("chinese", "中文"));
params.add(new BasicNameValuePair("english", "英文"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, _charset);
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(_targetHost+"/post");
post.addHeader("Cookie", "character=abcdefghijklmnopqrstuvwxyz; sign=abc-123-jkl-098");
post.setEntity(entity);
CloseableHttpResponse response = client.execute(post);
processResponse(response);
}
public void sendFile(String filePath) throws UnsupportedOperationException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(_targetHost+"/file");
File file = new File(filePath);
FileEntity entity = new FileEntity(file, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), _charset));
post.setEntity(entity);
CloseableHttpResponse response = client.execute(post);
processResponse(response);
}
private void processResponse(CloseableHttpResponse response)
throws UnsupportedOperationException, IOException {
try {
// 获取响应头
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
_logger.info(header.getName() + ":" + header.getValue());
}
// 获取状态信息
StatusLine sl =response.getStatusLine();
_logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s",
sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) );
// 获取响应内容
HttpEntity entity = response.getEntity();
_logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s",
null == entity.getContentType() ? "" : entity.getContentType().getValue(),
entity.getContentLength(),
null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) );
_logger.info(EntityUtils.toString(entity, _charset));
// _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同
} finally {
response.close();
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
HttpClientBasic basic = new HttpClientBasic();
// basic.get();
// basic.post();
basic.sendFile("/devdata/projects/open_source/mine/JavaTutorial/LICENSE");
}
}
| Estom/notes | Java/Java源代码/codedemo/httpclient/HttpClientBasic.java | 1,046 | // 获取状态信息 | line_comment | zh-cn | /**
* 创建时间:2016-2-23
*/
package cn.aofeng.demo.httpclient;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
/**
* HttpClient的基本操作。
*
* @author <a href="mailto:aofengblog@163.com">聂勇</a>
*/
public class HttpClientBasic {
private static Logger _logger = Logger.getLogger(HttpClientBasic.class);
private static String _targetHost = "http://127.0.0.1:8888";
private static String _charset = "utf-8";
public void get() throws URISyntaxException, ClientProtocolException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpGet get = new HttpGet(_targetHost+"/get");
CloseableHttpResponse response = client.execute(get);
processResponse(response);
}
public void post() throws ClientProtocolException, IOException {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("chinese", "中文"));
params.add(new BasicNameValuePair("english", "英文"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, _charset);
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(_targetHost+"/post");
post.addHeader("Cookie", "character=abcdefghijklmnopqrstuvwxyz; sign=abc-123-jkl-098");
post.setEntity(entity);
CloseableHttpResponse response = client.execute(post);
processResponse(response);
}
public void sendFile(String filePath) throws UnsupportedOperationException, IOException {
CloseableHttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(_targetHost+"/file");
File file = new File(filePath);
FileEntity entity = new FileEntity(file, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), _charset));
post.setEntity(entity);
CloseableHttpResponse response = client.execute(post);
processResponse(response);
}
private void processResponse(CloseableHttpResponse response)
throws UnsupportedOperationException, IOException {
try {
// 获取响应头
Header[] headers = response.getAllHeaders();
for (Header header : headers) {
_logger.info(header.getName() + ":" + header.getValue());
}
// 获取 <SUF>
StatusLine sl =response.getStatusLine();
_logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s",
sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) );
// 获取响应内容
HttpEntity entity = response.getEntity();
_logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s",
null == entity.getContentType() ? "" : entity.getContentType().getValue(),
entity.getContentLength(),
null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) );
_logger.info(EntityUtils.toString(entity, _charset));
// _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同
} finally {
response.close();
}
}
/**
* @param args
*/
public static void main(String[] args) throws Exception {
HttpClientBasic basic = new HttpClientBasic();
// basic.get();
// basic.post();
basic.sendFile("/devdata/projects/open_source/mine/JavaTutorial/LICENSE");
}
}
| 0 | 881 | 4 | 1,046 | 4 | 1,110 | 4 | 1,046 | 4 | 1,284 | 8 | false | false | false | false | false | true |
47478_1 | package com.dcx.concurrency.dcxTest;
//作者:卡巴拉的树
// 链接:https://juejin.im/post/5a38d2046fb9a045076fcb1f
// 来源:掘金
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
//厕所
//种族
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
class Employee implements Runnable {
private String id;
private Semaphore semaphore;
private static Random random = new Random(47);
public Employee(String id, Semaphore semaphore) {
this.id = id;
this.semaphore = semaphore;
}
public void run() {
try {
semaphore.acquire();
System.out.println(this.id + "is using the toilet");
TimeUnit.MILLISECONDS.sleep(random.nextInt(2000));
semaphore.release();
System.out.println(this.id + "is leaving");
} catch (InterruptedException e) {
}
}
}
public class ToiletRace {
private static final int THREAD_COUNT = 30;
private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
// 10个坑位 控制并行度
private static Semaphore semaphore = new Semaphore(10);
public static void main(String[] args) {
for (int i = 0; i < THREAD_COUNT; i++) {
threadPool.execute(new Employee(String.valueOf(i), semaphore));
}
threadPool.shutdown();
}
}
| EthanDCX/High-concurrency | src/main/java/com/dcx/concurrency/dcxTest/ToiletRace.java | 424 | // 链接:https://juejin.im/post/5a38d2046fb9a045076fcb1f | line_comment | zh-cn | package com.dcx.concurrency.dcxTest;
//作者:卡巴拉的树
// 链接 <SUF>
// 来源:掘金
// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
//厕所
//种族
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
class Employee implements Runnable {
private String id;
private Semaphore semaphore;
private static Random random = new Random(47);
public Employee(String id, Semaphore semaphore) {
this.id = id;
this.semaphore = semaphore;
}
public void run() {
try {
semaphore.acquire();
System.out.println(this.id + "is using the toilet");
TimeUnit.MILLISECONDS.sleep(random.nextInt(2000));
semaphore.release();
System.out.println(this.id + "is leaving");
} catch (InterruptedException e) {
}
}
}
public class ToiletRace {
private static final int THREAD_COUNT = 30;
private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT);
// 10个坑位 控制并行度
private static Semaphore semaphore = new Semaphore(10);
public static void main(String[] args) {
for (int i = 0; i < THREAD_COUNT; i++) {
threadPool.execute(new Employee(String.valueOf(i), semaphore));
}
threadPool.shutdown();
}
}
| 0 | 352 | 37 | 424 | 34 | 429 | 35 | 424 | 34 | 532 | 39 | false | false | false | false | false | true |
28574_6 | package TanXin;
import java.util.*;
/**
* @description:
* @author: wuboyu
* @date: 2022-07-21 16:58
*/
public class L56 {
//56. 合并区间
//以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。
//
//
//
//示例 1:
//
//输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
//输出:[[1,6],[8,10],[15,18]]
//解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
//示例 2:
//
//输入:intervals = [[1,4],[4,5]]
//输出:[[1,5]]
//解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。
//
//
//提示:
//
//1 <= intervals.length <= 104
//intervals[i].length == 2
//0 <= starti <= endi <= 104
public int[][] merge(int[][] intervals) {
//思路
//首先 按 左排序
//如果此区间的左>上一个的right 不合
//如果当前区间的左<=上一个的right 合并
Comparator<int[]> com=new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o1[0],o2[0]);
}
};
Arrays.sort(intervals,com);
LinkedList<int[]> answer=new LinkedList<>();
answer.add(intervals[0]);
int lastright=intervals[0][1];
for(int i=1;i<intervals.length;i++){
if(intervals[i][0]<=lastright){
//合并
//当前区间的左区间 在上一个区间的右区间中
int[] temp=answer.getLast();
answer.removeLast();
temp[1]=Math.max(intervals[i][1],lastright);
answer.add(temp);
lastright=Math.max(intervals[i][1],lastright);
}else {
//不合并
answer.add(intervals[i]);
lastright=intervals[i][1];
}
}
return answer.toArray(new int[answer.size()][]);
}
}
| Etherstrings/Algorithm | src/TanXin/L56.java | 639 | //解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. | line_comment | zh-cn | package TanXin;
import java.util.*;
/**
* @description:
* @author: wuboyu
* @date: 2022-07-21 16:58
*/
public class L56 {
//56. 合并区间
//以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。
//
//
//
//示例 1:
//
//输入:intervals = [[1,3],[2,6],[8,10],[15,18]]
//输出:[[1,6],[8,10],[15,18]]
//解释 <SUF>
//示例 2:
//
//输入:intervals = [[1,4],[4,5]]
//输出:[[1,5]]
//解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。
//
//
//提示:
//
//1 <= intervals.length <= 104
//intervals[i].length == 2
//0 <= starti <= endi <= 104
public int[][] merge(int[][] intervals) {
//思路
//首先 按 左排序
//如果此区间的左>上一个的right 不合
//如果当前区间的左<=上一个的right 合并
Comparator<int[]> com=new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o1[0],o2[0]);
}
};
Arrays.sort(intervals,com);
LinkedList<int[]> answer=new LinkedList<>();
answer.add(intervals[0]);
int lastright=intervals[0][1];
for(int i=1;i<intervals.length;i++){
if(intervals[i][0]<=lastright){
//合并
//当前区间的左区间 在上一个区间的右区间中
int[] temp=answer.getLast();
answer.removeLast();
temp[1]=Math.max(intervals[i][1],lastright);
answer.add(temp);
lastright=Math.max(intervals[i][1],lastright);
}else {
//不合并
answer.add(intervals[i]);
lastright=intervals[i][1];
}
}
return answer.toArray(new int[answer.size()][]);
}
}
| 0 | 598 | 29 | 639 | 30 | 657 | 27 | 639 | 30 | 791 | 40 | false | false | false | false | false | true |
46976_0 | package web;
import my_music.*;
import java.util.ArrayList;
import java.util.List;
public class Constants {
public static MusicDemo ErGe = new MusicDemo("快乐儿歌","无","佚名",0,0);
public final static MusicDemo Jiangjunling = new MusicDemo("将军令","五月天", "YOUR LEGEND ~燃烧的生命~", 0,0);
private static final User u1 = new User("Spark", "12121", "000", 0);
private static final User u2 = new User("降临者", "12121", "000", 0);
public static List<MusicDemo> musicLists = getMusicLists();
public static List<MusicDemo> getMusicLists(){
ArrayList<MusicDemo> musicDemos = new ArrayList<>();
Comments comments = new Comments();
//一些例子
comments.put(new SingleComment(u1, "太打动我了这首曲子!", new MyDate(2023,4,30,0,11,52)));
comments.put(new SingleComment(u2, "一个小评论!", new MyDate(2023,4,30,0,16,52)));
comments.put(new SingleComment(u1, "这是一个评论", new MyDate(2023,1,30,14,23,12)));
comments.put(new SingleComment(u1, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2022,11,6,13,11,52)));
comments.put(new SingleComment(u1, "这是依然一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52)));
comments.put(new SingleComment(u2, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52)));
comments.put(new SingleComment(new User("Knight", "16121", "000", 0), "好听", new MyDate(2023,4,30,0,11,52)));
musicDemos.add(ErGe);
Jiangjunling.setComments(comments);
musicDemos.add(Jiangjunling);
MusicDemo demo = new MusicDemo("转眼", "五月天", "自传", 0, 0);
demo.setComments(new Comments(new SingleComment(u1, "泪目", new MyDate(2022,10,14,16,29,4))));
musicDemos.add(demo);
musicDemos.add(new MusicDemo("兄弟","五月天","自传", 0,0));
musicDemos.add(new MusicDemo("顽固","五月天","自传", 0,0));
musicDemos.add(new MusicDemo("派对动物","五月天","自传",0,0));
musicDemos.add(new MusicDemo("干杯","五月天","第二人生-明日版",0,0));
return musicDemos;
}
}
| Ethylene9160/SUSTC_EE317_Android_applications | musicPlayer/src_server/web/Constants.java | 814 | //一些例子 | line_comment | zh-cn | package web;
import my_music.*;
import java.util.ArrayList;
import java.util.List;
public class Constants {
public static MusicDemo ErGe = new MusicDemo("快乐儿歌","无","佚名",0,0);
public final static MusicDemo Jiangjunling = new MusicDemo("将军令","五月天", "YOUR LEGEND ~燃烧的生命~", 0,0);
private static final User u1 = new User("Spark", "12121", "000", 0);
private static final User u2 = new User("降临者", "12121", "000", 0);
public static List<MusicDemo> musicLists = getMusicLists();
public static List<MusicDemo> getMusicLists(){
ArrayList<MusicDemo> musicDemos = new ArrayList<>();
Comments comments = new Comments();
//一些 <SUF>
comments.put(new SingleComment(u1, "太打动我了这首曲子!", new MyDate(2023,4,30,0,11,52)));
comments.put(new SingleComment(u2, "一个小评论!", new MyDate(2023,4,30,0,16,52)));
comments.put(new SingleComment(u1, "这是一个评论", new MyDate(2023,1,30,14,23,12)));
comments.put(new SingleComment(u1, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2022,11,6,13,11,52)));
comments.put(new SingleComment(u1, "这是依然一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52)));
comments.put(new SingleComment(u2, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52)));
comments.put(new SingleComment(new User("Knight", "16121", "000", 0), "好听", new MyDate(2023,4,30,0,11,52)));
musicDemos.add(ErGe);
Jiangjunling.setComments(comments);
musicDemos.add(Jiangjunling);
MusicDemo demo = new MusicDemo("转眼", "五月天", "自传", 0, 0);
demo.setComments(new Comments(new SingleComment(u1, "泪目", new MyDate(2022,10,14,16,29,4))));
musicDemos.add(demo);
musicDemos.add(new MusicDemo("兄弟","五月天","自传", 0,0));
musicDemos.add(new MusicDemo("顽固","五月天","自传", 0,0));
musicDemos.add(new MusicDemo("派对动物","五月天","自传",0,0));
musicDemos.add(new MusicDemo("干杯","五月天","第二人生-明日版",0,0));
return musicDemos;
}
}
| 0 | 705 | 3 | 814 | 3 | 791 | 3 | 814 | 3 | 925 | 5 | false | false | false | false | false | true |
45491_6 | package com.rookie.stack.ai.domain.chat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* @author eumenides
* @description
* @date 2023/11/28
*/
@Data
@Builder
@Slf4j
@JsonInclude(JsonInclude.Include.NON_NULL)
@NoArgsConstructor
@AllArgsConstructor
public class ChatCompletionRequest implements Serializable {
/** 默认模型 */
private String model = Model.GPT_3_5_TURBO.getCode();
/** 问题描述 */
private List<Message> messages;
/** 控制温度【随机性】;0到2之间。较高的值(如0.8)将使输出更加随机,而较低的值(如0.2)将使输出更加集中和确定 */
private double temperature = 0.2;
/** 多样性控制;使用温度采样的替代方法称为核心采样,其中模型考虑具有top_p概率质量的令牌的结果。因此,0.1 意味着只考虑包含前 10% 概率质量的代币 */
@JsonProperty("top_p")
private Double topP = 1d;
/** 为每个提示生成的完成次数 */
private Integer n = 1;
/** 是否为流式输出;就是一蹦一蹦的,出来结果 */
private boolean stream = false;
/** 停止输出标识 */
private List<String> stop;
/** 输出字符串限制;0 ~ 4096 */
@JsonProperty("max_tokens")
private Integer maxTokens = 2048;
/** 频率惩罚;降低模型重复同一行的可能性 */
@JsonProperty("frequency_penalty")
private double frequencyPenalty = 0;
/** 存在惩罚;增强模型谈论新话题的可能性 */
@JsonProperty("presence_penalty")
private double presencePenalty = 0;
/** 生成多个调用结果,只显示最佳的。这样会更多的消耗你的 api token */
@JsonProperty("logit_bias")
private Map logitBias;
/** 调用标识,避免重复调用 */
private String user;
@Getter
@AllArgsConstructor
public enum Model {
/** gpt-3.5-turbo */
GPT_3_5_TURBO("gpt-3.5-turbo"),
/** GPT4.0 */
GPT_4("gpt-4"),
/** GPT4.0 超长上下文 */
GPT_4_32K("gpt-4-32k"),
;
private String code;
}
}
| Eumenides1/rookie-gpt-sdk-java | src/main/java/com/rookie/stack/ai/domain/chat/ChatCompletionRequest.java | 678 | /** 是否为流式输出;就是一蹦一蹦的,出来结果 */ | block_comment | zh-cn | package com.rookie.stack.ai.domain.chat;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* @author eumenides
* @description
* @date 2023/11/28
*/
@Data
@Builder
@Slf4j
@JsonInclude(JsonInclude.Include.NON_NULL)
@NoArgsConstructor
@AllArgsConstructor
public class ChatCompletionRequest implements Serializable {
/** 默认模型 */
private String model = Model.GPT_3_5_TURBO.getCode();
/** 问题描述 */
private List<Message> messages;
/** 控制温度【随机性】;0到2之间。较高的值(如0.8)将使输出更加随机,而较低的值(如0.2)将使输出更加集中和确定 */
private double temperature = 0.2;
/** 多样性控制;使用温度采样的替代方法称为核心采样,其中模型考虑具有top_p概率质量的令牌的结果。因此,0.1 意味着只考虑包含前 10% 概率质量的代币 */
@JsonProperty("top_p")
private Double topP = 1d;
/** 为每个提示生成的完成次数 */
private Integer n = 1;
/** 是否为 <SUF>*/
private boolean stream = false;
/** 停止输出标识 */
private List<String> stop;
/** 输出字符串限制;0 ~ 4096 */
@JsonProperty("max_tokens")
private Integer maxTokens = 2048;
/** 频率惩罚;降低模型重复同一行的可能性 */
@JsonProperty("frequency_penalty")
private double frequencyPenalty = 0;
/** 存在惩罚;增强模型谈论新话题的可能性 */
@JsonProperty("presence_penalty")
private double presencePenalty = 0;
/** 生成多个调用结果,只显示最佳的。这样会更多的消耗你的 api token */
@JsonProperty("logit_bias")
private Map logitBias;
/** 调用标识,避免重复调用 */
private String user;
@Getter
@AllArgsConstructor
public enum Model {
/** gpt-3.5-turbo */
GPT_3_5_TURBO("gpt-3.5-turbo"),
/** GPT4.0 */
GPT_4("gpt-4"),
/** GPT4.0 超长上下文 */
GPT_4_32K("gpt-4-32k"),
;
private String code;
}
}
| 0 | 595 | 17 | 678 | 21 | 655 | 17 | 678 | 21 | 924 | 27 | false | false | false | false | false | true |
29042_0 | public class RealSubject implements Subject{
@Override
public void eat() {//吃饭
System.out.println("eating");
}
}
| Euraxluo/ProjectPractice | java/DesignPatternInJAVA/Proxy/src/RealSubject.java | 36 | //吃饭
| line_comment | zh-cn | public class RealSubject implements Subject{
@Override
public void eat() {//吃饭 <SUF>
System.out.println("eating");
}
}
| 0 | 30 | 3 | 35 | 5 | 36 | 3 | 35 | 5 | 44 | 8 | false | false | false | false | false | true |
56716_0 | class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList){
if (beginWord == null || endWord == null
|| beginWord.length() == 0 || endWord.length() == 0
|| beginWord.length() != endWord.length())
return 0;
// 此题关键是去重,还有去除和beginWord,相同的单词
Set<String> set = new HashSet<String>(wordList);
if (set.contains(beginWord))
set.remove(beginWord);
Queue<String> wordQueue = new LinkedList<String>();
int level = 1; // the start string already count for 1
int curnum = 1;// the candidate num on current level
int nextnum = 0;// counter for next level
// 或者使用map记录层数
// Map<String, Integer> map = new HashMap<String, Integer>();
// map.put(beginWord, 1);
wordQueue.add(beginWord);
while (!wordQueue.isEmpty()) {
String word = wordQueue.poll();
curnum--;
// int curLevel = map.get(word);
for (int i = 0; i < word.length(); i++) {
char[] wordunit = word.toCharArray();
for (char j = 'a'; j <= 'z'; j++) {
wordunit[i] = j;
String temp = new String(wordunit);
if (set.contains(temp)) {
if (temp.equals(endWord))
// return curLevel + 1;
return level + 1;
// map.put(temp, curLevel + 1);
nextnum++;
wordQueue.add(temp);
set.remove(temp);
}
}
}
if (curnum == 0) {
curnum = nextnum;
nextnum = 0;
level++;
}
}
return 0;
}
}
| Eurus-Holmes/LCED | Word Ladder.java | 490 | // 此题关键是去重,还有去除和beginWord,相同的单词 | line_comment | zh-cn | class Solution {
public int ladderLength(String beginWord, String endWord, List<String> wordList){
if (beginWord == null || endWord == null
|| beginWord.length() == 0 || endWord.length() == 0
|| beginWord.length() != endWord.length())
return 0;
// 此题 <SUF>
Set<String> set = new HashSet<String>(wordList);
if (set.contains(beginWord))
set.remove(beginWord);
Queue<String> wordQueue = new LinkedList<String>();
int level = 1; // the start string already count for 1
int curnum = 1;// the candidate num on current level
int nextnum = 0;// counter for next level
// 或者使用map记录层数
// Map<String, Integer> map = new HashMap<String, Integer>();
// map.put(beginWord, 1);
wordQueue.add(beginWord);
while (!wordQueue.isEmpty()) {
String word = wordQueue.poll();
curnum--;
// int curLevel = map.get(word);
for (int i = 0; i < word.length(); i++) {
char[] wordunit = word.toCharArray();
for (char j = 'a'; j <= 'z'; j++) {
wordunit[i] = j;
String temp = new String(wordunit);
if (set.contains(temp)) {
if (temp.equals(endWord))
// return curLevel + 1;
return level + 1;
// map.put(temp, curLevel + 1);
nextnum++;
wordQueue.add(temp);
set.remove(temp);
}
}
}
if (curnum == 0) {
curnum = nextnum;
nextnum = 0;
level++;
}
}
return 0;
}
}
| 0 | 426 | 16 | 490 | 19 | 489 | 16 | 490 | 19 | 624 | 27 | false | false | false | false | false | true |
31939_10 | package client.data;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
/**
*
*/
public class Txt2Excel {
public void txt2excel1() {
File file = new File("D:\\学习\\Slime's fighting\\account.txt");// 将读取的txt文件
File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.xls");// 将生成的excel表格
if (file.exists() && file.isFile()) {
InputStreamReader read = null;
BufferedReader input = null;
WritableWorkbook wbook = null;
WritableSheet sheet;
try {
read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
input = new BufferedReader(read);
Scanner scanner = new Scanner(read);
wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件
sheet = wbook.createSheet("first", 0);// 新标签页
try {
Label sName = new Label(0, 0, "");// 如下皆为列名
sheet.addCell(sName);
Label account = new Label(0, 0, "用户名");// 如下皆为列名
sheet.addCell(account);
Label pass = new Label(1, 0, "密码");
sheet.addCell(pass);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
int m = 1;// excel行数
int n = 0;// excel列数
int count = 0;
Label t;
while ((scanner.hasNext())) {
String word = scanner.next();
t = new Label(n, m, word.trim());
sheet.addCell(t);
n++;
count++;
if (count == 2) {
n = 0;// 回到列头部
m++;// 向下移动一行
count = 0;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} finally {
try {
wbook.write();
wbook.close();
input.close();
read.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
System.out.println("over!");
} else {
System.out.println("file is not exists or not a file");
}
}
public void txt2excel2() {
File file = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.txt");// 将读取的txt文件
File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\game_data.xls");// 将生成的excel表格
if (file.exists() && file.isFile()) {
InputStreamReader read = null;
BufferedReader input = null;
WritableWorkbook wbook = null;
WritableSheet sheet;
try {
read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
input = new BufferedReader(read);
Scanner scanner = new Scanner(read);
wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件
sheet = wbook.createSheet("first", 0);// 新标签页
try {
Label sName = new Label(0, 0, "");// 如下皆为列名
sheet.addCell(sName);
Label account = new Label(0, 0, "用户名");// 如下皆为列名
sheet.addCell(account);
Label team = new Label(1, 0, "队伍(0绿1蓝)");
sheet.addCell(team);
Label blood = new Label(2, 0, "剩余血量");
sheet.addCell(blood);
Label time = new Label(3, 0, "在线时长");
sheet.addCell(time);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
int m = 1;// excel行数
int n = 0;// excel列数
int count = 0;
Label t;
scanner.next();
scanner.next();
scanner.next();
scanner.next();
while ((scanner.hasNext())) {
String word = scanner.next();
t = new Label(n, m, word.trim());
sheet.addCell(t);
n++;
count++;
if (count == 4) {
n = 0;// 回到列头部
m++;// 向下移动一行
count = 0;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} finally {
try {
wbook.write();
wbook.close();
input.close();
read.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
System.out.println("over!");
} else {
System.out.println("file is not exists or not a file");
}
}
}
| Evelynn1014/BJTU-cxd-Slime-java-project | client/data/Txt2Excel.java | 1,373 | // 将读取的txt文件
| line_comment | zh-cn | package client.data;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;
/**
*
*/
public class Txt2Excel {
public void txt2excel1() {
File file = new File("D:\\学习\\Slime's fighting\\account.txt");// 将读取的txt文件
File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.xls");// 将生成的excel表格
if (file.exists() && file.isFile()) {
InputStreamReader read = null;
BufferedReader input = null;
WritableWorkbook wbook = null;
WritableSheet sheet;
try {
read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
input = new BufferedReader(read);
Scanner scanner = new Scanner(read);
wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件
sheet = wbook.createSheet("first", 0);// 新标签页
try {
Label sName = new Label(0, 0, "");// 如下皆为列名
sheet.addCell(sName);
Label account = new Label(0, 0, "用户名");// 如下皆为列名
sheet.addCell(account);
Label pass = new Label(1, 0, "密码");
sheet.addCell(pass);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
int m = 1;// excel行数
int n = 0;// excel列数
int count = 0;
Label t;
while ((scanner.hasNext())) {
String word = scanner.next();
t = new Label(n, m, word.trim());
sheet.addCell(t);
n++;
count++;
if (count == 2) {
n = 0;// 回到列头部
m++;// 向下移动一行
count = 0;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} finally {
try {
wbook.write();
wbook.close();
input.close();
read.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
System.out.println("over!");
} else {
System.out.println("file is not exists or not a file");
}
}
public void txt2excel2() {
File file = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.txt");// 将读 <SUF>
File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\game_data.xls");// 将生成的excel表格
if (file.exists() && file.isFile()) {
InputStreamReader read = null;
BufferedReader input = null;
WritableWorkbook wbook = null;
WritableSheet sheet;
try {
read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8);
input = new BufferedReader(read);
Scanner scanner = new Scanner(read);
wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件
sheet = wbook.createSheet("first", 0);// 新标签页
try {
Label sName = new Label(0, 0, "");// 如下皆为列名
sheet.addCell(sName);
Label account = new Label(0, 0, "用户名");// 如下皆为列名
sheet.addCell(account);
Label team = new Label(1, 0, "队伍(0绿1蓝)");
sheet.addCell(team);
Label blood = new Label(2, 0, "剩余血量");
sheet.addCell(blood);
Label time = new Label(3, 0, "在线时长");
sheet.addCell(time);
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
int m = 1;// excel行数
int n = 0;// excel列数
int count = 0;
Label t;
scanner.next();
scanner.next();
scanner.next();
scanner.next();
while ((scanner.hasNext())) {
String word = scanner.next();
t = new Label(n, m, word.trim());
sheet.addCell(t);
n++;
count++;
if (count == 4) {
n = 0;// 回到列头部
m++;// 向下移动一行
count = 0;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} finally {
try {
wbook.write();
wbook.close();
input.close();
read.close();
} catch (IOException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
}
}
System.out.println("over!");
} else {
System.out.println("file is not exists or not a file");
}
}
}
| 0 | 1,234 | 9 | 1,364 | 7 | 1,462 | 7 | 1,364 | 7 | 1,731 | 12 | false | false | false | false | false | true |
16451_1 | package db.log.sim;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import lombok.Data;
/**
* @Author : YangFan
* @Date : 2020年11月19日 10:10
* @effect : 获取sim卡、手机号
*/
@Data
public class Phone {
private Context context;
private TelephonyManager telephonyManager;
public Phone(Context context) {
this.context = context;
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
}
/**
* READ_PHONE_STATE
* @return 是否有读取手机状态的权限
* 电话 READ_PHONE_STATE 危险 允许对电话状态进行只读访问,包括设备的电话号码,当前蜂窝网络信息,任何正在进行的呼叫的状态以及设备上注册的任何PhoneAccounts列表
* 电话 CALL_PHONE 危险 允许应用程序在不通过拨号器用户界面的情况下发起电话呼叫,以便用户确认呼叫
* 电话 READ_CALL_LOG 危险 允许应用程序读取用户的通话记录
* 电话 WRITE_CALL_LOG 危险 允许应用程序写入(但不读取)用户的呼叫日志数据
* 电话 ADD_VOICEMAIL 危险 允许应用程序将语音邮件添加到系统中
* 电话 USE_SIP 危险 允许应用程序使用SIP服务
* 电话 PROCESS_OUTGOING_CALLS 危险 允许应用程序查看拨出呼叫期间拨打的号码,并选择将呼叫重定向到其他号码或完全中止呼叫
* 耗时3ms左右
*/
//获取SIM卡iccid
public String getIccid() {
String iccid = "N/A";
iccid = telephonyManager.getSimSerialNumber();
return iccid;
}
//获取电话号码
public String getNativePhoneNumber() {
String nativePhoneNumber = "N/A";
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_NUMBERS) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return nativePhoneNumber;
}
nativePhoneNumber = telephonyManager.getLine1Number();
return nativePhoneNumber;
}
}
| EvolvedHumans/EdgeAgent | CPE1/app/src/main/java/db/log/sim/Phone.java | 736 | /**
* READ_PHONE_STATE
* @return 是否有读取手机状态的权限
* 电话 READ_PHONE_STATE 危险 允许对电话状态进行只读访问,包括设备的电话号码,当前蜂窝网络信息,任何正在进行的呼叫的状态以及设备上注册的任何PhoneAccounts列表
* 电话 CALL_PHONE 危险 允许应用程序在不通过拨号器用户界面的情况下发起电话呼叫,以便用户确认呼叫
* 电话 READ_CALL_LOG 危险 允许应用程序读取用户的通话记录
* 电话 WRITE_CALL_LOG 危险 允许应用程序写入(但不读取)用户的呼叫日志数据
* 电话 ADD_VOICEMAIL 危险 允许应用程序将语音邮件添加到系统中
* 电话 USE_SIP 危险 允许应用程序使用SIP服务
* 电话 PROCESS_OUTGOING_CALLS 危险 允许应用程序查看拨出呼叫期间拨打的号码,并选择将呼叫重定向到其他号码或完全中止呼叫
* 耗时3ms左右
*/ | block_comment | zh-cn | package db.log.sim;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import lombok.Data;
/**
* @Author : YangFan
* @Date : 2020年11月19日 10:10
* @effect : 获取sim卡、手机号
*/
@Data
public class Phone {
private Context context;
private TelephonyManager telephonyManager;
public Phone(Context context) {
this.context = context;
telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
}
/**
* REA <SUF>*/
//获取SIM卡iccid
public String getIccid() {
String iccid = "N/A";
iccid = telephonyManager.getSimSerialNumber();
return iccid;
}
//获取电话号码
public String getNativePhoneNumber() {
String nativePhoneNumber = "N/A";
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_NUMBERS) !=
PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) !=
PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return nativePhoneNumber;
}
nativePhoneNumber = telephonyManager.getLine1Number();
return nativePhoneNumber;
}
}
| 0 | 601 | 233 | 736 | 284 | 714 | 247 | 736 | 284 | 1,036 | 494 | true | true | true | true | true | false |
3166_29 | package cn.exrick.xboot.common.utils;
import cn.exrick.xboot.common.exception.CaptchaException;
import cn.hutool.core.util.StrUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
/**
* 随机字符验证码生成工具类
* @author Exrickx
*/
public class CreateVerifyCode {
/**
* 随机字符
*/
public static final String STRING = "ABCDEFGHJKMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz1234567890";
/**
* 图片的宽度
*/
private int width = 160;
/**
* 图片的高度
*/
private int height = 40;
/**
* 验证码字符个数
*/
private int codeCount = 4;
/**
* 验证码干扰线数
*/
private int lineCount = 20;
/**
* 验证码
*/
private String code = null;
/**
* 验证码图片Buffer
*/
private BufferedImage buffImg = null;
SecureRandom random = new SecureRandom();
public CreateVerifyCode() {
creatImage();
}
public CreateVerifyCode(int width, int height) {
this.width = width;
this.height = height;
creatImage();
}
public CreateVerifyCode(int width, int height, int codeCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
creatImage();
}
public CreateVerifyCode(int width, int height, int codeCount, int lineCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
creatImage();
}
public CreateVerifyCode(int width, int height, int codeCount, int lineCount, String code) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
creatImage(code);
}
/**
* 生成图片
*/
private void creatImage() {
// 字体的宽度
int fontWidth = width / codeCount;
// 字体的高度
int fontHeight = height - 5;
int codeY = height - 8;
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = buffImg.getGraphics();
//Graphics2D g = buffImg.createGraphics();
// 设置背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设置字体
// Font font1 = getFont(fontHeight);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
g.setFont(font);
// 设置干扰线
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width);
int ye = ys + random.nextInt(height);
g.setColor(getRandColor(1, 255));
g.drawLine(xs, ys, xe, ye);
}
// 添加噪点 噪声率
float yawpRate = 0.01f;
int area = (int) (yawpRate * width * height);
for (int i = 0; i < area; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
buffImg.setRGB(x, y, random.nextInt(255));
}
// 得到随机字符
String str1 = randomStr(codeCount);
this.code = str1;
for (int i = 0; i < codeCount; i++) {
String strRand = str1.substring(i, i + 1);
g.setColor(getRandColor(1, 255));
// g.drawString(a,x,y);
// a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处
g.drawString(strRand, i * fontWidth + 3, codeY);
}
}
/**
* 生成指定字符图片
*/
private void creatImage(String code) {
if (StrUtil.isBlank(code)) {
throw new CaptchaException("验证码为空或已过期,请重新获取");
}
// 字体的宽度
int fontWidth = width / codeCount;
// 字体的高度
int fontHeight = height - 5;
int codeY = height - 8;
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = buffImg.getGraphics();
//Graphics2D g = buffImg.createGraphics();
// 设置背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设置字体
//Font font1 = getFont(fontHeight);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
g.setFont(font);
// 设置干扰线
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width);
int ye = ys + random.nextInt(height);
g.setColor(getRandColor(1, 255));
g.drawLine(xs, ys, xe, ye);
}
// 添加噪点 噪声率
float yawpRate = 0.01f;
int area = (int) (yawpRate * width * height);
for (int i = 0; i < area; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
buffImg.setRGB(x, y, random.nextInt(255));
}
this.code = code;
for (int i = 0; i < code.length(); i++) {
String strRand = code.substring(i, i + 1);
g.setColor(getRandColor(1, 255));
// g.drawString(a,x,y);
// a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处
g.drawString(strRand, i * fontWidth + 3, codeY);
}
}
/**
* 得到随机字符
* @param n
* @return
*/
public String randomStr(int n) {
String str = "";
int len = STRING.length() - 1;
double r;
for (int i = 0; i < n; i++) {
r = random.nextDouble() * len;
str = str + STRING.charAt((int) r);
}
return str;
}
/**
* 得到随机颜色
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
// 给定范围获得随机颜色
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
/**
* 产生随机字体
*/
private Font getFont(int size) {
Font[] font = new Font[5];
font[0] = new Font("Ravie", Font.PLAIN, size);
font[1] = new Font("Antique Olive Compact", Font.PLAIN, size);
font[2] = new Font("Fixedsys", Font.PLAIN, size);
font[3] = new Font("Wide Latin", Font.PLAIN, size);
font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size);
return font[random.nextInt(5)];
}
// 扭曲方法
private void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private void shearY(Graphics g, int w1, int h1, Color color) {
// 50
int period = random.nextInt(40) + 10;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
public void write(OutputStream sos) throws IOException {
ImageIO.write(buffImg, "png", sos);
sos.close();
}
public BufferedImage getBuffImg() {
return buffImg;
}
public String getCode() {
return code.toLowerCase();
}
}
| Exrick/xboot | xboot-fast/src/main/java/cn/exrick/xboot/common/utils/CreateVerifyCode.java | 2,567 | // 设置干扰线 | line_comment | zh-cn | package cn.exrick.xboot.common.utils;
import cn.exrick.xboot.common.exception.CaptchaException;
import cn.hutool.core.util.StrUtil;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.security.SecureRandom;
/**
* 随机字符验证码生成工具类
* @author Exrickx
*/
public class CreateVerifyCode {
/**
* 随机字符
*/
public static final String STRING = "ABCDEFGHJKMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz1234567890";
/**
* 图片的宽度
*/
private int width = 160;
/**
* 图片的高度
*/
private int height = 40;
/**
* 验证码字符个数
*/
private int codeCount = 4;
/**
* 验证码干扰线数
*/
private int lineCount = 20;
/**
* 验证码
*/
private String code = null;
/**
* 验证码图片Buffer
*/
private BufferedImage buffImg = null;
SecureRandom random = new SecureRandom();
public CreateVerifyCode() {
creatImage();
}
public CreateVerifyCode(int width, int height) {
this.width = width;
this.height = height;
creatImage();
}
public CreateVerifyCode(int width, int height, int codeCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
creatImage();
}
public CreateVerifyCode(int width, int height, int codeCount, int lineCount) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
creatImage();
}
public CreateVerifyCode(int width, int height, int codeCount, int lineCount, String code) {
this.width = width;
this.height = height;
this.codeCount = codeCount;
this.lineCount = lineCount;
creatImage(code);
}
/**
* 生成图片
*/
private void creatImage() {
// 字体的宽度
int fontWidth = width / codeCount;
// 字体的高度
int fontHeight = height - 5;
int codeY = height - 8;
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = buffImg.getGraphics();
//Graphics2D g = buffImg.createGraphics();
// 设置背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设置字体
// Font font1 = getFont(fontHeight);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
g.setFont(font);
// 设置干扰线
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width);
int ye = ys + random.nextInt(height);
g.setColor(getRandColor(1, 255));
g.drawLine(xs, ys, xe, ye);
}
// 添加噪点 噪声率
float yawpRate = 0.01f;
int area = (int) (yawpRate * width * height);
for (int i = 0; i < area; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
buffImg.setRGB(x, y, random.nextInt(255));
}
// 得到随机字符
String str1 = randomStr(codeCount);
this.code = str1;
for (int i = 0; i < codeCount; i++) {
String strRand = str1.substring(i, i + 1);
g.setColor(getRandColor(1, 255));
// g.drawString(a,x,y);
// a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处
g.drawString(strRand, i * fontWidth + 3, codeY);
}
}
/**
* 生成指定字符图片
*/
private void creatImage(String code) {
if (StrUtil.isBlank(code)) {
throw new CaptchaException("验证码为空或已过期,请重新获取");
}
// 字体的宽度
int fontWidth = width / codeCount;
// 字体的高度
int fontHeight = height - 5;
int codeY = height - 8;
// 图像buffer
buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = buffImg.getGraphics();
//Graphics2D g = buffImg.createGraphics();
// 设置背景色
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
// 设置字体
//Font font1 = getFont(fontHeight);
Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
g.setFont(font);
// 设置 <SUF>
for (int i = 0; i < lineCount; i++) {
int xs = random.nextInt(width);
int ys = random.nextInt(height);
int xe = xs + random.nextInt(width);
int ye = ys + random.nextInt(height);
g.setColor(getRandColor(1, 255));
g.drawLine(xs, ys, xe, ye);
}
// 添加噪点 噪声率
float yawpRate = 0.01f;
int area = (int) (yawpRate * width * height);
for (int i = 0; i < area; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
buffImg.setRGB(x, y, random.nextInt(255));
}
this.code = code;
for (int i = 0; i < code.length(); i++) {
String strRand = code.substring(i, i + 1);
g.setColor(getRandColor(1, 255));
// g.drawString(a,x,y);
// a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处
g.drawString(strRand, i * fontWidth + 3, codeY);
}
}
/**
* 得到随机字符
* @param n
* @return
*/
public String randomStr(int n) {
String str = "";
int len = STRING.length() - 1;
double r;
for (int i = 0; i < n; i++) {
r = random.nextDouble() * len;
str = str + STRING.charAt((int) r);
}
return str;
}
/**
* 得到随机颜色
* @param fc
* @param bc
* @return
*/
private Color getRandColor(int fc, int bc) {
// 给定范围获得随机颜色
if (fc > 255) {
fc = 255;
}
if (bc > 255) {
bc = 255;
}
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
/**
* 产生随机字体
*/
private Font getFont(int size) {
Font[] font = new Font[5];
font[0] = new Font("Ravie", Font.PLAIN, size);
font[1] = new Font("Antique Olive Compact", Font.PLAIN, size);
font[2] = new Font("Fixedsys", Font.PLAIN, size);
font[3] = new Font("Wide Latin", Font.PLAIN, size);
font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size);
return font[random.nextInt(5)];
}
// 扭曲方法
private void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private void shearY(Graphics g, int w1, int h1, Color color) {
// 50
int period = random.nextInt(40) + 10;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
public void write(OutputStream sos) throws IOException {
ImageIO.write(buffImg, "png", sos);
sos.close();
}
public BufferedImage getBuffImg() {
return buffImg;
}
public String getCode() {
return code.toLowerCase();
}
}
| 0 | 2,359 | 4 | 2,567 | 6 | 2,720 | 4 | 2,567 | 6 | 3,185 | 11 | false | false | false | false | false | true |
4963_1 | package cn.exrick.service.impl;
import cn.exrick.bean.Pay;
import cn.exrick.bean.dto.Count;
import cn.exrick.common.utils.DateUtils;
import cn.exrick.common.utils.StringUtils;
import cn.exrick.dao.PayDao;
import cn.exrick.service.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author Exrickx
*/
@Service
public class PayServiceImpl implements PayService {
private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class);
@Autowired
private PayDao payDao;
@Override
public Page<Pay> getPayListByPage(Integer state, String key, Pageable pageable) {
return payDao.findAll(new Specification<Pay>() {
@Override
public Predicate toPredicate(Root<Pay> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
Path<String> nickNameField = root.get("nickName");
Path<String> infoField = root.get("info");
Path<String> payTypeField=root.get("payType");
Path<Integer> stateField=root.get("state");
List<Predicate> list = new ArrayList<Predicate>();
//模糊搜素
if(StringUtils.isNotBlank(key)){
Predicate p1 = cb.like(nickNameField,'%'+key+'%');
Predicate p3 = cb.like(infoField,'%'+key+'%');
Predicate p4 = cb.like(payTypeField,'%'+key+'%');
list.add(cb.or(p1,p3,p4));
}
//状态
if(state!=null){
list.add(cb.equal(stateField, state));
}
Predicate[] arr = new Predicate[list.size()];
cq.where(list.toArray(arr));
return null;
}
}, pageable);
}
@Override
public List<Pay> getPayList(Integer state) {
List<Pay> list=payDao.getByStateIs(state);
for(Pay pay:list){
//屏蔽隐私数据
pay.setId("");
pay.setEmail("");
pay.setTestEmail("");
pay.setPayNum(null);
pay.setMobile(null);
pay.setCustom(null);
pay.setDevice(null);
}
return list;
}
@Override
public Pay getPay(String id) {
Pay pay=payDao.findOne(id);
pay.setTime(StringUtils.getTimeStamp(pay.getCreateTime()));
return pay;
}
@Override
public int addPay(Pay pay) {
pay.setId(UUID.randomUUID().toString());
pay.setCreateTime(new Date());
pay.setState(0);
payDao.save(pay);
return 1;
}
@Override
public int updatePay(Pay pay) {
pay.setUpdateTime(new Date());
payDao.saveAndFlush(pay);
return 1;
}
@Override
public int changePayState(String id, Integer state) {
Pay pay=getPay(id);
pay.setState(state);
pay.setUpdateTime(new Date());
payDao.saveAndFlush(pay);
return 1;
}
@Override
public int delPay(String id) {
payDao.delete(id);
return 1;
}
@Override
public Count statistic(Integer type, String start, String end) {
Count count=new Count();
if(type==-1){
// 总
count.setAmount(payDao.countAllMoney());
count.setAlipay(payDao.countAllMoneyByType("Alipay"));
count.setWechat(payDao.countAllMoneyByType("Wechat"));
count.setQq(payDao.countAllMoneyByType("QQ"));
count.setUnion(payDao.countAllMoneyByType("UnionPay"));
count.setDiandan(payDao.countAllMoneyByType("Diandan"));
return count;
}
Date startDate=null,endDate=null;
if(type==0){
// 今天
startDate = DateUtils.getDayBegin();
endDate = DateUtils.getDayEnd();
}if(type==6){
// 昨天
startDate = DateUtils.getBeginDayOfYesterday();
endDate = DateUtils.getEndDayOfYesterDay();
}else if(type==1){
// 本周
startDate = DateUtils.getBeginDayOfWeek();
endDate = DateUtils.getEndDayOfWeek();
}else if(type==2){
// 本月
startDate = DateUtils.getBeginDayOfMonth();
endDate = DateUtils.getEndDayOfMonth();
}else if(type==3){
// 本年
startDate = DateUtils.getBeginDayOfYear();
endDate = DateUtils.getEndDayOfYear();
}else if(type==4){
// 上周
startDate = DateUtils.getBeginDayOfLastWeek();
endDate = DateUtils.getEndDayOfLastWeek();
}else if(type==5){
// 上个月
startDate = DateUtils.getBeginDayOfLastMonth();
endDate = DateUtils.getEndDayOfLastMonth();
}else if(type==-2){
// 自定义
startDate = DateUtils.parseStartDate(start);
endDate = DateUtils.parseEndDate(end);
}
count.setAmount(payDao.countMoney(startDate, endDate));
count.setAlipay(payDao.countMoneyByType("Alipay", startDate, endDate));
count.setWechat(payDao.countMoneyByType("Wechat", startDate, endDate));
count.setQq(payDao.countMoneyByType("QQ", startDate, endDate));
count.setUnion(payDao.countMoneyByType("UnionPay", startDate, endDate));
count.setDiandan(payDao.countMoneyByType("Diandan", startDate, endDate));
return count;
}
}
| Exrick/xpay | xpay-code/src/main/java/cn/exrick/service/impl/PayServiceImpl.java | 1,487 | //模糊搜素
| line_comment | zh-cn | package cn.exrick.service.impl;
import cn.exrick.bean.Pay;
import cn.exrick.bean.dto.Count;
import cn.exrick.common.utils.DateUtils;
import cn.exrick.common.utils.StringUtils;
import cn.exrick.dao.PayDao;
import cn.exrick.service.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.*;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
/**
* @author Exrickx
*/
@Service
public class PayServiceImpl implements PayService {
private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class);
@Autowired
private PayDao payDao;
@Override
public Page<Pay> getPayListByPage(Integer state, String key, Pageable pageable) {
return payDao.findAll(new Specification<Pay>() {
@Override
public Predicate toPredicate(Root<Pay> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {
Path<String> nickNameField = root.get("nickName");
Path<String> infoField = root.get("info");
Path<String> payTypeField=root.get("payType");
Path<Integer> stateField=root.get("state");
List<Predicate> list = new ArrayList<Predicate>();
//模糊 <SUF>
if(StringUtils.isNotBlank(key)){
Predicate p1 = cb.like(nickNameField,'%'+key+'%');
Predicate p3 = cb.like(infoField,'%'+key+'%');
Predicate p4 = cb.like(payTypeField,'%'+key+'%');
list.add(cb.or(p1,p3,p4));
}
//状态
if(state!=null){
list.add(cb.equal(stateField, state));
}
Predicate[] arr = new Predicate[list.size()];
cq.where(list.toArray(arr));
return null;
}
}, pageable);
}
@Override
public List<Pay> getPayList(Integer state) {
List<Pay> list=payDao.getByStateIs(state);
for(Pay pay:list){
//屏蔽隐私数据
pay.setId("");
pay.setEmail("");
pay.setTestEmail("");
pay.setPayNum(null);
pay.setMobile(null);
pay.setCustom(null);
pay.setDevice(null);
}
return list;
}
@Override
public Pay getPay(String id) {
Pay pay=payDao.findOne(id);
pay.setTime(StringUtils.getTimeStamp(pay.getCreateTime()));
return pay;
}
@Override
public int addPay(Pay pay) {
pay.setId(UUID.randomUUID().toString());
pay.setCreateTime(new Date());
pay.setState(0);
payDao.save(pay);
return 1;
}
@Override
public int updatePay(Pay pay) {
pay.setUpdateTime(new Date());
payDao.saveAndFlush(pay);
return 1;
}
@Override
public int changePayState(String id, Integer state) {
Pay pay=getPay(id);
pay.setState(state);
pay.setUpdateTime(new Date());
payDao.saveAndFlush(pay);
return 1;
}
@Override
public int delPay(String id) {
payDao.delete(id);
return 1;
}
@Override
public Count statistic(Integer type, String start, String end) {
Count count=new Count();
if(type==-1){
// 总
count.setAmount(payDao.countAllMoney());
count.setAlipay(payDao.countAllMoneyByType("Alipay"));
count.setWechat(payDao.countAllMoneyByType("Wechat"));
count.setQq(payDao.countAllMoneyByType("QQ"));
count.setUnion(payDao.countAllMoneyByType("UnionPay"));
count.setDiandan(payDao.countAllMoneyByType("Diandan"));
return count;
}
Date startDate=null,endDate=null;
if(type==0){
// 今天
startDate = DateUtils.getDayBegin();
endDate = DateUtils.getDayEnd();
}if(type==6){
// 昨天
startDate = DateUtils.getBeginDayOfYesterday();
endDate = DateUtils.getEndDayOfYesterDay();
}else if(type==1){
// 本周
startDate = DateUtils.getBeginDayOfWeek();
endDate = DateUtils.getEndDayOfWeek();
}else if(type==2){
// 本月
startDate = DateUtils.getBeginDayOfMonth();
endDate = DateUtils.getEndDayOfMonth();
}else if(type==3){
// 本年
startDate = DateUtils.getBeginDayOfYear();
endDate = DateUtils.getEndDayOfYear();
}else if(type==4){
// 上周
startDate = DateUtils.getBeginDayOfLastWeek();
endDate = DateUtils.getEndDayOfLastWeek();
}else if(type==5){
// 上个月
startDate = DateUtils.getBeginDayOfLastMonth();
endDate = DateUtils.getEndDayOfLastMonth();
}else if(type==-2){
// 自定义
startDate = DateUtils.parseStartDate(start);
endDate = DateUtils.parseEndDate(end);
}
count.setAmount(payDao.countMoney(startDate, endDate));
count.setAlipay(payDao.countMoneyByType("Alipay", startDate, endDate));
count.setWechat(payDao.countMoneyByType("Wechat", startDate, endDate));
count.setQq(payDao.countMoneyByType("QQ", startDate, endDate));
count.setUnion(payDao.countMoneyByType("UnionPay", startDate, endDate));
count.setDiandan(payDao.countMoneyByType("Diandan", startDate, endDate));
return count;
}
}
| 0 | 1,252 | 5 | 1,467 | 8 | 1,559 | 5 | 1,467 | 8 | 1,814 | 10 | false | false | false | false | false | true |
52668_1 | package com.atguigu.practiceNo2.juc;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
//6辆汽车停三个停车位
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i <= 6; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "停车");
//随机停车时间
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + "离开");
} catch (Exception e) {
e.printStackTrace();
} finally {
//释放
semaphore.release();
}
}, "线程" + i).start();
}
}
}
| Ezrabin/juc_atguigu | src/com/atguigu/practiceNo2/juc/SemaphoreDemo.java | 217 | //随机停车时间 | line_comment | zh-cn | package com.atguigu.practiceNo2.juc;
import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class SemaphoreDemo {
public static void main(String[] args) {
//6辆汽车停三个停车位
Semaphore semaphore = new Semaphore(3);
for (int i = 0; i <= 6; i++) {
new Thread(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + "停车");
//随机 <SUF>
TimeUnit.SECONDS.sleep(new Random().nextInt(5));
System.out.println(Thread.currentThread().getName() + "离开");
} catch (Exception e) {
e.printStackTrace();
} finally {
//释放
semaphore.release();
}
}, "线程" + i).start();
}
}
}
| 0 | 179 | 4 | 217 | 5 | 225 | 4 | 217 | 5 | 298 | 13 | false | false | false | false | false | true |
58892_37 | package com.videogo.ui.login;
import java.util.ArrayList;
import java.util.List;
/**
* 开放平台服务端在分为海外和国内,海外又分为5个大区
* (北美、南美、新加坡(亚洲)、俄罗斯、欧洲)
* 必须根据当前使用的AppKey对应大区切换到所在大区的服务器
* 否则EZOpenSDK的接口调用将会出现异常
*/
public enum ServerAreasEnum {
/**
* 国内
*/
ASIA_CHINA(0,"Asia-China", "https://open.ys7.com",
"https://openauth.ys7.com",
"26810f3acd794862b608b6cfbc32a6b8"),
/**
* 海外:俄罗斯
*/
ASIA_Russia(5, "Asia-Russia", "https://irusopen.ezvizru.com",
"https://irusopenauth.ezvizru.com", true),
/**
* 海外:亚洲
* (服务亚洲的所有国家,但不包括中国和俄罗斯)
*/
ASIA(10, "Asia", "https://isgpopen.ezvizlife.com",
"https://isgpopenauth.ezvizlife.com", true),
/**
* 海外:北美洲
*/
NORTH_AMERICA(15,"North America", "https://iusopen.ezvizlife.com",
"https://iusopenauth.ezvizlife.com", true),
/**
* 海外:南美洲
*/
SOUTH_AMERICA(20, "South America", "https://isaopen.ezvizlife.com",
"https://isaopenauth.ezvizlife.com", true),
/**
* 海外:欧洲
*/
EUROPE(25, "Europe", "https://ieuopen.ezvizlife.com",
"https://ieuopenauth.ezvizlife.com",
"5cadedf5478d11e7ae26fa163e8bac01",
true),
OTHER(26, "Other", "",
"",
"1111"),
OTHER_GLOBAL(27, "Other Global", "",
"",
"1111",
true),
/*线上平台的id范围为0到99,测试平台的id范围为100+*/
/**
* 测试平台:test12
*/
TEST12(110, "test12", "https://test12open.ys7.com",
"https://test12openauth.ys7.com",
"b22035492c7949bca95286382ed90b01"),
/**
* 测试平台:testcn
*/
TEST_CN(115, "testcn", "https://testcnopen.ezvizlife.com",
"https://testcnopenauth.ezvizlife.com", true),
/**
* 测试平台:testus
*/
TEST_US(120, "testus", "https://testusopen.ezvizlife.com",
"https://testusopenauth.ezvizlife.com", true),
/**
* 测试平台:testeu
*/
// TEST_EU(125, "testeu", "https://testeuopen.ezvizlife.com",
// "https://testeuopenauth.ezvizlife.com", true),
TEST_EU(125, "testeu", "https://ys-open.wens.com.cn",
"https://test2auth.ys7.com:8643", true),
/**
* 温氏
*/
WENSHI(126, "WenShi", "https://ezcpcloudopen.wens.com.cn",
"https://ezcpcloudopenauth.wens.com.cn", false),
/**
* 华住
*/
HUAZHU(127, "HuaZhu", "https://ezcpatctestopen.ys7.com",
"https://ezcpatctestopenauth.ys7.com", false);
// TEST_NEW(130,"testnew", "https://ys-open.wens.com.cn",
// "https://test2auth.ys7.com:8643", true);
public int id;
public String areaName;
public String openApiServer;
public String openAuthApiServer;
// 预置的用于测试h5登录的appKey(该appKey的bundleId已绑定到ezviz.opensdk)
public String defaultOpenAuthAppKey;
// 是否正在海外域名,海外域名需要使用GlobalEZOpenSDK,反之使用EZOpenSDK
public boolean usingGlobalSDK;
ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer){
this(id, areaName, openApiServer, openAuthApiServer, null, false);
}
ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey){
this(id, areaName, openApiServer, openAuthApiServer, defaultOpenAuthAppKey, false);
}
ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, boolean usingGlobalSDK){
this(id, areaName, openApiServer, openAuthApiServer, null, usingGlobalSDK);
}
ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey, boolean usingGlobalSDK){
this.id = id;
this.areaName = areaName;
this.openApiServer = openApiServer;
this.openAuthApiServer = openAuthApiServer;
this.defaultOpenAuthAppKey = defaultOpenAuthAppKey;
this.usingGlobalSDK = usingGlobalSDK;
}
public static List<ServerAreasEnum> getAllServers(){
List<ServerAreasEnum> serversList = new ArrayList<>();
for (ServerAreasEnum server : values()) {
boolean isTestServer = server.id >= 100;
// 线上demo不展示测试平台
if (!com.videogo.openapi.BuildConfig.DEBUG && isTestServer) {
continue;
}
serversList.add(server);
}
return serversList;
}
@Override
public String toString() {
return "id: " + id + ", " + "areaName: " + areaName + ", " + "openApiServer: " + openApiServer + ", " + "openAuthApiServer: " + openAuthApiServer;
}
}
| Ezviz-Open/EzvizSDK-Android | app/src/main/java/com/videogo/ui/login/ServerAreasEnum.java | 1,598 | /**
* 华住
*/ | block_comment | zh-cn | package com.videogo.ui.login;
import java.util.ArrayList;
import java.util.List;
/**
* 开放平台服务端在分为海外和国内,海外又分为5个大区
* (北美、南美、新加坡(亚洲)、俄罗斯、欧洲)
* 必须根据当前使用的AppKey对应大区切换到所在大区的服务器
* 否则EZOpenSDK的接口调用将会出现异常
*/
public enum ServerAreasEnum {
/**
* 国内
*/
ASIA_CHINA(0,"Asia-China", "https://open.ys7.com",
"https://openauth.ys7.com",
"26810f3acd794862b608b6cfbc32a6b8"),
/**
* 海外:俄罗斯
*/
ASIA_Russia(5, "Asia-Russia", "https://irusopen.ezvizru.com",
"https://irusopenauth.ezvizru.com", true),
/**
* 海外:亚洲
* (服务亚洲的所有国家,但不包括中国和俄罗斯)
*/
ASIA(10, "Asia", "https://isgpopen.ezvizlife.com",
"https://isgpopenauth.ezvizlife.com", true),
/**
* 海外:北美洲
*/
NORTH_AMERICA(15,"North America", "https://iusopen.ezvizlife.com",
"https://iusopenauth.ezvizlife.com", true),
/**
* 海外:南美洲
*/
SOUTH_AMERICA(20, "South America", "https://isaopen.ezvizlife.com",
"https://isaopenauth.ezvizlife.com", true),
/**
* 海外:欧洲
*/
EUROPE(25, "Europe", "https://ieuopen.ezvizlife.com",
"https://ieuopenauth.ezvizlife.com",
"5cadedf5478d11e7ae26fa163e8bac01",
true),
OTHER(26, "Other", "",
"",
"1111"),
OTHER_GLOBAL(27, "Other Global", "",
"",
"1111",
true),
/*线上平台的id范围为0到99,测试平台的id范围为100+*/
/**
* 测试平台:test12
*/
TEST12(110, "test12", "https://test12open.ys7.com",
"https://test12openauth.ys7.com",
"b22035492c7949bca95286382ed90b01"),
/**
* 测试平台:testcn
*/
TEST_CN(115, "testcn", "https://testcnopen.ezvizlife.com",
"https://testcnopenauth.ezvizlife.com", true),
/**
* 测试平台:testus
*/
TEST_US(120, "testus", "https://testusopen.ezvizlife.com",
"https://testusopenauth.ezvizlife.com", true),
/**
* 测试平台:testeu
*/
// TEST_EU(125, "testeu", "https://testeuopen.ezvizlife.com",
// "https://testeuopenauth.ezvizlife.com", true),
TEST_EU(125, "testeu", "https://ys-open.wens.com.cn",
"https://test2auth.ys7.com:8643", true),
/**
* 温氏
*/
WENSHI(126, "WenShi", "https://ezcpcloudopen.wens.com.cn",
"https://ezcpcloudopenauth.wens.com.cn", false),
/**
* 华住
<SUF>*/
HUAZHU(127, "HuaZhu", "https://ezcpatctestopen.ys7.com",
"https://ezcpatctestopenauth.ys7.com", false);
// TEST_NEW(130,"testnew", "https://ys-open.wens.com.cn",
// "https://test2auth.ys7.com:8643", true);
public int id;
public String areaName;
public String openApiServer;
public String openAuthApiServer;
// 预置的用于测试h5登录的appKey(该appKey的bundleId已绑定到ezviz.opensdk)
public String defaultOpenAuthAppKey;
// 是否正在海外域名,海外域名需要使用GlobalEZOpenSDK,反之使用EZOpenSDK
public boolean usingGlobalSDK;
ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer){
this(id, areaName, openApiServer, openAuthApiServer, null, false);
}
ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey){
this(id, areaName, openApiServer, openAuthApiServer, defaultOpenAuthAppKey, false);
}
ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, boolean usingGlobalSDK){
this(id, areaName, openApiServer, openAuthApiServer, null, usingGlobalSDK);
}
ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey, boolean usingGlobalSDK){
this.id = id;
this.areaName = areaName;
this.openApiServer = openApiServer;
this.openAuthApiServer = openAuthApiServer;
this.defaultOpenAuthAppKey = defaultOpenAuthAppKey;
this.usingGlobalSDK = usingGlobalSDK;
}
public static List<ServerAreasEnum> getAllServers(){
List<ServerAreasEnum> serversList = new ArrayList<>();
for (ServerAreasEnum server : values()) {
boolean isTestServer = server.id >= 100;
// 线上demo不展示测试平台
if (!com.videogo.openapi.BuildConfig.DEBUG && isTestServer) {
continue;
}
serversList.add(server);
}
return serversList;
}
@Override
public String toString() {
return "id: " + id + ", " + "areaName: " + areaName + ", " + "openApiServer: " + openApiServer + ", " + "openAuthApiServer: " + openAuthApiServer;
}
}
| 0 | 1,472 | 9 | 1,592 | 8 | 1,620 | 9 | 1,592 | 8 | 1,886 | 12 | false | false | false | false | false | true |