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
15265_22
package com.GUI; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.Timer; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.geom.Ellipse2D; import java.util.ArrayList; public class CityBtn extends JButton { private int xOld = 0; private int yOld = 0; public Timer timer; private int clickTimes = 0; private boolean isPressed = false; private int btnWidth = 30; private int btnHeight = 30; private RoundPanel parent; private int startX = 0; private int startY = 0; private int lastX = 0; private int lastY = 0; private int id = 0; private String strCityInfo = new String(); public ArrayList<ArcInfo> listArcInfo = new ArrayList<>(); public MainWindow frameMainWindow; public JLabel labelCityName; private boolean isClicked = false; public String getStrCityInfo() { return strCityInfo; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setStrCityInfo(String strCityInfo) { this.strCityInfo = strCityInfo; } public void setClicked(boolean clicked) { isClicked = clicked; } ActionListener taskPerformer = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //System.out.println("time on"); if (clickTimes < 2) { clickTimes = 0;//如果时间到了还没双击那就不算了,此次双击失效 timer.stop(); } } }; CityBtn(MainWindow frameMainWindow, int id) { super(); //初始化定时器 this.id = id; timer = new Timer(300, taskPerformer); this.frameMainWindow = frameMainWindow; parent = (RoundPanel) this.getParent(); labelCityName = new JLabel(); setPreferredSize(new Dimension(btnWidth, btnHeight)); setSize(btnWidth, btnHeight); Font font = new Font("微软雅黑", Font.BOLD, 14); labelCityName.setFont(font); labelCityName.setForeground(new Color(116, 169, 181)); labelCityName.setVisible(true); setContentAreaFilled(false); this.setBorderPainted(false); // 不绘制边框 this.setFocusPainted(false); // 不绘制焦点状态 this.setSelected(true); labelCityName.setHorizontalAlignment(SwingConstants.CENTER); CityBtn that = this; //鼠标单击点击事件 this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == 1) { clickTimes++;//每点一次点击次数加1 xOld = e.getX();//记录鼠标按下时的坐标 yOld = e.getY(); if (!timer.isRunning()) ;//如果定时器未启动就启动 timer.start(); if (frameMainWindow.paintPad.isSettingArc()) {//在设置边的情况下按钮被点击了说明被点击的这个按钮是终点 clickTimes = 0; if (that.id == frameMainWindow.cityBtnCurrent.id) { frameMainWindow.logToWindow("不能设置自己到自己"); frameMainWindow.paintPad.setSettingArc(false); return; } //添加边到当前城市 if (frameMainWindow.cityBtnCurrent.addArcToVel(that, 0, true)) { frameMainWindow.logToWindow("添加成功"); that.addArcToVel(frameMainWindow.cityBtnCurrent, 0, false);//添加成功则添加反向的边 } else { frameMainWindow.logToWindow("边重复"); } ; frameMainWindow.paintPad.setSettingArc(false); } else { frameMainWindow.cityBtnCurrent = that; frameMainWindow.textFieldCityName.setText(labelCityName.getText()); frameMainWindow.roundTextArea.textAreaReal.setText(strCityInfo); Component cp = (Component) e.getSource(); //获取事件e的触发源 //当鼠标点下的时候记录组件当前的坐标与鼠标当前在屏幕的位置 //System.out.println(cp.getX() + " "+cp.getY()); if (getParent().getBounds().contains(xOld, yOld)) { xOld = cp.getX(); yOld = cp.getY(); startX = e.getXOnScreen(); startY = e.getYOnScreen(); isPressed = true; } frameMainWindow.paintPad.repaint(); if (clickTimes == 2) {//如果检测到双击 //这里执行双击事件 //System.out.println("检测到双击"); //System.out.println(getBounds()); //System.out.println(xOld + " : " + yOld); if (getBounds().contains(xOld, yOld)) { //检测到画板内双击 doubleClick(); } timer.stop(); clickTimes = 0; } } } } @Override public void mouseReleased(MouseEvent e) { isPressed = false; } }); this.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { //System.out.println(isPressed); if(isPressed){ int xOnScr = e.getXOnScreen(); int yOnScr = e.getYOnScreen(); int xx = (xOnScr - startX) + xOld; int yy = (yOnScr - startY) + yOld; //如果太靠近边界应该触发保护,防止城市丢失 Rectangle r = getParent().getBounds(); int shrinkPixel = 10;//缩小一周的宽度 r.x += shrinkPixel; r.y += shrinkPixel; r.width -= 2 * shrinkPixel; r.height -= 2 * shrinkPixel; if (!r.contains(xx + getWidth() / 2, yy + getHeight() / 2)) { CityBtn.this.setLocation(lastX, lastY); return; } CityBtn.this.setLocation(xx, yy);//设置拖拽后,窗口的位置 labelCityName.setLocation(xx - 25, yy + getHeight() / 2 + 5);//设置文本拖拽后的位置 lastX = xx; lastY = yy; } } }); } public void doubleClick() { frameMainWindow.paintPad.setSettingArc(true); frameMainWindow.paintPad.setPointStart(new Point(getX() + getWidth() / 2, getY() + getHeight() / 2)); frameMainWindow.paintPad.setPointEndLast(new Point(getX() + getWidth() / 2, getY() + getHeight() / 2)); } protected void paintComponent(Graphics g) { //设置抗锯齿 Graphics2D g2d = (Graphics2D) g; //System.out.println(w.getGraphics()); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (getModel().isArmed()) { g.setColor(Color.lightGray); // 点击时高亮 } else if (frameMainWindow.cityBtnCurrent == this) { g.setColor(Color.YELLOW); } else { g.setColor(getBackground()); } // fillOval方法画一个矩形的内切椭圆,并且填充这个椭圆, // 当矩形为正方形时,画出的椭圆便是圆 g.fillOval(0, 0, getSize().width - 1, getSize().height - 1); super.paintComponent(g); } // 用简单的弧画按钮的边界。 protected void paintBorder(Graphics g) { g.setColor(Color.white); // drawOval方法画矩形的内切椭圆,但不填充。只画出一个边界 g.drawOval(0, 0, getSize().width - 1, getSize().height - 1); } // shape对象用于保存按钮的形状,有助于侦听点击按钮事件 Shape shape; public boolean contains(int x, int y) { if ((shape == null) || (!shape.getBounds().equals(getBounds()))) { // 构造一个椭圆形对象 shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight()); } // 判断鼠标的x、y坐标是否落在按钮形状内。 return shape.contains(x, y); } private boolean addArcToVel(CityBtn target, int distance, boolean ifDraw) { //将info无重复地加到btn内 ArcInfo arcInfo = new ArcInfo(this, target, ifDraw, 0); //将画板的指针给到输入框这样输入框输入时画板不会刷新 if (ifDraw) arcInfo.setTextFieldOnArc(new TextFieldOnArc(frameMainWindow, arcInfo)); for (ArcInfo tempArc : this.listArcInfo) { if (tempArc.equal(arcInfo)) {//已经添加过这条边,就不加了 System.out.println("已经添加过这条边"); frameMainWindow.paintPad.setSettingArc(false); frameMainWindow.paintPad.setInputing(true); return false; } } this.listArcInfo.add(arcInfo); return true; } public String toString() { return this.labelCityName.getText(); } public boolean isNearOrigin(CityBtn another){ for (ArcInfo cityBtnTemp : another.listArcInfo){ if (cityBtnTemp.getmStart().equals(this)){ return true; } } return false; } }
Cheny5863/Pedlar
src/com/GUI/CityBtn.java
2,500
//如果太靠近边界应该触发保护,防止城市丢失
line_comment
zh-cn
package com.GUI; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.SwingConstants; import javax.swing.Timer; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.awt.geom.Ellipse2D; import java.util.ArrayList; public class CityBtn extends JButton { private int xOld = 0; private int yOld = 0; public Timer timer; private int clickTimes = 0; private boolean isPressed = false; private int btnWidth = 30; private int btnHeight = 30; private RoundPanel parent; private int startX = 0; private int startY = 0; private int lastX = 0; private int lastY = 0; private int id = 0; private String strCityInfo = new String(); public ArrayList<ArcInfo> listArcInfo = new ArrayList<>(); public MainWindow frameMainWindow; public JLabel labelCityName; private boolean isClicked = false; public String getStrCityInfo() { return strCityInfo; } public int getId() { return id; } public void setId(int id) { this.id = id; } public void setStrCityInfo(String strCityInfo) { this.strCityInfo = strCityInfo; } public void setClicked(boolean clicked) { isClicked = clicked; } ActionListener taskPerformer = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { //System.out.println("time on"); if (clickTimes < 2) { clickTimes = 0;//如果时间到了还没双击那就不算了,此次双击失效 timer.stop(); } } }; CityBtn(MainWindow frameMainWindow, int id) { super(); //初始化定时器 this.id = id; timer = new Timer(300, taskPerformer); this.frameMainWindow = frameMainWindow; parent = (RoundPanel) this.getParent(); labelCityName = new JLabel(); setPreferredSize(new Dimension(btnWidth, btnHeight)); setSize(btnWidth, btnHeight); Font font = new Font("微软雅黑", Font.BOLD, 14); labelCityName.setFont(font); labelCityName.setForeground(new Color(116, 169, 181)); labelCityName.setVisible(true); setContentAreaFilled(false); this.setBorderPainted(false); // 不绘制边框 this.setFocusPainted(false); // 不绘制焦点状态 this.setSelected(true); labelCityName.setHorizontalAlignment(SwingConstants.CENTER); CityBtn that = this; //鼠标单击点击事件 this.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if (e.getButton() == 1) { clickTimes++;//每点一次点击次数加1 xOld = e.getX();//记录鼠标按下时的坐标 yOld = e.getY(); if (!timer.isRunning()) ;//如果定时器未启动就启动 timer.start(); if (frameMainWindow.paintPad.isSettingArc()) {//在设置边的情况下按钮被点击了说明被点击的这个按钮是终点 clickTimes = 0; if (that.id == frameMainWindow.cityBtnCurrent.id) { frameMainWindow.logToWindow("不能设置自己到自己"); frameMainWindow.paintPad.setSettingArc(false); return; } //添加边到当前城市 if (frameMainWindow.cityBtnCurrent.addArcToVel(that, 0, true)) { frameMainWindow.logToWindow("添加成功"); that.addArcToVel(frameMainWindow.cityBtnCurrent, 0, false);//添加成功则添加反向的边 } else { frameMainWindow.logToWindow("边重复"); } ; frameMainWindow.paintPad.setSettingArc(false); } else { frameMainWindow.cityBtnCurrent = that; frameMainWindow.textFieldCityName.setText(labelCityName.getText()); frameMainWindow.roundTextArea.textAreaReal.setText(strCityInfo); Component cp = (Component) e.getSource(); //获取事件e的触发源 //当鼠标点下的时候记录组件当前的坐标与鼠标当前在屏幕的位置 //System.out.println(cp.getX() + " "+cp.getY()); if (getParent().getBounds().contains(xOld, yOld)) { xOld = cp.getX(); yOld = cp.getY(); startX = e.getXOnScreen(); startY = e.getYOnScreen(); isPressed = true; } frameMainWindow.paintPad.repaint(); if (clickTimes == 2) {//如果检测到双击 //这里执行双击事件 //System.out.println("检测到双击"); //System.out.println(getBounds()); //System.out.println(xOld + " : " + yOld); if (getBounds().contains(xOld, yOld)) { //检测到画板内双击 doubleClick(); } timer.stop(); clickTimes = 0; } } } } @Override public void mouseReleased(MouseEvent e) { isPressed = false; } }); this.addMouseMotionListener(new MouseMotionAdapter() { @Override public void mouseDragged(MouseEvent e) { //System.out.println(isPressed); if(isPressed){ int xOnScr = e.getXOnScreen(); int yOnScr = e.getYOnScreen(); int xx = (xOnScr - startX) + xOld; int yy = (yOnScr - startY) + yOld; //如果 <SUF> Rectangle r = getParent().getBounds(); int shrinkPixel = 10;//缩小一周的宽度 r.x += shrinkPixel; r.y += shrinkPixel; r.width -= 2 * shrinkPixel; r.height -= 2 * shrinkPixel; if (!r.contains(xx + getWidth() / 2, yy + getHeight() / 2)) { CityBtn.this.setLocation(lastX, lastY); return; } CityBtn.this.setLocation(xx, yy);//设置拖拽后,窗口的位置 labelCityName.setLocation(xx - 25, yy + getHeight() / 2 + 5);//设置文本拖拽后的位置 lastX = xx; lastY = yy; } } }); } public void doubleClick() { frameMainWindow.paintPad.setSettingArc(true); frameMainWindow.paintPad.setPointStart(new Point(getX() + getWidth() / 2, getY() + getHeight() / 2)); frameMainWindow.paintPad.setPointEndLast(new Point(getX() + getWidth() / 2, getY() + getHeight() / 2)); } protected void paintComponent(Graphics g) { //设置抗锯齿 Graphics2D g2d = (Graphics2D) g; //System.out.println(w.getGraphics()); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); if (getModel().isArmed()) { g.setColor(Color.lightGray); // 点击时高亮 } else if (frameMainWindow.cityBtnCurrent == this) { g.setColor(Color.YELLOW); } else { g.setColor(getBackground()); } // fillOval方法画一个矩形的内切椭圆,并且填充这个椭圆, // 当矩形为正方形时,画出的椭圆便是圆 g.fillOval(0, 0, getSize().width - 1, getSize().height - 1); super.paintComponent(g); } // 用简单的弧画按钮的边界。 protected void paintBorder(Graphics g) { g.setColor(Color.white); // drawOval方法画矩形的内切椭圆,但不填充。只画出一个边界 g.drawOval(0, 0, getSize().width - 1, getSize().height - 1); } // shape对象用于保存按钮的形状,有助于侦听点击按钮事件 Shape shape; public boolean contains(int x, int y) { if ((shape == null) || (!shape.getBounds().equals(getBounds()))) { // 构造一个椭圆形对象 shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight()); } // 判断鼠标的x、y坐标是否落在按钮形状内。 return shape.contains(x, y); } private boolean addArcToVel(CityBtn target, int distance, boolean ifDraw) { //将info无重复地加到btn内 ArcInfo arcInfo = new ArcInfo(this, target, ifDraw, 0); //将画板的指针给到输入框这样输入框输入时画板不会刷新 if (ifDraw) arcInfo.setTextFieldOnArc(new TextFieldOnArc(frameMainWindow, arcInfo)); for (ArcInfo tempArc : this.listArcInfo) { if (tempArc.equal(arcInfo)) {//已经添加过这条边,就不加了 System.out.println("已经添加过这条边"); frameMainWindow.paintPad.setSettingArc(false); frameMainWindow.paintPad.setInputing(true); return false; } } this.listArcInfo.add(arcInfo); return true; } public String toString() { return this.labelCityName.getText(); } public boolean isNearOrigin(CityBtn another){ for (ArcInfo cityBtnTemp : another.listArcInfo){ if (cityBtnTemp.getmStart().equals(this)){ return true; } } return false; } }
0
2,182
12
2,500
20
2,603
12
2,500
20
3,260
31
false
false
false
false
false
true
65338_8
package cn.ofpp; import cn.ofpp.core.BoyFriend; import cn.ofpp.core.GirlFriend; import cn.ofpp.core.MessageFactory; import cn.ofpp.core.Wx; /** * 启动类 * * 这个理论上只能用测试号 正式的号 个人认证是不支持模板消息的 企业认证的又必须使用微信模板库里的模板 只有测试的可以自定义模板内容 * <a href="https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index">申请公众号测试应用地址</a> * * @author DokiYolo * Date 2022-08-22 */ public class Application { /** * <li>创建配置</li> * <li>创建几个 男/女 朋友</li> * <li>发消息</li> */ public static void main(String[] args) { // load and init Bootstrap.init(); // ----------------- 以下为演示数据 ------------------------ // new 一个 女友 // GirlFriend girlFriend = new GirlFriend("某女友", // "江苏省", "南京市", "1999-08-08", "2011-04-16", "oDPNy6p8OCnWxQIgRB0O9FO9o_qM"); // Wx.sendTemplateMessage(MessageFactory.resolveMessage(girlFriend)); // new 一个 男友 也可单独针对一个friend设置模板ID 以达到不同人不同消息 BoyFriend boyFriend = new BoyFriend("陈攀宇", "浙江省", "温岭市", "2003-07-13", "2022-08-16", "oDPNy6p8OCnWxQIgRB0O9FO9o_qM", "rHwobdNNt4ZrlbVXtnassfGIhocIhVe69z2iQNW_yeM"); Wx.sendTemplateMessage(MessageFactory.resolveMessage(boyFriend)); } }
Chicksqace/Weather-forecast-and-greetings
src/main/java/cn/ofpp/Application.java
532
// new 一个 男友 也可单独针对一个friend设置模板ID 以达到不同人不同消息
line_comment
zh-cn
package cn.ofpp; import cn.ofpp.core.BoyFriend; import cn.ofpp.core.GirlFriend; import cn.ofpp.core.MessageFactory; import cn.ofpp.core.Wx; /** * 启动类 * * 这个理论上只能用测试号 正式的号 个人认证是不支持模板消息的 企业认证的又必须使用微信模板库里的模板 只有测试的可以自定义模板内容 * <a href="https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index">申请公众号测试应用地址</a> * * @author DokiYolo * Date 2022-08-22 */ public class Application { /** * <li>创建配置</li> * <li>创建几个 男/女 朋友</li> * <li>发消息</li> */ public static void main(String[] args) { // load and init Bootstrap.init(); // ----------------- 以下为演示数据 ------------------------ // new 一个 女友 // GirlFriend girlFriend = new GirlFriend("某女友", // "江苏省", "南京市", "1999-08-08", "2011-04-16", "oDPNy6p8OCnWxQIgRB0O9FO9o_qM"); // Wx.sendTemplateMessage(MessageFactory.resolveMessage(girlFriend)); // ne <SUF> BoyFriend boyFriend = new BoyFriend("陈攀宇", "浙江省", "温岭市", "2003-07-13", "2022-08-16", "oDPNy6p8OCnWxQIgRB0O9FO9o_qM", "rHwobdNNt4ZrlbVXtnassfGIhocIhVe69z2iQNW_yeM"); Wx.sendTemplateMessage(MessageFactory.resolveMessage(boyFriend)); } }
0
467
22
532
25
499
20
532
25
666
40
false
false
false
false
false
true
66472_40
package com.bilibili.diyviewcomponent.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class PathView extends View { private Paint mPaint; public PathView(Context context) { this(context, null); } public PathView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public PathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initPaint(); } private void initPaint() { mPaint = new Paint(); mPaint.setColor(Color.RED); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //普通PATH // Path path = new Path(); // path.moveTo(100, 100); // path.lineTo(200, 200); // path.lineTo(100, 300); // path.close(); // canvas.drawPath(path, mPaint); //矩形路径 //逆时针 // Path ccwPath = new Path(); // RectF ccwRect = new RectF(100, 100, 400, 400); // ccwPath.addRect(ccwRect, Path.Direction.CCW); // canvas.drawPath(ccwPath, mPaint); //顺时针 // Path cwPath = new Path(); // RectF cwRect = new RectF(500, 500, 700, 700); // cwPath.addRect(cwRect, Path.Direction.CW); // canvas.drawPath(cwPath, mPaint); // // String text = "打败鸣人的办法,堵了她的嘴,打败路飞的办法,把肉扔海里,打败纳兹的办法,把他音响砸了!"; // canvas.drawTextOnPath(text, ccwPath, 0, 18, mPaint); // canvas.drawTextOnPath(text, cwPath, 0, 18, mPaint); //圆角矩形路径 // RectF rectF = new RectF(200, 800, 400, 900); // Path roundCcwPath = new Path(); // roundCcwPath.addRoundRect(rectF, 10, 15, Path.Direction.CCW); // canvas.drawPath(roundCcwPath, mPaint); // // RectF rectF1 = new RectF(500, 800, 700, 900); // Path roundCwPath = new Path(); // float[] radius = new float[]{10, 15, 20, 25, 30, 35, 80, 90}; // roundCwPath.addRoundRect(rectF1, radius, Path.Direction.CCW); // canvas.drawPath(roundCwPath, mPaint); //圆形路径 // Path circlePath = new Path(); // circlePath.addCircle(300 ,1200 ,100 , Path.Direction.CCW); // canvas.drawPath(circlePath ,mPaint); //椭圆形路径 // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // Path roundOath = new Path(); // roundOath.addOval(300 ,1400 ,500 ,1600 , Path.Direction.CCW); // canvas.drawPath(roundOath ,mPaint); // } //画弧形 // Path arcPath = new Path(); // RectF arcRect = new RectF(300 ,1700 ,500 ,1500); // arcPath.addArc(arcRect ,0 ,120); // canvas.drawPath(arcPath ,mPaint); //文字 mPaint.setTextSize(80); mPaint.setStrokeWidth(5); mPaint.setTextSkewX((float) -0.25f); canvas.drawText("妖精的尾巴", 0, 100, mPaint); mPaint.setStyle(Paint.Style.STROKE); canvas.drawText("妖精的尾巴", 0, 200, mPaint); mPaint.setStyle(Paint.Style.FILL_AND_STROKE); canvas.drawText("妖精的尾巴", 0, 300, mPaint); // Typeface create可修改字体 } }
Chihiro23333/ChidoriX
diyviewcomponent/src/main/java/com/bilibili/diyviewcomponent/view/PathView.java
1,212
//画弧形
line_comment
zh-cn
package com.bilibili.diyviewcomponent.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import androidx.annotation.Nullable; import android.util.AttributeSet; import android.view.View; public class PathView extends View { private Paint mPaint; public PathView(Context context) { this(context, null); } public PathView(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } public PathView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initPaint(); } private void initPaint() { mPaint = new Paint(); mPaint.setColor(Color.RED); mPaint.setAntiAlias(true); mPaint.setStyle(Paint.Style.STROKE); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); //普通PATH // Path path = new Path(); // path.moveTo(100, 100); // path.lineTo(200, 200); // path.lineTo(100, 300); // path.close(); // canvas.drawPath(path, mPaint); //矩形路径 //逆时针 // Path ccwPath = new Path(); // RectF ccwRect = new RectF(100, 100, 400, 400); // ccwPath.addRect(ccwRect, Path.Direction.CCW); // canvas.drawPath(ccwPath, mPaint); //顺时针 // Path cwPath = new Path(); // RectF cwRect = new RectF(500, 500, 700, 700); // cwPath.addRect(cwRect, Path.Direction.CW); // canvas.drawPath(cwPath, mPaint); // // String text = "打败鸣人的办法,堵了她的嘴,打败路飞的办法,把肉扔海里,打败纳兹的办法,把他音响砸了!"; // canvas.drawTextOnPath(text, ccwPath, 0, 18, mPaint); // canvas.drawTextOnPath(text, cwPath, 0, 18, mPaint); //圆角矩形路径 // RectF rectF = new RectF(200, 800, 400, 900); // Path roundCcwPath = new Path(); // roundCcwPath.addRoundRect(rectF, 10, 15, Path.Direction.CCW); // canvas.drawPath(roundCcwPath, mPaint); // // RectF rectF1 = new RectF(500, 800, 700, 900); // Path roundCwPath = new Path(); // float[] radius = new float[]{10, 15, 20, 25, 30, 35, 80, 90}; // roundCwPath.addRoundRect(rectF1, radius, Path.Direction.CCW); // canvas.drawPath(roundCwPath, mPaint); //圆形路径 // Path circlePath = new Path(); // circlePath.addCircle(300 ,1200 ,100 , Path.Direction.CCW); // canvas.drawPath(circlePath ,mPaint); //椭圆形路径 // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // Path roundOath = new Path(); // roundOath.addOval(300 ,1400 ,500 ,1600 , Path.Direction.CCW); // canvas.drawPath(roundOath ,mPaint); // } //画弧 <SUF> // Path arcPath = new Path(); // RectF arcRect = new RectF(300 ,1700 ,500 ,1500); // arcPath.addArc(arcRect ,0 ,120); // canvas.drawPath(arcPath ,mPaint); //文字 mPaint.setTextSize(80); mPaint.setStrokeWidth(5); mPaint.setTextSkewX((float) -0.25f); canvas.drawText("妖精的尾巴", 0, 100, mPaint); mPaint.setStyle(Paint.Style.STROKE); canvas.drawText("妖精的尾巴", 0, 200, mPaint); mPaint.setStyle(Paint.Style.FILL_AND_STROKE); canvas.drawText("妖精的尾巴", 0, 300, mPaint); // Typeface create可修改字体 } }
0
1,024
4
1,212
5
1,185
4
1,212
5
1,378
6
false
false
false
false
false
true
28386_4
package com.cxd.algorithm.sort; /** * 冒泡排序 * * 重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。 * 走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。 * 这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。 * * 最好情况下:正序有序,则只需要比较n次。故,为O(n) * * 最坏情况下:逆序有序,则需要比较(n-1)+(n-2)+……+1,故为O(n*n) * * 排序过程中只交换相邻两个元素的位置。因此,当两个数相等时,是没必要交换两个数的位置的。所以,它们的相对位置并没有改变,冒泡排序算法是稳定的! * * @author childe * @date 2018/6/20 19:39 **/ public class BubbleSort { // 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 // 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。 // 针对所有的元素重复以上的步骤,除了最后一个。 // 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。 static int[] sort(int[] arr) { for (int i = 1; i < arr.length; i++) { // 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。 boolean flag = true; for (int j = 0; j < arr.length - i; j++) { if (arr[j] > arr[j + 1]) { int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; flag = false; } } if (flag) { break; } } return arr; } }
Childe-Chen/goodGoodStudy
src/main/java/com/cxd/algorithm/sort/BubbleSort.java
565
// 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
line_comment
zh-cn
package com.cxd.algorithm.sort; /** * 冒泡排序 * * 重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。 * 走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。 * 这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。 * * 最好情况下:正序有序,则只需要比较n次。故,为O(n) * * 最坏情况下:逆序有序,则需要比较(n-1)+(n-2)+……+1,故为O(n*n) * * 排序过程中只交换相邻两个元素的位置。因此,当两个数相等时,是没必要交换两个数的位置的。所以,它们的相对位置并没有改变,冒泡排序算法是稳定的! * * @author childe * @date 2018/6/20 19:39 **/ public class BubbleSort { // 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 // 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。 // 针对所有的元素重复以上的步骤,除了最后一个。 // 持续 <SUF> static int[] sort(int[] arr) { for (int i = 1; i < arr.length; i++) { // 设定一个标记,若为true,则表示此次循环没有进行交换,也就是待排序列已经有序,排序已经完成。 boolean flag = true; for (int j = 0; j < arr.length - i; j++) { if (arr[j] > arr[j + 1]) { int tmp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = tmp; flag = false; } } if (flag) { break; } } return arr; } }
0
469
23
565
28
514
19
565
28
776
45
false
false
false
false
false
true
40532_2
package com.lhr.jiandou.adapter; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.bumptech.glide.Glide; import com.lhr.jiandou.R; import com.lhr.jiandou.adapter.base.BasePagerAdapter; import com.lhr.jiandou.model.bean.SubjectsBean; import java.util.List; /** * Created by ChinaLHR on 2016/12/30. * Email:13435500980@163.com */ public class PageTopAdapter extends BasePagerAdapter<SubjectsBean> { public PageTopAdapter(Context context, List<SubjectsBean> date) { super(context, date); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_top250, parent, false); return new TopHolder(view); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { if (mDate.size()>1) { if (getItemViewType(position) == TYPE_FOOTER) return; ((TopHolder)holder).top_movie_brief.setText(""); Glide.with(mContext) .load(mDate.get(position).getImages().getLarge()) .into(((TopHolder) holder).top_img); ((TopHolder) holder).top_movie_title.setText(mDate.get(position).getTitle()); ((TopHolder) holder).top_num.setText(position+1+""); ((TopHolder) holder).top_movie_ratingnum.setText(mDate.get(position).getRating().getAverage() + ""); ((TopHolder) holder).top_movie_ratingbar.setRating((float) mDate.get(position).getRating().getAverage() / 2); /** * 上映时间 */ if (!mDate.get(position).getYear().trim().equals("")) { ((TopHolder) holder).top_movie_brief.append("上映时间:"); ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getYear() + "\n"); } /** * 导演信息 */ if (mDate.get(position).getDirectors() != null) { ((TopHolder) holder).top_movie_brief.append("导演:"); for (int i = 0; i < mDate.get(position).getDirectors().size(); i++) { if (i == mDate.get(position).getDirectors().size() - 1) { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getDirectors().get(i).getName()); } else { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getDirectors().get(i).getName() + "/"); } } ((TopHolder) holder).top_movie_brief.append("\n"); } /** * 演员信息 */ if (mDate.get(position).getCasts() != null) { ((TopHolder) holder).top_movie_brief.append("演员:"); for (int i = 0; i < mDate.get(position).getCasts().size(); i++) { if (i == mDate.get(position).getCasts().size()-1) { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getCasts().get(i).getName()); } else { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getCasts().get(i).getName() + "/"); } } ((TopHolder) holder).top_movie_brief.append("\n"); } /** * 类型信息 */ if (mDate.get(position).getCasts() != null) { ((TopHolder) holder).top_movie_brief.append("类型:"); for (int i = 0; i < mDate.get(position).getGenres().size(); i++) { if (i == mDate.get(position).getGenres().size() - 1) { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getGenres().get(i)); } else { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getGenres().get(i) + "/"); } } ((TopHolder) holder).top_movie_brief.append("\n"); } } if (mListener!=null){ ((TopHolder)holder).top_card.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = holder.getLayoutPosition(); mListener.ItemClickListener(holder.itemView, mDate.get(position).getId(),mDate.get(position).getImages().getLarge()); } }); } } class TopHolder extends RecyclerView.ViewHolder { TextView top_num; ImageView top_img; TextView top_movie_title; RatingBar top_movie_ratingbar; TextView top_movie_ratingnum; TextView top_movie_brief; CardView top_card; public TopHolder(View itemView) { super(itemView); top_card = (CardView) itemView.findViewById(R.id.top_card); top_num = (TextView) itemView.findViewById(R.id.top_num); top_img = (ImageView) itemView.findViewById(R.id.top_img); top_movie_title = (TextView) itemView.findViewById(R.id.top_movie_title); top_movie_ratingbar = (RatingBar) itemView.findViewById(R.id.top_movie_ratingbar); top_movie_ratingnum = (TextView) itemView.findViewById(R.id.top_movie_ratingnum); top_movie_brief = (TextView) itemView.findViewById(R.id.top_movie_brief); } } }
ChinaLHR/JianDou
app/src/main/java/com/lhr/jiandou/adapter/PageTopAdapter.java
1,508
/** * 导演信息 */
block_comment
zh-cn
package com.lhr.jiandou.adapter; import android.content.Context; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import com.bumptech.glide.Glide; import com.lhr.jiandou.R; import com.lhr.jiandou.adapter.base.BasePagerAdapter; import com.lhr.jiandou.model.bean.SubjectsBean; import java.util.List; /** * Created by ChinaLHR on 2016/12/30. * Email:13435500980@163.com */ public class PageTopAdapter extends BasePagerAdapter<SubjectsBean> { public PageTopAdapter(Context context, List<SubjectsBean> date) { super(context, date); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_top250, parent, false); return new TopHolder(view); } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) { if (mDate.size()>1) { if (getItemViewType(position) == TYPE_FOOTER) return; ((TopHolder)holder).top_movie_brief.setText(""); Glide.with(mContext) .load(mDate.get(position).getImages().getLarge()) .into(((TopHolder) holder).top_img); ((TopHolder) holder).top_movie_title.setText(mDate.get(position).getTitle()); ((TopHolder) holder).top_num.setText(position+1+""); ((TopHolder) holder).top_movie_ratingnum.setText(mDate.get(position).getRating().getAverage() + ""); ((TopHolder) holder).top_movie_ratingbar.setRating((float) mDate.get(position).getRating().getAverage() / 2); /** * 上映时间 */ if (!mDate.get(position).getYear().trim().equals("")) { ((TopHolder) holder).top_movie_brief.append("上映时间:"); ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getYear() + "\n"); } /** * 导演信 <SUF>*/ if (mDate.get(position).getDirectors() != null) { ((TopHolder) holder).top_movie_brief.append("导演:"); for (int i = 0; i < mDate.get(position).getDirectors().size(); i++) { if (i == mDate.get(position).getDirectors().size() - 1) { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getDirectors().get(i).getName()); } else { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getDirectors().get(i).getName() + "/"); } } ((TopHolder) holder).top_movie_brief.append("\n"); } /** * 演员信息 */ if (mDate.get(position).getCasts() != null) { ((TopHolder) holder).top_movie_brief.append("演员:"); for (int i = 0; i < mDate.get(position).getCasts().size(); i++) { if (i == mDate.get(position).getCasts().size()-1) { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getCasts().get(i).getName()); } else { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getCasts().get(i).getName() + "/"); } } ((TopHolder) holder).top_movie_brief.append("\n"); } /** * 类型信息 */ if (mDate.get(position).getCasts() != null) { ((TopHolder) holder).top_movie_brief.append("类型:"); for (int i = 0; i < mDate.get(position).getGenres().size(); i++) { if (i == mDate.get(position).getGenres().size() - 1) { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getGenres().get(i)); } else { ((TopHolder) holder).top_movie_brief.append(mDate.get(position).getGenres().get(i) + "/"); } } ((TopHolder) holder).top_movie_brief.append("\n"); } } if (mListener!=null){ ((TopHolder)holder).top_card.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int position = holder.getLayoutPosition(); mListener.ItemClickListener(holder.itemView, mDate.get(position).getId(),mDate.get(position).getImages().getLarge()); } }); } } class TopHolder extends RecyclerView.ViewHolder { TextView top_num; ImageView top_img; TextView top_movie_title; RatingBar top_movie_ratingbar; TextView top_movie_ratingnum; TextView top_movie_brief; CardView top_card; public TopHolder(View itemView) { super(itemView); top_card = (CardView) itemView.findViewById(R.id.top_card); top_num = (TextView) itemView.findViewById(R.id.top_num); top_img = (ImageView) itemView.findViewById(R.id.top_img); top_movie_title = (TextView) itemView.findViewById(R.id.top_movie_title); top_movie_ratingbar = (RatingBar) itemView.findViewById(R.id.top_movie_ratingbar); top_movie_ratingnum = (TextView) itemView.findViewById(R.id.top_movie_ratingnum); top_movie_brief = (TextView) itemView.findViewById(R.id.top_movie_brief); } } }
0
1,231
10
1,508
9
1,565
10
1,508
9
1,719
14
false
false
false
false
false
true
48416_2
package com.lbwan.game.room.gameTeam; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.lbwan.game.room.roomGame.GamePlayer; import com.lbwan.game.utils.GDPropertiesUtils; import com.lbwan.game.porkerEnumSet.FaceValueEnum; public class Team { private Log logger = LogFactory.getLog(getClass()); // 该队伍的主牌 private int majorFaceValue = GDPropertiesUtils.getPropertyAsInteger(GDPropertiesUtils.DEFAULT_MAJOR_CARD);; private boolean winTheGame = false; // 队伍 private Map<String, GamePlayer> gamePlayerMap = new HashMap<String, GamePlayer>(); public Team(String strPlayerOne, String strPlayerTwo, TeamGroup teamGroup){ GamePlayer playerOne = new GamePlayer(strPlayerOne, teamGroup); playerOne.initTeamPlayer(strPlayerTwo); gamePlayerMap.put(strPlayerOne, playerOne); GamePlayer playerTwo = new GamePlayer(strPlayerTwo, teamGroup); playerTwo.initTeamPlayer(strPlayerOne); gamePlayerMap.put(strPlayerTwo, playerTwo); majorFaceValue = 2; winTheGame = false; } public void initControlNextPlayer(String strControlerId, String strNextUserId){ GamePlayer controlPlayer = gamePlayerMap.get(strControlerId); if(null == controlPlayer){ logger.error("Team::initControlNextPlayer controlPlayer Null Error"); return ; } controlPlayer.initNextPlayerUserId(strNextUserId); } public GamePlayer searchPlayer(String strSearchUser){ GamePlayer controlPlayer = gamePlayerMap.get(strSearchUser); if(null == controlPlayer){ return null; } return controlPlayer; } public int getMajorFace(){ return this.majorFaceValue; } public void resetNewMajorFaceValue(int nNewMajorFaceValue){ this.majorFaceValue = nNewMajorFaceValue; } public int getHandOutPorkerNumOfTeam(){ int nHandOutPlayers = 0; Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::initControlNextPlayer player Null Error"); continue; } if(0 == player.getPlayerHandPorkerNum()){ nHandOutPlayers = nHandOutPlayers + 1; continue; } } return nHandOutPlayers; } public int teamPlayerNum(){ return gamePlayerMap.size(); } public void winTheGame(){ this.winTheGame = true; Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::winTheGame player Null Error"); continue; } player.winTheGameOfThisRound(); } } public boolean isTeamWinTheGame(){ if(true == this.winTheGame){ return true; } return false; } public void initNewRound(){ winTheGame = false; Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::initNewRound() player Null Error"); continue; } // 初始化 player.initPlayerData(); } } // 计算排位 public void calculateRank(TeamGroup teamGroup){ if(null == teamGroup){ logger.error("Team::calculateRank teamGroup Null Error"); return ; } GamePlayer minPlayer = new GamePlayer("MinPlayer", null); minPlayer.resetToTestGamePlayer(); GamePlayer secondMinPlayer = new GamePlayer("SecondMinPlayer", null); secondMinPlayer.resetToTestGamePlayer(); Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::calculateRank player Null Error"); continue; } // 手上没有牌了 则直接continue; int nHandPorkerNum = player.getPlayerHandPorkerNum(); if(0 == nHandPorkerNum){ continue; } // 小于最小值 if(nHandPorkerNum < minPlayer.getPlayerHandPorkerNum()){ secondMinPlayer = minPlayer; minPlayer = player; }else if((nHandPorkerNum >= minPlayer.getPlayerHandPorkerNum()) && (nHandPorkerNum < secondMinPlayer.getPlayerHandPorkerNum())){ // 大于等于最小值 并且 小于最大值 secondMinPlayer = player; } } if(false == minPlayer.isTestPlayer()){ minPlayer.recordOutPorkerPlayer(teamGroup); } if(false == secondMinPlayer.isTestPlayer()){ secondMinPlayer.recordOutPorkerPlayer(teamGroup); } } // 主牌做相对应的升级 public void upMajorFaceValue(){ int nLastHandOut = 0, nFirstHandOut = 0; Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::upMajorFaceValue player Null Error"); continue; } int nOutPorkerRank = player.getOutAllPorkerRank(); if(1 == nOutPorkerRank){ nFirstHandOut = nFirstHandOut + 1; continue; } nLastHandOut = nOutPorkerRank; } if(1 != nFirstHandOut){ logger.error("Team::upMajorFaceValue server Error"); return ; } int nNewMajorFaceValue = this.calcuNewMajorValue(nLastHandOut); if(0 == nNewMajorFaceValue){ logger.error("Team::upMajorFaceValue server Error Of calcuNewMajorValue"); return ; } this.resetNewMajorFaceValue(nNewMajorFaceValue); } private int calcuNewMajorValue(int nLastHandOut){ int nAddValue = 0; switch(nLastHandOut){ // 第二个出完牌 则升三级 case 2: nAddValue = 3; break; case 3: nAddValue = 2; break; case 4: nAddValue = 1; break; default: logger.error("Team::calcuNewMajorValue server Error"); break; } // 判断是否达到A int nCurrentMajorValue = this.getMajorFace(); if(FaceValueEnum.FACE_VALUE_A_VALUE == nCurrentMajorValue){ return (nAddValue + 1); } int nNewFaceValue = nCurrentMajorValue + nAddValue; // A必须打 if(nNewFaceValue >= FaceValueEnum.FACE_VALUE_A_VALUE){ nNewFaceValue = FaceValueEnum.FACE_VALUE_A_VALUE; return nNewFaceValue; } return nNewFaceValue; } // 是否是双下 public boolean isDoubleLow(){ // 赢得比赛 则不是 boolean bIsDoubleLowResult = false; if(true == this.isTeamWinTheGame()){ return bIsDoubleLowResult; } Set<Integer> doubelLowSet = new HashSet<>(); doubelLowSet.add(3); doubelLowSet.add(4); Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::isDoubleLow() player Null Error"); continue; } boolean bIsDouble = doubelLowSet.contains(player.getOutAllPorkerRank()); if(false == bIsDouble){ return bIsDoubleLowResult; } } bIsDoubleLowResult = true; return bIsDoubleLowResult; } public Map<String, GamePlayer> getAllTeamMembers(){ return gamePlayerMap; } }
ChinaZZH/GuanDan
game/room/gameTeam/Team.java
2,349
// 计算排位
line_comment
zh-cn
package com.lbwan.game.room.gameTeam; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.lbwan.game.room.roomGame.GamePlayer; import com.lbwan.game.utils.GDPropertiesUtils; import com.lbwan.game.porkerEnumSet.FaceValueEnum; public class Team { private Log logger = LogFactory.getLog(getClass()); // 该队伍的主牌 private int majorFaceValue = GDPropertiesUtils.getPropertyAsInteger(GDPropertiesUtils.DEFAULT_MAJOR_CARD);; private boolean winTheGame = false; // 队伍 private Map<String, GamePlayer> gamePlayerMap = new HashMap<String, GamePlayer>(); public Team(String strPlayerOne, String strPlayerTwo, TeamGroup teamGroup){ GamePlayer playerOne = new GamePlayer(strPlayerOne, teamGroup); playerOne.initTeamPlayer(strPlayerTwo); gamePlayerMap.put(strPlayerOne, playerOne); GamePlayer playerTwo = new GamePlayer(strPlayerTwo, teamGroup); playerTwo.initTeamPlayer(strPlayerOne); gamePlayerMap.put(strPlayerTwo, playerTwo); majorFaceValue = 2; winTheGame = false; } public void initControlNextPlayer(String strControlerId, String strNextUserId){ GamePlayer controlPlayer = gamePlayerMap.get(strControlerId); if(null == controlPlayer){ logger.error("Team::initControlNextPlayer controlPlayer Null Error"); return ; } controlPlayer.initNextPlayerUserId(strNextUserId); } public GamePlayer searchPlayer(String strSearchUser){ GamePlayer controlPlayer = gamePlayerMap.get(strSearchUser); if(null == controlPlayer){ return null; } return controlPlayer; } public int getMajorFace(){ return this.majorFaceValue; } public void resetNewMajorFaceValue(int nNewMajorFaceValue){ this.majorFaceValue = nNewMajorFaceValue; } public int getHandOutPorkerNumOfTeam(){ int nHandOutPlayers = 0; Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::initControlNextPlayer player Null Error"); continue; } if(0 == player.getPlayerHandPorkerNum()){ nHandOutPlayers = nHandOutPlayers + 1; continue; } } return nHandOutPlayers; } public int teamPlayerNum(){ return gamePlayerMap.size(); } public void winTheGame(){ this.winTheGame = true; Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::winTheGame player Null Error"); continue; } player.winTheGameOfThisRound(); } } public boolean isTeamWinTheGame(){ if(true == this.winTheGame){ return true; } return false; } public void initNewRound(){ winTheGame = false; Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::initNewRound() player Null Error"); continue; } // 初始化 player.initPlayerData(); } } // 计算 <SUF> public void calculateRank(TeamGroup teamGroup){ if(null == teamGroup){ logger.error("Team::calculateRank teamGroup Null Error"); return ; } GamePlayer minPlayer = new GamePlayer("MinPlayer", null); minPlayer.resetToTestGamePlayer(); GamePlayer secondMinPlayer = new GamePlayer("SecondMinPlayer", null); secondMinPlayer.resetToTestGamePlayer(); Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::calculateRank player Null Error"); continue; } // 手上没有牌了 则直接continue; int nHandPorkerNum = player.getPlayerHandPorkerNum(); if(0 == nHandPorkerNum){ continue; } // 小于最小值 if(nHandPorkerNum < minPlayer.getPlayerHandPorkerNum()){ secondMinPlayer = minPlayer; minPlayer = player; }else if((nHandPorkerNum >= minPlayer.getPlayerHandPorkerNum()) && (nHandPorkerNum < secondMinPlayer.getPlayerHandPorkerNum())){ // 大于等于最小值 并且 小于最大值 secondMinPlayer = player; } } if(false == minPlayer.isTestPlayer()){ minPlayer.recordOutPorkerPlayer(teamGroup); } if(false == secondMinPlayer.isTestPlayer()){ secondMinPlayer.recordOutPorkerPlayer(teamGroup); } } // 主牌做相对应的升级 public void upMajorFaceValue(){ int nLastHandOut = 0, nFirstHandOut = 0; Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::upMajorFaceValue player Null Error"); continue; } int nOutPorkerRank = player.getOutAllPorkerRank(); if(1 == nOutPorkerRank){ nFirstHandOut = nFirstHandOut + 1; continue; } nLastHandOut = nOutPorkerRank; } if(1 != nFirstHandOut){ logger.error("Team::upMajorFaceValue server Error"); return ; } int nNewMajorFaceValue = this.calcuNewMajorValue(nLastHandOut); if(0 == nNewMajorFaceValue){ logger.error("Team::upMajorFaceValue server Error Of calcuNewMajorValue"); return ; } this.resetNewMajorFaceValue(nNewMajorFaceValue); } private int calcuNewMajorValue(int nLastHandOut){ int nAddValue = 0; switch(nLastHandOut){ // 第二个出完牌 则升三级 case 2: nAddValue = 3; break; case 3: nAddValue = 2; break; case 4: nAddValue = 1; break; default: logger.error("Team::calcuNewMajorValue server Error"); break; } // 判断是否达到A int nCurrentMajorValue = this.getMajorFace(); if(FaceValueEnum.FACE_VALUE_A_VALUE == nCurrentMajorValue){ return (nAddValue + 1); } int nNewFaceValue = nCurrentMajorValue + nAddValue; // A必须打 if(nNewFaceValue >= FaceValueEnum.FACE_VALUE_A_VALUE){ nNewFaceValue = FaceValueEnum.FACE_VALUE_A_VALUE; return nNewFaceValue; } return nNewFaceValue; } // 是否是双下 public boolean isDoubleLow(){ // 赢得比赛 则不是 boolean bIsDoubleLowResult = false; if(true == this.isTeamWinTheGame()){ return bIsDoubleLowResult; } Set<Integer> doubelLowSet = new HashSet<>(); doubelLowSet.add(3); doubelLowSet.add(4); Iterator<Map.Entry<String, GamePlayer>> iter = gamePlayerMap.entrySet().iterator(); while(true == iter.hasNext()){ Map.Entry<String, GamePlayer> entry = iter.next(); GamePlayer player = entry.getValue(); if(null == player){ logger.error("Team::isDoubleLow() player Null Error"); continue; } boolean bIsDouble = doubelLowSet.contains(player.getOutAllPorkerRank()); if(false == bIsDouble){ return bIsDoubleLowResult; } } bIsDoubleLowResult = true; return bIsDoubleLowResult; } public Map<String, GamePlayer> getAllTeamMembers(){ return gamePlayerMap; } }
0
2,008
6
2,349
5
2,406
4
2,349
5
2,967
8
false
false
false
false
false
true
62721_0
package com.teach.javafx.controller.honor; import com.teach.javafx.AppStore; import com.teach.javafx.MainApplication; import com.teach.javafx.request.HttpRequestUtil; import io.github.palexdev.materialfx.controls.MFXButton; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.WindowEvent; import org.fatmansoft.teach.payload.request.DataRequest; import org.fatmansoft.teach.payload.response.DataResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HonorCheckController { private final String HONOR_TITLE = "HONOR_TITLE"; private final String HONOR_CONTEST = "HONOR_CONTEST"; private final String HONOR_TECH = "HONOR_TECH"; private final String HONOR_PRACTICE = "HONOR_PRACTICE"; private final String HONOR_INTERNSHIP = "HONOR_INTERNSHIP"; private final String HONOR_PROJ = "HONOR_PROJ"; private final String HONOR_LECTURE = "HONOR_LECTURE"; private final String BASE_URL = "/api/honor"; @FXML private GridPane gridPane; @FXML private BorderPane borderPane; private List<Map> honors = new ArrayList<>(); private List<Map> title = new ArrayList<>(); private List<Map> practice = new ArrayList<>(); private List<Map> internship = new ArrayList<>(); private List<Map> contest = new ArrayList<>(); private List<Map> tech = new ArrayList<>(); private List<Map> lecture = new ArrayList<>(); private List<Map> proj = new ArrayList<>(); private Stage filterStage = null; @FXML public void initialize(){ requestHonors(); arrangeHonor(); setDisplay(); } public void requestHonors(){ DataRequest req = new DataRequest(); req.add("studentId", AppStore.getJwt().getRoleId()); DataResponse res = HttpRequestUtil.request(BASE_URL+"/getHonors",req); if(res != null && res.getCode() == 0){ honors = (ArrayList<Map>)(res.getData()); System.out.println("已获取到当前学生的荣誉信息: " + honors); } else { System.out.println("获取荣誉信息失败! "); } } //将不同荣誉按类别分配到相应的数组中 public void arrangeHonor(){ for(Map m : honors){ String type = (String) m.get("honorType"); switch (type) { case HONOR_TITLE -> title.add(m); case HONOR_CONTEST -> contest.add(m); case HONOR_INTERNSHIP -> internship.add(m); case HONOR_PRACTICE -> practice.add(m); case HONOR_PROJ -> proj.add(m); case HONOR_TECH -> tech.add(m); case HONOR_LECTURE -> lecture.add(m); } } } public void setDisplay(){ gridPane.getChildren().clear(); int row = 0; gridPane.add(new Label("荣誉称号"), 0, row); row = setItem(row, title); gridPane.add(new Label("学科竞赛"), 0, row); row = setItem(row, contest); gridPane.add(new Label("社会实践"), 0, row); row = setItem(row, practice); gridPane.add(new Label("科技成果"), 0, row); row = setItem(row, tech); gridPane.add(new Label("校外实习"), 0, row); row = setItem(row, internship); gridPane.add(new Label("培训讲座"), 0, row); row = setItem(row, lecture); gridPane.add(new Label("创新项目"), 0, row); row = setItem(row, proj); int numOfHonors = honors.size(); if( numOfHonors == 0){ gridPane.add(new Label("你目前没有个人荣誉诶\n继续加油吧!"), 3, 0); } else if(numOfHonors <= 2){ gridPane.add(new Label("你目前有 " + numOfHonors + " 个荣誉耶\n小有成就!"), 3, 0); } else if(numOfHonors <= 5){ gridPane.add(new Label("真棒! 你现在有 " + numOfHonors + " 个荣誉\n再接再厉吧!"), 3, 0); } else { gridPane.add(new Label("Wow,你现在有 " + numOfHonors + " 个荣誉\nAmazing!"), 3, 0); } } private int setItem(int row, List<Map> title) { for(Map m : title){ gridPane.add(new Label((String) m.get("honorContent")), 1, row); row++; } if(title.isEmpty()){ gridPane.add(new Label("暂无奖项"),1,row); row++; } return row; } public void openFilterWindow(List<Map> honors, String honorType){ FXMLLoader loader = new FXMLLoader(MainApplication.class.getResource("honor/honor-filter-panel.fxml")); try { Scene scene = new Scene(loader.load(), 600, 400); HonorFilterController honorFilterController = (HonorFilterController) loader.getController(); honorFilterController.setData(honors, honorType); honorFilterController.setDisplay(); filterStage = new Stage(); filterStage.setScene(scene); filterStage.setTitle(honorType); filterStage.initOwner(getStage()); filterStage.initModality(Modality.WINDOW_MODAL); filterStage.setOnCloseRequest(windowEvent -> filterStage = null); filterStage.setResizable(false); filterStage.show(); } catch (IOException o){ System.out.println("打开分类浏览荣誉的视图失败: " + o.getMessage()); } } public void onFilterButtonClick(ActionEvent event) { MFXButton btn = (MFXButton) event.getTarget(); String text = btn.getText(); switch (text) { case "荣誉称号" -> openFilterWindow(title, text); case "学科竞赛" -> openFilterWindow(contest, text); case "科技成果" -> openFilterWindow(tech, text); case "社会实践" -> openFilterWindow(practice, text); case "培训讲座" -> openFilterWindow(lecture, text); case "创新项目" -> openFilterWindow(proj, text); case "校外实习" -> openFilterWindow(internship, text); } } private Stage getStage(){ Scene scene = this.borderPane.getScene(); return (Stage) scene.getWindow(); } }
ChinesePlayer/2024CourseDesign
java2/java-fx/src/main/java/com/teach/javafx/controller/honor/HonorCheckController.java
1,819
//将不同荣誉按类别分配到相应的数组中
line_comment
zh-cn
package com.teach.javafx.controller.honor; import com.teach.javafx.AppStore; import com.teach.javafx.MainApplication; import com.teach.javafx.request.HttpRequestUtil; import io.github.palexdev.materialfx.controls.MFXButton; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.WindowEvent; import org.fatmansoft.teach.payload.request.DataRequest; import org.fatmansoft.teach.payload.response.DataResponse; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HonorCheckController { private final String HONOR_TITLE = "HONOR_TITLE"; private final String HONOR_CONTEST = "HONOR_CONTEST"; private final String HONOR_TECH = "HONOR_TECH"; private final String HONOR_PRACTICE = "HONOR_PRACTICE"; private final String HONOR_INTERNSHIP = "HONOR_INTERNSHIP"; private final String HONOR_PROJ = "HONOR_PROJ"; private final String HONOR_LECTURE = "HONOR_LECTURE"; private final String BASE_URL = "/api/honor"; @FXML private GridPane gridPane; @FXML private BorderPane borderPane; private List<Map> honors = new ArrayList<>(); private List<Map> title = new ArrayList<>(); private List<Map> practice = new ArrayList<>(); private List<Map> internship = new ArrayList<>(); private List<Map> contest = new ArrayList<>(); private List<Map> tech = new ArrayList<>(); private List<Map> lecture = new ArrayList<>(); private List<Map> proj = new ArrayList<>(); private Stage filterStage = null; @FXML public void initialize(){ requestHonors(); arrangeHonor(); setDisplay(); } public void requestHonors(){ DataRequest req = new DataRequest(); req.add("studentId", AppStore.getJwt().getRoleId()); DataResponse res = HttpRequestUtil.request(BASE_URL+"/getHonors",req); if(res != null && res.getCode() == 0){ honors = (ArrayList<Map>)(res.getData()); System.out.println("已获取到当前学生的荣誉信息: " + honors); } else { System.out.println("获取荣誉信息失败! "); } } //将不 <SUF> public void arrangeHonor(){ for(Map m : honors){ String type = (String) m.get("honorType"); switch (type) { case HONOR_TITLE -> title.add(m); case HONOR_CONTEST -> contest.add(m); case HONOR_INTERNSHIP -> internship.add(m); case HONOR_PRACTICE -> practice.add(m); case HONOR_PROJ -> proj.add(m); case HONOR_TECH -> tech.add(m); case HONOR_LECTURE -> lecture.add(m); } } } public void setDisplay(){ gridPane.getChildren().clear(); int row = 0; gridPane.add(new Label("荣誉称号"), 0, row); row = setItem(row, title); gridPane.add(new Label("学科竞赛"), 0, row); row = setItem(row, contest); gridPane.add(new Label("社会实践"), 0, row); row = setItem(row, practice); gridPane.add(new Label("科技成果"), 0, row); row = setItem(row, tech); gridPane.add(new Label("校外实习"), 0, row); row = setItem(row, internship); gridPane.add(new Label("培训讲座"), 0, row); row = setItem(row, lecture); gridPane.add(new Label("创新项目"), 0, row); row = setItem(row, proj); int numOfHonors = honors.size(); if( numOfHonors == 0){ gridPane.add(new Label("你目前没有个人荣誉诶\n继续加油吧!"), 3, 0); } else if(numOfHonors <= 2){ gridPane.add(new Label("你目前有 " + numOfHonors + " 个荣誉耶\n小有成就!"), 3, 0); } else if(numOfHonors <= 5){ gridPane.add(new Label("真棒! 你现在有 " + numOfHonors + " 个荣誉\n再接再厉吧!"), 3, 0); } else { gridPane.add(new Label("Wow,你现在有 " + numOfHonors + " 个荣誉\nAmazing!"), 3, 0); } } private int setItem(int row, List<Map> title) { for(Map m : title){ gridPane.add(new Label((String) m.get("honorContent")), 1, row); row++; } if(title.isEmpty()){ gridPane.add(new Label("暂无奖项"),1,row); row++; } return row; } public void openFilterWindow(List<Map> honors, String honorType){ FXMLLoader loader = new FXMLLoader(MainApplication.class.getResource("honor/honor-filter-panel.fxml")); try { Scene scene = new Scene(loader.load(), 600, 400); HonorFilterController honorFilterController = (HonorFilterController) loader.getController(); honorFilterController.setData(honors, honorType); honorFilterController.setDisplay(); filterStage = new Stage(); filterStage.setScene(scene); filterStage.setTitle(honorType); filterStage.initOwner(getStage()); filterStage.initModality(Modality.WINDOW_MODAL); filterStage.setOnCloseRequest(windowEvent -> filterStage = null); filterStage.setResizable(false); filterStage.show(); } catch (IOException o){ System.out.println("打开分类浏览荣誉的视图失败: " + o.getMessage()); } } public void onFilterButtonClick(ActionEvent event) { MFXButton btn = (MFXButton) event.getTarget(); String text = btn.getText(); switch (text) { case "荣誉称号" -> openFilterWindow(title, text); case "学科竞赛" -> openFilterWindow(contest, text); case "科技成果" -> openFilterWindow(tech, text); case "社会实践" -> openFilterWindow(practice, text); case "培训讲座" -> openFilterWindow(lecture, text); case "创新项目" -> openFilterWindow(proj, text); case "校外实习" -> openFilterWindow(internship, text); } } private Stage getStage(){ Scene scene = this.borderPane.getScene(); return (Stage) scene.getWindow(); } }
0
1,489
11
1,820
16
1,775
11
1,819
16
2,132
24
false
false
false
false
false
true
46513_3
package com.tom; import com.google.common.collect.ImmutableList; import com.tom.enums.LimitType; import com.tom.util.Util; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.io.Serializable; import java.lang.reflect.Method; /** * @author wangtao */ @Aspect @Component public class LimitInterceptor { private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class); private final RedisTemplate<String, Serializable> limitRedisTemplate; @Autowired private HttpServletRequest httpServletRequest; @Autowired public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) { this.limitRedisTemplate = limitRedisTemplate; } @Around("execution(public * *(..)) && @annotation(com.tom.Limit)") public Object interceptor(ProceedingJoinPoint pjp) { MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); Limit limitAnnotation = method.getAnnotation(Limit.class); LimitType limitType = limitAnnotation.limitType(); String name = limitAnnotation.name(); logger.info("aop执行---->名字为{}",name); String key; int limitPeriod = limitAnnotation.period(); int limitCount = limitAnnotation.count(); switch (limitType) { case IP: key = Util.getIpAddress(httpServletRequest); break; case CUSTOMER: // TODO 如果此处想根据表达式或者一些规则生成 请看 一起来学Spring Boot | 第二十三篇:轻松搞定重复提交(分布式锁) key = limitAnnotation.key(); break; default: key = StringUtils.upperCase(method.getName()); } ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key)); try { String luaScript = buildLuaScript(); RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class); Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod); logger.info("Access try count is {} for name={} and key = {}", count, name, key); if (count != null && count.intValue() <= limitCount) { return pjp.proceed(); } else { throw new RuntimeException("You have been dragged into the blacklist"); } } catch (Throwable e) { if (e instanceof RuntimeException) { throw new RuntimeException(e.getLocalizedMessage()); } throw new RuntimeException("server exception"); } } /** * 限流 脚本 * * @return lua脚本 */ public String buildLuaScript() { StringBuilder lua = new StringBuilder(); lua.append("local c"); lua.append("\nc = redis.call('get',KEYS[1])"); // 调用不超过最大值,则直接返回 lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then"); lua.append("\nreturn c;"); lua.append("\nend"); // 执行计算器自加 lua.append("\nc = redis.call('incr',KEYS[1])"); lua.append("\nif tonumber(c) == 1 then"); // 从第一次调用开始限流,设置对应键值的过期 lua.append("\nredis.call('expire',KEYS[1],ARGV[2])"); lua.append("\nend"); lua.append("\nreturn c;"); return lua.toString(); } }
ChineseTony/javaDataStruct
myLimit/src/main/java/com/tom/LimitInterceptor.java
963
// 调用不超过最大值,则直接返回
line_comment
zh-cn
package com.tom; import com.google.common.collect.ImmutableList; import com.tom.enums.LimitType; import com.tom.util.Util; import org.apache.commons.lang3.StringUtils; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.core.script.RedisScript; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.io.Serializable; import java.lang.reflect.Method; /** * @author wangtao */ @Aspect @Component public class LimitInterceptor { private static final Logger logger = LoggerFactory.getLogger(LimitInterceptor.class); private final RedisTemplate<String, Serializable> limitRedisTemplate; @Autowired private HttpServletRequest httpServletRequest; @Autowired public LimitInterceptor(RedisTemplate<String, Serializable> limitRedisTemplate) { this.limitRedisTemplate = limitRedisTemplate; } @Around("execution(public * *(..)) && @annotation(com.tom.Limit)") public Object interceptor(ProceedingJoinPoint pjp) { MethodSignature signature = (MethodSignature) pjp.getSignature(); Method method = signature.getMethod(); Limit limitAnnotation = method.getAnnotation(Limit.class); LimitType limitType = limitAnnotation.limitType(); String name = limitAnnotation.name(); logger.info("aop执行---->名字为{}",name); String key; int limitPeriod = limitAnnotation.period(); int limitCount = limitAnnotation.count(); switch (limitType) { case IP: key = Util.getIpAddress(httpServletRequest); break; case CUSTOMER: // TODO 如果此处想根据表达式或者一些规则生成 请看 一起来学Spring Boot | 第二十三篇:轻松搞定重复提交(分布式锁) key = limitAnnotation.key(); break; default: key = StringUtils.upperCase(method.getName()); } ImmutableList<String> keys = ImmutableList.of(StringUtils.join(limitAnnotation.prefix(), key)); try { String luaScript = buildLuaScript(); RedisScript<Number> redisScript = new DefaultRedisScript<>(luaScript, Number.class); Number count = limitRedisTemplate.execute(redisScript, keys, limitCount, limitPeriod); logger.info("Access try count is {} for name={} and key = {}", count, name, key); if (count != null && count.intValue() <= limitCount) { return pjp.proceed(); } else { throw new RuntimeException("You have been dragged into the blacklist"); } } catch (Throwable e) { if (e instanceof RuntimeException) { throw new RuntimeException(e.getLocalizedMessage()); } throw new RuntimeException("server exception"); } } /** * 限流 脚本 * * @return lua脚本 */ public String buildLuaScript() { StringBuilder lua = new StringBuilder(); lua.append("local c"); lua.append("\nc = redis.call('get',KEYS[1])"); // 调用 <SUF> lua.append("\nif c and tonumber(c) > tonumber(ARGV[1]) then"); lua.append("\nreturn c;"); lua.append("\nend"); // 执行计算器自加 lua.append("\nc = redis.call('incr',KEYS[1])"); lua.append("\nif tonumber(c) == 1 then"); // 从第一次调用开始限流,设置对应键值的过期 lua.append("\nredis.call('expire',KEYS[1],ARGV[2])"); lua.append("\nend"); lua.append("\nreturn c;"); return lua.toString(); } }
0
823
11
963
11
1,010
10
963
11
1,206
16
false
false
false
false
false
true
64705_8
/** * * @author ChopinXBP 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 * 思路:Integer.toBinaryString(n)转为字符串判断 * */ public class NumberOf1_11 { public static void main(String[] args) { // TODO Auto-generated method stub int n = Solve(-5); System.out.println(n); } // -------------投机取巧的解法:转换为字符串---------------------// public static int Solve(int n) { int result = 0; String binstr = Integer.toBinaryString(n); System.out.println(binstr); for (int i = 0; i < binstr.length(); i++) { if (binstr.charAt(i) == '1') result++; } return result; } // -------------可能陷入死循环的解法:从右向左移---------------------// // 从n的2进制形式的最右边开始判断是不是1,该解法如果输入时负数会陷入死循环,因为负数右移时,在最高位补得是1,最后会补成0xFFFFFFFF。  public static int NumberOf1_CanNotUse(int n) { int count = 0; while (n != 0) { // 用1和n进行位与运算,结果要是为1则n的2进制形式.最右边那位肯定是1,否则为0 if ((n & 1) == 1) { count++; } // 把n的2进制形式往右推一位 n = n >> 1; } return count; } // --------------------正解:从左向右移---------------------------// // 思想:用1(1自身左移运算,其实后来就不是1了)和n的每位进行位与,来判断1的个数 private static int NumberOf1_low(int n) { int count = 0; int flag = 1; while (flag != 0) { if ((n & flag) != 0) { count++; } flag = flag << 1; } return count; } // ---------------------------最优解----------------------------// // 思想:把一个整数减去1,再和原整数做与运算,会把整数最右边的一个1变成0。 // 那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。 public static int NumberOf1(int n) { int count = 0; while (n != 0) { ++count; n = (n - 1) & n; } return count; } }
ChopinXBP/JZOffer_Babel
src/NumberOf1_11.java
702
// 思想:用1(1自身左移运算,其实后来就不是1了)和n的每位进行位与,来判断1的个数
line_comment
zh-cn
/** * * @author ChopinXBP 输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。 * 思路:Integer.toBinaryString(n)转为字符串判断 * */ public class NumberOf1_11 { public static void main(String[] args) { // TODO Auto-generated method stub int n = Solve(-5); System.out.println(n); } // -------------投机取巧的解法:转换为字符串---------------------// public static int Solve(int n) { int result = 0; String binstr = Integer.toBinaryString(n); System.out.println(binstr); for (int i = 0; i < binstr.length(); i++) { if (binstr.charAt(i) == '1') result++; } return result; } // -------------可能陷入死循环的解法:从右向左移---------------------// // 从n的2进制形式的最右边开始判断是不是1,该解法如果输入时负数会陷入死循环,因为负数右移时,在最高位补得是1,最后会补成0xFFFFFFFF。  public static int NumberOf1_CanNotUse(int n) { int count = 0; while (n != 0) { // 用1和n进行位与运算,结果要是为1则n的2进制形式.最右边那位肯定是1,否则为0 if ((n & 1) == 1) { count++; } // 把n的2进制形式往右推一位 n = n >> 1; } return count; } // --------------------正解:从左向右移---------------------------// // 思想 <SUF> private static int NumberOf1_low(int n) { int count = 0; int flag = 1; while (flag != 0) { if ((n & flag) != 0) { count++; } flag = flag << 1; } return count; } // ---------------------------最优解----------------------------// // 思想:把一个整数减去1,再和原整数做与运算,会把整数最右边的一个1变成0。 // 那么一个整数的二进制表示中有多少个1,就可以进行多少次这样的操作。 public static int NumberOf1(int n) { int count = 0; while (n != 0) { ++count; n = (n - 1) & n; } return count; } }
0
616
35
702
37
673
33
702
37
894
43
false
false
false
false
false
true
35998_5
package Problems; import java.util.HashMap; /** * * You are given K eggs, and you have access to a building with N floors from 1 to N. * Each egg is identical in function, and if an egg breaks, you cannot drop it again. * You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, * and any egg dropped at or below floor F will not break. * Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N). * Your goal is to know with certainty what the value of F is. * What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F? * 你将获得 K 个鸡蛋,并可以使用一栋从 1 到 N  共有 N 层楼的建筑。 * 每个蛋的功能都是一样的,如果一个蛋碎了,你就不能再把它掉下去。 * 你知道存在楼层 F ,满足 0 <= F <= N 任何从高于 F 的楼层落下的鸡蛋都会碎,从 F 楼层或比它低的楼层落下的鸡蛋都不会破。 * 每次移动,你可以取一个鸡蛋(如果你有完整的鸡蛋)并把它从任一楼层 X 扔下(满足 1 <= X <= N)。 * 你的目标是确切地知道 F 的值是多少。 * 无论 F 的初始值如何,你确定 F 的值的最小移动次数是多少? * */ public class SuperEggDrop { //递归(超时) public int superEggDrop2(int K, int N) { if(N < 2 || K == 1){ return N; } int result = N; //在手握K个鸡蛋时从第i层楼[0,N]向下丢鸡蛋,会有两种可能: //1.鸡蛋摔碎,将剩余K-1个鸡蛋移动到楼[0,i-1]进行测递归测试。 //2.鸡蛋没碎,将剩余K个鸡蛋移动到楼[i,N]进行测试,可将i层看成0层,对[0,N-i]进行递归测试。 for(int i = 1; i <= N; i++){ int curMin = Math.max(superEggDrop2(K - 1, i - 1), superEggDrop2(K, N - i)) + 1; result = curMin < result ? curMin : result; } return result; } //动态规划:二分搜索 //观察递归公式result = min(max(superEggDrop(K - 1, i - 1), superEggDrop(K, N - i)) + 1),其中i在[1.N]变化 //而fun1=superEggDrop(K - 1, i - 1)随i单调增,fun2=superEggDrop(K, N - i)随i单调减,两条单调函数的交点即为两者最大值的最小取值点 //因此可以对i在[1,N]上进行二分查找 HashMap<Integer, Integer> map = new HashMap<>(); public int superEggDrop3(int K, int N) { if (N == 0){ return 0; } if (K == 1){ return N; } //因为K<=100,可以设计一个key值的取值方法,将已经计算过的K,N组合存入哈希表避免重复计算 int key = N * 1000 + K; if (map.containsKey(key)){ return map.get(key); } int begin = 1; int end = N; while (begin + 1 < end) { int mid = (begin + end) >> 1; int lowVal = superEggDrop(K - 1, mid - 1); int highVal = superEggDrop(K, N - mid); if (lowVal < highVal){ begin = mid; } else if (lowVal > highVal){ end = mid; } else{ end = mid; begin = mid; } } int minimum = 1 + Math.min(Math.max(superEggDrop(K - 1, begin - 1), superEggDrop(K, N - begin)), Math.max(superEggDrop(K - 1, end - 1), superEggDrop(K, N - end))); map.put(key, minimum); return minimum; } //动态规划:自底向上 //观察转为动态规划的递归公式dp[i][j] = min(max(dp[i-1][loc-1], dp[i][j-loc]) + 1),其中i在[1.j]变化,j在[1, N]变化 //而fun1=dp[i-1][loc-1]随loc单调增,fun2=dp[i][j-loc]随loc单调减,两条单调函数的交点即为两者最大值的最小取值点 //寻找loc的思路转换为while循环遍历查找 public int superEggDrop4(int K, int N) { int[][] dp = new int[K + 1][N + 1]; for(int i = 1; i <= K; i++){ int loc = 1; for(int j = 1; j <= N; j++){ if(i == 1){ dp[i][j] = j; continue; } //令left为loc-1时的函数值,right为loc时的函数值,循环遍历找到最小值的拐点 //由于后序j值上限不断增大,loc拐点值只可能逐渐向右移动,以此可以简化后序查找 while (loc < j){ int left = Math.max(dp[i - 1][loc - 1], dp[i][j - loc]); int right = Math.max(dp[i - 1][loc], dp[i][j - loc - 1]); if(left <= right){ break; } loc++; } dp[i][j] = Math.max(dp[i - 1][loc - 1], dp[i][j - loc]) + 1; } } return dp[K][N]; } //动态规划(超时):求能够测得的最少楼层 public int superEggDrop5(int K, int N) { //dp[i][j]代表有i个鸡蛋和j次移动时一定能够测得的最少楼层数 int[][] dp = new int[K + 1][N + 1]; //没有鸡蛋时或没有移动次数时无法测试dp=0;只有1个鸡蛋但有j次移动,dp=j(从0层开始逐层测试) for (int i = 1; i <= N; i++) { dp[1][i] = i; dp[0][i] = 0; } for (int i = 1; i <= K; i++) { dp[i][0] = 0; } for (int i = 2; i <= K; i++) { for (int j = 1; j <= N; j++) { //有i个鸡蛋和j次移动时,前j-1次移动的测试结果可能由多种测试路径得来,将其划分为k次和(j-1)-k次遍历取最大 //第j-1次移动鸡蛋碎的结果为dp[i-1][k],鸡蛋未碎的结果为dp[i][(j - 1) - k],当前楼层第j次移动的最少测试结果为1(摔碎) //dp[i][j] = max(dp[i - 1][k], dp[i][(j - 1) - k]) + 1 int tMinDrop = N * N; for (int k = 0; k < j; k++) { tMinDrop = Math.min(tMinDrop, Math.max(dp[i - 1][k], dp[i][(j - 1) - k]) + 1); } dp[i][j] = tMinDrop; } } return dp[K][N]; } //动态规划(次优):求能够测得的最多楼层 public int superEggDrop6(int K, int N) { //dp[i][j]代表i个鸡蛋在j次移动内能测试确定的最多楼层数 int[][] dp = new int[N + 1][K + 1]; //从第一层楼开始更新dp数组 for(int i = 1; i <= N; i++){ //0次移动无法进行测试,初始值dp[i][0]=0 dp[i][0] = 0; for(int j = 1; j <= K; j++){ //每多一次移动,可以多进行一次测试。在手中有i-1个鸡蛋的第j-1次移动时已经测出楼高dp[i-1][j-1], //一次移动最差情况也可以测出当前楼层的情况,因此逆推出当前能够保证第j次移动得出结果的测试楼层为dp[i-1][j-1]+1 //第j次移动鸡蛋摔碎,可以确定当前层(1层)的结果(碎),剩余i-1个鸡蛋和j-1次移动能得出dp[i-1][j-1]层 //h1 = dp[i][j] = dp[i-1][j-1] + 1; //第j次移动鸡蛋未碎,可以确定前dp[i-1][j-1]+1层的结果(不碎),剩余i个鸡蛋和j-1次移动能得出dp[i][j-1]层 //h2 = dp[i][j] = dp[i-1][j-1] + 1 + dp[i-1][j]; //dp = h2 >= max(h1, h2) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + 1; if(dp[i][j] >= N){ return i; } } } return N; } //数学(最优) //最差情况下(一个鸡蛋)用N次移动可以测得N层楼高,因此可以移动次数x必在[1,N]之间,可以对x进行二分查找 public int superEggDrop(int K, int N) { int begin = 1; int end = N; while(begin < end){ int mid = (begin + end) >> 1; if(fun(mid, K, N) < N){ begin = mid + 1; }else { end = mid; } } return begin; } //递归函数fun(x)代表x次移动能够测试的最大楼高 //https://leetcode-cn.com/problems/super-egg-drop/solution/ji-dan-diao-luo-by-leetcode/ //https://leetcode-cn.com/problems/super-egg-drop/solution/shu-xue-fa-jie-shi-by-lycao/ private int fun(int x, int k, int n){ int result = 0; int r = 1; for(int i = 1; i <= k; ++i){ r *= x - i + 1; r /= i; result += r; if(result >= n){ break; } } return result; } }
ChopinXBP/LeetCode-Babel
src/Problems/SuperEggDrop.java
2,901
//动态规划:二分搜索
line_comment
zh-cn
package Problems; import java.util.HashMap; /** * * You are given K eggs, and you have access to a building with N floors from 1 to N. * Each egg is identical in function, and if an egg breaks, you cannot drop it again. * You know that there exists a floor F with 0 <= F <= N such that any egg dropped at a floor higher than F will break, * and any egg dropped at or below floor F will not break. * Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X (with 1 <= X <= N). * Your goal is to know with certainty what the value of F is. * What is the minimum number of moves that you need to know with certainty what F is, regardless of the initial value of F? * 你将获得 K 个鸡蛋,并可以使用一栋从 1 到 N  共有 N 层楼的建筑。 * 每个蛋的功能都是一样的,如果一个蛋碎了,你就不能再把它掉下去。 * 你知道存在楼层 F ,满足 0 <= F <= N 任何从高于 F 的楼层落下的鸡蛋都会碎,从 F 楼层或比它低的楼层落下的鸡蛋都不会破。 * 每次移动,你可以取一个鸡蛋(如果你有完整的鸡蛋)并把它从任一楼层 X 扔下(满足 1 <= X <= N)。 * 你的目标是确切地知道 F 的值是多少。 * 无论 F 的初始值如何,你确定 F 的值的最小移动次数是多少? * */ public class SuperEggDrop { //递归(超时) public int superEggDrop2(int K, int N) { if(N < 2 || K == 1){ return N; } int result = N; //在手握K个鸡蛋时从第i层楼[0,N]向下丢鸡蛋,会有两种可能: //1.鸡蛋摔碎,将剩余K-1个鸡蛋移动到楼[0,i-1]进行测递归测试。 //2.鸡蛋没碎,将剩余K个鸡蛋移动到楼[i,N]进行测试,可将i层看成0层,对[0,N-i]进行递归测试。 for(int i = 1; i <= N; i++){ int curMin = Math.max(superEggDrop2(K - 1, i - 1), superEggDrop2(K, N - i)) + 1; result = curMin < result ? curMin : result; } return result; } //动态 <SUF> //观察递归公式result = min(max(superEggDrop(K - 1, i - 1), superEggDrop(K, N - i)) + 1),其中i在[1.N]变化 //而fun1=superEggDrop(K - 1, i - 1)随i单调增,fun2=superEggDrop(K, N - i)随i单调减,两条单调函数的交点即为两者最大值的最小取值点 //因此可以对i在[1,N]上进行二分查找 HashMap<Integer, Integer> map = new HashMap<>(); public int superEggDrop3(int K, int N) { if (N == 0){ return 0; } if (K == 1){ return N; } //因为K<=100,可以设计一个key值的取值方法,将已经计算过的K,N组合存入哈希表避免重复计算 int key = N * 1000 + K; if (map.containsKey(key)){ return map.get(key); } int begin = 1; int end = N; while (begin + 1 < end) { int mid = (begin + end) >> 1; int lowVal = superEggDrop(K - 1, mid - 1); int highVal = superEggDrop(K, N - mid); if (lowVal < highVal){ begin = mid; } else if (lowVal > highVal){ end = mid; } else{ end = mid; begin = mid; } } int minimum = 1 + Math.min(Math.max(superEggDrop(K - 1, begin - 1), superEggDrop(K, N - begin)), Math.max(superEggDrop(K - 1, end - 1), superEggDrop(K, N - end))); map.put(key, minimum); return minimum; } //动态规划:自底向上 //观察转为动态规划的递归公式dp[i][j] = min(max(dp[i-1][loc-1], dp[i][j-loc]) + 1),其中i在[1.j]变化,j在[1, N]变化 //而fun1=dp[i-1][loc-1]随loc单调增,fun2=dp[i][j-loc]随loc单调减,两条单调函数的交点即为两者最大值的最小取值点 //寻找loc的思路转换为while循环遍历查找 public int superEggDrop4(int K, int N) { int[][] dp = new int[K + 1][N + 1]; for(int i = 1; i <= K; i++){ int loc = 1; for(int j = 1; j <= N; j++){ if(i == 1){ dp[i][j] = j; continue; } //令left为loc-1时的函数值,right为loc时的函数值,循环遍历找到最小值的拐点 //由于后序j值上限不断增大,loc拐点值只可能逐渐向右移动,以此可以简化后序查找 while (loc < j){ int left = Math.max(dp[i - 1][loc - 1], dp[i][j - loc]); int right = Math.max(dp[i - 1][loc], dp[i][j - loc - 1]); if(left <= right){ break; } loc++; } dp[i][j] = Math.max(dp[i - 1][loc - 1], dp[i][j - loc]) + 1; } } return dp[K][N]; } //动态规划(超时):求能够测得的最少楼层 public int superEggDrop5(int K, int N) { //dp[i][j]代表有i个鸡蛋和j次移动时一定能够测得的最少楼层数 int[][] dp = new int[K + 1][N + 1]; //没有鸡蛋时或没有移动次数时无法测试dp=0;只有1个鸡蛋但有j次移动,dp=j(从0层开始逐层测试) for (int i = 1; i <= N; i++) { dp[1][i] = i; dp[0][i] = 0; } for (int i = 1; i <= K; i++) { dp[i][0] = 0; } for (int i = 2; i <= K; i++) { for (int j = 1; j <= N; j++) { //有i个鸡蛋和j次移动时,前j-1次移动的测试结果可能由多种测试路径得来,将其划分为k次和(j-1)-k次遍历取最大 //第j-1次移动鸡蛋碎的结果为dp[i-1][k],鸡蛋未碎的结果为dp[i][(j - 1) - k],当前楼层第j次移动的最少测试结果为1(摔碎) //dp[i][j] = max(dp[i - 1][k], dp[i][(j - 1) - k]) + 1 int tMinDrop = N * N; for (int k = 0; k < j; k++) { tMinDrop = Math.min(tMinDrop, Math.max(dp[i - 1][k], dp[i][(j - 1) - k]) + 1); } dp[i][j] = tMinDrop; } } return dp[K][N]; } //动态规划(次优):求能够测得的最多楼层 public int superEggDrop6(int K, int N) { //dp[i][j]代表i个鸡蛋在j次移动内能测试确定的最多楼层数 int[][] dp = new int[N + 1][K + 1]; //从第一层楼开始更新dp数组 for(int i = 1; i <= N; i++){ //0次移动无法进行测试,初始值dp[i][0]=0 dp[i][0] = 0; for(int j = 1; j <= K; j++){ //每多一次移动,可以多进行一次测试。在手中有i-1个鸡蛋的第j-1次移动时已经测出楼高dp[i-1][j-1], //一次移动最差情况也可以测出当前楼层的情况,因此逆推出当前能够保证第j次移动得出结果的测试楼层为dp[i-1][j-1]+1 //第j次移动鸡蛋摔碎,可以确定当前层(1层)的结果(碎),剩余i-1个鸡蛋和j-1次移动能得出dp[i-1][j-1]层 //h1 = dp[i][j] = dp[i-1][j-1] + 1; //第j次移动鸡蛋未碎,可以确定前dp[i-1][j-1]+1层的结果(不碎),剩余i个鸡蛋和j-1次移动能得出dp[i][j-1]层 //h2 = dp[i][j] = dp[i-1][j-1] + 1 + dp[i-1][j]; //dp = h2 >= max(h1, h2) dp[i][j] = dp[i - 1][j] + dp[i - 1][j - 1] + 1; if(dp[i][j] >= N){ return i; } } } return N; } //数学(最优) //最差情况下(一个鸡蛋)用N次移动可以测得N层楼高,因此可以移动次数x必在[1,N]之间,可以对x进行二分查找 public int superEggDrop(int K, int N) { int begin = 1; int end = N; while(begin < end){ int mid = (begin + end) >> 1; if(fun(mid, K, N) < N){ begin = mid + 1; }else { end = mid; } } return begin; } //递归函数fun(x)代表x次移动能够测试的最大楼高 //https://leetcode-cn.com/problems/super-egg-drop/solution/ji-dan-diao-luo-by-leetcode/ //https://leetcode-cn.com/problems/super-egg-drop/solution/shu-xue-fa-jie-shi-by-lycao/ private int fun(int x, int k, int n){ int result = 0; int r = 1; for(int i = 1; i <= k; ++i){ r *= x - i + 1; r /= i; result += r; if(result >= n){ break; } } return result; } }
0
2,585
7
2,901
8
2,856
7
2,901
8
3,700
16
false
false
false
false
false
true
54162_12
package data_structure_homework_2; import data_structure_homework.Stack; public class SeqStack implements Stack{//顺序堆栈类 final int defaultSize=10;//堆栈默认大小 int top;//栈顶位置 Object[] stack;//数组对象 int maxStackSize;//最大数据元素个数 public SeqStack() {//无参构造方法 initiate(defaultSize); } public SeqStack(int sz) {//带参构造方法 initiate(sz); } private void initiate(int sz) {//初始化 maxStackSize=sz; top=0; stack=new Object[sz]; } public void push(Object obj) throws Exception{//入栈 if(top==maxStackSize) { throw new Exception("The stack is full!"); } stack[top]=obj;//保存元素 top++;//产生新的栈顶位置 } public Object pop() throws Exception{//出栈 if(top==0) { throw new Exception("The stack is empty!"); } top--;//产生原栈顶位置 return stack[top];//返回原栈顶元素 } public Object getTop() throws Exception{//取栈顶元素 if(top==0) { throw new Exception("The stack is empty!"); } return stack[top-1];//返回原栈顶元素 } public boolean notEmpty() {//非空否 return (top>0); } }
ChristopherFerryman/SSPKU_STUDY
SeqStack.java
365
//取栈顶元素
line_comment
zh-cn
package data_structure_homework_2; import data_structure_homework.Stack; public class SeqStack implements Stack{//顺序堆栈类 final int defaultSize=10;//堆栈默认大小 int top;//栈顶位置 Object[] stack;//数组对象 int maxStackSize;//最大数据元素个数 public SeqStack() {//无参构造方法 initiate(defaultSize); } public SeqStack(int sz) {//带参构造方法 initiate(sz); } private void initiate(int sz) {//初始化 maxStackSize=sz; top=0; stack=new Object[sz]; } public void push(Object obj) throws Exception{//入栈 if(top==maxStackSize) { throw new Exception("The stack is full!"); } stack[top]=obj;//保存元素 top++;//产生新的栈顶位置 } public Object pop() throws Exception{//出栈 if(top==0) { throw new Exception("The stack is empty!"); } top--;//产生原栈顶位置 return stack[top];//返回原栈顶元素 } public Object getTop() throws Exception{//取栈 <SUF> if(top==0) { throw new Exception("The stack is empty!"); } return stack[top-1];//返回原栈顶元素 } public boolean notEmpty() {//非空否 return (top>0); } }
0
312
5
365
5
365
5
365
5
487
10
false
false
false
false
false
true
16500_8
/** * @author Chunel * @Name JavaCaiss.java * @date 2020/9/15 1:23 上午 * @Desc 具体函数功能,请参考说明文档 */ import com.sun.jna.Native; // 使用前,请自行引入相关依赖。具体可参考给定pom.xml文件 import com.sun.jna.*; import com.sun.jna.ptr.NativeLongByReference; import com.sun.jna.ptr.PointerByReference; public class JaCaiss { public static String CAISS_PATH = "../libCaiss.so"; // 请设置正确caiss动态库的路径信息 private interface JnaCaiss extends Library { JnaCaiss instance = (JnaCaiss) Native.loadLibrary(CAISS_PATH, JnaCaiss.class); int CAISS_Environment(int maxThreadSize, int algoType, int manageType); int CAISS_CreateHandle(PointerByReference pointer); int CAISS_Init(Pointer handle, int mode, int distanceType, int dim, String modelPath, Object distFunc); int CAISS_Train(Pointer handle, String dataPath, int maxDataSize, int normalize, int maxIndexSize, float precision, int fastRank, int realRank, int step, int maxEpoch, int showSpan); int CAISS_Search(Pointer handle, String info, int searchType, int topK, int filterEditDistance, Object searchCBFunc, Pointer cbParams); // 暂不支持回调函数 int CAISS_Search(Pointer handle, float[] info, int searchType, int topK, int filterEditDistance, Object searchCBFunc, Pointer cbParams); // 传入向量的情况下, int CAISS_GetResultSize(Pointer handle, NativeLongByReference size); int CAISS_GetResult(Pointer handle, Pointer result, NativeLong size); int CAISS_Insert(Pointer handle, float[] node, String label, int insertType); int CAISS_Ignore(Pointer handle, String label, int isIgnore); int CAISS_Save(Pointer handle, String modelPath); int CAISS_ExecuteSQL(Pointer handle, String sql, Object sqlCBFunc, Pointer sqlParams); // 暂不支持回调函数 int CAISS_DestroyHandle(Pointer handle); } public synchronized static int Environment(int maxThreadSize, int algoType, int manageType) { return JnaCaiss.instance.CAISS_Environment(maxThreadSize, algoType, manageType); } public int CreateHandle(PointerByReference pointer) { return JnaCaiss.instance.CAISS_CreateHandle(pointer); } public int Init(Pointer handle, int mode, int distanceType, int dim, String modelPath) { return JnaCaiss.instance.CAISS_Init(handle, mode, distanceType, dim, modelPath, null); } public int Train(Pointer handle, String dataPath, int maxDataSize, int normalize, int maxIndexSize, float precision, int fastRank, int realRank, int step, int maxEpoch, int showSpan) { return JnaCaiss.instance.CAISS_Train(handle, dataPath, maxDataSize, normalize, maxIndexSize, precision, fastRank, realRank, step, maxEpoch, showSpan); } // 查询接口,适用于同步模式下的查询(单词查询) public String SyncSearch(Pointer handle, String info, int searchType, int topK, int filterEditDistance , NativeLongByReference ref) { if (searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_SEARCH_WORD && searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_LOOP_WORD) { // 如果不是单词查询的方式,则返回错误码 ref.setValue(new NativeLong(JaCaissDefine.CAISS_RET_PARAM)); return ""; } int ret = JnaCaiss.instance.CAISS_Search(handle, info, searchType, topK, filterEditDistance, null, null); if (JaCaissDefine.CAISS_RET_OK != ret) { ref.setValue(new NativeLong(ret)); return ""; } return getResultString(handle, ref); } public String SyncSearch(Pointer handle, float[] info, int searchType, int topK, int filterEditDistance , NativeLongByReference ref) { if (searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_SEARCH_QUERY && searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_LOOP_QUERY) { // 如果不是向量查询的方式,则返回错误码 ref.setValue(new NativeLong(JaCaissDefine.CAISS_RET_PARAM)); return ""; } int ret = JnaCaiss.instance.CAISS_Search(handle, info, searchType, topK, filterEditDistance, null, null); if (JaCaissDefine.CAISS_RET_OK != ret) { ref.setValue(new NativeLong(ret)); return ""; } return getResultString(handle, ref); } public String SyncExecuteSQL(Pointer handle, String sql, NativeLongByReference ref) { int ret = JnaCaiss.instance.CAISS_ExecuteSQL(handle, sql, null, null); if (JaCaissDefine.CAISS_RET_OK != ret) { ref.setValue(new NativeLong(ret)); return ""; } return getResultString(handle, ref); } public int Insert(Pointer handle, float[] node, String label, int insertType) { return JnaCaiss.instance.CAISS_Insert(handle, node, label, insertType); } public int Ignore(Pointer handle, String label, int isIgnore) { return JnaCaiss.instance.CAISS_Ignore(handle, label, isIgnore); } public int Save(Pointer handle, String modelPath) { return JnaCaiss.instance.CAISS_Save(handle, modelPath); } public int DestroyHandle(Pointer handle) { return JnaCaiss.instance.CAISS_DestroyHandle(handle); } /** * 获取最终的结果,并且返回对应的返回值 * @param handle 句柄信息 * @param ref CAISS函数的返回值信息 */ private String getResultString(Pointer handle, NativeLongByReference ref) { NativeLongByReference sizeRef = new NativeLongByReference(); int ret = JnaCaiss.instance.CAISS_GetResultSize(handle, sizeRef); if (JaCaissDefine.CAISS_RET_OK != ret) { ref.setValue(new NativeLong(ret)); return ""; } int size = sizeRef.getValue().intValue(); Pointer resultPtr = new Memory(size + 1); NativeLong size_ = new NativeLong(size); ret = JnaCaiss.instance.CAISS_GetResult(handle, resultPtr, size_); String result = (JaCaissDefine.CAISS_RET_OK == ret) ? resultPtr.getString(0) : ""; ref.setValue(new NativeLong(ret)); // 设置返回值信息 Native.free(Pointer.nativeValue(resultPtr)); // 释放申请的内存信息 Pointer.nativeValue(resultPtr, 0); return result; // 返回最终的查询结果信息 } }
ChunelFeng/caiss
java/JaCaiss.java
1,713
// 如果不是向量查询的方式,则返回错误码
line_comment
zh-cn
/** * @author Chunel * @Name JavaCaiss.java * @date 2020/9/15 1:23 上午 * @Desc 具体函数功能,请参考说明文档 */ import com.sun.jna.Native; // 使用前,请自行引入相关依赖。具体可参考给定pom.xml文件 import com.sun.jna.*; import com.sun.jna.ptr.NativeLongByReference; import com.sun.jna.ptr.PointerByReference; public class JaCaiss { public static String CAISS_PATH = "../libCaiss.so"; // 请设置正确caiss动态库的路径信息 private interface JnaCaiss extends Library { JnaCaiss instance = (JnaCaiss) Native.loadLibrary(CAISS_PATH, JnaCaiss.class); int CAISS_Environment(int maxThreadSize, int algoType, int manageType); int CAISS_CreateHandle(PointerByReference pointer); int CAISS_Init(Pointer handle, int mode, int distanceType, int dim, String modelPath, Object distFunc); int CAISS_Train(Pointer handle, String dataPath, int maxDataSize, int normalize, int maxIndexSize, float precision, int fastRank, int realRank, int step, int maxEpoch, int showSpan); int CAISS_Search(Pointer handle, String info, int searchType, int topK, int filterEditDistance, Object searchCBFunc, Pointer cbParams); // 暂不支持回调函数 int CAISS_Search(Pointer handle, float[] info, int searchType, int topK, int filterEditDistance, Object searchCBFunc, Pointer cbParams); // 传入向量的情况下, int CAISS_GetResultSize(Pointer handle, NativeLongByReference size); int CAISS_GetResult(Pointer handle, Pointer result, NativeLong size); int CAISS_Insert(Pointer handle, float[] node, String label, int insertType); int CAISS_Ignore(Pointer handle, String label, int isIgnore); int CAISS_Save(Pointer handle, String modelPath); int CAISS_ExecuteSQL(Pointer handle, String sql, Object sqlCBFunc, Pointer sqlParams); // 暂不支持回调函数 int CAISS_DestroyHandle(Pointer handle); } public synchronized static int Environment(int maxThreadSize, int algoType, int manageType) { return JnaCaiss.instance.CAISS_Environment(maxThreadSize, algoType, manageType); } public int CreateHandle(PointerByReference pointer) { return JnaCaiss.instance.CAISS_CreateHandle(pointer); } public int Init(Pointer handle, int mode, int distanceType, int dim, String modelPath) { return JnaCaiss.instance.CAISS_Init(handle, mode, distanceType, dim, modelPath, null); } public int Train(Pointer handle, String dataPath, int maxDataSize, int normalize, int maxIndexSize, float precision, int fastRank, int realRank, int step, int maxEpoch, int showSpan) { return JnaCaiss.instance.CAISS_Train(handle, dataPath, maxDataSize, normalize, maxIndexSize, precision, fastRank, realRank, step, maxEpoch, showSpan); } // 查询接口,适用于同步模式下的查询(单词查询) public String SyncSearch(Pointer handle, String info, int searchType, int topK, int filterEditDistance , NativeLongByReference ref) { if (searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_SEARCH_WORD && searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_LOOP_WORD) { // 如果不是单词查询的方式,则返回错误码 ref.setValue(new NativeLong(JaCaissDefine.CAISS_RET_PARAM)); return ""; } int ret = JnaCaiss.instance.CAISS_Search(handle, info, searchType, topK, filterEditDistance, null, null); if (JaCaissDefine.CAISS_RET_OK != ret) { ref.setValue(new NativeLong(ret)); return ""; } return getResultString(handle, ref); } public String SyncSearch(Pointer handle, float[] info, int searchType, int topK, int filterEditDistance , NativeLongByReference ref) { if (searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_SEARCH_QUERY && searchType != JaCaissDefine.CAISS_SEARCH_TYPE.CAISS_LOOP_QUERY) { // 如果 <SUF> ref.setValue(new NativeLong(JaCaissDefine.CAISS_RET_PARAM)); return ""; } int ret = JnaCaiss.instance.CAISS_Search(handle, info, searchType, topK, filterEditDistance, null, null); if (JaCaissDefine.CAISS_RET_OK != ret) { ref.setValue(new NativeLong(ret)); return ""; } return getResultString(handle, ref); } public String SyncExecuteSQL(Pointer handle, String sql, NativeLongByReference ref) { int ret = JnaCaiss.instance.CAISS_ExecuteSQL(handle, sql, null, null); if (JaCaissDefine.CAISS_RET_OK != ret) { ref.setValue(new NativeLong(ret)); return ""; } return getResultString(handle, ref); } public int Insert(Pointer handle, float[] node, String label, int insertType) { return JnaCaiss.instance.CAISS_Insert(handle, node, label, insertType); } public int Ignore(Pointer handle, String label, int isIgnore) { return JnaCaiss.instance.CAISS_Ignore(handle, label, isIgnore); } public int Save(Pointer handle, String modelPath) { return JnaCaiss.instance.CAISS_Save(handle, modelPath); } public int DestroyHandle(Pointer handle) { return JnaCaiss.instance.CAISS_DestroyHandle(handle); } /** * 获取最终的结果,并且返回对应的返回值 * @param handle 句柄信息 * @param ref CAISS函数的返回值信息 */ private String getResultString(Pointer handle, NativeLongByReference ref) { NativeLongByReference sizeRef = new NativeLongByReference(); int ret = JnaCaiss.instance.CAISS_GetResultSize(handle, sizeRef); if (JaCaissDefine.CAISS_RET_OK != ret) { ref.setValue(new NativeLong(ret)); return ""; } int size = sizeRef.getValue().intValue(); Pointer resultPtr = new Memory(size + 1); NativeLong size_ = new NativeLong(size); ret = JnaCaiss.instance.CAISS_GetResult(handle, resultPtr, size_); String result = (JaCaissDefine.CAISS_RET_OK == ret) ? resultPtr.getString(0) : ""; ref.setValue(new NativeLong(ret)); // 设置返回值信息 Native.free(Pointer.nativeValue(resultPtr)); // 释放申请的内存信息 Pointer.nativeValue(resultPtr, 0); return result; // 返回最终的查询结果信息 } }
0
1,546
11
1,713
12
1,787
11
1,713
12
2,115
24
false
false
false
false
false
true
23221_5
package com.company; import java.awt.*; public class Bg { // 关卡数 static int level = 1; // 目标得分 int goal = (level * 500) + 550; // 总分 static int count = 0; // 药水数量 static int waterNum = 3; // 药水状态 static boolean waterFlag = false; // 开始时间 long startTime; // 结束时间 long endTime; // 药水价格 int price = (int) (Math.random() * 10); // 是否进入商店 f不购买 boolean shop = false; // 载入图片 Image bg = Toolkit.getDefaultToolkit().getImage("imgs/bg.jpg"); Image bg1 = Toolkit.getDefaultToolkit().getImage("imgs/bg1.jpg"); Image peo = Toolkit.getDefaultToolkit().getImage("imgs/peo.png"); Image water = Toolkit.getDefaultToolkit().getImage("imgs/water.png"); // 绘制 void paintSelf(Graphics g) { g.drawImage(bg, 0, 200, null); g.drawImage(bg1, 0, 0, null); switch (GameWin.state) { case 0: drawWord(g, 80, Color.black, "按鼠标右键开始", 100, 400); drawWord(g, 60, Color.red, "游戏规则:", 100, 500); drawWord(g, 30, Color.black, "点击鼠标左键放出抓钩", 100, 560); drawWord(g, 30, Color.black, "抓住金块或石头可以点击鼠标右键", 100, 620); drawWord(g, 30, Color.black, "使用“大力神药”快速收回金块或者爆破石头", 100, 680); break; case 1: g.drawImage(peo, 310, 50, null); drawWord(g, 30, Color.black, "分数:" + count, 30, 150); g.drawImage(water, 550, 40, null); drawWord(g, 30, Color.black, "×" + waterNum, 610, 90); // 关卡数&目标得分 drawWord(g, 20, Color.black, "关卡:" + level, 30, 60); drawWord(g, 30, Color.black, "目标:" + goal, 30, 115); // 实时赋值 endTime = System.currentTimeMillis(); long time = 20 - (endTime - startTime) / 1000; drawWord(g, 30, Color.black, "时间:" + (time > 0 ? time : 0), 520, 150); break; case 2: g.drawImage(water, 330, 380, null); drawWord(g, 30, Color.black, "价格:" + price, 300, 500); drawWord(g, 30, Color.black, "是否购买“大力神药”?", 280, 550); drawWord(g, 30, Color.black, "点击鼠标左键确认购买,右键退出商店", 100, 700); if (shop) { count = count - price; waterNum++; shop = false; GameWin.state = 1; startTime = System.currentTimeMillis(); } break; case 3: drawWord(g, 80, Color.cyan, "失败", 300, 350); drawWord(g, 80, Color.black, "分数:" + count, 200, 450); drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550); break; case 4: drawWord(g, 80, Color.red, "恭喜过关", 250, 350); drawWord(g, 80, Color.black, "分数:" + count, 200, 450); drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550); break; default: } } // t倒计时完成,f未完成倒计时 boolean gameTime() { long time = (endTime - startTime) / 1000; if (time >= 20) { return true; } return false; } // 重置元素 void reGame() { // 关卡数 level = 1; // 目标得分 goal = (level * 500) + 550; // 总分 count = 0; // 药水数量 waterNum = 3; // 药水状态 waterFlag = false; } // 绘制字符串 public static void drawWord(Graphics g, int size, Color color, String str, int x, int y) { g.setColor(color); g.setFont(new Font("宋体", Font.BOLD, size)); g.drawString(str, x, y); } }
Cikian/GoldMiner
src/com/company/Bg.java
1,336
// 开始时间
line_comment
zh-cn
package com.company; import java.awt.*; public class Bg { // 关卡数 static int level = 1; // 目标得分 int goal = (level * 500) + 550; // 总分 static int count = 0; // 药水数量 static int waterNum = 3; // 药水状态 static boolean waterFlag = false; // 开始 <SUF> long startTime; // 结束时间 long endTime; // 药水价格 int price = (int) (Math.random() * 10); // 是否进入商店 f不购买 boolean shop = false; // 载入图片 Image bg = Toolkit.getDefaultToolkit().getImage("imgs/bg.jpg"); Image bg1 = Toolkit.getDefaultToolkit().getImage("imgs/bg1.jpg"); Image peo = Toolkit.getDefaultToolkit().getImage("imgs/peo.png"); Image water = Toolkit.getDefaultToolkit().getImage("imgs/water.png"); // 绘制 void paintSelf(Graphics g) { g.drawImage(bg, 0, 200, null); g.drawImage(bg1, 0, 0, null); switch (GameWin.state) { case 0: drawWord(g, 80, Color.black, "按鼠标右键开始", 100, 400); drawWord(g, 60, Color.red, "游戏规则:", 100, 500); drawWord(g, 30, Color.black, "点击鼠标左键放出抓钩", 100, 560); drawWord(g, 30, Color.black, "抓住金块或石头可以点击鼠标右键", 100, 620); drawWord(g, 30, Color.black, "使用“大力神药”快速收回金块或者爆破石头", 100, 680); break; case 1: g.drawImage(peo, 310, 50, null); drawWord(g, 30, Color.black, "分数:" + count, 30, 150); g.drawImage(water, 550, 40, null); drawWord(g, 30, Color.black, "×" + waterNum, 610, 90); // 关卡数&目标得分 drawWord(g, 20, Color.black, "关卡:" + level, 30, 60); drawWord(g, 30, Color.black, "目标:" + goal, 30, 115); // 实时赋值 endTime = System.currentTimeMillis(); long time = 20 - (endTime - startTime) / 1000; drawWord(g, 30, Color.black, "时间:" + (time > 0 ? time : 0), 520, 150); break; case 2: g.drawImage(water, 330, 380, null); drawWord(g, 30, Color.black, "价格:" + price, 300, 500); drawWord(g, 30, Color.black, "是否购买“大力神药”?", 280, 550); drawWord(g, 30, Color.black, "点击鼠标左键确认购买,右键退出商店", 100, 700); if (shop) { count = count - price; waterNum++; shop = false; GameWin.state = 1; startTime = System.currentTimeMillis(); } break; case 3: drawWord(g, 80, Color.cyan, "失败", 300, 350); drawWord(g, 80, Color.black, "分数:" + count, 200, 450); drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550); break; case 4: drawWord(g, 80, Color.red, "恭喜过关", 250, 350); drawWord(g, 80, Color.black, "分数:" + count, 200, 450); drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550); break; default: } } // t倒计时完成,f未完成倒计时 boolean gameTime() { long time = (endTime - startTime) / 1000; if (time >= 20) { return true; } return false; } // 重置元素 void reGame() { // 关卡数 level = 1; // 目标得分 goal = (level * 500) + 550; // 总分 count = 0; // 药水数量 waterNum = 3; // 药水状态 waterFlag = false; } // 绘制字符串 public static void drawWord(Graphics g, int size, Color color, String str, int x, int y) { g.setColor(color); g.setFont(new Font("宋体", Font.BOLD, size)); g.drawString(str, x, y); } }
0
1,236
5
1,336
5
1,370
4
1,336
5
1,637
7
false
false
false
false
false
true
15282_5
问题1 class Context { //保证一个引用 private AbstractStrategy strategy; public void setStrategy(AbstractStrategy str) { this.strategy= str; } //调用策略类中的算法 public void algorithm() { strategy.algorithm(); } } abstract class AbstractStrategy { //声明抽象算法 public abstract void algorithm(); } class ConcreteStrategyA extends AbstractStrategy { //算法的具体实现 public void algorithm() { System.out.println("重写"); } } class ConcreteStrategyB extends AbstractStrategy { //算法的具体实现 public void algorithm() { System.out.println("重写"); } } class ConcreteStrategyC extends AbstractStrategy { //算法的具体实现 public void algorithm() { System.out.println("重写"); } } 如果要添加其他算法,继续声明新类继承父类即可 问题2 使用模板方法模式 步骤不同的进行重写 class Context { private Algorithm algorithm; public void setAlgorithm(Algorithm algorithm) { this.algorithm= algorithm; } //调用策略类中的算法 public void algorithm() { algorithm.step1(); algorithm.step2(); algorithm.step3(); } } class Algorithm { public void step1() { System.out.println("step1的具体内容"); } public void step2() { System.out.println("step2的具体内容"); } public void step3() { System.out.println("step3的具体内容"); } class ConcreteAlgorithmA extends Algorithm { //算法的具体实现 public void step1() { System.out.println("重写了算法步骤1");//A步骤1有所不同 } } class ConcreteAlgorithmB extends Algorithm { //算法的具体实现 public void step2() { System.out.println("重写了算法步骤2"); //B步骤2有所不同 } } class ConcreteAlgorithmC extends Algorithm { //算法的具体实现 public void step3() { System.out.println("重写了算法步骤3");//C步骤3有所不同 } }
CirillaQL/DesignPatternsHomework
7-1.java
565
//算法的具体实现
line_comment
zh-cn
问题1 class Context { //保证一个引用 private AbstractStrategy strategy; public void setStrategy(AbstractStrategy str) { this.strategy= str; } //调用策略类中的算法 public void algorithm() { strategy.algorithm(); } } abstract class AbstractStrategy { //声明抽象算法 public abstract void algorithm(); } class ConcreteStrategyA extends AbstractStrategy { //算法的具体实现 public void algorithm() { System.out.println("重写"); } } class ConcreteStrategyB extends AbstractStrategy { //算法的具体实现 public void algorithm() { System.out.println("重写"); } } class ConcreteStrategyC extends AbstractStrategy { //算法 <SUF> public void algorithm() { System.out.println("重写"); } } 如果要添加其他算法,继续声明新类继承父类即可 问题2 使用模板方法模式 步骤不同的进行重写 class Context { private Algorithm algorithm; public void setAlgorithm(Algorithm algorithm) { this.algorithm= algorithm; } //调用策略类中的算法 public void algorithm() { algorithm.step1(); algorithm.step2(); algorithm.step3(); } } class Algorithm { public void step1() { System.out.println("step1的具体内容"); } public void step2() { System.out.println("step2的具体内容"); } public void step3() { System.out.println("step3的具体内容"); } class ConcreteAlgorithmA extends Algorithm { //算法的具体实现 public void step1() { System.out.println("重写了算法步骤1");//A步骤1有所不同 } } class ConcreteAlgorithmB extends Algorithm { //算法的具体实现 public void step2() { System.out.println("重写了算法步骤2"); //B步骤2有所不同 } } class ConcreteAlgorithmC extends Algorithm { //算法的具体实现 public void step3() { System.out.println("重写了算法步骤3");//C步骤3有所不同 } }
0
511
5
565
6
686
6
565
6
856
11
false
false
false
false
false
true
40721_6
package com.civitasv.spider.model.bo; import com.civitasv.spider.model.po.PoiPo; import com.civitasv.spider.util.BeanUtils; import com.google.gson.annotations.SerializedName; import lombok.*; import lombok.experimental.Accessors; import java.util.List; @Getter @Setter @Accessors(fluent = true) @Builder @ToString public class POI { @SerializedName("status") private final Integer status; @SerializedName("info") private String info; @SerializedName("infocode") private Integer infoCode; @SerializedName("count") private Integer count; @SerializedName("pois") private List<Info> details; @Getter @Accessors(fluent = true) @AllArgsConstructor public enum OutputFields { ID("id", "id", "唯一ID", false, true), NAME("name", "name", "名称", false, true), TYPE("type", "type", "类型", false, true), TYPE_CODE("typeCode", "typeCode", "类型编码", false, true), BIZ_TYPE("bizType", "bizType", "行业类型", false, true), ADDRESS("address", "address", "地址", false, true), GCJ02_LNG("gcj02_lng", "gcj02_lng", "gcj02 格式经度", false, true), GCJ02_LAT("gcj02_lat", "gcj02_lat", "gcj02 格式纬度", false, true), WGS84_LNG("wgs84_lng", "wgs84_lng", "wgs84 格式经度", false, true), WGS84_LAT("wgs84_lat", "wgs84_lat", "wgs84 格式纬度", false, true), TEL("tel", "tel", "电话", false, true), PROVINCE_NAME("provinceName", "province", "省份名称", false, true), CITY_NAME("cityName", "city", "城市名称", false, true), AD_NAME("adName", "ad", "区域名称", false, true), POST_CODE("postCode", "postCode", "邮编", true, false), WEBSITE("website", "website", "网址", true, false), EMAIL("email", "email", "邮箱", true, false), PROVINCE_CODE("provinceCode", "provCode", "省份编码", true, false), CITY_CODE("cityCode", "cityCode", "城市编码", true, false), AD_CODE("adCode", "adCode", "区域编码", true, false); private final String fieldName; private final String shapeFieldName; // shp 字段长度有限制 private final String description; private final boolean inExtension; private boolean checked; public void checked(boolean checked) { this.checked = checked; } @Override public String toString() { return description; } } @Getter @Setter @Accessors(fluent = true) @Builder @ToString public static class Info { private transient Long id; // 对应PoiPo id @SerializedName("id") private Object poiId; // 唯一id 对应pid @SerializedName("name") private Object name; // 名称 @SerializedName("type") private Object type; // 兴趣点类型 @SerializedName("typecode") private Object typeCode; // 兴趣点类型编码 @SerializedName("biz_type") private Object bizType; // 行业类型 @SerializedName("address") private Object address; // 地址 @SerializedName("location") private Object location; // 经纬度 @SerializedName("tel") private Object tel; // 电话 @SerializedName("pname") private Object provinceName; // 省份名称 @SerializedName("cityname") private Object cityName; // 城市名称 @SerializedName("adname") private Object adName; // 区域名称 @SerializedName("postcode") private Object postCode; // 邮编,extensions=all时返回 @SerializedName("website") private Object website; // 网址,extensions=all时返回 @SerializedName("email") private Object email; // 邮箱,extensions=all时返回 @SerializedName("pcode") private Object provinceCode; // 省份编码,extensions=all时返回 @SerializedName("citycode") private Object cityCode; // 城市编码,extensions=all时返回 @SerializedName("adcode") private Object adCode; // 区域编码,extensions=all时返回 public PoiPo toPoiPo(Long jobId) { return PoiPo.builder() .id(id) .poiId(BeanUtils.obj2String(poiId)) .jobId(jobId) .name(BeanUtils.obj2String(name)) .type(BeanUtils.obj2String(type)) .typeCode(BeanUtils.obj2String(typeCode)) .bizType(BeanUtils.obj2String(bizType)) .address(BeanUtils.obj2String(address)) .location(BeanUtils.obj2String(location)) .tel(BeanUtils.obj2String(tel)) .provinceName(BeanUtils.obj2String(provinceName)) .cityName(BeanUtils.obj2String(cityName)) .adName(BeanUtils.obj2String(adName)) .build(); } public PoiPo toPoiPoWithExtensions(Long jobId) { return PoiPo.builder() .id(id) .poiId(BeanUtils.obj2String(poiId)) .jobId(jobId) .name(BeanUtils.obj2String(name)) .type(BeanUtils.obj2String(type)) .typeCode(BeanUtils.obj2String(typeCode)) .bizType(BeanUtils.obj2String(bizType)) .address(BeanUtils.obj2String(address)) .location(BeanUtils.obj2String(location)) .tel(BeanUtils.obj2String(tel)) .provinceName(BeanUtils.obj2String(provinceName)) .cityName(BeanUtils.obj2String(cityName)) .adName(BeanUtils.obj2String(adName)) .postCode(BeanUtils.obj2String(postCode)) .website(BeanUtils.obj2String(website)) .email(BeanUtils.obj2String(email)) .provinceCode(BeanUtils.obj2String(provinceCode)) .cityCode(BeanUtils.obj2String(cityCode)) .adCode(BeanUtils.obj2String(adCode)) .build(); } } }
Civitasv/AMapPoi
src/main/java/com/civitasv/spider/model/bo/POI.java
1,565
// 经纬度
line_comment
zh-cn
package com.civitasv.spider.model.bo; import com.civitasv.spider.model.po.PoiPo; import com.civitasv.spider.util.BeanUtils; import com.google.gson.annotations.SerializedName; import lombok.*; import lombok.experimental.Accessors; import java.util.List; @Getter @Setter @Accessors(fluent = true) @Builder @ToString public class POI { @SerializedName("status") private final Integer status; @SerializedName("info") private String info; @SerializedName("infocode") private Integer infoCode; @SerializedName("count") private Integer count; @SerializedName("pois") private List<Info> details; @Getter @Accessors(fluent = true) @AllArgsConstructor public enum OutputFields { ID("id", "id", "唯一ID", false, true), NAME("name", "name", "名称", false, true), TYPE("type", "type", "类型", false, true), TYPE_CODE("typeCode", "typeCode", "类型编码", false, true), BIZ_TYPE("bizType", "bizType", "行业类型", false, true), ADDRESS("address", "address", "地址", false, true), GCJ02_LNG("gcj02_lng", "gcj02_lng", "gcj02 格式经度", false, true), GCJ02_LAT("gcj02_lat", "gcj02_lat", "gcj02 格式纬度", false, true), WGS84_LNG("wgs84_lng", "wgs84_lng", "wgs84 格式经度", false, true), WGS84_LAT("wgs84_lat", "wgs84_lat", "wgs84 格式纬度", false, true), TEL("tel", "tel", "电话", false, true), PROVINCE_NAME("provinceName", "province", "省份名称", false, true), CITY_NAME("cityName", "city", "城市名称", false, true), AD_NAME("adName", "ad", "区域名称", false, true), POST_CODE("postCode", "postCode", "邮编", true, false), WEBSITE("website", "website", "网址", true, false), EMAIL("email", "email", "邮箱", true, false), PROVINCE_CODE("provinceCode", "provCode", "省份编码", true, false), CITY_CODE("cityCode", "cityCode", "城市编码", true, false), AD_CODE("adCode", "adCode", "区域编码", true, false); private final String fieldName; private final String shapeFieldName; // shp 字段长度有限制 private final String description; private final boolean inExtension; private boolean checked; public void checked(boolean checked) { this.checked = checked; } @Override public String toString() { return description; } } @Getter @Setter @Accessors(fluent = true) @Builder @ToString public static class Info { private transient Long id; // 对应PoiPo id @SerializedName("id") private Object poiId; // 唯一id 对应pid @SerializedName("name") private Object name; // 名称 @SerializedName("type") private Object type; // 兴趣点类型 @SerializedName("typecode") private Object typeCode; // 兴趣点类型编码 @SerializedName("biz_type") private Object bizType; // 行业类型 @SerializedName("address") private Object address; // 地址 @SerializedName("location") private Object location; // 经纬 <SUF> @SerializedName("tel") private Object tel; // 电话 @SerializedName("pname") private Object provinceName; // 省份名称 @SerializedName("cityname") private Object cityName; // 城市名称 @SerializedName("adname") private Object adName; // 区域名称 @SerializedName("postcode") private Object postCode; // 邮编,extensions=all时返回 @SerializedName("website") private Object website; // 网址,extensions=all时返回 @SerializedName("email") private Object email; // 邮箱,extensions=all时返回 @SerializedName("pcode") private Object provinceCode; // 省份编码,extensions=all时返回 @SerializedName("citycode") private Object cityCode; // 城市编码,extensions=all时返回 @SerializedName("adcode") private Object adCode; // 区域编码,extensions=all时返回 public PoiPo toPoiPo(Long jobId) { return PoiPo.builder() .id(id) .poiId(BeanUtils.obj2String(poiId)) .jobId(jobId) .name(BeanUtils.obj2String(name)) .type(BeanUtils.obj2String(type)) .typeCode(BeanUtils.obj2String(typeCode)) .bizType(BeanUtils.obj2String(bizType)) .address(BeanUtils.obj2String(address)) .location(BeanUtils.obj2String(location)) .tel(BeanUtils.obj2String(tel)) .provinceName(BeanUtils.obj2String(provinceName)) .cityName(BeanUtils.obj2String(cityName)) .adName(BeanUtils.obj2String(adName)) .build(); } public PoiPo toPoiPoWithExtensions(Long jobId) { return PoiPo.builder() .id(id) .poiId(BeanUtils.obj2String(poiId)) .jobId(jobId) .name(BeanUtils.obj2String(name)) .type(BeanUtils.obj2String(type)) .typeCode(BeanUtils.obj2String(typeCode)) .bizType(BeanUtils.obj2String(bizType)) .address(BeanUtils.obj2String(address)) .location(BeanUtils.obj2String(location)) .tel(BeanUtils.obj2String(tel)) .provinceName(BeanUtils.obj2String(provinceName)) .cityName(BeanUtils.obj2String(cityName)) .adName(BeanUtils.obj2String(adName)) .postCode(BeanUtils.obj2String(postCode)) .website(BeanUtils.obj2String(website)) .email(BeanUtils.obj2String(email)) .provinceCode(BeanUtils.obj2String(provinceCode)) .cityCode(BeanUtils.obj2String(cityCode)) .adCode(BeanUtils.obj2String(adCode)) .build(); } } }
0
1,482
5
1,565
6
1,607
4
1,565
6
1,932
7
false
false
false
false
false
true
34769_11
package ali; import java.util.Arrays; /** * * @author Claudius * 给一个正整数数组,砍掉三个数,分为四个段,查看是否存在着三个数,让这四个段之和相等。如果存在则返回true。 * 阿里的笔试题。 */ public class NewMain { /** 请完成下面这个函数,实现题目要求的功能 **/ /** 当然,你也可以不按照这个模板来作答,完全按照自己的想法来 ^-^ **/ static boolean resolve(int[] A) { int length = A.length; if (length <= 7) { //数组中数的数量至少有七个 return false; } //先对两个和rightSum和leftSum赋值,分别为左端与右端赋值给两段的和 for(int left = 1,right = length - 2,rightSum = A[length - 1],leftSum = A[0];left <= right - 4; ){ //从两端开始遍历,直到左端与右端下标距离 if (leftSum < rightSum) { //哪个大,移动哪个 //(必须保证中间的数还可以分为两段) leftSum += A[left]; left++; continue; }else if (leftSum > rightSum) { rightSum += A[right]; right--; continue; } if(right - left + 2 <= 2*leftSum ){ return false; } //此时leftSum 和rightSum相等,left 和 right 分别对应需要跳过的下标 int middleLeft,middleRight,middleLeftSum; // middleRight 代表中间最右值的下标 //将左起第一个值赋值给middleLeftSum,累加循环,直到middleLeftSum大于等于leftSum 或者 距离右端只有两个值时 for( middleLeft = left+2,middleRight = right - 1,middleLeftSum = A[left + 1];middleLeft < middleRight-1; middleLeft++){ if (middleLeftSum >= leftSum) { //如果要是相等,或者比leftSum大,则跳出循环 break; }else if (middleLeftSum < leftSum) { //如果要是小于,则继续循环 middleLeftSum += A[middleLeft]; } } if (middleLeftSum < leftSum) { //小于代表着中间值加完了还是小于,所以最外圈循环再加下去会更小,没有必要再继续了 return false; }else if (middleLeftSum == leftSum) { //相等,判断剩下的值之和是否相等,如果不相等,则继续外圈循环 int middleRightSum = 0; //因为相等了,所以必然是从middleLeft + 1开始的,因为要空过下一个下标 for(int index = middleLeft + 1;index <= middleRight;index++){ middleRightSum += A[index]; } //判断是否相等 if (middleRightSum == rightSum) { return true; }else { continue; } }else { //大于,给左边继续加,然后继续循环 leftSum += A[left]; left++; } } return false; } public static void main(String[] args){ // ArrayList<Integer> inputs = new ArrayList<Integer>(); // Scanner in = new Scanner(System.in); // String line = in.nextLine(); // while(line != null && !line.isEmpty()) { // int value = Integer.parseInt(line.trim()); // if(value == 0) break; // inputs.add(value); // line = in.nextLine(); // } // int[] A = new int[inputs.size()]; // for(int i=0; i<inputs.size(); i++) { // A[i] = inputs.get(i).intValue(); // } int [] A = {2,2,5,1,2,1,1,3,1,10,1,1,1,1}; Boolean res = resolve(A); System.out.println(String.valueOf(res)); } }
ClaudiusJXK/SwordToOffer
java/NewMain.java
1,056
//如果要是小于,则继续循环
line_comment
zh-cn
package ali; import java.util.Arrays; /** * * @author Claudius * 给一个正整数数组,砍掉三个数,分为四个段,查看是否存在着三个数,让这四个段之和相等。如果存在则返回true。 * 阿里的笔试题。 */ public class NewMain { /** 请完成下面这个函数,实现题目要求的功能 **/ /** 当然,你也可以不按照这个模板来作答,完全按照自己的想法来 ^-^ **/ static boolean resolve(int[] A) { int length = A.length; if (length <= 7) { //数组中数的数量至少有七个 return false; } //先对两个和rightSum和leftSum赋值,分别为左端与右端赋值给两段的和 for(int left = 1,right = length - 2,rightSum = A[length - 1],leftSum = A[0];left <= right - 4; ){ //从两端开始遍历,直到左端与右端下标距离 if (leftSum < rightSum) { //哪个大,移动哪个 //(必须保证中间的数还可以分为两段) leftSum += A[left]; left++; continue; }else if (leftSum > rightSum) { rightSum += A[right]; right--; continue; } if(right - left + 2 <= 2*leftSum ){ return false; } //此时leftSum 和rightSum相等,left 和 right 分别对应需要跳过的下标 int middleLeft,middleRight,middleLeftSum; // middleRight 代表中间最右值的下标 //将左起第一个值赋值给middleLeftSum,累加循环,直到middleLeftSum大于等于leftSum 或者 距离右端只有两个值时 for( middleLeft = left+2,middleRight = right - 1,middleLeftSum = A[left + 1];middleLeft < middleRight-1; middleLeft++){ if (middleLeftSum >= leftSum) { //如果要是相等,或者比leftSum大,则跳出循环 break; }else if (middleLeftSum < leftSum) { //如果 <SUF> middleLeftSum += A[middleLeft]; } } if (middleLeftSum < leftSum) { //小于代表着中间值加完了还是小于,所以最外圈循环再加下去会更小,没有必要再继续了 return false; }else if (middleLeftSum == leftSum) { //相等,判断剩下的值之和是否相等,如果不相等,则继续外圈循环 int middleRightSum = 0; //因为相等了,所以必然是从middleLeft + 1开始的,因为要空过下一个下标 for(int index = middleLeft + 1;index <= middleRight;index++){ middleRightSum += A[index]; } //判断是否相等 if (middleRightSum == rightSum) { return true; }else { continue; } }else { //大于,给左边继续加,然后继续循环 leftSum += A[left]; left++; } } return false; } public static void main(String[] args){ // ArrayList<Integer> inputs = new ArrayList<Integer>(); // Scanner in = new Scanner(System.in); // String line = in.nextLine(); // while(line != null && !line.isEmpty()) { // int value = Integer.parseInt(line.trim()); // if(value == 0) break; // inputs.add(value); // line = in.nextLine(); // } // int[] A = new int[inputs.size()]; // for(int i=0; i<inputs.size(); i++) { // A[i] = inputs.get(i).intValue(); // } int [] A = {2,2,5,1,2,1,1,3,1,10,1,1,1,1}; Boolean res = resolve(A); System.out.println(String.valueOf(res)); } }
0
931
7
1,056
10
1,047
8
1,056
10
1,422
21
false
false
false
false
false
true
56555_8
package com.kesar.a; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; /** * * ClassName: AStar * @Description: A星算法 * @author kesar */ public class AStar { public final static int BAR = 1; // 障碍值 public final static int PATH = 2; // 路径 public final static int DIRECT_VALUE = 10; // 横竖移动代价 public final static int OBLIQUE_VALUE = 14; // 斜移动代价 Queue<Node> openList = new PriorityQueue<Node>(); // 优先队列(升序) List<Node> closeList = new ArrayList<Node>(); /** * 开始算法 */ public void start(MapInfo mapInfo) { if(mapInfo==null) return; // clean openList.clear(); closeList.clear(); // 开始搜索 openList.add(mapInfo.start); moveNodes(mapInfo); } /** * 移动当前结点 */ private void moveNodes(MapInfo mapInfo) { while (!openList.isEmpty()) { Node current = openList.poll(); closeList.add(current); addNeighborNodeInOpen(mapInfo,current); if (isCoordInClose(mapInfo.end.coord)) { drawPath(mapInfo.maps, mapInfo.end); break; } } } /** * 在二维数组中绘制路径 */ private void drawPath(int[][] maps, Node end) { if(end==null||maps==null) return; System.out.println("总代价:" + end.G); while (end != null) { Coord c = end.coord; maps[c.y][c.x] = PATH; end = end.parent; } } /** * 添加所有邻结点到open表 */ private void addNeighborNodeInOpen(MapInfo mapInfo,Node current) { int x = current.coord.x; int y = current.coord.y; // 左 addNeighborNodeInOpen(mapInfo,current, x - 1, y, DIRECT_VALUE); // 上 addNeighborNodeInOpen(mapInfo,current, x, y - 1, DIRECT_VALUE); // 右 addNeighborNodeInOpen(mapInfo,current, x + 1, y, DIRECT_VALUE); // 下 addNeighborNodeInOpen(mapInfo,current, x, y + 1, DIRECT_VALUE); // 左上 addNeighborNodeInOpen(mapInfo,current, x - 1, y - 1, OBLIQUE_VALUE); // 右上 addNeighborNodeInOpen(mapInfo,current, x + 1, y - 1, OBLIQUE_VALUE); // 右下 addNeighborNodeInOpen(mapInfo,current, x + 1, y + 1, OBLIQUE_VALUE); // 左下 addNeighborNodeInOpen(mapInfo,current, x - 1, y + 1, OBLIQUE_VALUE); } /** * 添加一个邻结点到open表 */ private void addNeighborNodeInOpen(MapInfo mapInfo,Node current, int x, int y, int value) { if (canAddNodeToOpen(mapInfo,x, y)) { Node end=mapInfo.end; Coord coord = new Coord(x, y); int G = current.G + value; // 计算邻结点的G值 Node child = findNodeInOpen(coord); if (child == null) { int H=calcH(end.coord,coord); // 计算H值 if(isEndNode(end.coord,coord)) { child=end; child.parent=current; child.G=G; child.H=H; } else { child = new Node(coord, current, G, H); } openList.add(child); } else if (child.G > G) { child.G = G; child.parent = current; openList.add(child); } } } /** * 从Open列表中查找结点 */ private Node findNodeInOpen(Coord coord) { if (coord == null || openList.isEmpty()) return null; for (Node node : openList) { if (node.coord.equals(coord)) { return node; } } return null; } /** * 计算H的估值:“曼哈顿”法,坐标分别取差值相加 */ private int calcH(Coord end,Coord coord) { return (Math.abs(end.x - coord.x) + Math.abs(end.y - coord.y)) * DIRECT_VALUE; } /** * 判断结点是否是最终结点 */ private boolean isEndNode(Coord end,Coord coord) { return coord != null && end.equals(coord); } /** * 判断结点能否放入Open列表 */ private boolean canAddNodeToOpen(MapInfo mapInfo,int x, int y) { // 是否在地图中 if (x < 0 || x >= mapInfo.width || y < 0 || y >= mapInfo.hight) return false; // 判断是否是不可通过的结点 if (mapInfo.maps[y][x] == BAR) return false; // 判断结点是否存在close表 if (isCoordInClose(x, y)) return false; return true; } /** * 判断坐标是否在close表中 */ private boolean isCoordInClose(Coord coord) { return coord!=null&&isCoordInClose(coord.x, coord.y); } /** * 判断坐标是否在close表中 */ private boolean isCoordInClose(int x, int y) { if (closeList.isEmpty()) return false; for (Node node : closeList) { if (node.coord.x == x && node.coord.y == y) { return true; } } return false; } }
ClaymanTwinkle/astar
src/com/kesar/a/AStar.java
1,621
// 开始搜索
line_comment
zh-cn
package com.kesar.a; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; /** * * ClassName: AStar * @Description: A星算法 * @author kesar */ public class AStar { public final static int BAR = 1; // 障碍值 public final static int PATH = 2; // 路径 public final static int DIRECT_VALUE = 10; // 横竖移动代价 public final static int OBLIQUE_VALUE = 14; // 斜移动代价 Queue<Node> openList = new PriorityQueue<Node>(); // 优先队列(升序) List<Node> closeList = new ArrayList<Node>(); /** * 开始算法 */ public void start(MapInfo mapInfo) { if(mapInfo==null) return; // clean openList.clear(); closeList.clear(); // 开始 <SUF> openList.add(mapInfo.start); moveNodes(mapInfo); } /** * 移动当前结点 */ private void moveNodes(MapInfo mapInfo) { while (!openList.isEmpty()) { Node current = openList.poll(); closeList.add(current); addNeighborNodeInOpen(mapInfo,current); if (isCoordInClose(mapInfo.end.coord)) { drawPath(mapInfo.maps, mapInfo.end); break; } } } /** * 在二维数组中绘制路径 */ private void drawPath(int[][] maps, Node end) { if(end==null||maps==null) return; System.out.println("总代价:" + end.G); while (end != null) { Coord c = end.coord; maps[c.y][c.x] = PATH; end = end.parent; } } /** * 添加所有邻结点到open表 */ private void addNeighborNodeInOpen(MapInfo mapInfo,Node current) { int x = current.coord.x; int y = current.coord.y; // 左 addNeighborNodeInOpen(mapInfo,current, x - 1, y, DIRECT_VALUE); // 上 addNeighborNodeInOpen(mapInfo,current, x, y - 1, DIRECT_VALUE); // 右 addNeighborNodeInOpen(mapInfo,current, x + 1, y, DIRECT_VALUE); // 下 addNeighborNodeInOpen(mapInfo,current, x, y + 1, DIRECT_VALUE); // 左上 addNeighborNodeInOpen(mapInfo,current, x - 1, y - 1, OBLIQUE_VALUE); // 右上 addNeighborNodeInOpen(mapInfo,current, x + 1, y - 1, OBLIQUE_VALUE); // 右下 addNeighborNodeInOpen(mapInfo,current, x + 1, y + 1, OBLIQUE_VALUE); // 左下 addNeighborNodeInOpen(mapInfo,current, x - 1, y + 1, OBLIQUE_VALUE); } /** * 添加一个邻结点到open表 */ private void addNeighborNodeInOpen(MapInfo mapInfo,Node current, int x, int y, int value) { if (canAddNodeToOpen(mapInfo,x, y)) { Node end=mapInfo.end; Coord coord = new Coord(x, y); int G = current.G + value; // 计算邻结点的G值 Node child = findNodeInOpen(coord); if (child == null) { int H=calcH(end.coord,coord); // 计算H值 if(isEndNode(end.coord,coord)) { child=end; child.parent=current; child.G=G; child.H=H; } else { child = new Node(coord, current, G, H); } openList.add(child); } else if (child.G > G) { child.G = G; child.parent = current; openList.add(child); } } } /** * 从Open列表中查找结点 */ private Node findNodeInOpen(Coord coord) { if (coord == null || openList.isEmpty()) return null; for (Node node : openList) { if (node.coord.equals(coord)) { return node; } } return null; } /** * 计算H的估值:“曼哈顿”法,坐标分别取差值相加 */ private int calcH(Coord end,Coord coord) { return (Math.abs(end.x - coord.x) + Math.abs(end.y - coord.y)) * DIRECT_VALUE; } /** * 判断结点是否是最终结点 */ private boolean isEndNode(Coord end,Coord coord) { return coord != null && end.equals(coord); } /** * 判断结点能否放入Open列表 */ private boolean canAddNodeToOpen(MapInfo mapInfo,int x, int y) { // 是否在地图中 if (x < 0 || x >= mapInfo.width || y < 0 || y >= mapInfo.hight) return false; // 判断是否是不可通过的结点 if (mapInfo.maps[y][x] == BAR) return false; // 判断结点是否存在close表 if (isCoordInClose(x, y)) return false; return true; } /** * 判断坐标是否在close表中 */ private boolean isCoordInClose(Coord coord) { return coord!=null&&isCoordInClose(coord.x, coord.y); } /** * 判断坐标是否在close表中 */ private boolean isCoordInClose(int x, int y) { if (closeList.isEmpty()) return false; for (Node node : closeList) { if (node.coord.x == x && node.coord.y == y) { return true; } } return false; } }
0
1,382
5
1,614
5
1,610
4
1,614
5
2,018
9
false
false
false
false
false
true
10127_7
package com.mcylm.coi.realm.tools.npc; import com.mcylm.coi.realm.model.COINpc; import com.mcylm.coi.realm.tools.npc.impl.COIEntity; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import java.util.List; /** * AI的接口层,AI的基础能力 */ public interface AI { // 创建NPC COIEntity create(COINpc coiNpc); // 更新NPC COIEntity update(COINpc coiNpc, boolean respawn); // AI寻路 void findPath(Location location); // 说话 void say(String message); // 捡起地上的东西 void pickItems(); // 吃东西 void eatFood(); // 自动穿衣服 void wearClothes(); // 获取NPC附近的方块 List<Block> getNearbyBlocks(double radius); // 获取NPC附近的生物 List<Entity> getNearByEntities(double radius); // 移动 void move(); // 生成NPC void spawn(Location location); // 消除NPC void despawn(); // 彻底清除NPC void remove(); // 是否还或者 boolean isAlive(); // 是否被清除 boolean isRemoved(); // 获取NPC位置 Location getLocation(); default int delayTick() { return 20; } }
Clayun/coi-realm
src/main/java/com/mcylm/coi/realm/tools/npc/AI.java
355
// 获取NPC附近的方块
line_comment
zh-cn
package com.mcylm.coi.realm.tools.npc; import com.mcylm.coi.realm.model.COINpc; import com.mcylm.coi.realm.tools.npc.impl.COIEntity; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Entity; import java.util.List; /** * AI的接口层,AI的基础能力 */ public interface AI { // 创建NPC COIEntity create(COINpc coiNpc); // 更新NPC COIEntity update(COINpc coiNpc, boolean respawn); // AI寻路 void findPath(Location location); // 说话 void say(String message); // 捡起地上的东西 void pickItems(); // 吃东西 void eatFood(); // 自动穿衣服 void wearClothes(); // 获取 <SUF> List<Block> getNearbyBlocks(double radius); // 获取NPC附近的生物 List<Entity> getNearByEntities(double radius); // 移动 void move(); // 生成NPC void spawn(Location location); // 消除NPC void despawn(); // 彻底清除NPC void remove(); // 是否还或者 boolean isAlive(); // 是否被清除 boolean isRemoved(); // 获取NPC位置 Location getLocation(); default int delayTick() { return 20; } }
0
314
6
355
8
359
6
355
8
489
15
false
false
false
false
false
true
55734_2
package com.guhao.learn.chapter6; import java.util.*; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.*; /** * @Author guhao * @DateTime 2019-12-06 8:58 * @Description **/ public class Demo04 { private static final List<Student> list = new ArrayList<>(); static { //true未毕业,false毕业 list.add(new Student("酱",23,"male",99.0,true)); list.add(new Student("航",23,"male",99.0,true)); list.add(new Student("兔",23,"male",99.0,true)); list.add(new Student("汁",23,"male",99.0,true)); list.add(new Student("彬",23,"male",99.0,true)); list.add(new Student("马",23,"male",99.0,true)); list.add(new Student("虎",23,"male",99.0,true)); list.add(new Student("菜",23,"male",99.0,true)); list.add(new Student("峰",23,"male",99.0,true)); list.add(new Student("猫",23,"male",99.0,true)); list.add(new Student("狗",18,"male",100.0,false)); list.add(new Student("白",23,"male",99.0,true)); list.add(new Student("夜",23,"male",99.0,true)); list.add(new Student("风",23,"male",99.0,true)); } public static void main(String[] args) { //毕业,未毕业人数 Map<Boolean, Long> collect = list.stream() .collect(partitioningBy(Student::getStatus, counting())); System.out.println(collect); //毕业,未毕业 Map<Boolean, Map<String, List<Student>>> collect1 = list.stream() .collect(partitioningBy(Student::getStatus, groupingBy(Student::getName))); System.out.println(collect1); //毕业,未毕业 // list.stream().collect(partitioningBy(Student::getStatus, collectingAndThen(maxBy(Student::getAge),Optional::get))); } }
ClearScenery/Java8-Learn
src/com/guhao/learn/chapter6/Demo04.java
592
//毕业,未毕业人数
line_comment
zh-cn
package com.guhao.learn.chapter6; import java.util.*; import static java.util.Comparator.comparing; import static java.util.stream.Collectors.*; /** * @Author guhao * @DateTime 2019-12-06 8:58 * @Description **/ public class Demo04 { private static final List<Student> list = new ArrayList<>(); static { //true未毕业,false毕业 list.add(new Student("酱",23,"male",99.0,true)); list.add(new Student("航",23,"male",99.0,true)); list.add(new Student("兔",23,"male",99.0,true)); list.add(new Student("汁",23,"male",99.0,true)); list.add(new Student("彬",23,"male",99.0,true)); list.add(new Student("马",23,"male",99.0,true)); list.add(new Student("虎",23,"male",99.0,true)); list.add(new Student("菜",23,"male",99.0,true)); list.add(new Student("峰",23,"male",99.0,true)); list.add(new Student("猫",23,"male",99.0,true)); list.add(new Student("狗",18,"male",100.0,false)); list.add(new Student("白",23,"male",99.0,true)); list.add(new Student("夜",23,"male",99.0,true)); list.add(new Student("风",23,"male",99.0,true)); } public static void main(String[] args) { //毕业 <SUF> Map<Boolean, Long> collect = list.stream() .collect(partitioningBy(Student::getStatus, counting())); System.out.println(collect); //毕业,未毕业 Map<Boolean, Map<String, List<Student>>> collect1 = list.stream() .collect(partitioningBy(Student::getStatus, groupingBy(Student::getName))); System.out.println(collect1); //毕业,未毕业 // list.stream().collect(partitioningBy(Student::getStatus, collectingAndThen(maxBy(Student::getAge),Optional::get))); } }
0
494
6
592
9
595
6
592
9
660
13
false
false
false
false
false
true
58142_10
/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.hasor.rsf.domain; import java.util.ArrayList; import java.util.List; /** * RSF Request 的化身,是封装 Request 的数据对象。 * @version : 2014年10月25日 * @author 赵永春 (zyc@hasor.net) */ public class RequestInfo extends OptionInfo { private long requestID = 0; //请求ID private short flags = 0; //标签 private long receiveTime = 0; //接收请求(本地时间戳) private String serviceName = null; //远程服务名 private String serviceGroup = null; //远程服务分组 private String serviceVersion = null; //远程服务版本 private String targetMethod = null; //远程服务方法名 private String serializeType = null; //序列化策略 private int clientTimeout = 0; //远程调用时最大忍受等待时间 private boolean isMessage = false;//是否为消息请求 private List<String> paramTypes = null; //参数类型 private List<Object> paramValues = null; //参数值 // // public RequestInfo() { this.paramTypes = new ArrayList<String>(); this.paramValues = new ArrayList<Object>(); } /**获取请求ID。*/ public long getRequestID() { return this.requestID; } /**设置请求ID。*/ public void setRequestID(long requestID) { this.requestID = requestID; } /**获取flag*/ public short getFlags() { return flags; } /**设置flag。*/ public void setFlags(short flags) { this.flags = flags; } /**数据包到达时间*/ public void setReceiveTime(long receiveTime) { this.receiveTime = receiveTime; } /**数据包到达时间*/ public long getReceiveTime() { return this.receiveTime; } /**获取服务名*/ public String getServiceName() { return this.serviceName; } /**设置服务名*/ public void setServiceName(String serviceName) { this.serviceName = serviceName; } /**获取服务分组*/ public String getServiceGroup() { return this.serviceGroup; } /**设置服务分组*/ public void setServiceGroup(String serviceGroup) { this.serviceGroup = serviceGroup; } /**获取服务版本*/ public String getServiceVersion() { return this.serviceVersion; } /**设置服务版本*/ public void setServiceVersion(String serviceVersion) { this.serviceVersion = serviceVersion; } /**获取调用的方法名*/ public String getTargetMethod() { return this.targetMethod; } /**设置调用的方法名*/ public void setTargetMethod(String targetMethod) { this.targetMethod = targetMethod; } /**获取序列化类型*/ public String getSerializeType() { return this.serializeType; } /**设置序列化类型*/ public void setSerializeType(String serializeType) { this.serializeType = serializeType; } /**获取远程客户端调用超时时间。*/ public int getClientTimeout() { return this.clientTimeout; } /**设置远程客户端调用超时时间。*/ public void setClientTimeout(int clientTimeout) { this.clientTimeout = clientTimeout; } /**是否为消息请求*/ public boolean isMessage() { return isMessage; } /**设置是否为消息请求*/ public void setMessage(boolean message) { isMessage = message; } // /**添加请求参数。*/ public void addParameter(String paramType, Object paramValue) { this.paramTypes.add(paramType); this.paramValues.add(paramValue); } /**添加请求参数。*/ public void updateParameter(int index, String paramType, Object paramValue) { if (index < 0 || index > this.paramTypes.size()) { throw new IndexOutOfBoundsException("index out of range 0~" + this.paramTypes.size()); } this.paramTypes.set(index, paramType); this.paramValues.set(index, paramValue); } /**获取请求参数类型列表。*/ public List<String> getParameterTypes() { return this.paramTypes; } /**获取请求参数值列表。*/ public List<Object> getParameterValues() { return this.paramValues; } }
ClouGence/hasor
hasor-rsf/rsf-framework/src/main/java/net/hasor/rsf/domain/RequestInfo.java
1,186
//是否为消息请求
line_comment
zh-cn
/* * Copyright 2008-2009 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.hasor.rsf.domain; import java.util.ArrayList; import java.util.List; /** * RSF Request 的化身,是封装 Request 的数据对象。 * @version : 2014年10月25日 * @author 赵永春 (zyc@hasor.net) */ public class RequestInfo extends OptionInfo { private long requestID = 0; //请求ID private short flags = 0; //标签 private long receiveTime = 0; //接收请求(本地时间戳) private String serviceName = null; //远程服务名 private String serviceGroup = null; //远程服务分组 private String serviceVersion = null; //远程服务版本 private String targetMethod = null; //远程服务方法名 private String serializeType = null; //序列化策略 private int clientTimeout = 0; //远程调用时最大忍受等待时间 private boolean isMessage = false;//是否 <SUF> private List<String> paramTypes = null; //参数类型 private List<Object> paramValues = null; //参数值 // // public RequestInfo() { this.paramTypes = new ArrayList<String>(); this.paramValues = new ArrayList<Object>(); } /**获取请求ID。*/ public long getRequestID() { return this.requestID; } /**设置请求ID。*/ public void setRequestID(long requestID) { this.requestID = requestID; } /**获取flag*/ public short getFlags() { return flags; } /**设置flag。*/ public void setFlags(short flags) { this.flags = flags; } /**数据包到达时间*/ public void setReceiveTime(long receiveTime) { this.receiveTime = receiveTime; } /**数据包到达时间*/ public long getReceiveTime() { return this.receiveTime; } /**获取服务名*/ public String getServiceName() { return this.serviceName; } /**设置服务名*/ public void setServiceName(String serviceName) { this.serviceName = serviceName; } /**获取服务分组*/ public String getServiceGroup() { return this.serviceGroup; } /**设置服务分组*/ public void setServiceGroup(String serviceGroup) { this.serviceGroup = serviceGroup; } /**获取服务版本*/ public String getServiceVersion() { return this.serviceVersion; } /**设置服务版本*/ public void setServiceVersion(String serviceVersion) { this.serviceVersion = serviceVersion; } /**获取调用的方法名*/ public String getTargetMethod() { return this.targetMethod; } /**设置调用的方法名*/ public void setTargetMethod(String targetMethod) { this.targetMethod = targetMethod; } /**获取序列化类型*/ public String getSerializeType() { return this.serializeType; } /**设置序列化类型*/ public void setSerializeType(String serializeType) { this.serializeType = serializeType; } /**获取远程客户端调用超时时间。*/ public int getClientTimeout() { return this.clientTimeout; } /**设置远程客户端调用超时时间。*/ public void setClientTimeout(int clientTimeout) { this.clientTimeout = clientTimeout; } /**是否为消息请求*/ public boolean isMessage() { return isMessage; } /**设置是否为消息请求*/ public void setMessage(boolean message) { isMessage = message; } // /**添加请求参数。*/ public void addParameter(String paramType, Object paramValue) { this.paramTypes.add(paramType); this.paramValues.add(paramValue); } /**添加请求参数。*/ public void updateParameter(int index, String paramType, Object paramValue) { if (index < 0 || index > this.paramTypes.size()) { throw new IndexOutOfBoundsException("index out of range 0~" + this.paramTypes.size()); } this.paramTypes.set(index, paramType); this.paramValues.set(index, paramValue); } /**获取请求参数类型列表。*/ public List<String> getParameterTypes() { return this.paramTypes; } /**获取请求参数值列表。*/ public List<Object> getParameterValues() { return this.paramValues; } }
0
1,112
5
1,186
5
1,291
5
1,186
5
1,516
8
false
false
false
false
false
true
37126_17
/* * Copyright 2022-present the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.code13.javase.time; import java.time.DateTimeException; import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.Month; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * @author <a href="https://github.com/Code-13/">code13</a> * @date 2021/6/15 13:55 */ class ZoneAndOffsetTest { @DisplayName("ZoneId: 指定时区标识符并提供 Instant 和 LocalDateTime 之间转换的规则。") static class ZoneIdTest { @Test @DisplayName("ZoneId") void test1() { // 获取所有可用的时区 Set<String> allZones = ZoneId.getAvailableZoneIds(); // 按自然顺序排序 // Create a List using the set of zones and sort it. List<String> zoneList = new ArrayList<>(allZones); Collections.sort(zoneList); LocalDateTime dt = LocalDateTime.now(); for (String s : zoneList) { ZoneId zone = ZoneId.of(s); ZonedDateTime zonedDateTime = dt.atZone(zone); ZoneOffset offset = zonedDateTime.getOffset(); int secondsOfHour = offset.getTotalSeconds() % (60 * 60); String out = String.format("%35s %10s%n", zone, offset); if (secondsOfHour != 0) { System.out.printf(out); } } } } /** * 你什么时候使用 OffsetDateTime 而不是 ZonedDateTime? 如果您正在编写复杂的软件, * 该软件根据地理位置对自己的日期和时间计算规则进行建模,或者将时间戳存储在仅跟踪格林威治/ UTC 时间的绝对偏移量的数据库中, 则可能需要使用 OffsetDateTime。另外,XML * 和其他网络格式将日期时间传输定义为 OffsetDateTime 或 OffsetTime。 */ @DisplayName("java.time.ZonedDateTime") static class ZonedDateTimeTest { // 实际上,结合了 LocalDateTime 与类 了 zoneid 类。它用于表示具有时区(地区/城市,如欧洲/巴黎)的完整日期(年,月,日)和时间(小时,分钟,秒,纳秒)。 @Test @DisplayName("ZonedDateTime 示例") void test1() { // DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a"); DateTimeFormatter format = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"); // Leaving from San Francisco on July 20, 2013, at 7:30 p.m. // 2013-07-20 19:30:00 LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); ZoneId leavingZone = ZoneId.of("America/Los_Angeles"); ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone); try { String out1 = departure.format(format); System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone); } catch (DateTimeException exc) { System.out.printf("%s can't be formatted!%n", departure); throw exc; } // Flight is 10 hours and 50 minutes, or 650 minutes ZoneId arrivingZone = ZoneId.of("Asia/Tokyo"); // 使用美国洛杉矶出发的时间,然后换算成东京的时区,返回该时区对应的时间 ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone).plusMinutes(650); // 在该时区的基础上加650分钟 try { String out2 = arrival.format(format); System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone); } catch (DateTimeException exc) { System.out.printf("%s can't be formatted!%n", arrival); throw exc; } // 夏令时 if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) { System.out.printf(" (%s daylight saving time will be in effect.)%n", arrivingZone); } else { // 标准时间 System.out.printf(" (%s standard time will be in effect.)%n", arrivingZone); } } } /** * 结合了 LocalDateTime 与类 ZoneOffset 类。 它用于表示格林威治/ UTC 时间的偏移量 (+/-小时:分钟,例如 +06:00 * 或-)的整个日期(年,月,日)和时间(小时,分钟,秒,纳秒)08:00)。 */ @DisplayName("java.time.OffsetDateTime") static class OffsetDateTimeTest { @Test @DisplayName("OffsetDateTime") void test1() { LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); ZoneOffset offset = ZoneOffset.of("-08:00"); OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset); OffsetDateTime lastThursday = offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY)); System.out.printf( "The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth()); } } /** * 结合 LocalDateTime 与类 ZoneOffset 类。它用于表示格林威治/ UTC 时间偏移 (+/-小时:分钟,例如+06:00或-08:00)的时间(小时,分钟,秒,纳秒)。 */ @DisplayName("java.time.OffsetTime") static class OffsetTime { @Test @DisplayName("OffsetTime 示例") void test1() { // 一个不带任何时区的时间 LocalDateTime date = LocalDateTime.of(2018, 05, 01, 0, 0, 0); ZonedDateTime d1 = ZonedDateTime.of(date, ZoneId.systemDefault()); ZoneOffset offset = ZoneOffset.of("+08:00"); OffsetDateTime d2 = OffsetDateTime.of(date, offset); // 2018-05-01T00:00+08:00[GMT+08:00] // ZoneId 带了具体的ID System.out.println(d1); // 2018-05-01T00:00+08:00 // 而偏移没有ID,因为多个ID对应的值有可能是一样的 System.out.println(d2); // 那么把中国时间变成其他的时间 // 2018-04-30T20:00+04:00[Asia/Yerevan] // 把该时间转换成指定时区了 d1.withZoneSameInstant(ZoneId.of("Asia/Yerevan")); // 2018-05-01T00:00+04:00[Asia/Yerevan] // 只是改变了时区 d1.withZoneSameLocal(ZoneId.of("Asia/Yerevan")); } } }
Code-13/java-stack-labs
javase/java-time/src/main/java/io/github/code13/javase/time/ZoneAndOffsetTest.java
2,028
// 一个不带任何时区的时间
line_comment
zh-cn
/* * Copyright 2022-present the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.code13.javase.time; import java.time.DateTimeException; import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.Month; import java.time.OffsetDateTime; import java.time.ZoneId; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; /** * @author <a href="https://github.com/Code-13/">code13</a> * @date 2021/6/15 13:55 */ class ZoneAndOffsetTest { @DisplayName("ZoneId: 指定时区标识符并提供 Instant 和 LocalDateTime 之间转换的规则。") static class ZoneIdTest { @Test @DisplayName("ZoneId") void test1() { // 获取所有可用的时区 Set<String> allZones = ZoneId.getAvailableZoneIds(); // 按自然顺序排序 // Create a List using the set of zones and sort it. List<String> zoneList = new ArrayList<>(allZones); Collections.sort(zoneList); LocalDateTime dt = LocalDateTime.now(); for (String s : zoneList) { ZoneId zone = ZoneId.of(s); ZonedDateTime zonedDateTime = dt.atZone(zone); ZoneOffset offset = zonedDateTime.getOffset(); int secondsOfHour = offset.getTotalSeconds() % (60 * 60); String out = String.format("%35s %10s%n", zone, offset); if (secondsOfHour != 0) { System.out.printf(out); } } } } /** * 你什么时候使用 OffsetDateTime 而不是 ZonedDateTime? 如果您正在编写复杂的软件, * 该软件根据地理位置对自己的日期和时间计算规则进行建模,或者将时间戳存储在仅跟踪格林威治/ UTC 时间的绝对偏移量的数据库中, 则可能需要使用 OffsetDateTime。另外,XML * 和其他网络格式将日期时间传输定义为 OffsetDateTime 或 OffsetTime。 */ @DisplayName("java.time.ZonedDateTime") static class ZonedDateTimeTest { // 实际上,结合了 LocalDateTime 与类 了 zoneid 类。它用于表示具有时区(地区/城市,如欧洲/巴黎)的完整日期(年,月,日)和时间(小时,分钟,秒,纳秒)。 @Test @DisplayName("ZonedDateTime 示例") void test1() { // DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a"); DateTimeFormatter format = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss"); // Leaving from San Francisco on July 20, 2013, at 7:30 p.m. // 2013-07-20 19:30:00 LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); ZoneId leavingZone = ZoneId.of("America/Los_Angeles"); ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone); try { String out1 = departure.format(format); System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone); } catch (DateTimeException exc) { System.out.printf("%s can't be formatted!%n", departure); throw exc; } // Flight is 10 hours and 50 minutes, or 650 minutes ZoneId arrivingZone = ZoneId.of("Asia/Tokyo"); // 使用美国洛杉矶出发的时间,然后换算成东京的时区,返回该时区对应的时间 ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone).plusMinutes(650); // 在该时区的基础上加650分钟 try { String out2 = arrival.format(format); System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone); } catch (DateTimeException exc) { System.out.printf("%s can't be formatted!%n", arrival); throw exc; } // 夏令时 if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) { System.out.printf(" (%s daylight saving time will be in effect.)%n", arrivingZone); } else { // 标准时间 System.out.printf(" (%s standard time will be in effect.)%n", arrivingZone); } } } /** * 结合了 LocalDateTime 与类 ZoneOffset 类。 它用于表示格林威治/ UTC 时间的偏移量 (+/-小时:分钟,例如 +06:00 * 或-)的整个日期(年,月,日)和时间(小时,分钟,秒,纳秒)08:00)。 */ @DisplayName("java.time.OffsetDateTime") static class OffsetDateTimeTest { @Test @DisplayName("OffsetDateTime") void test1() { LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30); ZoneOffset offset = ZoneOffset.of("-08:00"); OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset); OffsetDateTime lastThursday = offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY)); System.out.printf( "The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth()); } } /** * 结合 LocalDateTime 与类 ZoneOffset 类。它用于表示格林威治/ UTC 时间偏移 (+/-小时:分钟,例如+06:00或-08:00)的时间(小时,分钟,秒,纳秒)。 */ @DisplayName("java.time.OffsetTime") static class OffsetTime { @Test @DisplayName("OffsetTime 示例") void test1() { // 一个 <SUF> LocalDateTime date = LocalDateTime.of(2018, 05, 01, 0, 0, 0); ZonedDateTime d1 = ZonedDateTime.of(date, ZoneId.systemDefault()); ZoneOffset offset = ZoneOffset.of("+08:00"); OffsetDateTime d2 = OffsetDateTime.of(date, offset); // 2018-05-01T00:00+08:00[GMT+08:00] // ZoneId 带了具体的ID System.out.println(d1); // 2018-05-01T00:00+08:00 // 而偏移没有ID,因为多个ID对应的值有可能是一样的 System.out.println(d2); // 那么把中国时间变成其他的时间 // 2018-04-30T20:00+04:00[Asia/Yerevan] // 把该时间转换成指定时区了 d1.withZoneSameInstant(ZoneId.of("Asia/Yerevan")); // 2018-05-01T00:00+04:00[Asia/Yerevan] // 只是改变了时区 d1.withZoneSameLocal(ZoneId.of("Asia/Yerevan")); } } }
0
1,821
9
2,028
9
2,029
8
2,028
9
2,531
15
false
false
false
false
false
true
19707_15
package pic; import java.awt.Font; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; public class BarChart { ChartPanel frame1; public BarChart(){ CategoryDataset dataset = getDataSet(); JFreeChart chart = ChartFactory.createBarChart3D( "水果", // 图表标题 "水果种类", // 目录轴的显示标签 "数量", // 数值轴的显示标签 dataset, // 数据集 PlotOrientation.VERTICAL, // 图表方向:水平、垂直 true, // 是否显示图例(对于简单的柱状图必须是false) false, // 是否生成工具 false // 是否生成URL链接 ); //从这里开始 CategoryPlot plot=chart.getCategoryPlot();//获取图表区域对象 CategoryAxis domainAxis=plot.getDomainAxis(); //水平底部列表 domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14)); //水平底部标题 domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12)); //垂直标题 ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状 rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15)); chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15)); chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体 //到这里结束,虽然代码有点多,但只为一个目的,解决汉字乱码问题 frame1=new ChartPanel(chart,true); //这里也可以用chartFrame,可以直接生成一个独立的Frame } private static CategoryDataset getDataSet() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100, "北京", "苹果"); dataset.addValue(100, "上海", "苹果"); dataset.addValue(100, "广州", "苹果"); dataset.addValue(200, "北京", "梨子"); dataset.addValue(200, "上海", "梨子"); dataset.addValue(200, "广州", "梨子"); dataset.addValue(300, "北京", "葡萄"); dataset.addValue(300, "上海", "葡萄"); dataset.addValue(300, "广州", "葡萄"); dataset.addValue(400, "北京", "香蕉"); dataset.addValue(400, "上海", "香蕉"); dataset.addValue(400, "广州", "香蕉"); dataset.addValue(500, "北京", "荔枝"); dataset.addValue(500, "上海", "荔枝"); dataset.addValue(500, "广州", "荔枝"); return dataset; } public ChartPanel getChartPanel(){ return frame1; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { JFrame jframe = new JFrame(); jframe.setSize(1200,600); jframe.setLocationRelativeTo(null); jframe.setDefaultCloseOperation(3); BarChart bar = new BarChart(); ChartPanel panel = bar.getChartPanel(); jframe.add(panel); jframe.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }
CodeAsPoetry/PublicOpinion
src/pic/BarChart.java
1,050
//到这里结束,虽然代码有点多,但只为一个目的,解决汉字乱码问题
line_comment
zh-cn
package pic; import java.awt.Font; import javax.swing.JFrame; import javax.swing.SwingUtilities; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; public class BarChart { ChartPanel frame1; public BarChart(){ CategoryDataset dataset = getDataSet(); JFreeChart chart = ChartFactory.createBarChart3D( "水果", // 图表标题 "水果种类", // 目录轴的显示标签 "数量", // 数值轴的显示标签 dataset, // 数据集 PlotOrientation.VERTICAL, // 图表方向:水平、垂直 true, // 是否显示图例(对于简单的柱状图必须是false) false, // 是否生成工具 false // 是否生成URL链接 ); //从这里开始 CategoryPlot plot=chart.getCategoryPlot();//获取图表区域对象 CategoryAxis domainAxis=plot.getDomainAxis(); //水平底部列表 domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14)); //水平底部标题 domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12)); //垂直标题 ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状 rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15)); chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15)); chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体 //到这 <SUF> frame1=new ChartPanel(chart,true); //这里也可以用chartFrame,可以直接生成一个独立的Frame } private static CategoryDataset getDataSet() { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(100, "北京", "苹果"); dataset.addValue(100, "上海", "苹果"); dataset.addValue(100, "广州", "苹果"); dataset.addValue(200, "北京", "梨子"); dataset.addValue(200, "上海", "梨子"); dataset.addValue(200, "广州", "梨子"); dataset.addValue(300, "北京", "葡萄"); dataset.addValue(300, "上海", "葡萄"); dataset.addValue(300, "广州", "葡萄"); dataset.addValue(400, "北京", "香蕉"); dataset.addValue(400, "上海", "香蕉"); dataset.addValue(400, "广州", "香蕉"); dataset.addValue(500, "北京", "荔枝"); dataset.addValue(500, "上海", "荔枝"); dataset.addValue(500, "广州", "荔枝"); return dataset; } public ChartPanel getChartPanel(){ return frame1; } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { try { JFrame jframe = new JFrame(); jframe.setSize(1200,600); jframe.setLocationRelativeTo(null); jframe.setDefaultCloseOperation(3); BarChart bar = new BarChart(); ChartPanel panel = bar.getChartPanel(); jframe.add(panel); jframe.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } }
0
846
19
1,050
23
958
21
1,050
23
1,340
41
false
false
false
false
false
true
53514_4
package HOther; import jdk.internal.org.xml.sax.SAXException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; public class xmlDemo { public static void main(String[] args) { //创建一个DocumentBuilderFactory的对象 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //创建一个DocumentBuilder的对象 try { //创建DocumentBuilder对象 DocumentBuilder db = dbf.newDocumentBuilder(); //通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下 Document document = db.parse("./src/HOther/book.xml"); //获取所有book节点的集合 NodeList bookList = document.getElementsByTagName("book"); //通过nodelist的getLength()方法可以获取bookList的长度 System.out.println("一共有" + bookList.getLength() + "本书"); //遍历每一个book节点 for (int i = 0; i < bookList.getLength(); i++) { System.out.println("=================下面开始遍历第" + (i + 1) + "本书的内容================="); //通过 item(i)方法 获取一个book节点,nodelist的索引值从0开始 Node book = bookList.item(i); //获取book节点的所有属性集合 NamedNodeMap attrs = book.getAttributes(); System.out.println("第 " + (i + 1) + "本书共有" + attrs.getLength() + "个属性"); //遍历book的属性 for (int j = 0; j < attrs.getLength(); j++) { //通过item(index)方法获取book节点的某一个属性 Node attr = attrs.item(j); //获取属性名 System.out.print("属性名:" + attr.getNodeName()); //获取属性值 System.out.println("--属性值" + attr.getNodeValue()); } //解析book节点的子节点 NodeList childNodes = book.getChildNodes(); //遍历childNodes获取每个节点的节点名和节点值 System.out.println("第" + (i+1) + "本书共有" + childNodes.getLength() + "个子节点"); for (int k = 0; k < childNodes.getLength(); k++) { //区分出text类型的node以及element类型的node if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) { //获取了element类型节点的节点名 System.out.print("第" + (k + 1) + "个节点的节点名:" + childNodes.item(k).getNodeName()); //获取了element类型节点的节点值 System.out.println("--节点值是:" + childNodes.item(k).getFirstChild().getNodeValue()); //System.out.println("--节点值是:" + childNodes.item(k).getTextContent()); } } System.out.println("======================结束遍历第" + (i + 1) + "本书的内容================="); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (org.xml.sax.SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
CodeCoderCoding/Java-Demo
src/HOther/xmlDemo.java
808
//获取所有book节点的集合
line_comment
zh-cn
package HOther; import jdk.internal.org.xml.sax.SAXException; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.IOException; public class xmlDemo { public static void main(String[] args) { //创建一个DocumentBuilderFactory的对象 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //创建一个DocumentBuilder的对象 try { //创建DocumentBuilder对象 DocumentBuilder db = dbf.newDocumentBuilder(); //通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下 Document document = db.parse("./src/HOther/book.xml"); //获取 <SUF> NodeList bookList = document.getElementsByTagName("book"); //通过nodelist的getLength()方法可以获取bookList的长度 System.out.println("一共有" + bookList.getLength() + "本书"); //遍历每一个book节点 for (int i = 0; i < bookList.getLength(); i++) { System.out.println("=================下面开始遍历第" + (i + 1) + "本书的内容================="); //通过 item(i)方法 获取一个book节点,nodelist的索引值从0开始 Node book = bookList.item(i); //获取book节点的所有属性集合 NamedNodeMap attrs = book.getAttributes(); System.out.println("第 " + (i + 1) + "本书共有" + attrs.getLength() + "个属性"); //遍历book的属性 for (int j = 0; j < attrs.getLength(); j++) { //通过item(index)方法获取book节点的某一个属性 Node attr = attrs.item(j); //获取属性名 System.out.print("属性名:" + attr.getNodeName()); //获取属性值 System.out.println("--属性值" + attr.getNodeValue()); } //解析book节点的子节点 NodeList childNodes = book.getChildNodes(); //遍历childNodes获取每个节点的节点名和节点值 System.out.println("第" + (i+1) + "本书共有" + childNodes.getLength() + "个子节点"); for (int k = 0; k < childNodes.getLength(); k++) { //区分出text类型的node以及element类型的node if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) { //获取了element类型节点的节点名 System.out.print("第" + (k + 1) + "个节点的节点名:" + childNodes.item(k).getNodeName()); //获取了element类型节点的节点值 System.out.println("--节点值是:" + childNodes.item(k).getFirstChild().getNodeValue()); //System.out.println("--节点值是:" + childNodes.item(k).getTextContent()); } } System.out.println("======================结束遍历第" + (i + 1) + "本书的内容================="); } } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (org.xml.sax.SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
0
721
7
808
7
848
7
808
7
1,056
11
false
false
false
false
false
true
21911_3
package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.text.DecimalFormat; /** * @author Administrator */ public class Controller { private Stage primaryStage; @FXML private Button startServer; @FXML private TextField localPath; @FXML private Button selectFilePath; @FXML private TextField port; @FXML private TextArea dataView; @FXML private ProgressBar progress; @FXML private Label proValue; @FXML private ChoiceBox bufSizeChoice; @FXML private Button endServer; @FXML private Button cleanTextArea; private String bufStr = "1024*5"; private long bufSize; SocketThread socketThread; @FXML public void cleanTextArea() { dataView.clear(); } @FXML public void startServe(ActionEvent actionEvent) throws Exception { if (!valid()) { return; } init(); socketThread = new SocketThread(); socketThread.start(); endServer.setDisable(false); startServer.setDisable(true); new Thread(new DataViewTask(dataView, "服务启动成功。。。")).start(); LogService.logInfo("服务启动成功。。。"); } @FXML public void endServe(ActionEvent actionEvent) throws Exception { if (socketThread.isAlive()) { try { socketThread.closeServer(); } catch (Exception e) { LogService.logError(e.getLocalizedMessage()); } socketThread.interrupt(); } LogService.logInfo("服务停止。。。"); new Thread(new DataViewTask(dataView, "服务停止...")).start(); endServer.setDisable(true); port.setEditable(true); selectFilePath.setDisable(false); bufSizeChoice.setDisable(false); startServer.setDisable(false); } @FXML public void selectFilePath(ActionEvent actionEvent) { DirectoryChooser directoryChooser = new DirectoryChooser(); File file = directoryChooser.showDialog(primaryStage); String path = file.getPath(); localPath.setText(path); } @FXML public void choiceBoxBuf() { bufStr = (String) bufSizeChoice.getSelectionModel().getSelectedItem(); } private void init() { switch (bufStr) { case "1024*10": bufSize = 1024 * 10; break; case "1024*100": bufSize = 1024 * 100; break; default: bufSize = 1024 * 5; } System.out.println(bufSize); port.setEditable(false); selectFilePath.setDisable(true); bufSizeChoice.setDisable(true); } private boolean valid() { String path = localPath.getText(); String portStr = port.getText(); if (portStr.length() == 0) { LogService.logError("端口为空"); Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Warning Dialog"); alert.setHeaderText("端口为空"); alert.setContentText("port is null"); alert.showAndWait(); return false; } if (path.length() == 0) { LogService.logError("保存路径为空"); Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Warning Dialog"); alert.setHeaderText("保存路径为空"); alert.setContentText("savePath is null"); alert.showAndWait(); return false; } return true; } /** * 服务端 * * @throws Exception */ class SocketThread extends Thread { ServerSocket serverSocket; boolean isClose = false; int serverPort = Integer.valueOf(port.getText()); public void closeServer() throws IOException { isClose = true; new Socket("localhost",serverPort); // serverSocket.close(); } @Override public void run() { super.run(); try { serverSocket = new ServerSocket(serverPort); } catch (Exception e) { LogService.logError("启动异常。。。" + e.getLocalizedMessage()); new Thread(new AlertTask(Alert.AlertType.ERROR, "启动异常", "start error" + e.getMessage())).start(); return; } while (!isClose) { try { Socket socket = serverSocket.accept(); if (isClose){ socket.close(); serverSocket.close(); break; } int bufferSize = 1024 * 1000; byte[] buf = new byte[bufferSize]; //传输完成的数据长度 long donelen = 0; //接入地址 new Thread(new DataViewTask(dataView, socket.getInetAddress().getHostAddress() + "---已连接")).start(); DataInputStream dis = new DataInputStream(socket.getInputStream()); String filePath = localPath.getText() + File.separator; String remoteFile = dis.readUTF(); String filePathTo = filePath + remoteFile; File file = new File(filePathTo); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } //文件长度 Long fileLen = dis.readLong(); new Thread(new DataViewTask(dataView, "开始接收文件---" + file.getName())).start(); DataOutputStream dos = new DataOutputStream(new FileOutputStream(file)); int read = 0; while (true) { if (dis != null && socket.isConnected() && !socket.isClosed()) { read = dis.read(buf); } if (read == -1) { break; } donelen += read; DecimalFormat df = new DecimalFormat("#.00"); String pro = df.format((double) donelen / fileLen); new Thread(new ProgressTask(progress, Double.valueOf(pro))).start(); dos.write(buf, 0, read); } dos.flush(); if (donelen == fileLen) { new Thread(new DataViewTask(dataView, file.getName() + "---接收完成" + System.lineSeparator())).start(); LogService.logInfo(file.getName() + "---接收完成"); } else { LogService.logError("来自" + socket.getInetAddress().getHostName() + "的" + file.getName() + "---接收不完整已删除。"); new Thread(new DataViewTask(dataView, "来自" + socket.getInetAddress().getHostName() + "的" + file.getName() + "---接收不完整已删除。")).start(); file.delete(); } dis.close(); dos.close(); } catch (Exception e) { e.printStackTrace(); LogService.logError("接收异常。。。" + e.getLocalizedMessage()); new Thread(new AlertTask(Alert.AlertType.ERROR, "接收异常", "Receive error" + e.getMessage())).start(); } } } } }
CodeIsRunning/SocketTransServer
src/sample/Controller.java
1,665
//传输完成的数据长度
line_comment
zh-cn
package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.stage.DirectoryChooser; import javafx.stage.Stage; import java.io.*; import java.net.ServerSocket; import java.net.Socket; import java.text.DecimalFormat; /** * @author Administrator */ public class Controller { private Stage primaryStage; @FXML private Button startServer; @FXML private TextField localPath; @FXML private Button selectFilePath; @FXML private TextField port; @FXML private TextArea dataView; @FXML private ProgressBar progress; @FXML private Label proValue; @FXML private ChoiceBox bufSizeChoice; @FXML private Button endServer; @FXML private Button cleanTextArea; private String bufStr = "1024*5"; private long bufSize; SocketThread socketThread; @FXML public void cleanTextArea() { dataView.clear(); } @FXML public void startServe(ActionEvent actionEvent) throws Exception { if (!valid()) { return; } init(); socketThread = new SocketThread(); socketThread.start(); endServer.setDisable(false); startServer.setDisable(true); new Thread(new DataViewTask(dataView, "服务启动成功。。。")).start(); LogService.logInfo("服务启动成功。。。"); } @FXML public void endServe(ActionEvent actionEvent) throws Exception { if (socketThread.isAlive()) { try { socketThread.closeServer(); } catch (Exception e) { LogService.logError(e.getLocalizedMessage()); } socketThread.interrupt(); } LogService.logInfo("服务停止。。。"); new Thread(new DataViewTask(dataView, "服务停止...")).start(); endServer.setDisable(true); port.setEditable(true); selectFilePath.setDisable(false); bufSizeChoice.setDisable(false); startServer.setDisable(false); } @FXML public void selectFilePath(ActionEvent actionEvent) { DirectoryChooser directoryChooser = new DirectoryChooser(); File file = directoryChooser.showDialog(primaryStage); String path = file.getPath(); localPath.setText(path); } @FXML public void choiceBoxBuf() { bufStr = (String) bufSizeChoice.getSelectionModel().getSelectedItem(); } private void init() { switch (bufStr) { case "1024*10": bufSize = 1024 * 10; break; case "1024*100": bufSize = 1024 * 100; break; default: bufSize = 1024 * 5; } System.out.println(bufSize); port.setEditable(false); selectFilePath.setDisable(true); bufSizeChoice.setDisable(true); } private boolean valid() { String path = localPath.getText(); String portStr = port.getText(); if (portStr.length() == 0) { LogService.logError("端口为空"); Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Warning Dialog"); alert.setHeaderText("端口为空"); alert.setContentText("port is null"); alert.showAndWait(); return false; } if (path.length() == 0) { LogService.logError("保存路径为空"); Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Warning Dialog"); alert.setHeaderText("保存路径为空"); alert.setContentText("savePath is null"); alert.showAndWait(); return false; } return true; } /** * 服务端 * * @throws Exception */ class SocketThread extends Thread { ServerSocket serverSocket; boolean isClose = false; int serverPort = Integer.valueOf(port.getText()); public void closeServer() throws IOException { isClose = true; new Socket("localhost",serverPort); // serverSocket.close(); } @Override public void run() { super.run(); try { serverSocket = new ServerSocket(serverPort); } catch (Exception e) { LogService.logError("启动异常。。。" + e.getLocalizedMessage()); new Thread(new AlertTask(Alert.AlertType.ERROR, "启动异常", "start error" + e.getMessage())).start(); return; } while (!isClose) { try { Socket socket = serverSocket.accept(); if (isClose){ socket.close(); serverSocket.close(); break; } int bufferSize = 1024 * 1000; byte[] buf = new byte[bufferSize]; //传输 <SUF> long donelen = 0; //接入地址 new Thread(new DataViewTask(dataView, socket.getInetAddress().getHostAddress() + "---已连接")).start(); DataInputStream dis = new DataInputStream(socket.getInputStream()); String filePath = localPath.getText() + File.separator; String remoteFile = dis.readUTF(); String filePathTo = filePath + remoteFile; File file = new File(filePathTo); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } //文件长度 Long fileLen = dis.readLong(); new Thread(new DataViewTask(dataView, "开始接收文件---" + file.getName())).start(); DataOutputStream dos = new DataOutputStream(new FileOutputStream(file)); int read = 0; while (true) { if (dis != null && socket.isConnected() && !socket.isClosed()) { read = dis.read(buf); } if (read == -1) { break; } donelen += read; DecimalFormat df = new DecimalFormat("#.00"); String pro = df.format((double) donelen / fileLen); new Thread(new ProgressTask(progress, Double.valueOf(pro))).start(); dos.write(buf, 0, read); } dos.flush(); if (donelen == fileLen) { new Thread(new DataViewTask(dataView, file.getName() + "---接收完成" + System.lineSeparator())).start(); LogService.logInfo(file.getName() + "---接收完成"); } else { LogService.logError("来自" + socket.getInetAddress().getHostName() + "的" + file.getName() + "---接收不完整已删除。"); new Thread(new DataViewTask(dataView, "来自" + socket.getInetAddress().getHostName() + "的" + file.getName() + "---接收不完整已删除。")).start(); file.delete(); } dis.close(); dos.close(); } catch (Exception e) { e.printStackTrace(); LogService.logError("接收异常。。。" + e.getLocalizedMessage()); new Thread(new AlertTask(Alert.AlertType.ERROR, "接收异常", "Receive error" + e.getMessage())).start(); } } } } }
0
1,489
5
1,665
5
1,800
5
1,665
5
2,213
10
false
false
false
false
false
true
56326_10
import java.util.ArrayList; /** * @Author: zzStar * @Date: 11-29-2020 10:50 * <p> * 树结构本身是一种天然的的组织结构,用树存储数据能更加高效地搜索。 * <p> * 二叉树:和链表一样,动态数据结构。 * 1)、对于每一个节点,最多能分成2个节点,即左孩子和右孩子。 * 2)、没有孩子的节点称为叶子节点。 * 3)、每一个孩子节点最多只能有一个父亲节点。 * 4)、二叉树具有天然的递归结构,即每个节点的左右子树都是二叉树。 * <p> * 注意:一个节点也是二叉树、空也是二叉树。 * <p> * 二叉树的分类: * 1)、满二叉树:除了叶子节点外,每个节点都有两个子节点。 * <p> * <p> * 二分搜索树: * 1)、二分搜索树是一个二叉树,且其每一颗子树也是二分搜索树。 * 2)、二分搜索树的每个节点的值大于其左子树的所有节点的值,小于其右子树的所有节点的值。 * 3)、存储的元素必须有可比较性。 * 4)、通常来说,二分搜索树不包含重复元素。如果想包含重复元素的话,只需定义: * 左子树小于等于节点;或者右子树大于等于节点。注意:数组和链表可以有重复元素。 * <p> * 什么是遍历操作? * 1)、遍历就是把所有的节点都访问一遍。 * 2)、访问的原因和业务相关。 * 3)、在线性结构下,遍历是极其容易的,但是在树结构中,遍历会稍微有点难度。 * <p> * 如何对二叉树进行遍历? * 对于遍历操作,两颗子树都要顾及。 * <p> * 前序遍历:最自然和常用的遍历方式。规律:根左右 * 中序遍历:规律:左根右 * 后序遍历:中序遍历的结果就是我们在二叉搜索树中所有数据排序后的结果。规律:左右根。应用:为二分搜索树释放内存。 * <p> * 心算出二叉搜索树的前中后序遍历:每一个二叉树都会被访问三次,从根节点出发, * 前序遍历:当一个节点被访问第一次就记录它。 * 中序遍历:当一个节点被访问第二次的时候记录它。 * 后序遍历:当一个节点被访问第三次的时候才记录它。 * <p> * 前序遍历的非递归实现(深度优先遍历):需要使用栈记录下一步被访问的元素。 * 对于二叉搜索树的非递归实现一般有两种写法: * 1)、经典教科书写法。 * 2)、完全模拟系统调用栈的写法。 * <p> * 层序遍历(广度优先遍历):需要使用队列记录当前出队元素的左右子节点。 * 广度优先遍历的意义: * 1)、在于快速地查询要搜索的元素。 * 2)、更快地找到问题的解。 * 3)、常用于算法设计中——无权图最短路径。 * 4)、联想对比图的深度优先遍历与广度优先遍历。 * <p> * 从二分搜索树中删除最小值与最大值: * 往左走的最后一个节点即是存有最小值的节点,往右走的最后一个节点即是存有最大值的节点。 * <p> * 删除二分搜索树种的任意元素: * 1)、删除只有左孩子的节点。 * 2)、删除只有右孩子的节点。 * 3)、删除具有左右孩子的节点: * 1、找到 s = min(d->right) * s 是 d 的后继(successor)节点,也即 d 的右子树中的最小节点。 * s->right = delMin(d->right) * s->left = d->left * 删除 d,s 是新的子树的根。 * 2、找到 p = max(d->left) * p 是 d 的前驱(predecessor)节点。 * <p> * 如何高效实现 rank(E 是排名第几的元素)? * 如何高效实现 select(查找排名第10的元素)? * 最好的方式是实现一个维护 size 的二分搜索树: * 给 Node 节点添加新的成员变量 size。 * 维护 depth 的二分搜索树。 * 维护 count 支持重复元素的二分搜索树。 */ public class BSTImpl<K extends Comparable<K>, V> { private class Node { public K key; public V value; public Node left, right; public Node(K key, V value) { this.key = key; this.value = value; left = null; right = null; } } private Node root; private int size; public BSTImpl() { root = null; size = 0; } public int getSize() { return size; } public boolean isEmpty() { return size == 0; } // 向二分搜索树中添加新的元素(key, value) public void add(K key, V value) { root = add(root, key, value); } // 向以node为根的二分搜索树中插入元素(key, value),递归算法 // 返回插入新节点后二分搜索树的根 private Node add(Node node, K key, V value) { if (node == null) { size++; return new Node(key, value); } if (key.compareTo(node.key) < 0) node.left = add(node.left, key, value); else if (key.compareTo(node.key) > 0) node.right = add(node.right, key, value); else // key.compareTo(node.key) == 0 node.value = value; return node; } // 返回以node为根节点的二分搜索树中,key所在的节点 private Node getNode(Node node, K key) { if (node == null) return null; if (key.equals(node.key)) return node; else if (key.compareTo(node.key) < 0) return getNode(node.left, key); else // if(key.compareTo(node.key) > 0) return getNode(node.right, key); } public boolean contains(K key) { return getNode(root, key) != null; } public V get(K key) { Node node = getNode(root, key); return node == null ? null : node.value; } public void set(K key, V newValue) { Node node = getNode(root, key); if (node == null) throw new IllegalArgumentException(key + " doesn't exist!"); node.value = newValue; } // 返回以node为根的二分搜索树的最小值所在的节点 private Node minimum(Node node) { if (node.left == null) return node; return minimum(node.left); } // 删除掉以node为根的二分搜索树中的最小节点 // 返回删除节点后新的二分搜索树的根 private Node removeMin(Node node) { if (node.left == null) { Node rightNode = node.right; node.right = null; size--; return rightNode; } node.left = removeMin(node.left); return node; } // 从二分搜索树中删除键为key的节点 public V remove(K key) { Node node = getNode(root, key); if (node != null) { root = remove(root, key); return node.value; } return null; } private Node remove(Node node, K key) { if (node == null) return null; if (key.compareTo(node.key) < 0) { node.left = remove(node.left, key); return node; } else if (key.compareTo(node.key) > 0) { node.right = remove(node.right, key); return node; } else { // key.compareTo(node.key) == 0 // 待删除节点左子树为空的情况 if (node.left == null) { Node rightNode = node.right; node.right = null; size--; return rightNode; } // 待删除节点右子树为空的情况 if (node.right == null) { Node leftNode = node.left; node.left = null; size--; return leftNode; } // 待删除节点左右子树均不为空的情况 // 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点 // 用这个节点顶替待删除节点的位置 Node successor = minimum(node.right); successor.right = removeMin(node.right); successor.left = node.left; node.left = node.right = null; return successor; } } public static void main(String[] args) { System.out.println("Pride and Prejudice"); ArrayList<String> words = new ArrayList<>(); if (FileOperation.readFile("pride-and-prejudice.txt", words)) { System.out.println("Total words: " + words.size()); BSTImpl<String, Integer> map = new BSTImpl<>(); for (String word : words) { if (map.contains(word)) map.set(word, map.get(word) + 1); else map.add(word, 1); } System.out.println("Total different words: " + map.getSize()); System.out.println("Frequency of PRIDE: " + map.get("pride")); System.out.println("Frequency of PREJUDICE: " + map.get("prejudice")); } System.out.println(); } }
CodePrometheus/Data-Structures-and-Algorithms
Tree/BSTImpl.java
2,488
// 从二分搜索树中删除键为key的节点
line_comment
zh-cn
import java.util.ArrayList; /** * @Author: zzStar * @Date: 11-29-2020 10:50 * <p> * 树结构本身是一种天然的的组织结构,用树存储数据能更加高效地搜索。 * <p> * 二叉树:和链表一样,动态数据结构。 * 1)、对于每一个节点,最多能分成2个节点,即左孩子和右孩子。 * 2)、没有孩子的节点称为叶子节点。 * 3)、每一个孩子节点最多只能有一个父亲节点。 * 4)、二叉树具有天然的递归结构,即每个节点的左右子树都是二叉树。 * <p> * 注意:一个节点也是二叉树、空也是二叉树。 * <p> * 二叉树的分类: * 1)、满二叉树:除了叶子节点外,每个节点都有两个子节点。 * <p> * <p> * 二分搜索树: * 1)、二分搜索树是一个二叉树,且其每一颗子树也是二分搜索树。 * 2)、二分搜索树的每个节点的值大于其左子树的所有节点的值,小于其右子树的所有节点的值。 * 3)、存储的元素必须有可比较性。 * 4)、通常来说,二分搜索树不包含重复元素。如果想包含重复元素的话,只需定义: * 左子树小于等于节点;或者右子树大于等于节点。注意:数组和链表可以有重复元素。 * <p> * 什么是遍历操作? * 1)、遍历就是把所有的节点都访问一遍。 * 2)、访问的原因和业务相关。 * 3)、在线性结构下,遍历是极其容易的,但是在树结构中,遍历会稍微有点难度。 * <p> * 如何对二叉树进行遍历? * 对于遍历操作,两颗子树都要顾及。 * <p> * 前序遍历:最自然和常用的遍历方式。规律:根左右 * 中序遍历:规律:左根右 * 后序遍历:中序遍历的结果就是我们在二叉搜索树中所有数据排序后的结果。规律:左右根。应用:为二分搜索树释放内存。 * <p> * 心算出二叉搜索树的前中后序遍历:每一个二叉树都会被访问三次,从根节点出发, * 前序遍历:当一个节点被访问第一次就记录它。 * 中序遍历:当一个节点被访问第二次的时候记录它。 * 后序遍历:当一个节点被访问第三次的时候才记录它。 * <p> * 前序遍历的非递归实现(深度优先遍历):需要使用栈记录下一步被访问的元素。 * 对于二叉搜索树的非递归实现一般有两种写法: * 1)、经典教科书写法。 * 2)、完全模拟系统调用栈的写法。 * <p> * 层序遍历(广度优先遍历):需要使用队列记录当前出队元素的左右子节点。 * 广度优先遍历的意义: * 1)、在于快速地查询要搜索的元素。 * 2)、更快地找到问题的解。 * 3)、常用于算法设计中——无权图最短路径。 * 4)、联想对比图的深度优先遍历与广度优先遍历。 * <p> * 从二分搜索树中删除最小值与最大值: * 往左走的最后一个节点即是存有最小值的节点,往右走的最后一个节点即是存有最大值的节点。 * <p> * 删除二分搜索树种的任意元素: * 1)、删除只有左孩子的节点。 * 2)、删除只有右孩子的节点。 * 3)、删除具有左右孩子的节点: * 1、找到 s = min(d->right) * s 是 d 的后继(successor)节点,也即 d 的右子树中的最小节点。 * s->right = delMin(d->right) * s->left = d->left * 删除 d,s 是新的子树的根。 * 2、找到 p = max(d->left) * p 是 d 的前驱(predecessor)节点。 * <p> * 如何高效实现 rank(E 是排名第几的元素)? * 如何高效实现 select(查找排名第10的元素)? * 最好的方式是实现一个维护 size 的二分搜索树: * 给 Node 节点添加新的成员变量 size。 * 维护 depth 的二分搜索树。 * 维护 count 支持重复元素的二分搜索树。 */ public class BSTImpl<K extends Comparable<K>, V> { private class Node { public K key; public V value; public Node left, right; public Node(K key, V value) { this.key = key; this.value = value; left = null; right = null; } } private Node root; private int size; public BSTImpl() { root = null; size = 0; } public int getSize() { return size; } public boolean isEmpty() { return size == 0; } // 向二分搜索树中添加新的元素(key, value) public void add(K key, V value) { root = add(root, key, value); } // 向以node为根的二分搜索树中插入元素(key, value),递归算法 // 返回插入新节点后二分搜索树的根 private Node add(Node node, K key, V value) { if (node == null) { size++; return new Node(key, value); } if (key.compareTo(node.key) < 0) node.left = add(node.left, key, value); else if (key.compareTo(node.key) > 0) node.right = add(node.right, key, value); else // key.compareTo(node.key) == 0 node.value = value; return node; } // 返回以node为根节点的二分搜索树中,key所在的节点 private Node getNode(Node node, K key) { if (node == null) return null; if (key.equals(node.key)) return node; else if (key.compareTo(node.key) < 0) return getNode(node.left, key); else // if(key.compareTo(node.key) > 0) return getNode(node.right, key); } public boolean contains(K key) { return getNode(root, key) != null; } public V get(K key) { Node node = getNode(root, key); return node == null ? null : node.value; } public void set(K key, V newValue) { Node node = getNode(root, key); if (node == null) throw new IllegalArgumentException(key + " doesn't exist!"); node.value = newValue; } // 返回以node为根的二分搜索树的最小值所在的节点 private Node minimum(Node node) { if (node.left == null) return node; return minimum(node.left); } // 删除掉以node为根的二分搜索树中的最小节点 // 返回删除节点后新的二分搜索树的根 private Node removeMin(Node node) { if (node.left == null) { Node rightNode = node.right; node.right = null; size--; return rightNode; } node.left = removeMin(node.left); return node; } // 从二 <SUF> public V remove(K key) { Node node = getNode(root, key); if (node != null) { root = remove(root, key); return node.value; } return null; } private Node remove(Node node, K key) { if (node == null) return null; if (key.compareTo(node.key) < 0) { node.left = remove(node.left, key); return node; } else if (key.compareTo(node.key) > 0) { node.right = remove(node.right, key); return node; } else { // key.compareTo(node.key) == 0 // 待删除节点左子树为空的情况 if (node.left == null) { Node rightNode = node.right; node.right = null; size--; return rightNode; } // 待删除节点右子树为空的情况 if (node.right == null) { Node leftNode = node.left; node.left = null; size--; return leftNode; } // 待删除节点左右子树均不为空的情况 // 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点 // 用这个节点顶替待删除节点的位置 Node successor = minimum(node.right); successor.right = removeMin(node.right); successor.left = node.left; node.left = node.right = null; return successor; } } public static void main(String[] args) { System.out.println("Pride and Prejudice"); ArrayList<String> words = new ArrayList<>(); if (FileOperation.readFile("pride-and-prejudice.txt", words)) { System.out.println("Total words: " + words.size()); BSTImpl<String, Integer> map = new BSTImpl<>(); for (String word : words) { if (map.contains(word)) map.set(word, map.get(word) + 1); else map.add(word, 1); } System.out.println("Total different words: " + map.getSize()); System.out.println("Frequency of PRIDE: " + map.get("pride")); System.out.println("Frequency of PREJUDICE: " + map.get("prejudice")); } System.out.println(); } }
0
2,210
14
2,488
13
2,470
13
2,488
13
3,556
23
false
false
false
false
false
true
40913_4
//https://blog.csdn.net/cslbupt/article/details/53965440 动态规划过程是:每次决策依赖于当前状态,又随即引起状态的转移。一个决策序列就是在变化的状态中产生出来的,所以,这种多阶段最优化决策解决问题的过程就称为动态规划。 https://juejin.im/post/5a29d52cf265da43333e4da7 public class Solution { public boolean isInterleave(String s1, String s2, String s3) { int length1 = s1.length(); int length2 = s2.length(); int length3 = s3.length(); if (length1 + length2 != length3){ return false;//这种小判断可以大大提高程序速度 } //声明一个二维数组dp[][];其中dp[i][j]表示s1在第个位置,s2在第j个位置,s3在遍历第i+j个位置。dp[0][0]为s1和s2都为空 boolean[][] dp = new boolean[length1 + 1][length2 + 1]; //当s1不是empty,s2为empty时。只需比较当前遍历的位置s1的字串和s3的字串是否相等 for (int i = 0; i <= length1; i++){ dp[i][0] = s1.substring(0, i).equals(s3.substring(0, i)) ? true : false; } //当s2不是empty,s1是empty时 for (int j = 0; j <= length2; j++){//一个一个比较是否完全一致 dp[0][j] = s2.substring(0, j).equals(s3.substring(0, j)) ? true : false; } //当s1和s2都不是空时。有两种情况,一种是从(i-1,j)到达(i,j)位置,如果(i-1,j)已经是交叉的了,只需比较s1的第i个位置的元素与s3的第i+j个位置的元素是否相等;另一种情况同理。 for (int i = 1; i <= length1; i++){ for (int j = 1; j <= length2; j++){ dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[i][j-1] && s2.charAt(j - 1) == s3.charAt(i + j -1)); } } return dp[s1.length()][s2.length()]; } }
CodeStudyTogether/StudyAlgorithm
LeetCode/0097.java
652
//当s1不是empty,s2为empty时。只需比较当前遍历的位置s1的字串和s3的字串是否相等
line_comment
zh-cn
//https://blog.csdn.net/cslbupt/article/details/53965440 动态规划过程是:每次决策依赖于当前状态,又随即引起状态的转移。一个决策序列就是在变化的状态中产生出来的,所以,这种多阶段最优化决策解决问题的过程就称为动态规划。 https://juejin.im/post/5a29d52cf265da43333e4da7 public class Solution { public boolean isInterleave(String s1, String s2, String s3) { int length1 = s1.length(); int length2 = s2.length(); int length3 = s3.length(); if (length1 + length2 != length3){ return false;//这种小判断可以大大提高程序速度 } //声明一个二维数组dp[][];其中dp[i][j]表示s1在第个位置,s2在第j个位置,s3在遍历第i+j个位置。dp[0][0]为s1和s2都为空 boolean[][] dp = new boolean[length1 + 1][length2 + 1]; //当s <SUF> for (int i = 0; i <= length1; i++){ dp[i][0] = s1.substring(0, i).equals(s3.substring(0, i)) ? true : false; } //当s2不是empty,s1是empty时 for (int j = 0; j <= length2; j++){//一个一个比较是否完全一致 dp[0][j] = s2.substring(0, j).equals(s3.substring(0, j)) ? true : false; } //当s1和s2都不是空时。有两种情况,一种是从(i-1,j)到达(i,j)位置,如果(i-1,j)已经是交叉的了,只需比较s1的第i个位置的元素与s3的第i+j个位置的元素是否相等;另一种情况同理。 for (int i = 1; i <= length1; i++){ for (int j = 1; j <= length2; j++){ dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[i][j-1] && s2.charAt(j - 1) == s3.charAt(i + j -1)); } } return dp[s1.length()][s2.length()]; } }
0
592
33
652
34
651
32
652
34
826
46
false
false
false
false
false
true
60349_4
package acwing.basic.chapter5; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; /** * @author : CodeWater * @create :2022-06-18-16:27 * @Function Description :285.没有上司的舞会 */ public class _285ADanceWithoutABoss { public static int N = 6010; public static int n , idx ; // 每个人的快乐指数 public static int[] happy = new int[N]; // 邻接表存储树 public static int[] h = new int[N]; public static int[] e = new int[N]; public static int[] ne = new int[N]; //状态方程,f[u][0/1]:所有从以u为根的子树中选择,并且不选/选u这个点的方案 public static int[][] f = new int[N][2]; // 因为题目没有告知根结点,所以还需要再求一下。也就是没有父结点的点 public static boolean[] has_father = new boolean[N]; public static void main( String[] args ) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in ) ); String[] str = br.readLine().split(" "); n = Integer.parseInt( str[0] ); // 读取初始的快乐指数 read直接读取的是一个字符 for( int i = 1 ; i <= n ; i++ ){ str = br.readLine().split(" "); happy[i] = Integer.parseInt( str[0] ); } //初始化头结点 Arrays.fill( h , -1 ); //读入每一条边 for( int i = 0 ; i < n - 1 ; i++ ){ //b是a的父结点 str = br.readLine().split(" "); int a = Integer.parseInt( str[0] ), b = Integer.parseInt( str[1] ); has_father[a] = true; add( b , a );//添加a到b的一条边 } // //求根结点 int root = 1; while( has_father[root] == true ) root ++; dfs(root ); System.out.println( Math.max( f[root][0] , f[root][1] ) ); } public static void add( int a , int b ){ e[idx] = b ; ne[idx] = h[a] ; h[a] = idx++; } //递归求解每个状态 public static void dfs( int u ){ //选择u结点 f[u][1] = happy[u]; for( int i = h[u] ; i != -1 ; i = ne[i] ){ //j表示u的每个儿子 int j = e[i]; dfs(j); f[u][0] += Math.max( f[j][0] , f[j][1] ); f[u][1] += f[j][0]; } } }
CodeWater404/JavaCode
Algorithm/src/acwing/basic/chapter5/_285ADanceWithoutABoss.java
733
// 因为题目没有告知根结点,所以还需要再求一下。也就是没有父结点的点
line_comment
zh-cn
package acwing.basic.chapter5; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Arrays; /** * @author : CodeWater * @create :2022-06-18-16:27 * @Function Description :285.没有上司的舞会 */ public class _285ADanceWithoutABoss { public static int N = 6010; public static int n , idx ; // 每个人的快乐指数 public static int[] happy = new int[N]; // 邻接表存储树 public static int[] h = new int[N]; public static int[] e = new int[N]; public static int[] ne = new int[N]; //状态方程,f[u][0/1]:所有从以u为根的子树中选择,并且不选/选u这个点的方案 public static int[][] f = new int[N][2]; // 因为 <SUF> public static boolean[] has_father = new boolean[N]; public static void main( String[] args ) throws IOException { BufferedReader br = new BufferedReader( new InputStreamReader(System.in ) ); String[] str = br.readLine().split(" "); n = Integer.parseInt( str[0] ); // 读取初始的快乐指数 read直接读取的是一个字符 for( int i = 1 ; i <= n ; i++ ){ str = br.readLine().split(" "); happy[i] = Integer.parseInt( str[0] ); } //初始化头结点 Arrays.fill( h , -1 ); //读入每一条边 for( int i = 0 ; i < n - 1 ; i++ ){ //b是a的父结点 str = br.readLine().split(" "); int a = Integer.parseInt( str[0] ), b = Integer.parseInt( str[1] ); has_father[a] = true; add( b , a );//添加a到b的一条边 } // //求根结点 int root = 1; while( has_father[root] == true ) root ++; dfs(root ); System.out.println( Math.max( f[root][0] , f[root][1] ) ); } public static void add( int a , int b ){ e[idx] = b ; ne[idx] = h[a] ; h[a] = idx++; } //递归求解每个状态 public static void dfs( int u ){ //选择u结点 f[u][1] = happy[u]; for( int i = h[u] ; i != -1 ; i = ne[i] ){ //j表示u的每个儿子 int j = e[i]; dfs(j); f[u][0] += Math.max( f[j][0] , f[j][1] ); f[u][1] += f[j][0]; } } }
0
679
24
733
24
771
22
733
24
892
36
false
false
false
false
false
true
39798_12
package com.ssm.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; import java.io.IOException; import java.util.Properties; /** * created by viking on 2018/07/17 * 测试邮件发送controller */ @RestController @RequestMapping("mail") public class SendMailController { @Autowired private JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean @RequestMapping("send") public Object sendMail03(){ MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象 MimeMessageHelper mMessageHelper; Properties prop = new Properties(); String from; try { //从配置文件中拿到发件人邮箱地址 prop.load(this.getClass().getResourceAsStream("/config/mail.properties")); from = prop.get("mail.smtp.username")+""; mMessageHelper=new MimeMessageHelper(mMessage,true); mMessageHelper.setFrom(from);//发件人邮箱 mMessageHelper.setTo("viking_yan@163.com");//收件人邮箱 mMessageHelper.setSubject("Spring的邮件发送");//邮件的主题 mMessageHelper.setText("<p>这是使用spring的邮件功能发送的一封邮件</p><br/>" + "<a href='https://blog.csdn.net/Mr__Viking'>打开我的博客主页</a><br/>" + "<img src='cid:fengye'>",true);//邮件的文本内容,true表示文本以html格式打开 File file=new File("F:/img/枫叶.png");//在邮件中添加一张图片 FileSystemResource resource=new FileSystemResource(file); mMessageHelper.addInline("fengye", resource);//这里指定一个id,在上面引用 mMessageHelper.addAttachment("枫叶.png", resource);//在邮件中添加一个附件 javaMailSender.send(mMessage);//发送邮件 } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "发送成功"; } public void sendMail(){ SimpleMailMessage smm=new SimpleMailMessage(); smm.setFrom("发件人的邮件地址");//发送人的邮件 smm.setTo("收件人的邮件地址");//接收的邮箱的地址 smm.setSubject("使用了properties,哈哈");//邮件的标题 smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有");//邮件的内容 javaMailSender.send(smm);//发送邮件 System.out.println("发送成功"); } public void sendMail01(){ /** * 使用另一种的方式发送邮件,然后在邮件 使html格式生效 */ MimeMessage mm=javaMailSender.createMimeMessage(); MimeMessageHelper smm=new MimeMessageHelper(mm); try { smm.setFrom("发件人的邮件地址");//发送人的邮件 smm.setTo("接收的邮箱的地址");//接收的邮箱的地址 smm.setSubject("使用了properties,哈哈,猜猜我是谁?");//邮件的标题 smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有<br><a href='http://www.baidu.com'>去百度吧!</a>",true);//邮件的内容 true 是代表的html格式生效 } catch (MessagingException e) { e.printStackTrace(); } javaMailSender.send(mm);//发送邮件 System.out.println("发送成功"); } public void sendMail02(){ /** * 使用另一种的方式发送邮件,然后在邮件,发送一个照片 */ MimeMessage mm=javaMailSender.createMimeMessage(); MimeMessageHelper smm=null; try { smm=new MimeMessageHelper(mm,true); smm.setFrom("发送人的邮件");//发送人的邮件 smm.setTo("接收的邮箱的地址");//接收的邮箱的地址 smm.setSubject("你丫的吃了狗屎了,你还不发送成功");//邮件的标题 这里多此测试 有可能会导致报错,说你发送的邮件内容不合法,注意看报错码,然后在去找报错码的意思,我这里也是报错了的,我是在他们官网上面看到的 smm.setText("山东凯撒第三款<a href='http://www.baidu.com'>去百度吧!</a><img src='cid:identifier1234'>",true);//邮件的内容 true 是代表的html格式生效 File file=new File("D:/1.jpg");//发送邮件的图片 FileSystemResource resource=new FileSystemResource(file); smm.addInline("identifier1234", resource);//这里指定一个id,在上面引用 } catch (MessagingException e) { e.printStackTrace(); } javaMailSender.send(mm);//发送邮件 System.out.println("发送成功"); } }
CoderViking/SSMDemo
src/main/java/com/ssm/controller/SendMailController.java
1,294
//发送邮件
line_comment
zh-cn
package com.ssm.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.mail.SimpleMailMessage; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.mail.MessagingException; import javax.mail.internet.MimeMessage; import java.io.File; import java.io.IOException; import java.util.Properties; /** * created by viking on 2018/07/17 * 测试邮件发送controller */ @RestController @RequestMapping("mail") public class SendMailController { @Autowired private JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean @RequestMapping("send") public Object sendMail03(){ MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象 MimeMessageHelper mMessageHelper; Properties prop = new Properties(); String from; try { //从配置文件中拿到发件人邮箱地址 prop.load(this.getClass().getResourceAsStream("/config/mail.properties")); from = prop.get("mail.smtp.username")+""; mMessageHelper=new MimeMessageHelper(mMessage,true); mMessageHelper.setFrom(from);//发件人邮箱 mMessageHelper.setTo("viking_yan@163.com");//收件人邮箱 mMessageHelper.setSubject("Spring的邮件发送");//邮件的主题 mMessageHelper.setText("<p>这是使用spring的邮件功能发送的一封邮件</p><br/>" + "<a href='https://blog.csdn.net/Mr__Viking'>打开我的博客主页</a><br/>" + "<img src='cid:fengye'>",true);//邮件的文本内容,true表示文本以html格式打开 File file=new File("F:/img/枫叶.png");//在邮件中添加一张图片 FileSystemResource resource=new FileSystemResource(file); mMessageHelper.addInline("fengye", resource);//这里指定一个id,在上面引用 mMessageHelper.addAttachment("枫叶.png", resource);//在邮件中添加一个附件 javaMailSender.send(mMessage);//发送 <SUF> } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return "发送成功"; } public void sendMail(){ SimpleMailMessage smm=new SimpleMailMessage(); smm.setFrom("发件人的邮件地址");//发送人的邮件 smm.setTo("收件人的邮件地址");//接收的邮箱的地址 smm.setSubject("使用了properties,哈哈");//邮件的标题 smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有");//邮件的内容 javaMailSender.send(smm);//发送邮件 System.out.println("发送成功"); } public void sendMail01(){ /** * 使用另一种的方式发送邮件,然后在邮件 使html格式生效 */ MimeMessage mm=javaMailSender.createMimeMessage(); MimeMessageHelper smm=new MimeMessageHelper(mm); try { smm.setFrom("发件人的邮件地址");//发送人的邮件 smm.setTo("接收的邮箱的地址");//接收的邮箱的地址 smm.setSubject("使用了properties,哈哈,猜猜我是谁?");//邮件的标题 smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有<br><a href='http://www.baidu.com'>去百度吧!</a>",true);//邮件的内容 true 是代表的html格式生效 } catch (MessagingException e) { e.printStackTrace(); } javaMailSender.send(mm);//发送邮件 System.out.println("发送成功"); } public void sendMail02(){ /** * 使用另一种的方式发送邮件,然后在邮件,发送一个照片 */ MimeMessage mm=javaMailSender.createMimeMessage(); MimeMessageHelper smm=null; try { smm=new MimeMessageHelper(mm,true); smm.setFrom("发送人的邮件");//发送人的邮件 smm.setTo("接收的邮箱的地址");//接收的邮箱的地址 smm.setSubject("你丫的吃了狗屎了,你还不发送成功");//邮件的标题 这里多此测试 有可能会导致报错,说你发送的邮件内容不合法,注意看报错码,然后在去找报错码的意思,我这里也是报错了的,我是在他们官网上面看到的 smm.setText("山东凯撒第三款<a href='http://www.baidu.com'>去百度吧!</a><img src='cid:identifier1234'>",true);//邮件的内容 true 是代表的html格式生效 File file=new File("D:/1.jpg");//发送邮件的图片 FileSystemResource resource=new FileSystemResource(file); smm.addInline("identifier1234", resource);//这里指定一个id,在上面引用 } catch (MessagingException e) { e.printStackTrace(); } javaMailSender.send(mm);//发送邮件 System.out.println("发送成功"); } }
0
1,111
3
1,294
3
1,266
3
1,294
3
1,795
7
false
false
false
false
false
true
61479_0
package src; import static src.Util.obj2int; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.function.Predicate; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.exadel.flamingo.flex.amf.AMF0Body; import flex.messaging.io.ASObject; public class Garden { public static final int[] MIN_LEVEL = new int[]{1,21,41,51,61,71,81,86,91,96,101,106,111,116,121}; public static final int[] MAX_LEVEL = new int[]{20,40,50,60,70,80,85,90,95,100,105,110,115,120,125}; private static int gradeToIndex(int grade){ if (grade>=1 && grade<=40) { return (grade-1)/20; } if (grade>=41 && grade<=80) { return (grade-1)/10-2; } if (grade>=81 && grade<=125) { return (grade-1)/5-10; } return -1; } private static List<Integer> preferGrades = null; private static String plantFilename = null; private static int remainBeatCount = 5; private static int remainToBeat = 5; public static Document lookGarden(int grade, int pvzid, String name){ Log.logln("查看lv.%d %s(%d)的花园".formatted(grade,name,pvzid)); byte[] response = Request.sendGetRequest("/pvz/index.php/garden/index/id/%d/sig/c3f56017a56ae0e93716fdffbb3ade91?%d".formatted( pvzid, new Date().getTime() )); Document document = Util.parseXml(response); return document; } private static int getRemainBeatCount(Document gardenDoc){ Element garden = (Element) gardenDoc.getElementsByTagName("garden").item(0); return Integer.parseInt(garden.getAttribute("cn")); } private static List<Garden.Monster> getMonsters(Document gardenDoc){ Element monster = (Element) gardenDoc.getElementsByTagName("monster").item(0); NodeList monList = monster.getElementsByTagName("mon"); List<Monster> res = new ArrayList<>(); for (int i = 0; i < monList.getLength(); i++) { if (monList.item(i).getNodeType()==Node.ELEMENT_NODE){ Monster monst = new Monster((Element)monList.item(i)); res.add(monst); } } return res; } static class Monster { final int ownerId; final int lx; final int ly; final String name; public Monster(Element ele){ name = ele.getAttribute("name"); ownerId = Integer.parseInt(ele.getAttribute("owid")); Element position = (Element)ele.getElementsByTagName("position").item(0); lx = Integer.parseInt(position.getAttribute("lx")); ly = Integer.parseInt(position.getAttribute("ly")); } } public static boolean beatOnce(Monster monster){ Object[] value = new Object[4]; value[0] = monster.ownerId; value[1] = monster.lx; value[2] = monster.ly; List<Integer> plants = Util.readIntegersFromFile(plantFilename); if (plantFilename==null || plants==null) { Log.logln("请先设置好花园战斗的植物!"); return false; } value[3] = Util.integerArr2int(plants.toArray()); byte[] req = Util.encodeAMF("api.garden.challenge", "/1", value); Log.log("挑战%s(%d,%d)".formatted(monster.name,monster.lx,monster.ly)); byte[] response = Request.sendPostAmf(req, true); AMF0Body body = Util.decodeAMF(response).getBody(0); if(Response.isOnStatusException(body, true)){ return false; } ASObject obj = (ASObject)body.getValue(); boolean is_winning = (Boolean)obj.get("is_winning"); if (is_winning) { int exp = obj2int(obj.get("exp")); Log.println(" 成功,获得%d经验".formatted(exp)); String awards_key = obj.get("awards_key").toString(); GeneralBattle.getAward(awards_key); remainToBeat--; }else{ Log.println(" 失败"); } return true; } public static boolean checkBeatOneGarden(int grade, int pvzid, String name){ Document gardenDoc = lookGarden(grade,pvzid, name); return beatOneGarden(gardenDoc); } public static boolean beatOneGarden(Document gardenDoc){ List<Monster> monsters = getMonsters(gardenDoc); int actualCount = Math.min(remainToBeat, monsters.size()); for (int i = 0; i < actualCount; i++) { if (!beatOnce(monsters.get(i))) { return false; } } return true; } public static boolean gardenBattleRepeat(int count){ User me = User.getUser(); List<Friend> friendList = me.friends; Document myGarden = lookGarden(me.grade,me.id, me.name); remainBeatCount = getRemainBeatCount(myGarden); if (count==-1) remainToBeat=remainBeatCount; else remainToBeat=Math.min(count, remainBeatCount); if (preferGrades==null) { Log.logln("请先设置花园打怪等级优先顺序!"); return false; } // 按照设置的等级顺序去打 for (Integer index : preferGrades) { if (remainToBeat<=0) return true; if (me.grade >= MIN_LEVEL[index] && me.grade <= MAX_LEVEL[index]) { if (!beatOneGarden(myGarden)){ return false; } } List<Friend> tofight = friendList.stream().filter(new Predicate<Friend>() { @Override public boolean test(Friend t) { return t.grade>=MIN_LEVEL[index]&& t.grade <= MAX_LEVEL[index]; } }).toList(); for (Friend friend : tofight) { if (remainToBeat<=0) return true; if (!checkBeatOneGarden(friend.grade, friend.id_pvz, friend.name)){ return false; } } } return true; } public static void main(String[] args) { if (args.length==2&&args[0].equals("battle")) { int count; if (args[1].equals("auto")) { count=-1; }else{ count=Integer.parseInt(args[1]); } gardenBattleRepeat(count); return; } else if (args.length>=1 && args[0].equals("bgrade")){ preferGrades = new ArrayList<>(); for (int i = 1; i < args.length; i++) { int tmpgrade = Integer.parseInt(args[i]); preferGrades.add(gradeToIndex(tmpgrade)); } return; } else if (args.length==2 && args[0].equals("bplant")){ plantFilename = args[1]; return; } System.out.println("args: battle auto|<count>"); System.out.println("or : bplant <plant_filename>"); System.out.println("or : bgrade <grade_to_beat>..."); } }
CodingZn/PvzScript
src/Garden.java
1,936
// 按照设置的等级顺序去打
line_comment
zh-cn
package src; import static src.Util.obj2int; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.function.Predicate; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import com.exadel.flamingo.flex.amf.AMF0Body; import flex.messaging.io.ASObject; public class Garden { public static final int[] MIN_LEVEL = new int[]{1,21,41,51,61,71,81,86,91,96,101,106,111,116,121}; public static final int[] MAX_LEVEL = new int[]{20,40,50,60,70,80,85,90,95,100,105,110,115,120,125}; private static int gradeToIndex(int grade){ if (grade>=1 && grade<=40) { return (grade-1)/20; } if (grade>=41 && grade<=80) { return (grade-1)/10-2; } if (grade>=81 && grade<=125) { return (grade-1)/5-10; } return -1; } private static List<Integer> preferGrades = null; private static String plantFilename = null; private static int remainBeatCount = 5; private static int remainToBeat = 5; public static Document lookGarden(int grade, int pvzid, String name){ Log.logln("查看lv.%d %s(%d)的花园".formatted(grade,name,pvzid)); byte[] response = Request.sendGetRequest("/pvz/index.php/garden/index/id/%d/sig/c3f56017a56ae0e93716fdffbb3ade91?%d".formatted( pvzid, new Date().getTime() )); Document document = Util.parseXml(response); return document; } private static int getRemainBeatCount(Document gardenDoc){ Element garden = (Element) gardenDoc.getElementsByTagName("garden").item(0); return Integer.parseInt(garden.getAttribute("cn")); } private static List<Garden.Monster> getMonsters(Document gardenDoc){ Element monster = (Element) gardenDoc.getElementsByTagName("monster").item(0); NodeList monList = monster.getElementsByTagName("mon"); List<Monster> res = new ArrayList<>(); for (int i = 0; i < monList.getLength(); i++) { if (monList.item(i).getNodeType()==Node.ELEMENT_NODE){ Monster monst = new Monster((Element)monList.item(i)); res.add(monst); } } return res; } static class Monster { final int ownerId; final int lx; final int ly; final String name; public Monster(Element ele){ name = ele.getAttribute("name"); ownerId = Integer.parseInt(ele.getAttribute("owid")); Element position = (Element)ele.getElementsByTagName("position").item(0); lx = Integer.parseInt(position.getAttribute("lx")); ly = Integer.parseInt(position.getAttribute("ly")); } } public static boolean beatOnce(Monster monster){ Object[] value = new Object[4]; value[0] = monster.ownerId; value[1] = monster.lx; value[2] = monster.ly; List<Integer> plants = Util.readIntegersFromFile(plantFilename); if (plantFilename==null || plants==null) { Log.logln("请先设置好花园战斗的植物!"); return false; } value[3] = Util.integerArr2int(plants.toArray()); byte[] req = Util.encodeAMF("api.garden.challenge", "/1", value); Log.log("挑战%s(%d,%d)".formatted(monster.name,monster.lx,monster.ly)); byte[] response = Request.sendPostAmf(req, true); AMF0Body body = Util.decodeAMF(response).getBody(0); if(Response.isOnStatusException(body, true)){ return false; } ASObject obj = (ASObject)body.getValue(); boolean is_winning = (Boolean)obj.get("is_winning"); if (is_winning) { int exp = obj2int(obj.get("exp")); Log.println(" 成功,获得%d经验".formatted(exp)); String awards_key = obj.get("awards_key").toString(); GeneralBattle.getAward(awards_key); remainToBeat--; }else{ Log.println(" 失败"); } return true; } public static boolean checkBeatOneGarden(int grade, int pvzid, String name){ Document gardenDoc = lookGarden(grade,pvzid, name); return beatOneGarden(gardenDoc); } public static boolean beatOneGarden(Document gardenDoc){ List<Monster> monsters = getMonsters(gardenDoc); int actualCount = Math.min(remainToBeat, monsters.size()); for (int i = 0; i < actualCount; i++) { if (!beatOnce(monsters.get(i))) { return false; } } return true; } public static boolean gardenBattleRepeat(int count){ User me = User.getUser(); List<Friend> friendList = me.friends; Document myGarden = lookGarden(me.grade,me.id, me.name); remainBeatCount = getRemainBeatCount(myGarden); if (count==-1) remainToBeat=remainBeatCount; else remainToBeat=Math.min(count, remainBeatCount); if (preferGrades==null) { Log.logln("请先设置花园打怪等级优先顺序!"); return false; } // 按照 <SUF> for (Integer index : preferGrades) { if (remainToBeat<=0) return true; if (me.grade >= MIN_LEVEL[index] && me.grade <= MAX_LEVEL[index]) { if (!beatOneGarden(myGarden)){ return false; } } List<Friend> tofight = friendList.stream().filter(new Predicate<Friend>() { @Override public boolean test(Friend t) { return t.grade>=MIN_LEVEL[index]&& t.grade <= MAX_LEVEL[index]; } }).toList(); for (Friend friend : tofight) { if (remainToBeat<=0) return true; if (!checkBeatOneGarden(friend.grade, friend.id_pvz, friend.name)){ return false; } } } return true; } public static void main(String[] args) { if (args.length==2&&args[0].equals("battle")) { int count; if (args[1].equals("auto")) { count=-1; }else{ count=Integer.parseInt(args[1]); } gardenBattleRepeat(count); return; } else if (args.length>=1 && args[0].equals("bgrade")){ preferGrades = new ArrayList<>(); for (int i = 1; i < args.length; i++) { int tmpgrade = Integer.parseInt(args[i]); preferGrades.add(gradeToIndex(tmpgrade)); } return; } else if (args.length==2 && args[0].equals("bplant")){ plantFilename = args[1]; return; } System.out.println("args: battle auto|<count>"); System.out.println("or : bplant <plant_filename>"); System.out.println("or : bgrade <grade_to_beat>..."); } }
0
1,711
11
1,936
10
2,017
9
1,936
10
2,264
19
false
false
false
false
false
true
23083_3
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author WuBiao * @date 2020/4/2 19:51 */ public class Solution { public List<String> topKFrequent(String[] words, int k) { Map<String, Integer> count = new HashMap<>(); for (String word : words) { count.put(word, count.getOrDefault(word, 0) + 1);//统计每个单词出现的次数 } List<String>[] buckets = new List[words.length + 1]; for (String word : count.keySet()) {//把词放在数组根据频率放在数组里 int num = count.get(word); if (buckets[num] == null) { buckets[num] = new ArrayList<>(); } buckets[num].add(word); } List<String> res = new ArrayList<>(); for (int i = buckets.length - 1; i >= 0; i--) { if (buckets[i] == null) { continue; } buckets[i].sort(String::compareTo);//同一个频率按照字母序排序 if (buckets[i].size() <= k - res.size()) {//能放下的话全放下 res.addAll(buckets[i]); } else {//放不下的话看能放下多少 res.addAll(buckets[i].subList(0, k - res.size())); } } return res; } }
ColdPepsi/Leetcode
692-前K个高频单词/src/main/java/Solution.java
364
//同一个频率按照字母序排序
line_comment
zh-cn
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author WuBiao * @date 2020/4/2 19:51 */ public class Solution { public List<String> topKFrequent(String[] words, int k) { Map<String, Integer> count = new HashMap<>(); for (String word : words) { count.put(word, count.getOrDefault(word, 0) + 1);//统计每个单词出现的次数 } List<String>[] buckets = new List[words.length + 1]; for (String word : count.keySet()) {//把词放在数组根据频率放在数组里 int num = count.get(word); if (buckets[num] == null) { buckets[num] = new ArrayList<>(); } buckets[num].add(word); } List<String> res = new ArrayList<>(); for (int i = buckets.length - 1; i >= 0; i--) { if (buckets[i] == null) { continue; } buckets[i].sort(String::compareTo);//同一 <SUF> if (buckets[i].size() <= k - res.size()) {//能放下的话全放下 res.addAll(buckets[i]); } else {//放不下的话看能放下多少 res.addAll(buckets[i].subList(0, k - res.size())); } } return res; } }
0
314
7
364
10
378
7
364
10
445
21
false
false
false
false
false
true
32026_11
package lee.devis.joker; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.PagerTitleStrip; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ImageButton; import java.util.ArrayList; import lee.devis.joker.MyView.PathView; import lee.devis.joker.utility.MyToaster; public class MainActivity extends FragmentActivity implements NewestFragment.OnFragmentInteractionListener, HotFragment.OnFragmentInteractionListener, PictureFragment.OnFragmentInteractionListener, lee.devis.joker.MyView.PathView.OnItemClickListener { // 页面列表 private ArrayList<android.support.v4.app.Fragment> fragmentList; // 标题列表 ArrayList<String> titleList = new ArrayList<String>(); private PagerTitleStrip pagerTitleStrip; private long myTime;// 两次返回的间隔 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); /* 通过pagerTabStrip可以设置标题的属性 */ PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagertab); // 设置下划线的颜色 // pagerTabStrip.setTabIndicatorColor(getResources().getColor(android.R.color.holo_green_dark)); pagerTabStrip.setTabIndicatorColor(Color.RED); pagerTabStrip.setPadding(18, 18, 18, 18); // 文字颜色 pagerTabStrip.setTextColor(Color.WHITE); // 设置背景的颜色 pagerTabStrip.setBackgroundColor(Color.BLACK); // pagerTitleStrip=(PagerTitleStrip) findViewById(R.id.pagertab); // //设置背景的颜色 // pagerTitleStrip.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark)); NewestFragment newestFragment = new NewestFragment(); HotFragment hotFragment = new HotFragment(); PictureFragment pictureFragment = new PictureFragment(); fragmentList = new ArrayList<android.support.v4.app.Fragment>(); fragmentList.add(newestFragment); fragmentList.add(hotFragment); fragmentList.add(pictureFragment); titleList.add("最新糗事"); titleList.add("最热段子"); titleList.add("图说真相"); FragmentManager fragmentManager = getSupportFragmentManager(); viewPager.setAdapter(new MyViewPagerAdapter(fragmentManager)); viewPager.setOffscreenPageLimit(3); setupView(); } @Override public void onFragmentInteraction(Uri uri) { } public class MyViewPagerAdapter extends FragmentStatePagerAdapter { public MyViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int arg0) { return fragmentList.get(arg0); } @Override public int getCount() { return fragmentList.size(); } @Override public CharSequence getPageTitle(int position) { return titleList.get(position); } } // 双击退出 public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if ((System.currentTimeMillis() - myTime) > 2000) {// 两次按下的时间间隔如果小于2秒就退出,大于2秒就再次提示 MyToaster.showToast(this, "再按一次返回键退出程序"); myTime = System.currentTimeMillis();// 获取当前系统时间 } else { MyToaster.showToast(this, "客观慢走,欢迎再来哟~"); finish();// 退出应用 // System.exit(0); } return true; } return super.onKeyDown(keyCode, event); } // path菜单初始化 private void setupView() { PathView mPathView = (PathView) findViewById(R.id.mPathView); ImageButton startMenu = new ImageButton(this); startMenu.setBackgroundResource(R.drawable.start_menu_btn); mPathView.setStartMenu(startMenu); int[] drawableIds = new int[] { R.drawable.menu_contact, R.drawable.menu_background, R.drawable.menu_native, R.drawable.menu_net }; View[] items = new View[drawableIds.length]; for (int i = 0; i < drawableIds.length; i++) { ImageButton button = new ImageButton(this); button.setBackgroundResource(drawableIds[i]); items[i] = button; } mPathView.setItems(items); mPathView.setOnItemClickListener(this); } @Override public void onItemClick(View view, int position) { } }
ColorfulCat/Joker
src/lee/devis/joker/MainActivity.java
1,365
// 双击退出
line_comment
zh-cn
package lee.devis.joker; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.PagerTabStrip; import android.support.v4.view.PagerTitleStrip; import android.support.v4.view.ViewPager; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.ImageButton; import java.util.ArrayList; import lee.devis.joker.MyView.PathView; import lee.devis.joker.utility.MyToaster; public class MainActivity extends FragmentActivity implements NewestFragment.OnFragmentInteractionListener, HotFragment.OnFragmentInteractionListener, PictureFragment.OnFragmentInteractionListener, lee.devis.joker.MyView.PathView.OnItemClickListener { // 页面列表 private ArrayList<android.support.v4.app.Fragment> fragmentList; // 标题列表 ArrayList<String> titleList = new ArrayList<String>(); private PagerTitleStrip pagerTitleStrip; private long myTime;// 两次返回的间隔 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager); /* 通过pagerTabStrip可以设置标题的属性 */ PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagertab); // 设置下划线的颜色 // pagerTabStrip.setTabIndicatorColor(getResources().getColor(android.R.color.holo_green_dark)); pagerTabStrip.setTabIndicatorColor(Color.RED); pagerTabStrip.setPadding(18, 18, 18, 18); // 文字颜色 pagerTabStrip.setTextColor(Color.WHITE); // 设置背景的颜色 pagerTabStrip.setBackgroundColor(Color.BLACK); // pagerTitleStrip=(PagerTitleStrip) findViewById(R.id.pagertab); // //设置背景的颜色 // pagerTitleStrip.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark)); NewestFragment newestFragment = new NewestFragment(); HotFragment hotFragment = new HotFragment(); PictureFragment pictureFragment = new PictureFragment(); fragmentList = new ArrayList<android.support.v4.app.Fragment>(); fragmentList.add(newestFragment); fragmentList.add(hotFragment); fragmentList.add(pictureFragment); titleList.add("最新糗事"); titleList.add("最热段子"); titleList.add("图说真相"); FragmentManager fragmentManager = getSupportFragmentManager(); viewPager.setAdapter(new MyViewPagerAdapter(fragmentManager)); viewPager.setOffscreenPageLimit(3); setupView(); } @Override public void onFragmentInteraction(Uri uri) { } public class MyViewPagerAdapter extends FragmentStatePagerAdapter { public MyViewPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int arg0) { return fragmentList.get(arg0); } @Override public int getCount() { return fragmentList.size(); } @Override public CharSequence getPageTitle(int position) { return titleList.get(position); } } // 双击 <SUF> public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { if ((System.currentTimeMillis() - myTime) > 2000) {// 两次按下的时间间隔如果小于2秒就退出,大于2秒就再次提示 MyToaster.showToast(this, "再按一次返回键退出程序"); myTime = System.currentTimeMillis();// 获取当前系统时间 } else { MyToaster.showToast(this, "客观慢走,欢迎再来哟~"); finish();// 退出应用 // System.exit(0); } return true; } return super.onKeyDown(keyCode, event); } // path菜单初始化 private void setupView() { PathView mPathView = (PathView) findViewById(R.id.mPathView); ImageButton startMenu = new ImageButton(this); startMenu.setBackgroundResource(R.drawable.start_menu_btn); mPathView.setStartMenu(startMenu); int[] drawableIds = new int[] { R.drawable.menu_contact, R.drawable.menu_background, R.drawable.menu_native, R.drawable.menu_net }; View[] items = new View[drawableIds.length]; for (int i = 0; i < drawableIds.length; i++) { ImageButton button = new ImageButton(this); button.setBackgroundResource(drawableIds[i]); items[i] = button; } mPathView.setItems(items); mPathView.setOnItemClickListener(this); } @Override public void onItemClick(View view, int position) { } }
0
1,058
5
1,365
5
1,309
4
1,365
5
1,672
8
false
false
false
false
false
true
49653_14
package cn.tencent.DiscuzMob.net; /** * Created by cg on 2017/4/10. */ public class AppNetConfig { public static final String BASE_ADDRESS = "https://guanjia.comsenz-service.com/"; //【注意】更改BASE_ADDRESS的时候,要搜索全局替换, 因为JS中也有。 // public static final String BASE_ADDRESS = "https://bbs.comsenz-service.com/"; //正式服务器 public String ChangeUrl=BASE_ADDRESS; public String getChangeUrl() { return ChangeUrl; } public void setChangeUrl(String changeUrl) { ChangeUrl = changeUrl; } public static final String IMGURL = BASE_ADDRESS; public static final String IMGURL1 = BASE_ADDRESS; public static final String BASEURL = BASE_ADDRESS + "api/mobile/"; public static final String LIVEBASEURL = "http://bbs.wsq.comsenz-service.com/newwsq/forum.php"; public static final String LOGOURL = IMGURL1 + "static/image/common/logo.png"; public static final String IMAGES = BASEURL + "?module=iwechat&data=json&version=5&mobiletype=Android";//轮播图 public static final String ALLFORUM = BASEURL + "?module=forumindex&version=5&debug=1&mobiletype=Android";//全部版块 public static final String HOTFORUM = BASEURL + "?module=hotforum&version=5&mobiletype=Android";//热门版块 public static final String HOTPOST = BASEURL + "?module=hotthread&version=4&mobiletype=IOS&ios=1";//热帖 public static final String QUESTION = BASEURL + "?module=secure&version=5&mobiletype=Android&type=";//获取验证码/问题 public static final String LOGIN = BASEURL + "?module=login&version=5&&loginfield=auto&mobiletype=Android";//登录 public static final String LOGIN1 = BASEURL + "?module=login&loginsubmit=yes&version=5&mapifrom=wx&charset=utf-8";//登录 public static final String USERINFO1 = BASEURL + "?module=profile&version=4&loginsubmit=yes&mobiletype=Android";//用户信息 public static final String USERINFO = BASEURL + "?module=profile&version=5&loginsubmit=yes&mobiletype=Android";//用户信息 public static final String MYFRIEND = BASEURL + "?module=friend&checkavatar=1&version=4&uid=";//我的好友 public static final String MYFAV = BASEURL + "?module=myfavforum&version=1&android=1&debug=1";//我收藏的版块 public static final String MYFAVTHREAD = BASEURL + "?module=myfavthread&version=1&android=1&debug=1";//我收藏的帖子 public static final String SYSTEM_MESSAGE = BASEURL + "?module=mypm&filter=announcepm&version=5&mobiletype=Android&page=";//系统消息 public static final String PRIVATE_LETTER = BASEURL + "?module=mypm&touid=2&page=1&version=4&mobiletype=IOS&ios=1&debug=1";//我的消息————>私信 public static final String MESSAGE_REPLIES = BASEURL + "?module=mynoticelist&mapifrom=android";//我的消息--->回复 public static final String THEME = BASEURL + "?module=mythread&version=5&mobiletype=Android&type=thread";//我的主题 // public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复 public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复 public static final String COLLECTION_BANKUAI = BASEURL + "?module=favorite&version=5&type=forum";//点击收藏板块 public static final String HISTHME = BASEURL + "?module=userthread&version=5&android=1&debug=1&mobiletype=Android";//他的回复 public static final String CONVERSATION = BASEURL + "?module=mypm&subop=view&version=5&mobiletype=Android&checkavatar=1&Android=1&smiley=no&convimg=1";//会话详情 public static final String UNCOLLECTION = BASEURL + "?module=favorite&version=5&op=delete&type=forum&mobiletype=Android&id=";//点击取消收藏 public static final String REGISTER = BASEURL + "?version=5&regsubmit=yes&module=register&";//普通注册 public static final String GETREGISTER = BASEURL + "?version=5&module=check";//普通注册 public static final String REGISTERBANGDING = BASEURL + "?version=5&module=weiqqregister"; public static final String COMMENT = BASEURL + "?module=sendreply&version=5&replysubmit=yes&mobiletype=Android&mapifrom=android";//帖子详情跟帖 public static final String SEARCH = BASEURL + "?module=search&version=5&android=1";//搜索 public static final String JURISDICTION = BASEURL + "?module=newthread&submodule=checkpost&debug=1&version=1";//检查权限 public static final String ACTIVITYTHRADF = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//活动帖 public static final String VOTETHREAD = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//投票贴 public static final String THREAD = BASEURL + "?module=newthread&version=5&android=1&debug=1&topicsubmit=yes&fid=";//普通帖 public static final String QUOTE = BASEURL + "?module=sendreply&version=3";//回复引用 public static final String PRAISETHREAD = BASEURL + "?module=recommend&version=4";//帖子点赞 public static final String COLLECTTHEAD = BASEURL + "?module=favorite&version=5&type=thread&id=";//收藏帖子http://10.0.6.58/api/mobile/version=4&android=1&debug=1&module=favthread&id=46&favoritesubmit=true public static final String UNCOLLECTTHEAD = BASEURL + "?module=favorite&version=5&op=delete&mobiletype=Android&id=";//取消收藏帖子 public static final String JOINACTIVITY = BASEURL + "?module=activityapplies&version=5&activitysubmit=true";//参加活动 public static final String DELETELETTER = BASEURL + "?module=delpm&version=5&deletesubmit=1";//删除我的私信 public static final String DELETEMESSAGE = BASEURL + "?version=5&module=delpmview&deletesubmit=1";//删除聊天记录 public static final String LIVETHREAD = BASEURL + "?module=livethread&version=5&mobiletype=Android";//直播列表 public static final String LIVETOADY = BASEURL + "?module=recommon_livethread&version=5&mobiletype=Android";//直播推荐 public static final String LIVEDETIAL = BASEURL + "?version=5&ppp=10&module=viewthread&ordertype=1&submodule=checkpost&mobiletype=Android";//直播 public static final String INTERACTION = BASEURL + "?module=threadreply&version=5&mobiletype=Android&ppp=10"; public static final String RECOMMEND = BASEURL + "?module=recommon_thread&version=5&mobiletype=Android&android=1";//推荐 public static final String ESSENCE = BASEURL + "?module=forumguide&view=digest&version=5&type=digest&mobiletype=Android&page=";//精华帖 public static final String NEW = BASEURL + "?module=forumguide&view=newthread&version=5&type=digest&mobiletype=Android&page=";//最新帖 public static final String MYTHRED = BASEURL + "?module=mynotelist&view=mypost&type=post&version=5&mobiletype=Android";//我的帖子 public static final String MYCOMMON = BASEURL + "?module=mynotelist&view=mypost&type=pcomment&version=3&mobiletype=Android";//点评 public static final String NEWS = BASEURL + "?module=notes&version=5&mobiletype=Android";//是否有新的消息 public static final String MYACTVITY = BASEURL + "?module=mynotelist&view=mypost&type=activity&version=3&mobiletype=Android";//我的活动 public static final String MYREWARD = BASEURL + "?module=mynotelist&view=mypost&type=reward&version=3&mobiletype=Android";//悬赏 public static final String GOODS = BASEURL + "?module=mynotelist&view=mypost&type=goods&version=3&mobiletype=Android";//商品 public static final String MENTIONME = BASEURL + "?module=mynotelist&view=mypost&type=at&version=3&mobiletype=Android";//提到我的 public static final String MYCALL = BASEURL + "?module=mynotelist&view=interactive&type=post&version=3&mobiletype=Android";//打招呼 public static final String myFriends = BASEURL + "?module=mynotelist&view=interactive&type=friend&version=3&mobiletype=Android";//好友 public static final String LEAVINGMESSAGE = BASEURL + "?module=mynotelist&view=interactive&type=wall&version=3&mobiletype=Android";//留言 public static final String MYCOMMENT = BASEURL + "?module=mynotelist&view=interactive&type=comment&version=3&mobiletype=Android";//评论 public static final String QUITE = BASEURL + "?module=mynotelist&view=interactive&type=click&version=3&mobiletype=Android";//挺你 public static final String SHARE = BASEURL + "?module=mynotelist&view=interactive&type=sharenotice&version=3&mobiletype=Android";//分享 public static final String SYSTEM = BASEURL + "?module=mynotelist&view=system&version=3&mobiletype=Android";//系统提醒 public static final String ADMINISTRATION = BASEURL + "?module=mynotelist&view=manage&version=3&mobiletype=Android";//管理工作 public static final String JOINMANAGER = BASEURL + "?module=forummisc&action=activityapplylist&version=5&mobiletype=Android";//报名管理 public static final String activity_management = BASEURL + "?module=forummisc&action=activityapplylist&applylistsubmit=yes&version=5&tid="; }
Comsenz/Discuz-Android
app/src/main/java/cn/tencent/DiscuzMob/net/AppNetConfig.java
2,587
//我收藏的版块
line_comment
zh-cn
package cn.tencent.DiscuzMob.net; /** * Created by cg on 2017/4/10. */ public class AppNetConfig { public static final String BASE_ADDRESS = "https://guanjia.comsenz-service.com/"; //【注意】更改BASE_ADDRESS的时候,要搜索全局替换, 因为JS中也有。 // public static final String BASE_ADDRESS = "https://bbs.comsenz-service.com/"; //正式服务器 public String ChangeUrl=BASE_ADDRESS; public String getChangeUrl() { return ChangeUrl; } public void setChangeUrl(String changeUrl) { ChangeUrl = changeUrl; } public static final String IMGURL = BASE_ADDRESS; public static final String IMGURL1 = BASE_ADDRESS; public static final String BASEURL = BASE_ADDRESS + "api/mobile/"; public static final String LIVEBASEURL = "http://bbs.wsq.comsenz-service.com/newwsq/forum.php"; public static final String LOGOURL = IMGURL1 + "static/image/common/logo.png"; public static final String IMAGES = BASEURL + "?module=iwechat&data=json&version=5&mobiletype=Android";//轮播图 public static final String ALLFORUM = BASEURL + "?module=forumindex&version=5&debug=1&mobiletype=Android";//全部版块 public static final String HOTFORUM = BASEURL + "?module=hotforum&version=5&mobiletype=Android";//热门版块 public static final String HOTPOST = BASEURL + "?module=hotthread&version=4&mobiletype=IOS&ios=1";//热帖 public static final String QUESTION = BASEURL + "?module=secure&version=5&mobiletype=Android&type=";//获取验证码/问题 public static final String LOGIN = BASEURL + "?module=login&version=5&&loginfield=auto&mobiletype=Android";//登录 public static final String LOGIN1 = BASEURL + "?module=login&loginsubmit=yes&version=5&mapifrom=wx&charset=utf-8";//登录 public static final String USERINFO1 = BASEURL + "?module=profile&version=4&loginsubmit=yes&mobiletype=Android";//用户信息 public static final String USERINFO = BASEURL + "?module=profile&version=5&loginsubmit=yes&mobiletype=Android";//用户信息 public static final String MYFRIEND = BASEURL + "?module=friend&checkavatar=1&version=4&uid=";//我的好友 public static final String MYFAV = BASEURL + "?module=myfavforum&version=1&android=1&debug=1";//我收 <SUF> public static final String MYFAVTHREAD = BASEURL + "?module=myfavthread&version=1&android=1&debug=1";//我收藏的帖子 public static final String SYSTEM_MESSAGE = BASEURL + "?module=mypm&filter=announcepm&version=5&mobiletype=Android&page=";//系统消息 public static final String PRIVATE_LETTER = BASEURL + "?module=mypm&touid=2&page=1&version=4&mobiletype=IOS&ios=1&debug=1";//我的消息————>私信 public static final String MESSAGE_REPLIES = BASEURL + "?module=mynoticelist&mapifrom=android";//我的消息--->回复 public static final String THEME = BASEURL + "?module=mythread&version=5&mobiletype=Android&type=thread";//我的主题 // public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复 public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复 public static final String COLLECTION_BANKUAI = BASEURL + "?module=favorite&version=5&type=forum";//点击收藏板块 public static final String HISTHME = BASEURL + "?module=userthread&version=5&android=1&debug=1&mobiletype=Android";//他的回复 public static final String CONVERSATION = BASEURL + "?module=mypm&subop=view&version=5&mobiletype=Android&checkavatar=1&Android=1&smiley=no&convimg=1";//会话详情 public static final String UNCOLLECTION = BASEURL + "?module=favorite&version=5&op=delete&type=forum&mobiletype=Android&id=";//点击取消收藏 public static final String REGISTER = BASEURL + "?version=5&regsubmit=yes&module=register&";//普通注册 public static final String GETREGISTER = BASEURL + "?version=5&module=check";//普通注册 public static final String REGISTERBANGDING = BASEURL + "?version=5&module=weiqqregister"; public static final String COMMENT = BASEURL + "?module=sendreply&version=5&replysubmit=yes&mobiletype=Android&mapifrom=android";//帖子详情跟帖 public static final String SEARCH = BASEURL + "?module=search&version=5&android=1";//搜索 public static final String JURISDICTION = BASEURL + "?module=newthread&submodule=checkpost&debug=1&version=1";//检查权限 public static final String ACTIVITYTHRADF = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//活动帖 public static final String VOTETHREAD = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//投票贴 public static final String THREAD = BASEURL + "?module=newthread&version=5&android=1&debug=1&topicsubmit=yes&fid=";//普通帖 public static final String QUOTE = BASEURL + "?module=sendreply&version=3";//回复引用 public static final String PRAISETHREAD = BASEURL + "?module=recommend&version=4";//帖子点赞 public static final String COLLECTTHEAD = BASEURL + "?module=favorite&version=5&type=thread&id=";//收藏帖子http://10.0.6.58/api/mobile/version=4&android=1&debug=1&module=favthread&id=46&favoritesubmit=true public static final String UNCOLLECTTHEAD = BASEURL + "?module=favorite&version=5&op=delete&mobiletype=Android&id=";//取消收藏帖子 public static final String JOINACTIVITY = BASEURL + "?module=activityapplies&version=5&activitysubmit=true";//参加活动 public static final String DELETELETTER = BASEURL + "?module=delpm&version=5&deletesubmit=1";//删除我的私信 public static final String DELETEMESSAGE = BASEURL + "?version=5&module=delpmview&deletesubmit=1";//删除聊天记录 public static final String LIVETHREAD = BASEURL + "?module=livethread&version=5&mobiletype=Android";//直播列表 public static final String LIVETOADY = BASEURL + "?module=recommon_livethread&version=5&mobiletype=Android";//直播推荐 public static final String LIVEDETIAL = BASEURL + "?version=5&ppp=10&module=viewthread&ordertype=1&submodule=checkpost&mobiletype=Android";//直播 public static final String INTERACTION = BASEURL + "?module=threadreply&version=5&mobiletype=Android&ppp=10"; public static final String RECOMMEND = BASEURL + "?module=recommon_thread&version=5&mobiletype=Android&android=1";//推荐 public static final String ESSENCE = BASEURL + "?module=forumguide&view=digest&version=5&type=digest&mobiletype=Android&page=";//精华帖 public static final String NEW = BASEURL + "?module=forumguide&view=newthread&version=5&type=digest&mobiletype=Android&page=";//最新帖 public static final String MYTHRED = BASEURL + "?module=mynotelist&view=mypost&type=post&version=5&mobiletype=Android";//我的帖子 public static final String MYCOMMON = BASEURL + "?module=mynotelist&view=mypost&type=pcomment&version=3&mobiletype=Android";//点评 public static final String NEWS = BASEURL + "?module=notes&version=5&mobiletype=Android";//是否有新的消息 public static final String MYACTVITY = BASEURL + "?module=mynotelist&view=mypost&type=activity&version=3&mobiletype=Android";//我的活动 public static final String MYREWARD = BASEURL + "?module=mynotelist&view=mypost&type=reward&version=3&mobiletype=Android";//悬赏 public static final String GOODS = BASEURL + "?module=mynotelist&view=mypost&type=goods&version=3&mobiletype=Android";//商品 public static final String MENTIONME = BASEURL + "?module=mynotelist&view=mypost&type=at&version=3&mobiletype=Android";//提到我的 public static final String MYCALL = BASEURL + "?module=mynotelist&view=interactive&type=post&version=3&mobiletype=Android";//打招呼 public static final String myFriends = BASEURL + "?module=mynotelist&view=interactive&type=friend&version=3&mobiletype=Android";//好友 public static final String LEAVINGMESSAGE = BASEURL + "?module=mynotelist&view=interactive&type=wall&version=3&mobiletype=Android";//留言 public static final String MYCOMMENT = BASEURL + "?module=mynotelist&view=interactive&type=comment&version=3&mobiletype=Android";//评论 public static final String QUITE = BASEURL + "?module=mynotelist&view=interactive&type=click&version=3&mobiletype=Android";//挺你 public static final String SHARE = BASEURL + "?module=mynotelist&view=interactive&type=sharenotice&version=3&mobiletype=Android";//分享 public static final String SYSTEM = BASEURL + "?module=mynotelist&view=system&version=3&mobiletype=Android";//系统提醒 public static final String ADMINISTRATION = BASEURL + "?module=mynotelist&view=manage&version=3&mobiletype=Android";//管理工作 public static final String JOINMANAGER = BASEURL + "?module=forummisc&action=activityapplylist&version=5&mobiletype=Android";//报名管理 public static final String activity_management = BASEURL + "?module=forummisc&action=activityapplylist&applylistsubmit=yes&version=5&tid="; }
0
2,396
7
2,584
8
2,484
7
2,584
8
3,162
10
false
false
false
false
false
true
60215_4
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class A { public static void main(String[] args) { // Readwritel ReadWriteLock lock = new ReentrantReadWriteLock(); // AbstractQueuedSynchronizer // CountDownLatch int result = new A().locate(new int[]{1,-2,3,10,9,-6,9,8}); System.out.println(result); // System.arraycopy(args, result, lock, result, result); int[] nums = new int[]{}; List<List<Integer>> list = new A().threeSum(nums); System.out.println(list); } public int findGreatestSumOfSubArray(int[] array) { int x = array[0]; int y = 0; int maxsum = x; for(int i = 1; i < array.length; i++){ //状态转移:连续子数组和最大值 y = Math.max(x + array[i], array[i]); //维护最大值 maxsum = Math.max(maxsum, y); //更新x的状态 x = y; } return maxsum; } private int locate(int[] array){ int low = array[0]; int high = low; int maxAdd = -100; for (int i = 1; i < array.length; i++) { high = Math.max(low + array[i], array[i]); maxAdd = Math.max(high, maxAdd); low = high; } return maxAdd; } public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> list = new ArrayList(); int target = 0; Arrays.sort(nums); for(int i = 0; i < nums.length - 2; i++){ int left = i+1; int right = nums.length - 1; while(left < right){ int value = nums[i] + nums[left] + nums[right]; if(value == target){ List<Integer> interList = new ArrayList<Integer>(); interList.add(nums[i]); interList.add(nums[left]); interList.add(nums[right]); // if(!checkExists(list, interList)){ list.add(interList); // } left ++; }else if(value < target){ left ++; }else { right --; } } } return list; } private boolean checkExists(List<List<Integer>> list, List<Integer> interList){ if(list.size() < 1){ return false; } for(int i = 0; i < list.size(); i++){ if(checkExists0(list.get(list.size() - 1 - i), interList)){ return true; } } return false; } private boolean checkExists0(List<Integer> listItem, List<Integer> interList){ for(int i = 0; i < listItem.size(); i++){ if(!Objects.equals(listItem.get(i), interList.get(i))){ return false; } } return true; } }
Coner1/leetcode
src/A.java
892
//状态转移:连续子数组和最大值
line_comment
zh-cn
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.CountDownLatch; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.locks.AbstractQueuedSynchronizer; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; public class A { public static void main(String[] args) { // Readwritel ReadWriteLock lock = new ReentrantReadWriteLock(); // AbstractQueuedSynchronizer // CountDownLatch int result = new A().locate(new int[]{1,-2,3,10,9,-6,9,8}); System.out.println(result); // System.arraycopy(args, result, lock, result, result); int[] nums = new int[]{}; List<List<Integer>> list = new A().threeSum(nums); System.out.println(list); } public int findGreatestSumOfSubArray(int[] array) { int x = array[0]; int y = 0; int maxsum = x; for(int i = 1; i < array.length; i++){ //状态 <SUF> y = Math.max(x + array[i], array[i]); //维护最大值 maxsum = Math.max(maxsum, y); //更新x的状态 x = y; } return maxsum; } private int locate(int[] array){ int low = array[0]; int high = low; int maxAdd = -100; for (int i = 1; i < array.length; i++) { high = Math.max(low + array[i], array[i]); maxAdd = Math.max(high, maxAdd); low = high; } return maxAdd; } public List<List<Integer>> threeSum(int[] nums) { List<List<Integer>> list = new ArrayList(); int target = 0; Arrays.sort(nums); for(int i = 0; i < nums.length - 2; i++){ int left = i+1; int right = nums.length - 1; while(left < right){ int value = nums[i] + nums[left] + nums[right]; if(value == target){ List<Integer> interList = new ArrayList<Integer>(); interList.add(nums[i]); interList.add(nums[left]); interList.add(nums[right]); // if(!checkExists(list, interList)){ list.add(interList); // } left ++; }else if(value < target){ left ++; }else { right --; } } } return list; } private boolean checkExists(List<List<Integer>> list, List<Integer> interList){ if(list.size() < 1){ return false; } for(int i = 0; i < list.size(); i++){ if(checkExists0(list.get(list.size() - 1 - i), interList)){ return true; } } return false; } private boolean checkExists0(List<Integer> listItem, List<Integer> interList){ for(int i = 0; i < listItem.size(); i++){ if(!Objects.equals(listItem.get(i), interList.get(i))){ return false; } } return true; } }
0
769
10
892
12
977
10
892
12
1,074
17
false
false
false
false
false
true
31204_27
import java.util.*; // Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`, // then press Enter. You can now see whitespace characters in your code. public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Vector<Course> clist = new Vector<Course>(); // clist.add(new Course(1, "数学分析", 0, // new Teacher("韩老师", 1, "教授"), 20)); // clist.add(new Course(2, "高等代数", 0, // new Teacher("李老师", 2, "教授"), 15)); // clist.add(new Course(3, "Java", 1, // new Teacher("吴老师", 3, "副教授"), 23)); // clist.add(new Course(4, "深度学习", 0, // new Teacher("李老师", 4, "教授"), 50)); // User user = new User(); // Courses.addCourses(); // Courses.SortCourseList(); // Courses.showCourses(); // Courses.readCourses(); menu(); // Courses.saveCourse(); // StringBuffer s1 = new StringBuffer("124"); // s1.append(266); // s1.append("223"); // System.out.println(s1); } public static void menu() { Scanner sc = new Scanner(System.in); Vector loginInfo = login(); int identity = (int)loginInfo.get(0); if (identity == -1) { return; } database.init(); // 初始化 if (identity == 0) { // 管理员菜单 MainLoop: while (true) { System.out.println("请选择操作:\n1.新建课程\n" + "2.删除课程\n3.设置课程教师\n" + "4.查找老师讲课课程 \n5.显示课程列表 \n" + "6.按照选课人数进行排序\n7.显示学生列表\n" + "8.显示教师列表\n9.添加学生\n" + "10.添加老师\n11.删除学生\n" + "12.删除老师\n13.初始化学生密码\n" + "14.初始化老师密码\n0.退出"); int choice = sc.nextInt(); switch (choice) { case 0: //退出系统 database.dbstmt.close(); // 关数据库 break MainLoop; case 1: // 添加课程 Courses.addCourses(); break; case 2: // 删除课程 Courses.deleteCourse(); break; case 3: // 设置课程教师 Courses.setCourseTeacher(); break; case 4: // 根据授课教师查找课程 Courses.SearchCourseByTeacher(); break; case 5: // 显示课程信息 Courses.showCourses(); break; case 6: // 按照选课人数排序 Courses.SortCourseList(); break; case 7: // 显示所有学生 Users.showStudents(); break; case 8: // 显示所有教师 Users.showTeachers(); break; case 9: // 添加学生 Users.addStudents(); break; case 10: // 添加老师 Users.addTeachers(); break; case 11: // 删除学生 Users.deleteStudents(); break; case 12: // 删除老师 Users.deleteTeachers(); break; case 13: // 初始化学生密码 Users.recoverStudentsPass(); break; case 14: // 初始化老师密码 Users.recoverTeachersPass(); break; default: // 非法输入 System.out.println("输入错误!!!"); } } } else if (identity == 1) { // 教师菜单 Teacher loadingTeacher = (Teacher)loginInfo.get(1); MainLoop: while (true) { System.out.println("请选择操作:\n1.修改登录密码\n" + "2.查看自己所授课程\n3.查看课程学生名单\n" + "0.退出"); int choice = sc.nextInt(); switch (choice) { case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统 case 1 -> loadingTeacher.settPassWord(); // 修改登录密码 case 2 -> loadingTeacher.teachingCourse(); // 查看所授课程 case 3 -> loadingTeacher.studentList(); // 查看所授课程学生名单 } } } else { Student loadingStudent = (Student)loginInfo.get(1); MainLoop: while (true) { // 学生菜单 System.out.println("请选择操作:\n1.修改登录密码\n" + "2.查看自己所上课程\n3.选课\n" + "0.退出"); int choice = sc.nextInt(); switch (choice) { case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统 case 1 -> loadingStudent.setstPassWord(); // 修改登录密码 case 2 -> loadingStudent.learningCourse(); // 查看自己所上课程 case 3 -> loadingStudent.choiceCourse(); // 选课 } } } } public static Vector login() { // 登录用 Vector res = new Vector(); // result Scanner sc = new Scanner(System.in); System.out.println("请输入登陆身份:\n0.管理员\n" + "1.教师\n" + "2.学生"); int identity = sc.nextInt(); switch (identity) { case 0 -> System.out.println("请输入管理员密码:"); case 1 -> System.out.println("请输入教师账号、密码:"); case 2 -> System.out.println("请输入学生账号、密码:"); } if (identity == 0) { String pass = sc.next(); if (!pass.equals(Users.admin.getPass())) { System.out.println("密码错误!系统退出!"); res.add(-1); return res; } res.add(identity); return res; } else if (identity == 1) { String name = sc.next(); String pass = sc.next(); StringBuffer queryt = new StringBuffer("Select * \n" + "From teacher where tname = "); queryt.append("'").append(name).append("'"); queryt.append(" and pass = "); queryt.append("'").append(pass).append("'"); String queryst = new String(queryt); List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst); if (selectt.size() == 0) { // 姓名或密码错误 System.out.println("用户名或密码错误!系统退出!"); res.add(-1); return res; } res.add(identity); res.add(new Teacher((String)selectt.get(0).get("tname"), (String)selectt.get(0).get("pass"), (int)selectt.get(0).get("tid"), (String)selectt.get(0).get("tlevel"))); return res; } else if (identity == 2){ String name = sc.next(); String pass = sc.next(); StringBuffer queryt = new StringBuffer("Select * \n" + "From student where sname = "); queryt.append("'").append(name).append("'"); queryt.append(" and pass = "); queryt.append("'").append(pass).append("'"); String queryst = new String(queryt); List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst); if (selectt.size() == 0) { // 姓名或密码错误 System.out.println("用户名或密码错误!系统退出!"); res.add(-1); return res; } res.add(identity); res.add(new Student((String)selectt.get(0).get("sname"), (String)selectt.get(0).get("pass"), (int)selectt.get(0).get("sid"), (String)selectt.get(0).get("sclass"))); return res; } System.out.println("输入错误!系统退出!"); res.add(-1); return res; } }
Control-derek/NEU_Doka_Java_Experiment1
src/Main.java
2,075
// 设置课程教师
line_comment
zh-cn
import java.util.*; // Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`, // then press Enter. You can now see whitespace characters in your code. public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Vector<Course> clist = new Vector<Course>(); // clist.add(new Course(1, "数学分析", 0, // new Teacher("韩老师", 1, "教授"), 20)); // clist.add(new Course(2, "高等代数", 0, // new Teacher("李老师", 2, "教授"), 15)); // clist.add(new Course(3, "Java", 1, // new Teacher("吴老师", 3, "副教授"), 23)); // clist.add(new Course(4, "深度学习", 0, // new Teacher("李老师", 4, "教授"), 50)); // User user = new User(); // Courses.addCourses(); // Courses.SortCourseList(); // Courses.showCourses(); // Courses.readCourses(); menu(); // Courses.saveCourse(); // StringBuffer s1 = new StringBuffer("124"); // s1.append(266); // s1.append("223"); // System.out.println(s1); } public static void menu() { Scanner sc = new Scanner(System.in); Vector loginInfo = login(); int identity = (int)loginInfo.get(0); if (identity == -1) { return; } database.init(); // 初始化 if (identity == 0) { // 管理员菜单 MainLoop: while (true) { System.out.println("请选择操作:\n1.新建课程\n" + "2.删除课程\n3.设置课程教师\n" + "4.查找老师讲课课程 \n5.显示课程列表 \n" + "6.按照选课人数进行排序\n7.显示学生列表\n" + "8.显示教师列表\n9.添加学生\n" + "10.添加老师\n11.删除学生\n" + "12.删除老师\n13.初始化学生密码\n" + "14.初始化老师密码\n0.退出"); int choice = sc.nextInt(); switch (choice) { case 0: //退出系统 database.dbstmt.close(); // 关数据库 break MainLoop; case 1: // 添加课程 Courses.addCourses(); break; case 2: // 删除课程 Courses.deleteCourse(); break; case 3: // 设置 <SUF> Courses.setCourseTeacher(); break; case 4: // 根据授课教师查找课程 Courses.SearchCourseByTeacher(); break; case 5: // 显示课程信息 Courses.showCourses(); break; case 6: // 按照选课人数排序 Courses.SortCourseList(); break; case 7: // 显示所有学生 Users.showStudents(); break; case 8: // 显示所有教师 Users.showTeachers(); break; case 9: // 添加学生 Users.addStudents(); break; case 10: // 添加老师 Users.addTeachers(); break; case 11: // 删除学生 Users.deleteStudents(); break; case 12: // 删除老师 Users.deleteTeachers(); break; case 13: // 初始化学生密码 Users.recoverStudentsPass(); break; case 14: // 初始化老师密码 Users.recoverTeachersPass(); break; default: // 非法输入 System.out.println("输入错误!!!"); } } } else if (identity == 1) { // 教师菜单 Teacher loadingTeacher = (Teacher)loginInfo.get(1); MainLoop: while (true) { System.out.println("请选择操作:\n1.修改登录密码\n" + "2.查看自己所授课程\n3.查看课程学生名单\n" + "0.退出"); int choice = sc.nextInt(); switch (choice) { case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统 case 1 -> loadingTeacher.settPassWord(); // 修改登录密码 case 2 -> loadingTeacher.teachingCourse(); // 查看所授课程 case 3 -> loadingTeacher.studentList(); // 查看所授课程学生名单 } } } else { Student loadingStudent = (Student)loginInfo.get(1); MainLoop: while (true) { // 学生菜单 System.out.println("请选择操作:\n1.修改登录密码\n" + "2.查看自己所上课程\n3.选课\n" + "0.退出"); int choice = sc.nextInt(); switch (choice) { case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统 case 1 -> loadingStudent.setstPassWord(); // 修改登录密码 case 2 -> loadingStudent.learningCourse(); // 查看自己所上课程 case 3 -> loadingStudent.choiceCourse(); // 选课 } } } } public static Vector login() { // 登录用 Vector res = new Vector(); // result Scanner sc = new Scanner(System.in); System.out.println("请输入登陆身份:\n0.管理员\n" + "1.教师\n" + "2.学生"); int identity = sc.nextInt(); switch (identity) { case 0 -> System.out.println("请输入管理员密码:"); case 1 -> System.out.println("请输入教师账号、密码:"); case 2 -> System.out.println("请输入学生账号、密码:"); } if (identity == 0) { String pass = sc.next(); if (!pass.equals(Users.admin.getPass())) { System.out.println("密码错误!系统退出!"); res.add(-1); return res; } res.add(identity); return res; } else if (identity == 1) { String name = sc.next(); String pass = sc.next(); StringBuffer queryt = new StringBuffer("Select * \n" + "From teacher where tname = "); queryt.append("'").append(name).append("'"); queryt.append(" and pass = "); queryt.append("'").append(pass).append("'"); String queryst = new String(queryt); List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst); if (selectt.size() == 0) { // 姓名或密码错误 System.out.println("用户名或密码错误!系统退出!"); res.add(-1); return res; } res.add(identity); res.add(new Teacher((String)selectt.get(0).get("tname"), (String)selectt.get(0).get("pass"), (int)selectt.get(0).get("tid"), (String)selectt.get(0).get("tlevel"))); return res; } else if (identity == 2){ String name = sc.next(); String pass = sc.next(); StringBuffer queryt = new StringBuffer("Select * \n" + "From student where sname = "); queryt.append("'").append(name).append("'"); queryt.append(" and pass = "); queryt.append("'").append(pass).append("'"); String queryst = new String(queryt); List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst); if (selectt.size() == 0) { // 姓名或密码错误 System.out.println("用户名或密码错误!系统退出!"); res.add(-1); return res; } res.add(identity); res.add(new Student((String)selectt.get(0).get("sname"), (String)selectt.get(0).get("pass"), (int)selectt.get(0).get("sid"), (String)selectt.get(0).get("sclass"))); return res; } System.out.println("输入错误!系统退出!"); res.add(-1); return res; } }
0
1,868
4
2,075
5
2,163
4
2,075
5
2,749
12
false
false
false
false
false
true
13778_4
package com.hotel.entity; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import java.util.List; /** * @author guangyong.yang * @date 2019-01-15 * @description 客人 */ @Getter @Setter @Entity @Table(name = "customer") public class Customer { /** * id */ @Id @Column @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 姓名 */ @Column(nullable = false,length = 80) private String name; /** * 身份证号 */ @Column(nullable = false,length = 18) private String idCard; /** * 手机号 */ @Column(length = 11) private String phoneNo; /** * 房间 */ @ManyToMany(cascade = CascadeType.REFRESH,mappedBy = "customers") private List<Room> rooms; @Column(length = 100) private String comment; }
Cool-Coding/angular-springboot-demo
hotel-server/src/main/java/com/hotel/entity/Customer.java
263
/** * 手机号 */
block_comment
zh-cn
package com.hotel.entity; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import java.util.List; /** * @author guangyong.yang * @date 2019-01-15 * @description 客人 */ @Getter @Setter @Entity @Table(name = "customer") public class Customer { /** * id */ @Id @Column @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 姓名 */ @Column(nullable = false,length = 80) private String name; /** * 身份证号 */ @Column(nullable = false,length = 18) private String idCard; /** * 手机号 <SUF>*/ @Column(length = 11) private String phoneNo; /** * 房间 */ @ManyToMany(cascade = CascadeType.REFRESH,mappedBy = "customers") private List<Room> rooms; @Column(length = 100) private String comment; }
0
238
10
263
8
279
9
263
8
330
11
false
false
false
false
false
true
34852_9
package cn.yang.domain; import java.sql.Blob; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * 用户(会员) * @author <a href="mailto:riguang_2007@163.com">ygy</a> *2011-4-7 * */ @Entity public class User { // --- 基本信息 private String loginName;// 登录名(唯一),最长为128个字符 private String password;// 密码,最长为128个字符 private String email;// Email地址,最长为128个字符 // --- 个人信息 private String nickname;// 昵称,最多128个字符,64个汉字 private Gender gender; // 性别 private byte[] avatar;// 头像 private String signature;// 签名,最多127个汉字 private Integer score=0;//积分 private String rank;//等级 // --- 其他 private Date registrationTime;// 注册时间 private Date lastVisitTime; // 最后(上次)访问时间 private String lastVisitIpAddr; // 最后(上次)访问时所使用的ip地址 private int themeCount=0;// 发表的总主题数 private int replyCount=0;// 发表的总回复数 private boolean locked;// 是否被锁定 private String autoLoginAuthKey;// 用于自动登陆的一个认证的字符串 // private String activationKey;// 锁定用户自己激活帐号所用的激活码 private Set<Role> roles = new HashSet<Role>(0);// 所拥有的角色(权限) public User(){} public User(String loginName){ this.loginName=loginName; } @Id @Column(length=128) public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } @Column(length=128) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Column(length=128) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Column(length=128) public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } @Enumerated(EnumType.STRING) @Column(length=6) public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } @Lob @Basic(fetch=FetchType.LAZY) public byte[] getAvatar() { return avatar; } public void setAvatar(byte[] avatar) { this.avatar = avatar; } @Column(length=255) public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } @Temporal(TemporalType.TIMESTAMP) public Date getRegistrationTime() { return registrationTime; } public void setRegistrationTime(Date registrationTime) { this.registrationTime = registrationTime; } @Temporal(TemporalType.TIMESTAMP) public Date getLastVisitTime() { return lastVisitTime; } public void setLastVisitTime(Date lastVisitTime) { this.lastVisitTime = lastVisitTime; } @Column(length=15) public String getLastVisitIpAddr() { return lastVisitIpAddr; } public void setLastVisitIpAddr(String lastVisitIpAddr) { this.lastVisitIpAddr = lastVisitIpAddr; } @Column(length=1) public boolean isLocked() { return locked; } public void setLocked(boolean locked) { this.locked = locked; } @Column(nullable=false) public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } @Column(length=20) public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } @Column(nullable=false) public int getThemeCount() { return themeCount; } public void setThemeCount(int themeCount) { this.themeCount = themeCount; } @Column(nullable=false) public int getReplyCount() { return replyCount; } public void setReplyCount(int replyCount) { this.replyCount = replyCount; } @Column(length=128) public String getAutoLoginAuthKey() { return autoLoginAuthKey; } public void setAutoLoginAuthKey(String autoLoginAuthKey) { this.autoLoginAuthKey = autoLoginAuthKey; } @ManyToMany(fetch=FetchType.EAGER) @JoinTable( name="user_role", joinColumns=@JoinColumn(name="user_loginName", referencedColumnName="loginName"), inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id") ) public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } @Override public String toString() { return new StringBuffer().append("[User: ")// .append(",loginName=").append(loginName)// .append(",email=").append(email)// .append(",registrationTime=").append(registrationTime)// .append(",nickname=").append(nickname)// .append(",replyCount=").append(themeCount)// .append(",replyCount=").append(replyCount)// .append("]")// .toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((loginName == null) ? 0 : loginName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (loginName == null) { if (other.loginName != null) return false; } else if (!loginName.equals(other.loginName)) return false; return true; } }
Cool-Coding/bbs
src/cn/yang/domain/User.java
1,828
// 注册时间
line_comment
zh-cn
package cn.yang.domain; import java.sql.Blob; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.Lob; import javax.persistence.ManyToMany; import javax.persistence.Temporal; import javax.persistence.TemporalType; /** * 用户(会员) * @author <a href="mailto:riguang_2007@163.com">ygy</a> *2011-4-7 * */ @Entity public class User { // --- 基本信息 private String loginName;// 登录名(唯一),最长为128个字符 private String password;// 密码,最长为128个字符 private String email;// Email地址,最长为128个字符 // --- 个人信息 private String nickname;// 昵称,最多128个字符,64个汉字 private Gender gender; // 性别 private byte[] avatar;// 头像 private String signature;// 签名,最多127个汉字 private Integer score=0;//积分 private String rank;//等级 // --- 其他 private Date registrationTime;// 注册 <SUF> private Date lastVisitTime; // 最后(上次)访问时间 private String lastVisitIpAddr; // 最后(上次)访问时所使用的ip地址 private int themeCount=0;// 发表的总主题数 private int replyCount=0;// 发表的总回复数 private boolean locked;// 是否被锁定 private String autoLoginAuthKey;// 用于自动登陆的一个认证的字符串 // private String activationKey;// 锁定用户自己激活帐号所用的激活码 private Set<Role> roles = new HashSet<Role>(0);// 所拥有的角色(权限) public User(){} public User(String loginName){ this.loginName=loginName; } @Id @Column(length=128) public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } @Column(length=128) public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Column(length=128) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Column(length=128) public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } @Enumerated(EnumType.STRING) @Column(length=6) public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } @Lob @Basic(fetch=FetchType.LAZY) public byte[] getAvatar() { return avatar; } public void setAvatar(byte[] avatar) { this.avatar = avatar; } @Column(length=255) public String getSignature() { return signature; } public void setSignature(String signature) { this.signature = signature; } @Temporal(TemporalType.TIMESTAMP) public Date getRegistrationTime() { return registrationTime; } public void setRegistrationTime(Date registrationTime) { this.registrationTime = registrationTime; } @Temporal(TemporalType.TIMESTAMP) public Date getLastVisitTime() { return lastVisitTime; } public void setLastVisitTime(Date lastVisitTime) { this.lastVisitTime = lastVisitTime; } @Column(length=15) public String getLastVisitIpAddr() { return lastVisitIpAddr; } public void setLastVisitIpAddr(String lastVisitIpAddr) { this.lastVisitIpAddr = lastVisitIpAddr; } @Column(length=1) public boolean isLocked() { return locked; } public void setLocked(boolean locked) { this.locked = locked; } @Column(nullable=false) public Integer getScore() { return score; } public void setScore(Integer score) { this.score = score; } @Column(length=20) public String getRank() { return rank; } public void setRank(String rank) { this.rank = rank; } @Column(nullable=false) public int getThemeCount() { return themeCount; } public void setThemeCount(int themeCount) { this.themeCount = themeCount; } @Column(nullable=false) public int getReplyCount() { return replyCount; } public void setReplyCount(int replyCount) { this.replyCount = replyCount; } @Column(length=128) public String getAutoLoginAuthKey() { return autoLoginAuthKey; } public void setAutoLoginAuthKey(String autoLoginAuthKey) { this.autoLoginAuthKey = autoLoginAuthKey; } @ManyToMany(fetch=FetchType.EAGER) @JoinTable( name="user_role", joinColumns=@JoinColumn(name="user_loginName", referencedColumnName="loginName"), inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id") ) public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } @Override public String toString() { return new StringBuffer().append("[User: ")// .append(",loginName=").append(loginName)// .append(",email=").append(email)// .append(",registrationTime=").append(registrationTime)// .append(",nickname=").append(nickname)// .append(",replyCount=").append(themeCount)// .append(",replyCount=").append(replyCount)// .append("]")// .toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((loginName == null) ? 0 : loginName.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (loginName == null) { if (other.loginName != null) return false; } else if (!loginName.equals(other.loginName)) return false; return true; } }
0
1,455
4
1,828
4
1,804
3
1,828
4
2,206
8
false
false
false
false
false
true
54915_4
import java.util.Arrays; public class _76_match { public boolean match (String str, String pattern) { char[] strC = str.toCharArray(); char[] patternC = pattern.toCharArray(); boolean[] dp = new boolean[patternC.length + 1]; dp[0] = true; for (int i = 1; i < patternC.length && patternC[i] == '*'; i += 2) { dp[i + 1] = true; } boolean pre = true; for (int i = 1; i <= strC.length; i++) { dp[0] = false; for (int j = 1; j <= patternC.length; j++) { boolean temp = dp[j]; if (patternC[j - 1] == '.') { dp[j] = pre; } else if (patternC[j - 1] == '*') { if (patternC[j - 2] == '.' || patternC[j - 2] == strC[i - 1]) dp[j] = dp[j] || dp[j - 2]; else { dp[j] = dp[j - 2]; } } else { if (patternC[j - 1] == strC[i - 1]) dp[j] = pre; else dp[j] = false; } pre = temp; } } return dp[patternC.length]; } public boolean match2 (String str, String pattern) { int n1 = str.length(); int n2 = pattern.length(); //dp[i][j]表示str前i个字符和pattern前j个字符是否匹配 boolean[][] dp = new boolean[n1 + 1][n2 + 1]; //遍历str每个长度 for(int i = 0; i <= n1; i++){ //遍历pattern每个长度 for(int j = 0; j <= n2; j++){ //空正则的情况 if(j == 0){ dp[i][j] = (i == 0 ? true : false); //非空的情况下 星号、点号、字符 }else{ if(pattern.charAt(j - 1) != '*'){ //当前字符不为*,用.去匹配或者字符直接相同 if(i > 0 && (str.charAt(i - 1) == pattern.charAt(j - 1) || pattern.charAt(j - 1) == '.')){ dp[i][j] = dp[i - 1][j - 1]; } }else{ //碰到* if(j >= 2){ dp[i][j] |= dp[i][j - 2]; } //若是前一位为.或者前一位可以与这个数字匹配 if(i >= 1 && j >= 2 && (str.charAt(i - 1) == pattern.charAt(j - 2) || pattern.charAt(j - 2) == '.')){ dp[i][j] |= dp[i - 1][j]; } } } } } return dp[n1][n2]; } public static void main(String[] args) { System.out.println(new _76_match().match("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*")); System.out.println(new _76_match().match2("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*")); } }
Cqupt-Psyduck/my_algorithm
hot_100/_76_match.java
847
//非空的情况下 星号、点号、字符
line_comment
zh-cn
import java.util.Arrays; public class _76_match { public boolean match (String str, String pattern) { char[] strC = str.toCharArray(); char[] patternC = pattern.toCharArray(); boolean[] dp = new boolean[patternC.length + 1]; dp[0] = true; for (int i = 1; i < patternC.length && patternC[i] == '*'; i += 2) { dp[i + 1] = true; } boolean pre = true; for (int i = 1; i <= strC.length; i++) { dp[0] = false; for (int j = 1; j <= patternC.length; j++) { boolean temp = dp[j]; if (patternC[j - 1] == '.') { dp[j] = pre; } else if (patternC[j - 1] == '*') { if (patternC[j - 2] == '.' || patternC[j - 2] == strC[i - 1]) dp[j] = dp[j] || dp[j - 2]; else { dp[j] = dp[j - 2]; } } else { if (patternC[j - 1] == strC[i - 1]) dp[j] = pre; else dp[j] = false; } pre = temp; } } return dp[patternC.length]; } public boolean match2 (String str, String pattern) { int n1 = str.length(); int n2 = pattern.length(); //dp[i][j]表示str前i个字符和pattern前j个字符是否匹配 boolean[][] dp = new boolean[n1 + 1][n2 + 1]; //遍历str每个长度 for(int i = 0; i <= n1; i++){ //遍历pattern每个长度 for(int j = 0; j <= n2; j++){ //空正则的情况 if(j == 0){ dp[i][j] = (i == 0 ? true : false); //非空 <SUF> }else{ if(pattern.charAt(j - 1) != '*'){ //当前字符不为*,用.去匹配或者字符直接相同 if(i > 0 && (str.charAt(i - 1) == pattern.charAt(j - 1) || pattern.charAt(j - 1) == '.')){ dp[i][j] = dp[i - 1][j - 1]; } }else{ //碰到* if(j >= 2){ dp[i][j] |= dp[i][j - 2]; } //若是前一位为.或者前一位可以与这个数字匹配 if(i >= 1 && j >= 2 && (str.charAt(i - 1) == pattern.charAt(j - 2) || pattern.charAt(j - 2) == '.')){ dp[i][j] |= dp[i - 1][j]; } } } } } return dp[n1][n2]; } public static void main(String[] args) { System.out.println(new _76_match().match("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*")); System.out.println(new _76_match().match2("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*")); } }
0
768
12
847
13
909
11
847
13
1,042
18
false
false
false
false
false
true
55481_9
/* * * Copyright 2017 Crab2Died * All rights reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Browse for more information : * 1) https://gitee.com/Crab2Died/Excel4J * 2) https://github.com/Crab2died/Excel4J * */ package com.github.crab2died.utils; import com.github.crab2died.annotation.ExcelField; import com.github.crab2died.converter.DefaultConvertible; import com.github.crab2died.converter.WriteConvertible; import com.github.crab2died.exceptions.Excel4JException; import com.github.crab2died.handler.ExcelHeader; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.util.*; import java.util.regex.Pattern; /** * Excel4J工具类 * author : Crab2Died * date : 2017/5/24 9:43 */ public class Utils { /** * getter或setter枚举 */ public enum FieldAccessType { GETTER, SETTER } /** * <p>根据JAVA对象注解获取Excel表头信息</p> * * @param clz 类型 * @return 表头信息 */ public static List<ExcelHeader> getHeaderList(Class<?> clz) throws Excel4JException { List<ExcelHeader> headers = new ArrayList<>(); List<Field> fields = new ArrayList<>(); for (Class<?> clazz = clz; clazz != Object.class; clazz = clazz.getSuperclass()) { fields.addAll(Arrays.asList(clazz.getDeclaredFields())); } for (Field field : fields) { // 是否使用ExcelField注解 if (field.isAnnotationPresent(ExcelField.class)) { ExcelField er = field.getAnnotation(ExcelField.class); try { headers.add(new ExcelHeader( er.title(), er.order(), er.writeConverter().newInstance(), er.readConverter().newInstance(), field.getName(), field.getType() )); } catch (InstantiationException | IllegalAccessException e) { throw new Excel4JException(e); } } } Collections.sort(headers); return headers; } /** * 获取excel列表头 * * @param titleRow excel行 * @param clz 类型 * @return ExcelHeader集合 * @throws Excel4JException 异常 */ public static Map<Integer, ExcelHeader> getHeaderMap(Row titleRow, Class<?> clz) throws Excel4JException { List<ExcelHeader> headers = getHeaderList(clz); Map<Integer, ExcelHeader> maps = new HashMap<>(); for (Cell c : titleRow) { String title = c.getStringCellValue(); for (ExcelHeader eh : headers) { if (eh.getTitle().equals(title.trim())) { maps.put(c.getColumnIndex(), eh); break; } } } return maps; } /** * 获取单元格内容 * * @param c 单元格 * @return 单元格内容 */ public static String getCellValue(Cell c) { String o; switch (c.getCellType()) { case BLANK: o = ""; break; case BOOLEAN: o = String.valueOf(c.getBooleanCellValue()); break; case FORMULA: o = calculationFormula(c); break; case NUMERIC: if (DateUtil.isCellDateFormatted(c)) { o = DateUtils.date2Str(c.getDateCellValue()); } else { o = String.valueOf(c.getNumericCellValue()); o = matchDoneBigDecimal(o); o = RegularUtils.converNumByReg(o); } break; case STRING: o = c.getStringCellValue(); break; default: o = null; break; } return o; } /** * 字符串转对象 * * @param strField 字符串 * @param clazz 待转类型 * @return 转换后数据 */ public static Object str2TargetClass(String strField, Class<?> clazz) { if (null == strField || "".equals(strField)) return null; if ((Long.class == clazz) || (long.class == clazz)) { strField = matchDoneBigDecimal(strField); strField = RegularUtils.converNumByReg(strField); return Long.parseLong(strField); } if ((Integer.class == clazz) || (int.class == clazz)) { strField = matchDoneBigDecimal(strField); strField = RegularUtils.converNumByReg(strField); return Integer.parseInt(strField); } if ((Float.class == clazz) || (float.class == clazz)) { strField = matchDoneBigDecimal(strField); return Float.parseFloat(strField); } if ((Double.class == clazz) || (double.class == clazz)) { strField = matchDoneBigDecimal(strField); return Double.parseDouble(strField); } if ((Character.class == clazz) || (char.class == clazz)) { return strField.toCharArray()[0]; } if ((Boolean.class == clazz) || (boolean.class == clazz)) { return Boolean.parseBoolean(strField); } if (Date.class == clazz) { return DateUtils.str2DateUnmatch2Null(strField); } return strField; } /** * 科学计数法数据转换 * * @param bigDecimal 科学计数法 * @return 数据字符串 */ private static String matchDoneBigDecimal(String bigDecimal) { // 对科学计数法进行处理 boolean flg = Pattern.matches("^-?\\d+(\\.\\d+)?(E-?\\d+)?$", bigDecimal); if (flg) { BigDecimal bd = new BigDecimal(bigDecimal); bigDecimal = bd.toPlainString(); } return bigDecimal; } /** * <p>根据java对象属性{@link Field}获取该属性的getter或setter方法名, * 另对{@link boolean}及{@link Boolean}做了行管处理</p> * * @param clazz 操作对象 * @param fieldName 对象属性 * @param methodType 方法类型,getter或setter枚举 * @return getter或setter方法 * @throws IntrospectionException 异常 * @author Crab2Died */ public static Method getterOrSetter(Class clazz, String fieldName, FieldAccessType methodType) throws IntrospectionException { if (null == fieldName || "".equals(fieldName)) return null; BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor prop : props) { if (fieldName.equals(prop.getName())) { if (FieldAccessType.SETTER == methodType) { return prop.getWriteMethod(); } if (FieldAccessType.GETTER == methodType) { return prop.getReadMethod(); } } } throw new IntrospectionException("Can not get the getter or setter method"); } /** * <p>根据对象的属性名{@code fieldName}获取某个java的属性{@link java.lang.reflect.Field}</p> * * @param clazz java对象的class属性 * @param fieldName 属性名 * @return {@link java.lang.reflect.Field} java对象的属性 * @author Crab2Died */ private static Field matchClassField(Class clazz, String fieldName) { List<Field> fields = new ArrayList<>(); for (; clazz != Object.class; clazz = clazz.getSuperclass()) { fields.addAll(Arrays.asList(clazz.getDeclaredFields())); } for (Field field : fields) { if (fieldName.equals(field.getName())) { return field; } } throw new IllegalArgumentException("[" + clazz.getName() + "] can`t found field with [" + fieldName + "]"); } /** * 根据属性名与属性类型获取字段内容 * * @param bean 对象 * @param fieldName 字段名 * @param writeConvertible 写入转换器 * @return 对象指定字段内容 * @throws Excel4JException 异常 */ public static String getProperty(Object bean, String fieldName, WriteConvertible writeConvertible) throws Excel4JException { if (bean == null || fieldName == null) throw new IllegalArgumentException("Operating bean or filed class must not be null"); Method method; Object object; try { method = getterOrSetter(bean.getClass(), fieldName, FieldAccessType.GETTER); object = method.invoke(bean); } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { throw new Excel4JException(e); } if (null != writeConvertible && writeConvertible.getClass() != DefaultConvertible.class) { // 写入转换器 object = writeConvertible.execWrite(object); } return object == null ? "" : object.toString(); } /** * 根据属性名与属性类型获取字段内容 * * @param bean 对象 * @param name 字段名 * @param value 字段类型 */ public static void copyProperty(Object bean, String name, Object value) throws Excel4JException { if (null == name || null == value) return; Field field = matchClassField(bean.getClass(), name); if (null == field) return; Method method; try { method = getterOrSetter(bean.getClass(), name, FieldAccessType.SETTER); if (value.getClass() == field.getType()) { method.invoke(bean, value); } else { method.invoke(bean, str2TargetClass(value.toString(), field.getType())); } } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { throw new Excel4JException(e); } } /** * 计算公式结果 * * @param cell 单元格类型为公式的单元格 * @return 返回单元格计算后的值 格式化成String * @author QingMings * Email:1821063757@qq.com * date 2018-01-13 */ public static String calculationFormula(Cell cell) { CellValue cellValue = cell.getSheet().getWorkbook().getCreationHelper() .createFormulaEvaluator().evaluate(cell); return cellValue.formatAsString(); } }
Crab2died/Excel4J
src/main/java/com/github/crab2died/utils/Utils.java
2,754
// 对科学计数法进行处理
line_comment
zh-cn
/* * * Copyright 2017 Crab2Died * All rights reserved. * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Browse for more information : * 1) https://gitee.com/Crab2Died/Excel4J * 2) https://github.com/Crab2died/Excel4J * */ package com.github.crab2died.utils; import com.github.crab2died.annotation.ExcelField; import com.github.crab2died.converter.DefaultConvertible; import com.github.crab2died.converter.WriteConvertible; import com.github.crab2died.exceptions.Excel4JException; import com.github.crab2died.handler.ExcelHeader; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellValue; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.math.BigDecimal; import java.util.*; import java.util.regex.Pattern; /** * Excel4J工具类 * author : Crab2Died * date : 2017/5/24 9:43 */ public class Utils { /** * getter或setter枚举 */ public enum FieldAccessType { GETTER, SETTER } /** * <p>根据JAVA对象注解获取Excel表头信息</p> * * @param clz 类型 * @return 表头信息 */ public static List<ExcelHeader> getHeaderList(Class<?> clz) throws Excel4JException { List<ExcelHeader> headers = new ArrayList<>(); List<Field> fields = new ArrayList<>(); for (Class<?> clazz = clz; clazz != Object.class; clazz = clazz.getSuperclass()) { fields.addAll(Arrays.asList(clazz.getDeclaredFields())); } for (Field field : fields) { // 是否使用ExcelField注解 if (field.isAnnotationPresent(ExcelField.class)) { ExcelField er = field.getAnnotation(ExcelField.class); try { headers.add(new ExcelHeader( er.title(), er.order(), er.writeConverter().newInstance(), er.readConverter().newInstance(), field.getName(), field.getType() )); } catch (InstantiationException | IllegalAccessException e) { throw new Excel4JException(e); } } } Collections.sort(headers); return headers; } /** * 获取excel列表头 * * @param titleRow excel行 * @param clz 类型 * @return ExcelHeader集合 * @throws Excel4JException 异常 */ public static Map<Integer, ExcelHeader> getHeaderMap(Row titleRow, Class<?> clz) throws Excel4JException { List<ExcelHeader> headers = getHeaderList(clz); Map<Integer, ExcelHeader> maps = new HashMap<>(); for (Cell c : titleRow) { String title = c.getStringCellValue(); for (ExcelHeader eh : headers) { if (eh.getTitle().equals(title.trim())) { maps.put(c.getColumnIndex(), eh); break; } } } return maps; } /** * 获取单元格内容 * * @param c 单元格 * @return 单元格内容 */ public static String getCellValue(Cell c) { String o; switch (c.getCellType()) { case BLANK: o = ""; break; case BOOLEAN: o = String.valueOf(c.getBooleanCellValue()); break; case FORMULA: o = calculationFormula(c); break; case NUMERIC: if (DateUtil.isCellDateFormatted(c)) { o = DateUtils.date2Str(c.getDateCellValue()); } else { o = String.valueOf(c.getNumericCellValue()); o = matchDoneBigDecimal(o); o = RegularUtils.converNumByReg(o); } break; case STRING: o = c.getStringCellValue(); break; default: o = null; break; } return o; } /** * 字符串转对象 * * @param strField 字符串 * @param clazz 待转类型 * @return 转换后数据 */ public static Object str2TargetClass(String strField, Class<?> clazz) { if (null == strField || "".equals(strField)) return null; if ((Long.class == clazz) || (long.class == clazz)) { strField = matchDoneBigDecimal(strField); strField = RegularUtils.converNumByReg(strField); return Long.parseLong(strField); } if ((Integer.class == clazz) || (int.class == clazz)) { strField = matchDoneBigDecimal(strField); strField = RegularUtils.converNumByReg(strField); return Integer.parseInt(strField); } if ((Float.class == clazz) || (float.class == clazz)) { strField = matchDoneBigDecimal(strField); return Float.parseFloat(strField); } if ((Double.class == clazz) || (double.class == clazz)) { strField = matchDoneBigDecimal(strField); return Double.parseDouble(strField); } if ((Character.class == clazz) || (char.class == clazz)) { return strField.toCharArray()[0]; } if ((Boolean.class == clazz) || (boolean.class == clazz)) { return Boolean.parseBoolean(strField); } if (Date.class == clazz) { return DateUtils.str2DateUnmatch2Null(strField); } return strField; } /** * 科学计数法数据转换 * * @param bigDecimal 科学计数法 * @return 数据字符串 */ private static String matchDoneBigDecimal(String bigDecimal) { // 对科 <SUF> boolean flg = Pattern.matches("^-?\\d+(\\.\\d+)?(E-?\\d+)?$", bigDecimal); if (flg) { BigDecimal bd = new BigDecimal(bigDecimal); bigDecimal = bd.toPlainString(); } return bigDecimal; } /** * <p>根据java对象属性{@link Field}获取该属性的getter或setter方法名, * 另对{@link boolean}及{@link Boolean}做了行管处理</p> * * @param clazz 操作对象 * @param fieldName 对象属性 * @param methodType 方法类型,getter或setter枚举 * @return getter或setter方法 * @throws IntrospectionException 异常 * @author Crab2Died */ public static Method getterOrSetter(Class clazz, String fieldName, FieldAccessType methodType) throws IntrospectionException { if (null == fieldName || "".equals(fieldName)) return null; BeanInfo beanInfo = Introspector.getBeanInfo(clazz); PropertyDescriptor[] props = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor prop : props) { if (fieldName.equals(prop.getName())) { if (FieldAccessType.SETTER == methodType) { return prop.getWriteMethod(); } if (FieldAccessType.GETTER == methodType) { return prop.getReadMethod(); } } } throw new IntrospectionException("Can not get the getter or setter method"); } /** * <p>根据对象的属性名{@code fieldName}获取某个java的属性{@link java.lang.reflect.Field}</p> * * @param clazz java对象的class属性 * @param fieldName 属性名 * @return {@link java.lang.reflect.Field} java对象的属性 * @author Crab2Died */ private static Field matchClassField(Class clazz, String fieldName) { List<Field> fields = new ArrayList<>(); for (; clazz != Object.class; clazz = clazz.getSuperclass()) { fields.addAll(Arrays.asList(clazz.getDeclaredFields())); } for (Field field : fields) { if (fieldName.equals(field.getName())) { return field; } } throw new IllegalArgumentException("[" + clazz.getName() + "] can`t found field with [" + fieldName + "]"); } /** * 根据属性名与属性类型获取字段内容 * * @param bean 对象 * @param fieldName 字段名 * @param writeConvertible 写入转换器 * @return 对象指定字段内容 * @throws Excel4JException 异常 */ public static String getProperty(Object bean, String fieldName, WriteConvertible writeConvertible) throws Excel4JException { if (bean == null || fieldName == null) throw new IllegalArgumentException("Operating bean or filed class must not be null"); Method method; Object object; try { method = getterOrSetter(bean.getClass(), fieldName, FieldAccessType.GETTER); object = method.invoke(bean); } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { throw new Excel4JException(e); } if (null != writeConvertible && writeConvertible.getClass() != DefaultConvertible.class) { // 写入转换器 object = writeConvertible.execWrite(object); } return object == null ? "" : object.toString(); } /** * 根据属性名与属性类型获取字段内容 * * @param bean 对象 * @param name 字段名 * @param value 字段类型 */ public static void copyProperty(Object bean, String name, Object value) throws Excel4JException { if (null == name || null == value) return; Field field = matchClassField(bean.getClass(), name); if (null == field) return; Method method; try { method = getterOrSetter(bean.getClass(), name, FieldAccessType.SETTER); if (value.getClass() == field.getType()) { method.invoke(bean, value); } else { method.invoke(bean, str2TargetClass(value.toString(), field.getType())); } } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { throw new Excel4JException(e); } } /** * 计算公式结果 * * @param cell 单元格类型为公式的单元格 * @return 返回单元格计算后的值 格式化成String * @author QingMings * Email:1821063757@qq.com * date 2018-01-13 */ public static String calculationFormula(Cell cell) { CellValue cellValue = cell.getSheet().getWorkbook().getCreationHelper() .createFormulaEvaluator().evaluate(cell); return cellValue.formatAsString(); } }
0
2,541
8
2,754
9
2,959
7
2,754
9
3,444
12
false
false
false
false
false
true
29822_3
package com.ab.http; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Date; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * © 2012 amsoft.cn * 名称:EasyX509TrustManager.java * 描述:SSL自签名的实现类 * * @author 还如一梦中 * @version v1.0 * @date:2013-11-13 上午9:00:52 */ public class EasyX509TrustManager implements X509TrustManager { private X509TrustManager standardTrustManager = null; /** * Constructor for EasyX509TrustManager. */ public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { super(); TrustManagerFactory factory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(keystore); TrustManager[] trustmanagers = factory.getTrustManagers(); if (trustmanagers.length == 0) { throw new NoSuchAlgorithmException("no trust manager found"); } this.standardTrustManager = (X509TrustManager) trustmanagers[0]; } /** * 执行客户端的安全策略 */ @Override public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { standardTrustManager.checkClientTrusted(certificates, authType); } /** * 执行服务器的安全策略 * 检查签名、信任链中证书的有效日期和CRLs * 清除因证书过期出现的问题 */ @Override public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { // Clean up the certificates chain and build a new one. // Theoretically, we shouldn't have to do this, but various web servers // in practice are mis-configured to have out-of-order certificates or // expired self-issued root certificate. // int chainLength = certificates.length; if (certificates.length > 1) { // 1. we clean the received certificates chain. // We start from the end-entity certificate, tracing down by // matching // the "issuer" field and "subject" field until we can't continue. // This helps when the certificates are out of order or // some certificates are not related to the site. int currIndex; for (currIndex = 0; currIndex < certificates.length; ++currIndex) { boolean foundNext = false; for (int nextIndex = currIndex + 1; nextIndex < certificates.length; ++nextIndex) { if (certificates[currIndex].getIssuerDN().equals( certificates[nextIndex].getSubjectDN())) { foundNext = true; // Exchange certificates so that 0 through currIndex + 1 // are in proper order if (nextIndex != currIndex + 1) { X509Certificate tempCertificate = certificates[nextIndex]; certificates[nextIndex] = certificates[currIndex + 1]; certificates[currIndex + 1] = tempCertificate; } break; } } if (!foundNext) break; } // 2. we exam if the last traced certificate is self issued and it // is expired. // If so, we drop it and pass the rest to checkServerTrusted(), // hoping we might // have a similar but unexpired trusted root. int chainLength = currIndex + 1; X509Certificate lastCertificate = certificates[chainLength - 1]; Date now = new Date(); if (lastCertificate.getSubjectDN().equals( lastCertificate.getIssuerDN()) && now.after(lastCertificate.getNotAfter())) { --chainLength; } } // standardTrustManager.checkServerTrusted(certificates, authType); } /** * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ @Override public X509Certificate[] getAcceptedIssuers() { return this.standardTrustManager.getAcceptedIssuers(); } }
CraftsmenTech/AndBase
AndBase/src/com/ab/http/EasyX509TrustManager.java
1,096
/** * 执行服务器的安全策略 * 检查签名、信任链中证书的有效日期和CRLs * 清除因证书过期出现的问题 */
block_comment
zh-cn
package com.ab.http; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.Date; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; /** * © 2012 amsoft.cn * 名称:EasyX509TrustManager.java * 描述:SSL自签名的实现类 * * @author 还如一梦中 * @version v1.0 * @date:2013-11-13 上午9:00:52 */ public class EasyX509TrustManager implements X509TrustManager { private X509TrustManager standardTrustManager = null; /** * Constructor for EasyX509TrustManager. */ public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { super(); TrustManagerFactory factory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(keystore); TrustManager[] trustmanagers = factory.getTrustManagers(); if (trustmanagers.length == 0) { throw new NoSuchAlgorithmException("no trust manager found"); } this.standardTrustManager = (X509TrustManager) trustmanagers[0]; } /** * 执行客户端的安全策略 */ @Override public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { standardTrustManager.checkClientTrusted(certificates, authType); } /** * 执行服 <SUF>*/ @Override public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { // Clean up the certificates chain and build a new one. // Theoretically, we shouldn't have to do this, but various web servers // in practice are mis-configured to have out-of-order certificates or // expired self-issued root certificate. // int chainLength = certificates.length; if (certificates.length > 1) { // 1. we clean the received certificates chain. // We start from the end-entity certificate, tracing down by // matching // the "issuer" field and "subject" field until we can't continue. // This helps when the certificates are out of order or // some certificates are not related to the site. int currIndex; for (currIndex = 0; currIndex < certificates.length; ++currIndex) { boolean foundNext = false; for (int nextIndex = currIndex + 1; nextIndex < certificates.length; ++nextIndex) { if (certificates[currIndex].getIssuerDN().equals( certificates[nextIndex].getSubjectDN())) { foundNext = true; // Exchange certificates so that 0 through currIndex + 1 // are in proper order if (nextIndex != currIndex + 1) { X509Certificate tempCertificate = certificates[nextIndex]; certificates[nextIndex] = certificates[currIndex + 1]; certificates[currIndex + 1] = tempCertificate; } break; } } if (!foundNext) break; } // 2. we exam if the last traced certificate is self issued and it // is expired. // If so, we drop it and pass the rest to checkServerTrusted(), // hoping we might // have a similar but unexpired trusted root. int chainLength = currIndex + 1; X509Certificate lastCertificate = certificates[chainLength - 1]; Date now = new Date(); if (lastCertificate.getSubjectDN().equals( lastCertificate.getIssuerDN()) && now.after(lastCertificate.getNotAfter())) { --chainLength; } } // standardTrustManager.checkServerTrusted(certificates, authType); } /** * @see javax.net.ssl.X509TrustManager#getAcceptedIssuers() */ @Override public X509Certificate[] getAcceptedIssuers() { return this.standardTrustManager.getAcceptedIssuers(); } }
0
1,004
42
1,096
40
1,094
37
1,096
40
1,453
74
false
false
false
false
false
true
42246_2
package com.orong.activity; import org.json.JSONException; import org.json.JSONObject; import com.orong.Constant; import com.orong.R; import com.orong.entity.HttpDatas; import com.orong.utils.net.NetUtils; import com.orong.utils.net.HttpAsyncTask.TaskCallBack; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class TelUsActivity extends BaseActivity { private TextView tvTelephone;// 客服电话 private ImageView ivCallService;// 呼叫客服 private EditText etOpinion;// 意见信息 private Button btSubmit;// 确认提交 @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_tel_us); initivReabck(this); setTitle(this, R.string.aboutus); tvTelephone = (TextView) this.findViewById(R.id.tv_telephone); ivCallService = (ImageView) this.findViewById(R.id.iv_call_service); ivCallService.setOnClickListener(this); etOpinion = (EditText) this.findViewById(R.id.et_opinion); etOpinion.addTextChangedListener(new SuggestTextWatcher()); btSubmit = (Button) this.findViewById(R.id.bt_submit); btSubmit.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_call_service: callPhone(); break; case R.id.bt_submit: submintOpinion(); break; default: super.onClick(v); break; } } /** * 启动打电话功能 */ private void callPhone() { String phone = tvTelephone.getText().toString(); Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phone)); startActivity(intent); } private void submintOpinion() { String opinion = etOpinion.getText().toString().trim(); if ("".equals(opinion)) { Toast.makeText(this, "意见不能为空", 0).show(); return; } if (opinion.length() < 5) { Toast.makeText(this, getString(R.string.text_less_than_5), 0).show(); return; } if (opinion.length() > 100) { Toast.makeText(this, getString(R.string.text_more_than_100), 0).show(); return; } HttpDatas datas = new HttpDatas(Constant.USERAPI); datas.putParam("method", "ContactUs"); datas.putParam("reason", opinion); NetUtils.sendRequest(datas, this, getString(R.string.uploading_message), new TaskCallBack() { @Override public int excueHttpResponse(String respondsStr) { int code = 0; try { JSONObject jsonObject = new JSONObject(respondsStr); code = jsonObject.getInt("code"); } catch (JSONException e) { e.printStackTrace(); } return code; } @Override public void beforeTask() { } @Override public void afterTask(int result) { switch (result) { case Constant.RESPONSE_OK: Toast.makeText(getApplicationContext(), getString(R.string.thanks_for_opinion), 0).show(); break; case 3009: Toast.makeText(getApplicationContext(), getString(R.string.was_resummit), 0).show(); break; default: showResulttoast(result, TelUsActivity.this); break; } } }); } class SuggestTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { int length = s.length(); if (length > 100) { s.delete(length - 1, length); length--; Toast.makeText(getApplicationContext(), "字数超限", 0).show(); return; } } } }
CraftsmenTech/jurongwang
src/com/orong/activity/TelUsActivity.java
1,211
// 意见信息
line_comment
zh-cn
package com.orong.activity; import org.json.JSONException; import org.json.JSONObject; import com.orong.Constant; import com.orong.R; import com.orong.entity.HttpDatas; import com.orong.utils.net.NetUtils; import com.orong.utils.net.HttpAsyncTask.TaskCallBack; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class TelUsActivity extends BaseActivity { private TextView tvTelephone;// 客服电话 private ImageView ivCallService;// 呼叫客服 private EditText etOpinion;// 意见 <SUF> private Button btSubmit;// 确认提交 @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_tel_us); initivReabck(this); setTitle(this, R.string.aboutus); tvTelephone = (TextView) this.findViewById(R.id.tv_telephone); ivCallService = (ImageView) this.findViewById(R.id.iv_call_service); ivCallService.setOnClickListener(this); etOpinion = (EditText) this.findViewById(R.id.et_opinion); etOpinion.addTextChangedListener(new SuggestTextWatcher()); btSubmit = (Button) this.findViewById(R.id.bt_submit); btSubmit.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv_call_service: callPhone(); break; case R.id.bt_submit: submintOpinion(); break; default: super.onClick(v); break; } } /** * 启动打电话功能 */ private void callPhone() { String phone = tvTelephone.getText().toString(); Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phone)); startActivity(intent); } private void submintOpinion() { String opinion = etOpinion.getText().toString().trim(); if ("".equals(opinion)) { Toast.makeText(this, "意见不能为空", 0).show(); return; } if (opinion.length() < 5) { Toast.makeText(this, getString(R.string.text_less_than_5), 0).show(); return; } if (opinion.length() > 100) { Toast.makeText(this, getString(R.string.text_more_than_100), 0).show(); return; } HttpDatas datas = new HttpDatas(Constant.USERAPI); datas.putParam("method", "ContactUs"); datas.putParam("reason", opinion); NetUtils.sendRequest(datas, this, getString(R.string.uploading_message), new TaskCallBack() { @Override public int excueHttpResponse(String respondsStr) { int code = 0; try { JSONObject jsonObject = new JSONObject(respondsStr); code = jsonObject.getInt("code"); } catch (JSONException e) { e.printStackTrace(); } return code; } @Override public void beforeTask() { } @Override public void afterTask(int result) { switch (result) { case Constant.RESPONSE_OK: Toast.makeText(getApplicationContext(), getString(R.string.thanks_for_opinion), 0).show(); break; case 3009: Toast.makeText(getApplicationContext(), getString(R.string.was_resummit), 0).show(); break; default: showResulttoast(result, TelUsActivity.this); break; } } }); } class SuggestTextWatcher implements TextWatcher { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { int length = s.length(); if (length > 100) { s.delete(length - 1, length); length--; Toast.makeText(getApplicationContext(), "字数超限", 0).show(); return; } } } }
0
934
7
1,195
7
1,161
5
1,195
7
1,484
9
false
false
false
false
false
true
34722_11
package ai.zhuanzhi.dl4j.rbm4j; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.ops.transforms.Transforms; /** * @author hu * 该教程由专知(www.zhuanzhi.ai)提供 */ public class RBM { protected INDArray w, b, a; public RBM(int vDim, int hDim){ w = Nd4j.rand(vDim, hDim); b = Nd4j.rand(new int[]{hDim}); a = Nd4j.rand(new int[]{vDim}); } //输入可见层v,输出隐藏层为1的概率p(h|v) protected INDArray computeHProbs(INDArray vSamples){ INDArray hProbs = vSamples.mmul(w).addRowVector(b); hProbs = Transforms.sigmoid(hProbs); return hProbs; } //输入隐藏层h,输出可见层为1的概率p(v|h) protected INDArray computeVProbs(INDArray hSamples){ INDArray vProbs = hSamples.mmul(w.transpose()).addRowVector(a); vProbs = Transforms.sigmoid(vProbs); return vProbs; } //输入可见层,输出RBM重构的结果 public INDArray reconstruct(INDArray vSamples){ INDArray hProbs = computeHProbs(vSamples); INDArray hSamples = bernoulliSample(hProbs); INDArray negVSamples = bernoulliSample(computeVProbs(hSamples)); return negVSamples; } public double fit(INDArray vSamples, double learningRate){ INDArray hProbs = computeHProbs(vSamples); INDArray hSamples = bernoulliSample(hProbs); INDArray negVSamples = bernoulliSample(computeVProbs(hSamples)); INDArray negHProbs = computeHProbs(negVSamples); INDArray mseTempMatrix = negVSamples.sub(vSamples); double loss = mseTempMatrix.mul(mseTempMatrix).div(2).mean(0,1).getDouble(0,0); //正梯度 INDArray posGrad = vSamples.transpose().mmul(hProbs); //负梯度 INDArray negGrad = negVSamples.transpose().mmul(negHProbs); //输入样本数量 int numSamples = vSamples.shape()[0]; //计算并更新参数 INDArray dw = posGrad.sub(negGrad).mul(learningRate/numSamples); INDArray db = hProbs.mean(0).sub(negHProbs.mean(0)).mul(learningRate); INDArray da = vSamples.mean(0).sub(negVSamples.mean(0)).mul(learningRate); w.addi(dw); b.addi(db); a.addi(da); return loss; } //伯努利采样 protected INDArray bernoulliSample(INDArray probs){ INDArray randArray = Nd4j.rand(probs.shape()); INDArray samples = probs.gt(randArray); return samples; } public static void main(String[] args) { //手工设置一组数据 double[][] rawVSamples = new double[][]{ {1,1,1,1,0,0,0,0}, {1,1,1,1,0,0,0,0}, {0,0,1,1,1,1,0,0}, {0,0,1,1,1,1,0,0}, {0,0,0,0,1,1,1,1}, {0,0,0,0,1,1,1,1} }; INDArray vSamples = Nd4j.create(rawVSamples); //设置RBM(隐藏层大小为2) RBM rbm = new RBM(vSamples.shape()[1],2); //训练 for(int i=0;i<20000;i++){ double loss = rbm.fit(vSamples,5e-3); if(i % 1000 == 0){ System.out.println("batch:"+i+"\tloss:" + loss); } } //显示重构结果 System.out.println("reconstruction:"); System.out.println(rbm.reconstruct(vSamples)); //显示对应的隐藏层激活值(学习到的特征) System.out.println("features:"); System.out.println(rbm.computeHProbs(vSamples)); } }
CrawlScript/RBM4j
src/main/java/ai/zhuanzhi/dl4j/rbm4j/RBM.java
1,123
//显示重构结果
line_comment
zh-cn
package ai.zhuanzhi.dl4j.rbm4j; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.ops.transforms.Transforms; /** * @author hu * 该教程由专知(www.zhuanzhi.ai)提供 */ public class RBM { protected INDArray w, b, a; public RBM(int vDim, int hDim){ w = Nd4j.rand(vDim, hDim); b = Nd4j.rand(new int[]{hDim}); a = Nd4j.rand(new int[]{vDim}); } //输入可见层v,输出隐藏层为1的概率p(h|v) protected INDArray computeHProbs(INDArray vSamples){ INDArray hProbs = vSamples.mmul(w).addRowVector(b); hProbs = Transforms.sigmoid(hProbs); return hProbs; } //输入隐藏层h,输出可见层为1的概率p(v|h) protected INDArray computeVProbs(INDArray hSamples){ INDArray vProbs = hSamples.mmul(w.transpose()).addRowVector(a); vProbs = Transforms.sigmoid(vProbs); return vProbs; } //输入可见层,输出RBM重构的结果 public INDArray reconstruct(INDArray vSamples){ INDArray hProbs = computeHProbs(vSamples); INDArray hSamples = bernoulliSample(hProbs); INDArray negVSamples = bernoulliSample(computeVProbs(hSamples)); return negVSamples; } public double fit(INDArray vSamples, double learningRate){ INDArray hProbs = computeHProbs(vSamples); INDArray hSamples = bernoulliSample(hProbs); INDArray negVSamples = bernoulliSample(computeVProbs(hSamples)); INDArray negHProbs = computeHProbs(negVSamples); INDArray mseTempMatrix = negVSamples.sub(vSamples); double loss = mseTempMatrix.mul(mseTempMatrix).div(2).mean(0,1).getDouble(0,0); //正梯度 INDArray posGrad = vSamples.transpose().mmul(hProbs); //负梯度 INDArray negGrad = negVSamples.transpose().mmul(negHProbs); //输入样本数量 int numSamples = vSamples.shape()[0]; //计算并更新参数 INDArray dw = posGrad.sub(negGrad).mul(learningRate/numSamples); INDArray db = hProbs.mean(0).sub(negHProbs.mean(0)).mul(learningRate); INDArray da = vSamples.mean(0).sub(negVSamples.mean(0)).mul(learningRate); w.addi(dw); b.addi(db); a.addi(da); return loss; } //伯努利采样 protected INDArray bernoulliSample(INDArray probs){ INDArray randArray = Nd4j.rand(probs.shape()); INDArray samples = probs.gt(randArray); return samples; } public static void main(String[] args) { //手工设置一组数据 double[][] rawVSamples = new double[][]{ {1,1,1,1,0,0,0,0}, {1,1,1,1,0,0,0,0}, {0,0,1,1,1,1,0,0}, {0,0,1,1,1,1,0,0}, {0,0,0,0,1,1,1,1}, {0,0,0,0,1,1,1,1} }; INDArray vSamples = Nd4j.create(rawVSamples); //设置RBM(隐藏层大小为2) RBM rbm = new RBM(vSamples.shape()[1],2); //训练 for(int i=0;i<20000;i++){ double loss = rbm.fit(vSamples,5e-3); if(i % 1000 == 0){ System.out.println("batch:"+i+"\tloss:" + loss); } } //显示 <SUF> System.out.println("reconstruction:"); System.out.println(rbm.reconstruct(vSamples)); //显示对应的隐藏层激活值(学习到的特征) System.out.println("features:"); System.out.println(rbm.computeHProbs(vSamples)); } }
0
1,009
4
1,123
5
1,169
5
1,123
5
1,393
7
false
false
false
false
false
true
60032_8
package com.ynyes.lyz.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * 调色包实体类 * * @author dengxiao */ @Entity public class TdColorPackage { // id @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; // 调色包名称 @Column private String name; // 调色包编号 @Column private String number; // 调色包图片 @Column private String imageUri; // 库存 @Column private Long inventory; // 当前销售价格 @Column(scale = 2) private Double salePrice; // 当前进货价格 @Column(scale = 2) private Double stockPrice; // 购买数量 @Column private Long quantity; //总价 @Column private Double totalPrice; // 归属: 1 华润商品 2 乐意装商品 @Column private Long belongTo; // 排序号 @Column private Double sortId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getImageUri() { return imageUri; } public void setImageUri(String imageUri) { this.imageUri = imageUri; } public Long getInventory() { return inventory; } public void setInventory(Long inventory) { this.inventory = inventory; } public Double getSalePrice() { return salePrice; } public void setSalePrice(Double salePrice) { this.salePrice = salePrice; } public Double getStockPrice() { return stockPrice; } public void setStockPrice(Double stockPrice) { this.stockPrice = stockPrice; } public Long getQuantity() { return quantity; } public void setQuantity(Long quantity) { this.quantity = quantity; } public Double getTotalPrice() { return totalPrice; } public void setTotalPrice(Double totalPrice) { this.totalPrice = totalPrice; } public Long getBelongTo() { return belongTo; } public void setBelongTo(Long belongTo) { this.belongTo = belongTo; } public Double getSortId() { return sortId; } public void setSortId(Double sortId) { this.sortId = sortId; } }
CrazyApeDX/leyizhuang2.0-manager
src/main/java/com/ynyes/lyz/entity/TdColorPackage.java
768
// 排序号
line_comment
zh-cn
package com.ynyes.lyz.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * 调色包实体类 * * @author dengxiao */ @Entity public class TdColorPackage { // id @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; // 调色包名称 @Column private String name; // 调色包编号 @Column private String number; // 调色包图片 @Column private String imageUri; // 库存 @Column private Long inventory; // 当前销售价格 @Column(scale = 2) private Double salePrice; // 当前进货价格 @Column(scale = 2) private Double stockPrice; // 购买数量 @Column private Long quantity; //总价 @Column private Double totalPrice; // 归属: 1 华润商品 2 乐意装商品 @Column private Long belongTo; // 排序 <SUF> @Column private Double sortId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getImageUri() { return imageUri; } public void setImageUri(String imageUri) { this.imageUri = imageUri; } public Long getInventory() { return inventory; } public void setInventory(Long inventory) { this.inventory = inventory; } public Double getSalePrice() { return salePrice; } public void setSalePrice(Double salePrice) { this.salePrice = salePrice; } public Double getStockPrice() { return stockPrice; } public void setStockPrice(Double stockPrice) { this.stockPrice = stockPrice; } public Long getQuantity() { return quantity; } public void setQuantity(Long quantity) { this.quantity = quantity; } public Double getTotalPrice() { return totalPrice; } public void setTotalPrice(Double totalPrice) { this.totalPrice = totalPrice; } public Long getBelongTo() { return belongTo; } public void setBelongTo(Long belongTo) { this.belongTo = belongTo; } public Double getSortId() { return sortId; } public void setSortId(Double sortId) { this.sortId = sortId; } }
0
589
5
768
4
744
3
768
4
888
7
false
false
false
false
false
true
20931_4
package com.lou.simhasher; import java.math.BigInteger; import java.util.Map; import java.util.Set; import com.lou.simhasher.util.FNVHash; /** * 文本去重算法的simhash类 * 步骤如下: * 1,对文本分词,得到N维特征向量(默认为64维) * 2,为分词设置权重(tf-idf) * 3,为特征向量计算哈希 * 4,对所有特征向量加权,累加(目前仅进行非加权累加) * 5,对累加结果,大于零置一,小于零置零 * 6,得到文本指纹(fingerprint) * * @author louxuezheng@hotmail.com */ public class SimHasher { private String hash; private BigInteger signature; private KeywordExtractor wordExtractor = KeywordExtractor.getInstance(); /** * 构造函数 * * @param content 字符串 */ public SimHasher(String content) { this.analysis(content); } private void analysis(String content) { Map<String, Double> wordInfos = wordExtractor.extract(content); double[] featureVector = new double[FNVHash.HASH_BITS]; Set<String> words = wordInfos.keySet(); // System.out.println(words); for (String word : words) { BigInteger wordhash = FNVHash.fnv1aHash64(word); for (int i = 0; i < FNVHash.HASH_BITS; i++) { BigInteger bitmask = BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1); if (wordhash.and(bitmask).signum() != 0) { featureVector[i] += wordInfos.get(word); } else { featureVector[i] -= wordInfos.get(word); } } } BigInteger signature = BigInteger.ZERO; StringBuffer hashBuffer = new StringBuffer(); for (int i = 0; i < FNVHash.HASH_BITS; i++) { if (featureVector[i] >= 0) { signature = signature.add(BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1)); hashBuffer.append("1"); } else { hashBuffer.append("0"); } } this.hash = hashBuffer.toString(); this.signature = signature; } /** * 汉明距离 * * @param targetSignature 比较签名 * @return */ public int getHammingDistance(BigInteger targetSignature) { BigInteger x = this.getSignature().xor(targetSignature); int tot = 0; // 统计x中二进制位数为1的个数 // 我们想想,一个二进制数减去1,那么,从最后那个1(包括那个1)后面的数字全都反了, // 对吧,然后,n&(n-1)就相当于把后面的数字清0, // 我们看n能做多少次这样的操作就OK了。 while (x.signum() != 0) { tot += 1; x = x.and(x.subtract(new BigInteger("1"))); } return tot; } /** * hash距离。二进制比较 * * @param targetHash 比较目标 * @return */ public int getHashDistance(String targetHash) { int distance; if (this.getHash().length() != targetHash.length()) { distance = -1; } else { distance = 0; for (int i = 0; i < this.getHash().length(); i++) { if (this.getHash().charAt(i) != targetHash.charAt(i)) { distance++; } } } return distance; } public String getHash() { return this.hash; } public BigInteger getSignature() { return this.signature; } }
CreekLou/simhash
src/main/java/com/lou/simhasher/SimHasher.java
1,024
// 统计x中二进制位数为1的个数
line_comment
zh-cn
package com.lou.simhasher; import java.math.BigInteger; import java.util.Map; import java.util.Set; import com.lou.simhasher.util.FNVHash; /** * 文本去重算法的simhash类 * 步骤如下: * 1,对文本分词,得到N维特征向量(默认为64维) * 2,为分词设置权重(tf-idf) * 3,为特征向量计算哈希 * 4,对所有特征向量加权,累加(目前仅进行非加权累加) * 5,对累加结果,大于零置一,小于零置零 * 6,得到文本指纹(fingerprint) * * @author louxuezheng@hotmail.com */ public class SimHasher { private String hash; private BigInteger signature; private KeywordExtractor wordExtractor = KeywordExtractor.getInstance(); /** * 构造函数 * * @param content 字符串 */ public SimHasher(String content) { this.analysis(content); } private void analysis(String content) { Map<String, Double> wordInfos = wordExtractor.extract(content); double[] featureVector = new double[FNVHash.HASH_BITS]; Set<String> words = wordInfos.keySet(); // System.out.println(words); for (String word : words) { BigInteger wordhash = FNVHash.fnv1aHash64(word); for (int i = 0; i < FNVHash.HASH_BITS; i++) { BigInteger bitmask = BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1); if (wordhash.and(bitmask).signum() != 0) { featureVector[i] += wordInfos.get(word); } else { featureVector[i] -= wordInfos.get(word); } } } BigInteger signature = BigInteger.ZERO; StringBuffer hashBuffer = new StringBuffer(); for (int i = 0; i < FNVHash.HASH_BITS; i++) { if (featureVector[i] >= 0) { signature = signature.add(BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1)); hashBuffer.append("1"); } else { hashBuffer.append("0"); } } this.hash = hashBuffer.toString(); this.signature = signature; } /** * 汉明距离 * * @param targetSignature 比较签名 * @return */ public int getHammingDistance(BigInteger targetSignature) { BigInteger x = this.getSignature().xor(targetSignature); int tot = 0; // 统计 <SUF> // 我们想想,一个二进制数减去1,那么,从最后那个1(包括那个1)后面的数字全都反了, // 对吧,然后,n&(n-1)就相当于把后面的数字清0, // 我们看n能做多少次这样的操作就OK了。 while (x.signum() != 0) { tot += 1; x = x.and(x.subtract(new BigInteger("1"))); } return tot; } /** * hash距离。二进制比较 * * @param targetHash 比较目标 * @return */ public int getHashDistance(String targetHash) { int distance; if (this.getHash().length() != targetHash.length()) { distance = -1; } else { distance = 0; for (int i = 0; i < this.getHash().length(); i++) { if (this.getHash().charAt(i) != targetHash.charAt(i)) { distance++; } } } return distance; } public String getHash() { return this.hash; } public BigInteger getSignature() { return this.signature; } }
0
878
17
1,020
14
1,004
14
1,020
14
1,313
17
false
false
false
false
false
true
18675_4
package UI; // 所有的道具包 public class Bag extends FlyObject { public Bag(int x, int y) { this.x = x; this.y = y; this.height = 50; this.width = 50; } /** * 根据的类型来获取新的道具包,x和y是被打的砖块的位置,道具在砖块的位置生成 * @param i * @param x * @param y * @return */ public static Bag getBag(int i, int x, int y) { Bag bag = null; switch (i) { case 1: bag = new RocketBag(x, y); break; case 2: bag = new PunchBag(x, y); break; case 3: bag = new BoomBag(x, y); break; case 4: bag = new LengthenBag(x, y); break; case 5: bag = new ShortenBag(x, y); break; case 6: bag = new DieBag(x, y); break; case 7: bag = new BigBallBag(x, y); break; case 8: bag = new SmallBallBag(x, y); break; case 9: bag = new CommonBallBag(x, y); break; } return bag; } } // 导弹球 class RocketBag extends Bag { public RocketBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/RocketBag.png"); } } // 穿刺球 class PunchBag extends Bag { public PunchBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/PunchBag.png"); } } // 炸弹球 class BoomBag extends Bag { public BoomBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/BoomBag.png"); } } // 让挡板变长 class LengthenBag extends Bag { public LengthenBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/LengthenBag.png"); } } // 让挡板变小 class ShortenBag extends Bag { public ShortenBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/ShortenBag.png"); } } // 死亡 class DieBag extends Bag { public DieBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/DieBag.png"); } } // 让球变大 class BigBallBag extends Bag { public BigBallBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/BigBallBag.png"); } } // 让球变小 class SmallBallBag extends Bag { public SmallBallBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/SmallBallBag.png"); } } // 普通球道具包 class CommonBallBag extends Bag { public CommonBallBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/ball.png"); } }
CrispyCandy750/hit_brick
UI/Bag.java
841
// 炸弹球
line_comment
zh-cn
package UI; // 所有的道具包 public class Bag extends FlyObject { public Bag(int x, int y) { this.x = x; this.y = y; this.height = 50; this.width = 50; } /** * 根据的类型来获取新的道具包,x和y是被打的砖块的位置,道具在砖块的位置生成 * @param i * @param x * @param y * @return */ public static Bag getBag(int i, int x, int y) { Bag bag = null; switch (i) { case 1: bag = new RocketBag(x, y); break; case 2: bag = new PunchBag(x, y); break; case 3: bag = new BoomBag(x, y); break; case 4: bag = new LengthenBag(x, y); break; case 5: bag = new ShortenBag(x, y); break; case 6: bag = new DieBag(x, y); break; case 7: bag = new BigBallBag(x, y); break; case 8: bag = new SmallBallBag(x, y); break; case 9: bag = new CommonBallBag(x, y); break; } return bag; } } // 导弹球 class RocketBag extends Bag { public RocketBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/RocketBag.png"); } } // 穿刺球 class PunchBag extends Bag { public PunchBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/PunchBag.png"); } } // 炸弹 <SUF> class BoomBag extends Bag { public BoomBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/BoomBag.png"); } } // 让挡板变长 class LengthenBag extends Bag { public LengthenBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/LengthenBag.png"); } } // 让挡板变小 class ShortenBag extends Bag { public ShortenBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/ShortenBag.png"); } } // 死亡 class DieBag extends Bag { public DieBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/DieBag.png"); } } // 让球变大 class BigBallBag extends Bag { public BigBallBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/BigBallBag.png"); } } // 让球变小 class SmallBallBag extends Bag { public SmallBallBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/SmallBallBag.png"); } } // 普通球道具包 class CommonBallBag extends Bag { public CommonBallBag(int x, int y) { super(x, y); image = ImageManager.getImage("/Image/ball.png"); } }
0
746
6
841
6
878
4
841
6
999
9
false
false
false
false
false
true
62978_3
package org.brewchain.account.function; import org.apache.felix.ipojo.util.Log; import org.brewchain.account.core.AccountHelper; import org.brewchain.account.test.InternalCallTest; import com.google.protobuf.ByteString; import lombok.extern.slf4j.Slf4j; @Slf4j public class InternalFunction { /** * 挖矿奖励 * * @param accountHelper * @param blackHoleAddress * @param coinBase * @param balance * @throws Exception */ public static void MinerReward(AccountHelper accountHelper, String... params) throws Exception { String blackHoleAddress = ""; String balance = "0"; String coinBase = ""; log.debug(String.format("call MinerReward!")); accountHelper.addBalance(ByteString.copyFromUtf8(coinBase).toByteArray(), Long.valueOf(balance)); // 黑洞地址 accountHelper.addBalance(ByteString.copyFromUtf8(blackHoleAddress).toByteArray(), 0 - Long.valueOf(balance)); } /** * 挖矿惩罚 * * @param accountHelper * @param blackHoleAddress * @param coinBase * @param balance * @throws Exception */ public static void MinerPunish(AccountHelper accountHelper, byte[] blackHoleAddress, byte[] coinBase, long balance) throws Exception { accountHelper.addBalance(coinBase, 0 - balance); // 黑洞地址 accountHelper.addBalance(blackHoleAddress, balance); } }
CryptoWorldChain/chaincore
account/src/main/java/org/brewchain/account/function/InternalFunction.java
389
// 黑洞地址
line_comment
zh-cn
package org.brewchain.account.function; import org.apache.felix.ipojo.util.Log; import org.brewchain.account.core.AccountHelper; import org.brewchain.account.test.InternalCallTest; import com.google.protobuf.ByteString; import lombok.extern.slf4j.Slf4j; @Slf4j public class InternalFunction { /** * 挖矿奖励 * * @param accountHelper * @param blackHoleAddress * @param coinBase * @param balance * @throws Exception */ public static void MinerReward(AccountHelper accountHelper, String... params) throws Exception { String blackHoleAddress = ""; String balance = "0"; String coinBase = ""; log.debug(String.format("call MinerReward!")); accountHelper.addBalance(ByteString.copyFromUtf8(coinBase).toByteArray(), Long.valueOf(balance)); // 黑洞地址 accountHelper.addBalance(ByteString.copyFromUtf8(blackHoleAddress).toByteArray(), 0 - Long.valueOf(balance)); } /** * 挖矿惩罚 * * @param accountHelper * @param blackHoleAddress * @param coinBase * @param balance * @throws Exception */ public static void MinerPunish(AccountHelper accountHelper, byte[] blackHoleAddress, byte[] coinBase, long balance) throws Exception { accountHelper.addBalance(coinBase, 0 - balance); // 黑洞 <SUF> accountHelper.addBalance(blackHoleAddress, balance); } }
0
342
5
389
5
387
4
389
5
479
8
false
false
false
false
false
true
46751_25
package care; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.melnykov.fab.sample.R; import com.melnykov.fab.sample.tools.IMApplication; import com.melnykov.fab.sample.tools.crmMyDatabaseHelper; import com.ricky.database.CenterDatabase; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by dell on 2015/8/25. */ public class care_add extends Activity implements View.OnTouchListener{ private Button btn01; private EditText et01; private EditText et02; public static final String KEY_USER_ID="KEY_USER_ID"; public static final String KEY_USER_PASSWORD="KEY_USER_PASSWORD"; private List<String> list = new ArrayList<String>(); private ArrayAdapter<String> adapter; private List<String> list2 = new ArrayList<String>(); private ArrayAdapter<String> adapter2; private Spinner spinner_type; //private I TextView queding,text_care_time,text_care_time2; EditText care_note; // ImageView care_choose_time,care_choose_time2; RelativeLayout back; private String type="生日关爱",time=" ",time2,note="",isokflag=""; String userid; String care_id; String User_id; public crmMyDatabaseHelper dbHelper; String fff; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.care_dialog); CenterDatabase centerDatabase = new CenterDatabase(this, null); userid = centerDatabase.getUID(); centerDatabase.close(); User_id = IMApplication.getUserid(this); dbHelper = new crmMyDatabaseHelper(this, "customer.db3", 1); spinner_type=(Spinner)findViewById(R.id.spinner_type); //spinner_remind=(Spinner)findViewById(R.id.spinner_remind); text_care_time=(TextView)findViewById(R.id.care_time); text_care_time2=(TextView)findViewById(R.id.care_time2); care_note=(EditText)findViewById(R.id.care_note); back=(RelativeLayout)findViewById(R.id.ImageButton_back); queding=(TextView)findViewById(R.id.care_submit); text_care_time.setFocusable(true);text_care_time.setClickable(true); text_care_time2.setFocusable(true);text_care_time2.setClickable(true); text_care_time.setOnTouchListener(this);text_care_time2.setOnTouchListener(this); /* care_choose_time=(ImageView)findViewById(R.id.care_choose_time); care_choose_time2=(ImageView)findViewById(R.id.care_choose_time2);*/ queding.setFocusable(true);queding.setClickable(true); /* care_choose_time.setFocusable(true);care_choose_time.setClickable(true); care_choose_time.setOnTouchListener(this); care_choose_time2.setFocusable(true);care_choose_time2.setClickable(true); care_choose_time2.setOnTouchListener(this);*/ back.setFocusable(true);back.setClickable(true); back.setOnTouchListener(this); queding.setOnTouchListener(this); if(getIntent().getAction()=="edite"){ queding.setText("修改"); care_id= getIntent().getExtras().getString("_id"); // Toast.makeText(care_add.this, "修改id:" + care_id, Toast.LENGTH_LONG).show(); Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from care_table where _id=" + care_id, null); while (cursor.moveToNext()){ // Toast.makeText(care_add.this, "修改查询出来为:" + cursor.getString(1), Toast.LENGTH_LONG).show(); note=cursor.getString(5); care_note.setText(note); time=cursor.getString(3); text_care_time.setText(time); time2=cursor.getString(4); text_care_time2.setText(time2); } // Toast.makeText(care_add.this, "修改查询出来为:" + cursor.getString(1), Toast.LENGTH_LONG).show(); }else if(getIntent().getAction()=="lianxirenadd"){ } else{ /* Calendar calendar=Calendar.getInstance(); int year=calendar.get(Calendar.HOUR); int minute=calendar.get(Calendar.MINUTE); int second=calendar.get(Calendar.SECOND); Time time=new Time();*/ Date date=new Date(); DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time22=format.format(date); text_care_time.setText(time22); time=time22; } //第一步:添加一个下拉列表项的list,这里添加的项就是下拉列表的菜单项 list.add("生日"); list.add("节日"); list.add("庆祝日"); list.add("其他"); //第二步:为下拉列表定义一个适配器,这里就用到里前面定义的list。 adapter = new ArrayAdapter<String>(this,R.layout.myspinner_item, list); //第三步:为适配器设置下拉列表下拉时的菜单样式。 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //第四步:将适配器添加到下拉列表上 spinner_type.setAdapter(adapter); //第五步:为下拉列表设置各种事件的响应,这个事响应菜单被选中 spinner_type.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub type=adapter.getItem(arg2); /* 将mySpinner 显示*/ arg0.setVisibility(View.VISIBLE); } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub arg0.setVisibility(View.VISIBLE); } }); /*下拉菜单弹出的内容选项触屏事件处理*/ spinner_type.setOnTouchListener(new Spinner.OnTouchListener(){ public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return false; } }); /*下拉菜单弹出的内容选项焦点改变事件处理*/ spinner_type.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { // TODO Auto-generated method stub } }); } int ii=0; @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (v.getId() == R.id.care_time||v.getId() == R.id.care_time2) { // Toast.makeText(care_add.this,"1",Toast.LENGTH_SHORT).show(); if(v.getId() == R.id.care_time) ii=1;else ii=2; AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = View.inflate(this, R.layout.date_time_dialog, null); final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker); final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker); builder.setView(view); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); timePicker.setIs24HourView(true); timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(Calendar.MINUTE); builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { StringBuffer sb = new StringBuffer(); sb.append(String.format("%d-%02d-%02d", datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth())); sb.append(" "); sb.append(String.format("%02d:%02d", timePicker.getCurrentHour(), timePicker.getCurrentMinute())); if(ii==1) { text_care_time.setText(sb); time = sb.toString(); } else { text_care_time2.setText(sb); time2 = sb.toString(); } dialog.cancel(); } }); Dialog dialog = builder.create(); dialog.show(); } } if(event.getAction()==MotionEvent.ACTION_UP){ if(v.getId()== R.id.ImageButton_back){ new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage("确定退出填写吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { care_add.this.setResult(0); dialog.dismiss(); care_add.this.finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } else if(v.getId()== R.id.care_submit){ if(type==null||time==null||time2==null) { new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage("请完善信息!") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); }else if(getIntent().getAction()=="lianxirenadd"){ dbHelper.getWritableDatabase().execSQL("insert into care_table(uid,type,time,time2,note,fname,fsex,fphone,fid)" + " values(?,?,?,?,?,?,?,?,?)", new String[]{User_id,type ,time ,time2 , note, getIntent().getStringExtra("username"),getIntent().getStringExtra("sex"), getIntent().getStringExtra("phone"), getIntent().getStringExtra("lianxirenid")}); care_add.this.finish(); } else{ if (getIntent().getAction()!=null){ fff="确定修改?"; } else{ fff="确定提交?"; } /* new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage(fff) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {*/ note=care_note.getText().toString().trim(); if (fff.equals("确定提交?")) { Intent mIntent = new Intent(); mIntent.putExtra("type", type); mIntent.putExtra("time", time); mIntent.putExtra("time2",time2); mIntent.putExtra("note",note ); // 设置结果,并进行传送 care_add.this.setResult(1, mIntent); } else { /* dbHelper.getReadableDatabase().rawQuery("update care_table set type="+type+",time="+time+",remind="+remind+",note="+note+" where" + "uid="+userid,null);*/ dbHelper.getWritableDatabase().execSQL("update care_table set type = ?,time = ?,time2 = ?,note = ? where _id=?", new String[]{type, time, time2,note,care_id}); // Toast.makeText(care_add.this,"_id"+care_id,Toast.LENGTH_SHORT).show(); for (int i=0;i<100;i++){ if(aa.remindid[i][0]==care_id){ aa.cancelRemind(aa.remindid[i][1], care_add.this); aa.setRemind(time2,type+" "+time+note,"care_remind",0,2, care_add.this); } } Log.e("更新关爱信息","成功"); startActivity(new Intent().setClass(care_add.this, care_main.class)); } care_add.this.finish(); } } } return false; } }
CsterKuroi/CRM-Android
crmlianxi/src/main/java/care/care_add.java
3,231
// 设置结果,并进行传送
line_comment
zh-cn
package care; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.melnykov.fab.sample.R; import com.melnykov.fab.sample.tools.IMApplication; import com.melnykov.fab.sample.tools.crmMyDatabaseHelper; import com.ricky.database.CenterDatabase; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by dell on 2015/8/25. */ public class care_add extends Activity implements View.OnTouchListener{ private Button btn01; private EditText et01; private EditText et02; public static final String KEY_USER_ID="KEY_USER_ID"; public static final String KEY_USER_PASSWORD="KEY_USER_PASSWORD"; private List<String> list = new ArrayList<String>(); private ArrayAdapter<String> adapter; private List<String> list2 = new ArrayList<String>(); private ArrayAdapter<String> adapter2; private Spinner spinner_type; //private I TextView queding,text_care_time,text_care_time2; EditText care_note; // ImageView care_choose_time,care_choose_time2; RelativeLayout back; private String type="生日关爱",time=" ",time2,note="",isokflag=""; String userid; String care_id; String User_id; public crmMyDatabaseHelper dbHelper; String fff; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.care_dialog); CenterDatabase centerDatabase = new CenterDatabase(this, null); userid = centerDatabase.getUID(); centerDatabase.close(); User_id = IMApplication.getUserid(this); dbHelper = new crmMyDatabaseHelper(this, "customer.db3", 1); spinner_type=(Spinner)findViewById(R.id.spinner_type); //spinner_remind=(Spinner)findViewById(R.id.spinner_remind); text_care_time=(TextView)findViewById(R.id.care_time); text_care_time2=(TextView)findViewById(R.id.care_time2); care_note=(EditText)findViewById(R.id.care_note); back=(RelativeLayout)findViewById(R.id.ImageButton_back); queding=(TextView)findViewById(R.id.care_submit); text_care_time.setFocusable(true);text_care_time.setClickable(true); text_care_time2.setFocusable(true);text_care_time2.setClickable(true); text_care_time.setOnTouchListener(this);text_care_time2.setOnTouchListener(this); /* care_choose_time=(ImageView)findViewById(R.id.care_choose_time); care_choose_time2=(ImageView)findViewById(R.id.care_choose_time2);*/ queding.setFocusable(true);queding.setClickable(true); /* care_choose_time.setFocusable(true);care_choose_time.setClickable(true); care_choose_time.setOnTouchListener(this); care_choose_time2.setFocusable(true);care_choose_time2.setClickable(true); care_choose_time2.setOnTouchListener(this);*/ back.setFocusable(true);back.setClickable(true); back.setOnTouchListener(this); queding.setOnTouchListener(this); if(getIntent().getAction()=="edite"){ queding.setText("修改"); care_id= getIntent().getExtras().getString("_id"); // Toast.makeText(care_add.this, "修改id:" + care_id, Toast.LENGTH_LONG).show(); Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from care_table where _id=" + care_id, null); while (cursor.moveToNext()){ // Toast.makeText(care_add.this, "修改查询出来为:" + cursor.getString(1), Toast.LENGTH_LONG).show(); note=cursor.getString(5); care_note.setText(note); time=cursor.getString(3); text_care_time.setText(time); time2=cursor.getString(4); text_care_time2.setText(time2); } // Toast.makeText(care_add.this, "修改查询出来为:" + cursor.getString(1), Toast.LENGTH_LONG).show(); }else if(getIntent().getAction()=="lianxirenadd"){ } else{ /* Calendar calendar=Calendar.getInstance(); int year=calendar.get(Calendar.HOUR); int minute=calendar.get(Calendar.MINUTE); int second=calendar.get(Calendar.SECOND); Time time=new Time();*/ Date date=new Date(); DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time22=format.format(date); text_care_time.setText(time22); time=time22; } //第一步:添加一个下拉列表项的list,这里添加的项就是下拉列表的菜单项 list.add("生日"); list.add("节日"); list.add("庆祝日"); list.add("其他"); //第二步:为下拉列表定义一个适配器,这里就用到里前面定义的list。 adapter = new ArrayAdapter<String>(this,R.layout.myspinner_item, list); //第三步:为适配器设置下拉列表下拉时的菜单样式。 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //第四步:将适配器添加到下拉列表上 spinner_type.setAdapter(adapter); //第五步:为下拉列表设置各种事件的响应,这个事响应菜单被选中 spinner_type.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub type=adapter.getItem(arg2); /* 将mySpinner 显示*/ arg0.setVisibility(View.VISIBLE); } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub arg0.setVisibility(View.VISIBLE); } }); /*下拉菜单弹出的内容选项触屏事件处理*/ spinner_type.setOnTouchListener(new Spinner.OnTouchListener(){ public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return false; } }); /*下拉菜单弹出的内容选项焦点改变事件处理*/ spinner_type.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { // TODO Auto-generated method stub } }); } int ii=0; @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (v.getId() == R.id.care_time||v.getId() == R.id.care_time2) { // Toast.makeText(care_add.this,"1",Toast.LENGTH_SHORT).show(); if(v.getId() == R.id.care_time) ii=1;else ii=2; AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = View.inflate(this, R.layout.date_time_dialog, null); final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker); final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker); builder.setView(view); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); timePicker.setIs24HourView(true); timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(Calendar.MINUTE); builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { StringBuffer sb = new StringBuffer(); sb.append(String.format("%d-%02d-%02d", datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth())); sb.append(" "); sb.append(String.format("%02d:%02d", timePicker.getCurrentHour(), timePicker.getCurrentMinute())); if(ii==1) { text_care_time.setText(sb); time = sb.toString(); } else { text_care_time2.setText(sb); time2 = sb.toString(); } dialog.cancel(); } }); Dialog dialog = builder.create(); dialog.show(); } } if(event.getAction()==MotionEvent.ACTION_UP){ if(v.getId()== R.id.ImageButton_back){ new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage("确定退出填写吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { care_add.this.setResult(0); dialog.dismiss(); care_add.this.finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } else if(v.getId()== R.id.care_submit){ if(type==null||time==null||time2==null) { new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage("请完善信息!") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); }else if(getIntent().getAction()=="lianxirenadd"){ dbHelper.getWritableDatabase().execSQL("insert into care_table(uid,type,time,time2,note,fname,fsex,fphone,fid)" + " values(?,?,?,?,?,?,?,?,?)", new String[]{User_id,type ,time ,time2 , note, getIntent().getStringExtra("username"),getIntent().getStringExtra("sex"), getIntent().getStringExtra("phone"), getIntent().getStringExtra("lianxirenid")}); care_add.this.finish(); } else{ if (getIntent().getAction()!=null){ fff="确定修改?"; } else{ fff="确定提交?"; } /* new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage(fff) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {*/ note=care_note.getText().toString().trim(); if (fff.equals("确定提交?")) { Intent mIntent = new Intent(); mIntent.putExtra("type", type); mIntent.putExtra("time", time); mIntent.putExtra("time2",time2); mIntent.putExtra("note",note ); // 设置 <SUF> care_add.this.setResult(1, mIntent); } else { /* dbHelper.getReadableDatabase().rawQuery("update care_table set type="+type+",time="+time+",remind="+remind+",note="+note+" where" + "uid="+userid,null);*/ dbHelper.getWritableDatabase().execSQL("update care_table set type = ?,time = ?,time2 = ?,note = ? where _id=?", new String[]{type, time, time2,note,care_id}); // Toast.makeText(care_add.this,"_id"+care_id,Toast.LENGTH_SHORT).show(); for (int i=0;i<100;i++){ if(aa.remindid[i][0]==care_id){ aa.cancelRemind(aa.remindid[i][1], care_add.this); aa.setRemind(time2,type+" "+time+note,"care_remind",0,2, care_add.this); } } Log.e("更新关爱信息","成功"); startActivity(new Intent().setClass(care_add.this, care_main.class)); } care_add.this.finish(); } } } return false; } }
0
2,576
6
3,231
8
3,352
7
3,231
8
3,941
12
false
false
false
false
false
true
34755_5
package com.cui.rectprogress; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * Created by CZH on 2017/6/15. * RectProgress */ public class RectProgress extends View { private final int VERTICAL = 1; private final int HORIZONTAL = 2; private final int defaultBgColor = 0xFf000000; private final int defaultProgressColor = 0xFFFF4081; private int bgColor = defaultBgColor; private int progressColor = defaultProgressColor; /*圆角弧度*/ private float rectRadius = 20f; /*画背景使用的Rect*/ private RectF bgRect = new RectF(); /*画进度使用的Rect*/ private RectF progressRect = new RectF(); /*背景画笔*/ private Paint bgPaint; /*进度画笔*/ private Paint progressPaint; /*进度方向*/ private int orientation = VERTICAL; private int max = 100; private int progress = 15; private Bitmap bitmap; /*icon显示区域Rect*/ private Rect srcRect; /*icon显示位置Rect*/ private Rect dstRect; private float iconPadding; /*进度百分比*/ private int percent = 0; public RectProgress(Context context) { super(context); init(context, null); } public RectProgress(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs); } public RectProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { //关闭硬件加速,不然setXfermode()可能会不生效 setLayerType(View.LAYER_TYPE_SOFTWARE, null); if (attrs != null) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RectProgress); bgColor = typedArray.getColor(R.styleable.RectProgress_bgColor, defaultBgColor); progressColor = typedArray.getColor(R.styleable.RectProgress_progressColor, defaultProgressColor); progress = typedArray.getInteger(R.styleable.RectProgress_progressValue, progress); max = typedArray.getInteger(R.styleable.RectProgress_progressMax, max); if (max <= 0) throw new RuntimeException("Max 必须大于 0"); orientation = typedArray.getInteger(R.styleable.RectProgress_progressOrientation, VERTICAL); int imgSrc = typedArray.getResourceId(R.styleable.RectProgress_iconSrc, 0); iconPadding = typedArray.getDimensionPixelSize(R.styleable.RectProgress_iconPadding, 10); rectRadius = typedArray.getDimensionPixelSize(R.styleable.RectProgress_rectRadius, 20); if (max < progress) { progress = max; } typedArray.recycle(); if (imgSrc != 0) { bitmap = ((BitmapDrawable) getResources().getDrawable(imgSrc)).getBitmap(); } } bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); bgPaint.setColor(bgColor); progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG); progressPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); progressPaint.setColor(progressColor); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); bgRect.set(getPaddingLeft() , getPaddingTop() , getWidth() - getPaddingRight() , getHeight() - getPaddingBottom()); computeProgressRect(); if (bitmap != null) { srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); int iconSideLength; if (orientation == VERTICAL) { iconSideLength = (int) (bgRect.width() - iconPadding * 2); dstRect = new Rect((int) bgRect.left + (int) iconPadding , (int) (bgRect.bottom - iconSideLength - iconPadding) , (int) bgRect.right - (int) iconPadding , (int) bgRect.bottom - (int) iconPadding); } else { iconSideLength = (int) (bgRect.height() - iconPadding * 2); dstRect = new Rect((int) bgRect.left + (int) iconPadding , (int) (bgRect.bottom - iconPadding - iconSideLength) , (int) (bgRect.left + iconPadding + iconSideLength) , (int) (bgRect.bottom - iconPadding)); } } } @Override protected void onDraw(Canvas canvas) { int canvasWidth = canvas.getWidth(); int canvasHeight = canvas.getHeight(); int layerId = canvas.saveLayer(0, 0, canvasWidth, canvasHeight, null, Canvas.ALL_SAVE_FLAG); { bgPaint.setColor(bgColor); // draw the background of progress canvas.drawRoundRect(bgRect, rectRadius, rectRadius, bgPaint); // draw progress canvas.drawRect(progressRect, progressPaint); bgPaint.setXfermode(null); if (bitmap != null) { //draw icon canvas.drawBitmap(bitmap, srcRect, dstRect, bgPaint); } } canvas.restoreToCount(layerId); // TODO: 弄明白为什么在xml预览中,canvas.restoreToCount // TODO: 会导致后续的canvas对象为空 但canvas.restore方法则不会导致这个问题 // canvas.restore(); // canvas.save(); } @Override public boolean onTouchEvent(MotionEvent event) { //在家进度条内才执行操作 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (bgRect.contains(event.getX(), event.getY())) { //按下时,在进度内才执行操作 handleTouch(event); invalidate(); return true; } break; case MotionEvent.ACTION_MOVE: handleTouch(event); invalidate(); break; } invalidate(); return super.onTouchEvent(event); } private void handleTouch(MotionEvent event) { if (orientation == VERTICAL) { if (event.getY() < bgRect.top) { //触点超出Progress顶部 progressRect.top = bgRect.top; } else if (event.getY() > bgRect.bottom) { //触点超过Progress底部 progressRect.top = bgRect.bottom; } else { progressRect.top = event.getY(); } int tmp = (int) ((progressRect.height() / bgRect.height()) * 100); if (percent != tmp) { percent = tmp; progress = percent * max / 100; if (changedListener != null) changedListener.onProgressChanged(progress, percent); } } else { if (event.getX() > bgRect.right) { //触点超出Progress右端 progressRect.right = bgRect.right; } else if (event.getX() < bgRect.left) { //触点超出Progress左端 progressRect.right = bgRect.left; } else { progressRect.right = event.getX(); } int tmp = (int) ((progressRect.width() / bgRect.width()) * 100); if (percent != tmp) { percent = tmp; progress = percent * max / 100; if (changedListener != null) changedListener.onProgressChanged(progress, percent); } } } private OnProgressChangedListener changedListener; public void setChangedListener(OnProgressChangedListener changedListener) { this.changedListener = changedListener; } public interface OnProgressChangedListener { void onProgressChanged(int currentValue, int percent); } public void setMax(int m) { if (max <= 0) throw new RuntimeException("Max 必须大于 0"); max = m; } public void setProgress(int p) { int oldProgress = progress; progress = p; if (max < progress) { progress = max; } else if (progress < 0) progress = 0; startProgressAnim(oldProgress); } private ValueAnimator valueAnimator; /**/ private void startProgressAnim(int oldProgress) { if (valueAnimator != null && valueAnimator.isRunning()) { valueAnimator.cancel(); } valueAnimator = ValueAnimator.ofInt(oldProgress, progress); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { progress = (int) animation.getAnimatedValue(); computeProgressRect(); invalidate(); } }); valueAnimator.setDuration(1000); valueAnimator.start(); } /** * 计算进度Progress */ private void computeProgressRect() { if (orientation == VERTICAL) { progressRect.set(bgRect.left , bgRect.bottom - progress * bgRect.height() / max , bgRect.right , bgRect.bottom); } else { progressRect.set(bgRect.left , bgRect.top , bgRect.left + progress * bgRect.width() / max , bgRect.bottom); } } }
CuiZhaoHui/IOS11RectProgress
rectprogress/src/main/java/com/cui/rectprogress/RectProgress.java
2,370
/*进度画笔*/
block_comment
zh-cn
package com.cui.rectprogress; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * Created by CZH on 2017/6/15. * RectProgress */ public class RectProgress extends View { private final int VERTICAL = 1; private final int HORIZONTAL = 2; private final int defaultBgColor = 0xFf000000; private final int defaultProgressColor = 0xFFFF4081; private int bgColor = defaultBgColor; private int progressColor = defaultProgressColor; /*圆角弧度*/ private float rectRadius = 20f; /*画背景使用的Rect*/ private RectF bgRect = new RectF(); /*画进度使用的Rect*/ private RectF progressRect = new RectF(); /*背景画笔*/ private Paint bgPaint; /*进度画 <SUF>*/ private Paint progressPaint; /*进度方向*/ private int orientation = VERTICAL; private int max = 100; private int progress = 15; private Bitmap bitmap; /*icon显示区域Rect*/ private Rect srcRect; /*icon显示位置Rect*/ private Rect dstRect; private float iconPadding; /*进度百分比*/ private int percent = 0; public RectProgress(Context context) { super(context); init(context, null); } public RectProgress(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs); } public RectProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { //关闭硬件加速,不然setXfermode()可能会不生效 setLayerType(View.LAYER_TYPE_SOFTWARE, null); if (attrs != null) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RectProgress); bgColor = typedArray.getColor(R.styleable.RectProgress_bgColor, defaultBgColor); progressColor = typedArray.getColor(R.styleable.RectProgress_progressColor, defaultProgressColor); progress = typedArray.getInteger(R.styleable.RectProgress_progressValue, progress); max = typedArray.getInteger(R.styleable.RectProgress_progressMax, max); if (max <= 0) throw new RuntimeException("Max 必须大于 0"); orientation = typedArray.getInteger(R.styleable.RectProgress_progressOrientation, VERTICAL); int imgSrc = typedArray.getResourceId(R.styleable.RectProgress_iconSrc, 0); iconPadding = typedArray.getDimensionPixelSize(R.styleable.RectProgress_iconPadding, 10); rectRadius = typedArray.getDimensionPixelSize(R.styleable.RectProgress_rectRadius, 20); if (max < progress) { progress = max; } typedArray.recycle(); if (imgSrc != 0) { bitmap = ((BitmapDrawable) getResources().getDrawable(imgSrc)).getBitmap(); } } bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); bgPaint.setColor(bgColor); progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG); progressPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); progressPaint.setColor(progressColor); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); bgRect.set(getPaddingLeft() , getPaddingTop() , getWidth() - getPaddingRight() , getHeight() - getPaddingBottom()); computeProgressRect(); if (bitmap != null) { srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); int iconSideLength; if (orientation == VERTICAL) { iconSideLength = (int) (bgRect.width() - iconPadding * 2); dstRect = new Rect((int) bgRect.left + (int) iconPadding , (int) (bgRect.bottom - iconSideLength - iconPadding) , (int) bgRect.right - (int) iconPadding , (int) bgRect.bottom - (int) iconPadding); } else { iconSideLength = (int) (bgRect.height() - iconPadding * 2); dstRect = new Rect((int) bgRect.left + (int) iconPadding , (int) (bgRect.bottom - iconPadding - iconSideLength) , (int) (bgRect.left + iconPadding + iconSideLength) , (int) (bgRect.bottom - iconPadding)); } } } @Override protected void onDraw(Canvas canvas) { int canvasWidth = canvas.getWidth(); int canvasHeight = canvas.getHeight(); int layerId = canvas.saveLayer(0, 0, canvasWidth, canvasHeight, null, Canvas.ALL_SAVE_FLAG); { bgPaint.setColor(bgColor); // draw the background of progress canvas.drawRoundRect(bgRect, rectRadius, rectRadius, bgPaint); // draw progress canvas.drawRect(progressRect, progressPaint); bgPaint.setXfermode(null); if (bitmap != null) { //draw icon canvas.drawBitmap(bitmap, srcRect, dstRect, bgPaint); } } canvas.restoreToCount(layerId); // TODO: 弄明白为什么在xml预览中,canvas.restoreToCount // TODO: 会导致后续的canvas对象为空 但canvas.restore方法则不会导致这个问题 // canvas.restore(); // canvas.save(); } @Override public boolean onTouchEvent(MotionEvent event) { //在家进度条内才执行操作 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (bgRect.contains(event.getX(), event.getY())) { //按下时,在进度内才执行操作 handleTouch(event); invalidate(); return true; } break; case MotionEvent.ACTION_MOVE: handleTouch(event); invalidate(); break; } invalidate(); return super.onTouchEvent(event); } private void handleTouch(MotionEvent event) { if (orientation == VERTICAL) { if (event.getY() < bgRect.top) { //触点超出Progress顶部 progressRect.top = bgRect.top; } else if (event.getY() > bgRect.bottom) { //触点超过Progress底部 progressRect.top = bgRect.bottom; } else { progressRect.top = event.getY(); } int tmp = (int) ((progressRect.height() / bgRect.height()) * 100); if (percent != tmp) { percent = tmp; progress = percent * max / 100; if (changedListener != null) changedListener.onProgressChanged(progress, percent); } } else { if (event.getX() > bgRect.right) { //触点超出Progress右端 progressRect.right = bgRect.right; } else if (event.getX() < bgRect.left) { //触点超出Progress左端 progressRect.right = bgRect.left; } else { progressRect.right = event.getX(); } int tmp = (int) ((progressRect.width() / bgRect.width()) * 100); if (percent != tmp) { percent = tmp; progress = percent * max / 100; if (changedListener != null) changedListener.onProgressChanged(progress, percent); } } } private OnProgressChangedListener changedListener; public void setChangedListener(OnProgressChangedListener changedListener) { this.changedListener = changedListener; } public interface OnProgressChangedListener { void onProgressChanged(int currentValue, int percent); } public void setMax(int m) { if (max <= 0) throw new RuntimeException("Max 必须大于 0"); max = m; } public void setProgress(int p) { int oldProgress = progress; progress = p; if (max < progress) { progress = max; } else if (progress < 0) progress = 0; startProgressAnim(oldProgress); } private ValueAnimator valueAnimator; /**/ private void startProgressAnim(int oldProgress) { if (valueAnimator != null && valueAnimator.isRunning()) { valueAnimator.cancel(); } valueAnimator = ValueAnimator.ofInt(oldProgress, progress); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { progress = (int) animation.getAnimatedValue(); computeProgressRect(); invalidate(); } }); valueAnimator.setDuration(1000); valueAnimator.start(); } /** * 计算进度Progress */ private void computeProgressRect() { if (orientation == VERTICAL) { progressRect.set(bgRect.left , bgRect.bottom - progress * bgRect.height() / max , bgRect.right , bgRect.bottom); } else { progressRect.set(bgRect.left , bgRect.top , bgRect.left + progress * bgRect.width() / max , bgRect.bottom); } } }
0
2,098
5
2,370
6
2,511
5
2,370
6
2,877
8
false
false
false
false
false
true
49287_2
//给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。 // //我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。 //说明: n 的范围为 [1, 10,000]。 import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; public class NotIncreArr { //n-1 public static boolean checkPossibility(int[] nums) { int count = 0; for (int i = 1; i < nums.length; i++) { if (nums[i] < nums[i - 1]) { count++; if (count > 1) { return false; } int privous = i > 1 ? nums[i - 2] : 0; int after = i < nums.length - 1 ? nums[i + 1] : 10000; if (nums[i - 1] > after && nums[i] < privous) { return false; } } } return true; } public static void main(String[] args) { // Scanner in = new Scanner(System.in); // String inputStr = in.nextLine(); // StringTokenizer stringTokenizer = new StringTokenizer(inputStr," ",false); // ArrayList<String> arr = new ArrayList<>(); // while(stringTokenizer.hasMoreElements()){ // arr.add(stringTokenizer.nextToken()); // } // int[] arr = {4,2,3}; System.out.println(checkPossibility(arr)); //checkPossibility(arr); } }
Currycurrycurry/FDSS_Algorithm
java/src/NotIncreArr.java
438
//说明: n 的范围为 [1, 10,000]。
line_comment
zh-cn
//给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。 // //我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。 //说明 <SUF> import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; public class NotIncreArr { //n-1 public static boolean checkPossibility(int[] nums) { int count = 0; for (int i = 1; i < nums.length; i++) { if (nums[i] < nums[i - 1]) { count++; if (count > 1) { return false; } int privous = i > 1 ? nums[i - 2] : 0; int after = i < nums.length - 1 ? nums[i + 1] : 10000; if (nums[i - 1] > after && nums[i] < privous) { return false; } } } return true; } public static void main(String[] args) { // Scanner in = new Scanner(System.in); // String inputStr = in.nextLine(); // StringTokenizer stringTokenizer = new StringTokenizer(inputStr," ",false); // ArrayList<String> arr = new ArrayList<>(); // while(stringTokenizer.hasMoreElements()){ // arr.add(stringTokenizer.nextToken()); // } // int[] arr = {4,2,3}; System.out.println(checkPossibility(arr)); //checkPossibility(arr); } }
0
380
20
438
20
443
20
438
20
539
27
false
false
false
false
false
true
41830_0
package com.example.lukedict; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class ChatActivity extends AppCompatActivity { private List<Msg> msgList = new ArrayList<>(); private EditText inputText; private Button send; private RecyclerView msgRecyclerView; private MsgAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); initMsgs();//初始化消息数据 inputText = (EditText)findViewById(R.id.input_text); send = (Button) findViewById(R.id.send); msgRecyclerView = (RecyclerView)findViewById(R.id.msg_recycler_view); LinearLayoutManager layoutManager = new LinearLayoutManager(this); msgRecyclerView.setLayoutManager(layoutManager); layoutManager.setOrientation(RecyclerView.VERTICAL); adapter = new MsgAdapter(msgList); msgRecyclerView.setAdapter(adapter); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String content = inputText.getText().toString(); if(!"".equals(content)){ Msg msg = new Msg(content,Msg.TYPE_SENT); msgList.add(msg); adapter.notifyItemInserted(msgList.size() - 1); //当有新消息时,刷新RecycleView中的显示 msgRecyclerView.scrollToPosition(msgList.size() - 1); //将RecycleView定位到最后一行 inputText.setText("");//清空输入框中的内容 } } }); showActionbar(); } private void showActionbar() { ActionBar actionBar = this.getSupportActionBar();//定义actionbar上的返回箭头 actionBar.setTitle("客服"); actionBar.setDisplayHomeAsUpEnabled(true); } public boolean onOptionsItemSelected(MenuItem item) {//定义actionbar上的返回箭头 if(item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } public class Msg{ public static final int TYPE_RECEIVED = 0; public static final int TYPE_SENT = 1; private String content; private int type; public Msg(String content, int type){ this.content = content; this.type = type; } public String getContent(){ return content; } public int getType(){ return type; } } private void initMsgs(){ Msg msg1 = new Msg("你好!",Msg.TYPE_RECEIVED); msgList.add(msg1); Msg msg2 = new Msg("欢迎使用Luke English!",Msg.TYPE_RECEIVED); msgList.add(msg2); Msg msg3 = new Msg("我是客服小苏,很高兴为你服务!有事请留言,我会尽快回复",Msg.TYPE_RECEIVED); msgList.add(msg3); } }
Curzsu/LukeDict
app/src/main/java/com/example/lukedict/ChatActivity.java
794
//初始化消息数据
line_comment
zh-cn
package com.example.lukedict; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class ChatActivity extends AppCompatActivity { private List<Msg> msgList = new ArrayList<>(); private EditText inputText; private Button send; private RecyclerView msgRecyclerView; private MsgAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); initMsgs();//初始 <SUF> inputText = (EditText)findViewById(R.id.input_text); send = (Button) findViewById(R.id.send); msgRecyclerView = (RecyclerView)findViewById(R.id.msg_recycler_view); LinearLayoutManager layoutManager = new LinearLayoutManager(this); msgRecyclerView.setLayoutManager(layoutManager); layoutManager.setOrientation(RecyclerView.VERTICAL); adapter = new MsgAdapter(msgList); msgRecyclerView.setAdapter(adapter); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String content = inputText.getText().toString(); if(!"".equals(content)){ Msg msg = new Msg(content,Msg.TYPE_SENT); msgList.add(msg); adapter.notifyItemInserted(msgList.size() - 1); //当有新消息时,刷新RecycleView中的显示 msgRecyclerView.scrollToPosition(msgList.size() - 1); //将RecycleView定位到最后一行 inputText.setText("");//清空输入框中的内容 } } }); showActionbar(); } private void showActionbar() { ActionBar actionBar = this.getSupportActionBar();//定义actionbar上的返回箭头 actionBar.setTitle("客服"); actionBar.setDisplayHomeAsUpEnabled(true); } public boolean onOptionsItemSelected(MenuItem item) {//定义actionbar上的返回箭头 if(item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } public class Msg{ public static final int TYPE_RECEIVED = 0; public static final int TYPE_SENT = 1; private String content; private int type; public Msg(String content, int type){ this.content = content; this.type = type; } public String getContent(){ return content; } public int getType(){ return type; } } private void initMsgs(){ Msg msg1 = new Msg("你好!",Msg.TYPE_RECEIVED); msgList.add(msg1); Msg msg2 = new Msg("欢迎使用Luke English!",Msg.TYPE_RECEIVED); msgList.add(msg2); Msg msg3 = new Msg("我是客服小苏,很高兴为你服务!有事请留言,我会尽快回复",Msg.TYPE_RECEIVED); msgList.add(msg3); } }
0
633
4
794
4
825
4
794
4
993
8
false
false
false
false
false
true
18610_1
package top.strelitzia.service; import net.mamoe.mirai.Bot; import net.mamoe.mirai.contact.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import top.angelinaBot.annotation.AngelinaFriend; import top.angelinaBot.annotation.AngelinaGroup; import top.angelinaBot.model.MessageInfo; import top.angelinaBot.model.ReplayInfo; import top.strelitzia.dao.AdminUserMapper; import top.strelitzia.dao.GroupAdminInfoMapper; import top.strelitzia.dao.UserFoundMapper; import top.strelitzia.model.AdminUserInfo; import top.strelitzia.model.UserFoundInfo; import top.strelitzia.util.AdminUtil; import java.util.List; import java.util.Random; import java.util.stream.Collectors; /** * @author Cuthbert * @Date 2022/6/21 22:56 **/ @Service public class TodayWife { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TodayWife.class); @Autowired private UserFoundMapper userFoundMapper; @Autowired private AdminUserMapper adminUserMapper; /*编辑指令用法 * *所有功能都需要在最前面加上bot名今日老婆,且需要有step权限 * 重置:将你的wife以及wife的群号设置为0 * qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号 * 重置+qq号:将指定qq的wife以及wife的群号设置为0 * qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号 * qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号 * */ @AngelinaFriend(keyWords = "老婆") @AngelinaGroup(keyWords = "今日老婆" , description = "从本群中随机挑选一位幸运群友作为你今日的老婆") public ReplayInfo todayWife(MessageInfo messageInfo) { //准备工作 ReplayInfo replayInfo = new ReplayInfo(messageInfo); StringBuilder reply = new StringBuilder("*警告:请勿用此功能刷屏*\n" + messageInfo.getName() + ",\n"); UserFoundInfo userFoundInfo = userFoundMapper.selectUserFoundByQQ(messageInfo.getQq()); if (userFoundInfo == null) { userFoundInfo = new UserFoundInfo(); userFoundInfo.setQq(messageInfo.getQq()); userFoundInfo.setFoundCount(0); userFoundInfo.setTodayCount(0); userFoundInfo.setTodayWife(0L); userFoundInfo.setWifeGroup(0L); } //判断是否为编辑指令 if (messageInfo.getArgs().size() == 2) { String str = messageInfo.getArgs().get(1); if (str.equals("菜单")){ reply = new StringBuilder( "编辑指令用法\n" + " *所有功能都需要在最前面加上bot名今日老婆\n" + " *所有功能仅有群主和管理员,或step权限者才能使用\n" + " 重置:将你的wife以及wife的群号设置为0\n" + " qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号\n" + " 重置+qq号:将指定qq的wife以及wife的群号设置为0\n" + " qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号\n" + " qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号\n" + "eg.稀音今日老婆 重置 11111\n 稀音今日老婆 11111 22222" ); }else { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) { if (str.equals("重置") || str.equals("reset")) { userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), 0L, 0L); reply.append("你的今日老婆已经重置啦"); } else if (str.equals("重置本群")) { userFoundMapper.resetGroupWife(messageInfo.getGroupId()); reply = new StringBuilder("已重置本群"); } else { Long qq = Long.valueOf(str); userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId()); reply = new StringBuilder("设置完成"); } } else { reply = new StringBuilder("您没有权限编辑哦"); } } } else if (messageInfo.getArgs().size() == 3) { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) { String str1 = messageInfo.getArgs().get(1); String str2 = messageInfo.getArgs().get(2); if (str1.equals("重置") || str1.equals("reset")){ Long qq = Long.valueOf(str2); userFoundMapper.updateTodayWifeByQq(qq, 0L, 0L); reply = new StringBuilder("重置完成"); }else { Long qq = Long.valueOf(str1); Long wife = Long.valueOf(str2); userFoundMapper.updateTodayWifeByQq(qq, wife, messageInfo.getGroupId()); reply = new StringBuilder("设置完成"); } } else { reply = new StringBuilder("您没有权限编辑哦"); } } else if (messageInfo.getArgs().size() == 4) { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b) { Long qq = Long.valueOf(messageInfo.getArgs().get(1)); Long wife = Long.valueOf(messageInfo.getArgs().get(2)); Long group = Long.valueOf(messageInfo.getArgs().get(3)); userFoundMapper.updateTodayWifeByQq(qq, wife, group); reply = new StringBuilder("设置完成"); } else { reply = new StringBuilder("您没有权限编辑哦"); } }else { //查询今日是否抽取过老婆 Long today = userFoundInfo.getTodayWife(); Long group = userFoundInfo.getWifeGroup(); if (group.equals(messageInfo.getGroupId()) || group.equals(0L)) { Long qq = null; if (group.equals(0L)) { //今日未抽取 //获取MemberList并通过stream流提取qq,随机抽取一个 ContactList<NormalMember> qqList = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).getMembers(); List<Long> list = qqList.stream().map(Member::getId).collect(Collectors.toList()); list.add(messageInfo.getLoginQq()); Random random = new Random(); int n = random.nextInt(list.size()); qq = list.get(n); reply.append("你今天的老婆是:"); userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId()); } else if (group.equals(messageInfo.getGroupId())) { //在本群抽取过了 qq = userFoundInfo.getTodayWife(); reply.append("你今天已经抽取过老婆啦!" + "你的老婆是:"); } replayInfo.setReplayImg("http://q.qlogo.cn/headimg_dl?dst_uin=" + qq + "&spec=5"); String name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getNameCard(); if (name.isEmpty()) { name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getRemark(); } reply.append(name + "(" + qq + ")"); } else { //在其他群抽取过了 String groupName = Bot.getInstance(messageInfo.getLoginQq()).getGroup(group).getName(); reply.append("你今天已经在别的群(" + groupName + ")抽取过老婆啦"); } } replayInfo.setReplayMessage(reply.toString()); return replayInfo; } }
CuthbertTsao/SceneBot
src/main/java/top/strelitzia/service/TodayWife.java
2,238
/*编辑指令用法 * *所有功能都需要在最前面加上bot名今日老婆,且需要有step权限 * 重置:将你的wife以及wife的群号设置为0 * qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号 * 重置+qq号:将指定qq的wife以及wife的群号设置为0 * qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号 * qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号 * */
block_comment
zh-cn
package top.strelitzia.service; import net.mamoe.mirai.Bot; import net.mamoe.mirai.contact.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import top.angelinaBot.annotation.AngelinaFriend; import top.angelinaBot.annotation.AngelinaGroup; import top.angelinaBot.model.MessageInfo; import top.angelinaBot.model.ReplayInfo; import top.strelitzia.dao.AdminUserMapper; import top.strelitzia.dao.GroupAdminInfoMapper; import top.strelitzia.dao.UserFoundMapper; import top.strelitzia.model.AdminUserInfo; import top.strelitzia.model.UserFoundInfo; import top.strelitzia.util.AdminUtil; import java.util.List; import java.util.Random; import java.util.stream.Collectors; /** * @author Cuthbert * @Date 2022/6/21 22:56 **/ @Service public class TodayWife { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TodayWife.class); @Autowired private UserFoundMapper userFoundMapper; @Autowired private AdminUserMapper adminUserMapper; /*编辑指 <SUF>*/ @AngelinaFriend(keyWords = "老婆") @AngelinaGroup(keyWords = "今日老婆" , description = "从本群中随机挑选一位幸运群友作为你今日的老婆") public ReplayInfo todayWife(MessageInfo messageInfo) { //准备工作 ReplayInfo replayInfo = new ReplayInfo(messageInfo); StringBuilder reply = new StringBuilder("*警告:请勿用此功能刷屏*\n" + messageInfo.getName() + ",\n"); UserFoundInfo userFoundInfo = userFoundMapper.selectUserFoundByQQ(messageInfo.getQq()); if (userFoundInfo == null) { userFoundInfo = new UserFoundInfo(); userFoundInfo.setQq(messageInfo.getQq()); userFoundInfo.setFoundCount(0); userFoundInfo.setTodayCount(0); userFoundInfo.setTodayWife(0L); userFoundInfo.setWifeGroup(0L); } //判断是否为编辑指令 if (messageInfo.getArgs().size() == 2) { String str = messageInfo.getArgs().get(1); if (str.equals("菜单")){ reply = new StringBuilder( "编辑指令用法\n" + " *所有功能都需要在最前面加上bot名今日老婆\n" + " *所有功能仅有群主和管理员,或step权限者才能使用\n" + " 重置:将你的wife以及wife的群号设置为0\n" + " qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号\n" + " 重置+qq号:将指定qq的wife以及wife的群号设置为0\n" + " qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号\n" + " qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号\n" + "eg.稀音今日老婆 重置 11111\n 稀音今日老婆 11111 22222" ); }else { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) { if (str.equals("重置") || str.equals("reset")) { userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), 0L, 0L); reply.append("你的今日老婆已经重置啦"); } else if (str.equals("重置本群")) { userFoundMapper.resetGroupWife(messageInfo.getGroupId()); reply = new StringBuilder("已重置本群"); } else { Long qq = Long.valueOf(str); userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId()); reply = new StringBuilder("设置完成"); } } else { reply = new StringBuilder("您没有权限编辑哦"); } } } else if (messageInfo.getArgs().size() == 3) { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) { String str1 = messageInfo.getArgs().get(1); String str2 = messageInfo.getArgs().get(2); if (str1.equals("重置") || str1.equals("reset")){ Long qq = Long.valueOf(str2); userFoundMapper.updateTodayWifeByQq(qq, 0L, 0L); reply = new StringBuilder("重置完成"); }else { Long qq = Long.valueOf(str1); Long wife = Long.valueOf(str2); userFoundMapper.updateTodayWifeByQq(qq, wife, messageInfo.getGroupId()); reply = new StringBuilder("设置完成"); } } else { reply = new StringBuilder("您没有权限编辑哦"); } } else if (messageInfo.getArgs().size() == 4) { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b) { Long qq = Long.valueOf(messageInfo.getArgs().get(1)); Long wife = Long.valueOf(messageInfo.getArgs().get(2)); Long group = Long.valueOf(messageInfo.getArgs().get(3)); userFoundMapper.updateTodayWifeByQq(qq, wife, group); reply = new StringBuilder("设置完成"); } else { reply = new StringBuilder("您没有权限编辑哦"); } }else { //查询今日是否抽取过老婆 Long today = userFoundInfo.getTodayWife(); Long group = userFoundInfo.getWifeGroup(); if (group.equals(messageInfo.getGroupId()) || group.equals(0L)) { Long qq = null; if (group.equals(0L)) { //今日未抽取 //获取MemberList并通过stream流提取qq,随机抽取一个 ContactList<NormalMember> qqList = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).getMembers(); List<Long> list = qqList.stream().map(Member::getId).collect(Collectors.toList()); list.add(messageInfo.getLoginQq()); Random random = new Random(); int n = random.nextInt(list.size()); qq = list.get(n); reply.append("你今天的老婆是:"); userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId()); } else if (group.equals(messageInfo.getGroupId())) { //在本群抽取过了 qq = userFoundInfo.getTodayWife(); reply.append("你今天已经抽取过老婆啦!" + "你的老婆是:"); } replayInfo.setReplayImg("http://q.qlogo.cn/headimg_dl?dst_uin=" + qq + "&spec=5"); String name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getNameCard(); if (name.isEmpty()) { name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getRemark(); } reply.append(name + "(" + qq + ")"); } else { //在其他群抽取过了 String groupName = Bot.getInstance(messageInfo.getLoginQq()).getGroup(group).getName(); reply.append("你今天已经在别的群(" + groupName + ")抽取过老婆啦"); } } replayInfo.setReplayMessage(reply.toString()); return replayInfo; } }
0
1,940
169
2,220
188
2,178
167
2,220
188
2,792
252
true
true
true
true
true
false
29284_0
/** * 题目描述 * 给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1,m<=n),每段绳子的长度记为k[1],...,k[m]。请问k[1]x...xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。 * 输入描述: * 输入一个数n,意义见题面。(2 <= n <= 60) * 返回值描述: * 输出答案。 * 示例1 * 输入 * 8 * 返回值 * 18 */ public class Solution { public int cutRope(int target) { if (target<2){ return 0; }if(target==2){ return 1; }if (target==3){ return 2; } int result = 1; for(int i=0;i<target/3-1;i++){ result *=3; } if (target%3==1){ result*=4; }else if(target%3==2){ result*=6; }else { result*=3; } return result; } }
Cweiping/AlgorithmInterview
codingInterviews/CutRope.java
338
/** * 题目描述 * 给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1,m<=n),每段绳子的长度记为k[1],...,k[m]。请问k[1]x...xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。 * 输入描述: * 输入一个数n,意义见题面。(2 <= n <= 60) * 返回值描述: * 输出答案。 * 示例1 * 输入 * 8 * 返回值 * 18 */
block_comment
zh-cn
/** * 题目描 <SUF>*/ public class Solution { public int cutRope(int target) { if (target<2){ return 0; }if(target==2){ return 1; }if (target==3){ return 2; } int result = 1; for(int i=0;i<target/3-1;i++){ result *=3; } if (target%3==1){ result*=4; }else if(target%3==2){ result*=6; }else { result*=3; } return result; } }
0
302
173
338
202
330
173
338
202
439
277
true
true
true
true
true
false
22898_6
/** * Copyright (C), 2018-2019, csust * FileName: Conn * Author: Cwolf9 * Date: 2019/06/21 14:54 * Description: * History: * <author> <time> <version> <desc> * Cwolf9 2019/06/21 2018.3 * <p> * 〈可怕的是比你强的人比你还努力〉 * 〈〉 * * @author Cwolf9 * @create 2019/06/21 * @since 1.0.0 */ /** * 〈可怕的是比你强的人比你还努力〉 * 〈〉 * * @author Cwolf9 * @create 2019/06/21 * @since 1.0.0 */ package com.demo.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /* * 数据库连接 lhroot */ public class Conn { public static void main(String[] args) { Connection con; //jdbc驱动 String driver="com.mysql.cj.jdbc.Driver"; //这里我的数据库是bookcity String url="jdbc:mysql://localhost:3306/bookcity?useSSL=false&serverTimezone=UTC"; String user="root"; String password="lhroot"; try { //注册JDBC驱动程序 Class.forName(driver); //建立连接 con = DriverManager.getConnection(url, user, password); if (!con.isClosed()) { System.out.println("数据库连接成功"); } con.close(); } catch (ClassNotFoundException e) { System.out.println("数据库驱动没有安装"); } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } } }
Cwolf9/bookcity
src/main/java/com/demo/util/Conn.java
502
//注册JDBC驱动程序
line_comment
zh-cn
/** * Copyright (C), 2018-2019, csust * FileName: Conn * Author: Cwolf9 * Date: 2019/06/21 14:54 * Description: * History: * <author> <time> <version> <desc> * Cwolf9 2019/06/21 2018.3 * <p> * 〈可怕的是比你强的人比你还努力〉 * 〈〉 * * @author Cwolf9 * @create 2019/06/21 * @since 1.0.0 */ /** * 〈可怕的是比你强的人比你还努力〉 * 〈〉 * * @author Cwolf9 * @create 2019/06/21 * @since 1.0.0 */ package com.demo.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /* * 数据库连接 lhroot */ public class Conn { public static void main(String[] args) { Connection con; //jdbc驱动 String driver="com.mysql.cj.jdbc.Driver"; //这里我的数据库是bookcity String url="jdbc:mysql://localhost:3306/bookcity?useSSL=false&serverTimezone=UTC"; String user="root"; String password="lhroot"; try { //注册 <SUF> Class.forName(driver); //建立连接 con = DriverManager.getConnection(url, user, password); if (!con.isClosed()) { System.out.println("数据库连接成功"); } con.close(); } catch (ClassNotFoundException e) { System.out.println("数据库驱动没有安装"); } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } } }
0
433
6
502
5
494
5
502
5
596
13
false
false
false
false
false
true
12341_3
package com.chad.baserecyclerviewadapterhelper.utils; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; public class Tips { /** * 显示 Toast * @param message 提示信息 */ public static void show(String message) { show(message, Toast.LENGTH_SHORT); } /** * 显示 Toast * @param message 提示信息 * @param duration 显示时间长短 */ public static void show(String message, int duration) { Toast toast = new Toast(AppUtils.INSTANCE.getApp()); toast.setDuration(duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(createTextToastView(message)); toast.show(); } /** * 创建自定义 Toast View * * @param message 文本消息 * @return View */ private static View createTextToastView(String message) { // 画圆角矩形背景 float rc = dp2px(6); RoundRectShape shape = new RoundRectShape(new float[]{rc, rc, rc, rc, rc, rc, rc, rc}, null, null); ShapeDrawable drawable = new ShapeDrawable(shape); drawable.getPaint().setColor(Color.argb(225, 240, 240, 240)); drawable.getPaint().setStyle(Paint.Style.FILL); drawable.getPaint().setAntiAlias(true); drawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG); // 创建View FrameLayout layout = new FrameLayout(AppUtils.INSTANCE.getApp()); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layout.setLayoutParams(layoutParams); layout.setPadding(dp2px(16), dp2px(12), dp2px(16), dp2px(12)); layout.setBackground(drawable); TextView textView = new TextView(AppUtils.INSTANCE.getApp()); textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)); textView.setTextSize(15); textView.setText(message); textView.setLineSpacing(dp2px(4), 1f); textView.setTextColor(Color.BLACK); layout.addView(textView); return layout; } private static int dp2px(float dpValue) { final float scale = AppUtils.INSTANCE.getApp().getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }
CymChad/BaseRecyclerViewAdapterHelper
app/src/main/java/com/chad/baserecyclerviewadapterhelper/utils/Tips.java
680
// 画圆角矩形背景
line_comment
zh-cn
package com.chad.baserecyclerviewadapterhelper.utils; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; public class Tips { /** * 显示 Toast * @param message 提示信息 */ public static void show(String message) { show(message, Toast.LENGTH_SHORT); } /** * 显示 Toast * @param message 提示信息 * @param duration 显示时间长短 */ public static void show(String message, int duration) { Toast toast = new Toast(AppUtils.INSTANCE.getApp()); toast.setDuration(duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(createTextToastView(message)); toast.show(); } /** * 创建自定义 Toast View * * @param message 文本消息 * @return View */ private static View createTextToastView(String message) { // 画圆 <SUF> float rc = dp2px(6); RoundRectShape shape = new RoundRectShape(new float[]{rc, rc, rc, rc, rc, rc, rc, rc}, null, null); ShapeDrawable drawable = new ShapeDrawable(shape); drawable.getPaint().setColor(Color.argb(225, 240, 240, 240)); drawable.getPaint().setStyle(Paint.Style.FILL); drawable.getPaint().setAntiAlias(true); drawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG); // 创建View FrameLayout layout = new FrameLayout(AppUtils.INSTANCE.getApp()); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layout.setLayoutParams(layoutParams); layout.setPadding(dp2px(16), dp2px(12), dp2px(16), dp2px(12)); layout.setBackground(drawable); TextView textView = new TextView(AppUtils.INSTANCE.getApp()); textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)); textView.setTextSize(15); textView.setText(message); textView.setLineSpacing(dp2px(4), 1f); textView.setTextColor(Color.BLACK); layout.addView(textView); return layout; } private static int dp2px(float dpValue) { final float scale = AppUtils.INSTANCE.getApp().getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }
0
571
8
680
8
708
7
680
8
852
15
false
false
false
false
false
true
41236_3
package liuyuboo; import java.util.LinkedList; public class JZ27 { class Node { public int val; public Node left; public Node right; public Node() { } public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right) { val = _val; left = _left; right = _right; } } //目的:转化成排序的循环双向链表 Node head = new Node(); public Node treeToDoublyList(Node root) { //结果形式--和中序遍历类似 //结果链表是一个由中序顺序组织的链表 //所谓链表和bst都是节点靠指针维护的,这个结构是一致的,所以存在就地转换的可能 //这个处理工程,只涉及两个点角色之间的指针调整,其他部分不需要===》需要head cur两个小弟 //cur 代表当前节点,而这个当前节点是中序顺序组织的节点;也就是中序遍历框架中间位置,会自然拿到当前节点 //head 这里就要记录前一个节点 //前一个节点与当前节点的互动,只有三部分:两部分指针调整-前一个后指针指向下一个;后一个前指针指向前一个;记得更新head,来保证始终维持root的前一个节点 Node begin = head; inOrder(root); Node cur = ret; while (cur.left != begin) { cur = cur.left; } return cur; } Node ret = null; public void inOrder(Node root) { if (root == null) { return; } inOrder(root.left); head.right = root; root.left = head; head = head.right; ret = root; inOrder(root.right); } //分化瓦解--三个部分,每个部分都具有和上级同样的问题实质 /* Node lastNode = null; convertNode(root,lastNode); Node headNode = lastNode; while (headNode != null && headNode.left != null) { headNode = headNode.left; } return headNode; } public void convertNode(Node root,Node lastNode) { if (root == null) { return; } Node current = root; if (current.left != null) { convertNode(current.left,lastNode); } current.left = lastNode; if (lastNode != null) { lastNode.right = current; } lastNode = current; if (current.right != null) { convertNode(current.right,lastNode); } }*/ /* if (root.left == null) //小问题:左子树 leftTo(root.left).right = root; //小问题:右子树 rightTo(root.right).left = root; return root; } //返回左子树最大节点 public Node leftTo(Node root) { if(root.left == null && root.right == null) { return root; } leftTo(root.left).right = root; rightTo(root.right).left = root; return findMax(root.right); } public Node findMax(Node root) { if(root.right == null) { return root; } return findMax(root.right); } public Node findMin(Node root) { if (root.left == null) { return root; } return findMin(root.left); } //返回右子树最小节点 public Node rightTo(Node root) { if(root.left == null && root.right == null) { return root; } leftTo(root.left).right = root; rightTo(root.right).left = root; return findMin(root.left); } */ }
DA-MO-WANG/leetcode
java/src/liuyuboo/JZ27.java
918
//所谓链表和bst都是节点靠指针维护的,这个结构是一致的,所以存在就地转换的可能
line_comment
zh-cn
package liuyuboo; import java.util.LinkedList; public class JZ27 { class Node { public int val; public Node left; public Node right; public Node() { } public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right) { val = _val; left = _left; right = _right; } } //目的:转化成排序的循环双向链表 Node head = new Node(); public Node treeToDoublyList(Node root) { //结果形式--和中序遍历类似 //结果链表是一个由中序顺序组织的链表 //所谓 <SUF> //这个处理工程,只涉及两个点角色之间的指针调整,其他部分不需要===》需要head cur两个小弟 //cur 代表当前节点,而这个当前节点是中序顺序组织的节点;也就是中序遍历框架中间位置,会自然拿到当前节点 //head 这里就要记录前一个节点 //前一个节点与当前节点的互动,只有三部分:两部分指针调整-前一个后指针指向下一个;后一个前指针指向前一个;记得更新head,来保证始终维持root的前一个节点 Node begin = head; inOrder(root); Node cur = ret; while (cur.left != begin) { cur = cur.left; } return cur; } Node ret = null; public void inOrder(Node root) { if (root == null) { return; } inOrder(root.left); head.right = root; root.left = head; head = head.right; ret = root; inOrder(root.right); } //分化瓦解--三个部分,每个部分都具有和上级同样的问题实质 /* Node lastNode = null; convertNode(root,lastNode); Node headNode = lastNode; while (headNode != null && headNode.left != null) { headNode = headNode.left; } return headNode; } public void convertNode(Node root,Node lastNode) { if (root == null) { return; } Node current = root; if (current.left != null) { convertNode(current.left,lastNode); } current.left = lastNode; if (lastNode != null) { lastNode.right = current; } lastNode = current; if (current.right != null) { convertNode(current.right,lastNode); } }*/ /* if (root.left == null) //小问题:左子树 leftTo(root.left).right = root; //小问题:右子树 rightTo(root.right).left = root; return root; } //返回左子树最大节点 public Node leftTo(Node root) { if(root.left == null && root.right == null) { return root; } leftTo(root.left).right = root; rightTo(root.right).left = root; return findMax(root.right); } public Node findMax(Node root) { if(root.right == null) { return root; } return findMax(root.right); } public Node findMin(Node root) { if (root.left == null) { return root; } return findMin(root.left); } //返回右子树最小节点 public Node rightTo(Node root) { if(root.left == null && root.right == null) { return root; } leftTo(root.left).right = root; rightTo(root.right).left = root; return findMin(root.left); } */ }
0
850
27
918
28
999
25
918
28
1,235
52
false
false
false
false
false
true
26029_36
package compile; import entity.MultiComment; import entity.SingleComment; import entity.TokenList; import frame.OutText; import frame.ReadText; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * @description 这是词法分析的具体实现 */ @SuppressWarnings("all") public class Lexer extends MainComplier{ //词法分析解释规则,定义字符数组 String[] keyWords = {"if", "else", "while", "read", "write", "int", "double","for"}; //关键字数组 String[] operator = {"+", "-", "*", "/"};//运算符数组 String[] roperator = {">", "<", "==", "<>"};//关系运算符数组 String[] sepretor = {";", "{", "}", "(", ")", "."};//分隔符数组 String RegexToId = "^[a-zA-Z]([a-zA-Z_0-9])*[a-zA-Z0-9]$||[a-zA-Z]";//标识符的正则表达式 String RegexToNumber = "^^-?\\d+$";//整数的正则表达式 String RegexToFloat = "^(-?\\d+)(\\.\\d+)?$";//浮点数的正则表达式 String RegexToArray = "[a-zA-Z]+(\\[[0-9][1-9]*\\])+";//数组变量的正则表达式 //将父类的readText, outText继承过来 public Lexer(ReadText readText, OutText outText) throws HeadlessException { super(readText, outText); } //分析过程,此处为语法分析和词法分析提供已经修饰过的源程序 public List<TokenList> getTokens() { List<TokenList> tokenLists = new ArrayList<>();//用于记录Token的信息 String inputText = readText.getText(); StringTokenizer totalStrt = new StringTokenizer(inputText, "\r\n"); int row = 0;//行号 //获取所有的记号以及记号的信息 while (totalStrt.hasMoreTokens()) { List<String> Tokens = new ArrayList<>();//行记号 StringTokenizer rowOfStrt = new StringTokenizer(totalStrt.nextToken(), " \n\r\t;(){}\"\'+-<>/=*", true); //所有可能的界符,初步得到所有的Token,但需要进一步的合并 while (rowOfStrt.hasMoreTokens()) { Tokens.add(rowOfStrt.nextToken()); } TokenList tokenList = new TokenList(row, Tokens); tokenLists.add(tokenList); row++; } //对于初步得到的记号集合的进一步判断与整合,用于区别注释和*,/;以及=与==,以及<与<> for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组 for (int j = 0; j < tokenList.size() - 1; j++) { if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("/")) { //单行注释记号的识别 tokenList.set(j, "//"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("*")) { //多行注释的识别 tokenList.set(j, "/*"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("*") && tokenList.get(j + 1).equals("/")) { //多行注释的识别 tokenList.set(j, "*/"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("=") && tokenList.get(j + 1).equals("=")) { tokenList.set(j, "=="); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("<") && tokenList.get(j + 1).equals(">")) { tokenList.set(j, "<>"); tokenList.remove(j + 1);//判断不等于符号 } } } //第二次对记号进行判断整合,主要用于去除各种分隔符 for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组 String Pattern = "\\s+|\t|\r\n"; int j = 0; while(j<tokenList.size()) { if(tokenList.get(j).matches(Pattern)) { tokenList.remove(j); } else { j++; } } } //第三次对记号进行去除注释,得到真正的完整的记号 List<MultiComment> multiComments = new ArrayList<>();//存放多行注释的位置信息 List<SingleComment> singleComments = new ArrayList<>();//存放单行注释的位置信息 for (int i = 0; i < tokenLists.size(); i++)//多行注释的记号获取 { List<String> TokenOfrow = tokenLists.get(i).getTokenList(); int rowCount = tokenLists.get(i).getRow();//多行注释行号 for (int j = 0; j < TokenOfrow.size(); j++) { if (TokenOfrow.get(j).equals("//")) { SingleComment singleComment = new SingleComment(rowCount, j); singleComments.add(singleComment);//记录单行注释位置 } if (TokenOfrow.get(j).equals("/*")) { MultiComment multiComment = new MultiComment(rowCount, j, "/*");//j为列号 multiComments.add(multiComment); } else if (TokenOfrow.get(j).equals("*/")) { MultiComment multiComment = new MultiComment(rowCount, j, "*/"); multiComments.add(multiComment); } } } for (int i = 0; i < multiComments.size(); i = i + 2)//去除多行注释中的整行注释 { if ((multiComments.size() % 2) == 0 && i <= multiComments.size() - 2)//判断注释是否未闭合 { if (multiComments.get(i).getComment().equals("/*") && multiComments.get(i + 1).getComment().equals("*/")) { for (int j = multiComments.get(i).getRow() + 1; j < multiComments.get(i + 1).getRow(); j++) { tokenLists.remove(j); } List<String> StartLine = tokenLists.get(multiComments.get(i).getRow()).getTokenList();//注释行起始 List<String> EndLine = tokenLists.get(multiComments.get(i + 1).getRow()).getTokenList();//注释行结束 for (int j = multiComments.get(i).getColumn(); j < StartLine.size(); )//因为随着元素的删除减少,size大小也会发生改变 { StartLine.remove(j); } int position = multiComments.get(i).getColumn();//位置指针 for (int j = 0; j <= position; )//同理,元素的数量的减少导致size改变 { EndLine.remove(j); position--; } } } else { outText.append("无法继续分析"); outText.append("第" + multiComments.get(i).getRow() + "行第" + multiComments.get(i).getColumn() + "处的注释未闭合"); break; } } for (int i = 0; i < singleComments.size(); i++) { List<String> SignleLine = tokenLists.get(singleComments.get(i).getRow()).getTokenList(); for (int j = singleComments.get(i).getColumn(); j < SignleLine.size(); ) { SignleLine.remove(j);//去除单行注释 } } return tokenLists; } //所有的记号处理都做好,此处纯分析记号 public void Analysis() { List<TokenList> tokenLists = getTokens(); for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList(); outText.append("--------------------------------------------------分析第" + (i + 1) + "行--------------------------------------------------" + "\r\n"); for (int j = 0; j < tokenList.size(); j++) { int Count = 0; for (int k = 0; k < keyWords.length; k++) { if (tokenList.get(j).equals(keyWords[k])) { outText.append(tokenList.get(j) + " 是关键字" + "\r\n"); Count++; } } for (int k = 0; k < operator.length; k++) { if (tokenList.get(j).equals(operator[k])) { outText.append(tokenList.get(j) + " 是运算符" + "\r\n"); Count++; } } for (int k = 0; k < roperator.length; k++) { if (tokenList.get(j).equals(roperator[k])) { outText.append(tokenList.get(j) + " 是关系运算符" + "\r\n"); Count++; } } for (int k = 0; k < sepretor.length; k++) { if (tokenList.get(j).equals(sepretor[k])) { outText.append(tokenList.get(j) + " 是分隔符" + "\r\n"); Count++; } } if (tokenList.get(j).matches(RegexToId) && (Count == 0)) { outText.append(tokenList.get(j) + " 是标识符" + "\r\n"); } else if (tokenList.get(j).matches(RegexToNumber)) { outText.append(tokenList.get(j) + " 是整数" + "\r\n"); } else if (tokenList.get(j).matches(RegexToFloat)) { outText.append(tokenList.get(j) + " 是浮点数" + "\r\n"); } else if (tokenList.get(j).matches(RegexToArray)) { outText.append(tokenList.get(j) + " 是数组变量" + "\r\n"); } else if (tokenList.get(j).equals("=")) { outText.append(tokenList.get(j) + " 是等于号" + "\r\n"); } else if (Count == 0) { outText.append(tokenList.get(j) + " 标识符命名错误" + "\r\n"); } } } } }
DAQ121/Lexer-Parser
src/compile/Lexer.java
2,586
//注释行起始
line_comment
zh-cn
package compile; import entity.MultiComment; import entity.SingleComment; import entity.TokenList; import frame.OutText; import frame.ReadText; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * @description 这是词法分析的具体实现 */ @SuppressWarnings("all") public class Lexer extends MainComplier{ //词法分析解释规则,定义字符数组 String[] keyWords = {"if", "else", "while", "read", "write", "int", "double","for"}; //关键字数组 String[] operator = {"+", "-", "*", "/"};//运算符数组 String[] roperator = {">", "<", "==", "<>"};//关系运算符数组 String[] sepretor = {";", "{", "}", "(", ")", "."};//分隔符数组 String RegexToId = "^[a-zA-Z]([a-zA-Z_0-9])*[a-zA-Z0-9]$||[a-zA-Z]";//标识符的正则表达式 String RegexToNumber = "^^-?\\d+$";//整数的正则表达式 String RegexToFloat = "^(-?\\d+)(\\.\\d+)?$";//浮点数的正则表达式 String RegexToArray = "[a-zA-Z]+(\\[[0-9][1-9]*\\])+";//数组变量的正则表达式 //将父类的readText, outText继承过来 public Lexer(ReadText readText, OutText outText) throws HeadlessException { super(readText, outText); } //分析过程,此处为语法分析和词法分析提供已经修饰过的源程序 public List<TokenList> getTokens() { List<TokenList> tokenLists = new ArrayList<>();//用于记录Token的信息 String inputText = readText.getText(); StringTokenizer totalStrt = new StringTokenizer(inputText, "\r\n"); int row = 0;//行号 //获取所有的记号以及记号的信息 while (totalStrt.hasMoreTokens()) { List<String> Tokens = new ArrayList<>();//行记号 StringTokenizer rowOfStrt = new StringTokenizer(totalStrt.nextToken(), " \n\r\t;(){}\"\'+-<>/=*", true); //所有可能的界符,初步得到所有的Token,但需要进一步的合并 while (rowOfStrt.hasMoreTokens()) { Tokens.add(rowOfStrt.nextToken()); } TokenList tokenList = new TokenList(row, Tokens); tokenLists.add(tokenList); row++; } //对于初步得到的记号集合的进一步判断与整合,用于区别注释和*,/;以及=与==,以及<与<> for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组 for (int j = 0; j < tokenList.size() - 1; j++) { if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("/")) { //单行注释记号的识别 tokenList.set(j, "//"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("*")) { //多行注释的识别 tokenList.set(j, "/*"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("*") && tokenList.get(j + 1).equals("/")) { //多行注释的识别 tokenList.set(j, "*/"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("=") && tokenList.get(j + 1).equals("=")) { tokenList.set(j, "=="); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("<") && tokenList.get(j + 1).equals(">")) { tokenList.set(j, "<>"); tokenList.remove(j + 1);//判断不等于符号 } } } //第二次对记号进行判断整合,主要用于去除各种分隔符 for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组 String Pattern = "\\s+|\t|\r\n"; int j = 0; while(j<tokenList.size()) { if(tokenList.get(j).matches(Pattern)) { tokenList.remove(j); } else { j++; } } } //第三次对记号进行去除注释,得到真正的完整的记号 List<MultiComment> multiComments = new ArrayList<>();//存放多行注释的位置信息 List<SingleComment> singleComments = new ArrayList<>();//存放单行注释的位置信息 for (int i = 0; i < tokenLists.size(); i++)//多行注释的记号获取 { List<String> TokenOfrow = tokenLists.get(i).getTokenList(); int rowCount = tokenLists.get(i).getRow();//多行注释行号 for (int j = 0; j < TokenOfrow.size(); j++) { if (TokenOfrow.get(j).equals("//")) { SingleComment singleComment = new SingleComment(rowCount, j); singleComments.add(singleComment);//记录单行注释位置 } if (TokenOfrow.get(j).equals("/*")) { MultiComment multiComment = new MultiComment(rowCount, j, "/*");//j为列号 multiComments.add(multiComment); } else if (TokenOfrow.get(j).equals("*/")) { MultiComment multiComment = new MultiComment(rowCount, j, "*/"); multiComments.add(multiComment); } } } for (int i = 0; i < multiComments.size(); i = i + 2)//去除多行注释中的整行注释 { if ((multiComments.size() % 2) == 0 && i <= multiComments.size() - 2)//判断注释是否未闭合 { if (multiComments.get(i).getComment().equals("/*") && multiComments.get(i + 1).getComment().equals("*/")) { for (int j = multiComments.get(i).getRow() + 1; j < multiComments.get(i + 1).getRow(); j++) { tokenLists.remove(j); } List<String> StartLine = tokenLists.get(multiComments.get(i).getRow()).getTokenList();//注释 <SUF> List<String> EndLine = tokenLists.get(multiComments.get(i + 1).getRow()).getTokenList();//注释行结束 for (int j = multiComments.get(i).getColumn(); j < StartLine.size(); )//因为随着元素的删除减少,size大小也会发生改变 { StartLine.remove(j); } int position = multiComments.get(i).getColumn();//位置指针 for (int j = 0; j <= position; )//同理,元素的数量的减少导致size改变 { EndLine.remove(j); position--; } } } else { outText.append("无法继续分析"); outText.append("第" + multiComments.get(i).getRow() + "行第" + multiComments.get(i).getColumn() + "处的注释未闭合"); break; } } for (int i = 0; i < singleComments.size(); i++) { List<String> SignleLine = tokenLists.get(singleComments.get(i).getRow()).getTokenList(); for (int j = singleComments.get(i).getColumn(); j < SignleLine.size(); ) { SignleLine.remove(j);//去除单行注释 } } return tokenLists; } //所有的记号处理都做好,此处纯分析记号 public void Analysis() { List<TokenList> tokenLists = getTokens(); for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList(); outText.append("--------------------------------------------------分析第" + (i + 1) + "行--------------------------------------------------" + "\r\n"); for (int j = 0; j < tokenList.size(); j++) { int Count = 0; for (int k = 0; k < keyWords.length; k++) { if (tokenList.get(j).equals(keyWords[k])) { outText.append(tokenList.get(j) + " 是关键字" + "\r\n"); Count++; } } for (int k = 0; k < operator.length; k++) { if (tokenList.get(j).equals(operator[k])) { outText.append(tokenList.get(j) + " 是运算符" + "\r\n"); Count++; } } for (int k = 0; k < roperator.length; k++) { if (tokenList.get(j).equals(roperator[k])) { outText.append(tokenList.get(j) + " 是关系运算符" + "\r\n"); Count++; } } for (int k = 0; k < sepretor.length; k++) { if (tokenList.get(j).equals(sepretor[k])) { outText.append(tokenList.get(j) + " 是分隔符" + "\r\n"); Count++; } } if (tokenList.get(j).matches(RegexToId) && (Count == 0)) { outText.append(tokenList.get(j) + " 是标识符" + "\r\n"); } else if (tokenList.get(j).matches(RegexToNumber)) { outText.append(tokenList.get(j) + " 是整数" + "\r\n"); } else if (tokenList.get(j).matches(RegexToFloat)) { outText.append(tokenList.get(j) + " 是浮点数" + "\r\n"); } else if (tokenList.get(j).matches(RegexToArray)) { outText.append(tokenList.get(j) + " 是数组变量" + "\r\n"); } else if (tokenList.get(j).equals("=")) { outText.append(tokenList.get(j) + " 是等于号" + "\r\n"); } else if (Count == 0) { outText.append(tokenList.get(j) + " 标识符命名错误" + "\r\n"); } } } } }
0
2,335
6
2,584
5
2,711
4
2,586
5
3,266
8
false
false
false
false
false
true
41648_11
package tk.dcmmc.sorting.Algorithms; import tk.dcmmc.fundamentals.Algorithms.DoubleLinkedList; /** * 希尔排序法 * Created on 2017/8/5 * @author DCMMC * @since 1.5 */ class ShellSort extends Sort { /** * 在最糟糕的情况下时间复杂度为O(N^1.5), 一个小小的改进就能从InsertionSort的O(N^2)降低到O(N^1.5)(而且是最坏情况) * 平均下的时间复杂度不确定, 取决于increment sequence的选取. * * InsertionSort在每一轮插入的时候需要跟相邻的元素一个一个交换, 这样很消耗资源, 希尔排序作为插入排序的扩展, * 每次比较并交换的间隔不再是1(h=1这一特殊情况下h-sorting就是InsertionSort), 而是大于1的不同的步长. * 定义(Def.): h-sorting * 如果数组中的元素任意间隔h都是有序的, 那就称为h-sorting array, e.g., 1 2 3 4 5 6 7, * 取h为2, 则子序列1 3 5 7和子序列2 4 6分别都是有序的(即有h个互相独立有序的子序列交错组合在一起), 则该数组是h-sorted array * h-sorting即以h为间隔对子序列进行排序, e.g., 对序列 1 5 8 2 3 4 6 7 6 8 9 (共11个元素), 以h = 3进行h-sorting, * 首先这个序列拆分为一下3个子序列: 1 2 6 7和5 3 7 9和8 6 4, 然后依次对这三个子序列进行InsertionSort, 得到1 2 6 7, 3 5 7 9 * 和4 6 8这三个子序列, 合并之后为: 1 3 4 2 5 6 6 7 8 7 9, 这个序列就被称为原序列以h=3的h-sorted array * 一个更好的理解就是把序列放在一个h列的表中, 然后对其形成的二维表的每一列进行InsertionSort: * 1 5 8 2 3 4 6 7 6 8 9以h=3 * 1 5 8 * 2 3 4 * 6 7 6 * 8 9 * 然后依次对第一第二第三第四列进行InsertionSort: * 1 3 4 * 2 5 6 * 6 7 8 * 7 9 * * * ShellSort大体的原理是以一系列值(increment sequence)作为h(又叫步长), 由大的h到小的h来对序列进行h-sorting, 只要该h序列最后的h是1, * 就一定能得出排序好的序列, 比如 5 3 1就是一个h序列, 先以h=5对原序列进行h-sorting, 然后再以h=3进行h-sorting, 最后以h=1进行h-sorting. * 不过从1开始然后不断乘以2这样的序列的效率很低,因为1后面都是偶数,彼此h-sorting排序都是错开的的. * * 而公认的最好步长序列是由Sedgewick(本书作者)提出的(1, 5, 19, 41, 109,...),该序列的项来自9x4^i-9x2^i+1和2^(i+2)x(2^(i+2)-3)+1 * 这两个算式.用这样步长序列的希尔排序比插入排序要快,甚至在小数组中比快速排序和堆排序还快,但是在涉及大量数据时希尔排序还是比快速排序慢。 * * 另一个在大数组中表现优异的步长序列是(斐波那契数列除去0和1将剩余的数以黄金分区比的两倍的幂进行运算得到的数列) * * 不过一般使用的序列是Knuth提出的由递推公式h = h*3 + 1确定的数列(转成通项公式即为1/2(3^k-1)), 这个序列在元素数量比较大的时候, * 相比于SelectionSort和InsertionSort, 性能按照数组大小以2的次幂递增. * 使用Knuth提出序列的比较次数大概为N的若干倍再乘以这个序列的长度(差不多约为N^1.5, 由大量N很大的实验可以估算出) * * 虽然使用最优的序列的时候, 在对小数组排序性能有时候可以超过heapsort和quicksort, 不过在大量数据的时候还是慢于后两个, 不过相比于 * 后两者复杂一些的实现, ShellSort只需少量代码而且对资源的消耗也比较小, 所以适合用在嵌入式系统这些比较重视资源的场景中. */ public static void shellSort(Comparable[] a) { //先确定一个不大于a.length/3的一个数作为h序列的最大项 int h = 1; while (h < a.length/3) h = h*3 + 1;//by Knuth //Ex 2.1.11 //还可以把上述生成的increment sequence 保存在数组中 //DoubleLinkedList<Integer> list = new DoubleLinkedList<>(); //list.addLast(1); //while (h < a.length / 3) // list.addLast(list.get(list.getSize() - 1) * 3 + 1); //int[] incrementSeq = list.toArray(); //以这个h构成一个后项是前项的1/3(约)的序列 while (h >= 1) { //以当前h做h-sorting for (int i = h; i < a.length; i++) { for (int j = i; j >= h && less(a[j], a[j - h]); j -= h) exch(a, j, j - h); } h /= 3; } } }///~
DCMMC/Java-Algorithms-Learning
Algorithms/tk/dcmmc/sorting/Algorithms/ShellSort.java
1,626
//以这个h构成一个后项是前项的1/3(约)的序列
line_comment
zh-cn
package tk.dcmmc.sorting.Algorithms; import tk.dcmmc.fundamentals.Algorithms.DoubleLinkedList; /** * 希尔排序法 * Created on 2017/8/5 * @author DCMMC * @since 1.5 */ class ShellSort extends Sort { /** * 在最糟糕的情况下时间复杂度为O(N^1.5), 一个小小的改进就能从InsertionSort的O(N^2)降低到O(N^1.5)(而且是最坏情况) * 平均下的时间复杂度不确定, 取决于increment sequence的选取. * * InsertionSort在每一轮插入的时候需要跟相邻的元素一个一个交换, 这样很消耗资源, 希尔排序作为插入排序的扩展, * 每次比较并交换的间隔不再是1(h=1这一特殊情况下h-sorting就是InsertionSort), 而是大于1的不同的步长. * 定义(Def.): h-sorting * 如果数组中的元素任意间隔h都是有序的, 那就称为h-sorting array, e.g., 1 2 3 4 5 6 7, * 取h为2, 则子序列1 3 5 7和子序列2 4 6分别都是有序的(即有h个互相独立有序的子序列交错组合在一起), 则该数组是h-sorted array * h-sorting即以h为间隔对子序列进行排序, e.g., 对序列 1 5 8 2 3 4 6 7 6 8 9 (共11个元素), 以h = 3进行h-sorting, * 首先这个序列拆分为一下3个子序列: 1 2 6 7和5 3 7 9和8 6 4, 然后依次对这三个子序列进行InsertionSort, 得到1 2 6 7, 3 5 7 9 * 和4 6 8这三个子序列, 合并之后为: 1 3 4 2 5 6 6 7 8 7 9, 这个序列就被称为原序列以h=3的h-sorted array * 一个更好的理解就是把序列放在一个h列的表中, 然后对其形成的二维表的每一列进行InsertionSort: * 1 5 8 2 3 4 6 7 6 8 9以h=3 * 1 5 8 * 2 3 4 * 6 7 6 * 8 9 * 然后依次对第一第二第三第四列进行InsertionSort: * 1 3 4 * 2 5 6 * 6 7 8 * 7 9 * * * ShellSort大体的原理是以一系列值(increment sequence)作为h(又叫步长), 由大的h到小的h来对序列进行h-sorting, 只要该h序列最后的h是1, * 就一定能得出排序好的序列, 比如 5 3 1就是一个h序列, 先以h=5对原序列进行h-sorting, 然后再以h=3进行h-sorting, 最后以h=1进行h-sorting. * 不过从1开始然后不断乘以2这样的序列的效率很低,因为1后面都是偶数,彼此h-sorting排序都是错开的的. * * 而公认的最好步长序列是由Sedgewick(本书作者)提出的(1, 5, 19, 41, 109,...),该序列的项来自9x4^i-9x2^i+1和2^(i+2)x(2^(i+2)-3)+1 * 这两个算式.用这样步长序列的希尔排序比插入排序要快,甚至在小数组中比快速排序和堆排序还快,但是在涉及大量数据时希尔排序还是比快速排序慢。 * * 另一个在大数组中表现优异的步长序列是(斐波那契数列除去0和1将剩余的数以黄金分区比的两倍的幂进行运算得到的数列) * * 不过一般使用的序列是Knuth提出的由递推公式h = h*3 + 1确定的数列(转成通项公式即为1/2(3^k-1)), 这个序列在元素数量比较大的时候, * 相比于SelectionSort和InsertionSort, 性能按照数组大小以2的次幂递增. * 使用Knuth提出序列的比较次数大概为N的若干倍再乘以这个序列的长度(差不多约为N^1.5, 由大量N很大的实验可以估算出) * * 虽然使用最优的序列的时候, 在对小数组排序性能有时候可以超过heapsort和quicksort, 不过在大量数据的时候还是慢于后两个, 不过相比于 * 后两者复杂一些的实现, ShellSort只需少量代码而且对资源的消耗也比较小, 所以适合用在嵌入式系统这些比较重视资源的场景中. */ public static void shellSort(Comparable[] a) { //先确定一个不大于a.length/3的一个数作为h序列的最大项 int h = 1; while (h < a.length/3) h = h*3 + 1;//by Knuth //Ex 2.1.11 //还可以把上述生成的increment sequence 保存在数组中 //DoubleLinkedList<Integer> list = new DoubleLinkedList<>(); //list.addLast(1); //while (h < a.length / 3) // list.addLast(list.get(list.getSize() - 1) * 3 + 1); //int[] incrementSeq = list.toArray(); //以这 <SUF> while (h >= 1) { //以当前h做h-sorting for (int i = h; i < a.length; i++) { for (int j = i; j >= h && less(a[j], a[j - h]); j -= h) exch(a, j, j - h); } h /= 3; } } }///~
0
1,481
20
1,626
21
1,489
20
1,626
21
2,152
26
false
false
false
false
false
true
53256_12
//请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, //numberOfUnitsPerBoxi] : // // // numberOfBoxesi 是类型 i 的箱子的数量。 // numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。 // // // 整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。 // // 返回卡车可以装载 单元 的 最大 总数。 // // // // 示例 1: // // //输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 //输出:8 //解释:箱子的情况如下: //- 1 个第一类的箱子,里面含 3 个单元。 //- 2 个第二类的箱子,每个里面含 2 个单元。 //- 3 个第三类的箱子,每个里面含 1 个单元。 //可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。 //单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8 // // 示例 2: // // //输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 //输出:91 // // // // // 提示: // // // 1 <= boxTypes.length <= 1000 // 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000 // 1 <= truckSize <= 10⁶ // // // Related Topics 贪心 数组 排序 👍 78 👎 0 import java.util.Arrays; import java.util.Comparator; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int maximumUnits(int[][] boxTypes, int truckSize) { int len = boxTypes.length; Integer[][] arr = new Integer[len][2]; for (int i = 0; i < len; i++) { arr[i][0] = boxTypes[i][0]; arr[i][1] = boxTypes[i][1]; } Arrays.sort(arr, new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { return -o1[1] + o2[1]; } }); int sum = 0; int i = 0; while (truckSize > 0 && i < len) { if (truckSize - arr[i][0] >= 0) { truckSize -= arr[i][0]; sum += arr[i][0] * arr[i][1]; } else { sum += truckSize * arr[i][1]; truckSize = 0; } i++; } return sum; } } //leetcode submit region end(Prohibit modification and deletion)
DEAiFISH/LeetCode
editor/cn/[1710]卡车上的最大单元数.java
781
//- 3 个第三类的箱子,每个里面含 1 个单元。
line_comment
zh-cn
//请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, //numberOfUnitsPerBoxi] : // // // numberOfBoxesi 是类型 i 的箱子的数量。 // numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。 // // // 整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。 // // 返回卡车可以装载 单元 的 最大 总数。 // // // // 示例 1: // // //输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 //输出:8 //解释:箱子的情况如下: //- 1 个第一类的箱子,里面含 3 个单元。 //- 2 个第二类的箱子,每个里面含 2 个单元。 //- <SUF> //可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。 //单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8 // // 示例 2: // // //输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 //输出:91 // // // // // 提示: // // // 1 <= boxTypes.length <= 1000 // 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000 // 1 <= truckSize <= 10⁶ // // // Related Topics 贪心 数组 排序 👍 78 👎 0 import java.util.Arrays; import java.util.Comparator; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int maximumUnits(int[][] boxTypes, int truckSize) { int len = boxTypes.length; Integer[][] arr = new Integer[len][2]; for (int i = 0; i < len; i++) { arr[i][0] = boxTypes[i][0]; arr[i][1] = boxTypes[i][1]; } Arrays.sort(arr, new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { return -o1[1] + o2[1]; } }); int sum = 0; int i = 0; while (truckSize > 0 && i < len) { if (truckSize - arr[i][0] >= 0) { truckSize -= arr[i][0]; sum += arr[i][0] * arr[i][1]; } else { sum += truckSize * arr[i][1]; truckSize = 0; } i++; } return sum; } } //leetcode submit region end(Prohibit modification and deletion)
0
685
19
781
18
770
17
781
18
989
29
false
false
false
false
false
true
58548_7
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GoListener extends MouseAdapter implements ActionListener, GoData{ JRadioButton[] modelForm; String gameModel = "pvp";// 人机 人人 int chessFlag;// 0 不能下棋 1 黑棋 2 白棋 Graphics g; @Override public void actionPerformed(ActionEvent e){ if(modelForm[0].isSelected ()){ gameModel = "pve"; } else if(modelForm[1].isSelected ()){ gameModel = "pvp"; } String btnStr = e.getActionCommand (); JButton btn = (JButton) e.getSource (); if(btnStr.equals ("开始游戏")){ btn.setText ("结束对局"); chessFlag = 1; } else if(btnStr.equals ("悔棋")){ // 悔棋 } else if(btnStr.equals ("退出")){ System.exit (0); } else if(btnStr.equals ("结束对局")){ btn.setText ("开始游戏"); chessFlag = 0; } } @Override public void mousePressed(MouseEvent e){ int x = e.getX (); int y = e.getY (); if(chessFlag == 0){ JOptionPane.showConfirmDialog (null, "请先开始游戏", "提示", JOptionPane.DEFAULT_OPTION); return; } // System.out.println("x:" + x + " y:" + y); // 求行列值 int r = (y - Y + SIZE / 2) / SIZE; // 行 int c = (x - X + SIZE / 2) / SIZE; // 列 // System.out.println (r + " " + c); if(x < 25 || y < 25 || r < 0 || r >= ROWS || c < 0 || c >= COLS){ JOptionPane.showMessageDialog (null, "请下在棋盘内", "提示", JOptionPane.DEFAULT_OPTION); return; } if(chessArr[r][c]!=0){ JOptionPane.showMessageDialog (null, "此处已有棋子", "提示", JOptionPane.DEFAULT_OPTION); return; } if(gameModel.equals ("pvp")){ // 存储棋子 chessArr[r][c] = chessFlag; boolean ifwin = ChessJudge.checkWin(r, c, chessFlag); System.out.println("ifwin:" + ifwin); if(chessFlag == 1){ g.setColor (Color.BLACK); chessFlag = 2; } else{ g.setColor (Color.WHITE); chessFlag = 1; } // 还原坐标 int chessX = X + c * SIZE - SIZE / 2; int chessY = Y + r * SIZE - SIZE / 2; g.fillOval (chessX, chessY, SIZE, SIZE); // 判断输赢 } else{ } } }
DHUAVY/AIGo
GoListener.java
713
// 判断输赢
line_comment
zh-cn
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GoListener extends MouseAdapter implements ActionListener, GoData{ JRadioButton[] modelForm; String gameModel = "pvp";// 人机 人人 int chessFlag;// 0 不能下棋 1 黑棋 2 白棋 Graphics g; @Override public void actionPerformed(ActionEvent e){ if(modelForm[0].isSelected ()){ gameModel = "pve"; } else if(modelForm[1].isSelected ()){ gameModel = "pvp"; } String btnStr = e.getActionCommand (); JButton btn = (JButton) e.getSource (); if(btnStr.equals ("开始游戏")){ btn.setText ("结束对局"); chessFlag = 1; } else if(btnStr.equals ("悔棋")){ // 悔棋 } else if(btnStr.equals ("退出")){ System.exit (0); } else if(btnStr.equals ("结束对局")){ btn.setText ("开始游戏"); chessFlag = 0; } } @Override public void mousePressed(MouseEvent e){ int x = e.getX (); int y = e.getY (); if(chessFlag == 0){ JOptionPane.showConfirmDialog (null, "请先开始游戏", "提示", JOptionPane.DEFAULT_OPTION); return; } // System.out.println("x:" + x + " y:" + y); // 求行列值 int r = (y - Y + SIZE / 2) / SIZE; // 行 int c = (x - X + SIZE / 2) / SIZE; // 列 // System.out.println (r + " " + c); if(x < 25 || y < 25 || r < 0 || r >= ROWS || c < 0 || c >= COLS){ JOptionPane.showMessageDialog (null, "请下在棋盘内", "提示", JOptionPane.DEFAULT_OPTION); return; } if(chessArr[r][c]!=0){ JOptionPane.showMessageDialog (null, "此处已有棋子", "提示", JOptionPane.DEFAULT_OPTION); return; } if(gameModel.equals ("pvp")){ // 存储棋子 chessArr[r][c] = chessFlag; boolean ifwin = ChessJudge.checkWin(r, c, chessFlag); System.out.println("ifwin:" + ifwin); if(chessFlag == 1){ g.setColor (Color.BLACK); chessFlag = 2; } else{ g.setColor (Color.WHITE); chessFlag = 1; } // 还原坐标 int chessX = X + c * SIZE - SIZE / 2; int chessY = Y + r * SIZE - SIZE / 2; g.fillOval (chessX, chessY, SIZE, SIZE); // 判断 <SUF> } else{ } } }
0
643
5
713
5
737
4
713
5
911
8
false
false
false
false
false
true
17596_3
package code.DrawPad.src; import javax.swing.*; import java.awt.*; public class ImagePro extends JFrame{ ImageListen imageListen = new ImageListen (); public ImagePro(){ JFrame jf = new JFrame (); jf.setTitle ("图片处理"); jf.setSize (1000, 900); jf.setDefaultCloseOperation (EXIT_ON_CLOSE); jf.setVisible (true); ShowPanel showPanel = new ShowPanel ();// 显示图片的面板 // 初始化图层 showPanel.setBuffImgList (imageListen.buffImgList); imageListen.setShowPanel (showPanel); showPanel.addMouseListener (imageListen);//鼠标监听 showPanel.addMouseMotionListener (imageListen);// 鼠标移动监听 JPanel imgPanel = new JPanel ();// 图片选择的面板 ControlPanel controlPanel = new ControlPanel (imageListen);// 滤镜操作面板 jf.add (showPanel, BorderLayout.CENTER); jf.add (controlPanel, BorderLayout.SOUTH); JMenuBar jmb = new JMenuBar ();// 菜单栏 JMenu jm = new JMenu ("文件");// 菜单 JMenuItem jmiOpen = new JMenuItem ("打开");// 菜单项 JMenuItem jmiSave = new JMenuItem ("保存");// 菜单项 jmiOpen.addActionListener (imageListen); jmiSave.addActionListener (imageListen); jmiOpen.setActionCommand ("FileOP"); jmiSave.setActionCommand ("FileOP"); jm.add (jmiOpen); jm.add (jmiSave); jmb.add (jm); jf.setJMenuBar (jmb); jf.setVisible (true); } public static void main(String[] args){ new ImagePro (); } }
DHUAVY/DrawPad
src/ImagePro.java
421
// 鼠标移动监听
line_comment
zh-cn
package code.DrawPad.src; import javax.swing.*; import java.awt.*; public class ImagePro extends JFrame{ ImageListen imageListen = new ImageListen (); public ImagePro(){ JFrame jf = new JFrame (); jf.setTitle ("图片处理"); jf.setSize (1000, 900); jf.setDefaultCloseOperation (EXIT_ON_CLOSE); jf.setVisible (true); ShowPanel showPanel = new ShowPanel ();// 显示图片的面板 // 初始化图层 showPanel.setBuffImgList (imageListen.buffImgList); imageListen.setShowPanel (showPanel); showPanel.addMouseListener (imageListen);//鼠标监听 showPanel.addMouseMotionListener (imageListen);// 鼠标 <SUF> JPanel imgPanel = new JPanel ();// 图片选择的面板 ControlPanel controlPanel = new ControlPanel (imageListen);// 滤镜操作面板 jf.add (showPanel, BorderLayout.CENTER); jf.add (controlPanel, BorderLayout.SOUTH); JMenuBar jmb = new JMenuBar ();// 菜单栏 JMenu jm = new JMenu ("文件");// 菜单 JMenuItem jmiOpen = new JMenuItem ("打开");// 菜单项 JMenuItem jmiSave = new JMenuItem ("保存");// 菜单项 jmiOpen.addActionListener (imageListen); jmiSave.addActionListener (imageListen); jmiOpen.setActionCommand ("FileOP"); jmiSave.setActionCommand ("FileOP"); jm.add (jmiOpen); jm.add (jmiSave); jmb.add (jm); jf.setJMenuBar (jmb); jf.setVisible (true); } public static void main(String[] args){ new ImagePro (); } }
0
381
7
421
7
411
5
421
7
552
14
false
false
false
false
false
true
55587_1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.chunjun.cdc; import com.dtstack.chunjun.cdc.ddl.definition.TableIdentifier; import com.dtstack.chunjun.cdc.handler.CacheHandler; import com.dtstack.chunjun.cdc.handler.DDLHandler; import com.dtstack.chunjun.cdc.worker.WorkerManager; import com.dtstack.chunjun.element.ColumnRowData; import com.dtstack.chunjun.throwable.ChunJunRuntimeException; import org.apache.flink.api.common.functions.RichFlatMapFunction; import org.apache.flink.configuration.Configuration; import org.apache.flink.table.data.RowData; import org.apache.flink.table.data.StringData; import org.apache.flink.util.Collector; import java.util.Objects; /** * 数据(不论ddl还是dml数据)下发到对应表名下的unblock队列中,worker在轮询过程中,处理unblock数据队列中的数据,在遇到ddl数据之后,将数据队列置为block状态,并将队 * 列引用交给store处理,store在拿到队列引用之后,将队列头部的ddl数据下发到外部存储中, 并监听外部存储对ddl的反馈情况(监听工作由store中额外的线程来执行), * 此时,队列仍然处于block状态;在收到外部存储的反馈之后,将数据队列头部的ddl数据移除,同时将队列状 态回归为unblock状态,队列引用还给worker。 */ public class RestorationFlatMap extends RichFlatMapFunction<RowData, RowData> { private static final long serialVersionUID = -1936334572949200754L; private final QueuesChamberlain chamberlain; private final WorkerManager workerManager; public RestorationFlatMap(DDLHandler ddlHandler, CacheHandler cacheHandler, CdcConfig conf) { this.chamberlain = new QueuesChamberlain(ddlHandler, cacheHandler); this.workerManager = new WorkerManager(chamberlain, conf); } @Override public void open(Configuration parameters) throws Exception { workerManager.open(); chamberlain.open(); } @Override public void close() throws Exception { workerManager.close(); chamberlain.close(); } @Override public void flatMap(RowData value, Collector<RowData> out) { if (workerManager.getCollector() == null) { WrapCollector<RowData> wrapCollector = new WrapCollector<>(out); chamberlain.setCollector(wrapCollector); workerManager.setCollector(out); } if (!workerManager.isAlive()) { throw new ChunJunRuntimeException(workerManager.getException()); } put(value); } private void put(RowData rowData) { TableIdentifier tableIdentifier = getTableIdentifierFromColumnData(rowData); chamberlain.add(rowData, tableIdentifier); } /** * 从 RowData 获取对应的tableIdentifier * * @param data column row data. * @return table identifier. */ private TableIdentifier getTableIdentifierFromColumnData(RowData data) { String[] headers; if (data instanceof DdlRowData) { headers = ((DdlRowData) data).getHeaders(); } else { headers = ((ColumnRowData) data).getHeaders(); } int databaseIndex = -1; int schemaIndex = -1; int tableIndex = -1; for (int i = 0; i < Objects.requireNonNull(headers).length; i++) { if ("database".equalsIgnoreCase(headers[i])) { databaseIndex = i; continue; } if ("schema".equalsIgnoreCase(headers[i])) { schemaIndex = i; continue; } if ("table".equalsIgnoreCase(headers[i])) { tableIndex = i; } } String database = getDataFromIndex(databaseIndex, data); String schema = getDataFromIndex(schemaIndex, data); String table = getDataFromIndex(tableIndex, data); return new TableIdentifier(database, schema, table); } private String getDataFromIndex(int index, RowData data) { if (index >= 0) { StringData stringData = data.getString(index); if (null != stringData) { return stringData.toString(); } } return null; } }
DTStack/chunjun
chunjun-core/src/main/java/com/dtstack/chunjun/cdc/RestorationFlatMap.java
1,219
/** * 数据(不论ddl还是dml数据)下发到对应表名下的unblock队列中,worker在轮询过程中,处理unblock数据队列中的数据,在遇到ddl数据之后,将数据队列置为block状态,并将队 * 列引用交给store处理,store在拿到队列引用之后,将队列头部的ddl数据下发到外部存储中, 并监听外部存储对ddl的反馈情况(监听工作由store中额外的线程来执行), * 此时,队列仍然处于block状态;在收到外部存储的反馈之后,将数据队列头部的ddl数据移除,同时将队列状 态回归为unblock状态,队列引用还给worker。 */
block_comment
zh-cn
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.chunjun.cdc; import com.dtstack.chunjun.cdc.ddl.definition.TableIdentifier; import com.dtstack.chunjun.cdc.handler.CacheHandler; import com.dtstack.chunjun.cdc.handler.DDLHandler; import com.dtstack.chunjun.cdc.worker.WorkerManager; import com.dtstack.chunjun.element.ColumnRowData; import com.dtstack.chunjun.throwable.ChunJunRuntimeException; import org.apache.flink.api.common.functions.RichFlatMapFunction; import org.apache.flink.configuration.Configuration; import org.apache.flink.table.data.RowData; import org.apache.flink.table.data.StringData; import org.apache.flink.util.Collector; import java.util.Objects; /** * 数据( <SUF>*/ public class RestorationFlatMap extends RichFlatMapFunction<RowData, RowData> { private static final long serialVersionUID = -1936334572949200754L; private final QueuesChamberlain chamberlain; private final WorkerManager workerManager; public RestorationFlatMap(DDLHandler ddlHandler, CacheHandler cacheHandler, CdcConfig conf) { this.chamberlain = new QueuesChamberlain(ddlHandler, cacheHandler); this.workerManager = new WorkerManager(chamberlain, conf); } @Override public void open(Configuration parameters) throws Exception { workerManager.open(); chamberlain.open(); } @Override public void close() throws Exception { workerManager.close(); chamberlain.close(); } @Override public void flatMap(RowData value, Collector<RowData> out) { if (workerManager.getCollector() == null) { WrapCollector<RowData> wrapCollector = new WrapCollector<>(out); chamberlain.setCollector(wrapCollector); workerManager.setCollector(out); } if (!workerManager.isAlive()) { throw new ChunJunRuntimeException(workerManager.getException()); } put(value); } private void put(RowData rowData) { TableIdentifier tableIdentifier = getTableIdentifierFromColumnData(rowData); chamberlain.add(rowData, tableIdentifier); } /** * 从 RowData 获取对应的tableIdentifier * * @param data column row data. * @return table identifier. */ private TableIdentifier getTableIdentifierFromColumnData(RowData data) { String[] headers; if (data instanceof DdlRowData) { headers = ((DdlRowData) data).getHeaders(); } else { headers = ((ColumnRowData) data).getHeaders(); } int databaseIndex = -1; int schemaIndex = -1; int tableIndex = -1; for (int i = 0; i < Objects.requireNonNull(headers).length; i++) { if ("database".equalsIgnoreCase(headers[i])) { databaseIndex = i; continue; } if ("schema".equalsIgnoreCase(headers[i])) { schemaIndex = i; continue; } if ("table".equalsIgnoreCase(headers[i])) { tableIndex = i; } } String database = getDataFromIndex(databaseIndex, data); String schema = getDataFromIndex(schemaIndex, data); String table = getDataFromIndex(tableIndex, data); return new TableIdentifier(database, schema, table); } private String getDataFromIndex(int index, RowData data) { if (index >= 0) { StringData stringData = data.getString(index); if (null != stringData) { return stringData.toString(); } } return null; } }
0
1,094
160
1,219
169
1,256
151
1,219
169
1,518
282
true
true
true
true
true
false
9593_5
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flink.sql.localTest; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.alibaba.fastjson.JSONObject; import com.dtstack.flink.sql.Main; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; /** * @author tiezhu * @Date 2020/7/8 Wed * Company dtstack */ public class LocalTest { private static final Logger LOG = LoggerFactory.getLogger(LocalTest.class); public static void main(String[] args) throws Exception { setLogLevel("INFO"); List<String> propertiesList = new ArrayList<>(); String sqlPath = "/Users/wtz/dtstack/sql/test/FileDemoOne.sql"; Map<String, Object> conf = new HashMap<>(); JSONObject properties = new JSONObject(); //其他参数配置 properties.put("time.characteristic", "eventTime"); properties.put("timezone", TimeZone.getDefault()); properties.put("early.trigger", "1"); // 任务配置参数 conf.put("-sql", URLEncoder.encode(readSQL(sqlPath), StandardCharsets.UTF_8.name())); conf.put("-mode", "local"); conf.put("-name", "flinkStreamSQLLocalTest"); conf.put("-confProp", properties.toString()); conf.put("-pluginLoadMode", "LocalTest"); // conf.put("-checkResource", "true"); conf.put("-dirtyProperties", buildDirtyStr()); for (Map.Entry<String, Object> keyValue : conf.entrySet()) { propertiesList.add(keyValue.getKey()); propertiesList.add(keyValue.getValue().toString()); } Main.main(propertiesList.toArray(new String[0])); } private static String buildDirtyStr() { JSONObject jsonObject = new JSONObject(); jsonObject.put("type", "console"); // 多少条数据打印一次 jsonObject.put("printLimit", "100"); jsonObject.put("url", "jdbc:mysql://localhost:3306/tiezhu"); jsonObject.put("userName", "root"); jsonObject.put("password", "abc123"); jsonObject.put("isCreateTable", "false"); // 多少条数据写入一次 jsonObject.put("batchSize", "1"); jsonObject.put("tableName", "dirtyData"); return jsonObject.toJSONString(); } private static String readSQL(String sqlPath) { try { byte[] array = Files.readAllBytes(Paths.get(sqlPath)); return new String(array, StandardCharsets.UTF_8); } catch (IOException ioe) { LOG.error("Can not get the job info !!!", ioe); throw new RuntimeException(ioe); } } private static void setLogLevel(String level) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); ch.qos.logback.classic.Logger logger = loggerContext.getLogger("root"); logger.setLevel(Level.toLevel(level)); } }
DTStack/flinkStreamSQL
localTest/src/main/java/com/dtstack/flink/sql/localTest/LocalTest.java
985
// 多少条数据打印一次
line_comment
zh-cn
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flink.sql.localTest; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.alibaba.fastjson.JSONObject; import com.dtstack.flink.sql.Main; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; /** * @author tiezhu * @Date 2020/7/8 Wed * Company dtstack */ public class LocalTest { private static final Logger LOG = LoggerFactory.getLogger(LocalTest.class); public static void main(String[] args) throws Exception { setLogLevel("INFO"); List<String> propertiesList = new ArrayList<>(); String sqlPath = "/Users/wtz/dtstack/sql/test/FileDemoOne.sql"; Map<String, Object> conf = new HashMap<>(); JSONObject properties = new JSONObject(); //其他参数配置 properties.put("time.characteristic", "eventTime"); properties.put("timezone", TimeZone.getDefault()); properties.put("early.trigger", "1"); // 任务配置参数 conf.put("-sql", URLEncoder.encode(readSQL(sqlPath), StandardCharsets.UTF_8.name())); conf.put("-mode", "local"); conf.put("-name", "flinkStreamSQLLocalTest"); conf.put("-confProp", properties.toString()); conf.put("-pluginLoadMode", "LocalTest"); // conf.put("-checkResource", "true"); conf.put("-dirtyProperties", buildDirtyStr()); for (Map.Entry<String, Object> keyValue : conf.entrySet()) { propertiesList.add(keyValue.getKey()); propertiesList.add(keyValue.getValue().toString()); } Main.main(propertiesList.toArray(new String[0])); } private static String buildDirtyStr() { JSONObject jsonObject = new JSONObject(); jsonObject.put("type", "console"); // 多少 <SUF> jsonObject.put("printLimit", "100"); jsonObject.put("url", "jdbc:mysql://localhost:3306/tiezhu"); jsonObject.put("userName", "root"); jsonObject.put("password", "abc123"); jsonObject.put("isCreateTable", "false"); // 多少条数据写入一次 jsonObject.put("batchSize", "1"); jsonObject.put("tableName", "dirtyData"); return jsonObject.toJSONString(); } private static String readSQL(String sqlPath) { try { byte[] array = Files.readAllBytes(Paths.get(sqlPath)); return new String(array, StandardCharsets.UTF_8); } catch (IOException ioe) { LOG.error("Can not get the job info !!!", ioe); throw new RuntimeException(ioe); } } private static void setLogLevel(String level) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); ch.qos.logback.classic.Logger logger = loggerContext.getLogger("root"); logger.setLevel(Level.toLevel(level)); } }
0
843
8
985
7
1,022
6
985
7
1,173
13
false
false
false
false
false
true
54132_2
package com.njfu.model; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import com.njfu.entity.Player; import com.njfu.service.PlayerService; public class PlayerModel extends AbstractTableModel{ /** * */ private static final long serialVersionUID = 1L; //定义两个集合,一个用于装表头,一个用于装数据 ArrayList rowData,columnNames; PlayerService playerService = new PlayerService(); public PlayerModel(){ columnNames = new ArrayList<>(); columnNames.add("id"); columnNames.add("账号"); columnNames.add("密码"); columnNames.add("手机"); columnNames.add("状态"); columnNames.add("金币"); columnNames.add("钻石"); columnNames.add("等级"); columnNames.add("经验"); //装数据 List <Player> list = PlayerService.showDatabase(); rowData = new ArrayList(); for(int i = 0; i< list.size();i++){ //新建一个集合---排序 ArrayList array = new ArrayList(); array.add(list.get(i).getId()); array.add(list.get(i).getAccount()); array.add(list.get(i).getPassword()); array.add(list.get(i).getPhonenum()); array.add(list.get(i).getStation()); array.add(list.get(i).getGoldnum()); array.add(list.get(i).getDiamondnum()); array.add(list.get(i).getLv()); array.add(list.get(i).getEpx()); //将集合可添加到集合 rowData.add(array); } } @Override public int getRowCount() { return this.rowData.size(); } @Override public int getColumnCount() { return this.columnNames.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return ((ArrayList)this.rowData.get(rowIndex)).get(columnIndex); } @Override public String getColumnName(int column) { return (String) this.columnNames.get(column); } }
DVKunion/Knight
src/com/njfu/model/PlayerModel.java
576
//新建一个集合---排序
line_comment
zh-cn
package com.njfu.model; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import com.njfu.entity.Player; import com.njfu.service.PlayerService; public class PlayerModel extends AbstractTableModel{ /** * */ private static final long serialVersionUID = 1L; //定义两个集合,一个用于装表头,一个用于装数据 ArrayList rowData,columnNames; PlayerService playerService = new PlayerService(); public PlayerModel(){ columnNames = new ArrayList<>(); columnNames.add("id"); columnNames.add("账号"); columnNames.add("密码"); columnNames.add("手机"); columnNames.add("状态"); columnNames.add("金币"); columnNames.add("钻石"); columnNames.add("等级"); columnNames.add("经验"); //装数据 List <Player> list = PlayerService.showDatabase(); rowData = new ArrayList(); for(int i = 0; i< list.size();i++){ //新建 <SUF> ArrayList array = new ArrayList(); array.add(list.get(i).getId()); array.add(list.get(i).getAccount()); array.add(list.get(i).getPassword()); array.add(list.get(i).getPhonenum()); array.add(list.get(i).getStation()); array.add(list.get(i).getGoldnum()); array.add(list.get(i).getDiamondnum()); array.add(list.get(i).getLv()); array.add(list.get(i).getEpx()); //将集合可添加到集合 rowData.add(array); } } @Override public int getRowCount() { return this.rowData.size(); } @Override public int getColumnCount() { return this.columnNames.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return ((ArrayList)this.rowData.get(rowIndex)).get(columnIndex); } @Override public String getColumnName(int column) { return (String) this.columnNames.get(column); } }
0
454
6
576
6
569
6
576
6
736
12
false
false
false
false
false
true
13527_2
package com.dengzhou.sms; import com.dengzhou.utils.ESClient; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.get.GetIndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.query.Operator; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; public class create_sms_index { String index = "sms_logs_index"; String type = "sms_logs_type"; @Test public void create_index() throws IOException { Settings.Builder settings = Settings.builder() .put("number_of_shards", 3) .put("number_of_replicas", 1); XContentBuilder mappings = JsonXContent.contentBuilder() .startObject() .startObject("properties") .startObject("createDate") .field("type", "date") .field("format","yyyy-MM-dd") .endObject() .startObject("sendDate") .field("type", "date") .field("format", "yyyy-MM-dd") .endObject() .startObject("longCode") .field("type", "keyword") .endObject() .startObject("mobile") .field("type", "keyword") .endObject() .startObject("corpName") .field("type", "keyword") .endObject() .startObject("smsContent") .field("type", "text") .field("analyzer", "ik_max_word") .endObject() .startObject("state") .field("type", "integer") .endObject() .startObject("operatorid") .field("type", "integer") .endObject() .startObject("province") .field("type", "keyword") .endObject() .startObject("ipAddr") .field("type", "ip") .endObject() .startObject("replyTotal") .field("type", "integer") .endObject() .startObject("fee") .field("type", "long") .endObject() .endObject() .endObject(); CreateIndexRequest request = new CreateIndexRequest(index) .settings(settings) .mapping(type,mappings); RestHighLevelClient client = ESClient.getClient(); CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); System.out.println(response.toString()); } @Test public void exists() throws IOException { GetIndexRequest request = new GetIndexRequest(); request.indices(index); RestHighLevelClient client = ESClient.getClient(); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists); } @Test public void testQuery() throws IOException { // 1 创建Request对象 SearchRequest request = new SearchRequest(index); request.types(type); // 2 指定查询条件 SearchSourceBuilder builder = new SearchSourceBuilder(); builder.from(0); builder.size(5); builder.query(QueryBuilders.termQuery("province", "河北")); request.source(builder); // 3 执行查询 RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 4 获取到_source中的数据 for (SearchHit hit : response.getHits().getHits()) { Map<String, Object> result = hit.getSourceAsMap(); System.out.println(result); } } @Test public void test_terms() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.termsQuery("province","河北","河南")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse resp = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : resp.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_all() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchAllQuery()); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_field() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("smsContext","打车")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_boolean() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND)); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_multi_match() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); //builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND)); builder.query(QueryBuilders.multiMatchQuery("河北", "province", "smsContext")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()) { System.out.println(hit); } } }
DW-Zhou/ES-6.5.4
src/main/java/com/dengzhou/sms/create_sms_index.java
1,647
// 3 执行查询
line_comment
zh-cn
package com.dengzhou.sms; import com.dengzhou.utils.ESClient; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.get.GetIndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.query.Operator; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; public class create_sms_index { String index = "sms_logs_index"; String type = "sms_logs_type"; @Test public void create_index() throws IOException { Settings.Builder settings = Settings.builder() .put("number_of_shards", 3) .put("number_of_replicas", 1); XContentBuilder mappings = JsonXContent.contentBuilder() .startObject() .startObject("properties") .startObject("createDate") .field("type", "date") .field("format","yyyy-MM-dd") .endObject() .startObject("sendDate") .field("type", "date") .field("format", "yyyy-MM-dd") .endObject() .startObject("longCode") .field("type", "keyword") .endObject() .startObject("mobile") .field("type", "keyword") .endObject() .startObject("corpName") .field("type", "keyword") .endObject() .startObject("smsContent") .field("type", "text") .field("analyzer", "ik_max_word") .endObject() .startObject("state") .field("type", "integer") .endObject() .startObject("operatorid") .field("type", "integer") .endObject() .startObject("province") .field("type", "keyword") .endObject() .startObject("ipAddr") .field("type", "ip") .endObject() .startObject("replyTotal") .field("type", "integer") .endObject() .startObject("fee") .field("type", "long") .endObject() .endObject() .endObject(); CreateIndexRequest request = new CreateIndexRequest(index) .settings(settings) .mapping(type,mappings); RestHighLevelClient client = ESClient.getClient(); CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); System.out.println(response.toString()); } @Test public void exists() throws IOException { GetIndexRequest request = new GetIndexRequest(); request.indices(index); RestHighLevelClient client = ESClient.getClient(); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists); } @Test public void testQuery() throws IOException { // 1 创建Request对象 SearchRequest request = new SearchRequest(index); request.types(type); // 2 指定查询条件 SearchSourceBuilder builder = new SearchSourceBuilder(); builder.from(0); builder.size(5); builder.query(QueryBuilders.termQuery("province", "河北")); request.source(builder); // 3 <SUF> RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 4 获取到_source中的数据 for (SearchHit hit : response.getHits().getHits()) { Map<String, Object> result = hit.getSourceAsMap(); System.out.println(result); } } @Test public void test_terms() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.termsQuery("province","河北","河南")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse resp = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : resp.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_all() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchAllQuery()); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_field() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("smsContext","打车")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_boolean() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND)); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_multi_match() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); //builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND)); builder.query(QueryBuilders.multiMatchQuery("河北", "province", "smsContext")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()) { System.out.println(hit); } } }
0
1,406
7
1,647
5
1,780
5
1,647
5
1,972
12
false
false
false
false
false
true
15907_2
import java.util.LinkedList; public class P641 { public static void main(String[] args) { } } class MyCircularDeque { private int size = 0; private LinkedList<Integer> list = new LinkedList(); //初始化大小 public MyCircularDeque(int k) { this.size = k; } public boolean insertFront(int value) { //首先查看大小是否核算 if (list.size() == size){ return false; } list.addFirst(value); return true; } public boolean insertLast(int value) { //首先查看大小是否核算 if (list.size() == size){ return false; } list.addLast(value); return true; } public boolean deleteFront() { //判断大小是否为0,如果为0直接返回false if (list.size() == 0){ return false; } list.removeFirst(); return true; } public boolean deleteLast() { //判断大小是否为0,如果为0直接返回false if (list.size() == 0){ return false; } list.removeLast(); return true; } public int getFront() { //判断大小是否为0,如果为0直接返回-1 if (list.size() == 0){ return -1; } return list.getFirst(); } public int getRear() { if (list.size() == 0){ return -1; } return list.getLast(); } public boolean isEmpty() { return list.isEmpty(); } public boolean isFull() { return list.size() == size; } } /** * Your MyCircularDeque object will be instantiated and called as such: * MyCircularDeque obj = new MyCircularDeque(k); * boolean param_1 = obj.insertFront(value); * boolean param_2 = obj.insertLast(value); * boolean param_3 = obj.deleteFront(); * boolean param_4 = obj.deleteLast(); * int param_5 = obj.getFront(); * int param_6 = obj.getRear(); * boolean param_7 = obj.isEmpty(); * boolean param_8 = obj.isFull(); */
DaZuiZui/leetcode
P641.java
529
//首先查看大小是否核算
line_comment
zh-cn
import java.util.LinkedList; public class P641 { public static void main(String[] args) { } } class MyCircularDeque { private int size = 0; private LinkedList<Integer> list = new LinkedList(); //初始化大小 public MyCircularDeque(int k) { this.size = k; } public boolean insertFront(int value) { //首先查看大小是否核算 if (list.size() == size){ return false; } list.addFirst(value); return true; } public boolean insertLast(int value) { //首先 <SUF> if (list.size() == size){ return false; } list.addLast(value); return true; } public boolean deleteFront() { //判断大小是否为0,如果为0直接返回false if (list.size() == 0){ return false; } list.removeFirst(); return true; } public boolean deleteLast() { //判断大小是否为0,如果为0直接返回false if (list.size() == 0){ return false; } list.removeLast(); return true; } public int getFront() { //判断大小是否为0,如果为0直接返回-1 if (list.size() == 0){ return -1; } return list.getFirst(); } public int getRear() { if (list.size() == 0){ return -1; } return list.getLast(); } public boolean isEmpty() { return list.isEmpty(); } public boolean isFull() { return list.size() == size; } } /** * Your MyCircularDeque object will be instantiated and called as such: * MyCircularDeque obj = new MyCircularDeque(k); * boolean param_1 = obj.insertFront(value); * boolean param_2 = obj.insertLast(value); * boolean param_3 = obj.deleteFront(); * boolean param_4 = obj.deleteLast(); * int param_5 = obj.getFront(); * int param_6 = obj.getRear(); * boolean param_7 = obj.isEmpty(); * boolean param_8 = obj.isFull(); */
0
479
6
529
7
581
7
529
7
655
13
false
false
false
false
false
true
49972_6
package com.daemon.pas.presenter.player; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.MediaPlayer; import android.support.v4.content.LocalBroadcastManager; import com.daemon.framework.dutils.DLog; import com.daemon.pas.common.AppRunCache; import java.io.IOException; import java.util.List; /** * Created by Daemon on 2015/12/25. */ public class MusicPlayer implements BaseMusicPlayer, MediaPlayer.OnPreparedListener { public static final int State_Play = 0; public static final int State_Pasue = 1; public static final int State_Stop = 2; private Intent intent_update; private MediaPlayer mediaPlayer; //播放的music index 初始状态 private int play_index = 0; //当前音乐状态 private int Music_State; private List<String> musicList; private String path; private LocalBroadcastManager mLocalBroadcastManager; private IntentFilter intentFilter; private MusicPlayBroadReceiver myReceiver; private boolean isDestroy=false; public MusicPlayer(Context context) { Music_State = State_Stop; mediaPlayer = new MediaPlayer(); musicList = AppRunCache.musicList; intentFilter = new IntentFilter(); intentFilter.addAction(IntentFilterUtils.Music_Pause); intentFilter.addAction(IntentFilterUtils.Music_Resume); intentFilter.addAction(IntentFilterUtils.Music_Next); intentFilter.addAction(IntentFilterUtils.Music_Previous); intentFilter.addAction(IntentFilterUtils.Music_Play_Pause_Onlcik); intentFilter.addAction(IntentFilterUtils.Progress); intentFilter.addAction(IntentFilterUtils.Music_Reset); mLocalBroadcastManager = LocalBroadcastManager.getInstance(context); myReceiver = new MusicPlayBroadReceiver(); mLocalBroadcastManager.registerReceiver(myReceiver, intentFilter); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { //自动播放结束后 下一首 先通知 DLog.e("setOnCompletionListener"); next(); } }); DLog.e("onCreate"); mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mediaPlayer) { DLog.e("setOnSeekCompleteListener "); if (Music_State == State_Play) { mediaPlayer.start(); } } }); intent_update = new Intent(IntentFilterUtils.Progress_Update); mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) { intent_update.putExtra(IntentFilterUtils.Progress_Update, mediaPlayer.getCurrentPosition()); //DLog.e("setOnBufferingUpdateListener " + mediaPlayer.getCurrentPosition() + " " + i); mLocalBroadcastManager.sendBroadcast(intent_update); } }); play(); } /** * 对外点击播放按钮提供的方法 */ public void actionPlay() { switch (Music_State) { case State_Play: pause(); break; case State_Pasue: resume(); break; case State_Stop: Music_State = State_Play; if(mediaPlayer.getCurrentPosition()!=0){ //说明是拖拽过的 mediaPlayer.start(); sendUIAnimatorPlay(); }else { play(); } break; } } @Override public void play() { if(musicList==null || musicList.size()==0){ return; } path = musicList.get(play_index); try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(this); } catch (IOException e) { e.printStackTrace(); } DLog.e("play " + play_index); } @Override public void pause() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); Music_State = State_Pasue; mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Pause)); } DLog.e("pause " + musicList.size() + " -> " + play_index); } @Override public void resume() { if (Music_State == State_Pasue) { mediaPlayer.start(); Music_State = State_Play; mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Resume)); } DLog.e("resume " + musicList.size() + " -> " + play_index); } @Override public void seekTo(int progress) { DLog.e("接受 " + progress); mediaPlayer.seekTo(progress * mediaPlayer.getDuration() / 100); } /** * 上一首 */ public void previous() { if (play_index == 0) { sendNoPrevious(); return; } else { play_index--; } Music_State=State_Play; play(); sendCurrentPosition(); DLog.e("previous " + musicList.size() + " -> " + play_index); } /** * 下一首 */ public void next() { Music_State=State_Play; if (play_index == musicList.size() - 1) { play_index = 0; } else { play_index++; } play(); sendCurrentPosition(); DLog.e("next " + musicList.size() + " -> " + play_index); } /** * 当前显示的数据 停止上一个动画 */ private void sendCurrentPosition() { Intent intent = new Intent(IntentFilterUtils.Position); intent.putExtra(IntentFilterUtils.Index, play_index); mLocalBroadcastManager.sendBroadcast(intent); } private void reset() { play_index = 0; musicList = AppRunCache.musicList; sendCurrentPosition(); play(); } @Override public void destory() { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } mLocalBroadcastManager.unregisterReceiver(myReceiver); } /** * 通知没有上一首了 */ private void sendNoPrevious() { Intent intent = new Intent(IntentFilterUtils.Music_Previous_NO); mLocalBroadcastManager.sendBroadcast(intent); } /** * 通知 ui 改变 动画开始 显示当前歌曲信息 */ private void sendUIAnimatorPlay() { //缓存完毕 发送通知 动画 做出改变 Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK); intent.putExtra(IntentFilterUtils.Index, play_index); intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration()); mLocalBroadcastManager.sendBroadcast(intent); } @Override public void onPrepared(MediaPlayer mp) { if (Music_State != State_Stop) { //只要缓存完毕 就开始放歌 不不管现在是暂停还是播放 只要下一首就继续播放 mediaPlayer.start(); sendUIAnimatorPlay(); Music_State = State_Play; DLog.e("onPrepared pay" + musicList.size() + " -> " + play_index); }else { //只要缓冲完了 就将真个音乐的size传送 sendMusicSize(); Music_State=State_Pasue; DLog.e("onPrepared stop" + musicList.size() + " -> " + play_index); } } private void sendMusicSize() { //有位置就播放 没有就显示大小 Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK); intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration()); mLocalBroadcastManager.sendBroadcast(intent); } class MusicPlayBroadReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case IntentFilterUtils.Music_Play_Pause_Onlcik: DLog.e("Music_Play_Pause_Onlcik"); actionPlay(); break; case IntentFilterUtils.Music_Next: DLog.e("Music_Next"); next(); break; case IntentFilterUtils.Music_Previous: DLog.e("Music_Previous"); previous(); break; case IntentFilterUtils.Music_Reset: reset(); break; case IntentFilterUtils.Progress: int progress = intent.getIntExtra(IntentFilterUtils.Progress, -1); seekTo(progress); break; } } } }
Daemon1993/Pas
app/src/main/java/com/daemon/pas/presenter/player/MusicPlayer.java
2,096
//说明是拖拽过的
line_comment
zh-cn
package com.daemon.pas.presenter.player; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.MediaPlayer; import android.support.v4.content.LocalBroadcastManager; import com.daemon.framework.dutils.DLog; import com.daemon.pas.common.AppRunCache; import java.io.IOException; import java.util.List; /** * Created by Daemon on 2015/12/25. */ public class MusicPlayer implements BaseMusicPlayer, MediaPlayer.OnPreparedListener { public static final int State_Play = 0; public static final int State_Pasue = 1; public static final int State_Stop = 2; private Intent intent_update; private MediaPlayer mediaPlayer; //播放的music index 初始状态 private int play_index = 0; //当前音乐状态 private int Music_State; private List<String> musicList; private String path; private LocalBroadcastManager mLocalBroadcastManager; private IntentFilter intentFilter; private MusicPlayBroadReceiver myReceiver; private boolean isDestroy=false; public MusicPlayer(Context context) { Music_State = State_Stop; mediaPlayer = new MediaPlayer(); musicList = AppRunCache.musicList; intentFilter = new IntentFilter(); intentFilter.addAction(IntentFilterUtils.Music_Pause); intentFilter.addAction(IntentFilterUtils.Music_Resume); intentFilter.addAction(IntentFilterUtils.Music_Next); intentFilter.addAction(IntentFilterUtils.Music_Previous); intentFilter.addAction(IntentFilterUtils.Music_Play_Pause_Onlcik); intentFilter.addAction(IntentFilterUtils.Progress); intentFilter.addAction(IntentFilterUtils.Music_Reset); mLocalBroadcastManager = LocalBroadcastManager.getInstance(context); myReceiver = new MusicPlayBroadReceiver(); mLocalBroadcastManager.registerReceiver(myReceiver, intentFilter); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { //自动播放结束后 下一首 先通知 DLog.e("setOnCompletionListener"); next(); } }); DLog.e("onCreate"); mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mediaPlayer) { DLog.e("setOnSeekCompleteListener "); if (Music_State == State_Play) { mediaPlayer.start(); } } }); intent_update = new Intent(IntentFilterUtils.Progress_Update); mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) { intent_update.putExtra(IntentFilterUtils.Progress_Update, mediaPlayer.getCurrentPosition()); //DLog.e("setOnBufferingUpdateListener " + mediaPlayer.getCurrentPosition() + " " + i); mLocalBroadcastManager.sendBroadcast(intent_update); } }); play(); } /** * 对外点击播放按钮提供的方法 */ public void actionPlay() { switch (Music_State) { case State_Play: pause(); break; case State_Pasue: resume(); break; case State_Stop: Music_State = State_Play; if(mediaPlayer.getCurrentPosition()!=0){ //说明 <SUF> mediaPlayer.start(); sendUIAnimatorPlay(); }else { play(); } break; } } @Override public void play() { if(musicList==null || musicList.size()==0){ return; } path = musicList.get(play_index); try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(this); } catch (IOException e) { e.printStackTrace(); } DLog.e("play " + play_index); } @Override public void pause() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); Music_State = State_Pasue; mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Pause)); } DLog.e("pause " + musicList.size() + " -> " + play_index); } @Override public void resume() { if (Music_State == State_Pasue) { mediaPlayer.start(); Music_State = State_Play; mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Resume)); } DLog.e("resume " + musicList.size() + " -> " + play_index); } @Override public void seekTo(int progress) { DLog.e("接受 " + progress); mediaPlayer.seekTo(progress * mediaPlayer.getDuration() / 100); } /** * 上一首 */ public void previous() { if (play_index == 0) { sendNoPrevious(); return; } else { play_index--; } Music_State=State_Play; play(); sendCurrentPosition(); DLog.e("previous " + musicList.size() + " -> " + play_index); } /** * 下一首 */ public void next() { Music_State=State_Play; if (play_index == musicList.size() - 1) { play_index = 0; } else { play_index++; } play(); sendCurrentPosition(); DLog.e("next " + musicList.size() + " -> " + play_index); } /** * 当前显示的数据 停止上一个动画 */ private void sendCurrentPosition() { Intent intent = new Intent(IntentFilterUtils.Position); intent.putExtra(IntentFilterUtils.Index, play_index); mLocalBroadcastManager.sendBroadcast(intent); } private void reset() { play_index = 0; musicList = AppRunCache.musicList; sendCurrentPosition(); play(); } @Override public void destory() { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } mLocalBroadcastManager.unregisterReceiver(myReceiver); } /** * 通知没有上一首了 */ private void sendNoPrevious() { Intent intent = new Intent(IntentFilterUtils.Music_Previous_NO); mLocalBroadcastManager.sendBroadcast(intent); } /** * 通知 ui 改变 动画开始 显示当前歌曲信息 */ private void sendUIAnimatorPlay() { //缓存完毕 发送通知 动画 做出改变 Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK); intent.putExtra(IntentFilterUtils.Index, play_index); intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration()); mLocalBroadcastManager.sendBroadcast(intent); } @Override public void onPrepared(MediaPlayer mp) { if (Music_State != State_Stop) { //只要缓存完毕 就开始放歌 不不管现在是暂停还是播放 只要下一首就继续播放 mediaPlayer.start(); sendUIAnimatorPlay(); Music_State = State_Play; DLog.e("onPrepared pay" + musicList.size() + " -> " + play_index); }else { //只要缓冲完了 就将真个音乐的size传送 sendMusicSize(); Music_State=State_Pasue; DLog.e("onPrepared stop" + musicList.size() + " -> " + play_index); } } private void sendMusicSize() { //有位置就播放 没有就显示大小 Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK); intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration()); mLocalBroadcastManager.sendBroadcast(intent); } class MusicPlayBroadReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case IntentFilterUtils.Music_Play_Pause_Onlcik: DLog.e("Music_Play_Pause_Onlcik"); actionPlay(); break; case IntentFilterUtils.Music_Next: DLog.e("Music_Next"); next(); break; case IntentFilterUtils.Music_Previous: DLog.e("Music_Previous"); previous(); break; case IntentFilterUtils.Music_Reset: reset(); break; case IntentFilterUtils.Progress: int progress = intent.getIntExtra(IntentFilterUtils.Progress, -1); seekTo(progress); break; } } } }
0
1,845
6
2,096
9
2,241
6
2,096
9
2,664
12
false
false
false
false
false
true
44720_0
package main.Array; public interface Array { //查找对付 public int find(String element); //插入 public void insert(String element); //删除 public void delete(String element); //列出所有元素 public void display(); }
Daemonxiao/DataStructures
src/main/Array/Array.java
60
//查找对付
line_comment
zh-cn
package main.Array; public interface Array { //查找 <SUF> public int find(String element); //插入 public void insert(String element); //删除 public void delete(String element); //列出所有元素 public void display(); }
0
54
3
60
4
66
3
60
4
81
7
false
false
false
false
false
true
49387_3
package com.dai.entity; import java.util.Date; /** * 店铺 * @author 18491 * */ public class Shop { private Long shopId; private String shopName; private String shopDesc; //店铺地址 private String shopAddr; //店铺联系方式 private String phone; //店铺缩略图的地址 private String shopImg; private Integer priority; private Date createTime; private Date lastEditTime; //-1:不可用 0:审核中 1:可用 private Integer enableStatus; //超级管理员给店家的提醒 private String advice; //店铺的位置 private Area area; //店铺所属人 private PersonInfo owner; //店铺的类别 private ShopCategory shopCategory; public Long getShopId() { return shopId; } public void setShopId(Long shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public String getShopDesc() { return shopDesc; } public void setShopDesc(String shopDesc) { this.shopDesc = shopDesc; } public String getShopAddr() { return shopAddr; } public void setShopAddr(String shopAddr) { this.shopAddr = shopAddr; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getShopImg() { return shopImg; } public void setShopImg(String shopImg) { this.shopImg = shopImg; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastEditTime() { return lastEditTime; } public void setLastEditTime(Date lastEditTime) { this.lastEditTime = lastEditTime; } public Integer getEnableStatus() { return enableStatus; } public void setEnableStatus(Integer enableStatus) { this.enableStatus = enableStatus; } public String getAdvice() { return advice; } public void setAdvice(String advice) { this.advice = advice; } public Area getArea() { return area; } public void setArea(Area area) { this.area = area; } public PersonInfo getOwner() { return owner; } public void setOwner(PersonInfo owner) { this.owner = owner; } public ShopCategory getShopCategory() { return shopCategory; } public void setShopCategory(ShopCategory shopCategory) { this.shopCategory = shopCategory; } }
DaiOwen/DeskMate
src/main/java/com/dai/entity/Shop.java
819
//店铺缩略图的地址
line_comment
zh-cn
package com.dai.entity; import java.util.Date; /** * 店铺 * @author 18491 * */ public class Shop { private Long shopId; private String shopName; private String shopDesc; //店铺地址 private String shopAddr; //店铺联系方式 private String phone; //店铺 <SUF> private String shopImg; private Integer priority; private Date createTime; private Date lastEditTime; //-1:不可用 0:审核中 1:可用 private Integer enableStatus; //超级管理员给店家的提醒 private String advice; //店铺的位置 private Area area; //店铺所属人 private PersonInfo owner; //店铺的类别 private ShopCategory shopCategory; public Long getShopId() { return shopId; } public void setShopId(Long shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public String getShopDesc() { return shopDesc; } public void setShopDesc(String shopDesc) { this.shopDesc = shopDesc; } public String getShopAddr() { return shopAddr; } public void setShopAddr(String shopAddr) { this.shopAddr = shopAddr; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getShopImg() { return shopImg; } public void setShopImg(String shopImg) { this.shopImg = shopImg; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastEditTime() { return lastEditTime; } public void setLastEditTime(Date lastEditTime) { this.lastEditTime = lastEditTime; } public Integer getEnableStatus() { return enableStatus; } public void setEnableStatus(Integer enableStatus) { this.enableStatus = enableStatus; } public String getAdvice() { return advice; } public void setAdvice(String advice) { this.advice = advice; } public Area getArea() { return area; } public void setArea(Area area) { this.area = area; } public PersonInfo getOwner() { return owner; } public void setOwner(PersonInfo owner) { this.owner = owner; } public ShopCategory getShopCategory() { return shopCategory; } public void setShopCategory(ShopCategory shopCategory) { this.shopCategory = shopCategory; } }
0
620
7
819
9
795
7
819
9
916
15
false
false
false
false
false
true
39416_2
package com.damon.chain.travel2; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * 功能:链管理者,链上所有节点都在此管理 * * @author Damon * @since 2018-12-23 21:54 */ @Slf4j public class HandlerChain { private List<Handler> handlerList = new ArrayList<>(); /** * 维护当前链上位置 */ private int pos; /** * 链的长度 */ private int handlerLength; public void addHandler(Handler handler) { handlerList.add(handler); handlerLength = handlerList.size(); } public void handle(String name, double wallet) { if (CollectionUtils.isEmpty(handlerList)) { log.error("有钱,但没提供服务,{}也估计就只能步行了。", name); return; } if (pos >= handlerLength) { log.error("身上钱不够,{}也估计就只能步行了。", name); reuse(); return; } Handler handler = handlerList.get(pos++); if (Objects.isNull(handler)) { log.error("假服务,{}也估计就只能步行了。", name); reuse(); return; } handler.handleRequest(name, wallet, this); } /** * 链重新使用 */ public void reuse() { pos = 0; } }
DamonChow/design_pattern
chain/src/main/java/com/damon/chain/travel2/HandlerChain.java
388
/** * 链的长度 */
block_comment
zh-cn
package com.damon.chain.travel2; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * 功能:链管理者,链上所有节点都在此管理 * * @author Damon * @since 2018-12-23 21:54 */ @Slf4j public class HandlerChain { private List<Handler> handlerList = new ArrayList<>(); /** * 维护当前链上位置 */ private int pos; /** * 链的长 <SUF>*/ private int handlerLength; public void addHandler(Handler handler) { handlerList.add(handler); handlerLength = handlerList.size(); } public void handle(String name, double wallet) { if (CollectionUtils.isEmpty(handlerList)) { log.error("有钱,但没提供服务,{}也估计就只能步行了。", name); return; } if (pos >= handlerLength) { log.error("身上钱不够,{}也估计就只能步行了。", name); reuse(); return; } Handler handler = handlerList.get(pos++); if (Objects.isNull(handler)) { log.error("假服务,{}也估计就只能步行了。", name); reuse(); return; } handler.handleRequest(name, wallet, this); } /** * 链重新使用 */ public void reuse() { pos = 0; } }
0
336
11
388
9
405
10
388
9
500
14
false
false
false
false
false
true
54611_4
package com.sensor.entity; import com.sensor.Generate.*; import java.util.List; /** * Created by DanLongChen on 2018/11/26 * 网络节点类 **/ public class GANode extends Nodes { private int id; //唯一标示节点 private String data;//节点的数据 private Point point;//节点位置信息 private List<GANode> neibor;//邻居 private boolean state;//是否损坏 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } public List<GANode> getNeibor() { return neibor; } public void setNeibor(List<GANode> neibor) { this.neibor = neibor; } public boolean isState() { return state; } public void setState(boolean state) { this.state = state; } }
DanLongChen/SensorSys
src/main/java/com/sensor/entity/GANode.java
292
//是否损坏
line_comment
zh-cn
package com.sensor.entity; import com.sensor.Generate.*; import java.util.List; /** * Created by DanLongChen on 2018/11/26 * 网络节点类 **/ public class GANode extends Nodes { private int id; //唯一标示节点 private String data;//节点的数据 private Point point;//节点位置信息 private List<GANode> neibor;//邻居 private boolean state;//是否 <SUF> public int getId() { return id; } public void setId(int id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } public List<GANode> getNeibor() { return neibor; } public void setNeibor(List<GANode> neibor) { this.neibor = neibor; } public boolean isState() { return state; } public void setState(boolean state) { this.state = state; } }
0
268
3
292
6
316
3
292
6
373
9
false
false
false
false
false
true
36674_17
package com.real.simhotel.presenter; import com.real.simhotel.events.BaseStatus; import com.real.simhotel.events.EventCode; import com.real.simhotel.events.TrainStatus; import com.real.simhotel.events.StatusManager; import com.real.simhotel.presenter.base.BasePresenter; import com.real.simhotel.utils.log.KLog; import com.real.simhotel.view.adapter.DynamicListAdapter; import com.real.simhotel.view.adapter.DynamicListModel; import com.real.simhotel.view.adapter.DynamicListModelFactory; import com.real.simhotel.view.fragment.student.CeoNormalFragment; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.List; /** * Created by liudan on 2016/12/19. */ public class CeoNormalPresenter extends BasePresenter{ private CeoNormalFragment mView; private List<DynamicListModel> list; public static final int CEO_DECISION_HIRE = 1; public static final int CEO_DECISION_LOAN = 2; public CeoNormalPresenter(CeoNormalFragment view){ mView = view; } public DynamicListAdapter.NormalChooseInterface getChooseInterface() { return mChooseInterface; } @Override public void handleStatus(BaseStatus event) { switch (event.getStatus()){ case EventCode.GroupCode.GROUP_CEO_HIRE_ING: //开始 增加 雇员 信息 TODO 招聘会的时间 if (list == null){ list = new ArrayList<>(); } list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?", application.training.getCurrentCycle() + "", CEO_DECISION_HIRE)); //加载列表 mView.loadList(list); application.traingingStatusManager.consumeStatus(event); break; } } @Override public void destroy() { super.destroy(); EventBus.getDefault().unregister(this); } @Override public void requestData(Object... o) { super.requestData(o); // KLog.d("id = " + application.mHotel.getId()); // list = new ArrayList(); // if (application.group.getGroupStatus() == EventCode.GroupCode.GROUP_CEO_HIRE_ING){ // //增加一条招聘信息 // // list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?", // application.training.getCurrentCycle()+"", // CEO_DECISION_HIRE)); // // } // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 80 玩 ,支出 10 玩","2016年6月")); // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 90 玩 ,支出 30 玩","2016年6月")); // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 100 玩 ,支出 30 玩","2016年7月")); // list.add(DynamicListModelFactory.modelForCeoDecisionMessage("大哥你要破产了,贷款不?","2016年9月",2)); //加载列表 // mView.loadList(list); } /** * 监听list中的选项 */ private DynamicListAdapter.NormalChooseInterface mChooseInterface = new DynamicListAdapter.NormalChooseInterface() { @Override public void onChoose(DynamicListModel model, Boolean hasConfirm) { //修改状态 mView.showLoading(); int eventCode = 0; if ( (int)model.ext == CEO_DECISION_HIRE) { eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_REJECT; if (hasConfirm) eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_CONFIRM; }else if ((int)model.ext == CEO_DECISION_LOAN){ eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_REJECT; if (hasConfirm) eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_CONFIRM; } application.traingingStatusManager.changeGroupStatus( eventCode, new StatusManager.StatusChangeListener() { @Override public void OnChangedSuccess() { mView.disMissLoading(); if (hasConfirm){ model.butonChooseInfo = "已开始"; mView.showToast("已确认"); }else { model.butonChooseInfo = "已放弃"; mView.showToast("已放弃"); } model.hasChoose = true; mView.reload(); } @Override public void OnChangedFailed(String erro) { mView.disMissLoading(); mView.showToast("请求失败请稍后再试"); } }); } }; }
Danny1451/Simhotel
app/src/main/java/com/real/simhotel/presenter/CeoNormalPresenter.java
1,267
//修改状态
line_comment
zh-cn
package com.real.simhotel.presenter; import com.real.simhotel.events.BaseStatus; import com.real.simhotel.events.EventCode; import com.real.simhotel.events.TrainStatus; import com.real.simhotel.events.StatusManager; import com.real.simhotel.presenter.base.BasePresenter; import com.real.simhotel.utils.log.KLog; import com.real.simhotel.view.adapter.DynamicListAdapter; import com.real.simhotel.view.adapter.DynamicListModel; import com.real.simhotel.view.adapter.DynamicListModelFactory; import com.real.simhotel.view.fragment.student.CeoNormalFragment; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.List; /** * Created by liudan on 2016/12/19. */ public class CeoNormalPresenter extends BasePresenter{ private CeoNormalFragment mView; private List<DynamicListModel> list; public static final int CEO_DECISION_HIRE = 1; public static final int CEO_DECISION_LOAN = 2; public CeoNormalPresenter(CeoNormalFragment view){ mView = view; } public DynamicListAdapter.NormalChooseInterface getChooseInterface() { return mChooseInterface; } @Override public void handleStatus(BaseStatus event) { switch (event.getStatus()){ case EventCode.GroupCode.GROUP_CEO_HIRE_ING: //开始 增加 雇员 信息 TODO 招聘会的时间 if (list == null){ list = new ArrayList<>(); } list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?", application.training.getCurrentCycle() + "", CEO_DECISION_HIRE)); //加载列表 mView.loadList(list); application.traingingStatusManager.consumeStatus(event); break; } } @Override public void destroy() { super.destroy(); EventBus.getDefault().unregister(this); } @Override public void requestData(Object... o) { super.requestData(o); // KLog.d("id = " + application.mHotel.getId()); // list = new ArrayList(); // if (application.group.getGroupStatus() == EventCode.GroupCode.GROUP_CEO_HIRE_ING){ // //增加一条招聘信息 // // list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?", // application.training.getCurrentCycle()+"", // CEO_DECISION_HIRE)); // // } // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 80 玩 ,支出 10 玩","2016年6月")); // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 90 玩 ,支出 30 玩","2016年6月")); // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 100 玩 ,支出 30 玩","2016年7月")); // list.add(DynamicListModelFactory.modelForCeoDecisionMessage("大哥你要破产了,贷款不?","2016年9月",2)); //加载列表 // mView.loadList(list); } /** * 监听list中的选项 */ private DynamicListAdapter.NormalChooseInterface mChooseInterface = new DynamicListAdapter.NormalChooseInterface() { @Override public void onChoose(DynamicListModel model, Boolean hasConfirm) { //修改 <SUF> mView.showLoading(); int eventCode = 0; if ( (int)model.ext == CEO_DECISION_HIRE) { eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_REJECT; if (hasConfirm) eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_CONFIRM; }else if ((int)model.ext == CEO_DECISION_LOAN){ eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_REJECT; if (hasConfirm) eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_CONFIRM; } application.traingingStatusManager.changeGroupStatus( eventCode, new StatusManager.StatusChangeListener() { @Override public void OnChangedSuccess() { mView.disMissLoading(); if (hasConfirm){ model.butonChooseInfo = "已开始"; mView.showToast("已确认"); }else { model.butonChooseInfo = "已放弃"; mView.showToast("已放弃"); } model.hasChoose = true; mView.reload(); } @Override public void OnChangedFailed(String erro) { mView.disMissLoading(); mView.showToast("请求失败请稍后再试"); } }); } }; }
0
1,029
3
1,267
3
1,235
3
1,267
3
1,591
5
false
false
false
false
false
true
40713_1
package com.dl.officialsite.member; import com.dl.officialsite.common.privacy.PrivacyEncrypt; import com.dl.officialsite.common.privacy.PrivacyTypeEnum; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import java.io.Serializable; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString @EqualsAndHashCode(onlyExplicitlyIncluded = true) @EntityListeners(AuditingEntityListener.class) @Entity @DynamicUpdate @Table(name = "member", schema = "dl", uniqueConstraints = { @UniqueConstraint(name = "address", columnNames = {"address"}), @UniqueConstraint(name = "tweetId", columnNames = {"tweetId"}), @UniqueConstraint(name = "githubId", columnNames = {"githubId"}), @UniqueConstraint(name = "nickName", columnNames = {"nickName"})}) public class Member implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 42) @NotNull private String address; @Column(unique = true, length = 40) @NotNull @PrivacyEncrypt(type = PrivacyTypeEnum.EMAIL) private String email; @Column(unique = true, length = 20) @NotNull private String nickName; private int role; // 0开发者,1 设计师 2产品 3运营 4 测试 5 运维 6项目经理 7 研究员 8 投资人 9 市场 10 数据分析师 11 其他 @Column(unique = true, length = 38) private String githubId; @Column(length = 20) private String tweetId; @Column(unique = true, length = 64) private String tweetScreenName; @Column(length = 20) private String telegramId; @Column(length = 20) private String wechatId; private String avatar; private String techStack; //前端 ,后端 , 全栈, 运维,DBA, UI/UX, AI, 密码学,智能合约,数据分析, 共识算法,金融,数学, 网络安全, 英语, 其他 private String programing; // optional private String interests; //兴趣 private String city; private int shareCount; private int rewardCount; @CreatedDate @Column(updatable = false) private Long createTime; @LastModifiedDate @Column(updatable = false, nullable = false) private Long updateTime; //todo private Long workStatus; private int githubStatus; private int twitterStatus; //@PrivacyEncrypt(type= CUSTOMER) @JsonIgnore private String resume; /** * 1 forbidden 0 normal */ @Column(columnDefinition = "tinyint default 0") private Integer status = 0; }
Dapp-Learning-DAO/Official-website-backend
src/main/java/com/dl/officialsite/member/Member.java
857
//前端 ,后端 , 全栈, 运维,DBA, UI/UX, AI, 密码学,智能合约,数据分析, 共识算法,金融,数学, 网络安全, 英语, 其他
line_comment
zh-cn
package com.dl.officialsite.member; import com.dl.officialsite.common.privacy.PrivacyEncrypt; import com.dl.officialsite.common.privacy.PrivacyTypeEnum; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import java.io.Serializable; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString @EqualsAndHashCode(onlyExplicitlyIncluded = true) @EntityListeners(AuditingEntityListener.class) @Entity @DynamicUpdate @Table(name = "member", schema = "dl", uniqueConstraints = { @UniqueConstraint(name = "address", columnNames = {"address"}), @UniqueConstraint(name = "tweetId", columnNames = {"tweetId"}), @UniqueConstraint(name = "githubId", columnNames = {"githubId"}), @UniqueConstraint(name = "nickName", columnNames = {"nickName"})}) public class Member implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 42) @NotNull private String address; @Column(unique = true, length = 40) @NotNull @PrivacyEncrypt(type = PrivacyTypeEnum.EMAIL) private String email; @Column(unique = true, length = 20) @NotNull private String nickName; private int role; // 0开发者,1 设计师 2产品 3运营 4 测试 5 运维 6项目经理 7 研究员 8 投资人 9 市场 10 数据分析师 11 其他 @Column(unique = true, length = 38) private String githubId; @Column(length = 20) private String tweetId; @Column(unique = true, length = 64) private String tweetScreenName; @Column(length = 20) private String telegramId; @Column(length = 20) private String wechatId; private String avatar; private String techStack; //前端 <SUF> private String programing; // optional private String interests; //兴趣 private String city; private int shareCount; private int rewardCount; @CreatedDate @Column(updatable = false) private Long createTime; @LastModifiedDate @Column(updatable = false, nullable = false) private Long updateTime; //todo private Long workStatus; private int githubStatus; private int twitterStatus; //@PrivacyEncrypt(type= CUSTOMER) @JsonIgnore private String resume; /** * 1 forbidden 0 normal */ @Column(columnDefinition = "tinyint default 0") private Integer status = 0; }
0
752
58
857
60
871
47
857
60
1,087
87
false
false
false
false
false
true
31252_1
package org.datasays.wes.demo.fetch; import okhttp3.Cache; import okhttp3.OkHttpClient; import org.datasays.util.JsonObjGetter; import org.datasays.util.WCfg; import org.datasays.util.WPage; import org.datasays.util.WPageIterator; import org.datasays.wes.EsBaseService; import org.datasays.wes.core.HttpException; import org.datasays.wes.core.JsonObj; import org.datasays.wes.core.RequestInfo; import org.datasays.wes.core.WHttpClient; import org.datasays.wes.toolkit.WGsonConvert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by watano on 2016/12/5. */ public class BaiduFetcher { private static Logger LOG = LoggerFactory.getLogger(BaiduFetcher.class); private final int FetchInterval = 1;//间隔时间,单位s public final String index = "fetchdata"; public final String type = "BaiduMap"; private WHttpClient baiduClient; private EsBaseService esHelper; public String appKey; public String appSecret; public BaiduFetcher(String appKey, String appSecret) { this.appKey = appKey; this.appSecret = appSecret; } public void init() { OkHttpClient.Builder cBuilder = new OkHttpClient.Builder(); cBuilder.cache(new Cache(new File("./build/baidu"), 10000)); baiduClient = new WHttpClient(cBuilder.build(), new WGsonConvert()); baiduClient.setLogFlag(false, false, true); esHelper = new EsBaseService(); esHelper.init(WCfg.getValue("ES.server"), null, null); } private RequestInfo create() { RequestInfo action = new RequestInfo("http://api.map.baidu.com/place/v2/"); action.addParams("ak", appKey); return action; } public JsonObjGetter searchPOIByRegion(WPage page, String query, String region) throws HttpException { RequestInfo action = create(); action.setUrl("search"); action.addParams("scope", 2); action.addParams("output", "json"); action.addParams("query", query); action.addParams("region", region); action.addParams("page_size", page.getSize()); if (page.getPageNo() > 0) { action.addParams("page_num", page.getPageNo()-1); } LOG.info(page.toText()); JsonObjGetter result = new JsonObjGetter(baiduClient.get(action, Object.class)); if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) { if (result.num("total") != null && result.num("total").intValue() > 0) { page.setTotal(result.num("total").intValue()); } } return result; } public void fetchALLPOIByRegion(String query, String region){ WPage page = new WPage(); WPageIterator<Object> pageIterator = new WPageIterator<Object>(page) { @Override public void doSearch() { try { JsonObjGetter result = searchPOIByRegion(getPage(), query, region); if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) { int total = 0; if (result.num("total") != null && result.num("total").intValue() > 0) { total = result.num("total").intValue(); } List<Object> items = new ArrayList<>(); if (result.list("results") != null) { items.addAll(result.list("results")); } update(items, total); Thread.sleep(FetchInterval*1000); } } catch (Exception e) { e.printStackTrace(); } } }; while (pageIterator.hasNext()) { Object item = pageIterator.next(); save(item); } } public void save(Object item) { try { esHelper.index(index, type, null, item); } catch (Exception e) { LOG.error(e.getMessage(), e); } } public static void main(String[] args) { JsonObj allIndustry = new JsonObj(); allIndustry.lstAdd("美食", "中餐厅", "外国餐厅", "小吃快餐店", "蛋糕甜品店", "咖啡厅", "茶座", "酒吧"); allIndustry.lstAdd("酒店", "星级酒店", "快捷酒店", "公寓式酒店"); allIndustry.lstAdd("购物", "购物中心", "超市", "便利店", "家居建材", "家电数码", "商铺", "集市"); allIndustry.lstAdd("生活服务", "通讯营业厅", "邮局", "物流公司", "售票处", "洗衣店", "图文快印店", "照相馆", "房产中介机构", "公用事业", "维修点", "家政服务", "殡葬服务", "彩票销售点", "宠物服务", "报刊亭", "公共厕所"); allIndustry.lstAdd("丽人", "美容", "美发", "美甲", "美体"); allIndustry.lstAdd("旅游景点", "公园", "动物园", "植物园", "游乐园", "博物馆", "水族馆", "海滨浴场", "文物古迹", "教堂", "风景区"); allIndustry.lstAdd("休闲娱乐", "度假村", "农家院", "电影院", "KTV", "剧院", "歌舞厅", "网吧", "游戏场所", "洗浴按摩", "休闲广场"); allIndustry.lstAdd("运动健身", "体育场馆", "极限运动场所", "健身中心"); allIndustry.lstAdd("教育培训", "高等院校", "中学", "小学", "幼儿园", "成人教育", "亲子教育", "特殊教育学校", "留学中介机构", "科研机构", "培训机构", "图书馆", "科技馆"); allIndustry.lstAdd("文化传媒", "新闻出版", "广播电视", "艺术团体", "美术馆", "展览馆", "文化宫"); allIndustry.lstAdd("医疗", "综合医院", "专科医院", "诊所", "药店", "体检机构", "疗养院", "急救中心", "疾控中心"); allIndustry.lstAdd("汽车服务", "汽车销售", "汽车维修", "汽车美容", "汽车配件", "汽车租赁", "汽车检测场"); allIndustry.lstAdd("交通设施", "飞机场", "火车站", "地铁站", "长途汽车站", "公交车站", "港口", "停车场", "加油加气站", "服务区", "收费站", "桥"); allIndustry.lstAdd("金融", "银行", "ATM", "信用社", "投资理财", "典当行"); allIndustry.lstAdd("房地产", "写字楼", "住宅区", "宿舍"); allIndustry.lstAdd("公司企业", "公司", "园区", "农林园艺", "厂矿"); allIndustry.lstAdd("政府机构", "中央机构", "各级政府", "行政单位", "公检法机构", "涉外机构", "党派团体", "福利机构", "政治教育机构"); BaiduFetcher fetcher = new BaiduFetcher(args[0], args[1]); fetcher.init(); String region = "玉溪"; for(String mainIndustry: new String[]{"美食", "酒店", "购物", "丽人", "休闲娱乐"}){ for(Object industry: (Object[]) allIndustry.get(mainIndustry)){ fetcher.fetchALLPOIByRegion(industry.toString(), region); } } } }
DataSays/wES
wES-demo/src/main/java/org/datasays/wes/demo/fetch/BaiduFetcher.java
2,281
//间隔时间,单位s
line_comment
zh-cn
package org.datasays.wes.demo.fetch; import okhttp3.Cache; import okhttp3.OkHttpClient; import org.datasays.util.JsonObjGetter; import org.datasays.util.WCfg; import org.datasays.util.WPage; import org.datasays.util.WPageIterator; import org.datasays.wes.EsBaseService; import org.datasays.wes.core.HttpException; import org.datasays.wes.core.JsonObj; import org.datasays.wes.core.RequestInfo; import org.datasays.wes.core.WHttpClient; import org.datasays.wes.toolkit.WGsonConvert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by watano on 2016/12/5. */ public class BaiduFetcher { private static Logger LOG = LoggerFactory.getLogger(BaiduFetcher.class); private final int FetchInterval = 1;//间隔 <SUF> public final String index = "fetchdata"; public final String type = "BaiduMap"; private WHttpClient baiduClient; private EsBaseService esHelper; public String appKey; public String appSecret; public BaiduFetcher(String appKey, String appSecret) { this.appKey = appKey; this.appSecret = appSecret; } public void init() { OkHttpClient.Builder cBuilder = new OkHttpClient.Builder(); cBuilder.cache(new Cache(new File("./build/baidu"), 10000)); baiduClient = new WHttpClient(cBuilder.build(), new WGsonConvert()); baiduClient.setLogFlag(false, false, true); esHelper = new EsBaseService(); esHelper.init(WCfg.getValue("ES.server"), null, null); } private RequestInfo create() { RequestInfo action = new RequestInfo("http://api.map.baidu.com/place/v2/"); action.addParams("ak", appKey); return action; } public JsonObjGetter searchPOIByRegion(WPage page, String query, String region) throws HttpException { RequestInfo action = create(); action.setUrl("search"); action.addParams("scope", 2); action.addParams("output", "json"); action.addParams("query", query); action.addParams("region", region); action.addParams("page_size", page.getSize()); if (page.getPageNo() > 0) { action.addParams("page_num", page.getPageNo()-1); } LOG.info(page.toText()); JsonObjGetter result = new JsonObjGetter(baiduClient.get(action, Object.class)); if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) { if (result.num("total") != null && result.num("total").intValue() > 0) { page.setTotal(result.num("total").intValue()); } } return result; } public void fetchALLPOIByRegion(String query, String region){ WPage page = new WPage(); WPageIterator<Object> pageIterator = new WPageIterator<Object>(page) { @Override public void doSearch() { try { JsonObjGetter result = searchPOIByRegion(getPage(), query, region); if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) { int total = 0; if (result.num("total") != null && result.num("total").intValue() > 0) { total = result.num("total").intValue(); } List<Object> items = new ArrayList<>(); if (result.list("results") != null) { items.addAll(result.list("results")); } update(items, total); Thread.sleep(FetchInterval*1000); } } catch (Exception e) { e.printStackTrace(); } } }; while (pageIterator.hasNext()) { Object item = pageIterator.next(); save(item); } } public void save(Object item) { try { esHelper.index(index, type, null, item); } catch (Exception e) { LOG.error(e.getMessage(), e); } } public static void main(String[] args) { JsonObj allIndustry = new JsonObj(); allIndustry.lstAdd("美食", "中餐厅", "外国餐厅", "小吃快餐店", "蛋糕甜品店", "咖啡厅", "茶座", "酒吧"); allIndustry.lstAdd("酒店", "星级酒店", "快捷酒店", "公寓式酒店"); allIndustry.lstAdd("购物", "购物中心", "超市", "便利店", "家居建材", "家电数码", "商铺", "集市"); allIndustry.lstAdd("生活服务", "通讯营业厅", "邮局", "物流公司", "售票处", "洗衣店", "图文快印店", "照相馆", "房产中介机构", "公用事业", "维修点", "家政服务", "殡葬服务", "彩票销售点", "宠物服务", "报刊亭", "公共厕所"); allIndustry.lstAdd("丽人", "美容", "美发", "美甲", "美体"); allIndustry.lstAdd("旅游景点", "公园", "动物园", "植物园", "游乐园", "博物馆", "水族馆", "海滨浴场", "文物古迹", "教堂", "风景区"); allIndustry.lstAdd("休闲娱乐", "度假村", "农家院", "电影院", "KTV", "剧院", "歌舞厅", "网吧", "游戏场所", "洗浴按摩", "休闲广场"); allIndustry.lstAdd("运动健身", "体育场馆", "极限运动场所", "健身中心"); allIndustry.lstAdd("教育培训", "高等院校", "中学", "小学", "幼儿园", "成人教育", "亲子教育", "特殊教育学校", "留学中介机构", "科研机构", "培训机构", "图书馆", "科技馆"); allIndustry.lstAdd("文化传媒", "新闻出版", "广播电视", "艺术团体", "美术馆", "展览馆", "文化宫"); allIndustry.lstAdd("医疗", "综合医院", "专科医院", "诊所", "药店", "体检机构", "疗养院", "急救中心", "疾控中心"); allIndustry.lstAdd("汽车服务", "汽车销售", "汽车维修", "汽车美容", "汽车配件", "汽车租赁", "汽车检测场"); allIndustry.lstAdd("交通设施", "飞机场", "火车站", "地铁站", "长途汽车站", "公交车站", "港口", "停车场", "加油加气站", "服务区", "收费站", "桥"); allIndustry.lstAdd("金融", "银行", "ATM", "信用社", "投资理财", "典当行"); allIndustry.lstAdd("房地产", "写字楼", "住宅区", "宿舍"); allIndustry.lstAdd("公司企业", "公司", "园区", "农林园艺", "厂矿"); allIndustry.lstAdd("政府机构", "中央机构", "各级政府", "行政单位", "公检法机构", "涉外机构", "党派团体", "福利机构", "政治教育机构"); BaiduFetcher fetcher = new BaiduFetcher(args[0], args[1]); fetcher.init(); String region = "玉溪"; for(String mainIndustry: new String[]{"美食", "酒店", "购物", "丽人", "休闲娱乐"}){ for(Object industry: (Object[]) allIndustry.get(mainIndustry)){ fetcher.fetchALLPOIByRegion(industry.toString(), region); } } } }
0
1,667
6
2,281
7
1,983
6
2,281
7
2,831
11
false
false
false
false
false
true
22451_0
import java.util.Date; public class UserInfo { private String userid; private String username; private String userpwd; private int userStatus;//默认为0,正常。1为注销 private Date userTime; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpwd() { return userpwd; } public void setUserpwd(String userpwd) { this.userpwd = userpwd; } public int getUserStatus() { return userStatus; } public void setUserStatus(int userStatus) { this.userStatus = userStatus; } public Date getUserTime() { return userTime; } public void setUserTime(Date userTime) { this.userTime = userTime; } }
DaturaH/demo-struts2-mybatis
src/UserInfo.java
257
//默认为0,正常。1为注销
line_comment
zh-cn
import java.util.Date; public class UserInfo { private String userid; private String username; private String userpwd; private int userStatus;//默认 <SUF> private Date userTime; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpwd() { return userpwd; } public void setUserpwd(String userpwd) { this.userpwd = userpwd; } public int getUserStatus() { return userStatus; } public void setUserStatus(int userStatus) { this.userStatus = userStatus; } public Date getUserTime() { return userTime; } public void setUserTime(Date userTime) { this.userTime = userTime; } }
0
200
10
257
10
264
10
257
10
305
15
false
false
false
false
false
true
3203_5
package google.architecture.universal; import android.content.Context; import android.util.Log; import com.alibaba.android.arouter.facade.Postcard; import com.alibaba.android.arouter.facade.annotation.Interceptor; import com.alibaba.android.arouter.facade.callback.InterceptorCallback; import com.alibaba.android.arouter.facade.template.IInterceptor; import google.architecture.common.base.ARouterPath; /** * Created by danxx on 2017/11/27. * * 比较经典的应用就是在跳转过程中处理登陆事件,这样就不需要在目标页重复做登陆检查 * 拦截器会在跳转之前执行,多个拦截器会按优先级顺序依次执行 * * priority就是优先级 可以设置多个级别的拦截器都活一次执行 * 创建一个实现IInterceptor接口的类就是一个拦截器,不用做额外的配置了 */ @Interceptor(priority = 8, name = "测试用拦截器") public class RouterInterceptor implements IInterceptor { @Override public void process(Postcard postcard, InterceptorCallback callback) { if(postcard.getPath().contains(ARouterPath.GirlsListAty)){ Log.d("danxx", "拦截到向ActivityGirls跳转"); //自定义处理 }else { Log.d("danxx", "非拦截跳转执行path: "+postcard.getPath()); } callback.onContinue(postcard); // 处理完成,交还控制权 // callback.onInterrupt(new RuntimeException("我觉得有点异常")); // 觉得有问题,中断路由流程 // 以上两种至少需要调用其中一种,否则不会继续路由 } @Override public void init(Context context) { // 拦截器的初始化,会在sdk初始化的时候调用该方法,仅会调用一次 Log.d("danxx", "RouterInterceptor init"); } }
Dawish/GoogleArchitectureDemo
app_universal/src/main/java/google/architecture/universal/RouterInterceptor.java
474
// 拦截器的初始化,会在sdk初始化的时候调用该方法,仅会调用一次
line_comment
zh-cn
package google.architecture.universal; import android.content.Context; import android.util.Log; import com.alibaba.android.arouter.facade.Postcard; import com.alibaba.android.arouter.facade.annotation.Interceptor; import com.alibaba.android.arouter.facade.callback.InterceptorCallback; import com.alibaba.android.arouter.facade.template.IInterceptor; import google.architecture.common.base.ARouterPath; /** * Created by danxx on 2017/11/27. * * 比较经典的应用就是在跳转过程中处理登陆事件,这样就不需要在目标页重复做登陆检查 * 拦截器会在跳转之前执行,多个拦截器会按优先级顺序依次执行 * * priority就是优先级 可以设置多个级别的拦截器都活一次执行 * 创建一个实现IInterceptor接口的类就是一个拦截器,不用做额外的配置了 */ @Interceptor(priority = 8, name = "测试用拦截器") public class RouterInterceptor implements IInterceptor { @Override public void process(Postcard postcard, InterceptorCallback callback) { if(postcard.getPath().contains(ARouterPath.GirlsListAty)){ Log.d("danxx", "拦截到向ActivityGirls跳转"); //自定义处理 }else { Log.d("danxx", "非拦截跳转执行path: "+postcard.getPath()); } callback.onContinue(postcard); // 处理完成,交还控制权 // callback.onInterrupt(new RuntimeException("我觉得有点异常")); // 觉得有问题,中断路由流程 // 以上两种至少需要调用其中一种,否则不会继续路由 } @Override public void init(Context context) { // 拦截 <SUF> Log.d("danxx", "RouterInterceptor init"); } }
0
405
23
474
21
448
18
474
21
672
37
false
false
false
false
false
true
44559_6
package com.danxx.mdplayer.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; /** * * 类描述:网络链接类型判断 */ public class NetUtils { /** * 判断当前网络类型-1为未知网络0为没有网络连接1网络断开或关闭2为以太网3为WiFi4为2G5为3G6为4G */ public static int getNetworkType(Context context) { ConnectivityManager connectMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo(); if (networkInfo == null) { /** 没有任何网络 */ return 0; } if (!networkInfo.isConnected()) { /** 网络断开或关闭 */ return 1; } if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { /** 以太网网络 */ return 2; } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { /** wifi网络,当激活时,默认情况下,所有的数据流量将使用此连接 */ return 3; } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { /** 移动数据连接,不能与连接共存,如果wifi打开,则自动关闭 */ switch (networkInfo.getSubtype()) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: /** 2G网络 */ case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: /** 3G网络 */ case TelephonyManager.NETWORK_TYPE_LTE: /** 4G网络 */ return 4; } } /** 未知网络 */ return -1; } }
Dawish/MDPlayer
app/src/main/java/com/danxx/mdplayer/utils/NetUtils.java
646
/** 移动数据连接,不能与连接共存,如果wifi打开,则自动关闭 */
block_comment
zh-cn
package com.danxx.mdplayer.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; /** * * 类描述:网络链接类型判断 */ public class NetUtils { /** * 判断当前网络类型-1为未知网络0为没有网络连接1网络断开或关闭2为以太网3为WiFi4为2G5为3G6为4G */ public static int getNetworkType(Context context) { ConnectivityManager connectMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo(); if (networkInfo == null) { /** 没有任何网络 */ return 0; } if (!networkInfo.isConnected()) { /** 网络断开或关闭 */ return 1; } if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { /** 以太网网络 */ return 2; } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { /** wifi网络,当激活时,默认情况下,所有的数据流量将使用此连接 */ return 3; } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { /** 移动数 <SUF>*/ switch (networkInfo.getSubtype()) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: /** 2G网络 */ case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: /** 3G网络 */ case TelephonyManager.NETWORK_TYPE_LTE: /** 4G网络 */ return 4; } } /** 未知网络 */ return -1; } }
0
545
20
646
20
625
19
646
20
873
32
false
false
false
false
false
true
25646_1
import java.util.HashSet; /** * 最长没有重复数字的子串 * 滑动窗口法 */ public class Pro_003 { public int lengthOfLongestSubstring(String s) { int start = 0; int end = 0; int res = 0; HashSet<Character> set = new HashSet<>(); while (start < s.length() && end < s.length()) { if (set.contains(s.charAt(end))) { // 窗口前边后移 set.remove(s.charAt(start++)); } else { // 加入,并且后移 set.add(s.charAt(end++)); res = Math.max(res, end - start); } } return res; } }
DawnChau/leetcode
src/Pro_003.java
185
// 窗口前边后移
line_comment
zh-cn
import java.util.HashSet; /** * 最长没有重复数字的子串 * 滑动窗口法 */ public class Pro_003 { public int lengthOfLongestSubstring(String s) { int start = 0; int end = 0; int res = 0; HashSet<Character> set = new HashSet<>(); while (start < s.length() && end < s.length()) { if (set.contains(s.charAt(end))) { // 窗口 <SUF> set.remove(s.charAt(start++)); } else { // 加入,并且后移 set.add(s.charAt(end++)); res = Math.max(res, end - start); } } return res; } }
0
162
9
185
7
196
7
185
7
223
10
false
false
false
false
false
true
17958_1
package Top200; class NumSquares { public int numSquares(int n) { int[] dp = new int[n + 1]; for (int i = 0; i < n + 1; i++) { dp[i] = Integer.MAX_VALUE; } // base case dp[0] = 0; for (int i = 1; i <= n; i++) { for (int j = 1; i-j*j >= 0; j++) { // 这边等于号要注意,需要加上去,比如组成 4 的这个平方数个数只有 1 个。 dp[i] = Math.min(dp[i], dp[i - j*j] + 1); } } return dp[n]; } public static void main(String[] args) { NumSquares ns = new NumSquares(); System.out.println(ns.numSquares(4)); System.out.println(ns.numSquares(5)); System.out.println(ns.numSquares(6)); System.out.println(ns.numSquares(7)); System.out.println(ns.numSquares(12)); } }
DawnGuoDev/Algorithm
Top200/279-NumSquares.java
292
// 这边等于号要注意,需要加上去,比如组成 4 的这个平方数个数只有 1 个。
line_comment
zh-cn
package Top200; class NumSquares { public int numSquares(int n) { int[] dp = new int[n + 1]; for (int i = 0; i < n + 1; i++) { dp[i] = Integer.MAX_VALUE; } // base case dp[0] = 0; for (int i = 1; i <= n; i++) { for (int j = 1; i-j*j >= 0; j++) { // 这边 <SUF> dp[i] = Math.min(dp[i], dp[i - j*j] + 1); } } return dp[n]; } public static void main(String[] args) { NumSquares ns = new NumSquares(); System.out.println(ns.numSquares(4)); System.out.println(ns.numSquares(5)); System.out.println(ns.numSquares(6)); System.out.println(ns.numSquares(7)); System.out.println(ns.numSquares(12)); } }
0
253
28
292
30
299
25
292
30
343
39
false
false
false
false
false
true
38569_25
package blcs.lwb.lwbtool.utils.camera; import android.annotation.SuppressLint; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.Spanned; import android.text.TextWatcher; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import blcs.lwb.lwbtool.utils.MyUtils; import blcs.lwb.lwbtool.utils.RxTool.RxVibrateTool; /** * @author vondear * @date 2016/1/24 * RxTools的常用工具类 * <p> * For the brave souls who get this far: You are the chosen ones, * the valiant knights of programming who toil away, without rest, * fixing our most awful code. To you, true saviors, kings of men, * I say this: never gonna give you up, never gonna let you down, * never gonna run around and desert you. Never gonna make you cry, * never gonna say goodbye. Never gonna tell a lie and hurt you. * <p> * 致终于来到这里的勇敢的人: * 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。 * 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己, * 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。 */ public class RxTool { @SuppressLint("StaticFieldLeak") private static Context context; private static long lastClickTime; /** * 初始化工具类 * * @param context 上下文 */ public static void init(Context context) { RxTool.context = context.getApplicationContext(); RxCrashTool.init(context); } /** * 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context * <p> * 获取ApplicationContext * * @return ApplicationContext */ public static Context getContext() { if (context != null) { return context; } throw new NullPointerException("请先调用init()方法"); } //==============================================================================================延时任务封装 end //----------------------------------------------------------------------------------------------延时任务封装 start public static void delayToDo(long delayTime, final OnSimpleListener onSimpleListener) { new Handler().postDelayed(new Runnable() { @Override public void run() { //execute the task onSimpleListener.doSomething(); } }, delayTime); } /** * 倒计时 * * @param textView 控件 * @param waitTime 倒计时总时长 * @param interval 倒计时的间隔时间 * @param hint 倒计时完毕时显示的文字 */ public static void countDown(final TextView textView, long waitTime, long interval, final String hint) { textView.setEnabled(false); android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) { @SuppressLint("DefaultLocale") @Override public void onTick(long millisUntilFinished) { textView.setText(String.format("剩下 %d S", millisUntilFinished / 1000)); } @Override public void onFinish() { textView.setEnabled(true); textView.setText(hint); } }; timer.start(); } /** * 手动计算出listView的高度,但是不再具有滚动效果 * * @param listView */ public static void fixListViewHeight(ListView listView) { // 如果没有设置数据适配器,则ListView没有子项,返回。 ListAdapter listAdapter = listView.getAdapter(); int totalHeight = 0; if (listAdapter == null) { return; } for (int index = 0, len = listAdapter.getCount(); index < len; index++) { View listViewItem = listAdapter.getView(index, null, listView); // 计算子项View 的宽高 listViewItem.measure(0, 0); // 计算所有子项的高度 totalHeight += listViewItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); // listView.getDividerHeight()获取子项间分隔符的高度 // params.height设置ListView完全显示需要的高度 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } //---------------------------------------------MD5加密------------------------------------------- /** * 生成MD5加密32位字符串 * * @param MStr :需要加密的字符串 * @return */ public static String Md5(String MStr) { try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(MStr.getBytes()); return bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { return String.valueOf(MStr.hashCode()); } } // MD5内部算法---------------不能修改! private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } //============================================MD5加密============================================ /** * 根据资源名称获取资源 id * <p> * 不提倡使用这个方法获取资源,比其直接获取ID效率慢 * <p> * 例如 * getResources().getIdentifier("ic_launcher", "drawable", getPackageName()); * * @param context * @param name * @param defType * @return */ public final static int getResIdByName(Context context, String name, String defType) { return context.getResources().getIdentifier(name, defType, context.getPackageName()); } public static boolean isFastClick(int millisecond) { long curClickTime = System.currentTimeMillis(); long interval = (curClickTime - lastClickTime); if (0 < interval && interval < millisecond) { // 超过点击间隔后再将lastClickTime重置为当前点击时间 return true; } lastClickTime = curClickTime; return false; } /** * Edittext 首位小数点自动加零,最多两位小数 * * @param editText */ public static void setEdTwoDecimal(EditText editText) { setEdDecimal(editText, 2); } /** * 只允许数字和汉字 * @param editText */ public static void setEdType(final EditText editText) { editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String editable = editText.getText().toString(); String str = stringFilter(editable); if (!editable.equals(str)) { editText.setText(str); //设置新的光标所在位置 editText.setSelection(str.length()); } } @Override public void afterTextChanged(Editable s) { } }); } /** * // 只允许数字和汉字 * * @param str * @return * @throws PatternSyntaxException */ public static String stringFilter(String str) throws PatternSyntaxException { String regEx = "[^0-9\u4E00-\u9FA5]";//正则表达式 Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll("").trim(); } public static void setEdDecimal(EditText editText, int count) { if (count < 0) { count = 0; } count += 1; editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER); //设置字符过滤 final int finalCount = count; editText.setFilters(new InputFilter[]{new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (".".contentEquals(source) && dest.toString().length() == 0) { return "0."; } if (dest.toString().contains(".")) { int index = dest.toString().indexOf("."); int mlength = dest.toString().substring(index).length(); if (mlength == finalCount) { return ""; } } if (dest.toString().equals("0") && source.equals("0")) { return ""; } return null; } }}); } /** * @param editText 输入框控件 * @param number 位数 * 1 -> 1 * 2 -> 01 * 3 -> 001 * 4 -> 0001 * @param isStartForZero 是否从000开始 * true -> 从 000 开始 * false -> 从 001 开始 */ public static void setEditNumberAuto(final EditText editText, final int number, final boolean isStartForZero) { editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { setEditNumber(editText, number, isStartForZero); } } }); } /** * @param editText 输入框控件 * @param number 位数 * 1 -> 1 * 2 -> 01 * 3 -> 001 * 4 -> 0001 * @param isStartForZero 是否从000开始 * true -> 从 000 开始 * false -> 从 001 开始 */ public static void setEditNumber(EditText editText, int number, boolean isStartForZero) { StringBuilder s = new StringBuilder(editText.getText().toString()); StringBuilder temp = new StringBuilder(); int i; for (i = s.length(); i < number; ++i) { s.insert(0, "0"); } if (!isStartForZero) { for (i = 0; i < number; ++i) { temp.append("0"); } if (s.toString().equals(temp.toString())) { s = new StringBuilder(temp.substring(1) + "1"); } } editText.setText(s.toString()); } /** * 获取 * @return */ public static Handler getBackgroundHandler() { HandlerThread thread = new HandlerThread("background"); thread.start(); return new Handler(thread.getLooper()); } public static void initFastClickAndVibrate(Context mContext, OnDoListener onRxSimple) { if (RxTool.isFastClick(FAST_CLICK_TIME)) { MyUtils.toast(context,"请不要重复点击"); return; } else { RxVibrateTool.vibrateOnce(mContext, VIBRATE_TIME); onRxSimple.doSomething(); } } public final static int FAST_CLICK_TIME = 100; public final static int VIBRATE_TIME = 100; }
DayorNight/BLCS
LwbTool/src/main/java/blcs/lwb/lwbtool/utils/camera/RxTool.java
2,868
//设置字符过滤
line_comment
zh-cn
package blcs.lwb.lwbtool.utils.camera; import android.annotation.SuppressLint; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.Spanned; import android.text.TextWatcher; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import blcs.lwb.lwbtool.utils.MyUtils; import blcs.lwb.lwbtool.utils.RxTool.RxVibrateTool; /** * @author vondear * @date 2016/1/24 * RxTools的常用工具类 * <p> * For the brave souls who get this far: You are the chosen ones, * the valiant knights of programming who toil away, without rest, * fixing our most awful code. To you, true saviors, kings of men, * I say this: never gonna give you up, never gonna let you down, * never gonna run around and desert you. Never gonna make you cry, * never gonna say goodbye. Never gonna tell a lie and hurt you. * <p> * 致终于来到这里的勇敢的人: * 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。 * 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己, * 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。 */ public class RxTool { @SuppressLint("StaticFieldLeak") private static Context context; private static long lastClickTime; /** * 初始化工具类 * * @param context 上下文 */ public static void init(Context context) { RxTool.context = context.getApplicationContext(); RxCrashTool.init(context); } /** * 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context * <p> * 获取ApplicationContext * * @return ApplicationContext */ public static Context getContext() { if (context != null) { return context; } throw new NullPointerException("请先调用init()方法"); } //==============================================================================================延时任务封装 end //----------------------------------------------------------------------------------------------延时任务封装 start public static void delayToDo(long delayTime, final OnSimpleListener onSimpleListener) { new Handler().postDelayed(new Runnable() { @Override public void run() { //execute the task onSimpleListener.doSomething(); } }, delayTime); } /** * 倒计时 * * @param textView 控件 * @param waitTime 倒计时总时长 * @param interval 倒计时的间隔时间 * @param hint 倒计时完毕时显示的文字 */ public static void countDown(final TextView textView, long waitTime, long interval, final String hint) { textView.setEnabled(false); android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) { @SuppressLint("DefaultLocale") @Override public void onTick(long millisUntilFinished) { textView.setText(String.format("剩下 %d S", millisUntilFinished / 1000)); } @Override public void onFinish() { textView.setEnabled(true); textView.setText(hint); } }; timer.start(); } /** * 手动计算出listView的高度,但是不再具有滚动效果 * * @param listView */ public static void fixListViewHeight(ListView listView) { // 如果没有设置数据适配器,则ListView没有子项,返回。 ListAdapter listAdapter = listView.getAdapter(); int totalHeight = 0; if (listAdapter == null) { return; } for (int index = 0, len = listAdapter.getCount(); index < len; index++) { View listViewItem = listAdapter.getView(index, null, listView); // 计算子项View 的宽高 listViewItem.measure(0, 0); // 计算所有子项的高度 totalHeight += listViewItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); // listView.getDividerHeight()获取子项间分隔符的高度 // params.height设置ListView完全显示需要的高度 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } //---------------------------------------------MD5加密------------------------------------------- /** * 生成MD5加密32位字符串 * * @param MStr :需要加密的字符串 * @return */ public static String Md5(String MStr) { try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(MStr.getBytes()); return bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { return String.valueOf(MStr.hashCode()); } } // MD5内部算法---------------不能修改! private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } //============================================MD5加密============================================ /** * 根据资源名称获取资源 id * <p> * 不提倡使用这个方法获取资源,比其直接获取ID效率慢 * <p> * 例如 * getResources().getIdentifier("ic_launcher", "drawable", getPackageName()); * * @param context * @param name * @param defType * @return */ public final static int getResIdByName(Context context, String name, String defType) { return context.getResources().getIdentifier(name, defType, context.getPackageName()); } public static boolean isFastClick(int millisecond) { long curClickTime = System.currentTimeMillis(); long interval = (curClickTime - lastClickTime); if (0 < interval && interval < millisecond) { // 超过点击间隔后再将lastClickTime重置为当前点击时间 return true; } lastClickTime = curClickTime; return false; } /** * Edittext 首位小数点自动加零,最多两位小数 * * @param editText */ public static void setEdTwoDecimal(EditText editText) { setEdDecimal(editText, 2); } /** * 只允许数字和汉字 * @param editText */ public static void setEdType(final EditText editText) { editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String editable = editText.getText().toString(); String str = stringFilter(editable); if (!editable.equals(str)) { editText.setText(str); //设置新的光标所在位置 editText.setSelection(str.length()); } } @Override public void afterTextChanged(Editable s) { } }); } /** * // 只允许数字和汉字 * * @param str * @return * @throws PatternSyntaxException */ public static String stringFilter(String str) throws PatternSyntaxException { String regEx = "[^0-9\u4E00-\u9FA5]";//正则表达式 Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll("").trim(); } public static void setEdDecimal(EditText editText, int count) { if (count < 0) { count = 0; } count += 1; editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER); //设置 <SUF> final int finalCount = count; editText.setFilters(new InputFilter[]{new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (".".contentEquals(source) && dest.toString().length() == 0) { return "0."; } if (dest.toString().contains(".")) { int index = dest.toString().indexOf("."); int mlength = dest.toString().substring(index).length(); if (mlength == finalCount) { return ""; } } if (dest.toString().equals("0") && source.equals("0")) { return ""; } return null; } }}); } /** * @param editText 输入框控件 * @param number 位数 * 1 -> 1 * 2 -> 01 * 3 -> 001 * 4 -> 0001 * @param isStartForZero 是否从000开始 * true -> 从 000 开始 * false -> 从 001 开始 */ public static void setEditNumberAuto(final EditText editText, final int number, final boolean isStartForZero) { editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { setEditNumber(editText, number, isStartForZero); } } }); } /** * @param editText 输入框控件 * @param number 位数 * 1 -> 1 * 2 -> 01 * 3 -> 001 * 4 -> 0001 * @param isStartForZero 是否从000开始 * true -> 从 000 开始 * false -> 从 001 开始 */ public static void setEditNumber(EditText editText, int number, boolean isStartForZero) { StringBuilder s = new StringBuilder(editText.getText().toString()); StringBuilder temp = new StringBuilder(); int i; for (i = s.length(); i < number; ++i) { s.insert(0, "0"); } if (!isStartForZero) { for (i = 0; i < number; ++i) { temp.append("0"); } if (s.toString().equals(temp.toString())) { s = new StringBuilder(temp.substring(1) + "1"); } } editText.setText(s.toString()); } /** * 获取 * @return */ public static Handler getBackgroundHandler() { HandlerThread thread = new HandlerThread("background"); thread.start(); return new Handler(thread.getLooper()); } public static void initFastClickAndVibrate(Context mContext, OnDoListener onRxSimple) { if (RxTool.isFastClick(FAST_CLICK_TIME)) { MyUtils.toast(context,"请不要重复点击"); return; } else { RxVibrateTool.vibrateOnce(mContext, VIBRATE_TIME); onRxSimple.doSomething(); } } public final static int FAST_CLICK_TIME = 100; public final static int VIBRATE_TIME = 100; }
0
2,637
4
2,869
4
3,023
4
2,868
4
3,660
9
false
false
false
false
false
true
18997_2
public class Solution { // O(n * 2^n) time: // n为nums的length, subsets问题就是对于其中任意一个元素, 选或者不选入subset中 // 那么, 解的个数就是2^n // // 我们知道, subsets I的running time: // T(n) = n*2^(n-1) = θ(n*2^(n-1)) = O(n*2^n) // 但是我们知道在ret.contains()去重时, 每个解无论重复与否, 都有O(n)的时间, 所以 // 此题中, θ(n*2^(n-1))不再成立 // // contains()到底花了多少时间? // 我们知道list的大小是从1逐渐增加到2^m的, m为去重后解的个数, 那么其实就是 // 1 + 2 + 3 + ... + 2^m ~ 2^(m-1) + 2^(2m-1) // 这个时间是由重复元素个数决定的, 但我们可以用hashSet优化, 见subsetsWithDupOp // 那么最后running time还是O(n * 2^n) // O(n) space: // one n is the recursion stack // another n is the longest subset which is exactly the same as input // nums when used this in creating new linked list to store public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> ret = new LinkedList<List<Integer>>(); ret.add(new LinkedList<Integer>()); if(nums == null || nums.length == 0) return ret; Arrays.sort(nums); List<Integer> path = new LinkedList<Integer>(); doDFS(0, nums, path, ret); return ret; } private void doDFS(int start, int[] nums, List<Integer> path, List<List<Integer>> ret){ for(int i = start; i < nums.length; i++){ path.add(nums[i]); if(!ret.contains(path)){ ret.add(new LinkedList<Integer>(path)); doDFS(i + 1, nums, path, ret); } path.remove(path.size() - 1); } } // HashSet优化掉contains(), 实践证明可以省掉客观时间, 尤其是对于 // nums = {1, 1, ...... 1}这样的input public static List<List<Integer>> subsetsWithDupOp(int[] nums) { List<List<Integer>> ret = new LinkedList<List<Integer>>(); ret.add(new LinkedList<Integer>()); if(nums == null || nums.length == 0) return ret; Arrays.sort(nums); List<Integer> path = new LinkedList<Integer>(); HashSet<List<Integer>> set = new HashSet<List<Integer>>(); doDFS(0, nums, path, set); for(List<Integer> entry: set){ ret.add(entry); } return ret; } private static void doDFS(int start, int[] nums, List<Integer> path, HashSet<List<Integer>> set){ for(int i = start; i < nums.length; i++){ path.add(nums[i]); if(!set.contains(path)){ set.add(new LinkedList<Integer>(path)); doDFS(i + 1, nums, path, set); } path.remove(path.size() - 1); } } }
Deadbeef-ECE/Interview
Leetcode/All/090_Subsets_II.java
835
// 那么, 解的个数就是2^n
line_comment
zh-cn
public class Solution { // O(n * 2^n) time: // n为nums的length, subsets问题就是对于其中任意一个元素, 选或者不选入subset中 // 那么 <SUF> // // 我们知道, subsets I的running time: // T(n) = n*2^(n-1) = θ(n*2^(n-1)) = O(n*2^n) // 但是我们知道在ret.contains()去重时, 每个解无论重复与否, 都有O(n)的时间, 所以 // 此题中, θ(n*2^(n-1))不再成立 // // contains()到底花了多少时间? // 我们知道list的大小是从1逐渐增加到2^m的, m为去重后解的个数, 那么其实就是 // 1 + 2 + 3 + ... + 2^m ~ 2^(m-1) + 2^(2m-1) // 这个时间是由重复元素个数决定的, 但我们可以用hashSet优化, 见subsetsWithDupOp // 那么最后running time还是O(n * 2^n) // O(n) space: // one n is the recursion stack // another n is the longest subset which is exactly the same as input // nums when used this in creating new linked list to store public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> ret = new LinkedList<List<Integer>>(); ret.add(new LinkedList<Integer>()); if(nums == null || nums.length == 0) return ret; Arrays.sort(nums); List<Integer> path = new LinkedList<Integer>(); doDFS(0, nums, path, ret); return ret; } private void doDFS(int start, int[] nums, List<Integer> path, List<List<Integer>> ret){ for(int i = start; i < nums.length; i++){ path.add(nums[i]); if(!ret.contains(path)){ ret.add(new LinkedList<Integer>(path)); doDFS(i + 1, nums, path, ret); } path.remove(path.size() - 1); } } // HashSet优化掉contains(), 实践证明可以省掉客观时间, 尤其是对于 // nums = {1, 1, ...... 1}这样的input public static List<List<Integer>> subsetsWithDupOp(int[] nums) { List<List<Integer>> ret = new LinkedList<List<Integer>>(); ret.add(new LinkedList<Integer>()); if(nums == null || nums.length == 0) return ret; Arrays.sort(nums); List<Integer> path = new LinkedList<Integer>(); HashSet<List<Integer>> set = new HashSet<List<Integer>>(); doDFS(0, nums, path, set); for(List<Integer> entry: set){ ret.add(entry); } return ret; } private static void doDFS(int start, int[] nums, List<Integer> path, HashSet<List<Integer>> set){ for(int i = start; i < nums.length; i++){ path.add(nums[i]); if(!set.contains(path)){ set.add(new LinkedList<Integer>(path)); doDFS(i + 1, nums, path, set); } path.remove(path.size() - 1); } } }
0
749
13
835
12
865
11
835
12
1,031
15
false
false
false
false
false
true
56204_4
/*编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。 如果是有效的 IPv4 地址,返回 "IPv4" ; 如果是有效的 IPv6 地址,返回 "IPv6" ; 如果不是上述类型的 IP 地址,返回 "Neither" 。 IPv4 地址由十进制数和点来表示,每个地址包含 4 个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1; 同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。 IPv6 地址由 8 组 16 进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如,  2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。 然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。 同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。   :示例 1: 输入:IP = "172.16.254.1" 输出:"IPv4" 解释:有效的 IPv4 地址,返回 "IPv4" 示例 2: 输入:IP = "2001:0db8:85a3:0:08A2E:0370:7334" 输出:"IPv6" 解释:有效的 IPv6 地址,返回 "IPv6" 示例 3: 输入:IP = "256.256.256.256" 输出:"Neither" 解释:既不是 IPv4 地址,又不是 IPv6 地址 示例 4: 输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:" 输出:"Neither" 示例 5: 输入:IP = "1e1.4.5.6" 输出:"Neither"   提示: IP 仅由英文字母,数字,字符 '.' 和 ':' 组成。 */ public class Q468 { public static void main(String[] args) { System.out.print(validIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); } public static String validIPAddress(String IP) { String[] IP4Arr = IP.split("\\.",-1); // -1 表示尽可能用最多的次数 if(IP4Arr.length == 4){ return isIP4Arr(IP4Arr); } String[] IP6Arr = IP.split(":",-1); if(IP6Arr.length == 8){ return isIP6Arr(IP6Arr); } return "Neither"; } public static String isIP4Arr(String[] IP4Arr){ for(String ip : IP4Arr){ if(ip.length() > 3 || ip.length() <= 0){ return "Neither"; } for(int i = 0 ;i < ip.length();++i){ if(!Character.isDigit(ip.charAt(i))){ return "Neither"; } } int num = Integer.parseInt(ip); // String 转int --> Integer.parseInt() if(num > 255 || String.valueOf(num).length() != ip.length()){ // 判断是否是0开头, int转String --> String.valueOf() return "Neither"; } } return "IPv4"; } public static String isIP6Arr(String[] IP6Arr){ for(String ip : IP6Arr){ if(ip.length() > 4 || ip.length() <= 0){ return "Neither"; } for(int i = 0 ;i < ip.length();++i){ char c = ip.charAt(i); if(!Character.isDigit(c) && !( 'a' <= c && c <= 'f') && !('A' <= c && c <= 'F')){ // 判断字符串是否为数字 return "Neither"; } } } return "IPv6"; } }
DeadpanZiao/LEETCODE_comp
src/Q468.java
1,258
// 判断字符串是否为数字
line_comment
zh-cn
/*编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。 如果是有效的 IPv4 地址,返回 "IPv4" ; 如果是有效的 IPv6 地址,返回 "IPv6" ; 如果不是上述类型的 IP 地址,返回 "Neither" 。 IPv4 地址由十进制数和点来表示,每个地址包含 4 个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1; 同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。 IPv6 地址由 8 组 16 进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如,  2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。 然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。 同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。   :示例 1: 输入:IP = "172.16.254.1" 输出:"IPv4" 解释:有效的 IPv4 地址,返回 "IPv4" 示例 2: 输入:IP = "2001:0db8:85a3:0:08A2E:0370:7334" 输出:"IPv6" 解释:有效的 IPv6 地址,返回 "IPv6" 示例 3: 输入:IP = "256.256.256.256" 输出:"Neither" 解释:既不是 IPv4 地址,又不是 IPv6 地址 示例 4: 输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:" 输出:"Neither" 示例 5: 输入:IP = "1e1.4.5.6" 输出:"Neither"   提示: IP 仅由英文字母,数字,字符 '.' 和 ':' 组成。 */ public class Q468 { public static void main(String[] args) { System.out.print(validIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); } public static String validIPAddress(String IP) { String[] IP4Arr = IP.split("\\.",-1); // -1 表示尽可能用最多的次数 if(IP4Arr.length == 4){ return isIP4Arr(IP4Arr); } String[] IP6Arr = IP.split(":",-1); if(IP6Arr.length == 8){ return isIP6Arr(IP6Arr); } return "Neither"; } public static String isIP4Arr(String[] IP4Arr){ for(String ip : IP4Arr){ if(ip.length() > 3 || ip.length() <= 0){ return "Neither"; } for(int i = 0 ;i < ip.length();++i){ if(!Character.isDigit(ip.charAt(i))){ return "Neither"; } } int num = Integer.parseInt(ip); // String 转int --> Integer.parseInt() if(num > 255 || String.valueOf(num).length() != ip.length()){ // 判断是否是0开头, int转String --> String.valueOf() return "Neither"; } } return "IPv4"; } public static String isIP6Arr(String[] IP6Arr){ for(String ip : IP6Arr){ if(ip.length() > 4 || ip.length() <= 0){ return "Neither"; } for(int i = 0 ;i < ip.length();++i){ char c = ip.charAt(i); if(!Character.isDigit(c) && !( 'a' <= c && c <= 'f') && !('A' <= c && c <= 'F')){ // 判断 <SUF> return "Neither"; } } } return "IPv6"; } }
0
1,159
7
1,258
6
1,225
6
1,258
6
1,547
12
false
false
false
false
false
true
58790_0
package game.Object; import game.Engine.Base.BaseModel; import game.Engine.Enum.ObjectStatus; import game.Engine.GameObject; import game.Game; import game.Object.Model.Alpha; import game.Object.Model.ScoreIndicator; import java.util.concurrent.ThreadLocalRandom; @game.Engine.Annotation.GameObject public class Generator extends GameObject { private long lastTime = 0; private long interval = 1000; // 发射字母的时间间隔 private int maxAlphaCount = 8; private int currentAlphaCount = 0; @Override public void update() { if (status != ObjectStatus.ANIMATION) return; // 判断是否到达发射时间 if (System.currentTimeMillis() - lastTime < interval) return; // 判断是否达到最大限制 if (getAnimationAlphaCount() >= maxAlphaCount) return; ScoreIndicator scoreIndicator = ((ScoreIndicator) Game.getInstance().getModelManager().get("ScoreIndicator")); interval -= scoreIndicator.getScore() / 10; String rndAlpha = getRandomAlpha(); if (Game.getInstance().getModelManager().contains(rndAlpha)) { BaseModel alpha = Game.getInstance().getModelManager().get(rndAlpha); if (alpha.getStatus() != ObjectStatus.ANIMATION) alpha.start(); } else { Game.getInstance().getModelManager().register(new Alpha(rndAlpha), rndAlpha); } lastTime = System.currentTimeMillis(); } @Override public void start() { status = ObjectStatus.ANIMATION; } @Override public void stop() { status = ObjectStatus.STOP; } /** * 获取随机字母 * * @return */ private String getRandomAlpha() { int rnd = ThreadLocalRandom.current().nextInt(65, 90); return String.valueOf((char) rnd); } /** * 获取当前正在屏幕上运动的字母数量 * * @return 数量 */ private int getAnimationAlphaCount() { int result = 0; for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) { if (model instanceof Alpha) { if (model.getStatus() == ObjectStatus.ANIMATION) result++; } } return result; } /** * 重置字母生成器 */ public void reset() { lastTime = 0; interval = 1000; currentAlphaCount = 0; for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) { if (model instanceof Alpha) ((Alpha) model).stop(false); } } }
Deali-Axy/CrazyAlpha
src/main/java/game/Object/Generator.java
615
// 发射字母的时间间隔
line_comment
zh-cn
package game.Object; import game.Engine.Base.BaseModel; import game.Engine.Enum.ObjectStatus; import game.Engine.GameObject; import game.Game; import game.Object.Model.Alpha; import game.Object.Model.ScoreIndicator; import java.util.concurrent.ThreadLocalRandom; @game.Engine.Annotation.GameObject public class Generator extends GameObject { private long lastTime = 0; private long interval = 1000; // 发射 <SUF> private int maxAlphaCount = 8; private int currentAlphaCount = 0; @Override public void update() { if (status != ObjectStatus.ANIMATION) return; // 判断是否到达发射时间 if (System.currentTimeMillis() - lastTime < interval) return; // 判断是否达到最大限制 if (getAnimationAlphaCount() >= maxAlphaCount) return; ScoreIndicator scoreIndicator = ((ScoreIndicator) Game.getInstance().getModelManager().get("ScoreIndicator")); interval -= scoreIndicator.getScore() / 10; String rndAlpha = getRandomAlpha(); if (Game.getInstance().getModelManager().contains(rndAlpha)) { BaseModel alpha = Game.getInstance().getModelManager().get(rndAlpha); if (alpha.getStatus() != ObjectStatus.ANIMATION) alpha.start(); } else { Game.getInstance().getModelManager().register(new Alpha(rndAlpha), rndAlpha); } lastTime = System.currentTimeMillis(); } @Override public void start() { status = ObjectStatus.ANIMATION; } @Override public void stop() { status = ObjectStatus.STOP; } /** * 获取随机字母 * * @return */ private String getRandomAlpha() { int rnd = ThreadLocalRandom.current().nextInt(65, 90); return String.valueOf((char) rnd); } /** * 获取当前正在屏幕上运动的字母数量 * * @return 数量 */ private int getAnimationAlphaCount() { int result = 0; for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) { if (model instanceof Alpha) { if (model.getStatus() == ObjectStatus.ANIMATION) result++; } } return result; } /** * 重置字母生成器 */ public void reset() { lastTime = 0; interval = 1000; currentAlphaCount = 0; for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) { if (model instanceof Alpha) ((Alpha) model).stop(false); } } }
0
570
6
615
8
669
6
615
8
773
15
false
false
false
false
false
true
19954_0
package cn.deali.minimalpoem.task; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.support.v4.content.ContextCompat; import android.util.Log; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import cn.deali.minimalpoem.MainApp; import cn.deali.minimalpoem.R; import cn.deali.minimalpoem.utils.http.HttpRequestUtil; import cn.deali.minimalpoem.utils.http.tool.HttpRequestData; import cn.deali.minimalpoem.utils.http.tool.HttpResponseData; // 检查更新任务 public class CheckUpdateTask extends AsyncTask<Void, Integer, HttpResponseData> { private static final String TAG = "CheckUpdateTask"; private Context mContext; private boolean toast = false; /** * @param context Activity对象 * @param toast 是否显示 toast 提示最新版本 */ public CheckUpdateTask(Context context, boolean toast) { this.mContext = context; this.toast = toast; } @Override protected HttpResponseData doInBackground(Void... voids) { HttpRequestData request = new HttpRequestData(MainApp.getInstance().config.getHost() + "/qapp/get"); JSONObject json = new JSONObject(); try { json.put("id", MainApp.getInstance().config.getAppId()); } catch (JSONException ex) { Log.e(TAG, ex.getMessage()); this.cancel(true); } request.params = new StringBuffer(json.toString()); return HttpRequestUtil.postData(request); } @Override protected void onCancelled() { super.onCancelled(); Toast.makeText(mContext, "检查更新时发生错误!", Toast.LENGTH_SHORT).show(); } @Override protected void onPostExecute(HttpResponseData data) { super.onPostExecute(data); if (data.success) { try { JSONObject json = new JSONObject(data.content); if (json.getString("status").equals("ok")) { JSONObject app = json.getJSONObject("app"); if (app.getInt("version") > MainApp.getInstance().config.getVersionCode()) { showUpdateAlert(app); } else { if (toast) Toast.makeText(mContext, "你已经使用最新版本啦~", Toast.LENGTH_SHORT).show(); } } } catch (JSONException ex) { Log.e(TAG, ex.getMessage()); if (toast) Toast.makeText(mContext, "哦豁,完蛋,解析服务器数据失败~", Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Log.e(TAG, ex.getMessage()); if (toast) Toast.makeText(mContext, "糟糕,在检查更新的时候遇到奇奇怪怪的异常了~", Toast.LENGTH_SHORT).show(); } } } private void showUpdateAlert(JSONObject app) throws JSONException { final String download_link = app.getString("download_link"); final String detail_link = app.getString("detail_link"); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("发现新版本咯~"); builder.setMessage(String.format( "版本:%s\n更新说明:\n%s\n", app.getString("version_str"), app.getString("update_description"))); builder.setPositiveButton("下载", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri uri = Uri.parse(download_link); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setData(uri); mContext.startActivity(intent); } }); builder.setNeutralButton("了解详情", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri uri = Uri.parse(detail_link); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setData(uri); mContext.startActivity(intent); } }); AlertDialog dialog = builder.create(); // 适配夜间模式和白天模式 if (MainApp.getInstance().getNightMode()) dialog.setOnShowListener(dialogInterface -> { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.white)); dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.white)); }); else dialog.setOnShowListener(dialogInterface -> { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.black)); dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.black)); }); dialog.show(); } }
Deali-Axy/MinimalPoem
app/src/main/java/cn/deali/minimalpoem/task/CheckUpdateTask.java
1,177
// 检查更新任务
line_comment
zh-cn
package cn.deali.minimalpoem.task; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.support.v4.content.ContextCompat; import android.util.Log; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import cn.deali.minimalpoem.MainApp; import cn.deali.minimalpoem.R; import cn.deali.minimalpoem.utils.http.HttpRequestUtil; import cn.deali.minimalpoem.utils.http.tool.HttpRequestData; import cn.deali.minimalpoem.utils.http.tool.HttpResponseData; // 检查 <SUF> public class CheckUpdateTask extends AsyncTask<Void, Integer, HttpResponseData> { private static final String TAG = "CheckUpdateTask"; private Context mContext; private boolean toast = false; /** * @param context Activity对象 * @param toast 是否显示 toast 提示最新版本 */ public CheckUpdateTask(Context context, boolean toast) { this.mContext = context; this.toast = toast; } @Override protected HttpResponseData doInBackground(Void... voids) { HttpRequestData request = new HttpRequestData(MainApp.getInstance().config.getHost() + "/qapp/get"); JSONObject json = new JSONObject(); try { json.put("id", MainApp.getInstance().config.getAppId()); } catch (JSONException ex) { Log.e(TAG, ex.getMessage()); this.cancel(true); } request.params = new StringBuffer(json.toString()); return HttpRequestUtil.postData(request); } @Override protected void onCancelled() { super.onCancelled(); Toast.makeText(mContext, "检查更新时发生错误!", Toast.LENGTH_SHORT).show(); } @Override protected void onPostExecute(HttpResponseData data) { super.onPostExecute(data); if (data.success) { try { JSONObject json = new JSONObject(data.content); if (json.getString("status").equals("ok")) { JSONObject app = json.getJSONObject("app"); if (app.getInt("version") > MainApp.getInstance().config.getVersionCode()) { showUpdateAlert(app); } else { if (toast) Toast.makeText(mContext, "你已经使用最新版本啦~", Toast.LENGTH_SHORT).show(); } } } catch (JSONException ex) { Log.e(TAG, ex.getMessage()); if (toast) Toast.makeText(mContext, "哦豁,完蛋,解析服务器数据失败~", Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Log.e(TAG, ex.getMessage()); if (toast) Toast.makeText(mContext, "糟糕,在检查更新的时候遇到奇奇怪怪的异常了~", Toast.LENGTH_SHORT).show(); } } } private void showUpdateAlert(JSONObject app) throws JSONException { final String download_link = app.getString("download_link"); final String detail_link = app.getString("detail_link"); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("发现新版本咯~"); builder.setMessage(String.format( "版本:%s\n更新说明:\n%s\n", app.getString("version_str"), app.getString("update_description"))); builder.setPositiveButton("下载", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri uri = Uri.parse(download_link); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setData(uri); mContext.startActivity(intent); } }); builder.setNeutralButton("了解详情", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri uri = Uri.parse(detail_link); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setData(uri); mContext.startActivity(intent); } }); AlertDialog dialog = builder.create(); // 适配夜间模式和白天模式 if (MainApp.getInstance().getNightMode()) dialog.setOnShowListener(dialogInterface -> { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.white)); dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.white)); }); else dialog.setOnShowListener(dialogInterface -> { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.black)); dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.black)); }); dialog.show(); } }
0
956
7
1,177
5
1,225
4
1,177
5
1,475
10
false
false
false
false
false
true
66588_1
package com.hanyi.thread.common.component; import com.hanyi.thread.domain.ScheduledTask; import lombok.RequiredArgsConstructor; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.config.CronTask; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * cron任务注册器 * * @author wcwei@iflytek.com * @since 2021-08-03 10:29 */ @Component @RequiredArgsConstructor public class CronTaskRegistrar { /** * 计划任务 */ private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16); /** * 任务调度器 */ private final TaskScheduler taskScheduler; /** * 添加cron任务 * * @param task 任务 * @param cronExpression cron表达式 */ public void addCronTask(Runnable task, String cronExpression) { this.addCronTask(new CronTask(task, cronExpression)); } /** * 添加cron任务 * * @param cronTask cron任务 */ public void addCronTask(CronTask cronTask) { if (cronTask != null) { Runnable task = cronTask.getRunnable(); this.removeCronTask(task); this.scheduledTasks.computeIfAbsent(task, k -> this.scheduledTasks.put(k, this.scheduleCronTask(cronTask))); } } /** * 删除cron任务 * * @param task 任务 */ public void removeCronTask(Runnable task) { ScheduledTask scheduledTask = this.scheduledTasks.remove(task); if (scheduledTask != null) { scheduledTask.cancel(); } } /** * 安排cron任务 * * @param cronTask cron任务 * @return {@link ScheduledTask} */ public ScheduledTask scheduleCronTask(CronTask cronTask) { ScheduledTask scheduledTask = new ScheduledTask(); scheduledTask.setFuture(this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger())); return scheduledTask; } /** * 摧毁 */ @PreDestroy public void destroy() { this.scheduledTasks.values().forEach(ScheduledTask::cancel); this.scheduledTasks.clear(); } }
Dearker/middleground
hanyi-dynamic-threadpool/src/main/java/com/hanyi/thread/common/component/CronTaskRegistrar.java
564
/** * 计划任务 */
block_comment
zh-cn
package com.hanyi.thread.common.component; import com.hanyi.thread.domain.ScheduledTask; import lombok.RequiredArgsConstructor; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.config.CronTask; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * cron任务注册器 * * @author wcwei@iflytek.com * @since 2021-08-03 10:29 */ @Component @RequiredArgsConstructor public class CronTaskRegistrar { /** * 计划任 <SUF>*/ private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16); /** * 任务调度器 */ private final TaskScheduler taskScheduler; /** * 添加cron任务 * * @param task 任务 * @param cronExpression cron表达式 */ public void addCronTask(Runnable task, String cronExpression) { this.addCronTask(new CronTask(task, cronExpression)); } /** * 添加cron任务 * * @param cronTask cron任务 */ public void addCronTask(CronTask cronTask) { if (cronTask != null) { Runnable task = cronTask.getRunnable(); this.removeCronTask(task); this.scheduledTasks.computeIfAbsent(task, k -> this.scheduledTasks.put(k, this.scheduleCronTask(cronTask))); } } /** * 删除cron任务 * * @param task 任务 */ public void removeCronTask(Runnable task) { ScheduledTask scheduledTask = this.scheduledTasks.remove(task); if (scheduledTask != null) { scheduledTask.cancel(); } } /** * 安排cron任务 * * @param cronTask cron任务 * @return {@link ScheduledTask} */ public ScheduledTask scheduleCronTask(CronTask cronTask) { ScheduledTask scheduledTask = new ScheduledTask(); scheduledTask.setFuture(this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger())); return scheduledTask; } /** * 摧毁 */ @PreDestroy public void destroy() { this.scheduledTasks.values().forEach(ScheduledTask::cancel); this.scheduledTasks.clear(); } }
0
517
10
564
8
608
9
564
8
720
14
false
false
false
false
false
true
40720_30
package com.debugTeam.entity; import com.debugTeam.dao.impl.IOHelper; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @Author: Cauchy-Ny * @Description: * @Data: Create in 20:51 2018/4/1 * @Modified By: */ public class Marker implements Serializable { private static final long serialVersionUID = -5809782578272943999L; private String phoneNum; //电话号码 private String userName; //用户名 private String password; //密码 private int empiricalValue; //经验值 private int credits; //积分,标记者初始有1000 //基本统计 private ArrayList<String> uploaderList; //接过的项目的上传者列表 private ArrayList<MarkerJob> jobList; //接受的标记项目列表,内含具体信息 private ArrayList<Integer> aveMarkTimeList; //平均标记时间 // private ArrayList<Double> scoreList; //评分列表 0-5分 private Map<String, Integer> hotMap; //标记热点图 private Map<String, Integer> creditsMap; //每天的积分值 private Map<String, Integer> empiricalValueMap; //每天的经验值 private int[] jobTypeNum; //三类标注的数量,依次为:整体标注、标框标注、轮廓标注 private int[] timeMarkNum; //每个小时段标注的图片数量统计 private int kickOutCount; //被踢出数 private Map<String, String> creditsHistory; //积分获取记录<date, credits-cause> //每日任务 private String lastLoginTime; //最后登录时间 private ArrayList<DailyMission> dailyMissionList; //每日任务列表 private ArrayList<Medal> medalList; //勋章墙 //兴趣 private int interestNum; //可能感兴趣标注数量 private int interestType; //可能感兴趣类型 private ArrayList<String> interestClassification; //可能感兴趣分类 public Marker(String phoneNum, String userName, String password) { this.phoneNum = phoneNum; this.userName = userName; this.password = password; this.empiricalValue = 0; this.credits = 1000; this.uploaderList = new ArrayList<>(); this.jobList = new ArrayList<>(); this.aveMarkTimeList = new ArrayList<>(); this.jobTypeNum = new int[3]; this.timeMarkNum = new int[24]; this.hotMap = new HashMap<>(); this.creditsMap = new HashMap<>(); this.empiricalValueMap = new HashMap<>(); this.lastLoginTime = ""; this.dailyMissionList = new ArrayList<>(); this.medalList = new ArrayList<>(); this.medalList.add(new Medal(1)); this.medalList.add(new Medal(2)); this.medalList.add(new Medal(3)); this.interestNum = 0; this.interestType = 0; this.interestClassification = new ArrayList<>(); this.kickOutCount = 0; this.creditsHistory = new HashMap<>(); } //获取五维数据 0-信誉度 1-勤劳 2-经验 3-积分 4-评分 均为100分制 public double[] getFiveDimension() { double[] result = new double[5]; //计算信誉 result[0] = 80 - kickOutCount > 0 ? 80 - kickOutCount : 0; //计算勤劳 double industriousScore = 0; for(String date : hotMap.keySet()) { industriousScore += hotMap.get(date); } if(hotMap.size() != 0) industriousScore = industriousScore/hotMap.size() + 50; if(industriousScore > 100) //懒得想好的平均标记张数map到100分区间 industriousScore = 100; result[1] = industriousScore==0 ? 70 : industriousScore; //计算经验 double empiricalValueScore = 0; for(String date : empiricalValueMap.keySet()) { empiricalValueScore += empiricalValueMap.get(date); } empiricalValueScore = empiricalValueScore/300 + 50; if(empiricalValueScore > 100) //懒得想... empiricalValueScore = 100; result[2] = empiricalValueScore; //计算积分 double creditsScore = 0; for(String date : creditsMap.keySet()) { creditsScore += creditsMap.get(date); } creditsScore = creditsScore/300 + 50; if(creditsScore > 100) //懒得想... creditsScore = 100; result[3] = creditsScore; //计算评分 result[4] = 80; for(MarkerJob job: jobList) { if(job.getScore() != 0) { result[4] = jobList.stream() .map(p -> p.getScore()) .reduce(Double::sum) .orElse(0.0) / jobList.size() * 20; break; } } return result; } public void increaseKickOutCount() { this.kickOutCount++; } //更新每日任务 public void initDailyMission() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(!date.equals(this.lastLoginTime)) { this.lastLoginTime = date; this.dailyMissionList = new DailyMissionFactory().updateDailyMission(); } } //添加新任务 public void chooseNewJob(String id, String uploaderPhoneNum) { //初始化项目 String file_separator = System.getProperty("file.separator"); Project project = (Project) IOHelper.readProject("data" + file_separator + "project" + file_separator + id + file_separator + id + ".ser"); MarkerJob mj = new MarkerJob(project.getId(), project.getPicList()); //添加任务类型统计 //顺带每日任务的记录 switch (project.getType()) { case 1: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 0) { dm.updateMissionState(); } } jobTypeNum[0]++; break; case 2: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 1) { dm.updateMissionState(); } } jobTypeNum[1]++; break; case 3: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 2) { dm.updateMissionState(); } } jobTypeNum[2]++; break; default: break; } //关联项入队维护 this.jobList.add(mj); this.uploaderList.add(uploaderPhoneNum); } //添加新任务 public void quitJob(String id, String uploaderPhoneNum) { //初始化项目 String file_separator = System.getProperty("file.separator"); Project project = (Project) IOHelper.readProject("data" + file_separator + "project" + file_separator + id + file_separator + id + ".ser"); MarkerJob mj = getJob(id); //删除任务类型统计 switch (project.getType()) { case 1: jobTypeNum[0]--; break; case 2: jobTypeNum[1]--; break; case 3: jobTypeNum[2]--; break; default: break; } //关联项出队维护 if(jobList.contains(mj)) this.jobList.remove(mj); if(uploaderList.contains(uploaderPhoneNum)) this.uploaderList.remove(uploaderPhoneNum); } //根据某个id获取job public MarkerJob getJob(String id) { MarkerJob result = null; for(MarkerJob mj : jobList) { if(mj.getId().equals(id)) result = mj; } return result; } //获取标记者承接的所有job列表 public ArrayList<String> getJobList() { ArrayList<String> result = new ArrayList<>(); for(MarkerJob mj : jobList) result.add(mj.getId()); return result; } public MarkerJob getMarkerJob(String id) { for(MarkerJob mj : jobList) { if (mj.getId().equals(id)) return mj; } return null; } //更新已标记未标记列表 public void updateList(String id, String picName) { for(MarkerJob mj : jobList) { if(mj.getId().equals(id)) mj.updateList(picName); } } //更新每天不同时段(24h)标记图片数统计 public void setTagTimeAnalyse() { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); //只有时分秒 String hourTime = sdf.format(new Date()).substring(0, 2); //只取小时数 int hour = Integer.parseInt(hourTime); timeMarkNum[hour]++; } //更新热点图 public void updateHotMap() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(hotMap.containsKey(date)) hotMap.put(date, hotMap.get(date) + 1); else hotMap.put(date, 1); } //更新积分图 public void updateCreditsMap(int credits) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(creditsMap.containsKey(date)) creditsMap.put(date, creditsMap.get(date) + credits); else creditsMap.put(date, credits); } //更新经验值图 public void updateEmpiricalValueMap(int empiricalValue) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(empiricalValueMap.containsKey(date)) empiricalValueMap.put(date, empiricalValueMap.get(date) + empiricalValue); else empiricalValueMap.put(date, empiricalValue); } //更新经验值和经验值记录表 public void setCredits(int credits, String cause) { this.credits += credits; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = df.format(new Date()); creditsHistory.put(date, credits + "!" + cause); } public ArrayList<Integer> getAveMarkTimeList() { return aveMarkTimeList; } public ArrayList<MarkerJob> getMarkerJobList() { return jobList;} //添加新的平均标记时间 public void addNewAveMarkTime(int aveMarkTime) { this.aveMarkTimeList.add(aveMarkTime); } public int getInterestNum() { return interestNum; } public void setInterestNum(int interestNum) { this.interestNum = interestNum; } public int getInterestType() { return interestType; } public void setInterestType(int interestType) { this.interestType = interestType; } public ArrayList<String> getInterestClassification() { return interestClassification; } public void setInterestClassification(ArrayList<String> interestClassification) { this.interestClassification = interestClassification; } public String getLastLoginTime() { return lastLoginTime; } public ArrayList<Medal> getMedalList() { return medalList; } public ArrayList<DailyMission> getDailyMissionList() { return dailyMissionList; } public int getEmpiricalValue() { return empiricalValue; } public int[] getJobTypeNum() { return jobTypeNum; } public ArrayList<String> getUploaderList() { return uploaderList; } public Map<String, Integer> getHotMap() { return hotMap; } public Map<String, String> getCreditsHistory() { return creditsHistory; } public Map<String, Integer> getCreditsMap() { return creditsMap; } public Map<String, Integer> getEmpiricalValueMap() { return empiricalValueMap; } public int[] getTimeMarkNum() { return timeMarkNum; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getCredits() { return credits; } public String getPhoneNum() { return phoneNum; } public String getPassword() { return password; } public void setEmpiricalValue(int empiricalValue) { this.empiricalValue += empiricalValue; } }
Debug-Team/PictureTag
src/main/java/com/debugTeam/entity/Marker.java
3,159
//计算积分
line_comment
zh-cn
package com.debugTeam.entity; import com.debugTeam.dao.impl.IOHelper; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @Author: Cauchy-Ny * @Description: * @Data: Create in 20:51 2018/4/1 * @Modified By: */ public class Marker implements Serializable { private static final long serialVersionUID = -5809782578272943999L; private String phoneNum; //电话号码 private String userName; //用户名 private String password; //密码 private int empiricalValue; //经验值 private int credits; //积分,标记者初始有1000 //基本统计 private ArrayList<String> uploaderList; //接过的项目的上传者列表 private ArrayList<MarkerJob> jobList; //接受的标记项目列表,内含具体信息 private ArrayList<Integer> aveMarkTimeList; //平均标记时间 // private ArrayList<Double> scoreList; //评分列表 0-5分 private Map<String, Integer> hotMap; //标记热点图 private Map<String, Integer> creditsMap; //每天的积分值 private Map<String, Integer> empiricalValueMap; //每天的经验值 private int[] jobTypeNum; //三类标注的数量,依次为:整体标注、标框标注、轮廓标注 private int[] timeMarkNum; //每个小时段标注的图片数量统计 private int kickOutCount; //被踢出数 private Map<String, String> creditsHistory; //积分获取记录<date, credits-cause> //每日任务 private String lastLoginTime; //最后登录时间 private ArrayList<DailyMission> dailyMissionList; //每日任务列表 private ArrayList<Medal> medalList; //勋章墙 //兴趣 private int interestNum; //可能感兴趣标注数量 private int interestType; //可能感兴趣类型 private ArrayList<String> interestClassification; //可能感兴趣分类 public Marker(String phoneNum, String userName, String password) { this.phoneNum = phoneNum; this.userName = userName; this.password = password; this.empiricalValue = 0; this.credits = 1000; this.uploaderList = new ArrayList<>(); this.jobList = new ArrayList<>(); this.aveMarkTimeList = new ArrayList<>(); this.jobTypeNum = new int[3]; this.timeMarkNum = new int[24]; this.hotMap = new HashMap<>(); this.creditsMap = new HashMap<>(); this.empiricalValueMap = new HashMap<>(); this.lastLoginTime = ""; this.dailyMissionList = new ArrayList<>(); this.medalList = new ArrayList<>(); this.medalList.add(new Medal(1)); this.medalList.add(new Medal(2)); this.medalList.add(new Medal(3)); this.interestNum = 0; this.interestType = 0; this.interestClassification = new ArrayList<>(); this.kickOutCount = 0; this.creditsHistory = new HashMap<>(); } //获取五维数据 0-信誉度 1-勤劳 2-经验 3-积分 4-评分 均为100分制 public double[] getFiveDimension() { double[] result = new double[5]; //计算信誉 result[0] = 80 - kickOutCount > 0 ? 80 - kickOutCount : 0; //计算勤劳 double industriousScore = 0; for(String date : hotMap.keySet()) { industriousScore += hotMap.get(date); } if(hotMap.size() != 0) industriousScore = industriousScore/hotMap.size() + 50; if(industriousScore > 100) //懒得想好的平均标记张数map到100分区间 industriousScore = 100; result[1] = industriousScore==0 ? 70 : industriousScore; //计算经验 double empiricalValueScore = 0; for(String date : empiricalValueMap.keySet()) { empiricalValueScore += empiricalValueMap.get(date); } empiricalValueScore = empiricalValueScore/300 + 50; if(empiricalValueScore > 100) //懒得想... empiricalValueScore = 100; result[2] = empiricalValueScore; //计算 <SUF> double creditsScore = 0; for(String date : creditsMap.keySet()) { creditsScore += creditsMap.get(date); } creditsScore = creditsScore/300 + 50; if(creditsScore > 100) //懒得想... creditsScore = 100; result[3] = creditsScore; //计算评分 result[4] = 80; for(MarkerJob job: jobList) { if(job.getScore() != 0) { result[4] = jobList.stream() .map(p -> p.getScore()) .reduce(Double::sum) .orElse(0.0) / jobList.size() * 20; break; } } return result; } public void increaseKickOutCount() { this.kickOutCount++; } //更新每日任务 public void initDailyMission() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(!date.equals(this.lastLoginTime)) { this.lastLoginTime = date; this.dailyMissionList = new DailyMissionFactory().updateDailyMission(); } } //添加新任务 public void chooseNewJob(String id, String uploaderPhoneNum) { //初始化项目 String file_separator = System.getProperty("file.separator"); Project project = (Project) IOHelper.readProject("data" + file_separator + "project" + file_separator + id + file_separator + id + ".ser"); MarkerJob mj = new MarkerJob(project.getId(), project.getPicList()); //添加任务类型统计 //顺带每日任务的记录 switch (project.getType()) { case 1: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 0) { dm.updateMissionState(); } } jobTypeNum[0]++; break; case 2: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 1) { dm.updateMissionState(); } } jobTypeNum[1]++; break; case 3: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 2) { dm.updateMissionState(); } } jobTypeNum[2]++; break; default: break; } //关联项入队维护 this.jobList.add(mj); this.uploaderList.add(uploaderPhoneNum); } //添加新任务 public void quitJob(String id, String uploaderPhoneNum) { //初始化项目 String file_separator = System.getProperty("file.separator"); Project project = (Project) IOHelper.readProject("data" + file_separator + "project" + file_separator + id + file_separator + id + ".ser"); MarkerJob mj = getJob(id); //删除任务类型统计 switch (project.getType()) { case 1: jobTypeNum[0]--; break; case 2: jobTypeNum[1]--; break; case 3: jobTypeNum[2]--; break; default: break; } //关联项出队维护 if(jobList.contains(mj)) this.jobList.remove(mj); if(uploaderList.contains(uploaderPhoneNum)) this.uploaderList.remove(uploaderPhoneNum); } //根据某个id获取job public MarkerJob getJob(String id) { MarkerJob result = null; for(MarkerJob mj : jobList) { if(mj.getId().equals(id)) result = mj; } return result; } //获取标记者承接的所有job列表 public ArrayList<String> getJobList() { ArrayList<String> result = new ArrayList<>(); for(MarkerJob mj : jobList) result.add(mj.getId()); return result; } public MarkerJob getMarkerJob(String id) { for(MarkerJob mj : jobList) { if (mj.getId().equals(id)) return mj; } return null; } //更新已标记未标记列表 public void updateList(String id, String picName) { for(MarkerJob mj : jobList) { if(mj.getId().equals(id)) mj.updateList(picName); } } //更新每天不同时段(24h)标记图片数统计 public void setTagTimeAnalyse() { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); //只有时分秒 String hourTime = sdf.format(new Date()).substring(0, 2); //只取小时数 int hour = Integer.parseInt(hourTime); timeMarkNum[hour]++; } //更新热点图 public void updateHotMap() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(hotMap.containsKey(date)) hotMap.put(date, hotMap.get(date) + 1); else hotMap.put(date, 1); } //更新积分图 public void updateCreditsMap(int credits) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(creditsMap.containsKey(date)) creditsMap.put(date, creditsMap.get(date) + credits); else creditsMap.put(date, credits); } //更新经验值图 public void updateEmpiricalValueMap(int empiricalValue) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(empiricalValueMap.containsKey(date)) empiricalValueMap.put(date, empiricalValueMap.get(date) + empiricalValue); else empiricalValueMap.put(date, empiricalValue); } //更新经验值和经验值记录表 public void setCredits(int credits, String cause) { this.credits += credits; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = df.format(new Date()); creditsHistory.put(date, credits + "!" + cause); } public ArrayList<Integer> getAveMarkTimeList() { return aveMarkTimeList; } public ArrayList<MarkerJob> getMarkerJobList() { return jobList;} //添加新的平均标记时间 public void addNewAveMarkTime(int aveMarkTime) { this.aveMarkTimeList.add(aveMarkTime); } public int getInterestNum() { return interestNum; } public void setInterestNum(int interestNum) { this.interestNum = interestNum; } public int getInterestType() { return interestType; } public void setInterestType(int interestType) { this.interestType = interestType; } public ArrayList<String> getInterestClassification() { return interestClassification; } public void setInterestClassification(ArrayList<String> interestClassification) { this.interestClassification = interestClassification; } public String getLastLoginTime() { return lastLoginTime; } public ArrayList<Medal> getMedalList() { return medalList; } public ArrayList<DailyMission> getDailyMissionList() { return dailyMissionList; } public int getEmpiricalValue() { return empiricalValue; } public int[] getJobTypeNum() { return jobTypeNum; } public ArrayList<String> getUploaderList() { return uploaderList; } public Map<String, Integer> getHotMap() { return hotMap; } public Map<String, String> getCreditsHistory() { return creditsHistory; } public Map<String, Integer> getCreditsMap() { return creditsMap; } public Map<String, Integer> getEmpiricalValueMap() { return empiricalValueMap; } public int[] getTimeMarkNum() { return timeMarkNum; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getCredits() { return credits; } public String getPhoneNum() { return phoneNum; } public String getPassword() { return password; } public void setEmpiricalValue(int empiricalValue) { this.empiricalValue += empiricalValue; } }
0
2,851
3
3,188
4
3,341
3
3,159
4
3,947
7
false
false
false
false
false
true
24957_1
package com.mooctest; import io.appium.java_client.AndroidKeyCode; import io.appium.java_client.AppiumDriver; import org.openqa.selenium.remote.DesiredCapabilities; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; public class Main { /** * 所有和AppiumDriver相关的操作都必须写在该函数中 * * @param driver */ public void test(AppiumDriver driver) { driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); //设置尝试定位控件的最长时间为8s,也就是最多尝试8s /* * 余下的测试逻辑请按照题目要求进行编写 */ waitForActivity(driver, "MainActivity"); driver.findElementById("com.sankuai.meituan:id/city_button").click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } driver.findElementsByXPath("//android.widget.TextView[@text='南京']").get(1).click(); driver.findElementByXPath("//android.view.View[@content-desc='附近']").click(); driver.findElementByXPath("//android.view.View[@content-desc='发现']").click(); driver.findElementByXPath("//android.view.View[@content-desc='订单']").click(); driver.findElementByXPath("//android.view.View[@content-desc='我的']").click(); driver.findElementByXPath("//android.view.View[@content-desc='首页']").click(); driver.findElementByXPath("//android.view.View[@content-desc='美食']").click(); driver.findElementByXPath("//android.widget.TextView[@text='优惠团购']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='附近好券']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='预约订座']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='外卖']").click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='新店特惠']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='自助餐']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='火锅']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='江浙菜']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_list_map_menu_img").click(); driver.findElementById("com.sankuai.meituan:id/food_search_header_search").click(); driver.findElementByXPath("//android.widget.TextView[@text='新街口地区']").click(); driver.findElementById("com.sankuai.meituan:id/food_map_location_button").click(); driver.findElementById("com.sankuai.meituan:id/food_search_header_back").click(); driver.findElementById("com.sankuai.meituan:id/tv_search_text").click(); driver.findElementById("com.sankuai.meituan:id/search_edit").sendKeys("小龙虾"); driver.findElementById("com.sankuai.meituan:id/search").click(); driver.findElementById("com.sankuai.meituan:id/category").click(); driver.findElementByXPath("//android.widget.TextView[@text='美食']").click(); driver.findElementById("com.sankuai.meituan:id/category").click(); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.findElementByXPath("//android.widget.TextView[@text='海鲜']").click(); driver.findElementById("com.sankuai.meituan:id/area").click(); driver.findElementByXPath("//android.widget.TextView[@text='鼓楼区']").click(); driver.findElementByXPath("//android.widget.TextView[@text='新街口/金轮/五台山体育中心']").click(); driver.findElementById("com.sankuai.meituan:id/sort").click(); driver.findElementByXPath("//android.widget.TextView[@text='好评优先']").click(); driver.findElementById("com.sankuai.meituan:id/senior_filter").click(); driver.findElementByXPath("//android.widget.TextView[@text='5~10人餐']").click(); driver.findElementById("com.sankuai.meituan:id/bottom_confirm").click(); driver.findElementsById("com.sankuai.meituan:id/image").get(0).click(); driver.findElementById("com.sankuai.meituan:id/favor").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementById("com.sankuai.meituan:id/share_cancel").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementByXPath("//android.widget.TextView[@text='微信好友']"); //.click(); // driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='朋友圈']"); //.click(); // driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='复制']").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementByXPath("//android.widget.TextView[@text='更多']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_poi_top_image").click(); driver.findElementByXPath("//android.widget.ImageButton[@content-desc='转到上一层级']").click(); driver.findElementById("com.sankuai.meituan:id/food_poi_address_container").click(); driver.findElementById("com.sankuai.meituan:id/food_header_back").click(); driver.findElementById("com.sankuai.meituan:id/food_poi_taxi_img").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_poi_telephone_img").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='优惠信息']").click(); driver.findElementByXPath("//android.widget.TextView[@text='用户评论']").click(); driver.findElementByXPath("//android.widget.TextView[@text='商家信息']").click(); driver.quit(); } private void waitForActivity(AppiumDriver driver, String activity) { activity = "." + activity; while (!driver.currentActivity().contains(activity)) { System.out.println("- Waiting for " + activity); Thread.yield(); } System.out.println(">> Begin " + activity); } /** * AppiumDriver的初始化逻辑必须写在该函数中 * * @return */ public AppiumDriver initAppiumTest() { AppiumDriver driver = null; File classpathRoot = new File(System.getProperty("user.dir")); File appDir = new File(classpathRoot, "apk"); File app = new File(appDir, "Meituan.apk"); //设置自动化相关参数 DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("automationName", "UiAutomator2"); capabilities.setCapability("browserName", ""); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("deviceName", "Android Emulator"); //设置apk路径 capabilities.setCapability("app", app.getAbsolutePath()); capabilities.setCapability("appPackage", "com.sankuai.meituan"); capabilities.setCapability("appActivity", "com.meituan.android.pt.homepage.activity.Welcome"); //设置使用unicode键盘,支持输入中文和特殊字符 capabilities.setCapability("unicodeKeyboard", "true"); //设置用例执行完成后重置键盘 capabilities.setCapability("resetKeyboard", "true"); capabilities.setCapability("noSign", "true"); //初始化 try { driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return driver; } public void start() { test(initAppiumTest()); } public static void main(String[] args) { Main main = new Main(); main.start(); } }
DeepAQ/SoftwareTesting
Appium/Meituan/src/com/mooctest/Main.java
2,349
//设置尝试定位控件的最长时间为8s,也就是最多尝试8s
line_comment
zh-cn
package com.mooctest; import io.appium.java_client.AndroidKeyCode; import io.appium.java_client.AppiumDriver; import org.openqa.selenium.remote.DesiredCapabilities; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; public class Main { /** * 所有和AppiumDriver相关的操作都必须写在该函数中 * * @param driver */ public void test(AppiumDriver driver) { driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); //设置 <SUF> /* * 余下的测试逻辑请按照题目要求进行编写 */ waitForActivity(driver, "MainActivity"); driver.findElementById("com.sankuai.meituan:id/city_button").click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } driver.findElementsByXPath("//android.widget.TextView[@text='南京']").get(1).click(); driver.findElementByXPath("//android.view.View[@content-desc='附近']").click(); driver.findElementByXPath("//android.view.View[@content-desc='发现']").click(); driver.findElementByXPath("//android.view.View[@content-desc='订单']").click(); driver.findElementByXPath("//android.view.View[@content-desc='我的']").click(); driver.findElementByXPath("//android.view.View[@content-desc='首页']").click(); driver.findElementByXPath("//android.view.View[@content-desc='美食']").click(); driver.findElementByXPath("//android.widget.TextView[@text='优惠团购']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='附近好券']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='预约订座']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='外卖']").click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='新店特惠']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='自助餐']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='火锅']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='江浙菜']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_list_map_menu_img").click(); driver.findElementById("com.sankuai.meituan:id/food_search_header_search").click(); driver.findElementByXPath("//android.widget.TextView[@text='新街口地区']").click(); driver.findElementById("com.sankuai.meituan:id/food_map_location_button").click(); driver.findElementById("com.sankuai.meituan:id/food_search_header_back").click(); driver.findElementById("com.sankuai.meituan:id/tv_search_text").click(); driver.findElementById("com.sankuai.meituan:id/search_edit").sendKeys("小龙虾"); driver.findElementById("com.sankuai.meituan:id/search").click(); driver.findElementById("com.sankuai.meituan:id/category").click(); driver.findElementByXPath("//android.widget.TextView[@text='美食']").click(); driver.findElementById("com.sankuai.meituan:id/category").click(); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.findElementByXPath("//android.widget.TextView[@text='海鲜']").click(); driver.findElementById("com.sankuai.meituan:id/area").click(); driver.findElementByXPath("//android.widget.TextView[@text='鼓楼区']").click(); driver.findElementByXPath("//android.widget.TextView[@text='新街口/金轮/五台山体育中心']").click(); driver.findElementById("com.sankuai.meituan:id/sort").click(); driver.findElementByXPath("//android.widget.TextView[@text='好评优先']").click(); driver.findElementById("com.sankuai.meituan:id/senior_filter").click(); driver.findElementByXPath("//android.widget.TextView[@text='5~10人餐']").click(); driver.findElementById("com.sankuai.meituan:id/bottom_confirm").click(); driver.findElementsById("com.sankuai.meituan:id/image").get(0).click(); driver.findElementById("com.sankuai.meituan:id/favor").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementById("com.sankuai.meituan:id/share_cancel").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementByXPath("//android.widget.TextView[@text='微信好友']"); //.click(); // driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='朋友圈']"); //.click(); // driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='复制']").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementByXPath("//android.widget.TextView[@text='更多']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_poi_top_image").click(); driver.findElementByXPath("//android.widget.ImageButton[@content-desc='转到上一层级']").click(); driver.findElementById("com.sankuai.meituan:id/food_poi_address_container").click(); driver.findElementById("com.sankuai.meituan:id/food_header_back").click(); driver.findElementById("com.sankuai.meituan:id/food_poi_taxi_img").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_poi_telephone_img").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='优惠信息']").click(); driver.findElementByXPath("//android.widget.TextView[@text='用户评论']").click(); driver.findElementByXPath("//android.widget.TextView[@text='商家信息']").click(); driver.quit(); } private void waitForActivity(AppiumDriver driver, String activity) { activity = "." + activity; while (!driver.currentActivity().contains(activity)) { System.out.println("- Waiting for " + activity); Thread.yield(); } System.out.println(">> Begin " + activity); } /** * AppiumDriver的初始化逻辑必须写在该函数中 * * @return */ public AppiumDriver initAppiumTest() { AppiumDriver driver = null; File classpathRoot = new File(System.getProperty("user.dir")); File appDir = new File(classpathRoot, "apk"); File app = new File(appDir, "Meituan.apk"); //设置自动化相关参数 DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("automationName", "UiAutomator2"); capabilities.setCapability("browserName", ""); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("deviceName", "Android Emulator"); //设置apk路径 capabilities.setCapability("app", app.getAbsolutePath()); capabilities.setCapability("appPackage", "com.sankuai.meituan"); capabilities.setCapability("appActivity", "com.meituan.android.pt.homepage.activity.Welcome"); //设置使用unicode键盘,支持输入中文和特殊字符 capabilities.setCapability("unicodeKeyboard", "true"); //设置用例执行完成后重置键盘 capabilities.setCapability("resetKeyboard", "true"); capabilities.setCapability("noSign", "true"); //初始化 try { driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return driver; } public void start() { test(initAppiumTest()); } public static void main(String[] args) { Main main = new Main(); main.start(); } }
0
1,932
18
2,349
19
2,403
16
2,349
19
2,901
31
false
false
false
false
false
true
34717_5
package info.hb.ccn.main; import info.hb.cnn.core.CNN; import info.hb.cnn.core.CNN.LayerBuilder; import info.hb.cnn.core.Layer; import info.hb.cnn.core.Layer.Size; import info.hb.cnn.data.DataSet; import info.hb.cnn.utils.ConcurentRunner; public class CNNMnist { private static final String MODEL_NAME = "mnist/model/model.cnn"; private static final String TRAIN_DATA = "mnist/train.format"; private static final String TEST_DATA = "mnist/test.format"; private static final String TEST_PREDICT = "mnist/test.predict"; public static void main(String[] args) { System.err.println("训练阶段:"); runTrain(); System.err.println("测试阶段:"); runTest(); ConcurentRunner.stop(); } public static void runTrain() { // 构建网络层次结构 LayerBuilder builder = new LayerBuilder(); builder.addLayer(Layer.buildInputLayer(new Size(28, 28))); // 输入层输出map大小为28×28 builder.addLayer(Layer.buildConvLayer(6, new Size(5, 5))); // 卷积层输出map大小为24×24,24=28+1-5 builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样层输出map大小为12×12,12=24/2 builder.addLayer(Layer.buildConvLayer(12, new Size(5, 5))); // 卷积层输出map大小为8×8,8=12+1-5 builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样层输出map大小为4×4,4=8/2 builder.addLayer(Layer.buildOutputLayer(10)); CNN cnn = new CNN(builder, 10); // 加载训练数据 DataSet dataset = DataSet.load(TRAIN_DATA, ",", 784); // 开始训练模型 cnn.train(dataset, 5); // 保存训练好的模型 cnn.saveModel(MODEL_NAME); dataset.clear(); } public static void runTest() { // 加载训练好的模型 CNN cnn = CNN.loadModel(MODEL_NAME); // 加载测试数据 DataSet testSet = DataSet.load(TEST_DATA, ",", -1); // 预测结果 cnn.predict(testSet, TEST_PREDICT); testSet.clear(); } }
DeepCompute/cnn
src/main/java/info/hb/ccn/main/CNNMnist.java
664
// 采样层输出map大小为4×4,4=8/2
line_comment
zh-cn
package info.hb.ccn.main; import info.hb.cnn.core.CNN; import info.hb.cnn.core.CNN.LayerBuilder; import info.hb.cnn.core.Layer; import info.hb.cnn.core.Layer.Size; import info.hb.cnn.data.DataSet; import info.hb.cnn.utils.ConcurentRunner; public class CNNMnist { private static final String MODEL_NAME = "mnist/model/model.cnn"; private static final String TRAIN_DATA = "mnist/train.format"; private static final String TEST_DATA = "mnist/test.format"; private static final String TEST_PREDICT = "mnist/test.predict"; public static void main(String[] args) { System.err.println("训练阶段:"); runTrain(); System.err.println("测试阶段:"); runTest(); ConcurentRunner.stop(); } public static void runTrain() { // 构建网络层次结构 LayerBuilder builder = new LayerBuilder(); builder.addLayer(Layer.buildInputLayer(new Size(28, 28))); // 输入层输出map大小为28×28 builder.addLayer(Layer.buildConvLayer(6, new Size(5, 5))); // 卷积层输出map大小为24×24,24=28+1-5 builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样层输出map大小为12×12,12=24/2 builder.addLayer(Layer.buildConvLayer(12, new Size(5, 5))); // 卷积层输出map大小为8×8,8=12+1-5 builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样 <SUF> builder.addLayer(Layer.buildOutputLayer(10)); CNN cnn = new CNN(builder, 10); // 加载训练数据 DataSet dataset = DataSet.load(TRAIN_DATA, ",", 784); // 开始训练模型 cnn.train(dataset, 5); // 保存训练好的模型 cnn.saveModel(MODEL_NAME); dataset.clear(); } public static void runTest() { // 加载训练好的模型 CNN cnn = CNN.loadModel(MODEL_NAME); // 加载测试数据 DataSet testSet = DataSet.load(TEST_DATA, ",", -1); // 预测结果 cnn.predict(testSet, TEST_PREDICT); testSet.clear(); } }
0
575
18
664
18
641
18
664
18
836
24
false
false
false
false
false
true
58221_15
package bakacraft; import bakacraft.WeaponSkills.Random; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; public class CraftLimit extends BAKAPlugin implements Listener { public final static String CRAFT = Random.Colorilize("&2制造"); public final static String USE = Random.Colorilize("&3使用"); public final static String BREAK = Random.Colorilize("&c破坏"); public CraftLimit(JavaPlugin instance) { super(instance); getInstance().getServer().getPluginManager().registerEvents(this, instance); } @Override public void onDisable() { super.onDisable(); } //制造限制插件 //必须学习技能之后才有制造某件东西的权限 //限制下列工具: //木、石、铁、金、钻石 稿、斧、剑 //铲和锄不限制 //工作台、熔炉、打火机、剪刀、箱子 //合成除了原始合成之外,还需要旧的一件工具合成 //正常合成铁镐之后,会有无法使用标志 //需要使用一个石稿进行解锁 //熔炉需要打火机解锁才能使用。(消耗1点打火机耐久) //工作台、打火机、剪刀、箱子无需前置解锁即可使用() //挖掘限制: //木头可以手撸 //要挖石头必须木镐及以上 //要挖铁必须石镐及以上 //依次类推 //烧制相关矿石需要相关前置解锁 public boolean breakable(Material mat) { switch (mat) { case GOLD_ORE: case IRON_ORE: case DIAMOND_ORE: return true; default: return false; } } public boolean craftable(Material mat) { switch (mat) { case WOOD_AXE: case GOLD_AXE: case IRON_AXE: case STONE_AXE: case DIAMOND_AXE: case WOOD_PICKAXE: case GOLD_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: case DIAMOND_PICKAXE: case GOLD_SWORD: case STONE_SWORD: case IRON_SWORD: case WOOD_SWORD: case DIAMOND_SWORD: case WORKBENCH: case FURNACE: case SHEARS: case CHEST: return true; default: return false; } } public boolean usable(Material mat) { switch (mat) { case WOOD_AXE: case GOLD_AXE: case IRON_AXE: case STONE_AXE: case DIAMOND_AXE: case WOOD_PICKAXE: case GOLD_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: case DIAMOND_PICKAXE: case GOLD_SWORD: case STONE_SWORD: case IRON_SWORD: case WOOD_SWORD: case DIAMOND_SWORD: return true; default: return false; } } @EventHandler public void onPlayerCraft(CraftItemEvent e) { if (!craftable(e.getRecipe().getResult().getType())) return; if (e.getWhoClicked() instanceof Player) { Player p = (Player) e.getWhoClicked(); if (p.isOp()) return; if (!p.hasPermission(CRAFT + e.getCurrentItem().getItemMeta().getDisplayName())) { e.setCancelled(true); } else { List<String> lores = new ArrayList<>(); lores.add(Random.Colorilize("&e需要权限:")); lores.add(USE + e.getCurrentItem().getItemMeta().getDisplayName()); ItemMeta meta = e.getCurrentItem().getItemMeta(); meta.setLore(lores); e.getCurrentItem().setItemMeta(meta); } } } @EventHandler public void onPlayerFurnaceOpen(InventoryOpenEvent e) { if (e.getPlayer().isOp()) return; if (e.getInventory().getType() == InventoryType.FURNACE) { if (!e.getPlayer().getItemInHand().getType().equals(Material.FLINT_AND_STEEL)) { ((Player) e.getPlayer()).sendRawMessage("你需要一个打火石来点燃熔炉"); e.setCancelled(true); } } } @EventHandler public void onPlayerInteract(PlayerInteractEvent e) { if (e.getPlayer().isOp()) return; if (!usable(e.getPlayer().getItemInHand().getType())) return; if (e.getPlayer().hasPermission(CRAFT + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) { e.setCancelled(true); } } @EventHandler public void onPlayerBreak(BlockBreakEvent e) { if (e.getPlayer().isOp()) return; if (!breakable(e.getBlock().getType())) return; if (e.getPlayer().hasPermission(BREAK + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) { e.setCancelled(true); } } @EventHandler public void onPlayerSwitchHeld(PlayerItemHeldEvent e) { if (e.getPlayer().isOp()) return; ItemStack newItem = e.getPlayer().getInventory().getItem(e.getNewSlot()); if (newItem == null || !usable(newItem.getType())) return; if (e.getPlayer().hasPermission(USE + newItem.getItemMeta().getDisplayName())) { e.getPlayer().sendRawMessage("你需要解锁之后才能使用这件装备"); e.setCancelled(true); } } }
Deliay/BAKACraft
src/main/java/bakacraft/CraftLimit.java
1,568
//依次类推
line_comment
zh-cn
package bakacraft; import bakacraft.WeaponSkills.Random; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; public class CraftLimit extends BAKAPlugin implements Listener { public final static String CRAFT = Random.Colorilize("&2制造"); public final static String USE = Random.Colorilize("&3使用"); public final static String BREAK = Random.Colorilize("&c破坏"); public CraftLimit(JavaPlugin instance) { super(instance); getInstance().getServer().getPluginManager().registerEvents(this, instance); } @Override public void onDisable() { super.onDisable(); } //制造限制插件 //必须学习技能之后才有制造某件东西的权限 //限制下列工具: //木、石、铁、金、钻石 稿、斧、剑 //铲和锄不限制 //工作台、熔炉、打火机、剪刀、箱子 //合成除了原始合成之外,还需要旧的一件工具合成 //正常合成铁镐之后,会有无法使用标志 //需要使用一个石稿进行解锁 //熔炉需要打火机解锁才能使用。(消耗1点打火机耐久) //工作台、打火机、剪刀、箱子无需前置解锁即可使用() //挖掘限制: //木头可以手撸 //要挖石头必须木镐及以上 //要挖铁必须石镐及以上 //依次 <SUF> //烧制相关矿石需要相关前置解锁 public boolean breakable(Material mat) { switch (mat) { case GOLD_ORE: case IRON_ORE: case DIAMOND_ORE: return true; default: return false; } } public boolean craftable(Material mat) { switch (mat) { case WOOD_AXE: case GOLD_AXE: case IRON_AXE: case STONE_AXE: case DIAMOND_AXE: case WOOD_PICKAXE: case GOLD_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: case DIAMOND_PICKAXE: case GOLD_SWORD: case STONE_SWORD: case IRON_SWORD: case WOOD_SWORD: case DIAMOND_SWORD: case WORKBENCH: case FURNACE: case SHEARS: case CHEST: return true; default: return false; } } public boolean usable(Material mat) { switch (mat) { case WOOD_AXE: case GOLD_AXE: case IRON_AXE: case STONE_AXE: case DIAMOND_AXE: case WOOD_PICKAXE: case GOLD_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: case DIAMOND_PICKAXE: case GOLD_SWORD: case STONE_SWORD: case IRON_SWORD: case WOOD_SWORD: case DIAMOND_SWORD: return true; default: return false; } } @EventHandler public void onPlayerCraft(CraftItemEvent e) { if (!craftable(e.getRecipe().getResult().getType())) return; if (e.getWhoClicked() instanceof Player) { Player p = (Player) e.getWhoClicked(); if (p.isOp()) return; if (!p.hasPermission(CRAFT + e.getCurrentItem().getItemMeta().getDisplayName())) { e.setCancelled(true); } else { List<String> lores = new ArrayList<>(); lores.add(Random.Colorilize("&e需要权限:")); lores.add(USE + e.getCurrentItem().getItemMeta().getDisplayName()); ItemMeta meta = e.getCurrentItem().getItemMeta(); meta.setLore(lores); e.getCurrentItem().setItemMeta(meta); } } } @EventHandler public void onPlayerFurnaceOpen(InventoryOpenEvent e) { if (e.getPlayer().isOp()) return; if (e.getInventory().getType() == InventoryType.FURNACE) { if (!e.getPlayer().getItemInHand().getType().equals(Material.FLINT_AND_STEEL)) { ((Player) e.getPlayer()).sendRawMessage("你需要一个打火石来点燃熔炉"); e.setCancelled(true); } } } @EventHandler public void onPlayerInteract(PlayerInteractEvent e) { if (e.getPlayer().isOp()) return; if (!usable(e.getPlayer().getItemInHand().getType())) return; if (e.getPlayer().hasPermission(CRAFT + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) { e.setCancelled(true); } } @EventHandler public void onPlayerBreak(BlockBreakEvent e) { if (e.getPlayer().isOp()) return; if (!breakable(e.getBlock().getType())) return; if (e.getPlayer().hasPermission(BREAK + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) { e.setCancelled(true); } } @EventHandler public void onPlayerSwitchHeld(PlayerItemHeldEvent e) { if (e.getPlayer().isOp()) return; ItemStack newItem = e.getPlayer().getInventory().getItem(e.getNewSlot()); if (newItem == null || !usable(newItem.getType())) return; if (e.getPlayer().hasPermission(USE + newItem.getItemMeta().getDisplayName())) { e.getPlayer().sendRawMessage("你需要解锁之后才能使用这件装备"); e.setCancelled(true); } } }
0
1,324
4
1,568
5
1,559
5
1,568
5
2,013
9
false
false
false
false
false
true
55286_3
package com.xd.demi.view; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; /** * Created by demi on 17/4/24. */ public class MyFlowLayout extends LinearLayout { private int verticalSpacing = 20; private int horizontalSpacing = 20; public MyFlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int widthUsed = paddingLeft + paddingRight; //已经占用的宽度 int heightUsed = paddingTop + paddingBottom; //已经占用的高度 int childMaxHeightOfThisLine = 0; //孩子中最高的那位,其实都一样高 int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childUsedWidth = 0; //某个孩子的宽度 int childUsedHeight = 0; //某个孩子的高度 measureChild(child, widthMeasureSpec, heightMeasureSpec); childUsedWidth += child.getMeasuredWidth(); childUsedHeight += child.getMeasuredHeight(); LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; childUsedWidth += marginLayoutParams.leftMargin + marginLayoutParams.rightMargin + horizontalSpacing; childUsedHeight += marginLayoutParams.topMargin + marginLayoutParams.bottomMargin; if (widthUsed + childUsedWidth < widthSpecSize) { widthUsed += childUsedWidth; if (childUsedHeight > childMaxHeightOfThisLine) { childMaxHeightOfThisLine = childUsedHeight; } } else { heightUsed += childMaxHeightOfThisLine + verticalSpacing; widthUsed = paddingLeft + paddingRight + childUsedWidth; childMaxHeightOfThisLine = childUsedHeight; } } } heightUsed += childMaxHeightOfThisLine; setMeasuredDimension(widthSpecSize, heightUsed); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int childStartLayoutX = paddingLeft; int childStartLayoutY = paddingTop; int widthUsed = paddingLeft + paddingRight; int childMaxHeight = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childNeededWidth, childNeedHeight; int left, top, right, bottom; int childMeasuredWidth = child.getMeasuredWidth(); int childMeasuredHeight = child.getMeasuredHeight(); LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; int childLeftMargin = marginLayoutParams.leftMargin; int childTopMargin = marginLayoutParams.topMargin; int childRightMargin = marginLayoutParams.rightMargin; int childBottomMargin = marginLayoutParams.bottomMargin; childNeededWidth = childLeftMargin + childRightMargin + childMeasuredWidth + horizontalSpacing; childNeedHeight = childTopMargin + childBottomMargin + childMeasuredHeight; if (widthUsed + childNeededWidth <= r - l) { if (childNeedHeight > childMaxHeight) { childMaxHeight = childNeedHeight; } left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; } else { childStartLayoutY += childMaxHeight + verticalSpacing; childStartLayoutX = paddingLeft; widthUsed = paddingLeft + paddingRight; left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; childMaxHeight = childNeedHeight; } child.layout(left, top, right, bottom); } } } }
Demidong/ClockView
app/src/main/java/com/xd/demi/view/MyFlowLayout.java
1,135
//孩子中最高的那位,其实都一样高
line_comment
zh-cn
package com.xd.demi.view; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; /** * Created by demi on 17/4/24. */ public class MyFlowLayout extends LinearLayout { private int verticalSpacing = 20; private int horizontalSpacing = 20; public MyFlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int widthUsed = paddingLeft + paddingRight; //已经占用的宽度 int heightUsed = paddingTop + paddingBottom; //已经占用的高度 int childMaxHeightOfThisLine = 0; //孩子 <SUF> int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childUsedWidth = 0; //某个孩子的宽度 int childUsedHeight = 0; //某个孩子的高度 measureChild(child, widthMeasureSpec, heightMeasureSpec); childUsedWidth += child.getMeasuredWidth(); childUsedHeight += child.getMeasuredHeight(); LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; childUsedWidth += marginLayoutParams.leftMargin + marginLayoutParams.rightMargin + horizontalSpacing; childUsedHeight += marginLayoutParams.topMargin + marginLayoutParams.bottomMargin; if (widthUsed + childUsedWidth < widthSpecSize) { widthUsed += childUsedWidth; if (childUsedHeight > childMaxHeightOfThisLine) { childMaxHeightOfThisLine = childUsedHeight; } } else { heightUsed += childMaxHeightOfThisLine + verticalSpacing; widthUsed = paddingLeft + paddingRight + childUsedWidth; childMaxHeightOfThisLine = childUsedHeight; } } } heightUsed += childMaxHeightOfThisLine; setMeasuredDimension(widthSpecSize, heightUsed); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int childStartLayoutX = paddingLeft; int childStartLayoutY = paddingTop; int widthUsed = paddingLeft + paddingRight; int childMaxHeight = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childNeededWidth, childNeedHeight; int left, top, right, bottom; int childMeasuredWidth = child.getMeasuredWidth(); int childMeasuredHeight = child.getMeasuredHeight(); LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; int childLeftMargin = marginLayoutParams.leftMargin; int childTopMargin = marginLayoutParams.topMargin; int childRightMargin = marginLayoutParams.rightMargin; int childBottomMargin = marginLayoutParams.bottomMargin; childNeededWidth = childLeftMargin + childRightMargin + childMeasuredWidth + horizontalSpacing; childNeedHeight = childTopMargin + childBottomMargin + childMeasuredHeight; if (widthUsed + childNeededWidth <= r - l) { if (childNeedHeight > childMaxHeight) { childMaxHeight = childNeedHeight; } left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; } else { childStartLayoutY += childMaxHeight + verticalSpacing; childStartLayoutX = paddingLeft; widthUsed = paddingLeft + paddingRight; left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; childMaxHeight = childNeedHeight; } child.layout(left, top, right, bottom); } } } }
0
1,040
10
1,148
14
1,203
11
1,135
14
1,433
18
false
false
false
false
false
true
64372_3
package com.dxj.util; import lombok.extern.slf4j.Slf4j; /** * 原作者 zzxadi https://github.com/zzxadi/Snowflake-IdWorker * * @author Sinkiang */ @Slf4j public class SnowFlakeUtil { private final long id; /** * 机器标识位数 */ private final long workerIdBits = 10L; /** * 0,并发控制 */ private long sequence = 0L; private long lastTimestamp = -1L; private SnowFlakeUtil(long id) { // 机器ID最大值: 1023 long maxWorkerId = ~(-1L << this.workerIdBits); if (id > maxWorkerId || id < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } this.id = id; } public synchronized long nextId() { long timestamp = timeGen(); // 毫秒内自增位 long sequenceBits = 12L; if (this.lastTimestamp == timestamp) { //如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始 // 4095,111111111111,12位 long sequenceMask = ~(-1L << sequenceBits); this.sequence = this.sequence + 1 & sequenceMask; if (this.sequence == 0) { // 重新生成timestamp timestamp = this.tilNextMillis(this.lastTimestamp); } } else { this.sequence = 0; } if (timestamp < this.lastTimestamp) { log.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); return -1; } this.lastTimestamp = timestamp; // 22 long timestampLeftShift = sequenceBits + this.workerIdBits; // 时间起始标记点,作为基准,一般取系统的最近时间 long epoch = 1524291141010L; // 12 return timestamp - epoch << timestampLeftShift | this.id << sequenceBits | this.sequence; } private static SnowFlakeUtil flowIdWorker = new SnowFlakeUtil(1); public static SnowFlakeUtil getFlowIdInstance() { return flowIdWorker; } /** * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后 */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 获得系统当前毫秒数 */ private static long timeGen() { return System.currentTimeMillis(); } }
DengSinkiang/sk-admin
sk-common/src/main/java/com/dxj/util/SnowFlakeUtil.java
697
// 机器ID最大值: 1023
line_comment
zh-cn
package com.dxj.util; import lombok.extern.slf4j.Slf4j; /** * 原作者 zzxadi https://github.com/zzxadi/Snowflake-IdWorker * * @author Sinkiang */ @Slf4j public class SnowFlakeUtil { private final long id; /** * 机器标识位数 */ private final long workerIdBits = 10L; /** * 0,并发控制 */ private long sequence = 0L; private long lastTimestamp = -1L; private SnowFlakeUtil(long id) { // 机器 <SUF> long maxWorkerId = ~(-1L << this.workerIdBits); if (id > maxWorkerId || id < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } this.id = id; } public synchronized long nextId() { long timestamp = timeGen(); // 毫秒内自增位 long sequenceBits = 12L; if (this.lastTimestamp == timestamp) { //如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始 // 4095,111111111111,12位 long sequenceMask = ~(-1L << sequenceBits); this.sequence = this.sequence + 1 & sequenceMask; if (this.sequence == 0) { // 重新生成timestamp timestamp = this.tilNextMillis(this.lastTimestamp); } } else { this.sequence = 0; } if (timestamp < this.lastTimestamp) { log.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); return -1; } this.lastTimestamp = timestamp; // 22 long timestampLeftShift = sequenceBits + this.workerIdBits; // 时间起始标记点,作为基准,一般取系统的最近时间 long epoch = 1524291141010L; // 12 return timestamp - epoch << timestampLeftShift | this.id << sequenceBits | this.sequence; } private static SnowFlakeUtil flowIdWorker = new SnowFlakeUtil(1); public static SnowFlakeUtil getFlowIdInstance() { return flowIdWorker; } /** * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后 */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 获得系统当前毫秒数 */ private static long timeGen() { return System.currentTimeMillis(); } }
0
660
12
697
12
749
11
697
12
877
14
false
false
false
false
false
true
51482_14
/* * www.msxf.com Inc. * Copyright (c) 2017 All Rights Reserved */ package com.falcon.suitagent.util; // ,%%%%%%%%, // ,%%/\%%%%/\%% // ,%%%\c "" J/%%% // %. %%%%/ o o \%%% // `%%. %%%% _ |%%% // `%% `%%%%(__Y__)%%' // // ;%%%%`\-/%%%' // (( / `%%%%%%%' // \\ .' | // \\ / \ | | // \\/攻城狮保佑) | | // \ /_ | |__ // (___________))))))) `\/' /* * 修订记录: * long.qian@msxf.com 2017-08-04 14:08 创建 */ /** * @author long.qian@msxf.com */ public class HexUtil { private static boolean isCnSymbol(char ch) { if (0x3004 <= ch && ch <= 0x301C) return true; if (0x3020 <= ch && ch <= 0x303F) return true; return false; } private static boolean isEnSymbol(char ch){ if (ch == 0x40) return true; if (ch == 0x2D || ch == 0x2F) return true; if (0x23 <= ch && ch <= 0x26) return true; if (0x28 <= ch && ch <= 0x2B) return true; if (0x3C <= ch && ch <= 0x3E) return true; if (0x5B <= ch && ch <= 0x60) return true; if (0x7B <= ch && ch <= 0x7E) return true; return false; } private static boolean isPunctuation(char ch){ if(isCjkPunc(ch)) return true; if(isEnPunc(ch)) return true; if(0x2018 <= ch && ch <= 0x201F) return true; if(ch == 0xFF01 || ch == 0xFF02) return true; if(ch == 0xFF07 || ch == 0xFF0C) return true; if(ch == 0xFF1A || ch == 0xFF1B) return true; if(ch == 0xFF1F || ch == 0xFF61) return true; if(ch == 0xFF0E) return true; if(ch == 0xFF65) return true; return false; } private static boolean isEnPunc(char ch){ if (0x21 <= ch && ch <= 0x22) return true; if (ch == 0x27 || ch == 0x2C) return true; if (ch == 0x2E || ch == 0x3A) return true; if (ch == 0x3B || ch == 0x3F) return true; return false; } private static boolean isCjkPunc(char ch){ if (0x3001 <= ch && ch <= 0x3003) return true; if (0x301D <= ch && ch <= 0x301F) return true; return false; } private static boolean isSymbol(char ch) { if(isCnSymbol(ch)) return true; if(isEnSymbol(ch))return true; if(0x2010 <= ch && ch <= 0x2017) return true; if(0x2020 <= ch && ch <= 0x2027) return true; if(0x2B00 <= ch && ch <= 0x2BFF) return true; if(0xFF03 <= ch && ch <= 0xFF06) return true; if(0xFF08 <= ch && ch <= 0xFF0B) return true; if(ch == 0xFF0D || ch == 0xFF0F) return true; if(0xFF1C <= ch && ch <= 0xFF1E) return true; if(ch == 0xFF20 || ch == 0xFF65) return true; if(0xFF3B <= ch && ch <= 0xFF40) return true; if(0xFF5B <= ch && ch <= 0xFF60) return true; if(ch == 0xFF62 || ch == 0xFF63) return true; if(ch == 0x0020 || ch == 0x3000) return true; return false; } /** * 过滤字符串,返回可见字符形式(数字、字母、符号等) * @param str * @return */ public static String filter(String str){ StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") || isSymbol(c) || isPunctuation(c)){ sb.append(c); } } return sb.toString(); } /** * 过滤字符串,将不可见字符串替换为指定的字符串 * @param str * @param replace * @return */ public static String filter(String str,String replace){ StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") || isSymbol(c) || isPunctuation(c)){ sb.append(c); }else { sb.append(replace); } } return sb.toString(); } }
DevopsJK/SuitAgent
src/main/java/com/falcon/suitagent/util/HexUtil.java
1,432
/* * 修订记录: * long.qian@msxf.com 2017-08-04 14:08 创建 */
block_comment
zh-cn
/* * www.msxf.com Inc. * Copyright (c) 2017 All Rights Reserved */ package com.falcon.suitagent.util; // ,%%%%%%%%, // ,%%/\%%%%/\%% // ,%%%\c "" J/%%% // %. %%%%/ o o \%%% // `%%. %%%% _ |%%% // `%% `%%%%(__Y__)%%' // // ;%%%%`\-/%%%' // (( / `%%%%%%%' // \\ .' | // \\ / \ | | // \\/攻城狮保佑) | | // \ /_ | |__ // (___________))))))) `\/' /* * 修订记 <SUF>*/ /** * @author long.qian@msxf.com */ public class HexUtil { private static boolean isCnSymbol(char ch) { if (0x3004 <= ch && ch <= 0x301C) return true; if (0x3020 <= ch && ch <= 0x303F) return true; return false; } private static boolean isEnSymbol(char ch){ if (ch == 0x40) return true; if (ch == 0x2D || ch == 0x2F) return true; if (0x23 <= ch && ch <= 0x26) return true; if (0x28 <= ch && ch <= 0x2B) return true; if (0x3C <= ch && ch <= 0x3E) return true; if (0x5B <= ch && ch <= 0x60) return true; if (0x7B <= ch && ch <= 0x7E) return true; return false; } private static boolean isPunctuation(char ch){ if(isCjkPunc(ch)) return true; if(isEnPunc(ch)) return true; if(0x2018 <= ch && ch <= 0x201F) return true; if(ch == 0xFF01 || ch == 0xFF02) return true; if(ch == 0xFF07 || ch == 0xFF0C) return true; if(ch == 0xFF1A || ch == 0xFF1B) return true; if(ch == 0xFF1F || ch == 0xFF61) return true; if(ch == 0xFF0E) return true; if(ch == 0xFF65) return true; return false; } private static boolean isEnPunc(char ch){ if (0x21 <= ch && ch <= 0x22) return true; if (ch == 0x27 || ch == 0x2C) return true; if (ch == 0x2E || ch == 0x3A) return true; if (ch == 0x3B || ch == 0x3F) return true; return false; } private static boolean isCjkPunc(char ch){ if (0x3001 <= ch && ch <= 0x3003) return true; if (0x301D <= ch && ch <= 0x301F) return true; return false; } private static boolean isSymbol(char ch) { if(isCnSymbol(ch)) return true; if(isEnSymbol(ch))return true; if(0x2010 <= ch && ch <= 0x2017) return true; if(0x2020 <= ch && ch <= 0x2027) return true; if(0x2B00 <= ch && ch <= 0x2BFF) return true; if(0xFF03 <= ch && ch <= 0xFF06) return true; if(0xFF08 <= ch && ch <= 0xFF0B) return true; if(ch == 0xFF0D || ch == 0xFF0F) return true; if(0xFF1C <= ch && ch <= 0xFF1E) return true; if(ch == 0xFF20 || ch == 0xFF65) return true; if(0xFF3B <= ch && ch <= 0xFF40) return true; if(0xFF5B <= ch && ch <= 0xFF60) return true; if(ch == 0xFF62 || ch == 0xFF63) return true; if(ch == 0x0020 || ch == 0x3000) return true; return false; } /** * 过滤字符串,返回可见字符形式(数字、字母、符号等) * @param str * @return */ public static String filter(String str){ StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") || isSymbol(c) || isPunctuation(c)){ sb.append(c); } } return sb.toString(); } /** * 过滤字符串,将不可见字符串替换为指定的字符串 * @param str * @param replace * @return */ public static String filter(String str,String replace){ StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") || isSymbol(c) || isPunctuation(c)){ sb.append(c); }else { sb.append(replace); } } return sb.toString(); } }
0
1,355
34
1,432
39
1,504
37
1,432
39
1,635
44
false
false
false
false
false
true
13819_1
/** * @author liuhuanhuan * @version 1.0 * @date 2022/2/21 22:33 * @describe Twitter推出的分布式唯一id算法 */ public class UUIDUtil { //因为二进制里第一个 bit 为如果是 1,那么都是负数,但是我们生成的 id 都是正数,所以第一个 bit 统一都是 0。 //机器ID 2进制5位 32位减掉1位 31个 private long workerId; //机房ID 2进制5位 32位减掉1位 31个 private long datacenterId; //代表一毫秒内生成的多个id的最新序号 12位 4096 -1 = 4095 个 private long sequence; //设置一个时间初始值 2^41 - 1 差不多可以用69年 private long twepoch = 1585644268888L; //5位的机器id private long workerIdBits = 5L; //5位的机房id;。‘ private long datacenterIdBits = 5L; //每毫秒内产生的id数 2 的 12次方 private long sequenceBits = 12L; // 这个是二进制运算,就是5 bit最多只能有31个数字,也就是说机器id最多只能是32以内 private long maxWorkerId = -1L ^ (-1L << workerIdBits); // 这个是一个意思,就是5 bit最多只能有31个数字,机房id最多只能是32以内 private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); private long workerIdShift = sequenceBits; private long datacenterIdShift = sequenceBits + workerIdBits; private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // -1L 二进制就是1111 1111 为什么? // -1 左移12位就是 1111 1111 0000 0000 0000 0000 // 异或 相同为0 ,不同为1 // 1111 1111 0000 0000 0000 0000 // ^ // 1111 1111 1111 1111 1111 1111 // 0000 0000 1111 1111 1111 1111 换算成10进制就是4095 private long sequenceMask = -1L ^ (-1L << sequenceBits); //记录产生时间毫秒数,判断是否是同1毫秒 private long lastTimestamp = -1L; public long getWorkerId(){ return workerId; } public long getDatacenterId() { return datacenterId; } public long getTimestamp() { return System.currentTimeMillis(); } public UUIDUtil() { } public UUIDUtil(long workerId, long datacenterId, long sequence) { // 检查机房id和机器id是否超过31 不能小于0 if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException( String.format("worker Id can't be greater than %d or less than 0",maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException( String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; this.sequence = sequence; } // 这个是核心方法,通过调用nextId()方法, // 让当前这台机器上的snowflake算法程序生成一个全局唯一的id public synchronized long nextId() { // 这儿就是获取当前时间戳,单位是毫秒 long timestamp = timeGen(); // 判断是否小于上次时间戳,如果小于的话,就抛出异常 if (timestamp < lastTimestamp) { System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp); throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } // 下面是说假设在同一个毫秒内,又发送了一个请求生成一个id // 这个时候就得把seqence序号给递增1,最多就是4096 if (timestamp == lastTimestamp) { // 这个意思是说一个毫秒内最多只能有4096个数字,无论你传递多少进来, //这个位运算保证始终就是在4096这个范围内,避免你自己传递个sequence超过了4096这个范围 sequence = (sequence + 1) & sequenceMask; //当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0; } // 这儿记录一下最近一次生成id的时间戳,单位是毫秒 lastTimestamp = timestamp; // 这儿就是最核心的二进制位运算操作,生成一个64bit的id // 先将当前时间戳左移,放到41 bit那儿;将机房id左移放到5 bit那儿;将机器id左移放到5 bit那儿;将序号放最后12 bit // 最后拼接起来成一个64 bit的二进制数字,转换成10进制就是个long型 return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; } /** * 当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID * @param lastTimestamp * @return */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } //获取当前时间戳 private long timeGen(){ return System.currentTimeMillis(); } /** * main 测试类 * @param args */ public static void main(String[] args) { // System.out.println(1&4596); // System.out.println(2&4596); // System.out.println(6&4596); // System.out.println(6&4596); // System.out.println(6&4596); // System.out.println(6&4596); UUIDUtil snowFlow = new UUIDUtil(1, 1, 1); for (int i = 0; i < 22; i++) { System.out.println(snowFlow.nextId()); // } } } }
Dexter-Huang/mycode
Algorithm/src/main/java/UUIDUtil.java
1,738
//因为二进制里第一个 bit 为如果是 1,那么都是负数,但是我们生成的 id 都是正数,所以第一个 bit 统一都是 0。
line_comment
zh-cn
/** * @author liuhuanhuan * @version 1.0 * @date 2022/2/21 22:33 * @describe Twitter推出的分布式唯一id算法 */ public class UUIDUtil { //因为 <SUF> //机器ID 2进制5位 32位减掉1位 31个 private long workerId; //机房ID 2进制5位 32位减掉1位 31个 private long datacenterId; //代表一毫秒内生成的多个id的最新序号 12位 4096 -1 = 4095 个 private long sequence; //设置一个时间初始值 2^41 - 1 差不多可以用69年 private long twepoch = 1585644268888L; //5位的机器id private long workerIdBits = 5L; //5位的机房id;。‘ private long datacenterIdBits = 5L; //每毫秒内产生的id数 2 的 12次方 private long sequenceBits = 12L; // 这个是二进制运算,就是5 bit最多只能有31个数字,也就是说机器id最多只能是32以内 private long maxWorkerId = -1L ^ (-1L << workerIdBits); // 这个是一个意思,就是5 bit最多只能有31个数字,机房id最多只能是32以内 private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); private long workerIdShift = sequenceBits; private long datacenterIdShift = sequenceBits + workerIdBits; private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // -1L 二进制就是1111 1111 为什么? // -1 左移12位就是 1111 1111 0000 0000 0000 0000 // 异或 相同为0 ,不同为1 // 1111 1111 0000 0000 0000 0000 // ^ // 1111 1111 1111 1111 1111 1111 // 0000 0000 1111 1111 1111 1111 换算成10进制就是4095 private long sequenceMask = -1L ^ (-1L << sequenceBits); //记录产生时间毫秒数,判断是否是同1毫秒 private long lastTimestamp = -1L; public long getWorkerId(){ return workerId; } public long getDatacenterId() { return datacenterId; } public long getTimestamp() { return System.currentTimeMillis(); } public UUIDUtil() { } public UUIDUtil(long workerId, long datacenterId, long sequence) { // 检查机房id和机器id是否超过31 不能小于0 if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException( String.format("worker Id can't be greater than %d or less than 0",maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException( String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; this.sequence = sequence; } // 这个是核心方法,通过调用nextId()方法, // 让当前这台机器上的snowflake算法程序生成一个全局唯一的id public synchronized long nextId() { // 这儿就是获取当前时间戳,单位是毫秒 long timestamp = timeGen(); // 判断是否小于上次时间戳,如果小于的话,就抛出异常 if (timestamp < lastTimestamp) { System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp); throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } // 下面是说假设在同一个毫秒内,又发送了一个请求生成一个id // 这个时候就得把seqence序号给递增1,最多就是4096 if (timestamp == lastTimestamp) { // 这个意思是说一个毫秒内最多只能有4096个数字,无论你传递多少进来, //这个位运算保证始终就是在4096这个范围内,避免你自己传递个sequence超过了4096这个范围 sequence = (sequence + 1) & sequenceMask; //当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0; } // 这儿记录一下最近一次生成id的时间戳,单位是毫秒 lastTimestamp = timestamp; // 这儿就是最核心的二进制位运算操作,生成一个64bit的id // 先将当前时间戳左移,放到41 bit那儿;将机房id左移放到5 bit那儿;将机器id左移放到5 bit那儿;将序号放最后12 bit // 最后拼接起来成一个64 bit的二进制数字,转换成10进制就是个long型 return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; } /** * 当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID * @param lastTimestamp * @return */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } //获取当前时间戳 private long timeGen(){ return System.currentTimeMillis(); } /** * main 测试类 * @param args */ public static void main(String[] args) { // System.out.println(1&4596); // System.out.println(2&4596); // System.out.println(6&4596); // System.out.println(6&4596); // System.out.println(6&4596); // System.out.println(6&4596); UUIDUtil snowFlow = new UUIDUtil(1, 1, 1); for (int i = 0; i < 22; i++) { System.out.println(snowFlow.nextId()); // } } } }
0
1,704
40
1,738
37
1,770
35
1,738
37
2,252
58
false
false
false
false
false
true
34427_19
package util; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.UUID; import android.util.Log; public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * Android上传文件到服务端 * * @param file * 需要上传的文件 * @param RequestURL * 请求的rul * @return 返回响应的内容 */ public static String uploadFile(File file, String RequestURL) { String result = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); Log.e(TAG, "response code:" + res); // if(res==200) // { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); // } // else{ // Log.e(TAG, "request error"); // } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param url * Service net address * @param params * text content * @param files * pictures * @return String result of Service response * @throws IOException */ public static String post(String url, Map<String, String> params, Map<String, File> files) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(url); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(10 * 1000); // 缓存的最长时间 conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许输出 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // 首先组拼文本类型的参数 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream( conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // 发送文件数据 if (files != null) for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); Log.i("http", LINEND); } // 请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到响应码 int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sb2 = new StringBuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sb2.append((char) ch); } } outStream.close(); conn.disconnect(); return sb2.toString(); } }
DickyQie/android-picture-upload
src/util/UploadUtil.java
1,933
// 允许输出
line_comment
zh-cn
package util; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.UUID; import android.util.Log; public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * Android上传文件到服务端 * * @param file * 需要上传的文件 * @param RequestURL * 请求的rul * @return 返回响应的内容 */ public static String uploadFile(File file, String RequestURL) { String result = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); Log.e(TAG, "response code:" + res); // if(res==200) // { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); // } // else{ // Log.e(TAG, "request error"); // } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param url * Service net address * @param params * text content * @param files * pictures * @return String result of Service response * @throws IOException */ public static String post(String url, Map<String, String> params, Map<String, File> files) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(url); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(10 * 1000); // 缓存的最长时间 conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许 <SUF> conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // 首先组拼文本类型的参数 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream( conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // 发送文件数据 if (files != null) for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); Log.i("http", LINEND); } // 请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到响应码 int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sb2 = new StringBuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sb2.append((char) ch); } } outStream.close(); conn.disconnect(); return sb2.toString(); } }
0
1,667
5
1,933
4
1,929
4
1,933
4
2,609
10
false
false
false
false
false
true
28596_3
package com.zhangqie.videosummary.widget; import android.content.Context; import android.media.MediaPlayer; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; import java.io.IOException; /** * Created by zhangqie on 2019/8/29 * Describe: */ public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener { private SurfaceHolder holder; private MediaPlayer mediaPlayer; public MySurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); }//快进 public void setprogress(int progress) { int currentPosition = mediaPlayer.getCurrentPosition(); mediaPlayer.seekTo(currentPosition + progress); Toast.makeText(getContext(), "快进" + progress, Toast.LENGTH_SHORT).show(); } //暂停/播放方法 public void stopVideo() { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); } else { mediaPlayer.start(); } } //播放视频方法 public void playVideo(String path) { if (mediaPlayer == null) { mediaPlayer = new MediaPlayer();//设置surfaceview不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前 mediaPlayer.setOnCompletionListener(this); } try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.setDisplay(holder); mediaPlayer.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } private void init() { holder = this.getHolder(); //重写SurfaceHolder.Callback方法 holder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; } }//缓冲完成播放 @Override public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.start(); } }
DickyQie/android-video
app/src/main/java/com/zhangqie/videosummary/widget/MySurfaceView.java
537
//设置surfaceview不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前
line_comment
zh-cn
package com.zhangqie.videosummary.widget; import android.content.Context; import android.media.MediaPlayer; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; import java.io.IOException; /** * Created by zhangqie on 2019/8/29 * Describe: */ public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener { private SurfaceHolder holder; private MediaPlayer mediaPlayer; public MySurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); }//快进 public void setprogress(int progress) { int currentPosition = mediaPlayer.getCurrentPosition(); mediaPlayer.seekTo(currentPosition + progress); Toast.makeText(getContext(), "快进" + progress, Toast.LENGTH_SHORT).show(); } //暂停/播放方法 public void stopVideo() { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); } else { mediaPlayer.start(); } } //播放视频方法 public void playVideo(String path) { if (mediaPlayer == null) { mediaPlayer = new MediaPlayer();//设置 <SUF> mediaPlayer.setOnCompletionListener(this); } try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.setDisplay(holder); mediaPlayer.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } private void init() { holder = this.getHolder(); //重写SurfaceHolder.Callback方法 holder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; } }//缓冲完成播放 @Override public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.start(); } }
0
454
22
537
29
553
22
537
29
692
61
false
false
false
false
false
true
30972_0
package MeaT; import JDBC.JDBCUtils; import blockchain.Block; import blockchain.Transaction; import dataset.DataProcessing; import functions.MeaTUtils; import graph.Edge; import graph.Node; import merkletree.Leaf; import merkletree.MerkleTree; import javax.xml.crypto.dsig.TransformService; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class CreateMeaT { public Random ran=new Random(); public ArrayList<Transaction> txs=new ArrayList<>(); public ArrayList<Block> blocks=new ArrayList<>(); public String[] types={"food","electronic","face","furniture"}; public ArrayList<Node> all_nodes=new ArrayList<>(); public void create_nodes(){ int i=0; for (i=0;i<15;i++) { String id=String.valueOf(i); String type=types[ran.nextInt(4)]; Node node=new Node(id,type); all_nodes.add(node); System.out.println(node.getNode_id()); } } public void create_txs_blocks(ArrayList<Node> nodes){ int block_id=1; String[] types={"Electronic","Food","Furniture"}; for (int i=0;i<5;i++) { String blockid=String.valueOf(block_id); Block b=new Block(blockid); for(int j=0;j<20;j++) { String tx_id_string=String.valueOf(j); String tx_id=tx_id_string; String tx_time_cost=String.valueOf(ran.nextDouble()*150); String tx_repu=String.valueOf(ran.nextDouble()*100); int firstNumber = ran.nextInt(15); // 生成0到3之间的随机数 int secondNumber; do { secondNumber = ran.nextInt(15); } while (secondNumber == firstNumber); Node node1=nodes.get(firstNumber); Node node2=nodes.get(secondNumber); String tx_timestamp=String.valueOf(block_id); int type=ran.nextInt(3); Transaction tx=new Transaction(tx_id,tx_timestamp,tx_time_cost,tx_repu,node1,node2,types[type]); tx.setBlock(b); txs.add(tx); System.out.println("TX:"+tx.getType()); b.getTxs().add(tx); } block_id+=1; blocks.add(b); System.out.println("Block:"+b.getId()); System.out.println("Amounts:"+b.getTxs().size()); } } public Block query_block(String id, ArrayList<Block> blocks) { for (Block block:blocks) { if (block.getId().equals(id)) { return block; } } return null; } public boolean exist_block(String id, ArrayList<Block> blocks) { for (Block block:blocks) { if (block.getId().equals(id)) { return true; } } return false; } public Node query_node(String id, ArrayList<Node> nodes) { for (Node node:nodes) { if (node.getNode_id().equals(id)) { return node; } } return null; } public static void main(String[] args) throws NoSuchAlgorithmException, SQLException { String file="./Dataset/100000.csv"; HashMap<Node,ArrayList<Transaction>> node_txs=new HashMap<>(); JDBCUtils jdbcUtils=new JDBCUtils(); DataProcessing dp=new DataProcessing(); CreateMeaT cmt=new CreateMeaT(); //将交易、节点、区块写入数据库并暂存至内存 node_txs=dp.test_dataset_to_txs(file); for(Node node:node_txs.keySet()) { dp.insert_transaction_database(node_txs.get(node)); cmt.all_nodes.add(node); cmt.txs.addAll(node_txs.get(node)); } // //miniminitest的操作,一个区块,将所有交易加到这个区块中 // cmt.blocks.add(cmt.txs.get(0).getBlock()); // for (Transaction tx: cmt.txs){ // cmt.blocks.get(0).getTxs().add(tx); // } //交易、节点存完了,直接读就可以 //将数据库中的交易和节点读出来 ResultSet rs = dp.select_transaction(); ResultSet rs2=dp.select_node(); ResultSet rs3=dp.select_block(); while(rs2.next()) { Node node=new Node(rs2.getString("node_id")); cmt.all_nodes.add(node); } while(rs3.next()) { Block block=new Block(rs3.getString("block_id")); cmt.blocks.add(block); } System.out.println("All blocks: "+cmt.blocks.size()); System.out.println("All nodes: "+cmt.all_nodes.size()); Node start_node=null; Node end_node = new Node(""); // 创建一个空的Node对象,用于重复使用 while (rs.next()) { Transaction tx=null; start_node = cmt.query_node(rs.getString("start_node"), cmt.all_nodes); // 重复使用end_node对象,而不是在每次迭代中创建新对象 end_node.setNode_id(rs.getString("end_node")); Block b=cmt.query_block(rs.getString("block"),cmt.blocks); // 重复使用tx对象,而不是在每次迭代中创建新对象 if (tx == null) { tx = new Transaction("", "", "", "", null, null, ""); } // 更新tx对象的属性 tx.setId(rs.getString("id")); tx.setTimestamp(rs.getString("timestamp")); tx.setTime_cost(rs.getString("time_cost")); tx.setReputation(rs.getString("reputation")); tx.setStart_node(start_node); tx.setEnd_node(end_node); tx.setType(rs.getString("type")); tx.setBlock(b); cmt.txs.add(tx); System.out.println("Pre tx: " + rs.getString("id")); b.getTxs().add(tx); } System.out.println("Total blocks: "+cmt.blocks.size()); //Merkle树的 int leafcount=0; for (Block block: cmt.blocks) { ArrayList<Transaction> transactions=block.getTxs(); ArrayList<Leaf> leaves=new ArrayList<>(); for(Transaction tx: transactions) { Leaf leaf=Leaf.tx_to_leaf(tx); leaf.setId(String.valueOf(leafcount)); leaves.add(leaf); leafcount+=1; } System.out.println("Block "+block.getId()+" has "+leaves.size()+" leaves"); MerkleTree mt=MerkleTree.create_Merkletree(leaves); } //开始创建整体的graphmerkle树架构 System.out.println("------------------------------ Stage 1----------------------------"); System.out.println("------------------------------Lower MGT----------------------------"); //首先,按照起始节点的不同,将交易过滤为edge并分类(在MeaTUtils类中) int gnlItemcount=0; //MerkleGraphTree的 for (Block block: cmt.blocks) { HashMap<Node,ArrayList<Edge>> all_transactions=new HashMap<>(); all_transactions=MeaTUtils.start_node_filter(block.getTxs()); System.out.println("This block has "+block.getTxs().size()+" transactions"); //之后,对不同的节点构建多个下层MGT树 GraphNodeLink gnl=new GraphNodeLink(); int mgtleafcount=0; for(Node node: all_transactions.keySet()) { System.out.println("Pre Node id: "+node.getNode_id()); GraphNodeLinkItem gnlItem=new GraphNodeLinkItem(); ArrayList<Edge> edges=all_transactions.get(node); ArrayList<GraphLeaf> leaves=new ArrayList<>(); for(Edge e: edges){ GraphLeaf graphLeaf=GraphLeaf.edge_to_leaf(e); graphLeaf.setId(String.valueOf(mgtleafcount)); leaves.add(graphLeaf); mgtleafcount+=1; } MerkleGraphTree lower_mgt=MerkleGraphTree.create_Merkletree(leaves); gnlItem.addMGTs(lower_mgt); gnlItem.setPre_node(node); gnlItem.setId(String.valueOf(gnlItemcount)); gnlItemcount+=1; //将gnlItem写入数据库 Connection gnlCoon= jdbcUtils.connect_database(); String gnlSql="insert into graphnodelink (start_node,mgtroot_hashvalue,gnlitem_id) value (?,?,?)"; PreparedStatement ps=gnlCoon.prepareStatement(gnlSql); ps.setString(1,gnlItem.getPre_node().getNode_id()); ps.setString(2,lower_mgt.getHash_value().toString()); ps.setString(3,String.valueOf(gnlItemcount)); ps.executeUpdate(); try { if (null != ps) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (null != gnlCoon) { gnlCoon.close(); } } catch (SQLException e) { e.printStackTrace(); } //GNL中加入item gnl.addLink(lower_mgt); } System.out.println("GNL also has been created. It has "+gnl.getItems().size()+" items now."); System.out.println("------------------------------ Stage 2- -----------------------"); System.out.println("------------------------------Upper MGT--------------------------"); //接着,构建上层的MGT树 MerkleGraphTree upper_mgt=gnl.create_upper_MGT(gnl,block); System.out.println("Now the upper MGT has been created, the root is "+block.getRoot()+", and the hash is "+block.getHashroot()); System.out.println("-------------------------------Stage 3---------------------------"); System.out.println("------------------------------PST Tree---------------------------"); //最后,构建PST树 PropertySemanticTrie pst=new PropertySemanticTrie(); String[] filter={"type","time_cost","reputation"}; pst.create_PST(block.getRoot(),cmt.txs, filter, 3); } } }
Dignity556/MerkleTree0111
src/MeaT/CreateMeaT.java
2,606
// 生成0到3之间的随机数
line_comment
zh-cn
package MeaT; import JDBC.JDBCUtils; import blockchain.Block; import blockchain.Transaction; import dataset.DataProcessing; import functions.MeaTUtils; import graph.Edge; import graph.Node; import merkletree.Leaf; import merkletree.MerkleTree; import javax.xml.crypto.dsig.TransformService; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class CreateMeaT { public Random ran=new Random(); public ArrayList<Transaction> txs=new ArrayList<>(); public ArrayList<Block> blocks=new ArrayList<>(); public String[] types={"food","electronic","face","furniture"}; public ArrayList<Node> all_nodes=new ArrayList<>(); public void create_nodes(){ int i=0; for (i=0;i<15;i++) { String id=String.valueOf(i); String type=types[ran.nextInt(4)]; Node node=new Node(id,type); all_nodes.add(node); System.out.println(node.getNode_id()); } } public void create_txs_blocks(ArrayList<Node> nodes){ int block_id=1; String[] types={"Electronic","Food","Furniture"}; for (int i=0;i<5;i++) { String blockid=String.valueOf(block_id); Block b=new Block(blockid); for(int j=0;j<20;j++) { String tx_id_string=String.valueOf(j); String tx_id=tx_id_string; String tx_time_cost=String.valueOf(ran.nextDouble()*150); String tx_repu=String.valueOf(ran.nextDouble()*100); int firstNumber = ran.nextInt(15); // 生成 <SUF> int secondNumber; do { secondNumber = ran.nextInt(15); } while (secondNumber == firstNumber); Node node1=nodes.get(firstNumber); Node node2=nodes.get(secondNumber); String tx_timestamp=String.valueOf(block_id); int type=ran.nextInt(3); Transaction tx=new Transaction(tx_id,tx_timestamp,tx_time_cost,tx_repu,node1,node2,types[type]); tx.setBlock(b); txs.add(tx); System.out.println("TX:"+tx.getType()); b.getTxs().add(tx); } block_id+=1; blocks.add(b); System.out.println("Block:"+b.getId()); System.out.println("Amounts:"+b.getTxs().size()); } } public Block query_block(String id, ArrayList<Block> blocks) { for (Block block:blocks) { if (block.getId().equals(id)) { return block; } } return null; } public boolean exist_block(String id, ArrayList<Block> blocks) { for (Block block:blocks) { if (block.getId().equals(id)) { return true; } } return false; } public Node query_node(String id, ArrayList<Node> nodes) { for (Node node:nodes) { if (node.getNode_id().equals(id)) { return node; } } return null; } public static void main(String[] args) throws NoSuchAlgorithmException, SQLException { String file="./Dataset/100000.csv"; HashMap<Node,ArrayList<Transaction>> node_txs=new HashMap<>(); JDBCUtils jdbcUtils=new JDBCUtils(); DataProcessing dp=new DataProcessing(); CreateMeaT cmt=new CreateMeaT(); //将交易、节点、区块写入数据库并暂存至内存 node_txs=dp.test_dataset_to_txs(file); for(Node node:node_txs.keySet()) { dp.insert_transaction_database(node_txs.get(node)); cmt.all_nodes.add(node); cmt.txs.addAll(node_txs.get(node)); } // //miniminitest的操作,一个区块,将所有交易加到这个区块中 // cmt.blocks.add(cmt.txs.get(0).getBlock()); // for (Transaction tx: cmt.txs){ // cmt.blocks.get(0).getTxs().add(tx); // } //交易、节点存完了,直接读就可以 //将数据库中的交易和节点读出来 ResultSet rs = dp.select_transaction(); ResultSet rs2=dp.select_node(); ResultSet rs3=dp.select_block(); while(rs2.next()) { Node node=new Node(rs2.getString("node_id")); cmt.all_nodes.add(node); } while(rs3.next()) { Block block=new Block(rs3.getString("block_id")); cmt.blocks.add(block); } System.out.println("All blocks: "+cmt.blocks.size()); System.out.println("All nodes: "+cmt.all_nodes.size()); Node start_node=null; Node end_node = new Node(""); // 创建一个空的Node对象,用于重复使用 while (rs.next()) { Transaction tx=null; start_node = cmt.query_node(rs.getString("start_node"), cmt.all_nodes); // 重复使用end_node对象,而不是在每次迭代中创建新对象 end_node.setNode_id(rs.getString("end_node")); Block b=cmt.query_block(rs.getString("block"),cmt.blocks); // 重复使用tx对象,而不是在每次迭代中创建新对象 if (tx == null) { tx = new Transaction("", "", "", "", null, null, ""); } // 更新tx对象的属性 tx.setId(rs.getString("id")); tx.setTimestamp(rs.getString("timestamp")); tx.setTime_cost(rs.getString("time_cost")); tx.setReputation(rs.getString("reputation")); tx.setStart_node(start_node); tx.setEnd_node(end_node); tx.setType(rs.getString("type")); tx.setBlock(b); cmt.txs.add(tx); System.out.println("Pre tx: " + rs.getString("id")); b.getTxs().add(tx); } System.out.println("Total blocks: "+cmt.blocks.size()); //Merkle树的 int leafcount=0; for (Block block: cmt.blocks) { ArrayList<Transaction> transactions=block.getTxs(); ArrayList<Leaf> leaves=new ArrayList<>(); for(Transaction tx: transactions) { Leaf leaf=Leaf.tx_to_leaf(tx); leaf.setId(String.valueOf(leafcount)); leaves.add(leaf); leafcount+=1; } System.out.println("Block "+block.getId()+" has "+leaves.size()+" leaves"); MerkleTree mt=MerkleTree.create_Merkletree(leaves); } //开始创建整体的graphmerkle树架构 System.out.println("------------------------------ Stage 1----------------------------"); System.out.println("------------------------------Lower MGT----------------------------"); //首先,按照起始节点的不同,将交易过滤为edge并分类(在MeaTUtils类中) int gnlItemcount=0; //MerkleGraphTree的 for (Block block: cmt.blocks) { HashMap<Node,ArrayList<Edge>> all_transactions=new HashMap<>(); all_transactions=MeaTUtils.start_node_filter(block.getTxs()); System.out.println("This block has "+block.getTxs().size()+" transactions"); //之后,对不同的节点构建多个下层MGT树 GraphNodeLink gnl=new GraphNodeLink(); int mgtleafcount=0; for(Node node: all_transactions.keySet()) { System.out.println("Pre Node id: "+node.getNode_id()); GraphNodeLinkItem gnlItem=new GraphNodeLinkItem(); ArrayList<Edge> edges=all_transactions.get(node); ArrayList<GraphLeaf> leaves=new ArrayList<>(); for(Edge e: edges){ GraphLeaf graphLeaf=GraphLeaf.edge_to_leaf(e); graphLeaf.setId(String.valueOf(mgtleafcount)); leaves.add(graphLeaf); mgtleafcount+=1; } MerkleGraphTree lower_mgt=MerkleGraphTree.create_Merkletree(leaves); gnlItem.addMGTs(lower_mgt); gnlItem.setPre_node(node); gnlItem.setId(String.valueOf(gnlItemcount)); gnlItemcount+=1; //将gnlItem写入数据库 Connection gnlCoon= jdbcUtils.connect_database(); String gnlSql="insert into graphnodelink (start_node,mgtroot_hashvalue,gnlitem_id) value (?,?,?)"; PreparedStatement ps=gnlCoon.prepareStatement(gnlSql); ps.setString(1,gnlItem.getPre_node().getNode_id()); ps.setString(2,lower_mgt.getHash_value().toString()); ps.setString(3,String.valueOf(gnlItemcount)); ps.executeUpdate(); try { if (null != ps) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (null != gnlCoon) { gnlCoon.close(); } } catch (SQLException e) { e.printStackTrace(); } //GNL中加入item gnl.addLink(lower_mgt); } System.out.println("GNL also has been created. It has "+gnl.getItems().size()+" items now."); System.out.println("------------------------------ Stage 2- -----------------------"); System.out.println("------------------------------Upper MGT--------------------------"); //接着,构建上层的MGT树 MerkleGraphTree upper_mgt=gnl.create_upper_MGT(gnl,block); System.out.println("Now the upper MGT has been created, the root is "+block.getRoot()+", and the hash is "+block.getHashroot()); System.out.println("-------------------------------Stage 3---------------------------"); System.out.println("------------------------------PST Tree---------------------------"); //最后,构建PST树 PropertySemanticTrie pst=new PropertySemanticTrie(); String[] filter={"type","time_cost","reputation"}; pst.create_PST(block.getRoot(),cmt.txs, filter, 3); } } }
0
2,193
9
2,606
8
2,790
8
2,606
8
3,166
15
false
false
false
false
false
true
21688_2
package design20_备忘录模式.sample_2; //相当于Originator, public class Game { private int checkPoint = 1;//游戏第一关 private int lifeValue = 100;//刚开始血量满满 private String weapon = "匕首";//武器 //开始游戏 public void play(){ System.out.println("开始游戏:"+String.format("第%d关",checkPoint)+" fighting!! ︻$▅▆▇◤"); lifeValue -= 10; System.out.println("闯关成功"); checkPoint++; System.out.println("到达"+String.format("第%d关",checkPoint)); } //退出游戏 public void quit(){ System.out.println(". . . . . ."); System.out.println(this.toString()+"\n退出游戏"); } //创建备忘录 public Memoto createMemoto(){ Memoto memoto = new Memoto(); memoto.setCheckPoint(this.checkPoint); memoto.setLifeValue(lifeValue); memoto.setWeapon(weapon); return memoto; } //恢复游戏 public void restore(Memoto memoto){ this.checkPoint = memoto.getCheckPoint(); this.lifeValue = memoto.getLifeValue(); this.weapon = memoto.getWeapon(); System.out.println("恢复后的游戏状态:"+this.toString()); } @Override public String toString() { return "当前游戏关数:"+checkPoint+" 血量:"+lifeValue+" 武器:"+weapon; } }
DingMouRen/DesignPattern
src/design20_备忘录模式/sample_2/Game.java
387
//刚开始血量满满
line_comment
zh-cn
package design20_备忘录模式.sample_2; //相当于Originator, public class Game { private int checkPoint = 1;//游戏第一关 private int lifeValue = 100;//刚开 <SUF> private String weapon = "匕首";//武器 //开始游戏 public void play(){ System.out.println("开始游戏:"+String.format("第%d关",checkPoint)+" fighting!! ︻$▅▆▇◤"); lifeValue -= 10; System.out.println("闯关成功"); checkPoint++; System.out.println("到达"+String.format("第%d关",checkPoint)); } //退出游戏 public void quit(){ System.out.println(". . . . . ."); System.out.println(this.toString()+"\n退出游戏"); } //创建备忘录 public Memoto createMemoto(){ Memoto memoto = new Memoto(); memoto.setCheckPoint(this.checkPoint); memoto.setLifeValue(lifeValue); memoto.setWeapon(weapon); return memoto; } //恢复游戏 public void restore(Memoto memoto){ this.checkPoint = memoto.getCheckPoint(); this.lifeValue = memoto.getLifeValue(); this.weapon = memoto.getWeapon(); System.out.println("恢复后的游戏状态:"+this.toString()); } @Override public String toString() { return "当前游戏关数:"+checkPoint+" 血量:"+lifeValue+" 武器:"+weapon; } }
0
337
5
387
8
402
6
387
8
520
16
false
false
false
false
false
true
15017_3
package com.ding.makeup.beauty; import android.graphics.Bitmap; import android.graphics.Point; import com.ding.makeup.utils.TimeAopUtils; /** * @author by dingdegao * time 2017/9/29 16:03 * function: 眼睛放大 */ public class MagnifyEyeUtils { /** * 眼睛放大算法 * @param bitmap 原来的bitmap * @param centerPoint 放大中心点 * @param radius 放大半径 * @param sizeLevel 放大力度 [0,4] * @return 放大眼睛后的图片 */ public static Bitmap magnifyEye(Bitmap bitmap, Point centerPoint, int radius, float sizeLevel) { TimeAopUtils.start(); Bitmap dstBitmap = bitmap.copy(Bitmap.Config.RGB_565, true); int left = centerPoint.x - radius < 0 ? 0 : centerPoint.x - radius; int top = centerPoint.y - radius < 0 ? 0 : centerPoint.y - radius; int right = centerPoint.x + radius > bitmap.getWidth() ? bitmap.getWidth() - 1 : centerPoint.x + radius; int bottom = centerPoint.y + radius > bitmap.getHeight() ? bitmap.getHeight() - 1 : centerPoint.y + radius; int powRadius = radius * radius; int offsetX, offsetY, powDistance, powOffsetX, powOffsetY; int disX, disY; //当为负数时,为缩小 float strength = (5 + sizeLevel * 2) / 10; for (int i = top; i <= bottom; i++) { offsetY = i - centerPoint.y; for (int j = left; j <= right; j++) { offsetX = j - centerPoint.x; powOffsetX = offsetX * offsetX; powOffsetY = offsetY * offsetY; powDistance = powOffsetX + powOffsetY; if (powDistance <= powRadius) { double distance = Math.sqrt(powDistance); double sinA = offsetX / distance; double cosA = offsetY / distance; double scaleFactor = distance / radius - 1; scaleFactor = (1 - scaleFactor * scaleFactor * (distance / radius) * strength); distance = distance * scaleFactor; disY = (int) (distance * cosA + centerPoint.y + 0.5); disY = checkY(disY, bitmap); disX = (int) (distance * sinA + centerPoint.x + 0.5); disX = checkX(disX, bitmap); //中心点不做处理 if (!(j == centerPoint.x && i == centerPoint.y)) { dstBitmap.setPixel(j, i, bitmap.getPixel(disX, disY)); } } } } TimeAopUtils.end("eye","magnifyEye"); return dstBitmap; } private static int checkY(int disY, Bitmap bitmap) { if (disY < 0) { disY = 0; } else if (disY >= bitmap.getHeight()) { disY = bitmap.getHeight() - 1; } return disY; } private static int checkX(int disX, Bitmap bitmap) { if (disX < 0) { disX = 0; } else if (disX >= bitmap.getWidth()) { disX = bitmap.getWidth() - 1; } return disX; } }
DingProg/Makeup
app/src/main/java/com/ding/makeup/beauty/MagnifyEyeUtils.java
853
//中心点不做处理
line_comment
zh-cn
package com.ding.makeup.beauty; import android.graphics.Bitmap; import android.graphics.Point; import com.ding.makeup.utils.TimeAopUtils; /** * @author by dingdegao * time 2017/9/29 16:03 * function: 眼睛放大 */ public class MagnifyEyeUtils { /** * 眼睛放大算法 * @param bitmap 原来的bitmap * @param centerPoint 放大中心点 * @param radius 放大半径 * @param sizeLevel 放大力度 [0,4] * @return 放大眼睛后的图片 */ public static Bitmap magnifyEye(Bitmap bitmap, Point centerPoint, int radius, float sizeLevel) { TimeAopUtils.start(); Bitmap dstBitmap = bitmap.copy(Bitmap.Config.RGB_565, true); int left = centerPoint.x - radius < 0 ? 0 : centerPoint.x - radius; int top = centerPoint.y - radius < 0 ? 0 : centerPoint.y - radius; int right = centerPoint.x + radius > bitmap.getWidth() ? bitmap.getWidth() - 1 : centerPoint.x + radius; int bottom = centerPoint.y + radius > bitmap.getHeight() ? bitmap.getHeight() - 1 : centerPoint.y + radius; int powRadius = radius * radius; int offsetX, offsetY, powDistance, powOffsetX, powOffsetY; int disX, disY; //当为负数时,为缩小 float strength = (5 + sizeLevel * 2) / 10; for (int i = top; i <= bottom; i++) { offsetY = i - centerPoint.y; for (int j = left; j <= right; j++) { offsetX = j - centerPoint.x; powOffsetX = offsetX * offsetX; powOffsetY = offsetY * offsetY; powDistance = powOffsetX + powOffsetY; if (powDistance <= powRadius) { double distance = Math.sqrt(powDistance); double sinA = offsetX / distance; double cosA = offsetY / distance; double scaleFactor = distance / radius - 1; scaleFactor = (1 - scaleFactor * scaleFactor * (distance / radius) * strength); distance = distance * scaleFactor; disY = (int) (distance * cosA + centerPoint.y + 0.5); disY = checkY(disY, bitmap); disX = (int) (distance * sinA + centerPoint.x + 0.5); disX = checkX(disX, bitmap); //中心 <SUF> if (!(j == centerPoint.x && i == centerPoint.y)) { dstBitmap.setPixel(j, i, bitmap.getPixel(disX, disY)); } } } } TimeAopUtils.end("eye","magnifyEye"); return dstBitmap; } private static int checkY(int disY, Bitmap bitmap) { if (disY < 0) { disY = 0; } else if (disY >= bitmap.getHeight()) { disY = bitmap.getHeight() - 1; } return disY; } private static int checkX(int disX, Bitmap bitmap) { if (disX < 0) { disX = 0; } else if (disX >= bitmap.getWidth()) { disX = bitmap.getWidth() - 1; } return disX; } }
0
777
5
853
6
877
5
853
6
983
10
false
false
false
false
false
true
36265_0
package com.parkingwang.keyboard.engine; import static com.parkingwang.keyboard.engine.NumberType.AVIATION; import static com.parkingwang.keyboard.engine.NumberType.CIVIL; import static com.parkingwang.keyboard.engine.NumberType.LING2012; import static com.parkingwang.keyboard.engine.NumberType.LING2018; import static com.parkingwang.keyboard.engine.NumberType.NEW_ENERGY; import static com.parkingwang.keyboard.engine.NumberType.PLA2012; import static com.parkingwang.keyboard.engine.NumberType.SHI2012; import static com.parkingwang.keyboard.engine.NumberType.WJ2012; /** * 禁用更多键的逻辑: * 1. 第1位,民用、新能源、新旧领事馆 * 2. 第3位,武警类型; * 3. 第7位,新能源、武警、军队、旧式2012大使馆、民航类型; * 4. 第8位; * */ public class MoreKeyTransformer extends LayoutMixer.AbstractTypedKeyTransformer { public MoreKeyTransformer() { super(KeyType.FUNC_MORE); } @Override protected KeyEntry transform(Context ctx, KeyEntry key) { if (0 == ctx.selectIndex && ctx.numberType.isAnyOf(CIVIL, NEW_ENERGY, LING2012, LING2018)) { return KeyEntry.newOfSetEnable(key, false); } else if (2 == ctx.selectIndex && WJ2012.equals(ctx.numberType)) { return KeyEntry.newOfSetEnable(key, false); } else if (6 == ctx.selectIndex && ctx.numberType.isAnyOf(NEW_ENERGY, WJ2012, PLA2012, SHI2012, AVIATION)) { return KeyEntry.newOfSetEnable(key, false); } else if (7 == ctx.selectIndex) { return KeyEntry.newOfSetEnable(key, false); } else { return key; } } }
DingXianSen/ProDemo
keyboard/src/main/java/com/parkingwang/keyboard/engine/MoreKeyTransformer.java
539
/** * 禁用更多键的逻辑: * 1. 第1位,民用、新能源、新旧领事馆 * 2. 第3位,武警类型; * 3. 第7位,新能源、武警、军队、旧式2012大使馆、民航类型; * 4. 第8位; * */
block_comment
zh-cn
package com.parkingwang.keyboard.engine; import static com.parkingwang.keyboard.engine.NumberType.AVIATION; import static com.parkingwang.keyboard.engine.NumberType.CIVIL; import static com.parkingwang.keyboard.engine.NumberType.LING2012; import static com.parkingwang.keyboard.engine.NumberType.LING2018; import static com.parkingwang.keyboard.engine.NumberType.NEW_ENERGY; import static com.parkingwang.keyboard.engine.NumberType.PLA2012; import static com.parkingwang.keyboard.engine.NumberType.SHI2012; import static com.parkingwang.keyboard.engine.NumberType.WJ2012; /** * 禁用更 <SUF>*/ public class MoreKeyTransformer extends LayoutMixer.AbstractTypedKeyTransformer { public MoreKeyTransformer() { super(KeyType.FUNC_MORE); } @Override protected KeyEntry transform(Context ctx, KeyEntry key) { if (0 == ctx.selectIndex && ctx.numberType.isAnyOf(CIVIL, NEW_ENERGY, LING2012, LING2018)) { return KeyEntry.newOfSetEnable(key, false); } else if (2 == ctx.selectIndex && WJ2012.equals(ctx.numberType)) { return KeyEntry.newOfSetEnable(key, false); } else if (6 == ctx.selectIndex && ctx.numberType.isAnyOf(NEW_ENERGY, WJ2012, PLA2012, SHI2012, AVIATION)) { return KeyEntry.newOfSetEnable(key, false); } else if (7 == ctx.selectIndex) { return KeyEntry.newOfSetEnable(key, false); } else { return key; } } }
0
440
76
539
97
519
84
539
97
623
123
false
false
false
false
false
true
8274_8
package com.mori.domain; import java.util.ArrayList; import java.util.List; public class Lesson { private String pk_LId;// 每门课都有那本书的ID +课程者TPhone 组合成ID 由课程建设者设定 Len 32 private String LName;//Len 20 private String LInfo;//Len 50 private String LIcon;//Len 100 private String fk_L_TPhone;//Len 11 private int LCount;//Len 255(数据库每个int 4字节 255=8字节 就32字节 没错) //考虑到有的课程课程号一样 老师不一样 所以老师在建设课程的时候输入的只是课程ID 而主键还是要老师PHONE+课程ID组合成唯一辨识 我了个去劳资又要改表又要 //从最里面改 = = ==== = = == = == = =所以就在逻辑上偷偷这样定义 自己手动添加PHONE 和ID组合再存入PK 在APP中JSON也有PK 不显示 隐藏起来 //点击课程显示章什么的再通过这个隐藏字段去FIND 显示详细章 节 private String fk_DId;//系ID private List<Section> sd=new ArrayList<Section>();//非字段 public List<Section> getSd() { return sd; } public void setSd(List<Section> sd) { this.sd = sd; } public String getFk_DId() { return fk_DId; } public void setFk_DId(String fk_DId) { this.fk_DId = fk_DId; } public int getLCount() { return LCount; } public void setLCount(int lCount) { LCount = lCount; } public String getFk_L_TPhone() { return fk_L_TPhone; } public void setFk_L_TPhone(String fk_L_TPhone) { this.fk_L_TPhone = fk_L_TPhone; } @Override public String toString() { return "Lesson [pk_LId=" + pk_LId + ", LName=" + LName + ", LInfo=" + LInfo + ", LIcon=" + LIcon + ", fk_L_TPhone=" + fk_L_TPhone + ", LCount=" + LCount + ", fk_DId=" + fk_DId + "]"; } public String getPk_LId() { return pk_LId; } public void setPk_LId(String pk_LId) { this.pk_LId = pk_LId; } public String getLName() { return LName; } public void setLName(String lName) { LName = lName; } public String getLInfo() { return LInfo; } public void setLInfo(String lInfo) { LInfo = lInfo; } public String getLIcon() { return LIcon; } public void setLIcon(String lIcon) { LIcon = lIcon; } }
DingYonghui/OnlineClass
web端源码/OnlineClass/src/com/mori/domain/Lesson.java
816
//点击课程显示章什么的再通过这个隐藏字段去FIND 显示详细章 节
line_comment
zh-cn
package com.mori.domain; import java.util.ArrayList; import java.util.List; public class Lesson { private String pk_LId;// 每门课都有那本书的ID +课程者TPhone 组合成ID 由课程建设者设定 Len 32 private String LName;//Len 20 private String LInfo;//Len 50 private String LIcon;//Len 100 private String fk_L_TPhone;//Len 11 private int LCount;//Len 255(数据库每个int 4字节 255=8字节 就32字节 没错) //考虑到有的课程课程号一样 老师不一样 所以老师在建设课程的时候输入的只是课程ID 而主键还是要老师PHONE+课程ID组合成唯一辨识 我了个去劳资又要改表又要 //从最里面改 = = ==== = = == = == = =所以就在逻辑上偷偷这样定义 自己手动添加PHONE 和ID组合再存入PK 在APP中JSON也有PK 不显示 隐藏起来 //点击 <SUF> private String fk_DId;//系ID private List<Section> sd=new ArrayList<Section>();//非字段 public List<Section> getSd() { return sd; } public void setSd(List<Section> sd) { this.sd = sd; } public String getFk_DId() { return fk_DId; } public void setFk_DId(String fk_DId) { this.fk_DId = fk_DId; } public int getLCount() { return LCount; } public void setLCount(int lCount) { LCount = lCount; } public String getFk_L_TPhone() { return fk_L_TPhone; } public void setFk_L_TPhone(String fk_L_TPhone) { this.fk_L_TPhone = fk_L_TPhone; } @Override public String toString() { return "Lesson [pk_LId=" + pk_LId + ", LName=" + LName + ", LInfo=" + LInfo + ", LIcon=" + LIcon + ", fk_L_TPhone=" + fk_L_TPhone + ", LCount=" + LCount + ", fk_DId=" + fk_DId + "]"; } public String getPk_LId() { return pk_LId; } public void setPk_LId(String pk_LId) { this.pk_LId = pk_LId; } public String getLName() { return LName; } public void setLName(String lName) { LName = lName; } public String getLInfo() { return LInfo; } public void setLInfo(String lInfo) { LInfo = lInfo; } public String getLIcon() { return LIcon; } public void setLIcon(String lIcon) { LIcon = lIcon; } }
0
675
22
816
20
783
17
816
20
1,021
41
false
false
false
false
false
true
50094_0
import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public interface Utility { static boolean isSpace(char c) { return c == ' '; } static boolean isNewLine(char c) { return c == '\n'; } static boolean isTab(char c) { return c == '\t'; } static long filesCompareByLine(Path path1, Path path2) throws IOException { try (BufferedReader bf1 = Files.newBufferedReader(path1); BufferedReader bf2 = Files.newBufferedReader(path2)) { // 用于标识两文件是否相同,-1是完全相同, // 否则是不同的行的行号,某种条件下也是较小文件的最大行号 long lineNumber = 1; String line1 = "", line2 = ""; while ((line1 = bf1.readLine()) != null) { line2 = bf2.readLine(); if (!line1.equals(line2)) { return lineNumber; } lineNumber++; } if (bf2.readLine() == null) { return -1; } else { return lineNumber; } } } }
Dludora/BUAA_Compiler
syntactic_analysis/src/Utility.java
282
// 用于标识两文件是否相同,-1是完全相同,
line_comment
zh-cn
import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public interface Utility { static boolean isSpace(char c) { return c == ' '; } static boolean isNewLine(char c) { return c == '\n'; } static boolean isTab(char c) { return c == '\t'; } static long filesCompareByLine(Path path1, Path path2) throws IOException { try (BufferedReader bf1 = Files.newBufferedReader(path1); BufferedReader bf2 = Files.newBufferedReader(path2)) { // 用于 <SUF> // 否则是不同的行的行号,某种条件下也是较小文件的最大行号 long lineNumber = 1; String line1 = "", line2 = ""; while ((line1 = bf1.readLine()) != null) { line2 = bf2.readLine(); if (!line1.equals(line2)) { return lineNumber; } lineNumber++; } if (bf2.readLine() == null) { return -1; } else { return lineNumber; } } } }
0
254
15
282
15
313
14
282
15
363
24
false
false
false
false
false
true
18212_1
package cn.nuaa.dmrfcoder.androidexceldemo; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StrictMode; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.List; import cn.nuaa.dmrfcoder.androidexceldemo.Bean.DemoBean; import cn.nuaa.dmrfcoder.androidexceldemo.Utils.ExcelUtil; public class MainActivity extends Activity implements View.OnClickListener { private Button exportButton; private Button openButton; private TextView textView; private AlertDialog alertDialog; private AlertDialog mDialog; String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}; private int REQUEST_PERMISSION_CODE = 1000; private String filePath = "/sdcard/AndroidExcelDemo"; private void requestPermission() { if (Build.VERSION.SDK_INT > 23) { if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED) { //授予权限 Log.i("requestPermission:", "用户之前已经授予了权限!"); } else { //未获得权限 Log.i("requestPermission:", "未获得权限,现在申请!"); requestPermissions(permissions , REQUEST_PERMISSION_CODE); } } } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); requestPermission(); StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); builder.detectFileUriExposure(); exportButton = findViewById(R.id.export_button); exportButton.setOnClickListener(this); openButton = findViewById(R.id.open_button); openButton.setOnClickListener(this); textView = findViewById(R.id.textView); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.i("onPermissionsResult:", "权限" + permissions[0] + "申请成功"); // permission was granted, yay! Do the // contacts-related task you need to do. } else { Log.i("onPermissionsResult:", "用户拒绝了权限申请"); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("permission") .setMessage("点击允许才可以使用我们的app哦") .setPositiveButton("去允许", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { if (alertDialog != null && alertDialog.isShowing()) { alertDialog.dismiss(); } ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } }); alertDialog = builder.create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); // permission denied, boo! Disable the // functionality that depends on this permission. } } } private void showDialogTipUserRequestPermission() { ActivityCompat.requestPermissions(this, permissions, 321); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.export_button: exportExcel(this); break; case R.id.open_button: openDir(); default: break; } } private void openDir() { File file = new File(filePath); Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setDataAndType(Uri.fromFile(file), "file/*"); try { startActivity(intent); } catch (Exception e) { Toast.makeText(this, "没有正确打开文件管理器", Toast.LENGTH_SHORT).show(); } } private void exportExcel(Context context) { File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } String excelFileName = "/demo.xls"; String[] title = {"姓名", "年龄", "男孩"}; String sheetName = "demoSheetName"; List<DemoBean> demoBeanList = new ArrayList<>(); DemoBean demoBean1 = new DemoBean("张三", 10, true); DemoBean demoBean2 = new DemoBean("小红", 12, false); DemoBean demoBean3 = new DemoBean("李四", 18, true); DemoBean demoBean4 = new DemoBean("王香", 13, false); demoBeanList.add(demoBean1); demoBeanList.add(demoBean2); demoBeanList.add(demoBean3); demoBeanList.add(demoBean4); filePath = filePath + excelFileName; ExcelUtil.initExcel(filePath, sheetName, title); ExcelUtil.writeObjListToExcel(demoBeanList, filePath, context); textView.setText("excel已导出至:" + filePath); } }
DmrfCoder/AndroidExcelDemo
app/src/main/java/cn/nuaa/dmrfcoder/androidexceldemo/MainActivity.java
1,433
//未获得权限
line_comment
zh-cn
package cn.nuaa.dmrfcoder.androidexceldemo; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StrictMode; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.List; import cn.nuaa.dmrfcoder.androidexceldemo.Bean.DemoBean; import cn.nuaa.dmrfcoder.androidexceldemo.Utils.ExcelUtil; public class MainActivity extends Activity implements View.OnClickListener { private Button exportButton; private Button openButton; private TextView textView; private AlertDialog alertDialog; private AlertDialog mDialog; String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}; private int REQUEST_PERMISSION_CODE = 1000; private String filePath = "/sdcard/AndroidExcelDemo"; private void requestPermission() { if (Build.VERSION.SDK_INT > 23) { if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED) { //授予权限 Log.i("requestPermission:", "用户之前已经授予了权限!"); } else { //未获 <SUF> Log.i("requestPermission:", "未获得权限,现在申请!"); requestPermissions(permissions , REQUEST_PERMISSION_CODE); } } } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); requestPermission(); StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); builder.detectFileUriExposure(); exportButton = findViewById(R.id.export_button); exportButton.setOnClickListener(this); openButton = findViewById(R.id.open_button); openButton.setOnClickListener(this); textView = findViewById(R.id.textView); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.i("onPermissionsResult:", "权限" + permissions[0] + "申请成功"); // permission was granted, yay! Do the // contacts-related task you need to do. } else { Log.i("onPermissionsResult:", "用户拒绝了权限申请"); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("permission") .setMessage("点击允许才可以使用我们的app哦") .setPositiveButton("去允许", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { if (alertDialog != null && alertDialog.isShowing()) { alertDialog.dismiss(); } ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } }); alertDialog = builder.create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); // permission denied, boo! Disable the // functionality that depends on this permission. } } } private void showDialogTipUserRequestPermission() { ActivityCompat.requestPermissions(this, permissions, 321); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.export_button: exportExcel(this); break; case R.id.open_button: openDir(); default: break; } } private void openDir() { File file = new File(filePath); Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setDataAndType(Uri.fromFile(file), "file/*"); try { startActivity(intent); } catch (Exception e) { Toast.makeText(this, "没有正确打开文件管理器", Toast.LENGTH_SHORT).show(); } } private void exportExcel(Context context) { File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } String excelFileName = "/demo.xls"; String[] title = {"姓名", "年龄", "男孩"}; String sheetName = "demoSheetName"; List<DemoBean> demoBeanList = new ArrayList<>(); DemoBean demoBean1 = new DemoBean("张三", 10, true); DemoBean demoBean2 = new DemoBean("小红", 12, false); DemoBean demoBean3 = new DemoBean("李四", 18, true); DemoBean demoBean4 = new DemoBean("王香", 13, false); demoBeanList.add(demoBean1); demoBeanList.add(demoBean2); demoBeanList.add(demoBean3); demoBeanList.add(demoBean4); filePath = filePath + excelFileName; ExcelUtil.initExcel(filePath, sheetName, title); ExcelUtil.writeObjListToExcel(demoBeanList, filePath, context); textView.setText("excel已导出至:" + filePath); } }
0
1,177
4
1,433
4
1,510
4
1,433
4
1,811
8
false
false
false
false
false
true