file_id
stringlengths
5
9
content
stringlengths
128
32.8k
repo
stringlengths
9
63
path
stringlengths
8
120
token_length
int64
52
8.14k
original_comment
stringlengths
5
1.83k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
111
32.8k
excluded
float64
0
1
tmp
float64
5
1.83k
test
float64
0
1
18644_4
package lab11.graphs; import java.util.PriorityQueue; /** * @author Josh Hug */ public class MazeAStarPath extends MazeExplorer { private int s; private int t; private boolean targetFound = false; private Maze maze; public MazeAStarPath(Maze m, int sourceX, int sourceY, int targetX, int targetY) { super(m); maze = m; s = maze.xyTo1D(sourceX, sourceY); t = maze.xyTo1D(targetX, targetY); distTo[s] = 0; edgeTo[s] = s; } /** Estimate of the distance from v to the target. */ private int h(int v) { int size=maze.N(); int v_X = v % size + 1; int v_Y = v / size + 1; int target_X = t % size + 1; int target_Y = t / size + 1; return Math.abs(target_X - v_X) + Math.abs(target_Y - v_Y); } /** Finds vertex estimated to be closest to target. */ private int findMinimumUnmarked() { return -1; /* You do not have to use this method. */ } private class Node implements Comparable<Node>{ public int vertice; public Node parent; public int moves; public int priority; Node(int v,int moves,Node parent){ this.vertice = v; this.moves=moves; this.parent = parent; this.priority = h(v) + moves; } @Override public int compareTo(Node o) { return this.priority - o.priority; } } //标记图中哪些点已经访问过(指曾经以该点为中心向四周探索的点,即从优先队列中出队的点) private boolean book[]=new boolean[marked.length]; /** Performs an A star search from vertex s. */ private void astar(int s) { marked[s] = true; announce(); PriorityQueue<Node>pq=new PriorityQueue<>(); pq.offer(new Node(s, 0, null)); while (!pq.isEmpty() && h(pq.peek().vertice) != 0) { Node v = pq.poll(); book[v.vertice]=true; for (int w : maze.adj(v.vertice)) { //曾经加入过优先队列的点没有访问的意义 if ((v.parent == null || w != v.parent.vertice) && book[w] == false) { book[w] = true; pq.offer(new Node(w, v.moves + 1, v)); marked[w] = true; edgeTo[w] = v.vertice; distTo[w] = distTo[v.vertice] + 1; announce(); } } } } @Override public void solve() { astar(s); } }
BoL0150/Berkeley-cs61b
lab11/lab11/graphs/MazeAStarPath.java
732
//标记图中哪些点已经访问过(指曾经以该点为中心向四周探索的点,即从优先队列中出队的点)
line_comment
zh-cn
package lab11.graphs; import java.util.PriorityQueue; /** * @author Josh Hug */ public class MazeAStarPath extends MazeExplorer { private int s; private int t; private boolean targetFound = false; private Maze maze; public MazeAStarPath(Maze m, int sourceX, int sourceY, int targetX, int targetY) { super(m); maze = m; s = maze.xyTo1D(sourceX, sourceY); t = maze.xyTo1D(targetX, targetY); distTo[s] = 0; edgeTo[s] = s; } /** Estimate of the distance from v to the target. */ private int h(int v) { int size=maze.N(); int v_X = v % size + 1; int v_Y = v / size + 1; int target_X = t % size + 1; int target_Y = t / size + 1; return Math.abs(target_X - v_X) + Math.abs(target_Y - v_Y); } /** Finds vertex estimated to be closest to target. */ private int findMinimumUnmarked() { return -1; /* You do not have to use this method. */ } private class Node implements Comparable<Node>{ public int vertice; public Node parent; public int moves; public int priority; Node(int v,int moves,Node parent){ this.vertice = v; this.moves=moves; this.parent = parent; this.priority = h(v) + moves; } @Override public int compareTo(Node o) { return this.priority - o.priority; } } //标记 <SUF> private boolean book[]=new boolean[marked.length]; /** Performs an A star search from vertex s. */ private void astar(int s) { marked[s] = true; announce(); PriorityQueue<Node>pq=new PriorityQueue<>(); pq.offer(new Node(s, 0, null)); while (!pq.isEmpty() && h(pq.peek().vertice) != 0) { Node v = pq.poll(); book[v.vertice]=true; for (int w : maze.adj(v.vertice)) { //曾经加入过优先队列的点没有访问的意义 if ((v.parent == null || w != v.parent.vertice) && book[w] == false) { book[w] = true; pq.offer(new Node(w, v.moves + 1, v)); marked[w] = true; edgeTo[w] = v.vertice; distTo[w] = distTo[v.vertice] + 1; announce(); } } } } @Override public void solve() { astar(s); } }
1
44
1
61584_1
package cr; import cr.data.FileInfo; import cr.plugin.PluginManager; import cr.tool.Logger; import cr.tool.Settings; import cr.ui.comp.ChatArea; import cr.ui.comp.FileList; import cr.ui.comp.InputPane; import cr.ui.comp.UserList; import cr.ui.frame.MainFrame; import cr.ui.popmenu.ChatPopMenu; import cr.ui.popmenu.UserPopMenu; import cr.util.Client; import cr.util.Server; import cr.util.user.User; import jni.NativeFrame; import javax.swing.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /* * _oo0oo_ * o8888888o * 88" . "88 * (| -_- |) * O\ = /O * ____/'---'\____ * .' \\| |// '. * / \\||| : |||// \ * / _||||| -:- |||||_ \ * | | | \\\ - /// | | | * | \_| ''\---/'' |_/ | * \ .-\__ `-` __/-. / * ___`. .' /--.--\ `. .'___ * ."" '< `.___\_<|>_/___.' >' "". * | | : `- \`.;`\ _ /`;.`/ -` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-`====== * `=---=` * * ....................................................... * 佛祖保佑 永无BUG * 佛曰: * 写字楼里写字间,写字间里程序员。 * 程序人员写程序,又拿程序换酒钱。 * 酒醒只在网上坐,酒醉还来网下眠。 * 酒醉酒醒日复日,网上网下年复年。 * 但愿老死电脑间,不愿鞠躬老板前。 * 奔驰宝马贵者趣,公交自行程序员。 * 别人笑我忒疯癫,我笑自己命太贱; * 不见满街漂亮妹,哪个归得程序员? */ public final class Main { public static MainFrame mainFrame; public static final ThreadPoolExecutor executor=new ThreadPoolExecutor(1,8,200000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10)); public static void main(String[] args) { long startTime = System.currentTimeMillis(); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } Logger.init(); Settings.init(); User.init(); UserList.init(); Client.init(); ChatPopMenu.init(); UserPopMenu.init(); ChatArea.init(); FileList.init(); InputPane.init(); MainFrame.init(); Server.init(); mainFrame = MainFrame.obj; mainFrame.setVisible(true); FileInfo.init(); /* 暂时删除了插件功能 原因:无法很好的处理插件中的Error,版本依赖太强,功能性不高,因为插件卡死重启程序不值得 */ // PluginManager.init(); long endTime = System.currentTimeMillis(); Logger.getLogger().info("Program starts in " + (endTime - startTime) / 1000.0 + 's' + " JRE version:" + System.getProperty("java.version")); if (!System.getProperty("java.version").startsWith("17")) { MainFrame.warn("检测到当前运行环境非Java17,可能存在兼容性问题,建议使用Java17运行本程序"); } } public static void exit() { PluginManager.callExit(); if (Client.getClient().isJoined()) Client.getClient().leave(false); if (Server.getServer().on) { Server.getServer().close(); } Settings.obj.save(); } }
BobbyWch/Chatroom
src/cr/Main.java
1,056
/* 暂时删除了插件功能 原因:无法很好的处理插件中的Error,版本依赖太强,功能性不高,因为插件卡死重启程序不值得 */
block_comment
zh-cn
package cr; import cr.data.FileInfo; import cr.plugin.PluginManager; import cr.tool.Logger; import cr.tool.Settings; import cr.ui.comp.ChatArea; import cr.ui.comp.FileList; import cr.ui.comp.InputPane; import cr.ui.comp.UserList; import cr.ui.frame.MainFrame; import cr.ui.popmenu.ChatPopMenu; import cr.ui.popmenu.UserPopMenu; import cr.util.Client; import cr.util.Server; import cr.util.user.User; import jni.NativeFrame; import javax.swing.*; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /* * _oo0oo_ * o8888888o * 88" . "88 * (| -_- |) * O\ = /O * ____/'---'\____ * .' \\| |// '. * / \\||| : |||// \ * / _||||| -:- |||||_ \ * | | | \\\ - /// | | | * | \_| ''\---/'' |_/ | * \ .-\__ `-` __/-. / * ___`. .' /--.--\ `. .'___ * ."" '< `.___\_<|>_/___.' >' "". * | | : `- \`.;`\ _ /`;.`/ -` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-`====== * `=---=` * * ....................................................... * 佛祖保佑 永无BUG * 佛曰: * 写字楼里写字间,写字间里程序员。 * 程序人员写程序,又拿程序换酒钱。 * 酒醒只在网上坐,酒醉还来网下眠。 * 酒醉酒醒日复日,网上网下年复年。 * 但愿老死电脑间,不愿鞠躬老板前。 * 奔驰宝马贵者趣,公交自行程序员。 * 别人笑我忒疯癫,我笑自己命太贱; * 不见满街漂亮妹,哪个归得程序员? */ public final class Main { public static MainFrame mainFrame; public static final ThreadPoolExecutor executor=new ThreadPoolExecutor(1,8,200000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10)); public static void main(String[] args) { long startTime = System.currentTimeMillis(); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } Logger.init(); Settings.init(); User.init(); UserList.init(); Client.init(); ChatPopMenu.init(); UserPopMenu.init(); ChatArea.init(); FileList.init(); InputPane.init(); MainFrame.init(); Server.init(); mainFrame = MainFrame.obj; mainFrame.setVisible(true); FileInfo.init(); /* 暂时删 <SUF>*/ // PluginManager.init(); long endTime = System.currentTimeMillis(); Logger.getLogger().info("Program starts in " + (endTime - startTime) / 1000.0 + 's' + " JRE version:" + System.getProperty("java.version")); if (!System.getProperty("java.version").startsWith("17")) { MainFrame.warn("检测到当前运行环境非Java17,可能存在兼容性问题,建议使用Java17运行本程序"); } } public static void exit() { PluginManager.callExit(); if (Client.getClient().isJoined()) Client.getClient().leave(false); if (Server.getServer().on) { Server.getServer().close(); } Settings.obj.save(); } }
0
87
0
29832_4
package com.wolf.routermanager.bean; import java.io.Serializable; import java.io.UnsupportedEncodingException; /** * 存储已连接的用户信息的javabean * * @author 狼骑兵 * @date 2014-06-25 */ @SuppressWarnings("serial") public class WifiUserBean implements Serializable{ private int id; /** * 机器名,如android-2223643254353 */ private String userName; /** * mac地址 */ private String macAddress; /** * ip地址 */ private String ipAddress; /** * 已经持续使用的时间 */ private String validTime; /** * 接受数据包数 */ private String receiveData; /** * 发送数据包数 */ private String outputData; /** * 信任时的别名 */ private boolean otherName; /** * 厂商 */ private String company; public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { if(userName!=null){ try { return new String(userName.getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return "未知"; } public void setUserName(String userName) { this.userName = userName; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public boolean getOtherName() { return otherName; } public void setOtherName(boolean otherName) { this.otherName = otherName; } public String getValidTime() { return validTime; } public void setValidTime(String validTime) { this.validTime = validTime; } public String getReceiveData() { return receiveData; } public void setReceiveData(String receiveData) { this.receiveData = receiveData; } public String getOutputData() { return outputData; } public void setOutputData(String outputData) { this.outputData = outputData; } }
BobsWang/RouterManager
src/com/wolf/routermanager/bean/WifiUserBean.java
693
/** * 已经持续使用的时间 */
block_comment
zh-cn
package com.wolf.routermanager.bean; import java.io.Serializable; import java.io.UnsupportedEncodingException; /** * 存储已连接的用户信息的javabean * * @author 狼骑兵 * @date 2014-06-25 */ @SuppressWarnings("serial") public class WifiUserBean implements Serializable{ private int id; /** * 机器名,如android-2223643254353 */ private String userName; /** * mac地址 */ private String macAddress; /** * ip地址 */ private String ipAddress; /** * 已经持 <SUF>*/ private String validTime; /** * 接受数据包数 */ private String receiveData; /** * 发送数据包数 */ private String outputData; /** * 信任时的别名 */ private boolean otherName; /** * 厂商 */ private String company; public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { if(userName!=null){ try { return new String(userName.getBytes("ISO-8859-1"), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return "未知"; } public void setUserName(String userName) { this.userName = userName; } public String getMacAddress() { return macAddress; } public void setMacAddress(String macAddress) { this.macAddress = macAddress; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } public boolean getOtherName() { return otherName; } public void setOtherName(boolean otherName) { this.otherName = otherName; } public String getValidTime() { return validTime; } public void setValidTime(String validTime) { this.validTime = validTime; } public String getReceiveData() { return receiveData; } public void setReceiveData(String receiveData) { this.receiveData = receiveData; } public String getOutputData() { return outputData; } public void setOutputData(String outputData) { this.outputData = outputData; } }
1
22
1
29851_3
package com.lc.nio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class NioServe2 { public static void main(String[] args) throws Exception { //创建ServerSocketChannel -> ServerSocket ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //得到一个Selecor对象 Selector selector = Selector.open(); //绑定一个端口6666, 在服务器端监听 serverSocketChannel.socket().bind(new InetSocketAddress(6666)); //设置为非阻塞 serverSocketChannel.configureBlocking(false); //把 serverSocketChannel 注册到 selector 关心 事件为 OP_ACCEPT pos_1 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("注册后的selectionkey 数量=" + selector.keys().size()); // 1 //循环等待客户端连接 while (true) { //这里我们等待1秒,如果没有事件发生, 返回 if (selector.select(1000) == 0) { //没有事件发生 System.out.println("服务器等待了1秒,无连接"); continue; } //如果返回的>0, 就获取到相关的 selectionKey集合 //1.如果返回的>0, 表示已经获取到关注的事件 //2. selector.selectedKeys() 返回关注事件的集合 // 通过 selectionKeys 反向获取通道 Set<SelectionKey> selectionKeys = selector.selectedKeys(); System.out.println("selectionKeys 数量 = " + selectionKeys.size()); //遍历 Set<SelectionKey>, 使用迭代器遍历 Iterator<SelectionKey> keyIterator = selectionKeys.iterator(); while (keyIterator.hasNext()) { //获取到SelectionKey SelectionKey key = keyIterator.next(); //根据key 对应的通道发生的事件做相应处理 if (key.isAcceptable()) { //如果是 OP_ACCEPT, 有新的客户端连接 //该该客户端生成一个 SocketChannel SocketChannel socketChannel = serverSocketChannel.accept(); System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode()); //将 SocketChannel 设置为非阻塞 socketChannel.configureBlocking(false); //将socketChannel 注册到selector, 关注事件为 OP_READ, 同时给socketChannel //关联一个Buffer socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024)); System.out.println("客户端连接后 ,注册的selectionkey 数量=" + selector.keys().size()); //2,3,4.. } if (key.isReadable()) { //发生 OP_READ //通过key 反向获取到对应channel SocketChannel channel = (SocketChannel) key.channel(); //获取到该channel关联的buffer ByteBuffer buffer = (ByteBuffer) key.attachment(); channel.read(buffer); System.out.println("form 客户端 " + new String(buffer.array())); } //手动从集合中移动当前的selectionKey, 防止重复操作 keyIterator.remove(); } } } }
Bocolvchao/springcloudstudy
netty-project/src/main/java/com/lc/nio/NioServe2.java
760
//设置为非阻塞
line_comment
zh-cn
package com.lc.nio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; public class NioServe2 { public static void main(String[] args) throws Exception { //创建ServerSocketChannel -> ServerSocket ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); //得到一个Selecor对象 Selector selector = Selector.open(); //绑定一个端口6666, 在服务器端监听 serverSocketChannel.socket().bind(new InetSocketAddress(6666)); //设置 <SUF> serverSocketChannel.configureBlocking(false); //把 serverSocketChannel 注册到 selector 关心 事件为 OP_ACCEPT pos_1 serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); System.out.println("注册后的selectionkey 数量=" + selector.keys().size()); // 1 //循环等待客户端连接 while (true) { //这里我们等待1秒,如果没有事件发生, 返回 if (selector.select(1000) == 0) { //没有事件发生 System.out.println("服务器等待了1秒,无连接"); continue; } //如果返回的>0, 就获取到相关的 selectionKey集合 //1.如果返回的>0, 表示已经获取到关注的事件 //2. selector.selectedKeys() 返回关注事件的集合 // 通过 selectionKeys 反向获取通道 Set<SelectionKey> selectionKeys = selector.selectedKeys(); System.out.println("selectionKeys 数量 = " + selectionKeys.size()); //遍历 Set<SelectionKey>, 使用迭代器遍历 Iterator<SelectionKey> keyIterator = selectionKeys.iterator(); while (keyIterator.hasNext()) { //获取到SelectionKey SelectionKey key = keyIterator.next(); //根据key 对应的通道发生的事件做相应处理 if (key.isAcceptable()) { //如果是 OP_ACCEPT, 有新的客户端连接 //该该客户端生成一个 SocketChannel SocketChannel socketChannel = serverSocketChannel.accept(); System.out.println("客户端连接成功 生成了一个 socketChannel " + socketChannel.hashCode()); //将 SocketChannel 设置为非阻塞 socketChannel.configureBlocking(false); //将socketChannel 注册到selector, 关注事件为 OP_READ, 同时给socketChannel //关联一个Buffer socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024)); System.out.println("客户端连接后 ,注册的selectionkey 数量=" + selector.keys().size()); //2,3,4.. } if (key.isReadable()) { //发生 OP_READ //通过key 反向获取到对应channel SocketChannel channel = (SocketChannel) key.channel(); //获取到该channel关联的buffer ByteBuffer buffer = (ByteBuffer) key.attachment(); channel.read(buffer); System.out.println("form 客户端 " + new String(buffer.array())); } //手动从集合中移动当前的selectionKey, 防止重复操作 keyIterator.remove(); } } } }
1
8
1
55182_1
//归并排序虽然是nlogn的时间复杂度,但是它需要用到额外的O(n)的空间 //这是它不优于快排的原因 public class Solution { public void sortIntegers2(int[] A) { if(A==null||A.length==0){ return ; } int [] temp=new int[A.length]; mergeSort(A,0,A.length-1,temp); } public void mergeSort(int []nums,int start,int end,int[] temp){ if(start>=end) return; mergeSort(nums,start,(start+end)/2,temp); mergeSort(nums,(start+end)/2 + 1,end,temp); merge(nums,start,end,temp); } public void merge(int []nums,int start,int end,int[]temp){ int mid=(start+end)/2; int left=start; int right=mid+1; int i=left; while(left<=mid&&right<=end){ if(nums[left]<nums[right]){ temp[i++]=nums[left++]; } else{ temp[i++]=nums[right++]; } } while(left<=mid){ temp[i++]=nums[left++]; } while(right<=end){ temp[i++]=nums[right++]; } for(int j=start;j<=end;j++){ nums[j]=temp[j]; } } }
BoogieStreet/jiuzhangsuanfa
mergeSort.java
350
//这是它不优于快排的原因
line_comment
zh-cn
//归并排序虽然是nlogn的时间复杂度,但是它需要用到额外的O(n)的空间 //这是 <SUF> public class Solution { public void sortIntegers2(int[] A) { if(A==null||A.length==0){ return ; } int [] temp=new int[A.length]; mergeSort(A,0,A.length-1,temp); } public void mergeSort(int []nums,int start,int end,int[] temp){ if(start>=end) return; mergeSort(nums,start,(start+end)/2,temp); mergeSort(nums,(start+end)/2 + 1,end,temp); merge(nums,start,end,temp); } public void merge(int []nums,int start,int end,int[]temp){ int mid=(start+end)/2; int left=start; int right=mid+1; int i=left; while(left<=mid&&right<=end){ if(nums[left]<nums[right]){ temp[i++]=nums[left++]; } else{ temp[i++]=nums[right++]; } } while(left<=mid){ temp[i++]=nums[left++]; } while(right<=end){ temp[i++]=nums[right++]; } for(int j=start;j<=end;j++){ nums[j]=temp[j]; } } }
1
13
1
33101_8
package com.bc.cache.controller; import com.bc.cache.entity.GoodsInventory; import com.bc.cache.request.Request; import com.bc.cache.request.impl.GoodsInventoryCacheRefreshRequest; import com.bc.cache.request.impl.GoodsInventoryDbUpdateRequest; import com.bc.cache.response.Response; import com.bc.cache.service.GoodsInventoryService; import com.bc.cache.service.RequestAsyncProcessService; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * 库存控制器 * * @author zhou */ @RestController @RequestMapping("goodsInventory") public class GoodsInventoryController { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GoodsInventoryController.class); @Resource private GoodsInventoryService goodsInventoryService; @Resource private RequestAsyncProcessService requestAsyncProcessService; /** * 更新商品库存 */ @ApiOperation(value = "修改商品库存", notes = "修改商品库存") @PutMapping(value = "/") public Response updateProductInventory(@RequestParam Integer goodsId, @RequestParam Long inventoryCount) { GoodsInventory goodsInventory = new GoodsInventory(goodsId, inventoryCount); logger.info("接收到更新商品库存的请求,商品id: " + goodsInventory.getGoodsId() + ", 商品库存数量: " + goodsInventory.getInventoryCount()); Response response; try { Request request = new GoodsInventoryDbUpdateRequest( goodsInventory, goodsInventoryService); requestAsyncProcessService.process(request); response = new Response(Response.SUCCESS); } catch (Exception e) { e.printStackTrace(); response = new Response(Response.FAILURE); } return response; } /** * 获取商品库存 */ @ApiOperation(value = "获取商品库存", notes = "获取商品库存") @GetMapping(value = "/") public GoodsInventory getGoodsInventory(Integer goodsId) { logger.info("接收到一个商品库存的读请求,商品id: " + goodsId); GoodsInventory goodsInventory; try { Request request = new GoodsInventoryCacheRefreshRequest( goodsId, goodsInventoryService); requestAsyncProcessService.process(request); // 将请求扔给service异步去处理以后,就需要while(true)一会儿,在这里hang住 // 去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 long startTime = System.currentTimeMillis(); long endTime; long waitTime = 0L; // 等待超过200ms没有从缓存中获取到结果 while (true) { // 一般公司里面,面向用户的读请求控制在200ms就可以了 if (waitTime > 200) { break; } // 尝试去redis中读取一次商品库存的缓存数据 goodsInventory = goodsInventoryService.getGoodsInventoryCache(goodsId); // 如果读取到了结果,那么就返回 if (goodsInventory != null) { logger.info("在200ms内读取到了redis中的库存缓存,商品id: " + goodsInventory.getGoodsId() + ", 商品库存数量: " + goodsInventory.getInventoryCount()); return goodsInventory; } // 如果没有读取到结果,那么等待一段时间 else { Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } // 直接尝试从数据库中读取数据 goodsInventory = goodsInventoryService.findGoodsInventory(goodsId); if (goodsInventory != null) { // 将缓存刷新一下 goodsInventoryService.setGoodsInventoryCache(goodsInventory); return goodsInventory; } } catch (Exception e) { e.printStackTrace(); } return new GoodsInventory(goodsId, -1L); } }
BooksCup/cache-aside-pattern
src/main/java/com/bc/cache/controller/GoodsInventoryController.java
945
// 尝试去redis中读取一次商品库存的缓存数据
line_comment
zh-cn
package com.bc.cache.controller; import com.bc.cache.entity.GoodsInventory; import com.bc.cache.request.Request; import com.bc.cache.request.impl.GoodsInventoryCacheRefreshRequest; import com.bc.cache.request.impl.GoodsInventoryDbUpdateRequest; import com.bc.cache.response.Response; import com.bc.cache.service.GoodsInventoryService; import com.bc.cache.service.RequestAsyncProcessService; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; /** * 库存控制器 * * @author zhou */ @RestController @RequestMapping("goodsInventory") public class GoodsInventoryController { /** * 日志 */ private static final Logger logger = LoggerFactory.getLogger(GoodsInventoryController.class); @Resource private GoodsInventoryService goodsInventoryService; @Resource private RequestAsyncProcessService requestAsyncProcessService; /** * 更新商品库存 */ @ApiOperation(value = "修改商品库存", notes = "修改商品库存") @PutMapping(value = "/") public Response updateProductInventory(@RequestParam Integer goodsId, @RequestParam Long inventoryCount) { GoodsInventory goodsInventory = new GoodsInventory(goodsId, inventoryCount); logger.info("接收到更新商品库存的请求,商品id: " + goodsInventory.getGoodsId() + ", 商品库存数量: " + goodsInventory.getInventoryCount()); Response response; try { Request request = new GoodsInventoryDbUpdateRequest( goodsInventory, goodsInventoryService); requestAsyncProcessService.process(request); response = new Response(Response.SUCCESS); } catch (Exception e) { e.printStackTrace(); response = new Response(Response.FAILURE); } return response; } /** * 获取商品库存 */ @ApiOperation(value = "获取商品库存", notes = "获取商品库存") @GetMapping(value = "/") public GoodsInventory getGoodsInventory(Integer goodsId) { logger.info("接收到一个商品库存的读请求,商品id: " + goodsId); GoodsInventory goodsInventory; try { Request request = new GoodsInventoryCacheRefreshRequest( goodsId, goodsInventoryService); requestAsyncProcessService.process(request); // 将请求扔给service异步去处理以后,就需要while(true)一会儿,在这里hang住 // 去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 long startTime = System.currentTimeMillis(); long endTime; long waitTime = 0L; // 等待超过200ms没有从缓存中获取到结果 while (true) { // 一般公司里面,面向用户的读请求控制在200ms就可以了 if (waitTime > 200) { break; } // 尝试 <SUF> goodsInventory = goodsInventoryService.getGoodsInventoryCache(goodsId); // 如果读取到了结果,那么就返回 if (goodsInventory != null) { logger.info("在200ms内读取到了redis中的库存缓存,商品id: " + goodsInventory.getGoodsId() + ", 商品库存数量: " + goodsInventory.getInventoryCount()); return goodsInventory; } // 如果没有读取到结果,那么等待一段时间 else { Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } // 直接尝试从数据库中读取数据 goodsInventory = goodsInventoryService.findGoodsInventory(goodsId); if (goodsInventory != null) { // 将缓存刷新一下 goodsInventoryService.setGoodsInventoryCache(goodsInventory); return goodsInventory; } } catch (Exception e) { e.printStackTrace(); } return new GoodsInventory(goodsId, -1L); } }
1
25
1
48433_2
/* * @lc app=leetcode id=123 lang=java * * [123] Best Time to Buy and Sell Stock III */ // @lc code=start class Solution { /* 假设手上最开始只有0元钱,那么如果买入股票的价格为price,手上的钱需要减去这个price,如果卖出股票的价格为price, 手上的钱需要加上这个price。然后不断更新第一次买,第一次卖,第二次买,第二次卖的钱。 time: O(n) space: O(1) */ public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) return 0; int buy1= Integer.MIN_VALUE, buy2= Integer.MIN_VALUE; int sell1 = 0, sell2 = 0; for (int price : prices) { buy1 = Math.max(buy1, -price); sell1 = Math.max(sell1, buy1 + price); buy2 = Math.max(buy2, sell1 - price); sell2 = Math.max(sell2, buy2 + price); } return sell2; } } // @lc code=end
BoscoSuen/leetcode
Java/123.best-time-to-buy-and-sell-stock-iii.java
296
/* 假设手上最开始只有0元钱,那么如果买入股票的价格为price,手上的钱需要减去这个price,如果卖出股票的价格为price, 手上的钱需要加上这个price。然后不断更新第一次买,第一次卖,第二次买,第二次卖的钱。 time: O(n) space: O(1) */
block_comment
zh-cn
/* * @lc app=leetcode id=123 lang=java * * [123] Best Time to Buy and Sell Stock III */ // @lc code=start class Solution { /* 假设手 <SUF>*/ public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) return 0; int buy1= Integer.MIN_VALUE, buy2= Integer.MIN_VALUE; int sell1 = 0, sell2 = 0; for (int price : prices) { buy1 = Math.max(buy1, -price); sell1 = Math.max(sell1, buy1 + price); buy2 = Math.max(buy2, sell1 - price); sell2 = Math.max(sell2, buy2 + price); } return sell2; } } // @lc code=end
0
157
0
25363_17
package net.bowen.chapter4; import net.bowen.engine.GLFWWindow; import net.bowen.engine.ShaderProgram; import net.bowen.engine.util.Color; import org.joml.Matrix4f; import org.joml.Matrix4fStack; import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFWFramebufferSizeCallbackI; import static org.joml.Math.cos; import static org.joml.Math.sin; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL43.*; public class Program4_4 { private static long windowHandle; private static float cameraX; private static float cameraY; private static float cameraZ; private static Matrix4f pMat; private static final float[] vals = new float[16];// utility buffer for transferring matrices private static final int[] vbo = new int[2]; private static final GLFWFramebufferSizeCallbackI resizeGlViewportAndResetAspect = (long window, int w, int h) -> { System.out.println("GLFW Window Resized to: " + w + "*" + h); glViewport(0, 0, w, h); createProjMat(w, h); }; private static int projLoc; private static int mvLoc; public static void main(String[] args) { init(); // 迴圈 loop(); // 釋出 GLFW.glfwTerminate(); System.out.println("App exit and freed glfw."); } private static void init() { final int windowCreatedW = 800, windowCreatedH = 600; GLFWWindow glfwWindow = new GLFWWindow(windowCreatedW, windowCreatedH, "第4章"); windowHandle = glfwWindow.getID(); glfwWindow.setClearColor(new Color(0f, 0f, 0f, 0f)); // 一開始要先呼叫,才能以長、寬構建透視矩陣 createProjMat(windowCreatedW, windowCreatedH); // 設定frameBuffer大小改變callback glfwSetFramebufferSizeCallback(windowHandle, resizeGlViewportAndResetAspect); int program = new ShaderProgram("assets/shaders/program4_3&4/VertexShader.glsl" , "assets/shaders/program4_3&4/FragmentShader.glsl") .getID(); cameraX = 0f; cameraY = 0f; cameraZ = 8f; setupVertices(); glUseProgram(program); System.out.println("Using ProgramID: " + program); // 獲取mv矩陣和投影矩陣的統一變量 mvLoc = glGetUniformLocation(program, "mv_matrix"); projLoc = glGetUniformLocation(program, "proj_matrix"); } private static void loop() { while (!GLFW.glfwWindowShouldClose(windowHandle)) { float currentTime = (float) glfwGetTime(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_CULL_FACE); glUniformMatrix4fv(projLoc, false, pMat.get(vals)); // 將視圖矩陣壓入栈 Matrix4fStack mvStack = new Matrix4fStack(5); mvStack.pushMatrix(); mvStack.translate(-cameraX, -cameraY, -cameraZ); // ------------------四角錐 : 太陽------------------------------------------- mvStack.pushMatrix(); mvStack.translate(0f, 0f, 0f); // 太陽位置 mvStack.pushMatrix(); mvStack.rotateX(currentTime); // 太陽旋轉 glUniformMatrix4fv(mvLoc, false, mvStack.get(vals)); glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glDrawArrays(GL_TRIANGLES, 0, 18); // 繪製太陽 mvStack.popMatrix(); // 從栈中移除太陽自轉 // ------------------大立方體 : 地球------------------------------------------- mvStack.pushMatrix(); mvStack.translate(sin(currentTime) * 4f, 0f, cos(currentTime) * 4f); // 地球繞太陽移動 mvStack.pushMatrix(); mvStack.rotateY(currentTime); // 地球旋轉 glUniformMatrix4fv(mvLoc, false, mvStack.get(vals)); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 36); // 繪製地球 mvStack.popMatrix(); // 移除栈中的地球自旋轉 // ------------------小立方體 : 月球------------------------------------------- mvStack.pushMatrix(); mvStack.translate(0f, sin(currentTime) * 2f, cos(currentTime) * 2f); // 月球繞地球移動 mvStack.rotateZ(currentTime); // 月球旋轉 mvStack.scale(.5f); // 讓月球小一點 glUniformMatrix4fv(mvLoc, false, mvStack.get(vals)); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 36); // 繪製月球 glfwSwapBuffers(windowHandle); glfwPollEvents(); } } private static void setupVertices() { float[] cubePositions = { // 36個頂點,12個三角形; 2*2*2 正方體 -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, }; float[] pyramidPositions = { // 四角椎 -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f }; int vao = glGenVertexArrays(); // vao: Vertex Array Object glBindVertexArray(vao); vbo[0] = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER, cubePositions, GL_STATIC_DRAW); vbo[1] = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glBufferData(GL_ARRAY_BUFFER, pyramidPositions, GL_STATIC_DRAW); } private static void createProjMat(int w, int h) { float aspect = (float) w / (float) h; pMat = new Matrix4f().perspective(1.0472f, aspect, .1f, 1000f); // 1.0472 = 60度 } }
Bowen951209/opengl-java-exercising
src/main/java/net/bowen/chapter4/Program4_4.java
2,637
// 月球旋轉
line_comment
zh-cn
package net.bowen.chapter4; import net.bowen.engine.GLFWWindow; import net.bowen.engine.ShaderProgram; import net.bowen.engine.util.Color; import org.joml.Matrix4f; import org.joml.Matrix4fStack; import org.lwjgl.glfw.GLFW; import org.lwjgl.glfw.GLFWFramebufferSizeCallbackI; import static org.joml.Math.cos; import static org.joml.Math.sin; import static org.lwjgl.glfw.GLFW.*; import static org.lwjgl.opengl.GL43.*; public class Program4_4 { private static long windowHandle; private static float cameraX; private static float cameraY; private static float cameraZ; private static Matrix4f pMat; private static final float[] vals = new float[16];// utility buffer for transferring matrices private static final int[] vbo = new int[2]; private static final GLFWFramebufferSizeCallbackI resizeGlViewportAndResetAspect = (long window, int w, int h) -> { System.out.println("GLFW Window Resized to: " + w + "*" + h); glViewport(0, 0, w, h); createProjMat(w, h); }; private static int projLoc; private static int mvLoc; public static void main(String[] args) { init(); // 迴圈 loop(); // 釋出 GLFW.glfwTerminate(); System.out.println("App exit and freed glfw."); } private static void init() { final int windowCreatedW = 800, windowCreatedH = 600; GLFWWindow glfwWindow = new GLFWWindow(windowCreatedW, windowCreatedH, "第4章"); windowHandle = glfwWindow.getID(); glfwWindow.setClearColor(new Color(0f, 0f, 0f, 0f)); // 一開始要先呼叫,才能以長、寬構建透視矩陣 createProjMat(windowCreatedW, windowCreatedH); // 設定frameBuffer大小改變callback glfwSetFramebufferSizeCallback(windowHandle, resizeGlViewportAndResetAspect); int program = new ShaderProgram("assets/shaders/program4_3&4/VertexShader.glsl" , "assets/shaders/program4_3&4/FragmentShader.glsl") .getID(); cameraX = 0f; cameraY = 0f; cameraZ = 8f; setupVertices(); glUseProgram(program); System.out.println("Using ProgramID: " + program); // 獲取mv矩陣和投影矩陣的統一變量 mvLoc = glGetUniformLocation(program, "mv_matrix"); projLoc = glGetUniformLocation(program, "proj_matrix"); } private static void loop() { while (!GLFW.glfwWindowShouldClose(windowHandle)) { float currentTime = (float) glfwGetTime(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_CULL_FACE); glUniformMatrix4fv(projLoc, false, pMat.get(vals)); // 將視圖矩陣壓入栈 Matrix4fStack mvStack = new Matrix4fStack(5); mvStack.pushMatrix(); mvStack.translate(-cameraX, -cameraY, -cameraZ); // ------------------四角錐 : 太陽------------------------------------------- mvStack.pushMatrix(); mvStack.translate(0f, 0f, 0f); // 太陽位置 mvStack.pushMatrix(); mvStack.rotateX(currentTime); // 太陽旋轉 glUniformMatrix4fv(mvLoc, false, mvStack.get(vals)); glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(0); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); glDrawArrays(GL_TRIANGLES, 0, 18); // 繪製太陽 mvStack.popMatrix(); // 從栈中移除太陽自轉 // ------------------大立方體 : 地球------------------------------------------- mvStack.pushMatrix(); mvStack.translate(sin(currentTime) * 4f, 0f, cos(currentTime) * 4f); // 地球繞太陽移動 mvStack.pushMatrix(); mvStack.rotateY(currentTime); // 地球旋轉 glUniformMatrix4fv(mvLoc, false, mvStack.get(vals)); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 36); // 繪製地球 mvStack.popMatrix(); // 移除栈中的地球自旋轉 // ------------------小立方體 : 月球------------------------------------------- mvStack.pushMatrix(); mvStack.translate(0f, sin(currentTime) * 2f, cos(currentTime) * 2f); // 月球繞地球移動 mvStack.rotateZ(currentTime); // 月球 <SUF> mvStack.scale(.5f); // 讓月球小一點 glUniformMatrix4fv(mvLoc, false, mvStack.get(vals)); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 36); // 繪製月球 glfwSwapBuffers(windowHandle); glfwPollEvents(); } } private static void setupVertices() { float[] cubePositions = { // 36個頂點,12個三角形; 2*2*2 正方體 -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, }; float[] pyramidPositions = { // 四角椎 -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 0.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f }; int vao = glGenVertexArrays(); // vao: Vertex Array Object glBindVertexArray(vao); vbo[0] = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); glBufferData(GL_ARRAY_BUFFER, cubePositions, GL_STATIC_DRAW); vbo[1] = glGenBuffers(); glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); glBufferData(GL_ARRAY_BUFFER, pyramidPositions, GL_STATIC_DRAW); } private static void createProjMat(int w, int h) { float aspect = (float) w / (float) h; pMat = new Matrix4f().perspective(1.0472f, aspect, .1f, 1000f); // 1.0472 = 60度 } }
0
7
0
19514_4
package com.alex.space.common; import java.text.DecimalFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.concurrent.ThreadLocalRandom; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; /** * 生成Key和value * * @author Alex Created by Alex on 2018/9/9. */ @Slf4j public class KeyValueGenerator { private static char[] CHARS = "abcdefghijklmnopqrstuvwxyz1234567890" .toCharArray(); private static char[] SHORT_CHARS = "abcde".toCharArray(); private static int ARRAY_MAX_LENGTH = 5; private static City[] cities = { new City("北京市", "北京市"), new City("天津市", "天津市"), new City("重庆市", "重庆市"), new City("上海市", "上海市"), new City("广东省", "广州市"), new City("广东省", "深圳市"), new City("广东省", "汕头市"), new City("广东省", "韶关市"), new City("广东省", "佛山市"), new City("广东省", "湛江市"), new City("广东省", "茂名市"), new City("辽宁省", "沈阳市"), new City("辽宁省", "大连市"), new City("辽宁省", "抚顺市"), new City("辽宁省", "抚顺市"), new City("辽宁省", "丹东市"), new City("辽宁省", "锦州市"), new City("辽宁省", "阜新市"), new City("辽宁省", "葫芦岛市"), new City("江苏省", "南京市"), new City("江苏省", "苏州市"), new City("江苏省", "常州市"), new City("江苏省", "连云港市"), new City("江苏省", "盐城市"), new City("湖北省", "武汉市"), new City("湖北省", "黄石市"), new City("湖北省", "宜昌市"), new City("四川省", "成都市"), new City("四川省", "自贡市"), new City("四川省", "德阳市"), new City("陕西省", "西安市"), new City("陕西省", "铜川市"), new City("陕西省", "延安市"), new City("陕西省", "汉中市"), new City("河北省", "石家庄市"), new City("河北省", "唐山市"), new City("河北省", "秦皇岛市"), new City("河北省", "邯郸市"), new City("山西省", "太原市"), new City("山西省", "大同市"), new City("山西省", "长治市"), new City("山西省", "晋中市"), new City("河南省", "郑州市"), new City("河南省", "开封市"), new City("河南省", "洛阳市"), new City("河南省", "安阳市"), new City("河南省", "新乡市"), new City("吉林省", "长春市"), new City("吉林省", "吉林市"), new City("黑龙江省", "哈尔滨市"), new City("黑龙江省", "齐齐哈尔市"), new City("黑龙江省", "鸡西市"), new City("黑龙江省", "鹤岗市"), new City("内蒙古", "呼和浩特市"), new City("内蒙古", "包头市"), new City("江苏省", "盐城市"), new City("江苏省", "宿迁市"), new City("浙江省", "嘉兴市"), new City("浙江省", "湖州市"), new City("福建省", "福州市"), new City("福建省", "厦门市"), new City("广西壮族自治区", "柳州"), new City("广西壮族自治区", "梧州"), new City("广西壮族自治区", "玉林"), new City("贵州省", "六盘水市"), new City("贵州省", "安顺市"), new City("贵州省", "黔南布依族苗族自治州"), new City("云南省", "昆明市"), new City("西藏自治区", "拉萨市"), new City("西藏自治区", "阿里地区"), new City("甘肃省", "兰州市"), new City("甘肃省", "天水市"), new City("甘肃省", "陇南市"), new City("青海省", "西宁市"), new City("新疆维吾尔族自治区", "乌鲁木齐市"), new City("新疆维吾尔族自治区", "克拉玛依市"), new City("新疆维吾尔族自治区", "阿拉尔市"), new City("新疆维吾尔族自治区", "阿拉尔市") }; private static String[] items = { "AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG", "HHH", "III", "JJJ", "KKK", "LLL", "MMM", "NNN", "OOO", "PPP", "QQQ", "RRR", "SSS", "TTT", "UUU", "VVV", "WWW", "XXX", "YYY", "ZZZ", "aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk", "ll", "mm", "nn", "oo", "pp", "qq", "rr", "ss", "tt", "uu", "vv", "ww", "xx", "yy", "zz", "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vw", "xyz", "Jacob", "雅各布", "Michael", "迈克尔", "Ethan", "伊桑", "Joshua", "乔舒亚", "Alexander", "亚历山大", "Anthony", "安东尼", "William", "威廉", "Christopher", "克里斯托弗", "Jayden", "杰顿", "Andrew", "安德鲁", "Joseph", "约瑟夫", "David", "大卫", "Noad", "诺阿", "Aiden", "艾丹", "James", "詹姆斯", "Ryan", "赖恩", "Logan", "洛根", "John", "约翰", "Nathan", "内森", "Elijah", "伊莱贾", "Christian", "克里斯琴", "Gabriel", "加布里尔", "Benjamin", "本杰明", "Jonathan", "乔纳森", "Tyler", "泰勒", "Samuel", "塞缪尔", "Nicholas", "尼古拉斯", "Gavin", "加文", "Dylan", "迪兰", "Jackson", "杰克逊", "Brandon", "布兰顿", "Caleb", "凯勒布", "Brandon", "布兰顿", "Mason", "梅森", "Angel", "安吉尔", "Isaac", "艾萨克", "Evan", "埃文", "Jack", "杰克", "Kevin", "凯文", "Jose", "乔斯", "Isaiah", "艾塞亚", "Luke", "卢克", "Landon", "兰登", "Justin", "贾斯可", "Lucas", "卢卡斯", "Zachary", "扎克里", "Jordan", "乔丹", "Robert", "罗伯特", "Aaron", "艾伦", "Brayden", "布雷登", "Thomas", "托马斯", "Cameron", "卡梅伦", "Hunter", "亨特", "Austin", "奥斯汀", "Adrian", "艾德里安", "Connor", "康纳", "Owen", "欧文", "Aidan", "艾丹", "Jason", "贾森", "Julian", "朱利安", "Wyatt", "怀亚特", "Charles", "查尔斯", "Luis", "路易斯", "Carter", "卡特", "Juan", "胡安", "Chase", "蔡斯", "Diego", "迪格", "Jeremiah", "杰里迈亚", "Brody", "布罗迪", "Zavier", "泽维尔", "Adam", "亚当", "Liam", "利亚姆", "Hayden", "海顿", "Jesus", "杰西斯", "Ian", "伊恩", "Tristan", "特里斯坦", "Sean", "肖恩", "Cole", "科尔", "Alex", "亚历克斯", "Eric", "埃里克", "Brian", "布赖恩", "Jaden", "杰登", "Carson", "卡森", "Blake", "布莱克", "Ayden", "艾登", "Cooper", "库珀", "Dominic", "多米尼克", "Brady", "布雷迪", "Caden", "凯登", "Josiah", "乔塞亚", "Kyle", "凯尔", "Colton", "克尔顿", "Kaden", "凯登", "Eli", "伊莱" }; /** * 保留两位小数 */ private static DecimalFormat df = new DecimalFormat("#.00"); /** * 生成Column name <p> 每种类型生成100列,列名:数据类型+num * * @param dataTypeEnum 数据类型 */ public static String randomKey(DataTypeEnum dataTypeEnum) { // Json格式数据生成10列,以免数据列过多,导入elastic search有问题 int num = dataTypeEnum == DataTypeEnum.Json ? ThreadLocalRandom.current().nextInt(CommonConstants.JSON_MAX_NUMBER) : ThreadLocalRandom.current().nextInt(CommonConstants.COLUMN_MAX_NUMBER); return dataTypeEnum.getKeyName() + num; } public static String generateKey(DataTypeEnum dataTypeEnum, int num) { return dataTypeEnum.getKeyName() + num; } public static String[] randomStringArray() { String[] array = new String[ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH)]; for (int i = 0; i < array.length; i++) { array[i] = items[ThreadLocalRandom.current().nextInt(items.length)]; } return array; } public static double[] randomNumberArray() { double[] array = new double[ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH)]; for (int i = 0; i < array.length; i++) { array[i] = randomNumberValue(); } return array; } public static boolean[] randomBoolArray() { boolean[] array = new boolean[ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH)]; for (int i = 0; i < array.length; i++) { array[i] = randomBoolValue(); } return array; } /** * 产生一个给定长度的随机字符串 */ public static String randomStringValue(int numItems) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < numItems; i++) { sb.append(CHARS[ThreadLocalRandom.current().nextInt(CHARS.length)]); } return sb.toString(); } /** * 产生一个给定长度的字符串 */ public static String randomStringValue(int numItems, char[] chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < numItems; i++) { sb.append(chars[ThreadLocalRandom.current().nextInt(chars.length)]); } return sb.toString(); } /** * 随机Bool <p> 0~10000的随机数 */ public static double randomNumberValue() { String number = df.format(ThreadLocalRandom.current().nextDouble(10000)); return Double.parseDouble(number); } /** * 随机Bool */ public static boolean randomBoolValue() { return ThreadLocalRandom.current().nextInt(10) % 2 == 0; } /** * 随机日期 <p> 距离now() 0~30天的日期 */ public static Date randomDateValue() { LocalDateTime localDateTime = LocalDateTime.now() .minusDays(ThreadLocalRandom.current().nextInt(30)); ZoneId zone = ZoneId.systemDefault(); Instant instant = localDateTime.atZone(zone).toInstant(); return Date.from(instant); } /** * 根据数据类型,随机生成数据 * * @param dataTypeEnum 数据类型 */ public static String randomValue(DataTypeEnum dataTypeEnum) { try { switch (dataTypeEnum) { case String: return randomStringValue(ThreadLocalRandom.current().nextInt(1, 20)); case Number: return String.valueOf(randomNumberValue()); case Bool: return String.valueOf(randomBoolValue()); case Date: return String.valueOf(randomDateValue().getTime()); case StringArray: JSONArray strArray = new JSONArray(); for (int i = 0; i < ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH); i++) { strArray.put(items[ThreadLocalRandom.current().nextInt(items.length)]); } return strArray.toString(); case NumberArray: JSONArray numArray = new JSONArray(); for (int i = 0; i < ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH); i++) { numArray.put(randomNumberValue()); } return numArray.toString(); case BoolArray: JSONArray boolArray = new JSONArray(); for (int i = 0; i < ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH); i++) { boolArray.put(randomBoolValue()); } return boolArray.toString(); case Json: City city = cities[ThreadLocalRandom.current().nextInt(cities.length)]; JSONObject jsonObject = new JSONObject(); jsonObject.put("value", randomStringValue(10, CHARS)); jsonObject.put("province", city.province); jsonObject.put("city", city.city); return jsonObject.toString(); default: return randomStringValue(10); } } catch (Exception e) { log.error("randomValue with exception: {}, type: {}", e.getMessage(), dataTypeEnum); } return ""; } @AllArgsConstructor static class City { private String province; private String city; } }
BowenSun90/hbase-elasticsearch
hbase-elastic-common/src/main/java/com/alex/space/common/KeyValueGenerator.java
3,736
/** * 产生一个给定长度的随机字符串 */
block_comment
zh-cn
package com.alex.space.common; import java.text.DecimalFormat; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.concurrent.ThreadLocalRandom; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.codehaus.jettison.json.JSONArray; import org.codehaus.jettison.json.JSONObject; /** * 生成Key和value * * @author Alex Created by Alex on 2018/9/9. */ @Slf4j public class KeyValueGenerator { private static char[] CHARS = "abcdefghijklmnopqrstuvwxyz1234567890" .toCharArray(); private static char[] SHORT_CHARS = "abcde".toCharArray(); private static int ARRAY_MAX_LENGTH = 5; private static City[] cities = { new City("北京市", "北京市"), new City("天津市", "天津市"), new City("重庆市", "重庆市"), new City("上海市", "上海市"), new City("广东省", "广州市"), new City("广东省", "深圳市"), new City("广东省", "汕头市"), new City("广东省", "韶关市"), new City("广东省", "佛山市"), new City("广东省", "湛江市"), new City("广东省", "茂名市"), new City("辽宁省", "沈阳市"), new City("辽宁省", "大连市"), new City("辽宁省", "抚顺市"), new City("辽宁省", "抚顺市"), new City("辽宁省", "丹东市"), new City("辽宁省", "锦州市"), new City("辽宁省", "阜新市"), new City("辽宁省", "葫芦岛市"), new City("江苏省", "南京市"), new City("江苏省", "苏州市"), new City("江苏省", "常州市"), new City("江苏省", "连云港市"), new City("江苏省", "盐城市"), new City("湖北省", "武汉市"), new City("湖北省", "黄石市"), new City("湖北省", "宜昌市"), new City("四川省", "成都市"), new City("四川省", "自贡市"), new City("四川省", "德阳市"), new City("陕西省", "西安市"), new City("陕西省", "铜川市"), new City("陕西省", "延安市"), new City("陕西省", "汉中市"), new City("河北省", "石家庄市"), new City("河北省", "唐山市"), new City("河北省", "秦皇岛市"), new City("河北省", "邯郸市"), new City("山西省", "太原市"), new City("山西省", "大同市"), new City("山西省", "长治市"), new City("山西省", "晋中市"), new City("河南省", "郑州市"), new City("河南省", "开封市"), new City("河南省", "洛阳市"), new City("河南省", "安阳市"), new City("河南省", "新乡市"), new City("吉林省", "长春市"), new City("吉林省", "吉林市"), new City("黑龙江省", "哈尔滨市"), new City("黑龙江省", "齐齐哈尔市"), new City("黑龙江省", "鸡西市"), new City("黑龙江省", "鹤岗市"), new City("内蒙古", "呼和浩特市"), new City("内蒙古", "包头市"), new City("江苏省", "盐城市"), new City("江苏省", "宿迁市"), new City("浙江省", "嘉兴市"), new City("浙江省", "湖州市"), new City("福建省", "福州市"), new City("福建省", "厦门市"), new City("广西壮族自治区", "柳州"), new City("广西壮族自治区", "梧州"), new City("广西壮族自治区", "玉林"), new City("贵州省", "六盘水市"), new City("贵州省", "安顺市"), new City("贵州省", "黔南布依族苗族自治州"), new City("云南省", "昆明市"), new City("西藏自治区", "拉萨市"), new City("西藏自治区", "阿里地区"), new City("甘肃省", "兰州市"), new City("甘肃省", "天水市"), new City("甘肃省", "陇南市"), new City("青海省", "西宁市"), new City("新疆维吾尔族自治区", "乌鲁木齐市"), new City("新疆维吾尔族自治区", "克拉玛依市"), new City("新疆维吾尔族自治区", "阿拉尔市"), new City("新疆维吾尔族自治区", "阿拉尔市") }; private static String[] items = { "AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG", "HHH", "III", "JJJ", "KKK", "LLL", "MMM", "NNN", "OOO", "PPP", "QQQ", "RRR", "SSS", "TTT", "UUU", "VVV", "WWW", "XXX", "YYY", "ZZZ", "aa", "bb", "cc", "dd", "ee", "ff", "gg", "hh", "ii", "jj", "kk", "ll", "mm", "nn", "oo", "pp", "qq", "rr", "ss", "tt", "uu", "vv", "ww", "xx", "yy", "zz", "abc", "def", "ghi", "jkl", "mno", "pqr", "stu", "vw", "xyz", "Jacob", "雅各布", "Michael", "迈克尔", "Ethan", "伊桑", "Joshua", "乔舒亚", "Alexander", "亚历山大", "Anthony", "安东尼", "William", "威廉", "Christopher", "克里斯托弗", "Jayden", "杰顿", "Andrew", "安德鲁", "Joseph", "约瑟夫", "David", "大卫", "Noad", "诺阿", "Aiden", "艾丹", "James", "詹姆斯", "Ryan", "赖恩", "Logan", "洛根", "John", "约翰", "Nathan", "内森", "Elijah", "伊莱贾", "Christian", "克里斯琴", "Gabriel", "加布里尔", "Benjamin", "本杰明", "Jonathan", "乔纳森", "Tyler", "泰勒", "Samuel", "塞缪尔", "Nicholas", "尼古拉斯", "Gavin", "加文", "Dylan", "迪兰", "Jackson", "杰克逊", "Brandon", "布兰顿", "Caleb", "凯勒布", "Brandon", "布兰顿", "Mason", "梅森", "Angel", "安吉尔", "Isaac", "艾萨克", "Evan", "埃文", "Jack", "杰克", "Kevin", "凯文", "Jose", "乔斯", "Isaiah", "艾塞亚", "Luke", "卢克", "Landon", "兰登", "Justin", "贾斯可", "Lucas", "卢卡斯", "Zachary", "扎克里", "Jordan", "乔丹", "Robert", "罗伯特", "Aaron", "艾伦", "Brayden", "布雷登", "Thomas", "托马斯", "Cameron", "卡梅伦", "Hunter", "亨特", "Austin", "奥斯汀", "Adrian", "艾德里安", "Connor", "康纳", "Owen", "欧文", "Aidan", "艾丹", "Jason", "贾森", "Julian", "朱利安", "Wyatt", "怀亚特", "Charles", "查尔斯", "Luis", "路易斯", "Carter", "卡特", "Juan", "胡安", "Chase", "蔡斯", "Diego", "迪格", "Jeremiah", "杰里迈亚", "Brody", "布罗迪", "Zavier", "泽维尔", "Adam", "亚当", "Liam", "利亚姆", "Hayden", "海顿", "Jesus", "杰西斯", "Ian", "伊恩", "Tristan", "特里斯坦", "Sean", "肖恩", "Cole", "科尔", "Alex", "亚历克斯", "Eric", "埃里克", "Brian", "布赖恩", "Jaden", "杰登", "Carson", "卡森", "Blake", "布莱克", "Ayden", "艾登", "Cooper", "库珀", "Dominic", "多米尼克", "Brady", "布雷迪", "Caden", "凯登", "Josiah", "乔塞亚", "Kyle", "凯尔", "Colton", "克尔顿", "Kaden", "凯登", "Eli", "伊莱" }; /** * 保留两位小数 */ private static DecimalFormat df = new DecimalFormat("#.00"); /** * 生成Column name <p> 每种类型生成100列,列名:数据类型+num * * @param dataTypeEnum 数据类型 */ public static String randomKey(DataTypeEnum dataTypeEnum) { // Json格式数据生成10列,以免数据列过多,导入elastic search有问题 int num = dataTypeEnum == DataTypeEnum.Json ? ThreadLocalRandom.current().nextInt(CommonConstants.JSON_MAX_NUMBER) : ThreadLocalRandom.current().nextInt(CommonConstants.COLUMN_MAX_NUMBER); return dataTypeEnum.getKeyName() + num; } public static String generateKey(DataTypeEnum dataTypeEnum, int num) { return dataTypeEnum.getKeyName() + num; } public static String[] randomStringArray() { String[] array = new String[ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH)]; for (int i = 0; i < array.length; i++) { array[i] = items[ThreadLocalRandom.current().nextInt(items.length)]; } return array; } public static double[] randomNumberArray() { double[] array = new double[ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH)]; for (int i = 0; i < array.length; i++) { array[i] = randomNumberValue(); } return array; } public static boolean[] randomBoolArray() { boolean[] array = new boolean[ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH)]; for (int i = 0; i < array.length; i++) { array[i] = randomBoolValue(); } return array; } /** * 产生一 <SUF>*/ public static String randomStringValue(int numItems) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < numItems; i++) { sb.append(CHARS[ThreadLocalRandom.current().nextInt(CHARS.length)]); } return sb.toString(); } /** * 产生一个给定长度的字符串 */ public static String randomStringValue(int numItems, char[] chars) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < numItems; i++) { sb.append(chars[ThreadLocalRandom.current().nextInt(chars.length)]); } return sb.toString(); } /** * 随机Bool <p> 0~10000的随机数 */ public static double randomNumberValue() { String number = df.format(ThreadLocalRandom.current().nextDouble(10000)); return Double.parseDouble(number); } /** * 随机Bool */ public static boolean randomBoolValue() { return ThreadLocalRandom.current().nextInt(10) % 2 == 0; } /** * 随机日期 <p> 距离now() 0~30天的日期 */ public static Date randomDateValue() { LocalDateTime localDateTime = LocalDateTime.now() .minusDays(ThreadLocalRandom.current().nextInt(30)); ZoneId zone = ZoneId.systemDefault(); Instant instant = localDateTime.atZone(zone).toInstant(); return Date.from(instant); } /** * 根据数据类型,随机生成数据 * * @param dataTypeEnum 数据类型 */ public static String randomValue(DataTypeEnum dataTypeEnum) { try { switch (dataTypeEnum) { case String: return randomStringValue(ThreadLocalRandom.current().nextInt(1, 20)); case Number: return String.valueOf(randomNumberValue()); case Bool: return String.valueOf(randomBoolValue()); case Date: return String.valueOf(randomDateValue().getTime()); case StringArray: JSONArray strArray = new JSONArray(); for (int i = 0; i < ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH); i++) { strArray.put(items[ThreadLocalRandom.current().nextInt(items.length)]); } return strArray.toString(); case NumberArray: JSONArray numArray = new JSONArray(); for (int i = 0; i < ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH); i++) { numArray.put(randomNumberValue()); } return numArray.toString(); case BoolArray: JSONArray boolArray = new JSONArray(); for (int i = 0; i < ThreadLocalRandom.current().nextInt(ARRAY_MAX_LENGTH); i++) { boolArray.put(randomBoolValue()); } return boolArray.toString(); case Json: City city = cities[ThreadLocalRandom.current().nextInt(cities.length)]; JSONObject jsonObject = new JSONObject(); jsonObject.put("value", randomStringValue(10, CHARS)); jsonObject.put("province", city.province); jsonObject.put("city", city.city); return jsonObject.toString(); default: return randomStringValue(10); } } catch (Exception e) { log.error("randomValue with exception: {}, type: {}", e.getMessage(), dataTypeEnum); } return ""; } @AllArgsConstructor static class City { private String province; private String city; } }
1
29
1
51000_8
package org.bran.module; import java.awt.Font; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.bran.db.DBOperation; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.title.TextTitle; import org.jfree.data.general.DefaultPieDataset; /** * *<p>Title: MyChartPanel.java</p> *<p>Description:图标显示面板 </p> * @author BranSummer * @date 2017年6月4日 */ public class MyChartPanel extends JPanel { //ChartPanel private ChartPanel chartPanel; //列表框 private JList list; String[] elements={"图书类型饼图","读者类型图","借阅条形图"}; /** * constructor */ public MyChartPanel(DBOperation db){ super(); //分割面板 竖直分割 JSplitPane sp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); this.add(sp); //创建列表框 JScrollPane leftPanel=new JScrollPane(); list=new JList<String>(elements); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { //TODO } }); leftPanel.setViewportView(list); //创建图表面板 //创建一个默认的饼图 ResultSet rs=null; DefaultPieDataset pdSet=new DefaultPieDataset(); // pdSet.setValue("计算机", 50); // pdSet.setValue("小说", 80); // pdSet.setValue("文学", 30); // pdSet.setValue("艺术", 20); try { rs=db.executeQuery("select booksort,count(booksort) as count from book group by booksort"); while(rs.next()){ pdSet.setValue(rs.getString("booksort"), rs.getInt("count")); } } catch (SQLException e) { e.printStackTrace(); } JFreeChart chart=ChartFactory.createPieChart("demo", pdSet, true,true,false); PiePlot plot=(PiePlot) chart.getPlot(); plot.setLabelFont(new Font("黑体", Font.PLAIN, 20)); TextTitle textTitle = chart.getTitle(); textTitle.setFont(new Font("黑体", Font.PLAIN, 20)); chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12)); chartPanel=new ChartPanel(chart); //加入分割面板 sp.add(leftPanel, JSplitPane.LEFT); sp.add(chartPanel, JSplitPane.RIGHT); } public static void main(String[] args) { JFrame test=new JFrame("test"); test.setSize(600, 400); test.getContentPane().add(new MyChartPanel(new DBOperation())); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); } }
BranSummer/library-management-sys
src/main/java/org/bran/module/MyChartPanel.java
911
//创建一个默认的饼图
line_comment
zh-cn
package org.bran.module; import java.awt.Font; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.bran.db.DBOperation; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.title.TextTitle; import org.jfree.data.general.DefaultPieDataset; /** * *<p>Title: MyChartPanel.java</p> *<p>Description:图标显示面板 </p> * @author BranSummer * @date 2017年6月4日 */ public class MyChartPanel extends JPanel { //ChartPanel private ChartPanel chartPanel; //列表框 private JList list; String[] elements={"图书类型饼图","读者类型图","借阅条形图"}; /** * constructor */ public MyChartPanel(DBOperation db){ super(); //分割面板 竖直分割 JSplitPane sp=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); this.add(sp); //创建列表框 JScrollPane leftPanel=new JScrollPane(); list=new JList<String>(elements); list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent arg0) { //TODO } }); leftPanel.setViewportView(list); //创建图表面板 //创建 <SUF> ResultSet rs=null; DefaultPieDataset pdSet=new DefaultPieDataset(); // pdSet.setValue("计算机", 50); // pdSet.setValue("小说", 80); // pdSet.setValue("文学", 30); // pdSet.setValue("艺术", 20); try { rs=db.executeQuery("select booksort,count(booksort) as count from book group by booksort"); while(rs.next()){ pdSet.setValue(rs.getString("booksort"), rs.getInt("count")); } } catch (SQLException e) { e.printStackTrace(); } JFreeChart chart=ChartFactory.createPieChart("demo", pdSet, true,true,false); PiePlot plot=(PiePlot) chart.getPlot(); plot.setLabelFont(new Font("黑体", Font.PLAIN, 20)); TextTitle textTitle = chart.getTitle(); textTitle.setFont(new Font("黑体", Font.PLAIN, 20)); chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12)); chartPanel=new ChartPanel(chart); //加入分割面板 sp.add(leftPanel, JSplitPane.LEFT); sp.add(chartPanel, JSplitPane.RIGHT); } public static void main(String[] args) { JFrame test=new JFrame("test"); test.setSize(600, 400); test.getContentPane().add(new MyChartPanel(new DBOperation())); test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); test.setVisible(true); } }
1
11
1
61463_73
package client; import java.awt.Font; import java.awt.TextField; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.SocketException; import java.util.Optional; import server.Message; import server.MessageType; import server.Player; import server.Point; import server.ServerConfig; import util.GuiUtils; import javafx.application.Application; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.RadioButton; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextInputDialog; import javafx.scene.control.TitledPane; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.FlowPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; /** * @version V1.0 * @Date: 2019/8/20 * @Description:五子棋在线游戏用户界面主窗口 * @Project: 网络编程技术 * @Copyright: All rights reserved */ public class Chess5GUI extends Application { Chess5Pane pane;//五子棋盘 Label lbl_name;//用于显示玩家信息 Label lbl_status, lbl_jifen, lbl_duanwei; ChoiceBox<String> cBox;//用于擂主列表 Button btn_join_game, btn_join_host, btn_update_host, btn_challenge, btn_alpha, btn_guanzhan, btn_update_player, btn_renew, btn_send,btn_preview,btn_img; RadioButton rbtn_white, rbtn_black; static Player player; static DatagramSocket s = null; TextArea ta_qunliao, ta_siliao, ta_sends; ComboBox<String> cBox_send_type; ComboBox<String> cBox_player;//用于玩家列表 public Chess5GUI() { try { // start(new Stage()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void start(Stage stage) throws Exception { // TODO Auto-generated method stub pane = new Chess5Pane(); pane.setMouseTransparent(true);//屏蔽棋盘上鼠标事件 //pane.setCompetition(competition); FlowPane fPane_01 = new FlowPane(); fPane_01.setAlignment(Pos.BOTTOM_CENTER); // for(int n=0; n<5; n++){ // Circle c = new Circle(20-n*2, Color.BLACK); // fPane_01.getChildren().add(c); // } Button btn_join_game = new Button("加入游戏"); btn_join_game.setOnAction(this::btnJoinGameHandler); fPane_01.getChildren().add(btn_join_game); // for(int n=0; n<5; n++){ // Circle c = new Circle(12+n*2, Color.WHITE); // fPane_01.getChildren().add(c); // } FlowPane fPane_title = new FlowPane(); fPane_title.setAlignment(Pos.BOTTOM_CENTER); fPane_title.setMinHeight(70); Label lb_title = new Label("五 子 棋 游 戏 "); lb_title.setStyle("-fx-font-size: 40;-fx-text-fill: white;"); fPane_title.getChildren().add(lb_title); btn_join_host = new Button("加入擂台"); btn_join_host.setDisable(true); btn_join_host.setOnAction(this::btnJoinHostHandler); btn_update_host = new Button("更新擂台"); btn_update_host.setDisable(true); btn_update_host.setOnAction(this::btnUpdateHostHandler); cBox = new ChoiceBox<String>(); btn_challenge = new Button("挑战"); btn_challenge.setDisable(true); btn_challenge.setOnAction(this::btnChallengeHandler); btn_renew = new Button("重新准备"); btn_renew.setDisable(true); btn_renew.setOnAction(this::btnRenewHandler); btn_alpha = new Button("人机对战"); btn_alpha.setDisable(true); btn_alpha.setOnAction(this::btnAlphaHandler); btn_update_player = new Button("更新在线玩家列表"); btn_update_player.setDisable(true); btn_update_player.setOnAction(this::btnUpdatePlayerHandler); Label player_name = new Label("在线玩家列表:"); player_name.setStyle("-fx-text-fill: white;-fx-font-size: 20;"); cBox_player = new ComboBox<String>(); btn_guanzhan = new Button("观战"); btn_guanzhan.setDisable(true); btn_guanzhan.setOnAction(this::btnGuanzhanHandler); ToggleGroup tg = new ToggleGroup(); rbtn_white = new RadioButton("白子先手"); rbtn_white.setToggleGroup(tg); rbtn_white.setSelected(true); rbtn_white.setStyle("-fx-text-fill: white;"); rbtn_black = new RadioButton("黑子后手"); rbtn_black.setToggleGroup(tg); rbtn_black.setStyle("-fx-text-fill: white;"); FlowPane fPane_02 = new FlowPane(btn_join_host, btn_update_host, cBox, btn_challenge, btn_alpha); fPane_02.setAlignment(Pos.CENTER); fPane_02.setHgap(40); //fPane_02.setStyle(""); FlowPane fPane_03 = new FlowPane(rbtn_white, rbtn_black, btn_renew); fPane_03.setAlignment(Pos.CENTER); fPane_03.setHgap(40); fPane_03.setStyle("-fx-border-width:5;-fx-padding: 8;"); FlowPane fPane_04 = new FlowPane(btn_update_player, player_name, cBox_player, btn_guanzhan); fPane_04.setAlignment(Pos.CENTER); fPane_04.setHgap(40); fPane_04.setStyle("-fx-border-width:5;-fx-padding: 8;"); lbl_status = new Label("未加入游戏......"); FlowPane fPane_status = new FlowPane(lbl_status); fPane_status.setAlignment(Pos.CENTER); fPane_status.setStyle("-fx-border-color:#f5cc8a;-fx-background-color:#fff4e1;-fx-border-width:5;-fx-font-size: 24;"); VBox box = new VBox(fPane_title, fPane_01); box.setAlignment(Pos.CENTER); box.setSpacing(10); box.setStyle("-fx-border-color:#65420a;-fx-background-color:#55270f;-fx-border-width:5"); VBox boxChildren = new VBox(); boxChildren.setAlignment(Pos.CENTER); boxChildren.setSpacing(10); boxChildren.setStyle("-fx-border-color:#65420a;-fx-background-color:#55270f;-fx-border-width:5"); //Label lbl_player_name = new Label("昵称 :高手搜索"); lbl_name = new Label("昵称 :......"); lbl_jifen = new Label("积分: ....."); lbl_duanwei = new Label("段位:......"); VBox vb_player_info = new VBox(lbl_name, lbl_jifen, lbl_duanwei); vb_player_info.setStyle("-fx-border-color:#f5cc8a;-fx-background-color:#f5cc8a;-fx-border-width:5;-fx-font-size: 24;"); /* 群聊窗口 */ ta_qunliao = new TextArea(); ta_qunliao.setPrefSize(400, 180); ScrollPane pane_qunliao_info = new ScrollPane(ta_qunliao); TitledPane pane_qunliao = new TitledPane("大厅", pane_qunliao_info); /* 私聊窗口 */ ta_siliao = new TextArea(); ta_siliao.setPrefSize(400, 180); ScrollPane pane_siliao_info = new ScrollPane(ta_siliao); TitledPane pane_siliao = new TitledPane("聊天窗口", pane_siliao_info); /* 发送窗口 */ ta_sends = new TextArea(); ta_sends.setPrefSize(400, 100); ScrollPane pane_sends_info = new ScrollPane(ta_sends); TitledPane pane_sends = new TitledPane("发送窗口", pane_sends_info); /* 发送和按钮事件 */ btn_send = new Button("发送"); btn_send.setDisable(true); btn_send.setOnAction(this::btnSend); /* 关闭和按钮事件 */ // Button btn_close = new Button("关闭"); // btn_close.setOnAction(this::btnClose); /* 发送图片和按钮事件 */ btn_img = new Button("选择图片"); btn_img.setDisable(true); //btn_img.setOnAction(this::btnImg); btn_preview = new Button("预览图片"); btn_preview.setDisable(true); //btn_preview.setOnAction(this::btnPreview); /* 窗口抖动 */ // Button btn_shake = new Button("窗口抖动"); //btn_shake.setOnAction(this::btnShake); /* 按钮大小 */ btn_send.setPrefSize(70, 30); // btn_close.setPrefSize(70, 30); cBox_send_type = new ComboBox<String>(); cBox_send_type.getItems().addAll("群聊"); cBox_send_type.setValue("群聊"); //cBox_send_type.getItems(). FlowPane pane_sends_zujian = new FlowPane(); pane_sends_zujian.setPadding(new Insets(11, 12, 13, 14)); pane_sends_zujian.setHgap(5);//设置控件之间的垂直间隔距离 pane_sends_zujian.setVgap(5);//设置控件之间的水平间隔距离 pane_sends_zujian.getChildren().addAll(btn_send, cBox_send_type, btn_img, btn_preview); VBox vb_r = new VBox(vb_player_info, pane_qunliao, pane_siliao, pane_sends, pane_sends_zujian); HBox hbox = new HBox(); VBox vb_l = new VBox(fPane_02, fPane_03, fPane_04, fPane_status, pane); //hbox.getChildren(box,pane_02); hbox.getChildren().add(vb_l); //hbox.getChildren().add(boxChildren); hbox.getChildren().add(vb_r); box.getChildren().add(hbox); Scene scene = new Scene(box, 1000, 888); stage.setScene(scene); stage.setTitle("五子棋"); stage.show(); } /** * 当玩家点击“加入游戏”按钮后,会响应该方法进行处理:会弹出对话框输入玩家的昵称;发送加入游戏的信息给服务器, * 并等待服务器回复确认,同时更新擂台列表信息 * * @param e */ public void btnJoinGameHandler(ActionEvent e) { //pane.setMouseTransparent(false); String PlayerName = Chess5Utils.getPlayName(); try { System.out.println(ClientConfig.LOCAL_ADDR); s = new DatagramSocket(ClientConfig.LOCAL_ADDR); //SocketAddress LOCAL_ADDR = new InetSocketAddress("127.0.0.1", 5005); //System.out.println(LOCAL_ADDR); //s = new DatagramSocket(LOCAL_ADDR); player = new Player(PlayerName, ClientConfig.LOCAL_ADDR, 0); Message joinGame = new Message(); joinGame.setMsgType(1); joinGame.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(joinGame), Message.convertToBytes(joinGame).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 DatagramPacket pin = new DatagramPacket(new byte[1024], 1024); s.receive(pin);//接收数据 //System.out.println(pin); Message msg = (Message) Message.convertToObj(pin.getData(), 0, pin.getLength()); if (msg.getStatus() == 1) { Chess5Utils.showAlert("加入成功!"); lbl_name.setText("昵称 :" + PlayerName); lbl_status.setText("空闲中......."); lbl_jifen.setText("积分: " + player.getScore()); lbl_duanwei.setText("段位: 菜鸟"); } else { Chess5Utils.showAlert("加入失败,昵称已经存在!"); } String list_PlayerName[] = msg.getContent().toString().split(":"); for (int i = 0; i < list_PlayerName.length; i++) { cBox.getItems().addAll(list_PlayerName[i]); } cBox.setValue(list_PlayerName[0]); //s.close(); // Platform.runLater(new Runnable() { // public void run() { // btn_join_game.setDisable(true); // } // }); btn_challenge.setDisable(false); btn_join_host.setDisable(false); btn_alpha.setDisable(false); btn_guanzhan.setDisable(false); btn_renew.setDisable(false); btn_update_player.setDisable(false); btn_update_host.setDisable(false); btn_send.setDisable(false); btn_preview.setDisable(false); btn_img.setDisable(false); Chess5ClientThread t1 = new Chess5ClientThread( s, pane, lbl_status, cBox, btn_join_game, btn_join_host, btn_update_host, btn_challenge, rbtn_white, rbtn_black, player, ta_qunliao, ta_siliao, btn_guanzhan, cBox_player, btn_renew, btn_alpha, lbl_jifen, lbl_duanwei, cBox_send_type ); t1.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnJoinHostHandler(ActionEvent e) { try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message JoinHost = new Message(); JoinHost.setMsgType(2); JoinHost.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(JoinHost), Message.convertToBytes(JoinHost).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 // DatagramPacket pin = new DatagramPacket(new byte[512],512); // s.receive(pin);//接收数据 // Message msg = (Message) Message.convertToObj(pin.getData(),0,pin.getLength()); // if(msg.getStatus() == 1){ // Chess5Utils.showAlert("加入擂台成功!"); // cBox.getItems().addAll(player.getName()); // btn_join_host.setDisable(true); //// DatagramPacket challenge = new DatagramPacket(new byte[512],512); //// s.receive(challenge);//接收数据 //// Message challenge_msg = (Message) Message.convertToObj(challenge.getData(),0,challenge.getLength()); //// System.out.println(challenge_msg.toString()); //// Chess5Thread t1 = new Chess5Thread(s); //// t1.start(); // }else{ // Chess5Utils.showAlert("加入擂台失败!"); // } //System.out.println("close"); //s.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnUpdateHostHandler(ActionEvent e) { try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message UpdateHost = new Message(); UpdateHost.setMsgType(5); UpdateHost.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(UpdateHost), Message.convertToBytes(UpdateHost).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnChallengeHandler(ActionEvent e) { try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message Challenge = new Message(); Challenge.setMsgType(MessageType.CHALLENGE); if (rbtn_white.isSelected()) { player.setColor(2); } else { player.setColor(1); } Challenge.setFromPlayer(player); //System.out.println(rbtn_white.isSelected()); String Challenge_Name = cBox.getValue(); // Challenge.setToPlayer(ServerConfig.getPlayer(Challenge_Name)); Challenge.setContent(Challenge_Name); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(Challenge), Message.convertToBytes(Challenge).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 // DatagramPacket pin = new DatagramPacket(new byte[512],512); // s.receive(pin);//接收数据 // Message rspmsg = (Message) Message.convertToObj(pin.getData(),0,pin.getLength()); // System.out.println(rspmsg); // if(rspmsg.getStatus() == 1){ // Chess5Utils.showAlert("挑战开始!"); // btn_challenge.setDisable(false); // }else{ // Chess5Utils.showAlert("挑战失败!"); // } // //s.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnAlphaHandler(ActionEvent e) { //setMouseTransparent(true); try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message Alpha = new Message(); Alpha.setMsgType(MessageType.Alpha); if (rbtn_white.isSelected()) { player.setColor(2); } else { player.setColor(1); } Alpha.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(Alpha), Message.convertToBytes(Alpha).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnSend(ActionEvent e) { //setMouseTransparent(true); try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message message = new Message(); String sent_type = cBox_send_type.getValue(); String msg_content = ta_sends.getText(); //String Sends_Name = cBox_player.getValue(); Player Send_Player = new Player(sent_type, null, 0); // System.out.println(sent_type); // System.out.println(msg_sent); message.setFromPlayer(player); if (sent_type.equals("群聊")) { message.setMsgType(MessageType.Message_qunliao); } else { message.setMsgType(MessageType.Message_siliao); message.setToPlayer(Send_Player); ta_siliao.appendText(Chess5Utils.getTimeString() + " " + player.getName() + " : " + msg_content + "\n"); } //System.out.println(rbtn_white.isSelected()); // String Challenge_Name = cBox.getValue(); // Challenge.setToPlayer(ServerConfig.getPlayer(Challenge_Name)); message.setContent(msg_content); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(message), Message.convertToBytes(message).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 ta_sends.clear(); // DatagramPacket pin = new DatagramPacket(new byte[512],512); // s.receive(pin);//接收数据 // Message rspmsg = (Message) Message.convertToObj(pin.getData(),0,pin.getLength()); // System.out.println(rspmsg); // if(rspmsg.getStatus() == 1){ // Chess5Utils.showAlert("挑战开始!"); // btn_challenge.setDisable(false); // }else{ // Chess5Utils.showAlert("挑战失败!"); // } // //s.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnGuanzhanHandler(ActionEvent e) { //setMouseTransparent(true); try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message message = new Message(); message.setMsgType(MessageType.GUANZHAN); String guanzhan_player = cBox_player.getValue(); Player Guanzhan_Player = new Player(guanzhan_player, null, 0); message.setFromPlayer(player); message.setToPlayer(Guanzhan_Player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(message), Message.convertToBytes(message).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnUpdatePlayerHandler(ActionEvent e) { //setMouseTransparent(true); try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message UpdatePlayer = new Message(); UpdatePlayer.setMsgType(MessageType.UPDATE_PLAYER); UpdatePlayer.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(UpdatePlayer), Message.convertToBytes(UpdatePlayer).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnRenewHandler(ActionEvent e) { pane.clear(); btn_alpha.setDisable(false); btn_challenge.setDisable(false); btn_guanzhan.setDisable(false); lbl_status.setText("空闲中......."); cBox_send_type.getItems().clear(); cBox_send_type.getItems().add("群聊"); cBox_send_type.setValue("群聊"); } public static void main(String[] args) { //Chess5Utils.denglu(); Application.launch(args); } }
Brant-lzh/Chess5_online
src/client/Chess5GUI.java
6,028
//发送数据
line_comment
zh-cn
package client; import java.awt.Font; import java.awt.TextField; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.SocketException; import java.util.Optional; import server.Message; import server.MessageType; import server.Player; import server.Point; import server.ServerConfig; import util.GuiUtils; import javafx.application.Application; import javafx.application.Platform; import javafx.event.ActionEvent; import javafx.geometry.HPos; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.ChoiceBox; import javafx.scene.control.ComboBox; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.RadioButton; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextInputDialog; import javafx.scene.control.TitledPane; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.FlowPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; /** * @version V1.0 * @Date: 2019/8/20 * @Description:五子棋在线游戏用户界面主窗口 * @Project: 网络编程技术 * @Copyright: All rights reserved */ public class Chess5GUI extends Application { Chess5Pane pane;//五子棋盘 Label lbl_name;//用于显示玩家信息 Label lbl_status, lbl_jifen, lbl_duanwei; ChoiceBox<String> cBox;//用于擂主列表 Button btn_join_game, btn_join_host, btn_update_host, btn_challenge, btn_alpha, btn_guanzhan, btn_update_player, btn_renew, btn_send,btn_preview,btn_img; RadioButton rbtn_white, rbtn_black; static Player player; static DatagramSocket s = null; TextArea ta_qunliao, ta_siliao, ta_sends; ComboBox<String> cBox_send_type; ComboBox<String> cBox_player;//用于玩家列表 public Chess5GUI() { try { // start(new Stage()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void start(Stage stage) throws Exception { // TODO Auto-generated method stub pane = new Chess5Pane(); pane.setMouseTransparent(true);//屏蔽棋盘上鼠标事件 //pane.setCompetition(competition); FlowPane fPane_01 = new FlowPane(); fPane_01.setAlignment(Pos.BOTTOM_CENTER); // for(int n=0; n<5; n++){ // Circle c = new Circle(20-n*2, Color.BLACK); // fPane_01.getChildren().add(c); // } Button btn_join_game = new Button("加入游戏"); btn_join_game.setOnAction(this::btnJoinGameHandler); fPane_01.getChildren().add(btn_join_game); // for(int n=0; n<5; n++){ // Circle c = new Circle(12+n*2, Color.WHITE); // fPane_01.getChildren().add(c); // } FlowPane fPane_title = new FlowPane(); fPane_title.setAlignment(Pos.BOTTOM_CENTER); fPane_title.setMinHeight(70); Label lb_title = new Label("五 子 棋 游 戏 "); lb_title.setStyle("-fx-font-size: 40;-fx-text-fill: white;"); fPane_title.getChildren().add(lb_title); btn_join_host = new Button("加入擂台"); btn_join_host.setDisable(true); btn_join_host.setOnAction(this::btnJoinHostHandler); btn_update_host = new Button("更新擂台"); btn_update_host.setDisable(true); btn_update_host.setOnAction(this::btnUpdateHostHandler); cBox = new ChoiceBox<String>(); btn_challenge = new Button("挑战"); btn_challenge.setDisable(true); btn_challenge.setOnAction(this::btnChallengeHandler); btn_renew = new Button("重新准备"); btn_renew.setDisable(true); btn_renew.setOnAction(this::btnRenewHandler); btn_alpha = new Button("人机对战"); btn_alpha.setDisable(true); btn_alpha.setOnAction(this::btnAlphaHandler); btn_update_player = new Button("更新在线玩家列表"); btn_update_player.setDisable(true); btn_update_player.setOnAction(this::btnUpdatePlayerHandler); Label player_name = new Label("在线玩家列表:"); player_name.setStyle("-fx-text-fill: white;-fx-font-size: 20;"); cBox_player = new ComboBox<String>(); btn_guanzhan = new Button("观战"); btn_guanzhan.setDisable(true); btn_guanzhan.setOnAction(this::btnGuanzhanHandler); ToggleGroup tg = new ToggleGroup(); rbtn_white = new RadioButton("白子先手"); rbtn_white.setToggleGroup(tg); rbtn_white.setSelected(true); rbtn_white.setStyle("-fx-text-fill: white;"); rbtn_black = new RadioButton("黑子后手"); rbtn_black.setToggleGroup(tg); rbtn_black.setStyle("-fx-text-fill: white;"); FlowPane fPane_02 = new FlowPane(btn_join_host, btn_update_host, cBox, btn_challenge, btn_alpha); fPane_02.setAlignment(Pos.CENTER); fPane_02.setHgap(40); //fPane_02.setStyle(""); FlowPane fPane_03 = new FlowPane(rbtn_white, rbtn_black, btn_renew); fPane_03.setAlignment(Pos.CENTER); fPane_03.setHgap(40); fPane_03.setStyle("-fx-border-width:5;-fx-padding: 8;"); FlowPane fPane_04 = new FlowPane(btn_update_player, player_name, cBox_player, btn_guanzhan); fPane_04.setAlignment(Pos.CENTER); fPane_04.setHgap(40); fPane_04.setStyle("-fx-border-width:5;-fx-padding: 8;"); lbl_status = new Label("未加入游戏......"); FlowPane fPane_status = new FlowPane(lbl_status); fPane_status.setAlignment(Pos.CENTER); fPane_status.setStyle("-fx-border-color:#f5cc8a;-fx-background-color:#fff4e1;-fx-border-width:5;-fx-font-size: 24;"); VBox box = new VBox(fPane_title, fPane_01); box.setAlignment(Pos.CENTER); box.setSpacing(10); box.setStyle("-fx-border-color:#65420a;-fx-background-color:#55270f;-fx-border-width:5"); VBox boxChildren = new VBox(); boxChildren.setAlignment(Pos.CENTER); boxChildren.setSpacing(10); boxChildren.setStyle("-fx-border-color:#65420a;-fx-background-color:#55270f;-fx-border-width:5"); //Label lbl_player_name = new Label("昵称 :高手搜索"); lbl_name = new Label("昵称 :......"); lbl_jifen = new Label("积分: ....."); lbl_duanwei = new Label("段位:......"); VBox vb_player_info = new VBox(lbl_name, lbl_jifen, lbl_duanwei); vb_player_info.setStyle("-fx-border-color:#f5cc8a;-fx-background-color:#f5cc8a;-fx-border-width:5;-fx-font-size: 24;"); /* 群聊窗口 */ ta_qunliao = new TextArea(); ta_qunliao.setPrefSize(400, 180); ScrollPane pane_qunliao_info = new ScrollPane(ta_qunliao); TitledPane pane_qunliao = new TitledPane("大厅", pane_qunliao_info); /* 私聊窗口 */ ta_siliao = new TextArea(); ta_siliao.setPrefSize(400, 180); ScrollPane pane_siliao_info = new ScrollPane(ta_siliao); TitledPane pane_siliao = new TitledPane("聊天窗口", pane_siliao_info); /* 发送窗口 */ ta_sends = new TextArea(); ta_sends.setPrefSize(400, 100); ScrollPane pane_sends_info = new ScrollPane(ta_sends); TitledPane pane_sends = new TitledPane("发送窗口", pane_sends_info); /* 发送和按钮事件 */ btn_send = new Button("发送"); btn_send.setDisable(true); btn_send.setOnAction(this::btnSend); /* 关闭和按钮事件 */ // Button btn_close = new Button("关闭"); // btn_close.setOnAction(this::btnClose); /* 发送图片和按钮事件 */ btn_img = new Button("选择图片"); btn_img.setDisable(true); //btn_img.setOnAction(this::btnImg); btn_preview = new Button("预览图片"); btn_preview.setDisable(true); //btn_preview.setOnAction(this::btnPreview); /* 窗口抖动 */ // Button btn_shake = new Button("窗口抖动"); //btn_shake.setOnAction(this::btnShake); /* 按钮大小 */ btn_send.setPrefSize(70, 30); // btn_close.setPrefSize(70, 30); cBox_send_type = new ComboBox<String>(); cBox_send_type.getItems().addAll("群聊"); cBox_send_type.setValue("群聊"); //cBox_send_type.getItems(). FlowPane pane_sends_zujian = new FlowPane(); pane_sends_zujian.setPadding(new Insets(11, 12, 13, 14)); pane_sends_zujian.setHgap(5);//设置控件之间的垂直间隔距离 pane_sends_zujian.setVgap(5);//设置控件之间的水平间隔距离 pane_sends_zujian.getChildren().addAll(btn_send, cBox_send_type, btn_img, btn_preview); VBox vb_r = new VBox(vb_player_info, pane_qunliao, pane_siliao, pane_sends, pane_sends_zujian); HBox hbox = new HBox(); VBox vb_l = new VBox(fPane_02, fPane_03, fPane_04, fPane_status, pane); //hbox.getChildren(box,pane_02); hbox.getChildren().add(vb_l); //hbox.getChildren().add(boxChildren); hbox.getChildren().add(vb_r); box.getChildren().add(hbox); Scene scene = new Scene(box, 1000, 888); stage.setScene(scene); stage.setTitle("五子棋"); stage.show(); } /** * 当玩家点击“加入游戏”按钮后,会响应该方法进行处理:会弹出对话框输入玩家的昵称;发送加入游戏的信息给服务器, * 并等待服务器回复确认,同时更新擂台列表信息 * * @param e */ public void btnJoinGameHandler(ActionEvent e) { //pane.setMouseTransparent(false); String PlayerName = Chess5Utils.getPlayName(); try { System.out.println(ClientConfig.LOCAL_ADDR); s = new DatagramSocket(ClientConfig.LOCAL_ADDR); //SocketAddress LOCAL_ADDR = new InetSocketAddress("127.0.0.1", 5005); //System.out.println(LOCAL_ADDR); //s = new DatagramSocket(LOCAL_ADDR); player = new Player(PlayerName, ClientConfig.LOCAL_ADDR, 0); Message joinGame = new Message(); joinGame.setMsgType(1); joinGame.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(joinGame), Message.convertToBytes(joinGame).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 DatagramPacket pin = new DatagramPacket(new byte[1024], 1024); s.receive(pin);//接收数据 //System.out.println(pin); Message msg = (Message) Message.convertToObj(pin.getData(), 0, pin.getLength()); if (msg.getStatus() == 1) { Chess5Utils.showAlert("加入成功!"); lbl_name.setText("昵称 :" + PlayerName); lbl_status.setText("空闲中......."); lbl_jifen.setText("积分: " + player.getScore()); lbl_duanwei.setText("段位: 菜鸟"); } else { Chess5Utils.showAlert("加入失败,昵称已经存在!"); } String list_PlayerName[] = msg.getContent().toString().split(":"); for (int i = 0; i < list_PlayerName.length; i++) { cBox.getItems().addAll(list_PlayerName[i]); } cBox.setValue(list_PlayerName[0]); //s.close(); // Platform.runLater(new Runnable() { // public void run() { // btn_join_game.setDisable(true); // } // }); btn_challenge.setDisable(false); btn_join_host.setDisable(false); btn_alpha.setDisable(false); btn_guanzhan.setDisable(false); btn_renew.setDisable(false); btn_update_player.setDisable(false); btn_update_host.setDisable(false); btn_send.setDisable(false); btn_preview.setDisable(false); btn_img.setDisable(false); Chess5ClientThread t1 = new Chess5ClientThread( s, pane, lbl_status, cBox, btn_join_game, btn_join_host, btn_update_host, btn_challenge, rbtn_white, rbtn_black, player, ta_qunliao, ta_siliao, btn_guanzhan, cBox_player, btn_renew, btn_alpha, lbl_jifen, lbl_duanwei, cBox_send_type ); t1.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnJoinHostHandler(ActionEvent e) { try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message JoinHost = new Message(); JoinHost.setMsgType(2); JoinHost.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(JoinHost), Message.convertToBytes(JoinHost).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 // DatagramPacket pin = new DatagramPacket(new byte[512],512); // s.receive(pin);//接收数据 // Message msg = (Message) Message.convertToObj(pin.getData(),0,pin.getLength()); // if(msg.getStatus() == 1){ // Chess5Utils.showAlert("加入擂台成功!"); // cBox.getItems().addAll(player.getName()); // btn_join_host.setDisable(true); //// DatagramPacket challenge = new DatagramPacket(new byte[512],512); //// s.receive(challenge);//接收数据 //// Message challenge_msg = (Message) Message.convertToObj(challenge.getData(),0,challenge.getLength()); //// System.out.println(challenge_msg.toString()); //// Chess5Thread t1 = new Chess5Thread(s); //// t1.start(); // }else{ // Chess5Utils.showAlert("加入擂台失败!"); // } //System.out.println("close"); //s.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnUpdateHostHandler(ActionEvent e) { try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message UpdateHost = new Message(); UpdateHost.setMsgType(5); UpdateHost.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(UpdateHost), Message.convertToBytes(UpdateHost).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送 <SUF> } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnChallengeHandler(ActionEvent e) { try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message Challenge = new Message(); Challenge.setMsgType(MessageType.CHALLENGE); if (rbtn_white.isSelected()) { player.setColor(2); } else { player.setColor(1); } Challenge.setFromPlayer(player); //System.out.println(rbtn_white.isSelected()); String Challenge_Name = cBox.getValue(); // Challenge.setToPlayer(ServerConfig.getPlayer(Challenge_Name)); Challenge.setContent(Challenge_Name); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(Challenge), Message.convertToBytes(Challenge).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 // DatagramPacket pin = new DatagramPacket(new byte[512],512); // s.receive(pin);//接收数据 // Message rspmsg = (Message) Message.convertToObj(pin.getData(),0,pin.getLength()); // System.out.println(rspmsg); // if(rspmsg.getStatus() == 1){ // Chess5Utils.showAlert("挑战开始!"); // btn_challenge.setDisable(false); // }else{ // Chess5Utils.showAlert("挑战失败!"); // } // //s.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnAlphaHandler(ActionEvent e) { //setMouseTransparent(true); try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message Alpha = new Message(); Alpha.setMsgType(MessageType.Alpha); if (rbtn_white.isSelected()) { player.setColor(2); } else { player.setColor(1); } Alpha.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(Alpha), Message.convertToBytes(Alpha).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnSend(ActionEvent e) { //setMouseTransparent(true); try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message message = new Message(); String sent_type = cBox_send_type.getValue(); String msg_content = ta_sends.getText(); //String Sends_Name = cBox_player.getValue(); Player Send_Player = new Player(sent_type, null, 0); // System.out.println(sent_type); // System.out.println(msg_sent); message.setFromPlayer(player); if (sent_type.equals("群聊")) { message.setMsgType(MessageType.Message_qunliao); } else { message.setMsgType(MessageType.Message_siliao); message.setToPlayer(Send_Player); ta_siliao.appendText(Chess5Utils.getTimeString() + " " + player.getName() + " : " + msg_content + "\n"); } //System.out.println(rbtn_white.isSelected()); // String Challenge_Name = cBox.getValue(); // Challenge.setToPlayer(ServerConfig.getPlayer(Challenge_Name)); message.setContent(msg_content); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(message), Message.convertToBytes(message).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 ta_sends.clear(); // DatagramPacket pin = new DatagramPacket(new byte[512],512); // s.receive(pin);//接收数据 // Message rspmsg = (Message) Message.convertToObj(pin.getData(),0,pin.getLength()); // System.out.println(rspmsg); // if(rspmsg.getStatus() == 1){ // Chess5Utils.showAlert("挑战开始!"); // btn_challenge.setDisable(false); // }else{ // Chess5Utils.showAlert("挑战失败!"); // } // //s.close(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnGuanzhanHandler(ActionEvent e) { //setMouseTransparent(true); try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message message = new Message(); message.setMsgType(MessageType.GUANZHAN); String guanzhan_player = cBox_player.getValue(); Player Guanzhan_Player = new Player(guanzhan_player, null, 0); message.setFromPlayer(player); message.setToPlayer(Guanzhan_Player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(message), Message.convertToBytes(message).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnUpdatePlayerHandler(ActionEvent e) { //setMouseTransparent(true); try { //DatagramSocket s = new DatagramSocket(ClientConfig.LOCAL_ADDR); Message UpdatePlayer = new Message(); UpdatePlayer.setMsgType(MessageType.UPDATE_PLAYER); UpdatePlayer.setFromPlayer(player); DatagramPacket pout = new DatagramPacket(Message.convertToBytes(UpdatePlayer), Message.convertToBytes(UpdatePlayer).length, ClientConfig.SERVER_ADDR); s.send(pout);//发送数据 } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } public void btnRenewHandler(ActionEvent e) { pane.clear(); btn_alpha.setDisable(false); btn_challenge.setDisable(false); btn_guanzhan.setDisable(false); lbl_status.setText("空闲中......."); cBox_send_type.getItems().clear(); cBox_send_type.getItems().add("群聊"); cBox_send_type.setValue("群聊"); } public static void main(String[] args) { //Chess5Utils.denglu(); Application.launch(args); } }
1
6
1
54147_0
/* 彩票游戏 假设你想开发一个玩彩票的游戏,程序随机地产生一个两位数的彩票,提示用户输入一个两位数,然后按照下面的规则判定用户是否能赢。 1)如果用户输入的数匹配彩票的实际顺序,奖金10 000美元。 2)如果用户输入的所有数字匹配彩票的所有数字,但顺序不一致,奖金 3 000美元。 3)如果用户输入的一个数字仅满足顺序情况下匹配彩票的一个数字,奖金1 000美元。 4)如果用户输入的一个数字仅满足非顺序情况下匹配彩票的一个数字,奖金500美元。 5)如果用户输入的数字没有匹配任何一个数字,则彩票作废。 提示:使用Math.random() 产生随机数 Math.random() 产生[0,1)范围的随机值 Math.random() * 90:[0,90) 即;Math.random() * 90 + 10:[10,100) 即得到 [10,99] 使用(int)(Math.random() * 90 + 10)产生一个两位数的随机数 */ import java.util.Scanner; public class TestCaiPiao { public static void main(String[] args){ int number = (int)(Math.random()*90 + 10); int numberShi = number / 10; int numberGe = number % 10; Scanner input = new Scanner(System.in); System.out.println("请输入一个两位数"); int guess = input.nextInt(); int guessShi = guess / 10; int guessGe = guess % 10; if(number == guess){ System.out.println("奖金10000美金"); }else if(numberShi == guessGe && numberGe == guessShi){ System.out.println("奖金3000美元"); }else if(numberShi == guessShi || numberGe == guessGe){ System.out.println("奖金1000美元"); }else if (numberShi == guessGe || numberGe == guessShi){ System.out.print("奖金500美元"); }else{ System.out.println("抱歉 您没有中将"); } System.out.println("中奖号码是;" + number); } }
Brayden-9/firstexercises.java
src/TestCaiPiao.java
595
/* 彩票游戏 假设你想开发一个玩彩票的游戏,程序随机地产生一个两位数的彩票,提示用户输入一个两位数,然后按照下面的规则判定用户是否能赢。 1)如果用户输入的数匹配彩票的实际顺序,奖金10 000美元。 2)如果用户输入的所有数字匹配彩票的所有数字,但顺序不一致,奖金 3 000美元。 3)如果用户输入的一个数字仅满足顺序情况下匹配彩票的一个数字,奖金1 000美元。 4)如果用户输入的一个数字仅满足非顺序情况下匹配彩票的一个数字,奖金500美元。 5)如果用户输入的数字没有匹配任何一个数字,则彩票作废。 提示:使用Math.random() 产生随机数 Math.random() 产生[0,1)范围的随机值 Math.random() * 90:[0,90) 即;Math.random() * 90 + 10:[10,100) 即得到 [10,99] 使用(int)(Math.random() * 90 + 10)产生一个两位数的随机数 */
block_comment
zh-cn
/* 彩票游 <SUF>*/ import java.util.Scanner; public class TestCaiPiao { public static void main(String[] args){ int number = (int)(Math.random()*90 + 10); int numberShi = number / 10; int numberGe = number % 10; Scanner input = new Scanner(System.in); System.out.println("请输入一个两位数"); int guess = input.nextInt(); int guessShi = guess / 10; int guessGe = guess % 10; if(number == guess){ System.out.println("奖金10000美金"); }else if(numberShi == guessGe && numberGe == guessShi){ System.out.println("奖金3000美元"); }else if(numberShi == guessShi || numberGe == guessGe){ System.out.println("奖金1000美元"); }else if (numberShi == guessGe || numberGe == guessShi){ System.out.print("奖金500美元"); }else{ System.out.println("抱歉 您没有中将"); } System.out.println("中奖号码是;" + number); } }
0
433
0
29984_1
package cn.breadnicecat.candycraftce.item.items; import cn.breadnicecat.candycraftce.item.CItems; import cn.breadnicecat.candycraftce.misc.muitlblocks.VectorPortalShape; import cn.breadnicecat.candycraftce.utils.LevelUtils; import cn.breadnicecat.candycraftce.utils.TickUtils; import com.google.common.collect.Lists; import com.mojang.serialization.JsonOps; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.GsonHelper; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.List; import java.util.Optional; import static cn.breadnicecat.candycraftce.block.blocks.CaramelPortalBlock.CONFIG; import static net.minecraft.ChatFormatting.RED; import static net.minecraft.ChatFormatting.YELLOW; /** * Created in 2023/7/30 14:12 * Project: candycraftce * * @author <a href="https://github.com/Bread-Nicecat">Bread_NiceCat</a> * <p> * <hr> **/ public class IIDebugItem extends Item { private final String FUN_ORD_KEY = "fun_ord"; private final String USED_TIMES_KEY = "used_times"; private final Component CUR_FUN = Component.literal("当前模式: ").withStyle(ChatFormatting.LIGHT_PURPLE); private final Component SWITCH_FUN = Component.literal("对空气 SHIFT+右键 切换模式").withStyle(YELLOW); public IIDebugItem() { super(new Properties().stacksTo(1).rarity(Rarity.EPIC)); } @Override public @NotNull InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand usedHand) { ItemStack item = player.getItemInHand(usedHand); if (level.isClientSide) return InteractionResultHolder.success(item); if (player.isShiftKeyDown() && usedHand == InteractionHand.MAIN_HAND) { //切换模式 CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); if (player.isShiftKeyDown()) { if (--ord < 0) { ord = FUNCTIONS.size() - 1; } } else if (++ord >= FUNCTIONS.size()) { ord = 0; } IIIDebugFunction fun = FUNCTIONS.get(ord); player.sendSystemMessage(CUR_FUN.copy().append(fun.getName())); tag.putInt(FUN_ORD_KEY, ord); return InteractionResultHolder.consume(item); } return InteractionResultHolder.fail(item); } @Override public @NotNull InteractionResult useOn(UseOnContext pContext) { Player player = pContext.getPlayer(); if (player == null || !player.isCreative()) { return InteractionResult.FAIL; } Level level = pContext.getLevel(); if (level.isClientSide()) { return InteractionResult.SUCCESS; } BlockPos pos = pContext.getClickedPos(); ItemStack item = pContext.getItemInHand(); CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); IIIDebugFunction fun = FUNCTIONS.get(ord); String ord_s = String.valueOf(ord); CompoundTag nbt = tag.getCompound(ord_s); fun.onRightClickOn(level.getBlockState(pos), (ServerLevel) level, pos, pContext.getClickedFace(), player, item, nbt); tag.put(ord_s, nbt); { int used = (tag.contains(USED_TIMES_KEY) ? tag.getInt(USED_TIMES_KEY) : 0) + 1; tag.putInt(USED_TIMES_KEY, used); if (used > 0 && used % 666 == 0) { LevelUtils.spawnItemEntity(level, pos, CItems.RECORD_o.getDefaultInstance().setHoverName(Component.literal("头发").withStyle(RED))); LevelUtils.spawnItemEntity(level, pos, Items.JUKEBOX.getDefaultInstance()); level.playSound(player, pos, SoundEvents.FIREWORK_ROCKET_LARGE_BLAST_FAR, SoundSource.BLOCKS); player.sendSystemMessage(Component.literal("随着你日日夜夜的对Mod进行调试, 你逐渐觉得使用用Debug工具越来越顺手了。 嗯?什么东西掉下来了?").withStyle(YELLOW)); } } return InteractionResult.CONSUME; } public boolean canAttackBlock(@NotNull BlockState pState, @NotNull Level pLevel, @NotNull BlockPos pPos, @NotNull Player pPlayer) { if (!pLevel.isClientSide()) { ItemStack item = pPlayer.getItemInHand(InteractionHand.MAIN_HAND); CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); IIIDebugFunction fun = FUNCTIONS.get(ord); String ord_s = String.valueOf(ord); CompoundTag nbt = tag.getCompound(ord_s); fun.onLeftClickOn(pState, (ServerLevel) pLevel, pPos, pPlayer, item, nbt); tag.put(ord_s, nbt); } return false; } public boolean isFoil(@NotNull ItemStack pStack) { return true; } @Override public void appendHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced) { CompoundTag root = stack.getOrCreateTag(); int ord = getFunOrd(root); IIIDebugFunction fun = FUNCTIONS.get(ord); tooltips.add(CUR_FUN.copy().append(fun.getName())); tooltips.add(SWITCH_FUN); CompoundTag nbt = root.getCompound(String.valueOf(ord)); fun.appendExtraHoverText(stack, level, tooltips, isAdvanced, nbt); } @Override public @NotNull Component getName(ItemStack stack) { return super.getName(stack).copy().append("(").append(FUNCTIONS.get(getFunOrd(stack.getOrCreateTag())).getName()).append(")"); } private int getFunOrd(CompoundTag tag) { return tag.getInt(FUN_ORD_KEY) % FUNCTIONS.size(); } //============================================================// private static final IIIDebugFunction DF_RELATIVE = new IIIDebugFunction() { private static final String ZERO = "zero"; private static final Component NAME = Component.literal("坐标测算"); private static final Component SET = Component.literal("左键 调零").withStyle(YELLOW); private static final Component RESET = Component.literal("SHIFT+左键 清除调零").withStyle(YELLOW); private static final Component GET = Component.literal("右键 获取相对坐标").withStyle(YELLOW); @Override public Component getName() { return NAME; } @Override public void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { int[] zero = nbt.contains(ZERO) ? nbt.getIntArray(ZERO) : new int[]{0, 0, 0}; player.sendSystemMessage(NAME.copy().append(" 坐标: %d,%d,%d".formatted(pos.getX() - zero[0], pos.getY() - zero[1], pos.getZ() - zero[2])).withStyle(YELLOW)); } @Override public void onLeftClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull Player player, ItemStack item, CompoundTag nbt) { int[] po = player.isShiftKeyDown() ? new int[]{0, 0, 0} : new int[]{pos.getX(), pos.getY(), pos.getZ()}; nbt.putIntArray(ZERO, po); player.sendSystemMessage(NAME.copy().append(" 调零: %s".formatted(Arrays.toString(po))).withStyle(ChatFormatting.GREEN)); } @Override public void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { tooltips.add(SET); tooltips.add(RESET); tooltips.add(GET); int[] zero = nbt.contains(ZERO) ? nbt.getIntArray(ZERO) : new int[]{0, 0, 0}; tooltips.add(Component.literal("当前零点: " + Arrays.toString(zero)).withStyle(ChatFormatting.GREEN)); } }; private static final IIIDebugFunction DF_DETECT_PORTAL = new IIIDebugFunction() { private static final Component NAME = Component.literal("传送门测试"); private static final Component TEST = Component.literal("右键传送门框架检测").withStyle(YELLOW); @Override public Component getName() { return NAME; } @Override public void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { long stt = System.nanoTime(); Optional<VectorPortalShape> portal = Optional.empty(); if (CONFIG.isFrame(state)) { portal = VectorPortalShape.findPortalOnFrame(level, pos, CONFIG); } float ttt = (System.nanoTime() - stt) / 1E6F; if (portal.isPresent()) { VectorPortalShape shape = portal.get(); level.playSound(null, pos, SoundEvents.NOTE_BLOCK_PLING.value(), SoundSource.BLOCKS); player.sendSystemMessage(NAME.copy().append(" 框架已找到").withStyle(ChatFormatting.GREEN)); //colorful outputs player.sendSystemMessage(NbtUtils.toPrettyComponent(JsonOps.COMPRESSED.convertTo(NbtOps.INSTANCE, GsonHelper.parse(shape.toString())))); // player.sendSystemMessage(Component.literal(shape.toString())); } else { level.playSound(null, pos, SoundEvents.FIRE_EXTINGUISH, SoundSource.BLOCKS); player.sendSystemMessage(NAME.copy().append(" 未找到正确的传送门框架").withStyle(RED)); } player.sendSystemMessage(NAME.copy().append(" 共耗时: " + ttt + " ms (" + ttt / TickUtils.MS_PER_TICK + " tick)").withStyle(ChatFormatting.GOLD)); } @Override public void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { tooltips.add(TEST); } }; //============================================================// public static final List<IIIDebugFunction> FUNCTIONS = Lists.newArrayList( DF_RELATIVE, DF_DETECT_PORTAL ); public interface IIIDebugFunction { Component getName(); default void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { } default void onLeftClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull Player player, ItemStack item, CompoundTag nbt) { } default void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { } } }
Bread-NiceCat/CandyCraftCE
common/src/main/java/cn/breadnicecat/candycraftce/item/items/IIDebugItem.java
3,075
//切换模式
line_comment
zh-cn
package cn.breadnicecat.candycraftce.item.items; import cn.breadnicecat.candycraftce.item.CItems; import cn.breadnicecat.candycraftce.misc.muitlblocks.VectorPortalShape; import cn.breadnicecat.candycraftce.utils.LevelUtils; import cn.breadnicecat.candycraftce.utils.TickUtils; import com.google.common.collect.Lists; import com.mojang.serialization.JsonOps; import net.minecraft.ChatFormatting; import net.minecraft.core.BlockPos; import net.minecraft.core.Direction; import net.minecraft.nbt.CompoundTag; import net.minecraft.nbt.NbtOps; import net.minecraft.nbt.NbtUtils; import net.minecraft.network.chat.Component; import net.minecraft.server.level.ServerLevel; import net.minecraft.sounds.SoundEvents; import net.minecraft.sounds.SoundSource; import net.minecraft.util.GsonHelper; import net.minecraft.world.InteractionHand; import net.minecraft.world.InteractionResult; import net.minecraft.world.InteractionResultHolder; import net.minecraft.world.entity.player.Player; import net.minecraft.world.item.*; import net.minecraft.world.item.context.UseOnContext; import net.minecraft.world.level.Level; import net.minecraft.world.level.block.state.BlockState; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.List; import java.util.Optional; import static cn.breadnicecat.candycraftce.block.blocks.CaramelPortalBlock.CONFIG; import static net.minecraft.ChatFormatting.RED; import static net.minecraft.ChatFormatting.YELLOW; /** * Created in 2023/7/30 14:12 * Project: candycraftce * * @author <a href="https://github.com/Bread-Nicecat">Bread_NiceCat</a> * <p> * <hr> **/ public class IIDebugItem extends Item { private final String FUN_ORD_KEY = "fun_ord"; private final String USED_TIMES_KEY = "used_times"; private final Component CUR_FUN = Component.literal("当前模式: ").withStyle(ChatFormatting.LIGHT_PURPLE); private final Component SWITCH_FUN = Component.literal("对空气 SHIFT+右键 切换模式").withStyle(YELLOW); public IIDebugItem() { super(new Properties().stacksTo(1).rarity(Rarity.EPIC)); } @Override public @NotNull InteractionResultHolder<ItemStack> use(Level level, Player player, InteractionHand usedHand) { ItemStack item = player.getItemInHand(usedHand); if (level.isClientSide) return InteractionResultHolder.success(item); if (player.isShiftKeyDown() && usedHand == InteractionHand.MAIN_HAND) { //切换 <SUF> CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); if (player.isShiftKeyDown()) { if (--ord < 0) { ord = FUNCTIONS.size() - 1; } } else if (++ord >= FUNCTIONS.size()) { ord = 0; } IIIDebugFunction fun = FUNCTIONS.get(ord); player.sendSystemMessage(CUR_FUN.copy().append(fun.getName())); tag.putInt(FUN_ORD_KEY, ord); return InteractionResultHolder.consume(item); } return InteractionResultHolder.fail(item); } @Override public @NotNull InteractionResult useOn(UseOnContext pContext) { Player player = pContext.getPlayer(); if (player == null || !player.isCreative()) { return InteractionResult.FAIL; } Level level = pContext.getLevel(); if (level.isClientSide()) { return InteractionResult.SUCCESS; } BlockPos pos = pContext.getClickedPos(); ItemStack item = pContext.getItemInHand(); CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); IIIDebugFunction fun = FUNCTIONS.get(ord); String ord_s = String.valueOf(ord); CompoundTag nbt = tag.getCompound(ord_s); fun.onRightClickOn(level.getBlockState(pos), (ServerLevel) level, pos, pContext.getClickedFace(), player, item, nbt); tag.put(ord_s, nbt); { int used = (tag.contains(USED_TIMES_KEY) ? tag.getInt(USED_TIMES_KEY) : 0) + 1; tag.putInt(USED_TIMES_KEY, used); if (used > 0 && used % 666 == 0) { LevelUtils.spawnItemEntity(level, pos, CItems.RECORD_o.getDefaultInstance().setHoverName(Component.literal("头发").withStyle(RED))); LevelUtils.spawnItemEntity(level, pos, Items.JUKEBOX.getDefaultInstance()); level.playSound(player, pos, SoundEvents.FIREWORK_ROCKET_LARGE_BLAST_FAR, SoundSource.BLOCKS); player.sendSystemMessage(Component.literal("随着你日日夜夜的对Mod进行调试, 你逐渐觉得使用用Debug工具越来越顺手了。 嗯?什么东西掉下来了?").withStyle(YELLOW)); } } return InteractionResult.CONSUME; } public boolean canAttackBlock(@NotNull BlockState pState, @NotNull Level pLevel, @NotNull BlockPos pPos, @NotNull Player pPlayer) { if (!pLevel.isClientSide()) { ItemStack item = pPlayer.getItemInHand(InteractionHand.MAIN_HAND); CompoundTag tag = item.getOrCreateTag(); int ord = getFunOrd(tag); IIIDebugFunction fun = FUNCTIONS.get(ord); String ord_s = String.valueOf(ord); CompoundTag nbt = tag.getCompound(ord_s); fun.onLeftClickOn(pState, (ServerLevel) pLevel, pPos, pPlayer, item, nbt); tag.put(ord_s, nbt); } return false; } public boolean isFoil(@NotNull ItemStack pStack) { return true; } @Override public void appendHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced) { CompoundTag root = stack.getOrCreateTag(); int ord = getFunOrd(root); IIIDebugFunction fun = FUNCTIONS.get(ord); tooltips.add(CUR_FUN.copy().append(fun.getName())); tooltips.add(SWITCH_FUN); CompoundTag nbt = root.getCompound(String.valueOf(ord)); fun.appendExtraHoverText(stack, level, tooltips, isAdvanced, nbt); } @Override public @NotNull Component getName(ItemStack stack) { return super.getName(stack).copy().append("(").append(FUNCTIONS.get(getFunOrd(stack.getOrCreateTag())).getName()).append(")"); } private int getFunOrd(CompoundTag tag) { return tag.getInt(FUN_ORD_KEY) % FUNCTIONS.size(); } //============================================================// private static final IIIDebugFunction DF_RELATIVE = new IIIDebugFunction() { private static final String ZERO = "zero"; private static final Component NAME = Component.literal("坐标测算"); private static final Component SET = Component.literal("左键 调零").withStyle(YELLOW); private static final Component RESET = Component.literal("SHIFT+左键 清除调零").withStyle(YELLOW); private static final Component GET = Component.literal("右键 获取相对坐标").withStyle(YELLOW); @Override public Component getName() { return NAME; } @Override public void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { int[] zero = nbt.contains(ZERO) ? nbt.getIntArray(ZERO) : new int[]{0, 0, 0}; player.sendSystemMessage(NAME.copy().append(" 坐标: %d,%d,%d".formatted(pos.getX() - zero[0], pos.getY() - zero[1], pos.getZ() - zero[2])).withStyle(YELLOW)); } @Override public void onLeftClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull Player player, ItemStack item, CompoundTag nbt) { int[] po = player.isShiftKeyDown() ? new int[]{0, 0, 0} : new int[]{pos.getX(), pos.getY(), pos.getZ()}; nbt.putIntArray(ZERO, po); player.sendSystemMessage(NAME.copy().append(" 调零: %s".formatted(Arrays.toString(po))).withStyle(ChatFormatting.GREEN)); } @Override public void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { tooltips.add(SET); tooltips.add(RESET); tooltips.add(GET); int[] zero = nbt.contains(ZERO) ? nbt.getIntArray(ZERO) : new int[]{0, 0, 0}; tooltips.add(Component.literal("当前零点: " + Arrays.toString(zero)).withStyle(ChatFormatting.GREEN)); } }; private static final IIIDebugFunction DF_DETECT_PORTAL = new IIIDebugFunction() { private static final Component NAME = Component.literal("传送门测试"); private static final Component TEST = Component.literal("右键传送门框架检测").withStyle(YELLOW); @Override public Component getName() { return NAME; } @Override public void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { long stt = System.nanoTime(); Optional<VectorPortalShape> portal = Optional.empty(); if (CONFIG.isFrame(state)) { portal = VectorPortalShape.findPortalOnFrame(level, pos, CONFIG); } float ttt = (System.nanoTime() - stt) / 1E6F; if (portal.isPresent()) { VectorPortalShape shape = portal.get(); level.playSound(null, pos, SoundEvents.NOTE_BLOCK_PLING.value(), SoundSource.BLOCKS); player.sendSystemMessage(NAME.copy().append(" 框架已找到").withStyle(ChatFormatting.GREEN)); //colorful outputs player.sendSystemMessage(NbtUtils.toPrettyComponent(JsonOps.COMPRESSED.convertTo(NbtOps.INSTANCE, GsonHelper.parse(shape.toString())))); // player.sendSystemMessage(Component.literal(shape.toString())); } else { level.playSound(null, pos, SoundEvents.FIRE_EXTINGUISH, SoundSource.BLOCKS); player.sendSystemMessage(NAME.copy().append(" 未找到正确的传送门框架").withStyle(RED)); } player.sendSystemMessage(NAME.copy().append(" 共耗时: " + ttt + " ms (" + ttt / TickUtils.MS_PER_TICK + " tick)").withStyle(ChatFormatting.GOLD)); } @Override public void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { tooltips.add(TEST); } }; //============================================================// public static final List<IIIDebugFunction> FUNCTIONS = Lists.newArrayList( DF_RELATIVE, DF_DETECT_PORTAL ); public interface IIIDebugFunction { Component getName(); default void onRightClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, Direction clickedFace, @NotNull Player player, ItemStack item, CompoundTag nbt) { } default void onLeftClickOn(@NotNull BlockState state, @NotNull ServerLevel level, @NotNull BlockPos pos, @NotNull Player player, ItemStack item, CompoundTag nbt) { } default void appendExtraHoverText(ItemStack stack, @Nullable Level level, List<Component> tooltips, TooltipFlag isAdvanced, CompoundTag nbt) { } } }
1
6
1
39582_2
package swingDemo; import javax.swing.*; public class JComboxDemo { public static void main(String[] args) { // 创建窗口 JFrame jframe=new JFrame("选择界面"); // 创建面板 JPanel jPanel=new JPanel(); // 创建标签 JLabel jLabel=new JLabel("证件类型"); // 创建下拉列表框 JComboBox com=new JComboBox(); // 在下拉列表框中添加自组 com.addItem("军人证"); com.addItem("身份证"); com.addItem("学生证"); com.addItem("士兵证"); // 将组键添加到面板中 jPanel.add(jLabel); jPanel.add(com); // 将面板添加到窗口中 jframe.add(jPanel); jframe.setSize(300,400); jframe.setVisible(true); jframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jframe.setLocationRelativeTo(null); } }
Breeze1203/study-essay
javaEE/src/swingDemo/JComboxDemo.java
233
// 创建标签
line_comment
zh-cn
package swingDemo; import javax.swing.*; public class JComboxDemo { public static void main(String[] args) { // 创建窗口 JFrame jframe=new JFrame("选择界面"); // 创建面板 JPanel jPanel=new JPanel(); // 创建 <SUF> JLabel jLabel=new JLabel("证件类型"); // 创建下拉列表框 JComboBox com=new JComboBox(); // 在下拉列表框中添加自组 com.addItem("军人证"); com.addItem("身份证"); com.addItem("学生证"); com.addItem("士兵证"); // 将组键添加到面板中 jPanel.add(jLabel); jPanel.add(com); // 将面板添加到窗口中 jframe.add(jPanel); jframe.setSize(300,400); jframe.setVisible(true); jframe.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); jframe.setLocationRelativeTo(null); } }
1
7
1
13506_10
/*- * << * DBus * == * Copyright (C) 2016 - 2019 Bridata * == * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * >> */ package com.creditease.dbus.heartbeat.util; public class Constants { private Constants() { } public static final String SYS_PROPS_LOG_TYPE = "log.type"; public static final String SYS_PROPS_LOG4J_CONFIG = "log4j.configuration"; public static final String SYS_PROPS_LOG_BASE_PATH = "logs.base.path"; public static final String SYS_PROPS_LOG_HOME = "logs.home"; public static final String CONFIG_DB_KEY = "dbus.conf"; public static final String CONFIG_DB_TYPE_ORA = "oracle"; public static final String CONFIG_DB_TYPE_MYSQL = "mysql"; public static final String CONFIG_DB_TYPE_DB2 = "db2"; public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_SCHEMA_KEY = "schema"; public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_DB_KEY = "DB"; public static final String GLOBAL_CTRL_TOPIC = "global_ctrl_topic"; /** * 安全相关配置 */ public static final String SECURITY_CONFIG_TRUE_VALUE = "kerberos_kafkaACL"; public static final String SECURITY_CONFIG_KEY = "AuthenticationAndAuthorization"; /** * 心跳邮件报警内容 */ public static final String MAIL_HEART_BEAT = "尊敬的先生/女士您好,Dbus心跳监控发现数据线路:{0}发生异常,报警次数:{1},超时次数:{2},请及时处理."; /** * 全量邮件报警内容 */ public static final String MAIL_FULL_PULLER = "尊敬的先生/女士您好,Dbus全量拉取监控发现拉取表:{0}数据时发生异常,报警次数:{1},超时次数:{2},请及时处理."; public static final String MAIL_FULL_PULLER_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;表:{3}</br>" + "&nbsp;&nbsp;版本:{4}</br>" + "&nbsp;&nbsp;报警时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + ",请及时处理.</br></br>" + "详细信息:</br>{7}"; public static final String MAIL_FULL_PULLER_NEW_PROJECT = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目名:{1}</br>" + "&nbsp;&nbsp;数据源:{2}</br>" + "&nbsp;&nbsp;数据库:{3}</br>" + "&nbsp;&nbsp;表:{4}</br>" + "&nbsp;&nbsp;版本:{5}</br>" + "&nbsp;&nbsp;报警时间:{6}</br>" + "&nbsp;&nbsp;报警环境:{7}</br>" + ",请及时处理.</br></br>" + "详细信息:</br>{8}"; /** * 新版心跳邮件报警内容 */ // public static final String MAIL_HEART_BEAT_NEW = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>以下表格中table发生超时,请及时处理.</br></br>{2}"; public static final String MAIL_HEART_BEAT_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;报警时间:{3}</br>" + "&nbsp;&nbsp;报警环境:{4}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{5}</br></br>{6}"; /** * 数据库主备延时报警邮件内容 */ // public static final String MAIL_MASTER_SLAVE_DELAY = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>所在主备数据库延时过长发生超时,请及时处理."; public static final String MAIL_MASTER_SLAVE_DELAY = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;主备延时:{3}</br>" + "&nbsp;&nbsp;主库时间:{4}</br>" + "&nbsp;&nbsp;备库时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + "&nbsp;&nbsp;报警时间:{7}</br>" + "请及时处理."; public static final String MAIL_SCHEMA_CHANGE = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;表名:{3}</br>" + "&nbsp;&nbsp;报警时间:{4}</br>" + "&nbsp;&nbsp;报警环境:{5}</br>" + "请及时处理.</br></br>{6}"; /** * 新版心跳邮件报警内容 */ // public static final String MAIL_HEART_BEAT_NEW = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>以下表格中table发生超时,请及时处理.</br></br>{2}"; public static final String MAIL_HEART_BEAT_NEW_PROJECT = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目:{1}</br>" + "&nbsp;&nbsp;拓扑:{2}</br>" + "&nbsp;&nbsp;数据源:{3}</br>" + "&nbsp;&nbsp;数据库:{4}</br>" + "&nbsp;&nbsp;报警时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{7}"; public static final String PROJECT_EXPIRE_TIME = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目名称:{1}</br>" + "&nbsp;&nbsp;有效期至:{2}</br>" + "&nbsp;&nbsp;剩余:{3}天</br>" + "&nbsp;&nbsp;报警环境:{4}</br>" + "{5}. 请及时处理.</br>"; public static final String MAIL_MYSQL_MASTER_STATUS = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;报警时间:{2}</br>" + "&nbsp;&nbsp;报警环境:{3}</br>" + "mysql binlog文件号变小,请及时处理."; /** * SINKER心跳邮件报警内容 */ public static final String MAIL_SINKER_HEART_BEAT_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;报警时间:{1}</br>" + "&nbsp;&nbsp;报警环境:{2}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{3}"; }
BriData/DBus
dbus-heartbeat/src/main/java/com/creditease/dbus/heartbeat/util/Constants.java
2,034
/** * SINKER心跳邮件报警内容 */
block_comment
zh-cn
/*- * << * DBus * == * Copyright (C) 2016 - 2019 Bridata * == * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * >> */ package com.creditease.dbus.heartbeat.util; public class Constants { private Constants() { } public static final String SYS_PROPS_LOG_TYPE = "log.type"; public static final String SYS_PROPS_LOG4J_CONFIG = "log4j.configuration"; public static final String SYS_PROPS_LOG_BASE_PATH = "logs.base.path"; public static final String SYS_PROPS_LOG_HOME = "logs.home"; public static final String CONFIG_DB_KEY = "dbus.conf"; public static final String CONFIG_DB_TYPE_ORA = "oracle"; public static final String CONFIG_DB_TYPE_MYSQL = "mysql"; public static final String CONFIG_DB_TYPE_DB2 = "db2"; public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_SCHEMA_KEY = "schema"; public static final String CONFIG_KAFKA_CONTROL_PAYLOAD_DB_KEY = "DB"; public static final String GLOBAL_CTRL_TOPIC = "global_ctrl_topic"; /** * 安全相关配置 */ public static final String SECURITY_CONFIG_TRUE_VALUE = "kerberos_kafkaACL"; public static final String SECURITY_CONFIG_KEY = "AuthenticationAndAuthorization"; /** * 心跳邮件报警内容 */ public static final String MAIL_HEART_BEAT = "尊敬的先生/女士您好,Dbus心跳监控发现数据线路:{0}发生异常,报警次数:{1},超时次数:{2},请及时处理."; /** * 全量邮件报警内容 */ public static final String MAIL_FULL_PULLER = "尊敬的先生/女士您好,Dbus全量拉取监控发现拉取表:{0}数据时发生异常,报警次数:{1},超时次数:{2},请及时处理."; public static final String MAIL_FULL_PULLER_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;表:{3}</br>" + "&nbsp;&nbsp;版本:{4}</br>" + "&nbsp;&nbsp;报警时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + ",请及时处理.</br></br>" + "详细信息:</br>{7}"; public static final String MAIL_FULL_PULLER_NEW_PROJECT = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目名:{1}</br>" + "&nbsp;&nbsp;数据源:{2}</br>" + "&nbsp;&nbsp;数据库:{3}</br>" + "&nbsp;&nbsp;表:{4}</br>" + "&nbsp;&nbsp;版本:{5}</br>" + "&nbsp;&nbsp;报警时间:{6}</br>" + "&nbsp;&nbsp;报警环境:{7}</br>" + ",请及时处理.</br></br>" + "详细信息:</br>{8}"; /** * 新版心跳邮件报警内容 */ // public static final String MAIL_HEART_BEAT_NEW = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>以下表格中table发生超时,请及时处理.</br></br>{2}"; public static final String MAIL_HEART_BEAT_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;报警时间:{3}</br>" + "&nbsp;&nbsp;报警环境:{4}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{5}</br></br>{6}"; /** * 数据库主备延时报警邮件内容 */ // public static final String MAIL_MASTER_SLAVE_DELAY = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>所在主备数据库延时过长发生超时,请及时处理."; public static final String MAIL_MASTER_SLAVE_DELAY = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;主备延时:{3}</br>" + "&nbsp;&nbsp;主库时间:{4}</br>" + "&nbsp;&nbsp;备库时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + "&nbsp;&nbsp;报警时间:{7}</br>" + "请及时处理."; public static final String MAIL_SCHEMA_CHANGE = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;数据库:{2}</br>" + "&nbsp;&nbsp;表名:{3}</br>" + "&nbsp;&nbsp;报警时间:{4}</br>" + "&nbsp;&nbsp;报警环境:{5}</br>" + "请及时处理.</br></br>{6}"; /** * 新版心跳邮件报警内容 */ // public static final String MAIL_HEART_BEAT_NEW = "尊敬的先生/女士您好:</br>&nbsp;&nbsp;Dbus心跳监控发现数据源:{0}</br>&nbsp;&nbsp;schema:{1}</br>以下表格中table发生超时,请及时处理.</br></br>{2}"; public static final String MAIL_HEART_BEAT_NEW_PROJECT = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目:{1}</br>" + "&nbsp;&nbsp;拓扑:{2}</br>" + "&nbsp;&nbsp;数据源:{3}</br>" + "&nbsp;&nbsp;数据库:{4}</br>" + "&nbsp;&nbsp;报警时间:{5}</br>" + "&nbsp;&nbsp;报警环境:{6}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{7}"; public static final String PROJECT_EXPIRE_TIME = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;项目名称:{1}</br>" + "&nbsp;&nbsp;有效期至:{2}</br>" + "&nbsp;&nbsp;剩余:{3}天</br>" + "&nbsp;&nbsp;报警环境:{4}</br>" + "{5}. 请及时处理.</br>"; public static final String MAIL_MYSQL_MASTER_STATUS = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;数据源:{1}</br>" + "&nbsp;&nbsp;报警时间:{2}</br>" + "&nbsp;&nbsp;报警环境:{3}</br>" + "mysql binlog文件号变小,请及时处理."; /** * SIN <SUF>*/ public static final String MAIL_SINKER_HEART_BEAT_NEW = "您好:</br>" + "&nbsp;&nbsp;报警类型:{0}</br>" + "&nbsp;&nbsp;报警时间:{1}</br>" + "&nbsp;&nbsp;报警环境:{2}</br>" + "以下表格中table发生报警,请及时处理.</br></br>{3}"; }
1
33
1
62246_14
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * problem: 一条线路上有 n 个公交车站,假设在到达第 i 个站点之前,车上总共有 x 个乘客,过了该站点后车上总共有 y 个乘客, * 司机会把 y-x 这个数字,即乘客数量变化值 d_i 记录下来,公交车有固定的载客量 g,若有一份司机的开车日志,车上乘客数量的可能情况有多少种 * * 输入:第一行有两个数字 n 和 g,分别表示站点数量及当前撤了的最大载客数量(1 <= n,g <= 1000) * 第二行共 n 个数字,由空格分开,经过第 i 个公交车站后车上乘客的变化数量 d_i (-1000 <= d_i <= 1000) * 输入数据保证从总站出发时乘客数量大于等于 0 * 输出:输出一个数字,即司机从总站出发时,车上乘客数量的可能性个数。 * * 样例输入一: * 4 10 * 1 2 3 4 * 样例输出一: * 1 * * 样例输入二: * 4 5 * 2 -1 2 1 * 样例输出二: * 2 */ class Main{ private int station = 0; // station 个公交车站 private int carSize = 0; // 固定载客量 private int cases = 0; // 可能的情况数 private int[] d_i; // 乘客数量变化值 private int[] person; public static void main(String [] args){ Main m = new Main(); try { m.init(); // m.printPersonRange(); m.findMinCase(); } catch (Exception e) { e.printStackTrace(); } System.out.println(m.cases); } private void init() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); /*========= read first line to get variable n and g =========*/ String firstLine = br.readLine(); String[] first = firstLine.split(" "); station = Integer.valueOf(first[0]); carSize = Integer.valueOf(first[1]); cases = carSize+1; // the maximum cases is carSize + 1 ( from 0 to carSize) /*===========================================================*/ /*========= read second line to get variable d_i and initialize person =========*/ d_i = new int[station]; person = new int[(station+1)*2]; // odd means lower, even means upper String secondLine = br.readLine(); String[] second = secondLine.split(" "); for (int i = 0; i < station; i++) { d_i[i] = Integer.valueOf(second[i]); person[i*2] = 0; person[i*2+1] = carSize; } person[station*2] = 0; person[station*2+1] = carSize; /*========================================================*/ int tmp = 0, tmpMax = carSize, tmpMin = 0; tmp = carSize - d_i[0]; // 算出 P0 的最小最大值 person[0*2] = getMax(0, -diff[0]); person[0*2+1] = getMin(carSize, carSize - diff[0]); for(int gap = 1; gap < station; gap++) { for(int i = gap; i < station + 1; i++) { tmpMax = person[(i-gap)*2+1] + personChanged(i-gap, i); tmpMin = person[(i-gap)*2] + personChanged(i-gap, i); if( i < station) { // 最后一个计算的时候没有额外的约束条件了 tmp = carSize - d_i[i]; tmpMax = getMin(tmp, tmpMax); // 取较小的(即取交集) } if( tmpMax < tmpMin ) { // 若上限小于下限,对应的不等式不成立,说明不存在这种情况 cases = 0; return; } tmpMax = getMin(tmpMax, carSize); person[i*2+1] = getMin(person[i*2+1], tmpMax); tmpMin = getMax(0, tmpMin); person[i*2] = getMax(person[i*2], tmpMin); } } } /** * 求出所有站点可能情况的交集 */ private void findMinCase() { int tmpCase; for(int i = 0; i <= station; i++) { tmpCase = person[i*2+1]-person[i*2]+1; if(cases > tmpCase) { cases = tmpCase; } } } /** * 打印出每个站点的可能的人数范围 * @apiNote 第一个站点为总站 */ private void printPersonRange() { for (int i = 0; i < station+1; i++) { System.out.print( person[i*2] + "-" + person[i*2+1]+" "); } System.out.println(); } /** * 计算从 from (include) 到 to (not include) 站点的人数变化 * @apiNote 第一站的序号为 0 * 例如: * 经过四个站点的人数变化为: d_i = { 1, 2, 3, 4, -2, 3 } * personChanged(1, 5) 计算的值为 2 + 3 + 4 + (-2),返回值为 7 */ private int personChanged(int from, int to) { int p = 0; for(int i = from; i < to; i++) p += d_i[i]; return p; } /** * 取 a,b中的最大值 * @param a * @param b * @return */ private int getMax(int a, int b) { return (a > b) ? a : b; } /** * 取 a,b中的最小值 * @param a * @param b * @return */ private int getMin(int a, int b) { return (a<b) ? a: b; } }
BriFuture/blog-code-example
18-06to09/quesion_buscases/Main.java
1,584
// 取较小的(即取交集)
line_comment
zh-cn
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * problem: 一条线路上有 n 个公交车站,假设在到达第 i 个站点之前,车上总共有 x 个乘客,过了该站点后车上总共有 y 个乘客, * 司机会把 y-x 这个数字,即乘客数量变化值 d_i 记录下来,公交车有固定的载客量 g,若有一份司机的开车日志,车上乘客数量的可能情况有多少种 * * 输入:第一行有两个数字 n 和 g,分别表示站点数量及当前撤了的最大载客数量(1 <= n,g <= 1000) * 第二行共 n 个数字,由空格分开,经过第 i 个公交车站后车上乘客的变化数量 d_i (-1000 <= d_i <= 1000) * 输入数据保证从总站出发时乘客数量大于等于 0 * 输出:输出一个数字,即司机从总站出发时,车上乘客数量的可能性个数。 * * 样例输入一: * 4 10 * 1 2 3 4 * 样例输出一: * 1 * * 样例输入二: * 4 5 * 2 -1 2 1 * 样例输出二: * 2 */ class Main{ private int station = 0; // station 个公交车站 private int carSize = 0; // 固定载客量 private int cases = 0; // 可能的情况数 private int[] d_i; // 乘客数量变化值 private int[] person; public static void main(String [] args){ Main m = new Main(); try { m.init(); // m.printPersonRange(); m.findMinCase(); } catch (Exception e) { e.printStackTrace(); } System.out.println(m.cases); } private void init() throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); /*========= read first line to get variable n and g =========*/ String firstLine = br.readLine(); String[] first = firstLine.split(" "); station = Integer.valueOf(first[0]); carSize = Integer.valueOf(first[1]); cases = carSize+1; // the maximum cases is carSize + 1 ( from 0 to carSize) /*===========================================================*/ /*========= read second line to get variable d_i and initialize person =========*/ d_i = new int[station]; person = new int[(station+1)*2]; // odd means lower, even means upper String secondLine = br.readLine(); String[] second = secondLine.split(" "); for (int i = 0; i < station; i++) { d_i[i] = Integer.valueOf(second[i]); person[i*2] = 0; person[i*2+1] = carSize; } person[station*2] = 0; person[station*2+1] = carSize; /*========================================================*/ int tmp = 0, tmpMax = carSize, tmpMin = 0; tmp = carSize - d_i[0]; // 算出 P0 的最小最大值 person[0*2] = getMax(0, -diff[0]); person[0*2+1] = getMin(carSize, carSize - diff[0]); for(int gap = 1; gap < station; gap++) { for(int i = gap; i < station + 1; i++) { tmpMax = person[(i-gap)*2+1] + personChanged(i-gap, i); tmpMin = person[(i-gap)*2] + personChanged(i-gap, i); if( i < station) { // 最后一个计算的时候没有额外的约束条件了 tmp = carSize - d_i[i]; tmpMax = getMin(tmp, tmpMax); // 取较 <SUF> } if( tmpMax < tmpMin ) { // 若上限小于下限,对应的不等式不成立,说明不存在这种情况 cases = 0; return; } tmpMax = getMin(tmpMax, carSize); person[i*2+1] = getMin(person[i*2+1], tmpMax); tmpMin = getMax(0, tmpMin); person[i*2] = getMax(person[i*2], tmpMin); } } } /** * 求出所有站点可能情况的交集 */ private void findMinCase() { int tmpCase; for(int i = 0; i <= station; i++) { tmpCase = person[i*2+1]-person[i*2]+1; if(cases > tmpCase) { cases = tmpCase; } } } /** * 打印出每个站点的可能的人数范围 * @apiNote 第一个站点为总站 */ private void printPersonRange() { for (int i = 0; i < station+1; i++) { System.out.print( person[i*2] + "-" + person[i*2+1]+" "); } System.out.println(); } /** * 计算从 from (include) 到 to (not include) 站点的人数变化 * @apiNote 第一站的序号为 0 * 例如: * 经过四个站点的人数变化为: d_i = { 1, 2, 3, 4, -2, 3 } * personChanged(1, 5) 计算的值为 2 + 3 + 4 + (-2),返回值为 7 */ private int personChanged(int from, int to) { int p = 0; for(int i = from; i < to; i++) p += d_i[i]; return p; } /** * 取 a,b中的最大值 * @param a * @param b * @return */ private int getMax(int a, int b) { return (a > b) ? a : b; } /** * 取 a,b中的最小值 * @param a * @param b * @return */ private int getMin(int a, int b) { return (a<b) ? a: b; } }
1
13
1
56553_5
package chiya.graph; /** * 图中的边 * * @author chiya * */ public class GraphSide { /** 从节点 */ private String nodeFrom; /** 目标节点 */ private String nodeTo; /** 代价 */ private double cost = 0; /** 从区块 */ private String blockFrom; /** 从节点 */ private String blockTo; /** * 节点互换 * * @return 新节点 */ public GraphSide exchange() { return new GraphSide() .chainCost(cost) .chainNodeTo(nodeFrom) .chainNodeFrom(nodeTo) .chainBlockFrom(blockTo) .chainNodeFrom(nodeTo) .chainBlockTo(blockFrom) .chainNodeTo(nodeFrom); } /** * 获取从节点 * * @return 从节点 */ public String getNodeFrom() { return nodeFrom; } /** * 设置从节点 * * @param nodeFrom 从节点 */ public void setNodeFrom(String nodeFrom) { this.nodeFrom = nodeFrom; } /** * 链式添加从节点 * * @param nodeFrom 从节点 * @return 对象本身 */ public GraphSide chainNodeFrom(String nodeFrom) { setNodeFrom(nodeFrom); return this; } /** * 获取目标节点 * * @return 目标节点 */ public String getNodeTo() { return nodeTo; } /** * 设置目标节点 * * @param nodeTo 目标节点 */ public void setNodeTo(String nodeTo) { this.nodeTo = nodeTo; } /** * 链式添加目标节点 * * @param nodeTo 目标节点 * @return 对象本身 */ public GraphSide chainNodeTo(String nodeTo) { setNodeTo(nodeTo); return this; } /** * 获取代价 * * @return 代价 */ public double getCost() { return cost; } /** * 设置代价 * * @param cost 代价 */ public void setCost(double cost) { this.cost = cost; } /** * 链式添加代价 * * @param cost 代价 * @return 对象本身 */ public GraphSide chainCost(double cost) { setCost(cost); return this; } /** * 获取从区块 * * @return 从区块 */ public String getBlockFrom() { return blockFrom; } /** * 设置从区块 * * @param blockFrom 从区块 */ public void setBlockFrom(String blockFrom) { this.blockFrom = blockFrom; } /** * 链式添加从区块 * * @param blockFrom 从区块 * @return 对象本身 */ public GraphSide chainBlockFrom(String blockFrom) { setBlockFrom(blockFrom); return this; } /** * 获取从节点 * * @return 从节点 */ public String getBlockTo() { return blockTo; } /** * 设置从节点 * * @param blockTo 从节点 */ public void setBlockTo(String blockTo) { this.blockTo = blockTo; } /** * 链式添加从节点 * * @param blockTo 从节点 * @return 对象本身 */ public GraphSide chainBlockTo(String blockTo) { setBlockTo(blockTo); return this; } }
Briandis/chiyaUtil
src/chiya/graph/GraphSide.java
926
/** 从节点 */
block_comment
zh-cn
package chiya.graph; /** * 图中的边 * * @author chiya * */ public class GraphSide { /** 从节点 */ private String nodeFrom; /** 目标节点 */ private String nodeTo; /** 代价 */ private double cost = 0; /** 从区块 */ private String blockFrom; /** 从节点 <SUF>*/ private String blockTo; /** * 节点互换 * * @return 新节点 */ public GraphSide exchange() { return new GraphSide() .chainCost(cost) .chainNodeTo(nodeFrom) .chainNodeFrom(nodeTo) .chainBlockFrom(blockTo) .chainNodeFrom(nodeTo) .chainBlockTo(blockFrom) .chainNodeTo(nodeFrom); } /** * 获取从节点 * * @return 从节点 */ public String getNodeFrom() { return nodeFrom; } /** * 设置从节点 * * @param nodeFrom 从节点 */ public void setNodeFrom(String nodeFrom) { this.nodeFrom = nodeFrom; } /** * 链式添加从节点 * * @param nodeFrom 从节点 * @return 对象本身 */ public GraphSide chainNodeFrom(String nodeFrom) { setNodeFrom(nodeFrom); return this; } /** * 获取目标节点 * * @return 目标节点 */ public String getNodeTo() { return nodeTo; } /** * 设置目标节点 * * @param nodeTo 目标节点 */ public void setNodeTo(String nodeTo) { this.nodeTo = nodeTo; } /** * 链式添加目标节点 * * @param nodeTo 目标节点 * @return 对象本身 */ public GraphSide chainNodeTo(String nodeTo) { setNodeTo(nodeTo); return this; } /** * 获取代价 * * @return 代价 */ public double getCost() { return cost; } /** * 设置代价 * * @param cost 代价 */ public void setCost(double cost) { this.cost = cost; } /** * 链式添加代价 * * @param cost 代价 * @return 对象本身 */ public GraphSide chainCost(double cost) { setCost(cost); return this; } /** * 获取从区块 * * @return 从区块 */ public String getBlockFrom() { return blockFrom; } /** * 设置从区块 * * @param blockFrom 从区块 */ public void setBlockFrom(String blockFrom) { this.blockFrom = blockFrom; } /** * 链式添加从区块 * * @param blockFrom 从区块 * @return 对象本身 */ public GraphSide chainBlockFrom(String blockFrom) { setBlockFrom(blockFrom); return this; } /** * 获取从节点 * * @return 从节点 */ public String getBlockTo() { return blockTo; } /** * 设置从节点 * * @param blockTo 从节点 */ public void setBlockTo(String blockTo) { this.blockTo = blockTo; } /** * 链式添加从节点 * * @param blockTo 从节点 * @return 对象本身 */ public GraphSide chainBlockTo(String blockTo) { setBlockTo(blockTo); return this; } }
0
10
0
27922_10
package com.zx.security.core.social.qq.api; import lombok.Data; import lombok.experimental.Accessors; /** * author:ZhengXing * datetime:2018-01-02 21:20 * qq用户信息 * 从文档中获取的字段 * * 使用IDEA的多行编辑,..几秒搞定.舒服 */ @Data @Accessors(chain = true) public class QQUserInfo { private String openId;//用户id 不是返回来的,需要自行添加 private Integer is_lost;//..文档中没有 private Integer ret;//返回码 private String msg;//如果ret<0,会有相应的错误信息提示,返回数据全部用UTF-8编码。 private String nickname;//用户在QQ空间的昵称。 private String figureurl;//大小为30×30像素的QQ空间头像URL。 private String figureurl_1;//大小为50×50像素的QQ空间头像URL。 private String figureurl_2;//大小为100×100像素的QQ空间头像URL。 private String figureurl_qq_1;//大小为40×40像素的QQ头像URL。 private String figureurl_qq_2;//大小为100×100像素的QQ头像URL。需要注意,不是所有的用户都拥有QQ的100x100的头像,但40x40像素则是一定会有。 private String gender;//性别。 如果获取不到则默认返回"男" private String is_yellow_vip;//标识用户是否为黄钻用户(0:不是;1:是)。 private String vip;//标识用户是否为黄钻用户(0:不是;1:是) private String yellow_vip_level;//黄钻等级 private String level;//黄钻等级 private String is_yellow_year_vip;//标识是否为年费黄钻用户(0:不是; 1:是) private String province;//省份 private String city;//城市 private String year;//出生年分 }
BrightStarry/zx-security
zx-security-core/src/main/java/com/zx/security/core/social/qq/api/QQUserInfo.java
497
//大小为100×100像素的QQ头像URL。需要注意,不是所有的用户都拥有QQ的100x100的头像,但40x40像素则是一定会有。
line_comment
zh-cn
package com.zx.security.core.social.qq.api; import lombok.Data; import lombok.experimental.Accessors; /** * author:ZhengXing * datetime:2018-01-02 21:20 * qq用户信息 * 从文档中获取的字段 * * 使用IDEA的多行编辑,..几秒搞定.舒服 */ @Data @Accessors(chain = true) public class QQUserInfo { private String openId;//用户id 不是返回来的,需要自行添加 private Integer is_lost;//..文档中没有 private Integer ret;//返回码 private String msg;//如果ret<0,会有相应的错误信息提示,返回数据全部用UTF-8编码。 private String nickname;//用户在QQ空间的昵称。 private String figureurl;//大小为30×30像素的QQ空间头像URL。 private String figureurl_1;//大小为50×50像素的QQ空间头像URL。 private String figureurl_2;//大小为100×100像素的QQ空间头像URL。 private String figureurl_qq_1;//大小为40×40像素的QQ头像URL。 private String figureurl_qq_2;//大小 <SUF> private String gender;//性别。 如果获取不到则默认返回"男" private String is_yellow_vip;//标识用户是否为黄钻用户(0:不是;1:是)。 private String vip;//标识用户是否为黄钻用户(0:不是;1:是) private String yellow_vip_level;//黄钻等级 private String level;//黄钻等级 private String is_yellow_year_vip;//标识是否为年费黄钻用户(0:不是; 1:是) private String province;//省份 private String city;//城市 private String year;//出生年分 }
1
67
1
16223_11
package com.makiyo.pojo; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * tb_checkin * @author */ @Data public class TbCheckin implements Serializable { /** * 主键 */ private Integer id; /** * 用户ID */ private Integer userId; /** * 签到地址 */ private String address; /** * 国家 */ private String country; /** * 省份 */ private String province; /** * 城市 */ private String city; /** * 区划 */ private String district; /** * 考勤结果 */ private Byte status; /** * 风险等级 */ private Integer risk; /** * 签到日期 */ private String date; /** * 签到时间 */ private Date createTime; private static final long serialVersionUID = 1L; }
Bruce6230/epidemic-prevention-system
src/main/java/com/makiyo/pojo/TbCheckin.java
230
/** * 签到时间 */
block_comment
zh-cn
package com.makiyo.pojo; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * tb_checkin * @author */ @Data public class TbCheckin implements Serializable { /** * 主键 */ private Integer id; /** * 用户ID */ private Integer userId; /** * 签到地址 */ private String address; /** * 国家 */ private String country; /** * 省份 */ private String province; /** * 城市 */ private String city; /** * 区划 */ private String district; /** * 考勤结果 */ private Byte status; /** * 风险等级 */ private Integer risk; /** * 签到日期 */ private String date; /** * 签到时 <SUF>*/ private Date createTime; private static final long serialVersionUID = 1L; }
1
23
1
32717_8
package model; /** * 新政政区域划分 * Created by liyonglin on 2017/10/26. */ public class Area { public static final String CHINA = "中国"; public static final String XINJIANG = "新疆维吾尔自治区"; public static final String WLMQ = "乌鲁木齐市"; public static final String KLMY = "克拉玛依市"; public static final String TLF = "吐鲁番市"; public static final String HM = "哈密市"; public static final String HKS = "阿克苏地区"; public static final String KS = "喀什地区"; public static final String HT = "和田地区"; public static final String CJ = "昌吉回族自治州"; public static final String BETLMG = "博尔塔拉蒙古自治州"; public static final String BYGL = "巴音郭楞蒙古自治州"; public static final String KMLSKEKM = "克孜勒苏柯尔克孜自治州"; public static final String YL = "伊犁哈萨克自治州"; /** * 地区综合命名 */ public String formatted_address = ""; /** * 国家 */ public String country = ""; /** * 省份,自治区,直辖市 */ public String province = ""; /** * 市 */ public String city = ""; /** * 区,县 */ public String district = ""; public String town = "";//乡镇 /** * 街道 */ public String street = "";//街道名(行政区划中的街道层级) public String street_number = "";//街道门牌号 @Override public String toString() { return "Area{" + "formatted_address='" + formatted_address + '\'' + ", country='" + country + '\'' + ", province='" + province + '\'' + ", city='" + city + '\'' + ", district='" + district + '\'' + ", town='" + town + '\'' + ", street='" + street + '\'' + ", street_number='" + street_number + '\'' + '}'; } }
BruceLii/BaiduPOI
src/main/java/model/Area.java
538
//街道门牌号
line_comment
zh-cn
package model; /** * 新政政区域划分 * Created by liyonglin on 2017/10/26. */ public class Area { public static final String CHINA = "中国"; public static final String XINJIANG = "新疆维吾尔自治区"; public static final String WLMQ = "乌鲁木齐市"; public static final String KLMY = "克拉玛依市"; public static final String TLF = "吐鲁番市"; public static final String HM = "哈密市"; public static final String HKS = "阿克苏地区"; public static final String KS = "喀什地区"; public static final String HT = "和田地区"; public static final String CJ = "昌吉回族自治州"; public static final String BETLMG = "博尔塔拉蒙古自治州"; public static final String BYGL = "巴音郭楞蒙古自治州"; public static final String KMLSKEKM = "克孜勒苏柯尔克孜自治州"; public static final String YL = "伊犁哈萨克自治州"; /** * 地区综合命名 */ public String formatted_address = ""; /** * 国家 */ public String country = ""; /** * 省份,自治区,直辖市 */ public String province = ""; /** * 市 */ public String city = ""; /** * 区,县 */ public String district = ""; public String town = "";//乡镇 /** * 街道 */ public String street = "";//街道名(行政区划中的街道层级) public String street_number = "";//街道 <SUF> @Override public String toString() { return "Area{" + "formatted_address='" + formatted_address + '\'' + ", country='" + country + '\'' + ", province='" + province + '\'' + ", city='" + city + '\'' + ", district='" + district + '\'' + ", town='" + town + '\'' + ", street='" + street + '\'' + ", street_number='" + street_number + '\'' + '}'; } }
1
7
1
45126_0
package com.fc.demo1._static; // 诉讼接口 public interface Lawsuit { // 提起诉讼 void submit(); // 法庭辩护 void defend(); }
BufferC/dev01
04-DesignPattern-01-Proxy/src/main/java/com/fc/demo1/_static/Lawsuit.java
53
// 诉讼接口
line_comment
zh-cn
package com.fc.demo1._static; // 诉讼 <SUF> public interface Lawsuit { // 提起诉讼 void submit(); // 法庭辩护 void defend(); }
1
7
1
41042_5
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ // 中序遍历 自己写的 class Solution { public int findTargetNode(TreeNode root, int cnt) { List<TreeNode> list = new ArrayList<>(); inOrder(root, list); // 返回倒数第cnt个 return list.get(list.size()-cnt).val; } public void inOrder(TreeNode node, List<TreeNode> list) { if(node == null) return; inOrder(node.left, list); list.add(node); inOrder(node.right, list); } } // 优化时间,倒序遍历(得到递减的序列),提前返回 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int k = 0, res; public int findTargetNode(TreeNode root, int cnt) { this.k = cnt; inOrder(root); // 右 -> 根 -> 左 return res; } public void inOrder(TreeNode node) { if(node == null) return; inOrder(node.right); k--; if(k == 0) { res = node.val; } inOrder(node.left); } }
Bug-Dever/Code
L54.java
478
// 右 -> 根 -> 左
line_comment
zh-cn
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ // 中序遍历 自己写的 class Solution { public int findTargetNode(TreeNode root, int cnt) { List<TreeNode> list = new ArrayList<>(); inOrder(root, list); // 返回倒数第cnt个 return list.get(list.size()-cnt).val; } public void inOrder(TreeNode node, List<TreeNode> list) { if(node == null) return; inOrder(node.left, list); list.add(node); inOrder(node.right, list); } } // 优化时间,倒序遍历(得到递减的序列),提前返回 /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { int k = 0, res; public int findTargetNode(TreeNode root, int cnt) { this.k = cnt; inOrder(root); // 右 <SUF> return res; } public void inOrder(TreeNode node) { if(node == null) return; inOrder(node.right); k--; if(k == 0) { res = node.val; } inOrder(node.left); } }
0
14
0
53349_3
package sms; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.sms.model.v20160927.SingleSendSmsRequest; import com.aliyuncs.sms.model.v20160927.SingleSendSmsResponse; public class SingleSendSms { public static void smsSend(String phone,String modeid,String param) { try { IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIiL3nLmMzSuIR", "Q8oLL7wTjmhK4y3z4erWSJbAiP1FLx"); DefaultProfile.addEndpoint("cn-qingdao", "cn-qingdao", "Sms", "sms.aliyuncs.com"); IAcsClient client = new DefaultAcsClient(profile); SingleSendSmsRequest request = new SingleSendSmsRequest(); request.setSignName("冒险家");//控制台创建的签名名称 request.setTemplateCode(modeid);//控制台创建的模板CODE //request.setParamString("{\"name\":\"123\"}");//短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。" request.setParamString(param); request.setRecNum(phone);//接收号码 SingleSendSmsResponse httpResponse = client.getAcsResponse(request); } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } } public static void main(String args[]) { smsSend("18703996021","SMS_56665270","{\"code\":\"123\",\"product\":\"亲子淘\"}"); } }
BugGirls/camprecruit
src/sms/SingleSendSms.java
472
//接收号码
line_comment
zh-cn
package sms; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.exceptions.ServerException; import com.aliyuncs.profile.DefaultProfile; import com.aliyuncs.profile.IClientProfile; import com.aliyuncs.sms.model.v20160927.SingleSendSmsRequest; import com.aliyuncs.sms.model.v20160927.SingleSendSmsResponse; public class SingleSendSms { public static void smsSend(String phone,String modeid,String param) { try { IClientProfile profile = DefaultProfile.getProfile("cn-qingdao", "LTAIiL3nLmMzSuIR", "Q8oLL7wTjmhK4y3z4erWSJbAiP1FLx"); DefaultProfile.addEndpoint("cn-qingdao", "cn-qingdao", "Sms", "sms.aliyuncs.com"); IAcsClient client = new DefaultAcsClient(profile); SingleSendSmsRequest request = new SingleSendSmsRequest(); request.setSignName("冒险家");//控制台创建的签名名称 request.setTemplateCode(modeid);//控制台创建的模板CODE //request.setParamString("{\"name\":\"123\"}");//短信模板中的变量;数字需要转换为字符串;个人用户每个变量长度必须小于15个字符。" request.setParamString(param); request.setRecNum(phone);//接收 <SUF> SingleSendSmsResponse httpResponse = client.getAcsResponse(request); } catch (ServerException e) { e.printStackTrace(); } catch (ClientException e) { e.printStackTrace(); } } public static void main(String args[]) { smsSend("18703996021","SMS_56665270","{\"code\":\"123\",\"product\":\"亲子淘\"}"); } }
1
6
1
37057_30
package parsing; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import java.util.TreeMap; import java.util.TreeSet; public class Parsing { //分析表 private String[][] analyzeTable; //文法集 private ArrayList<String> grammarArray; //产生式集 private HashMap<String, ArrayList<String>> productionMap; //开始符 private String startSymbol; //非终结符集 private TreeSet<String> nonTerminatorSet; //终结符集 private TreeSet<String> terminatorSet; //FIRST集 private HashMap<String, TreeSet<String>> firstMap; //FOLLOW集 private HashMap<String, TreeSet<String>> followMap; //SELECT集 private TreeMap<String, HashMap<String, TreeSet<String>>> selectMap; public TreeMap<String, HashMap<String, TreeSet<String>>> getSelectMap() { return selectMap; } //初始化文法(程序入口,文法为产生式的集合) public Parsing() { grammarArray = new ArrayList<String>(); nonTerminatorSet = new TreeSet<String>(); terminatorSet = new TreeSet<String>(); firstMap = new HashMap<String, TreeSet<String>>(); followMap = new HashMap<String, TreeSet<String>>(); selectMap = new TreeMap<String, HashMap<String, TreeSet<String>>>(); } //初始化文法(测试时用) public void setGrammarArray(ArrayList<String> grammarArray) { this.grammarArray = grammarArray; } //初始化开始符(测试时用) public void setStartSymbol(String startSymbol) { this.startSymbol = startSymbol; } //初始化非终结符集合/终结符集合/表达式集合(求FIRST时用) public void initTerminAndNonTerminSet(){ productionMap = new HashMap<String, ArrayList<String>>(); for(String production : grammarArray){ //取到每个产生式的左部和右部 String left = production.split("->")[0]; //左部一定是非终结符,所以直接加 nonTerminatorSet.add(left); } for(String production : grammarArray){ String right = production.split("->")[1]; //右部一个一个字符取出,然后判断如果不是非终结符和"ε"就一定是终结符 for(int i=0;i<right.length();i++){ String singleSymble = right.charAt(i)+""; if(!nonTerminatorSet.contains(singleSymble) && !singleSymble.equals("ε")){ terminatorSet.add(singleSymble); } } } for(String production : grammarArray){ String left = production.split("->")[0]; String right = production.split("->")[1]; //将产生式按照左右部K-V放到Map里 ArrayList<String> productionArray; if(!productionMap.containsKey(left)){ productionArray = new ArrayList<String>(); } else{ productionArray = productionMap.get(left); } productionArray.add(right); productionMap.put(left, productionArray); } } //获取First集 public void getFirst() { for(String nonTermin : nonTerminatorSet){ ArrayList<String> rightArray = productionMap.get(nonTermin); for(String right : rightArray){ TreeSet<String> firstSet = firstMap.get(nonTermin); if(firstSet == null){ firstSet = new TreeSet<String>(); } int flag = 0; for(int i=0;i<right.length();i++){ String singleSymble = right.charAt(i)+""; if(nonTermin.equals("E")){ for(String s : firstSet){ System.out.println(s); } } flag = recursionFirst(firstSet, nonTermin, singleSymble); if(flag == 1){ break; } } } } } //递归求FIRST public int recursionFirst(TreeSet<String>firstSet, String nonTermin, String singleSymble){ if(terminatorSet.contains(singleSymble) || singleSymble.equals("ε")){ firstSet.add(singleSymble); firstMap.put(nonTermin, firstSet); return 1; } else if(nonTerminatorSet.contains(singleSymble)){ ArrayList<String> arrayList = productionMap.get(singleSymble); for(String s : arrayList){ String letter = s.charAt(0)+""; recursionFirst(firstSet, nonTermin, letter); } } return 1; } public void printFirst(){ System.out.println("First集:"); for(Map.Entry<String, TreeSet<String>> entry : firstMap.entrySet()){ System.out.println(entry.getKey() + ": " + entry.getValue()); } System.out.println(); } //判断当前的非终结符的下一个是否是终结符(求FOLLOW时用) public boolean hasNextTermin(TreeSet<String> terminSet, String right, String nonTer) { //在所有产生式的右部里寻找当前的非终结符 if (right.contains(nonTer)) { String next; try { //取出找到的当前非终结符的下一个 next = right.substring(right.indexOf(nonTer)+1, right.indexOf(nonTer)+2); } catch (Exception e) { return false; } //如果当前非终结符的下一个是终结符 if (terminSet.contains(next)) { return true; } else { return false; } } else { return false; } } //判断当前的非终结符的下一个是否是非终结符(求FOLLOW时用) public boolean hasNextNonTermin(TreeSet<String> nonTerminSet, String right, String nonTer) { if (right.contains(nonTer)) { String next; try { //取出找到的当前非终结符的下一个 next = right.substring(right.indexOf(nonTer)+1, right.indexOf(nonTer)+2); } catch (Exception e) { return false; } //如果当前非终结符的下一个是非终结符 if (nonTerminSet.contains(next)) { return true; } else { return false; } } else { return false; } } //在已知当前非终结符的下一个是非终结符的情况下,判断其下一个非终结符是否能推空(求FOLLOW时用) public boolean nextNonTerminIsNull(TreeSet<String> nonTerminSet, String right, String nonTer, HashMap<String, ArrayList<String>> productionMap) { if (hasNextNonTermin(nonTerminatorSet, right, nonTer)) { String next = getNext(right, nonTer); ArrayList<String> arrayList = productionMap.get(next); if (arrayList.contains("ε")) { return true; } } return false; } //判断当前非终结符的右边是否为空(即当前非终结符是否在右部末尾)(求FOLLOW时用) public boolean hasNoNext(TreeSet<String> nonTerminSet, String right, String nonTer, HashMap<String, ArrayList<String>> productionMap){ String last = right.substring(right.length()-1); //如果该非终结符是右部的最后一个,则说明其右边为空 if(nonTer.equals(last)){ return true; } return false; } //获取一个产生式右部某非终结符的下一个符号(求FOLLOW时用) public String getNext(String right, String nonTer) { if (right.contains(nonTer)) { String next = ""; try { //获取一个产生式右部某非终结符右边的终结符 next = right.substring(right.indexOf(nonTer)+1, right.indexOf(nonTer)+2); } catch (Exception e) { return null; } return next; } return null; } //获取Follow集 public void getFollow() { //初始化followMap,先为每一个非终结符映射一个空集合 for(String nonTermin : nonTerminatorSet){ TreeSet<String> treeSet = new TreeSet<String>(); followMap.put(nonTermin, treeSet); } for(String nonTermin : nonTerminatorSet){ //取出所有key,即非终结符,放到nonTerminSet里 Set<String> nonTerminSet = productionMap.keySet(); for(String nonTerm : nonTerminSet){ //得到右部的集合 ArrayList<String> rightArray = productionMap.get(nonTerm); for(String right : rightArray){ TreeSet<String> followSet = followMap.get(nonTermin); recursionFollow(nonTermin, nonTermin, nonTerm, right, followSet); } } } } //递归求FOLLOW public void recursionFollow(String nowNonTermin, String nonTermin, String nonTerm, String right, TreeSet<String> followSet){ //(1)对于开始符来说,直接把#加进去 if(nonTermin.equals(startSymbol)){ followSet.add("#"); followMap.put(nowNonTermin, followSet); } //在所有产生式右部寻找待求非终结符 //(2)若待求非终结符的右边直接跟着终结符,则直接把该终结符加进去 if(hasNextTermin(terminatorSet, right, nonTermin)){ String next = getNext(right, nonTermin); followSet.add(next); followMap.put(nowNonTermin, followSet); } //(3)若待求非终结符的右边跟着非终结符,则把该非终结符的First集除掉"ε"后加进去 if(hasNextNonTermin(nonTerminatorSet, right, nonTermin)){ String next = getNext(right, nonTermin); TreeSet<String> firstSet = firstMap.get(next); followSet.addAll(firstSet); //如果First集里含有"ε"的话,"#"也要加进去 if(firstSet.contains("ε")){ followSet.add("#"); } followSet.remove("ε"); followMap.put(nowNonTermin, followSet); //(4)在(3)的前提下,若后边跟着的非终结符能推空,则需再把左部的Follow集加进去 if(nextNonTerminIsNull(nonTerminatorSet, right, nonTermin, productionMap)){ if(!nonTerm.equals(nonTermin)){ Set<String> nonTerminSet = productionMap.keySet(); for(String s : nonTerminSet){ //得到右部的集合 ArrayList<String> rightArray = productionMap.get(s); //循环递归 for(String rightStr : rightArray){ recursionFollow(nowNonTermin, nonTerm, s, rightStr, followSet); } } } } } //(5)若待求非终结符的右边为空,则把左部的Follow集加进去(操作同(4)) if(hasNoNext(nonTerminatorSet, right, nonTermin, productionMap)){ if(!nonTerm.equals(nonTermin)){ Set<String> nonTerminSet = productionMap.keySet(); for(String s : nonTerminSet){ //得到右部的集合 ArrayList<String> rightArray = productionMap.get(s); //循环递归 for(String rightStr : rightArray){ recursionFollow(nowNonTermin, nonTerm, s, rightStr, followSet); } } } } } public void printFollow(){ System.out.println("Follow集:"); for(Map.Entry<String, TreeSet<String>> entry : followMap.entrySet()){ System.out.println(entry.getKey() + ": " + entry.getValue()); } System.out.println(); } //判断产生式右部为空(求SELECT时用) public static boolean isEmpty(String right) { if (right.equals("ε")) { return true; } return false; } //判断产生式右部是从终结符开始的(求SELECT时用) public static boolean isTerminStart(TreeSet<String> terminSet, String right) { char charAt = right.charAt(0); if (terminSet.contains(charAt+"")) { return true; } return false; } //判断产生式右部是从非终结符开始的(求SELECT时用) public static boolean isNonTerminStart(TreeSet<String> nonTerminSet, String right) { char charAt = right.charAt(0); if (nonTerminSet.contains(charAt+"")) { return true; } return false; } //求SELECT集 public void getSelect(){ Set<String> nonTerminSet = productionMap.keySet(); for(String leftNonTermin : nonTerminSet){ ArrayList<String> rightArray = productionMap.get(leftNonTermin); //最后selectMap的Value,也用一个Map存储 HashMap<String, TreeSet<String>> selectMapValue = new HashMap<String, TreeSet<String>>(); for(String right : rightArray){ //每一个产生式求select集的结果集合 TreeSet<String> selectSet = new TreeSet<String>(); //(1)若产生式右部为空,则将左部的Follow集加进去 if(isEmpty(right)){ selectSet = followMap.get(leftNonTermin); } //(2)若产生式右部是从终结符开始的,则直接将该终结符加进去 else if(isTerminStart(terminatorSet, right)){ selectSet.add(right.charAt(0)+""); } //(3)若产生式右部是从非终结符开始的,则将该非终结符的First集加进去 else if(isNonTerminStart(nonTerminatorSet, right)){ selectSet = firstMap.get(leftNonTermin); } selectSet.remove("ε"); selectMapValue.put(leftNonTermin+"->"+right, selectSet); selectMap.put(leftNonTermin, selectMapValue); } } } public void printSelect(){ System.out.println("Select集:"); for(Map.Entry<String, HashMap<String, TreeSet<String>>> entry : selectMap.entrySet()){ System.out.println(entry.getKey() + ": " + entry.getValue()); } System.out.println(); } //找到某行某列对应的产生式(获取LL(1)分析表时用) public String findProduction(TreeMap<String, HashMap<String, TreeSet<String>>> selectMap, String nonTermin, String termin) { try { //先找到当前非终结符的SELECT集(也是一个HashMap) HashMap<String, TreeSet<String>> hashMap = selectMap.get(nonTermin); //将找到的SELECT集的产生式取出 Set<String> keySet = hashMap.keySet(); for (String production : keySet) { //找到该产生式对应的结果集 TreeSet<String> treeSet = hashMap.get(production); //若结果集中包含当前的终结符,则返回该产生式 if (treeSet.contains(termin)) { return production; } } } catch (Exception e) { return null; } return null; } //获取分析表 public void genAnalyzeTable(){ //定义行与列,各用一个一维数组 Object[] nonTerminArray = nonTerminatorSet.toArray(); String[] terminArray = new String[terminatorSet.size()+1]; Iterator<String> iterator = terminatorSet.iterator(); int count = 0; while(iterator.hasNext()){ terminArray[count] = iterator.next(); count++; } //终结符不要忘了再一个"#" terminArray[terminatorSet.size()] = "#"; //初始化分析表 analyzeTable = new String[nonTerminArray.length+1][terminArray.length+1]; //表格左上角的说明 analyzeTable[0][0] = "Vn/Vt"; //初始化首行,即放入所有终结符 for(int i=0;i<terminArray.length;i++){ analyzeTable[0][i+1] = terminArray[i]+""; } for(int i=0;i<nonTerminArray.length;i++){ //初始化首列,即放入所有非终结符 analyzeTable[i+1][0] = nonTerminArray[i]+""; for(int j=0;j<terminArray.length;j++){ String nowProduction = findProduction(selectMap, nonTerminArray[i]+"", terminArray[j]+""); //System.out.println(nowProduction); if (nowProduction == null) { analyzeTable[i+1][j+1] = "×"; } else{ analyzeTable[i+1][j+1] = nowProduction; } } } } public void printAnalyzeTable(){ System.out.println("LL(1)分析表:"); for(int i=0;i<analyzeTable.length;i++){ for(int j=0;j<analyzeTable[i].length;j++){ System.out.printf(analyzeTable[i][j]+"\t\t"); } System.out.println(); } System.out.println(); } }
BuglessCoder/LL1-Parsing
Parsing.java
4,509
//获取一个产生式右部某非终结符右边的终结符
line_comment
zh-cn
package parsing; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import java.util.TreeMap; import java.util.TreeSet; public class Parsing { //分析表 private String[][] analyzeTable; //文法集 private ArrayList<String> grammarArray; //产生式集 private HashMap<String, ArrayList<String>> productionMap; //开始符 private String startSymbol; //非终结符集 private TreeSet<String> nonTerminatorSet; //终结符集 private TreeSet<String> terminatorSet; //FIRST集 private HashMap<String, TreeSet<String>> firstMap; //FOLLOW集 private HashMap<String, TreeSet<String>> followMap; //SELECT集 private TreeMap<String, HashMap<String, TreeSet<String>>> selectMap; public TreeMap<String, HashMap<String, TreeSet<String>>> getSelectMap() { return selectMap; } //初始化文法(程序入口,文法为产生式的集合) public Parsing() { grammarArray = new ArrayList<String>(); nonTerminatorSet = new TreeSet<String>(); terminatorSet = new TreeSet<String>(); firstMap = new HashMap<String, TreeSet<String>>(); followMap = new HashMap<String, TreeSet<String>>(); selectMap = new TreeMap<String, HashMap<String, TreeSet<String>>>(); } //初始化文法(测试时用) public void setGrammarArray(ArrayList<String> grammarArray) { this.grammarArray = grammarArray; } //初始化开始符(测试时用) public void setStartSymbol(String startSymbol) { this.startSymbol = startSymbol; } //初始化非终结符集合/终结符集合/表达式集合(求FIRST时用) public void initTerminAndNonTerminSet(){ productionMap = new HashMap<String, ArrayList<String>>(); for(String production : grammarArray){ //取到每个产生式的左部和右部 String left = production.split("->")[0]; //左部一定是非终结符,所以直接加 nonTerminatorSet.add(left); } for(String production : grammarArray){ String right = production.split("->")[1]; //右部一个一个字符取出,然后判断如果不是非终结符和"ε"就一定是终结符 for(int i=0;i<right.length();i++){ String singleSymble = right.charAt(i)+""; if(!nonTerminatorSet.contains(singleSymble) && !singleSymble.equals("ε")){ terminatorSet.add(singleSymble); } } } for(String production : grammarArray){ String left = production.split("->")[0]; String right = production.split("->")[1]; //将产生式按照左右部K-V放到Map里 ArrayList<String> productionArray; if(!productionMap.containsKey(left)){ productionArray = new ArrayList<String>(); } else{ productionArray = productionMap.get(left); } productionArray.add(right); productionMap.put(left, productionArray); } } //获取First集 public void getFirst() { for(String nonTermin : nonTerminatorSet){ ArrayList<String> rightArray = productionMap.get(nonTermin); for(String right : rightArray){ TreeSet<String> firstSet = firstMap.get(nonTermin); if(firstSet == null){ firstSet = new TreeSet<String>(); } int flag = 0; for(int i=0;i<right.length();i++){ String singleSymble = right.charAt(i)+""; if(nonTermin.equals("E")){ for(String s : firstSet){ System.out.println(s); } } flag = recursionFirst(firstSet, nonTermin, singleSymble); if(flag == 1){ break; } } } } } //递归求FIRST public int recursionFirst(TreeSet<String>firstSet, String nonTermin, String singleSymble){ if(terminatorSet.contains(singleSymble) || singleSymble.equals("ε")){ firstSet.add(singleSymble); firstMap.put(nonTermin, firstSet); return 1; } else if(nonTerminatorSet.contains(singleSymble)){ ArrayList<String> arrayList = productionMap.get(singleSymble); for(String s : arrayList){ String letter = s.charAt(0)+""; recursionFirst(firstSet, nonTermin, letter); } } return 1; } public void printFirst(){ System.out.println("First集:"); for(Map.Entry<String, TreeSet<String>> entry : firstMap.entrySet()){ System.out.println(entry.getKey() + ": " + entry.getValue()); } System.out.println(); } //判断当前的非终结符的下一个是否是终结符(求FOLLOW时用) public boolean hasNextTermin(TreeSet<String> terminSet, String right, String nonTer) { //在所有产生式的右部里寻找当前的非终结符 if (right.contains(nonTer)) { String next; try { //取出找到的当前非终结符的下一个 next = right.substring(right.indexOf(nonTer)+1, right.indexOf(nonTer)+2); } catch (Exception e) { return false; } //如果当前非终结符的下一个是终结符 if (terminSet.contains(next)) { return true; } else { return false; } } else { return false; } } //判断当前的非终结符的下一个是否是非终结符(求FOLLOW时用) public boolean hasNextNonTermin(TreeSet<String> nonTerminSet, String right, String nonTer) { if (right.contains(nonTer)) { String next; try { //取出找到的当前非终结符的下一个 next = right.substring(right.indexOf(nonTer)+1, right.indexOf(nonTer)+2); } catch (Exception e) { return false; } //如果当前非终结符的下一个是非终结符 if (nonTerminSet.contains(next)) { return true; } else { return false; } } else { return false; } } //在已知当前非终结符的下一个是非终结符的情况下,判断其下一个非终结符是否能推空(求FOLLOW时用) public boolean nextNonTerminIsNull(TreeSet<String> nonTerminSet, String right, String nonTer, HashMap<String, ArrayList<String>> productionMap) { if (hasNextNonTermin(nonTerminatorSet, right, nonTer)) { String next = getNext(right, nonTer); ArrayList<String> arrayList = productionMap.get(next); if (arrayList.contains("ε")) { return true; } } return false; } //判断当前非终结符的右边是否为空(即当前非终结符是否在右部末尾)(求FOLLOW时用) public boolean hasNoNext(TreeSet<String> nonTerminSet, String right, String nonTer, HashMap<String, ArrayList<String>> productionMap){ String last = right.substring(right.length()-1); //如果该非终结符是右部的最后一个,则说明其右边为空 if(nonTer.equals(last)){ return true; } return false; } //获取一个产生式右部某非终结符的下一个符号(求FOLLOW时用) public String getNext(String right, String nonTer) { if (right.contains(nonTer)) { String next = ""; try { //获取 <SUF> next = right.substring(right.indexOf(nonTer)+1, right.indexOf(nonTer)+2); } catch (Exception e) { return null; } return next; } return null; } //获取Follow集 public void getFollow() { //初始化followMap,先为每一个非终结符映射一个空集合 for(String nonTermin : nonTerminatorSet){ TreeSet<String> treeSet = new TreeSet<String>(); followMap.put(nonTermin, treeSet); } for(String nonTermin : nonTerminatorSet){ //取出所有key,即非终结符,放到nonTerminSet里 Set<String> nonTerminSet = productionMap.keySet(); for(String nonTerm : nonTerminSet){ //得到右部的集合 ArrayList<String> rightArray = productionMap.get(nonTerm); for(String right : rightArray){ TreeSet<String> followSet = followMap.get(nonTermin); recursionFollow(nonTermin, nonTermin, nonTerm, right, followSet); } } } } //递归求FOLLOW public void recursionFollow(String nowNonTermin, String nonTermin, String nonTerm, String right, TreeSet<String> followSet){ //(1)对于开始符来说,直接把#加进去 if(nonTermin.equals(startSymbol)){ followSet.add("#"); followMap.put(nowNonTermin, followSet); } //在所有产生式右部寻找待求非终结符 //(2)若待求非终结符的右边直接跟着终结符,则直接把该终结符加进去 if(hasNextTermin(terminatorSet, right, nonTermin)){ String next = getNext(right, nonTermin); followSet.add(next); followMap.put(nowNonTermin, followSet); } //(3)若待求非终结符的右边跟着非终结符,则把该非终结符的First集除掉"ε"后加进去 if(hasNextNonTermin(nonTerminatorSet, right, nonTermin)){ String next = getNext(right, nonTermin); TreeSet<String> firstSet = firstMap.get(next); followSet.addAll(firstSet); //如果First集里含有"ε"的话,"#"也要加进去 if(firstSet.contains("ε")){ followSet.add("#"); } followSet.remove("ε"); followMap.put(nowNonTermin, followSet); //(4)在(3)的前提下,若后边跟着的非终结符能推空,则需再把左部的Follow集加进去 if(nextNonTerminIsNull(nonTerminatorSet, right, nonTermin, productionMap)){ if(!nonTerm.equals(nonTermin)){ Set<String> nonTerminSet = productionMap.keySet(); for(String s : nonTerminSet){ //得到右部的集合 ArrayList<String> rightArray = productionMap.get(s); //循环递归 for(String rightStr : rightArray){ recursionFollow(nowNonTermin, nonTerm, s, rightStr, followSet); } } } } } //(5)若待求非终结符的右边为空,则把左部的Follow集加进去(操作同(4)) if(hasNoNext(nonTerminatorSet, right, nonTermin, productionMap)){ if(!nonTerm.equals(nonTermin)){ Set<String> nonTerminSet = productionMap.keySet(); for(String s : nonTerminSet){ //得到右部的集合 ArrayList<String> rightArray = productionMap.get(s); //循环递归 for(String rightStr : rightArray){ recursionFollow(nowNonTermin, nonTerm, s, rightStr, followSet); } } } } } public void printFollow(){ System.out.println("Follow集:"); for(Map.Entry<String, TreeSet<String>> entry : followMap.entrySet()){ System.out.println(entry.getKey() + ": " + entry.getValue()); } System.out.println(); } //判断产生式右部为空(求SELECT时用) public static boolean isEmpty(String right) { if (right.equals("ε")) { return true; } return false; } //判断产生式右部是从终结符开始的(求SELECT时用) public static boolean isTerminStart(TreeSet<String> terminSet, String right) { char charAt = right.charAt(0); if (terminSet.contains(charAt+"")) { return true; } return false; } //判断产生式右部是从非终结符开始的(求SELECT时用) public static boolean isNonTerminStart(TreeSet<String> nonTerminSet, String right) { char charAt = right.charAt(0); if (nonTerminSet.contains(charAt+"")) { return true; } return false; } //求SELECT集 public void getSelect(){ Set<String> nonTerminSet = productionMap.keySet(); for(String leftNonTermin : nonTerminSet){ ArrayList<String> rightArray = productionMap.get(leftNonTermin); //最后selectMap的Value,也用一个Map存储 HashMap<String, TreeSet<String>> selectMapValue = new HashMap<String, TreeSet<String>>(); for(String right : rightArray){ //每一个产生式求select集的结果集合 TreeSet<String> selectSet = new TreeSet<String>(); //(1)若产生式右部为空,则将左部的Follow集加进去 if(isEmpty(right)){ selectSet = followMap.get(leftNonTermin); } //(2)若产生式右部是从终结符开始的,则直接将该终结符加进去 else if(isTerminStart(terminatorSet, right)){ selectSet.add(right.charAt(0)+""); } //(3)若产生式右部是从非终结符开始的,则将该非终结符的First集加进去 else if(isNonTerminStart(nonTerminatorSet, right)){ selectSet = firstMap.get(leftNonTermin); } selectSet.remove("ε"); selectMapValue.put(leftNonTermin+"->"+right, selectSet); selectMap.put(leftNonTermin, selectMapValue); } } } public void printSelect(){ System.out.println("Select集:"); for(Map.Entry<String, HashMap<String, TreeSet<String>>> entry : selectMap.entrySet()){ System.out.println(entry.getKey() + ": " + entry.getValue()); } System.out.println(); } //找到某行某列对应的产生式(获取LL(1)分析表时用) public String findProduction(TreeMap<String, HashMap<String, TreeSet<String>>> selectMap, String nonTermin, String termin) { try { //先找到当前非终结符的SELECT集(也是一个HashMap) HashMap<String, TreeSet<String>> hashMap = selectMap.get(nonTermin); //将找到的SELECT集的产生式取出 Set<String> keySet = hashMap.keySet(); for (String production : keySet) { //找到该产生式对应的结果集 TreeSet<String> treeSet = hashMap.get(production); //若结果集中包含当前的终结符,则返回该产生式 if (treeSet.contains(termin)) { return production; } } } catch (Exception e) { return null; } return null; } //获取分析表 public void genAnalyzeTable(){ //定义行与列,各用一个一维数组 Object[] nonTerminArray = nonTerminatorSet.toArray(); String[] terminArray = new String[terminatorSet.size()+1]; Iterator<String> iterator = terminatorSet.iterator(); int count = 0; while(iterator.hasNext()){ terminArray[count] = iterator.next(); count++; } //终结符不要忘了再一个"#" terminArray[terminatorSet.size()] = "#"; //初始化分析表 analyzeTable = new String[nonTerminArray.length+1][terminArray.length+1]; //表格左上角的说明 analyzeTable[0][0] = "Vn/Vt"; //初始化首行,即放入所有终结符 for(int i=0;i<terminArray.length;i++){ analyzeTable[0][i+1] = terminArray[i]+""; } for(int i=0;i<nonTerminArray.length;i++){ //初始化首列,即放入所有非终结符 analyzeTable[i+1][0] = nonTerminArray[i]+""; for(int j=0;j<terminArray.length;j++){ String nowProduction = findProduction(selectMap, nonTerminArray[i]+"", terminArray[j]+""); //System.out.println(nowProduction); if (nowProduction == null) { analyzeTable[i+1][j+1] = "×"; } else{ analyzeTable[i+1][j+1] = nowProduction; } } } } public void printAnalyzeTable(){ System.out.println("LL(1)分析表:"); for(int i=0;i<analyzeTable.length;i++){ for(int j=0;j<analyzeTable[i].length;j++){ System.out.printf(analyzeTable[i][j]+"\t\t"); } System.out.println(); } System.out.println(); } }
1
22
1
43102_1
package com.tencent.bugly.hotfix; /** * 测试bug类. * * @author devilwwj * @since 2016/10/25 */ public class BugClass { public String bug() { // 这段代码会报空指针异常 String str = null; int length = str.length(); return "This is a bug class"; } }
BuglyDevTeam/Bugly-Android-Demo
BuglyHotfixDemo/base/BugClass.java
100
// 这段代码会报空指针异常
line_comment
zh-cn
package com.tencent.bugly.hotfix; /** * 测试bug类. * * @author devilwwj * @since 2016/10/25 */ public class BugClass { public String bug() { // 这段 <SUF> String str = null; int length = str.length(); return "This is a bug class"; } }
0
14
0
65379_25
package org.bukkit.event.entity; import org.bukkit.Chunk; import org.bukkit.entity.LivingEntity; import org.bukkit.event.world.ChunkLoadEvent; import org.jetbrains.annotations.NotNull; /** * 当一个生物体在世界中出生时触发该事件. * <p> * 如果该事件被取消了,那么这个生物将不会出生. */ public class CreatureSpawnEvent extends EntitySpawnEvent { private final SpawnReason spawnReason; public CreatureSpawnEvent(@NotNull final LivingEntity spawnee, @NotNull final SpawnReason spawnReason) { super(spawnee); this.spawnReason = spawnReason; } @NotNull @Override public LivingEntity getEntity() { return (LivingEntity) entity; } /** * 返回生物出生的原因 * <p> * 原文: * Gets the reason for why the creature is being spawned. * * @return 出生原因 */ @NotNull public SpawnReason getSpawnReason() { return spawnReason; } /** * 生成原因的枚举类. */ public enum SpawnReason { /** * 自然生成 */ NATURAL, /** * 当实体因为乘骑而被生成时 (大多是蜘蛛骑士) */ JOCKEY, /** * 当区块产生而生成生物时 * * @deprecated 不再调用, 区块与已经存在的实体一同生成. * 请考虑使用{@link ChunkLoadEvent#isNewChunk()} 和 {@link Chunk#getEntities()} * 以达到类似效果 */ @Deprecated CHUNK_GEN, /** * 当生物由于刷怪箱生成时 */ SPAWNER, /** * 当生物由于蛋生成时 (不是刷怪蛋,是普通的鸡蛋) */ EGG, /** * 当生物由于刷怪蛋生成时 */ SPAWNER_EGG, /** * 当生物由于闪电而生成时 */ LIGHTNING, /** * 当雪人被建造时 */ BUILD_SNOWMAN, /** * 当一个铁傀儡被建造时 */ BUILD_IRONGOLEM, /** * 当一个凋零被建造时 */ BUILD_WITHER, /** * 当村庄生成保卫的铁傀儡时 */ VILLAGE_DEFENSE, /** * 当一个僵尸进攻村庄而生成时. */ VILLAGE_INVASION, /** * When an entity breeds to create a child, this also include Shulker and Allay */ BREEDING, /** * 当史莱姆分裂时 */ SLIME_SPLIT, /** * 当一个实体请求支援时 */ REINFORCEMENTS, /** * 当生物由于地狱传送门而生成时 */ NETHER_PORTAL, /** * 当生物由于投掷器丢出鸡蛋而生成时 */ DISPENSE_EGG, /** * 当一个僵尸感染一个村民时 */ INFECTION, /** * 当村民从僵尸状态痊愈时 */ CURED, /** * 当豹猫为了照顾自己的孩子而出生时 */ OCELOT_BABY, /** * 当一条蠹虫从方块中生成时 */ SILVERFISH_BLOCK, /** * 当一个实体成为其他实体坐骑时 (大多数时是鸡骑士) */ MOUNT, /** * 当实体作为陷阱陷害玩家时 */ TRAP, /** * 由于末影珍珠的使用而生成. */ ENDER_PEARL, /** * When an entity is spawned as a result of the entity it is being * perched on jumping or being damaged */ SHOULDER_ENTITY, /** * 当一个实体溺亡而生成时 */ DROWNED, /** * When an cow is spawned by shearing a mushroom cow */ SHEARED, /** * 由于苦力怕等发生爆炸产生效果云时/When eg an effect cloud is spawned as a result of a creeper exploding */ EXPLOSION, /** * When an entity is spawned as part of a raid */ RAID, /** * When an entity is spawned as part of a patrol */ PATROL, /** * When a bee is released from a beehive/bee nest */ BEEHIVE, /** * When a piglin is converted to a zombified piglin. */ PIGLIN_ZOMBIFIED, /** * When an entity is created by a cast spell. */ SPELL, /** * When an entity is shaking in Powder Snow and a new entity spawns. */ FROZEN, /** * When a tadpole converts to a frog */ METAMORPHOSIS, /** * When an Allay duplicate itself */ DUPLICATION, /** * When a creature is spawned by the "/summon" command */ COMMAND, /** * 当生物被插件生成时 */ CUSTOM, /** * 实体由于其他原因而生成 */ DEFAULT } }
BukkitAPI-Translation-Group/Chinese_BukkitAPI
BukkitApi/org/bukkit/event/entity/CreatureSpawnEvent.java
1,340
/** * 当实体作为陷阱陷害玩家时 */
block_comment
zh-cn
package org.bukkit.event.entity; import org.bukkit.Chunk; import org.bukkit.entity.LivingEntity; import org.bukkit.event.world.ChunkLoadEvent; import org.jetbrains.annotations.NotNull; /** * 当一个生物体在世界中出生时触发该事件. * <p> * 如果该事件被取消了,那么这个生物将不会出生. */ public class CreatureSpawnEvent extends EntitySpawnEvent { private final SpawnReason spawnReason; public CreatureSpawnEvent(@NotNull final LivingEntity spawnee, @NotNull final SpawnReason spawnReason) { super(spawnee); this.spawnReason = spawnReason; } @NotNull @Override public LivingEntity getEntity() { return (LivingEntity) entity; } /** * 返回生物出生的原因 * <p> * 原文: * Gets the reason for why the creature is being spawned. * * @return 出生原因 */ @NotNull public SpawnReason getSpawnReason() { return spawnReason; } /** * 生成原因的枚举类. */ public enum SpawnReason { /** * 自然生成 */ NATURAL, /** * 当实体因为乘骑而被生成时 (大多是蜘蛛骑士) */ JOCKEY, /** * 当区块产生而生成生物时 * * @deprecated 不再调用, 区块与已经存在的实体一同生成. * 请考虑使用{@link ChunkLoadEvent#isNewChunk()} 和 {@link Chunk#getEntities()} * 以达到类似效果 */ @Deprecated CHUNK_GEN, /** * 当生物由于刷怪箱生成时 */ SPAWNER, /** * 当生物由于蛋生成时 (不是刷怪蛋,是普通的鸡蛋) */ EGG, /** * 当生物由于刷怪蛋生成时 */ SPAWNER_EGG, /** * 当生物由于闪电而生成时 */ LIGHTNING, /** * 当雪人被建造时 */ BUILD_SNOWMAN, /** * 当一个铁傀儡被建造时 */ BUILD_IRONGOLEM, /** * 当一个凋零被建造时 */ BUILD_WITHER, /** * 当村庄生成保卫的铁傀儡时 */ VILLAGE_DEFENSE, /** * 当一个僵尸进攻村庄而生成时. */ VILLAGE_INVASION, /** * When an entity breeds to create a child, this also include Shulker and Allay */ BREEDING, /** * 当史莱姆分裂时 */ SLIME_SPLIT, /** * 当一个实体请求支援时 */ REINFORCEMENTS, /** * 当生物由于地狱传送门而生成时 */ NETHER_PORTAL, /** * 当生物由于投掷器丢出鸡蛋而生成时 */ DISPENSE_EGG, /** * 当一个僵尸感染一个村民时 */ INFECTION, /** * 当村民从僵尸状态痊愈时 */ CURED, /** * 当豹猫为了照顾自己的孩子而出生时 */ OCELOT_BABY, /** * 当一条蠹虫从方块中生成时 */ SILVERFISH_BLOCK, /** * 当一个实体成为其他实体坐骑时 (大多数时是鸡骑士) */ MOUNT, /** * 当实体 <SUF>*/ TRAP, /** * 由于末影珍珠的使用而生成. */ ENDER_PEARL, /** * When an entity is spawned as a result of the entity it is being * perched on jumping or being damaged */ SHOULDER_ENTITY, /** * 当一个实体溺亡而生成时 */ DROWNED, /** * When an cow is spawned by shearing a mushroom cow */ SHEARED, /** * 由于苦力怕等发生爆炸产生效果云时/When eg an effect cloud is spawned as a result of a creeper exploding */ EXPLOSION, /** * When an entity is spawned as part of a raid */ RAID, /** * When an entity is spawned as part of a patrol */ PATROL, /** * When a bee is released from a beehive/bee nest */ BEEHIVE, /** * When a piglin is converted to a zombified piglin. */ PIGLIN_ZOMBIFIED, /** * When an entity is created by a cast spell. */ SPELL, /** * When an entity is shaking in Powder Snow and a new entity spawns. */ FROZEN, /** * When a tadpole converts to a frog */ METAMORPHOSIS, /** * When an Allay duplicate itself */ DUPLICATION, /** * When a creature is spawned by the "/summon" command */ COMMAND, /** * 当生物被插件生成时 */ CUSTOM, /** * 实体由于其他原因而生成 */ DEFAULT } }
1
39
1
52506_0
package org.bukkit; /** * 一个处理方块更变的代表. 服务器作为一个计算服务器内生物生成和使用代码的 * 直接的接口. */ public interface BlockChangeDelegate { /** * 指定特定坐标方块的类型而不需要进行全世界更新并通知 * <p> * 通过调用World.setTypeId比较安全,但比可能使用World.setRawTypeId * 慢一些. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setRawTypeId(int x, int y, int z, int typeId); /** * 指定特定坐标方块的数据而不需要进行全世界更新并通知 * <p> * 通过调用World.setTypeId比较安全,但比可能使用World.setRawTypeId * 慢一些. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @param data 方块数据 * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setRawTypeIdAndData(int x, int y, int z, int typeId, int data); /** * 设置指定坐标的方块类型. * <p> * 这方式不需要调用World.setRawTypeId,但需要全局更新. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setTypeId(int x, int y, int z, int typeId); /** * 设置指定坐标的方块类型和数据. * <p> * 这方式不需要调用World.setRawTypeId,但需要全局更新. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @param data 方块数据 * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setTypeIdAndData(int x, int y, int z, int typeId, int data); /** * 获取某一位置的方块类型. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @deprecated Magic value */ @Deprecated public int getTypeId(int x, int y, int z); /** * 获取世界的高度. * * @return 世界的高度 */ public int getHeight(); /** * 检查指定的方块是否为空(空气). * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @return true 如果方块成功设置 */ public boolean isEmpty(int x, int y, int z); }
BukkitDocChinese/BukkitAPI
src/main/java/org/bukkit/BlockChangeDelegate.java
735
/** * 一个处理方块更变的代表. 服务器作为一个计算服务器内生物生成和使用代码的 * 直接的接口. */
block_comment
zh-cn
package org.bukkit; /** * 一个处 <SUF>*/ public interface BlockChangeDelegate { /** * 指定特定坐标方块的类型而不需要进行全世界更新并通知 * <p> * 通过调用World.setTypeId比较安全,但比可能使用World.setRawTypeId * 慢一些. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setRawTypeId(int x, int y, int z, int typeId); /** * 指定特定坐标方块的数据而不需要进行全世界更新并通知 * <p> * 通过调用World.setTypeId比较安全,但比可能使用World.setRawTypeId * 慢一些. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @param data 方块数据 * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setRawTypeIdAndData(int x, int y, int z, int typeId, int data); /** * 设置指定坐标的方块类型. * <p> * 这方式不需要调用World.setRawTypeId,但需要全局更新. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setTypeId(int x, int y, int z, int typeId); /** * 设置指定坐标的方块类型和数据. * <p> * 这方式不需要调用World.setRawTypeId,但需要全局更新. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @param data 方块数据 * @return true 如果方块成功设置 * @deprecated Magic value */ @Deprecated public boolean setTypeIdAndData(int x, int y, int z, int typeId, int data); /** * 获取某一位置的方块类型. * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @param typeId 新方块ID * @deprecated Magic value */ @Deprecated public int getTypeId(int x, int y, int z); /** * 获取世界的高度. * * @return 世界的高度 */ public int getHeight(); /** * 检查指定的方块是否为空(空气). * * @param x X 坐标 * @param y Y 坐标 * @param z Z 坐标 * @return true 如果方块成功设置 */ public boolean isEmpty(int x, int y, int z); }
1
57
1
47835_8
package class0103; import java.util.HashMap; import rlgs4.Stack; /** * @Description 算术表达式的中序遍历变成后序遍历 * @author Leon * @date 2016-05-31 17:08:35 */ public class InfixToPostfix { private static HashMap<Character,Integer> priority=new HashMap<Character,Integer>(){ private static final long serialVersionUID = 3714469304942582582L; { put('+', 1); put('-', 1); put('/', 2); put('*', 2); put('(', 0); } }; public static boolean isOperator(char c) { return c=='+'||c=='-'||c=='*'||c=='/'; } /** * 将带有计算的优先级和括号的中序表达式inOrder变成符合前述文法的后序表达式 */ public static String inToPost(String inOrder) { // 保存操作符 Stack<Character> stack = new Stack<Character>(); // postfix expresultsion String result = ""; // 保存s.pop() char tmp; char[] exp = inOrder.trim().toCharArray(); for (char x : exp) { // 如果是操作数,直接输出 if (!isOperator(x) && (x != '(') && (x != ')')) { result = result + x; } else if (x == '(') { stack.push(x); // 入栈 } else if (x == ')') { // 输出栈中的右操作符直到弹出'('为止 tmp = stack.pop(); while (tmp != '(') { result = result + tmp; tmp = stack.pop(); } tmp = '\0'; } else if (isOperator(x)) {// 与栈顶操作符比较优先级 if (!stack.isEmpty()) { tmp = stack.pop(); int prio1 = priority.get(tmp); int prio2 = priority.get(x); while (prio1 >= prio2) { result = result + tmp; // 如果栈顶优先级高则直接合并,出栈并重算 prio1 = -1; if (!stack.isEmpty()) { tmp = stack.pop(); prio1 = priority.get(tmp); } } if ((prio1 < prio2) && (prio1 != -1)) { stack.push(tmp); } } stack.push(x); } } while (!stack.isEmpty()) { tmp = stack.pop(); result = result + tmp; } return result; } public static void main(String[] args) { System.out.println(inToPost("1+2*3-4/5")); } }
BurningBright/algorithms-fourth-edition
src/class0103/InfixToPostfix.java
676
// 如果栈顶优先级高则直接合并,出栈并重算
line_comment
zh-cn
package class0103; import java.util.HashMap; import rlgs4.Stack; /** * @Description 算术表达式的中序遍历变成后序遍历 * @author Leon * @date 2016-05-31 17:08:35 */ public class InfixToPostfix { private static HashMap<Character,Integer> priority=new HashMap<Character,Integer>(){ private static final long serialVersionUID = 3714469304942582582L; { put('+', 1); put('-', 1); put('/', 2); put('*', 2); put('(', 0); } }; public static boolean isOperator(char c) { return c=='+'||c=='-'||c=='*'||c=='/'; } /** * 将带有计算的优先级和括号的中序表达式inOrder变成符合前述文法的后序表达式 */ public static String inToPost(String inOrder) { // 保存操作符 Stack<Character> stack = new Stack<Character>(); // postfix expresultsion String result = ""; // 保存s.pop() char tmp; char[] exp = inOrder.trim().toCharArray(); for (char x : exp) { // 如果是操作数,直接输出 if (!isOperator(x) && (x != '(') && (x != ')')) { result = result + x; } else if (x == '(') { stack.push(x); // 入栈 } else if (x == ')') { // 输出栈中的右操作符直到弹出'('为止 tmp = stack.pop(); while (tmp != '(') { result = result + tmp; tmp = stack.pop(); } tmp = '\0'; } else if (isOperator(x)) {// 与栈顶操作符比较优先级 if (!stack.isEmpty()) { tmp = stack.pop(); int prio1 = priority.get(tmp); int prio2 = priority.get(x); while (prio1 >= prio2) { result = result + tmp; // 如果 <SUF> prio1 = -1; if (!stack.isEmpty()) { tmp = stack.pop(); prio1 = priority.get(tmp); } } if ((prio1 < prio2) && (prio1 != -1)) { stack.push(tmp); } } stack.push(x); } } while (!stack.isEmpty()) { tmp = stack.pop(); result = result + tmp; } return result; } public static void main(String[] args) { System.out.println(inToPost("1+2*3-4/5")); } }
1
22
1
53097_4
package com.zskx.pemsystem.util; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.util.Log; public class AsyncImageLoader { public static String TAG = "AsyncImageLoader"; private HashMap<String, SoftReference<Drawable>> imageCache; private List<String> loadingUrls=new ArrayList<String>(); Drawable drawable; int i = 0; public AsyncImageLoader() { imageCache = new HashMap<String, SoftReference<Drawable>>(); } /** * 加载图片并处理 * * @param imageUrl * @param imageCallback */ public void loadDrawable(final String imageUrl, final ImageCallback imageCallback) { // Log.i(TAG, "loadDrawable:" + imageUrl); // 异步处理图片 final Handler handler = new Handler() { public void handleMessage(Message message) { if (message.obj != null){ imageCallback.imageLoaded((Drawable) message.obj, imageUrl); } } }; // 如果缓存内含有图片,直接返回缓存内图片 if (imageCache.containsKey(imageUrl)) { SoftReference<Drawable> softReference = imageCache.get(imageUrl); Drawable drawable = softReference.get(); if (drawable != null) { Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); return; } Log.i(TAG, "hashmap中有這個鑰匙值,但是還沒有獲取到圖片,這兒就到下面去!會出現再次訪問相同數據!"); } // 缓存内没有图片,开启线程下载图片 newThread(imageUrl, handler); System.out.println("i::::" + i); return; } private void newThread(final String imageUrl, final Handler handler) { if(imageUrl != null && !imageUrl.equals("") && !loadingUrls.contains(imageUrl)) new Thread() { @Override public void run() { Drawable drawable = null; if (drawable == null) { drawable = loadImageFromUrl(imageUrl); } // Log.i(TAG, "drawable:" + drawable); if(drawable != null) { loadingUrls.add(imageUrl); imageCache.put(imageUrl, new SoftReference<Drawable>(drawable)); loadingUrls.remove(imageUrl); Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); drawable = null;// 重置引用。 }else{ i++; if(i <= 3){ newThread(imageUrl, handler); } } drawable = null;// 重置引用。 } }.start(); } /** * 从网络下载图片 * * @param url * @return */ public static Drawable loadImageFromUrl(String url) { Log.i(TAG, "loadImageFromUrl:" + url); URL m; Drawable d = null; try { m = new URL(url); HttpURLConnection hcc = (HttpURLConnection) m.openConnection(); hcc.connect(); if (hcc.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream i = hcc.getInputStream(); Bitmap dd = BitmapFactory.decodeStream(i); BitmapDrawable bd= new BitmapDrawable(dd); d = bd; // d = Drawable.createFromStream(i, "src"); i.close(); } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e2) { e2.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } return d; } /** * 异步处理图片的接口方法 * * @author guokai * */ public interface ImageCallback { public void imageLoaded(Drawable imageDrawable, String imageUrl); } }
Buwder/nibiru-vr-android-app
android/PEMsystem_V1.0/src/com/zskx/pemsystem/util/AsyncImageLoader.java
1,115
// 缓存内没有图片,开启线程下载图片
line_comment
zh-cn
package com.zskx.pemsystem.util; import java.io.IOException; import java.io.InputStream; import java.lang.ref.SoftReference; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Message; import android.util.Log; public class AsyncImageLoader { public static String TAG = "AsyncImageLoader"; private HashMap<String, SoftReference<Drawable>> imageCache; private List<String> loadingUrls=new ArrayList<String>(); Drawable drawable; int i = 0; public AsyncImageLoader() { imageCache = new HashMap<String, SoftReference<Drawable>>(); } /** * 加载图片并处理 * * @param imageUrl * @param imageCallback */ public void loadDrawable(final String imageUrl, final ImageCallback imageCallback) { // Log.i(TAG, "loadDrawable:" + imageUrl); // 异步处理图片 final Handler handler = new Handler() { public void handleMessage(Message message) { if (message.obj != null){ imageCallback.imageLoaded((Drawable) message.obj, imageUrl); } } }; // 如果缓存内含有图片,直接返回缓存内图片 if (imageCache.containsKey(imageUrl)) { SoftReference<Drawable> softReference = imageCache.get(imageUrl); Drawable drawable = softReference.get(); if (drawable != null) { Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); return; } Log.i(TAG, "hashmap中有這個鑰匙值,但是還沒有獲取到圖片,這兒就到下面去!會出現再次訪問相同數據!"); } // 缓存 <SUF> newThread(imageUrl, handler); System.out.println("i::::" + i); return; } private void newThread(final String imageUrl, final Handler handler) { if(imageUrl != null && !imageUrl.equals("") && !loadingUrls.contains(imageUrl)) new Thread() { @Override public void run() { Drawable drawable = null; if (drawable == null) { drawable = loadImageFromUrl(imageUrl); } // Log.i(TAG, "drawable:" + drawable); if(drawable != null) { loadingUrls.add(imageUrl); imageCache.put(imageUrl, new SoftReference<Drawable>(drawable)); loadingUrls.remove(imageUrl); Message message = handler.obtainMessage(0, drawable); handler.sendMessage(message); drawable = null;// 重置引用。 }else{ i++; if(i <= 3){ newThread(imageUrl, handler); } } drawable = null;// 重置引用。 } }.start(); } /** * 从网络下载图片 * * @param url * @return */ public static Drawable loadImageFromUrl(String url) { Log.i(TAG, "loadImageFromUrl:" + url); URL m; Drawable d = null; try { m = new URL(url); HttpURLConnection hcc = (HttpURLConnection) m.openConnection(); hcc.connect(); if (hcc.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream i = hcc.getInputStream(); Bitmap dd = BitmapFactory.decodeStream(i); BitmapDrawable bd= new BitmapDrawable(dd); d = bd; // d = Drawable.createFromStream(i, "src"); i.close(); } } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e2) { e2.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } return d; } /** * 异步处理图片的接口方法 * * @author guokai * */ public interface ImageCallback { public void imageLoaded(Drawable imageDrawable, String imageUrl); } }
1
19
1
36148_0
package org.byron4j.cookbook.designpattern.builder; /** * 晚餐实体类 */ public class Meal { private String sandwich; private String sideOrder; private String drink; private String offer; private double price; @Override public String toString() { return "Meal{" + "sandwich='" + sandwich + '\'' + ", sideOrder='" + sideOrder + '\'' + ", drink='" + drink + '\'' + ", offer='" + offer + '\'' + ", price='" + price + '\'' + '}'; } public void setSandwich(String sandwich) { this.sandwich = sandwich; } public void setSideOrder(String sideOrder) { this.sideOrder = sideOrder; } public void setDrink(String drink) { this.drink = drink; } public void setOffer(String offer) { this.offer = offer; } public void setPrice(double price) { this.price = price; } }
Byron4j/CookBook
src/main/java/org/byron4j/cookbook/designpattern/builder/Meal.java
245
/** * 晚餐实体类 */
block_comment
zh-cn
package org.byron4j.cookbook.designpattern.builder; /** * 晚餐实 <SUF>*/ public class Meal { private String sandwich; private String sideOrder; private String drink; private String offer; private double price; @Override public String toString() { return "Meal{" + "sandwich='" + sandwich + '\'' + ", sideOrder='" + sideOrder + '\'' + ", drink='" + drink + '\'' + ", offer='" + offer + '\'' + ", price='" + price + '\'' + '}'; } public void setSandwich(String sandwich) { this.sandwich = sandwich; } public void setSideOrder(String sideOrder) { this.sideOrder = sideOrder; } public void setDrink(String drink) { this.drink = drink; } public void setOffer(String offer) { this.offer = offer; } public void setPrice(double price) { this.price = price; } }
1
16
1
59121_3
package com.byronlee; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class main extends Activity{ public void onCreat(Bundle savedInstanceState){ super.onCreate(savedInstanceState); //强制全屏 //首先去掉title,就是没有title 那一行,但是还不是全屏 requestWindowFeature(Window.FEATURE_NO_TITLE); // 禁止屏幕休眠 getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //去掉状态栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } }
Byronlee/ByronleeTeeter
src/com/byronlee/main.java
200
//去掉状态栏
line_comment
zh-cn
package com.byronlee; import android.app.Activity; import android.os.Bundle; import android.view.Window; import android.view.WindowManager; public class main extends Activity{ public void onCreat(Bundle savedInstanceState){ super.onCreate(savedInstanceState); //强制全屏 //首先去掉title,就是没有title 那一行,但是还不是全屏 requestWindowFeature(Window.FEATURE_NO_TITLE); // 禁止屏幕休眠 getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); //去掉 <SUF> getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } }
1
8
1
12269_1
package cn.byteforge.openqq.http.entity; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Arrays; /** * 表情枚举类 * <a href="https://github.com/kyubotics/coolq-http-api/wiki/%E8%A1%A8%E6%83%85-CQ-%E7%A0%81-ID-%E8%A1%A8"> * https://github.com/kyubotics/coolq-http-api/wiki/%E8%A1%A8%E6%83%85-CQ-%E7%A0%81-ID-%E8%A1%A8 * </a> * */ @Getter @AllArgsConstructor public enum FaceType { UNKNOWN(-1, "未知"), JY(0, "惊讶"), PZ(1, "撇嘴"), SE(2, "色"), FD(3, "发呆"), DY(4, "得意"), LL(5, "流泪"), HX(6, "害羞"), BZ(7, "闭嘴"), SHUI(8, "睡"), DK(9, "大哭"), GG(10, "尴尬"), FN(11, "发怒"), TP(12, "调皮"), CY(13, "呲牙"), WX(14, "微笑"), NG(15, "难过"), KUK(16, "酷"), ZK(18, "抓狂"), TUU(19, "吐"), TX(20, "偷笑"), KA(21, "可爱"), BAIY(22, "白眼"), AM(23, "傲慢"), JIE(24, "饥饿"), KUN(25, "困"), JK(26, "惊恐"), LH(27, "流汗"), HANX(28, "憨笑"), DB(29, "悠闲"), FENDOU(30, "奋斗"), ZHM(31, "咒骂"), YIW(32, "疑问"), XU(33, "嘘"), YUN(34, "晕"), ZHEM(35, "折磨"), SHUAI(36, "衰"), KL(37, "骷髅"), QIAO(38, "敲打"), ZJ(39, "再见"), FAD(41, "发抖"), AIQ(42, "爱情"), TIAO(43, "跳跳"), ZT(46, "猪头"), YB(49, "拥抱"), DG(53, "蛋糕"), SHD(54, "闪电"), ZHD(55, "炸弹"), DAO(56, "刀"), ZQ(57, "足球"), BB(59, "便便"), KF(60, "咖啡"), FAN(61, "饭"), YAO(62, "药"), MG(63, "玫瑰"), DX(64, "凋谢"), XIN(66, "爱心"), XS(67, "心碎"), LW(69, "礼物"), _072(72, "信封", true), TY(74, "太阳"), YL(75, "月亮"), QIANG(76, "赞"), RUO(77, "踩"), WS(78, "握手"), SHL(79, "胜利"), FW(85, "飞吻"), OH(86, "怄火"), XIG(89, "西瓜"), _090(90, "下雨", true), _091(91, "多云", true), LENGH(96, "冷汗"), CH(97, "擦汗"), KB(98, "抠鼻"), GZ(99, "鼓掌"), QD(100, "糗大了"), HUAIX(101, "坏笑"), ZHH(102, "左哼哼"), YHH(103, "右哼哼"), HQ(104, "哈欠"), BS(105, "鄙视"), WQ(106, "委屈"), KK(107, "快哭了"), YX(108, "阴险"), QQ(109, "左亲戚"), XIA(110, "吓"), XJJ(111, "小纠结"), CD(112, "菜刀"), PJ(113, "啤酒"), LQ(114, "篮球"), PP(115, "乒乓"), SA(116, "示爱"), PCH(117, "瓢虫"), BQ(118, "抱拳"), GY(119, "勾引"), QT(120, "拳头"), CJ(121, "差劲"), AINI(122, "爱你"), BU(123, "NO"), HD(124, "OK"), ZHQ(125, "转圈"), KT(126, "磕头"), HT(127, "回头"), TSH(128, "跳绳"), HSH(129, "挥手"), JD(130, "激动"), JW(131, "街舞"), XW(132, "献吻"), ZUOTJ(133, "左太极"), YOUTJ(134, "右太极"), SHX(136, "双喜"), BP(137, "嗨皮牛耶"), DL(138, "灯笼"), _139(139, "发财", true), KG(140, "K歌", true), _141(141, "购物", true), _142(142, "信封", true), _143(143, "帅", true), HEC(144, "喝彩"), QIDAO(145, "祈祷"), BAOJIN(146, "爆筋"), BANGBANGT(147, "棒棒糖"), HN(148, "喝奶"), _149(149, "面条", true), _150(150, "香蕉", true), FJ(151, "飞机"), _152(152, "汽车", true), _153(153, "左车头", true), _154(154, "车厢", true), _155(155, "右车头", true), _156(156, "下雨", true), _157(157, "多云", true), CP(158, "钞票"), _159(159, "熊猫", true), _160(160, "灯泡", true), _161(161, "小风车", true), _162(162, "闹钟", true), _163(163, "雨伞", true), _164(164, "气球", true), _165(165, "钻戒", true), _166(166, "沙发", true), _167(167, "卷纸", true), YAO_(168, "药"), SHQ(169, "手枪"), _170(170, "青蛙", true), CHA(171, "茶"), ZYJ(172, "眨眼睛"), LB(173, "泪奔"), WN(174, "无奈"), MM(175, "卖萌"), XJJ_(176, "小纠结"), PX(177, "喷血"), XYX(178, "斜眼笑"), DOGE(179, "doge"), JX(180, "惊喜"), SR(181, "骚扰"), XK(182, "笑哭"), WZM(183, "我最美"), XHX(184, "河蟹"), YT(185, "羊驼"), _186(186, "栗子", true), YOUL(187, "幽灵"), DAN(188, "蛋"), _189(189, "九宫格", true), JH(190, "菊花"), _191(191, "香皂", true), HB(192, "红包"), DX_(193, "大笑"), BKX(194, "不开心"), LM(197, "冷漠"), EE(198, "呃呃"), HAOB(199, "好棒"), BT(200, "拜托"), DZ(201, "点赞"), WL(202, "无聊"), TL(203, "托脸"), CHI(204, "吃"), SH(205, "送花"), HP(206, "害怕"), HC(207, "花痴"), XY(208, "小样"), BL(210, "飙泪"), WBK(211, "我不看"), TS(212, "托腮"), _214(214, "啵啵"), _215(215, "糊脸"), _216(216, "拍头"), _217(217, "扯一扯"), _218(218, "舔一舔"), _219(219, "蹭一蹭"), _220(220, "酷", true), _221(221, "顶呱呱"), _222(222, "抱抱"), _223(223, "暴击"), _224(224, "开枪"), _225(225, "撩一撩"), _226(226, "拍桌"), _227(227, "拍手"), _229(229, "干杯"), _230(230, "嘲讽"), _231(231, "哼"), _232(232, "佛系"), _233(233, "掐一掐"), _235(235, "颤抖"), _237(237, "偷看"), _238(238, "扇脸"), _239(239, "原谅"), _240(240, "喷脸"), _241(241, "生日快乐"), _243(243, "甩头"), _244(244, "扔狗"), _262(262, "脑阔疼"), _263(263, "沧桑"), _264(264, "捂脸"), _265(265, "辣眼睛"), _266(266, "哦哟"), _267(267, "头秃"), _268(268, "问号脸"), _269(269, "暗中观察"), _270(270, "emm"), _271(271, "吃瓜"), _272(272, "呵呵哒"), _273(273, "我酸了"), WW(277, "汪汪"), _278(278, "汗"), _281(281, "无眼笑"), _282(282, "敬礼"), _283(283, "狂笑"), _284(284, "面无表情"), _285(285, "摸鱼"), _286(286, "魔鬼笑"), _287(287, "哦"), _288(288, "请"), _289(289, "睁眼"), _290(290, "敲开心"), _292(292, "让我康康"), _293(293, "摸锦鲤"), _294(294, "期待"), _295(295, "拿到红包"), _297(297, "拜谢"), _298(298, "元宝"), _299(299, "牛啊"), _300(300, "胖三斤"), _301(301, "好闪"), _302(302, "左拜年"), _303(303, "右拜年"), _306(306, "牛气冲天"), _307(307, "喵喵"), _311(311, "打call"), _312(312, "变形"), _314(314, "仔细分析"), _317(317, "菜汪"), _318(318, "崇拜"), _319(319, "比心"), _322(322, "拒绝"), _323(323, "嫌弃"), _324(324, "庆祝"), _325(325, "吃糖"), _326(326, "生气"), _332(332, "举牌牌"), _333(333, "烟花"), _334(334, "虎虎生威"), _336(336, "豹富"), _337(337, "花朵脸"), _338(338, "我想开了"), _339(339, "舔屏"), _341(341, "打招呼"), _342(342, "酸Q"), _343(343, "我方了"), _344(344, "大怨种"), _345(345, "红包多多"), _346(346, "你真棒棒"), _347(347, "大展宏兔"), _348(348, "福萝卜"); private final Integer id; /** * 表情名称 * @apiNote 默认为快捷键标识,以 _ 开头的名称表示该表情无快捷键 * */ private final String name; /** * 该表情当前是否属于经典表情 * */ private final boolean deprecated; FaceType(Integer id, String name) { this(id, name, false); } public static FaceType getFaceType(int id) { if (id < 0) return UNKNOWN; return Arrays.stream(FaceType.values()) .filter(face -> face.id == id) .findFirst() .orElse(UNKNOWN); } }
ByteForgeTech/openqq-java
openqq-for-java/src/main/java/cn/byteforge/openqq/http/entity/FaceType.java
4,181
/** * 表情名称 * @apiNote 默认为快捷键标识,以 _ 开头的名称表示该表情无快捷键 * */
block_comment
zh-cn
package cn.byteforge.openqq.http.entity; import lombok.AllArgsConstructor; import lombok.Getter; import java.util.Arrays; /** * 表情枚举类 * <a href="https://github.com/kyubotics/coolq-http-api/wiki/%E8%A1%A8%E6%83%85-CQ-%E7%A0%81-ID-%E8%A1%A8"> * https://github.com/kyubotics/coolq-http-api/wiki/%E8%A1%A8%E6%83%85-CQ-%E7%A0%81-ID-%E8%A1%A8 * </a> * */ @Getter @AllArgsConstructor public enum FaceType { UNKNOWN(-1, "未知"), JY(0, "惊讶"), PZ(1, "撇嘴"), SE(2, "色"), FD(3, "发呆"), DY(4, "得意"), LL(5, "流泪"), HX(6, "害羞"), BZ(7, "闭嘴"), SHUI(8, "睡"), DK(9, "大哭"), GG(10, "尴尬"), FN(11, "发怒"), TP(12, "调皮"), CY(13, "呲牙"), WX(14, "微笑"), NG(15, "难过"), KUK(16, "酷"), ZK(18, "抓狂"), TUU(19, "吐"), TX(20, "偷笑"), KA(21, "可爱"), BAIY(22, "白眼"), AM(23, "傲慢"), JIE(24, "饥饿"), KUN(25, "困"), JK(26, "惊恐"), LH(27, "流汗"), HANX(28, "憨笑"), DB(29, "悠闲"), FENDOU(30, "奋斗"), ZHM(31, "咒骂"), YIW(32, "疑问"), XU(33, "嘘"), YUN(34, "晕"), ZHEM(35, "折磨"), SHUAI(36, "衰"), KL(37, "骷髅"), QIAO(38, "敲打"), ZJ(39, "再见"), FAD(41, "发抖"), AIQ(42, "爱情"), TIAO(43, "跳跳"), ZT(46, "猪头"), YB(49, "拥抱"), DG(53, "蛋糕"), SHD(54, "闪电"), ZHD(55, "炸弹"), DAO(56, "刀"), ZQ(57, "足球"), BB(59, "便便"), KF(60, "咖啡"), FAN(61, "饭"), YAO(62, "药"), MG(63, "玫瑰"), DX(64, "凋谢"), XIN(66, "爱心"), XS(67, "心碎"), LW(69, "礼物"), _072(72, "信封", true), TY(74, "太阳"), YL(75, "月亮"), QIANG(76, "赞"), RUO(77, "踩"), WS(78, "握手"), SHL(79, "胜利"), FW(85, "飞吻"), OH(86, "怄火"), XIG(89, "西瓜"), _090(90, "下雨", true), _091(91, "多云", true), LENGH(96, "冷汗"), CH(97, "擦汗"), KB(98, "抠鼻"), GZ(99, "鼓掌"), QD(100, "糗大了"), HUAIX(101, "坏笑"), ZHH(102, "左哼哼"), YHH(103, "右哼哼"), HQ(104, "哈欠"), BS(105, "鄙视"), WQ(106, "委屈"), KK(107, "快哭了"), YX(108, "阴险"), QQ(109, "左亲戚"), XIA(110, "吓"), XJJ(111, "小纠结"), CD(112, "菜刀"), PJ(113, "啤酒"), LQ(114, "篮球"), PP(115, "乒乓"), SA(116, "示爱"), PCH(117, "瓢虫"), BQ(118, "抱拳"), GY(119, "勾引"), QT(120, "拳头"), CJ(121, "差劲"), AINI(122, "爱你"), BU(123, "NO"), HD(124, "OK"), ZHQ(125, "转圈"), KT(126, "磕头"), HT(127, "回头"), TSH(128, "跳绳"), HSH(129, "挥手"), JD(130, "激动"), JW(131, "街舞"), XW(132, "献吻"), ZUOTJ(133, "左太极"), YOUTJ(134, "右太极"), SHX(136, "双喜"), BP(137, "嗨皮牛耶"), DL(138, "灯笼"), _139(139, "发财", true), KG(140, "K歌", true), _141(141, "购物", true), _142(142, "信封", true), _143(143, "帅", true), HEC(144, "喝彩"), QIDAO(145, "祈祷"), BAOJIN(146, "爆筋"), BANGBANGT(147, "棒棒糖"), HN(148, "喝奶"), _149(149, "面条", true), _150(150, "香蕉", true), FJ(151, "飞机"), _152(152, "汽车", true), _153(153, "左车头", true), _154(154, "车厢", true), _155(155, "右车头", true), _156(156, "下雨", true), _157(157, "多云", true), CP(158, "钞票"), _159(159, "熊猫", true), _160(160, "灯泡", true), _161(161, "小风车", true), _162(162, "闹钟", true), _163(163, "雨伞", true), _164(164, "气球", true), _165(165, "钻戒", true), _166(166, "沙发", true), _167(167, "卷纸", true), YAO_(168, "药"), SHQ(169, "手枪"), _170(170, "青蛙", true), CHA(171, "茶"), ZYJ(172, "眨眼睛"), LB(173, "泪奔"), WN(174, "无奈"), MM(175, "卖萌"), XJJ_(176, "小纠结"), PX(177, "喷血"), XYX(178, "斜眼笑"), DOGE(179, "doge"), JX(180, "惊喜"), SR(181, "骚扰"), XK(182, "笑哭"), WZM(183, "我最美"), XHX(184, "河蟹"), YT(185, "羊驼"), _186(186, "栗子", true), YOUL(187, "幽灵"), DAN(188, "蛋"), _189(189, "九宫格", true), JH(190, "菊花"), _191(191, "香皂", true), HB(192, "红包"), DX_(193, "大笑"), BKX(194, "不开心"), LM(197, "冷漠"), EE(198, "呃呃"), HAOB(199, "好棒"), BT(200, "拜托"), DZ(201, "点赞"), WL(202, "无聊"), TL(203, "托脸"), CHI(204, "吃"), SH(205, "送花"), HP(206, "害怕"), HC(207, "花痴"), XY(208, "小样"), BL(210, "飙泪"), WBK(211, "我不看"), TS(212, "托腮"), _214(214, "啵啵"), _215(215, "糊脸"), _216(216, "拍头"), _217(217, "扯一扯"), _218(218, "舔一舔"), _219(219, "蹭一蹭"), _220(220, "酷", true), _221(221, "顶呱呱"), _222(222, "抱抱"), _223(223, "暴击"), _224(224, "开枪"), _225(225, "撩一撩"), _226(226, "拍桌"), _227(227, "拍手"), _229(229, "干杯"), _230(230, "嘲讽"), _231(231, "哼"), _232(232, "佛系"), _233(233, "掐一掐"), _235(235, "颤抖"), _237(237, "偷看"), _238(238, "扇脸"), _239(239, "原谅"), _240(240, "喷脸"), _241(241, "生日快乐"), _243(243, "甩头"), _244(244, "扔狗"), _262(262, "脑阔疼"), _263(263, "沧桑"), _264(264, "捂脸"), _265(265, "辣眼睛"), _266(266, "哦哟"), _267(267, "头秃"), _268(268, "问号脸"), _269(269, "暗中观察"), _270(270, "emm"), _271(271, "吃瓜"), _272(272, "呵呵哒"), _273(273, "我酸了"), WW(277, "汪汪"), _278(278, "汗"), _281(281, "无眼笑"), _282(282, "敬礼"), _283(283, "狂笑"), _284(284, "面无表情"), _285(285, "摸鱼"), _286(286, "魔鬼笑"), _287(287, "哦"), _288(288, "请"), _289(289, "睁眼"), _290(290, "敲开心"), _292(292, "让我康康"), _293(293, "摸锦鲤"), _294(294, "期待"), _295(295, "拿到红包"), _297(297, "拜谢"), _298(298, "元宝"), _299(299, "牛啊"), _300(300, "胖三斤"), _301(301, "好闪"), _302(302, "左拜年"), _303(303, "右拜年"), _306(306, "牛气冲天"), _307(307, "喵喵"), _311(311, "打call"), _312(312, "变形"), _314(314, "仔细分析"), _317(317, "菜汪"), _318(318, "崇拜"), _319(319, "比心"), _322(322, "拒绝"), _323(323, "嫌弃"), _324(324, "庆祝"), _325(325, "吃糖"), _326(326, "生气"), _332(332, "举牌牌"), _333(333, "烟花"), _334(334, "虎虎生威"), _336(336, "豹富"), _337(337, "花朵脸"), _338(338, "我想开了"), _339(339, "舔屏"), _341(341, "打招呼"), _342(342, "酸Q"), _343(343, "我方了"), _344(344, "大怨种"), _345(345, "红包多多"), _346(346, "你真棒棒"), _347(347, "大展宏兔"), _348(348, "福萝卜"); private final Integer id; /** * 表情名 <SUF>*/ private final String name; /** * 该表情当前是否属于经典表情 * */ private final boolean deprecated; FaceType(Integer id, String name) { this(id, name, false); } public static FaceType getFaceType(int id) { if (id < 0) return UNKNOWN; return Arrays.stream(FaceType.values()) .filter(face -> face.id == id) .findFirst() .orElse(UNKNOWN); } }
0
69
0
60179_20
package com.anna.ft_home.view.home; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import androidx.drawerlayout.widget.DrawerLayout; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.viewpager.widget.ViewPager; import com.alibaba.android.arouter.launcher.ARouter; import com.anna.ft_home.R; import com.anna.ft_home.model.CHANNEL; import com.anna.ft_home.view.home.adapter.HomePagerAdapter; import com.anna.lib_base.module.audio.AudioImpl; import com.anna.lib_base.module.audio.model.CommonAudioBean; import com.anna.lib_base.module.login.LoginImpl; import com.anna.lib_common_ui.base.BaseActivity; import com.anna.lib_common_ui.base.constant.Constant; import com.anna.lib_common_ui.pager_indictor.ScaleTransitionPagerTitleView; import net.lucode.hackware.magicindicator.MagicIndicator; import net.lucode.hackware.magicindicator.ViewPagerHelper; import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView; import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView; import java.util.ArrayList; /** * 首页Activity */ public class HomeActivity extends BaseActivity implements View.OnClickListener { private static final CHANNEL[] CHANNELS = new CHANNEL[]{CHANNEL.MY, CHANNEL.DISCORY, CHANNEL.FRIEND}; private UpdateReceiver mReceiver = null; /* * View */ private DrawerLayout mDrawerLayout; private View mToggleView; private View mSearchView; private ViewPager mViewPager; private HomePagerAdapter mAdapter; private View mDrawerQrcodeView; private View mDrawerShareView; private View unLogginLayout; private ImageView mPhotoView; public static void start(Context context) { Intent intent = new Intent(context, HomeActivity.class); context.startActivity(intent); } /* * data */ private ArrayList<CommonAudioBean> mLists = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerBroadcastReceiver(); // EventBus.getDefault().register(this); setContentView(R.layout.activity_main); initView(); initData(); } private void initData() { mLists.add(new CommonAudioBean("100001", "http://sp-sycdn.kuwo.cn/resource/n2/85/58/433900159.mp3", "我走后", "小咪", "生而为人", "为梦想打拼的每一个个体都是闪光的,为梦想打拼的每一个个体都是闪光的,为梦想打拼的每一个个体都是闪光的。", "http://img0.imgtn.bdimg.com/it/u=2329770966,4069416364&fm=26&gp=0.jpg", "4:30")); mLists.add( new CommonAudioBean("100002", "http://sq-sycdn.kuwo.cn/resource/n1/98/51/3777061809.mp3", "勇气", "梁静茹", "勇气", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://b-ssl.duitang.com/uploads/item/201707/01/20170701182157_5eMn2.jpeg", "4:40")); mLists.add( new CommonAudioBean("100003", "http://sp-sycdn.kuwo.cn/resource/n2/52/80/2933081485.mp3", "灿烂如你", "汪峰", "春天里", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://img3.imgtn.bdimg.com/it/u=2136332768,653918923&fm=26&gp=0.jpg", "3:20")); mLists.add( new CommonAudioBean("100004", "http://sr-sycdn.kuwo.cn/resource/n2/33/25/2629654819.mp3", "小情歌", "五月天", "小幸运", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://pic1.win4000.com/mobile/2018-10-08/5bbb0343355a0.jpg", "2:45")); AudioImpl.getInstance().setQueue(mLists); } private void initView() { mDrawerLayout = findViewById(R.id.drawer_layout); mToggleView = findViewById(R.id.toggle_view); mToggleView.setOnClickListener(this); mSearchView = findViewById(R.id.search_view); mSearchView.setOnClickListener(this); //初始化adpater mAdapter = new HomePagerAdapter(getSupportFragmentManager(), CHANNELS); mViewPager = findViewById(R.id.view_pager); mViewPager.setAdapter(mAdapter); initMagicIndicator(); mDrawerQrcodeView = findViewById(R.id.home_qrcode); mDrawerQrcodeView.setOnClickListener(this); mDrawerShareView = findViewById(R.id.home_music); mDrawerShareView.setOnClickListener(this); findViewById(R.id.online_music_view).setOnClickListener(this); findViewById(R.id.check_update_view).setOnClickListener(this); unLogginLayout = findViewById(R.id.unloggin_layout); unLogginLayout.setOnClickListener(this); mPhotoView = findViewById(R.id.avatr_view); findViewById(R.id.exit_layout).setOnClickListener(this); DisplayMetrics dm = new DisplayMetrics(); WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(dm); Log.d("tag1112:","width:"+dm.widthPixels); } private void initMagicIndicator() { MagicIndicator magicIndicator = findViewById(R.id.magic_indicator); magicIndicator.setBackgroundColor(Color.WHITE); CommonNavigator commonNavigator = new CommonNavigator(this); commonNavigator.setAdjustMode(true); commonNavigator.setAdapter(new CommonNavigatorAdapter() { @Override public int getCount() { return CHANNELS == null ? 0 : CHANNELS.length; } @Override public IPagerTitleView getTitleView(Context context, final int index) { SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); simplePagerTitleView.setText(CHANNELS[index].getKey()); simplePagerTitleView.setTextSize(19); simplePagerTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); simplePagerTitleView.setNormalColor(Color.parseColor("#999999")); simplePagerTitleView.setSelectedColor(Color.parseColor("#333333")); simplePagerTitleView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mViewPager.setCurrentItem(index); } }); return simplePagerTitleView; } @Override public IPagerIndicator getIndicator(Context context) { return null; } @Override public float getTitleWeight(Context context, int index) { return 1.0f; } }); magicIndicator.setNavigator(commonNavigator); ViewPagerHelper.bind(magicIndicator, mViewPager); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.exit_layout) { finish(); System.exit(0); } else if (id == R.id.unloggin_layout) { if (!LoginImpl.getInstance().hasLogin()) { LoginImpl.getInstance().login(this); } else { mDrawerLayout.closeDrawer(Gravity.LEFT); } } else if (id == R.id.toggle_view) { if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { mDrawerLayout.closeDrawer(Gravity.LEFT); } else { mDrawerLayout.openDrawer(Gravity.LEFT); } } else if (id == R.id.home_qrcode) { if (hasPermission(Constant.HARDWEAR_CAMERA_PERMISSION)) { doCameraPermission(); } else { requestPermission(Constant.HARDWEAR_CAMERA_CODE, Constant.HARDWEAR_CAMERA_PERMISSION); } } else if (id == R.id.home_music) {//shareFriend(); goToMusic(); } else if (id == R.id.online_music_view) {//跳到指定webactivity gotoWebView("https://www.imooc.com"); } else if (id == R.id.check_update_view) { checkUpdate(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { //退出不销毁task中activity moveTaskToBack(true); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { super.onDestroy(); // EventBus.getDefault().unregister(this); unRegisterBroadcastReceiver(); } @Override public void doCameraPermission() { // ARouter.getInstance().build(Constant.Router.ROUTER_CAPTURE_ACTIVIYT).navigation(); } private void goToMusic() { // ARouter.getInstance().build(Constant.Router.ROUTER_MUSIC_ACTIVIYT).navigation(); } private void gotoWebView(String url) { ARouter.getInstance() .build(Constant.Router.ROUTER_WEB_ACTIVIYT) .withString("url", url) .navigation(); } //启动检查更新 private void checkUpdate() { // UpdateHelper.checkUpdate(this); } private void registerBroadcastReceiver() { // if (mReceiver == null) { // mReceiver = new UpdateReceiver(); // LocalBroadcastManager.getInstance(this) // .registerReceiver(mReceiver, new IntentFilter(UpdateHelper.UPDATE_ACTION)); // } } private void unRegisterBroadcastReceiver() { if (mReceiver != null) { LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); } } /** * 接收Update发送的广播 */ public class UpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //启动安装页面 // context.startActivity( // Utils.getInstallApkIntent(context, intent.getStringExtra(UpdateHelper.UPDATE_FILE_KEY))); } } // /** // * 处理登陆事件 // */ // @Subscribe(threadMode = ThreadMode.MAIN) // public void onLoginEvent(LoginEvent event) { // unLogginLayout.setVisibility(View.GONE); // mPhotoView.setVisibility(View.VISIBLE); // CustomImageLoader.getInstance() // .displayImageForCircleView(mPhotoView, UserManager.getInstance().getUser().data.photoUrl); // } }
ByteYuhb/anna_music_app
ft_home/src/main/java/com/anna/ft_home/view/home/HomeActivity.java
3,034
//启动检查更新
line_comment
zh-cn
package com.anna.ft_home.view.home; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.graphics.Typeface; import android.os.Bundle; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.ImageView; import androidx.drawerlayout.widget.DrawerLayout; import androidx.localbroadcastmanager.content.LocalBroadcastManager; import androidx.viewpager.widget.ViewPager; import com.alibaba.android.arouter.launcher.ARouter; import com.anna.ft_home.R; import com.anna.ft_home.model.CHANNEL; import com.anna.ft_home.view.home.adapter.HomePagerAdapter; import com.anna.lib_base.module.audio.AudioImpl; import com.anna.lib_base.module.audio.model.CommonAudioBean; import com.anna.lib_base.module.login.LoginImpl; import com.anna.lib_common_ui.base.BaseActivity; import com.anna.lib_common_ui.base.constant.Constant; import com.anna.lib_common_ui.pager_indictor.ScaleTransitionPagerTitleView; import net.lucode.hackware.magicindicator.MagicIndicator; import net.lucode.hackware.magicindicator.ViewPagerHelper; import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator; import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView; import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView; import java.util.ArrayList; /** * 首页Activity */ public class HomeActivity extends BaseActivity implements View.OnClickListener { private static final CHANNEL[] CHANNELS = new CHANNEL[]{CHANNEL.MY, CHANNEL.DISCORY, CHANNEL.FRIEND}; private UpdateReceiver mReceiver = null; /* * View */ private DrawerLayout mDrawerLayout; private View mToggleView; private View mSearchView; private ViewPager mViewPager; private HomePagerAdapter mAdapter; private View mDrawerQrcodeView; private View mDrawerShareView; private View unLogginLayout; private ImageView mPhotoView; public static void start(Context context) { Intent intent = new Intent(context, HomeActivity.class); context.startActivity(intent); } /* * data */ private ArrayList<CommonAudioBean> mLists = new ArrayList<>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); registerBroadcastReceiver(); // EventBus.getDefault().register(this); setContentView(R.layout.activity_main); initView(); initData(); } private void initData() { mLists.add(new CommonAudioBean("100001", "http://sp-sycdn.kuwo.cn/resource/n2/85/58/433900159.mp3", "我走后", "小咪", "生而为人", "为梦想打拼的每一个个体都是闪光的,为梦想打拼的每一个个体都是闪光的,为梦想打拼的每一个个体都是闪光的。", "http://img0.imgtn.bdimg.com/it/u=2329770966,4069416364&fm=26&gp=0.jpg", "4:30")); mLists.add( new CommonAudioBean("100002", "http://sq-sycdn.kuwo.cn/resource/n1/98/51/3777061809.mp3", "勇气", "梁静茹", "勇气", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://b-ssl.duitang.com/uploads/item/201707/01/20170701182157_5eMn2.jpeg", "4:40")); mLists.add( new CommonAudioBean("100003", "http://sp-sycdn.kuwo.cn/resource/n2/52/80/2933081485.mp3", "灿烂如你", "汪峰", "春天里", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://img3.imgtn.bdimg.com/it/u=2136332768,653918923&fm=26&gp=0.jpg", "3:20")); mLists.add( new CommonAudioBean("100004", "http://sr-sycdn.kuwo.cn/resource/n2/33/25/2629654819.mp3", "小情歌", "五月天", "小幸运", "电影《不能说的秘密》主题曲,尤其以最美的不是下雨天,是与你一起躲过雨的屋檐最为经典", "http://pic1.win4000.com/mobile/2018-10-08/5bbb0343355a0.jpg", "2:45")); AudioImpl.getInstance().setQueue(mLists); } private void initView() { mDrawerLayout = findViewById(R.id.drawer_layout); mToggleView = findViewById(R.id.toggle_view); mToggleView.setOnClickListener(this); mSearchView = findViewById(R.id.search_view); mSearchView.setOnClickListener(this); //初始化adpater mAdapter = new HomePagerAdapter(getSupportFragmentManager(), CHANNELS); mViewPager = findViewById(R.id.view_pager); mViewPager.setAdapter(mAdapter); initMagicIndicator(); mDrawerQrcodeView = findViewById(R.id.home_qrcode); mDrawerQrcodeView.setOnClickListener(this); mDrawerShareView = findViewById(R.id.home_music); mDrawerShareView.setOnClickListener(this); findViewById(R.id.online_music_view).setOnClickListener(this); findViewById(R.id.check_update_view).setOnClickListener(this); unLogginLayout = findViewById(R.id.unloggin_layout); unLogginLayout.setOnClickListener(this); mPhotoView = findViewById(R.id.avatr_view); findViewById(R.id.exit_layout).setOnClickListener(this); DisplayMetrics dm = new DisplayMetrics(); WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE); wm.getDefaultDisplay().getMetrics(dm); Log.d("tag1112:","width:"+dm.widthPixels); } private void initMagicIndicator() { MagicIndicator magicIndicator = findViewById(R.id.magic_indicator); magicIndicator.setBackgroundColor(Color.WHITE); CommonNavigator commonNavigator = new CommonNavigator(this); commonNavigator.setAdjustMode(true); commonNavigator.setAdapter(new CommonNavigatorAdapter() { @Override public int getCount() { return CHANNELS == null ? 0 : CHANNELS.length; } @Override public IPagerTitleView getTitleView(Context context, final int index) { SimplePagerTitleView simplePagerTitleView = new ScaleTransitionPagerTitleView(context); simplePagerTitleView.setText(CHANNELS[index].getKey()); simplePagerTitleView.setTextSize(19); simplePagerTitleView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD)); simplePagerTitleView.setNormalColor(Color.parseColor("#999999")); simplePagerTitleView.setSelectedColor(Color.parseColor("#333333")); simplePagerTitleView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mViewPager.setCurrentItem(index); } }); return simplePagerTitleView; } @Override public IPagerIndicator getIndicator(Context context) { return null; } @Override public float getTitleWeight(Context context, int index) { return 1.0f; } }); magicIndicator.setNavigator(commonNavigator); ViewPagerHelper.bind(magicIndicator, mViewPager); } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.exit_layout) { finish(); System.exit(0); } else if (id == R.id.unloggin_layout) { if (!LoginImpl.getInstance().hasLogin()) { LoginImpl.getInstance().login(this); } else { mDrawerLayout.closeDrawer(Gravity.LEFT); } } else if (id == R.id.toggle_view) { if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) { mDrawerLayout.closeDrawer(Gravity.LEFT); } else { mDrawerLayout.openDrawer(Gravity.LEFT); } } else if (id == R.id.home_qrcode) { if (hasPermission(Constant.HARDWEAR_CAMERA_PERMISSION)) { doCameraPermission(); } else { requestPermission(Constant.HARDWEAR_CAMERA_CODE, Constant.HARDWEAR_CAMERA_PERMISSION); } } else if (id == R.id.home_music) {//shareFriend(); goToMusic(); } else if (id == R.id.online_music_view) {//跳到指定webactivity gotoWebView("https://www.imooc.com"); } else if (id == R.id.check_update_view) { checkUpdate(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { //退出不销毁task中activity moveTaskToBack(true); return true; } return super.onKeyDown(keyCode, event); } @Override protected void onDestroy() { super.onDestroy(); // EventBus.getDefault().unregister(this); unRegisterBroadcastReceiver(); } @Override public void doCameraPermission() { // ARouter.getInstance().build(Constant.Router.ROUTER_CAPTURE_ACTIVIYT).navigation(); } private void goToMusic() { // ARouter.getInstance().build(Constant.Router.ROUTER_MUSIC_ACTIVIYT).navigation(); } private void gotoWebView(String url) { ARouter.getInstance() .build(Constant.Router.ROUTER_WEB_ACTIVIYT) .withString("url", url) .navigation(); } //启动 <SUF> private void checkUpdate() { // UpdateHelper.checkUpdate(this); } private void registerBroadcastReceiver() { // if (mReceiver == null) { // mReceiver = new UpdateReceiver(); // LocalBroadcastManager.getInstance(this) // .registerReceiver(mReceiver, new IntentFilter(UpdateHelper.UPDATE_ACTION)); // } } private void unRegisterBroadcastReceiver() { if (mReceiver != null) { LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); } } /** * 接收Update发送的广播 */ public class UpdateReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { //启动安装页面 // context.startActivity( // Utils.getInstallApkIntent(context, intent.getStringExtra(UpdateHelper.UPDATE_FILE_KEY))); } } // /** // * 处理登陆事件 // */ // @Subscribe(threadMode = ThreadMode.MAIN) // public void onLoginEvent(LoginEvent event) { // unLogginLayout.setVisibility(View.GONE); // mPhotoView.setVisibility(View.VISIBLE); // CustomImageLoader.getInstance() // .displayImageForCircleView(mPhotoView, UserManager.getInstance().getUser().data.photoUrl); // } }
1
8
1
56406_3
package com.chen.LeoBlog.po; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 黑名单 * * @TableName lb_black */ @TableName(value = "lb_black") @Data public class Black implements Serializable { /** * id */ @TableId(type = IdType.AUTO) private Long id; /** * 拉黑目标类型 1.ip 2uid */ private Integer type; /** * 拉黑目标 */ private String target; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; @TableField(exist = false) private static final long serialVersionUID = 1L; }
C-176/LeoBlog-back
src/main/java/com/chen/LeoBlog/po/Black.java
235
/** * 拉黑目标 */
block_comment
zh-cn
package com.chen.LeoBlog.po; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * 黑名单 * * @TableName lb_black */ @TableName(value = "lb_black") @Data public class Black implements Serializable { /** * id */ @TableId(type = IdType.AUTO) private Long id; /** * 拉黑目标类型 1.ip 2uid */ private Integer type; /** * 拉黑目 <SUF>*/ private String target; /** * 创建时间 */ private Date createTime; /** * 修改时间 */ private Date updateTime; @TableField(exist = false) private static final long serialVersionUID = 1L; }
1
23
1
56405_4
package com.bandgear.apfree.bean; import java.io.Serializable; public class IPWhite implements Serializable{ /** * ip白名单,对应rule_ipwhite表 * 加入ip白名单的设备会被限速 */ private Integer ap_id;//对应路由器ap_id private Integer id;//唯一标识 private String ip;//目标ip private String netmask;//子网掩码,跟ip结合使用代表某一网段 private Integer enable;//是否可用,0不可用,1可用 public IPWhite(Integer id, String ip, String netmask, Integer enable) { super(); this.id = id; this.ip = ip; this.netmask = netmask; this.enable = enable; } public IPWhite(){}; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getNetmask() { return netmask; } public void setNetmask(String netmask) { this.netmask = netmask; } public Integer getEnable() { return enable; } public void setEnable(Integer enable) { this.enable = enable; } public Integer getAp_id() { return ap_id; } public void setAp_id(Integer apId) { ap_id = apId; } }
C-hill/java4wifidog_server
src/com/bandgear/apfree/bean/IPWhite.java
402
//子网掩码,跟ip结合使用代表某一网段
line_comment
zh-cn
package com.bandgear.apfree.bean; import java.io.Serializable; public class IPWhite implements Serializable{ /** * ip白名单,对应rule_ipwhite表 * 加入ip白名单的设备会被限速 */ private Integer ap_id;//对应路由器ap_id private Integer id;//唯一标识 private String ip;//目标ip private String netmask;//子网 <SUF> private Integer enable;//是否可用,0不可用,1可用 public IPWhite(Integer id, String ip, String netmask, Integer enable) { super(); this.id = id; this.ip = ip; this.netmask = netmask; this.enable = enable; } public IPWhite(){}; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getNetmask() { return netmask; } public void setNetmask(String netmask) { this.netmask = netmask; } public Integer getEnable() { return enable; } public void setEnable(Integer enable) { this.enable = enable; } public Integer getAp_id() { return ap_id; } public void setAp_id(Integer apId) { ap_id = apId; } }
1
20
1
50905_20
package com.demo.smartport.Table; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import static com.baomidou.mybatisplus.annotation.IdType.AUTO; @NoArgsConstructor @AllArgsConstructor @Data @TableName("tb_ship") //船舶绑定数据 public class Ship implements Serializable { //船舶主键/唯一关键静态信息 @TableId(type= AUTO) private Integer id; //(主键)id private String name; //名称 private String letter; //呼号 private String imo; //imo private String mmsi; //mmsi //船舶静态数据 private Integer type; //船舶类型 private Double length; //船长(米) private Double width; //船宽(米) private Double draft; //吃水(米) private String portrait; //船舶预览图url //船舶动态数据 private Integer status; //船舶状态 private Double head; //船首向(度) private Double track; //船迹向(度) private Double speed; //航速(节)ar private String latitude; //纬度(N) private String longitude; //经度(E) private String destination; //目的地 private String arrive; //预到时间(年/月/日 时:分:秒) private String refresh; //更新时间(年/月/日 时:分:秒) }
CANDYFLOSSKKI/smart-port-BillProcessing
smartport/src/main/java/com/demo/smartport/Table/Ship.java
399
//更新时间(年/月/日 时:分:秒)
line_comment
zh-cn
package com.demo.smartport.Table; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import static com.baomidou.mybatisplus.annotation.IdType.AUTO; @NoArgsConstructor @AllArgsConstructor @Data @TableName("tb_ship") //船舶绑定数据 public class Ship implements Serializable { //船舶主键/唯一关键静态信息 @TableId(type= AUTO) private Integer id; //(主键)id private String name; //名称 private String letter; //呼号 private String imo; //imo private String mmsi; //mmsi //船舶静态数据 private Integer type; //船舶类型 private Double length; //船长(米) private Double width; //船宽(米) private Double draft; //吃水(米) private String portrait; //船舶预览图url //船舶动态数据 private Integer status; //船舶状态 private Double head; //船首向(度) private Double track; //船迹向(度) private Double speed; //航速(节)ar private String latitude; //纬度(N) private String longitude; //经度(E) private String destination; //目的地 private String arrive; //预到时间(年/月/日 时:分:秒) private String refresh; //更新 <SUF> }
1
19
1
21123_6
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { // myidea:我分析感觉像是最短路径问题,如果两个单词只有一个字母不一样那么就建立一条无向边,切权值为1,最后记录由beginWord到endWord的路径paths即可 // 实现点1:如何构建图,想法:按照单词的下标对应最终的图邻接矩阵的下标,然后beginWord的下标为n,n是wordList的长度 // int n = wordList.size(); // 大小是n+1的原因是0--n存储的是wordList中的元素,n存储的是beginWorld int[][] graph = new int[n+1][n+1]; // 找到endword在wordList中的下标位置 int end = -1; for(int i = 0;i<n;i++) if(wordList.get(i).equals(endWord)) end = i; // 如果wordList中不包含endWord if(end == -1) return 0; // 初始化graph for(int i = 0;i<n;i++) if(calcDis(beginWord,wordList.get(i))){ graph[n][i] = 1; graph[i][n] = 1; } for(int i = 0;i<n;i++){ for(int j = 0;j<n;j++){ if(i!=j && calcDis(wordList.get(i),wordList.get(j))){ graph[i][j] = 1; graph[j][i] = 1; } } } // 图构建完成之后,接下来就是计算单源最短路径,使用dijskra return dijskra(graph,n,end)==0?0:dijskra(graph,n,end)+1; } // 计算两个单词之间是否只有1个字符不相同,是则为true反之false public boolean calcDis(String s1,String s2){ // 因为题目说了所有的单词具有一样的长度,所以没有必要进行长度的判断 int dis = 0; for(int i = 0;i<s1.length();i++) if(s1.charAt(i) != s2.charAt(i)) dis++; return dis == 1; } // dijskra public int dijskra(int[][] graph,int start,int end){ int n = graph.length; // 存放start到各个下标节点的距离,初始化 int[] distance = new int[n]; for(int i = 0;i<n;i++) distance[i] = graph[start][i]; distance[start] = 0; // 判断start到下标位置的节点是否有最短路径 boolean[] visited = new boolean[n]; visited[start] = true; // 遍历除了start本身节点的所有节点、也就是说循环n-1次 for(int i = 1;i < n;i++){ // 当前最短距离 int minDistance = Integer.MAX_VALUE; // 当前最短距离的节点下标 int minIndex = 1; // 遍历所有的节点,找到距离start的最近的节点 for(int j =0;j < n;j++){ if(!visited[j] && distance[j] != 0 && distance[j]<=minDistance){ minDistance = distance[j]; minIndex = j; } } // 标记最近距离节点已经找到了 visited[minIndex] = true; // 根据刚刚找到的最近距离节点,更新start节点到其他节点的距离 for(int j=0;j< n;j++){ // 如果已更新的最短距离节点可以到达当前便利的节点 if(graph[minIndex][j] == 1){ if(distance[j] != 0) distance[j] = Math.min(distance[j],distance[minIndex] + graph[minIndex][j]); else distance[j] = distance[minIndex] + graph[minIndex][j]; } } } return distance[end]; } }
CAS-IICT/leetcode-algorithm-hack
Word-Ladder/Solution.java
987
// 图构建完成之后,接下来就是计算单源最短路径,使用dijskra
line_comment
zh-cn
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList) { // myidea:我分析感觉像是最短路径问题,如果两个单词只有一个字母不一样那么就建立一条无向边,切权值为1,最后记录由beginWord到endWord的路径paths即可 // 实现点1:如何构建图,想法:按照单词的下标对应最终的图邻接矩阵的下标,然后beginWord的下标为n,n是wordList的长度 // int n = wordList.size(); // 大小是n+1的原因是0--n存储的是wordList中的元素,n存储的是beginWorld int[][] graph = new int[n+1][n+1]; // 找到endword在wordList中的下标位置 int end = -1; for(int i = 0;i<n;i++) if(wordList.get(i).equals(endWord)) end = i; // 如果wordList中不包含endWord if(end == -1) return 0; // 初始化graph for(int i = 0;i<n;i++) if(calcDis(beginWord,wordList.get(i))){ graph[n][i] = 1; graph[i][n] = 1; } for(int i = 0;i<n;i++){ for(int j = 0;j<n;j++){ if(i!=j && calcDis(wordList.get(i),wordList.get(j))){ graph[i][j] = 1; graph[j][i] = 1; } } } // 图构 <SUF> return dijskra(graph,n,end)==0?0:dijskra(graph,n,end)+1; } // 计算两个单词之间是否只有1个字符不相同,是则为true反之false public boolean calcDis(String s1,String s2){ // 因为题目说了所有的单词具有一样的长度,所以没有必要进行长度的判断 int dis = 0; for(int i = 0;i<s1.length();i++) if(s1.charAt(i) != s2.charAt(i)) dis++; return dis == 1; } // dijskra public int dijskra(int[][] graph,int start,int end){ int n = graph.length; // 存放start到各个下标节点的距离,初始化 int[] distance = new int[n]; for(int i = 0;i<n;i++) distance[i] = graph[start][i]; distance[start] = 0; // 判断start到下标位置的节点是否有最短路径 boolean[] visited = new boolean[n]; visited[start] = true; // 遍历除了start本身节点的所有节点、也就是说循环n-1次 for(int i = 1;i < n;i++){ // 当前最短距离 int minDistance = Integer.MAX_VALUE; // 当前最短距离的节点下标 int minIndex = 1; // 遍历所有的节点,找到距离start的最近的节点 for(int j =0;j < n;j++){ if(!visited[j] && distance[j] != 0 && distance[j]<=minDistance){ minDistance = distance[j]; minIndex = j; } } // 标记最近距离节点已经找到了 visited[minIndex] = true; // 根据刚刚找到的最近距离节点,更新start节点到其他节点的距离 for(int j=0;j< n;j++){ // 如果已更新的最短距离节点可以到达当前便利的节点 if(graph[minIndex][j] == 1){ if(distance[j] != 0) distance[j] = Math.min(distance[j],distance[minIndex] + graph[minIndex][j]); else distance[j] = distance[minIndex] + graph[minIndex][j]; } } } return distance[end]; } }
1
34
1
53544_10
import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * ### 数据库类封装 * * 通过HashMap传参和返回,可以更加方便使用 * * 真的炒鸡方便 QAQ * * * * @author CATT-L * Created by CATT-L on 12/17/2017. * * --- * 2017-12-19 14:13:05 * 增加了`列出表`和`删除表` * * show tables; * drop table `table`; * * --- * 2017-12-18 12:17:45 * 增加了`更新记录`和`删除记录` * * 更新 * update `table` set `k1`='v1',`k2`='v2' where (`k`='v'); * update `table` set `k1`='v1',`k2`='v2' where (`wk1`='wv2' and `wk2`='wv2'); * * 删除 * delete from `table` where (`k`='v'); * delete from `table` where (`k1`='v1' or `k2`='v2' or `k3`='v3'); * * 今天天气好冷啊! 10℃ !!! 冷死了冷死了 QAQ * * --- * 2017-12-17 17:26:12 * 搞定了最基本的 `连接数据库`, 以及 `查找记录` 和 `插入记录` * 目前能实现如下语句 * * 查询 * select * from `table`; * select * from `table` limit offset,num; * select * from `table` where `key`='value'; * select * from `table` where `key`='value' limit 0,1; * select * from `table` where `key`='value' limit offset,num; * * 插入 * insert into `table` (`k1`,`k2`,`k3`) values('v1','v2','v3'); * insert into `table` (`k1`,`k2`,`k3`) values('v11','v12','v13'),('v21','v22','v23'),('v31','v32','v33'); * * 呃... 目前就这么多 吃饭吃饭! (๑و•̀ω•́)و * * */ public class CattSQL { /** * 静态常量 * * 供外部获取的键名 为了防止打错字 * 可以在其它类里通过常量的方式引用. * */ public static String KEY_HOST = "host"; public static String KEY_PORT = "port"; public static String KEY_NAME = "name"; public static String KEY_USER = "user"; public static String KEY_PASS = "pass"; /** * 私有成员 记录数据库基本信息 * * dbHost 主机地址 * dbPort 端口 * dbName 数据库名 * dbUser 用户名 * dbPass 密码 * * sql 上一条成功执行的SQL语句 * conn 数据库连接对象 * */ private String dbHost; private String dbPort; private String dbName; private String dbUser; private String dbPass; private String sql = ""; private Connection conn = null; /** * 构造函数 * @param data Map类型 键名键值都是字符串形式 * * 必须包含如下数据 * KEY_NAME,数据库名 * * 可缺省 缺省值 * KEY_HOST,主机地址 127.0.0.1 * KEY_PORT,端口号 3306 * KEY_USER,用户名 root * KEY_PASS,连接密码 无密码 */ public CattSQL(Map<String, String> data) throws CattSqlException{ this( data.get(KEY_HOST), data.get(KEY_PORT), data.get(KEY_NAME), data.get(KEY_USER), data.get(KEY_PASS) ); } /** * 构造函数 * @param host 主机地址 可以是IP也可以是域名 * @param port 端口号 字符串格式 * @param name 数据库名称 * @param user 用户名 * @param pass 密码 */ public CattSQL(String host, String port, String name, String user, String pass) throws CattSqlException{ this.dbHost = host; this.dbPort = port; this.dbName = name; this.dbUser = user; this.dbPass = pass; // 传参错误 抛出异常 paramCheck(); // 开始连接 loadDatabaseDriver(); connect(); } /** * 检查参数正确性 * * @throws CattSqlException 传参错误异常 */ private void paramCheck() throws CattSqlException{ // 地址缺省 127.0.0.1 if(this.dbHost == null || this.dbHost.length() == 0) this.dbHost = "127.0.0.1"; // 端口缺省 3306 if(this.dbPort == null || this.dbPort.length() == 0) this.dbPort = "3306"; // 数据库名不能为空啊! if(this.dbName == null || this.dbName.length() == 0) throw new CattSqlException("数据库名不能为空"); // 用户名缺省 root if(this.dbUser == null || this.dbUser.length() == 0) this.dbUser = "root"; // 密码缺省 空 if(this.dbPass == null) this.dbPass = ""; } /** * 加载数据库驱动类 * * @throws CattSqlException 加载失败 */ private void loadDatabaseDriver() throws CattSqlException{ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new CattSqlException("加载数据库驱动失败!"); } } /** * 连接数据库 * * @throws CattSqlException 连接失败 */ private void connect() throws CattSqlException{ String url = "jdbc:mysql://" + this.dbHost + ":" + this.dbPort + "/" + this.dbName; try { this.conn = DriverManager.getConnection(url, this.dbUser, this.dbPass); } catch (SQLException e) { throw new CattSqlException("连接数据库失败"); } } /** * 获取上一步sql语句 * @return sql语句 */ public String lastSQL(){ return this.sql; } /** * 多条查询 * * 内部方法 能够实现 * select * from table; * select * from table where k=v; * select * from table limit offset,num; * select * from table where k=v limit offset,num; * * 不可缺省 * @param table 表名 * @param num 取出数量 0 为所有 * @param offset 偏移量 开始位置 * * 可缺省 * @param k 键名 * @param v 键值 * @return 键值对列表 * @throws CattSqlException 表名为空或查询异常 */ public List<Map<String, String>> select(String table, int num, int offset, String k, String v) throws CattSqlException{ if(this.conn == null) connect(); if(table == null || table.length() == 0) throw new CattSqlException("表名不能为空"); // sql 构造 String sql = "select * from `" + table + "`"; if(k != null && k.length() > 0){ sql += " where `" + k + "`='" + v + "'"; } if(num > 0){ // 偏移不能为负数 if(offset < 0) offset = 0; String limit = "limit " + offset + "," + num; sql += " " + limit; } sql += ";"; // System.out.println(sql); try { PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); // 空值 返回空 if(!rs.next()) return null; // 获取字段名 int colNum = rs.getMetaData().getColumnCount(); String[] colName = new String[colNum]; for(int i = 0; i < colNum; i++){ colName[i] = rs.getMetaData().getColumnName(i+1); } // 存放结果 List<Map<String, String>> list = new ArrayList<>(); do{ // 封装数据 Map<String, String> map = new HashMap<>(); for(int i = 0; i < colNum; i++){ String _k = colName[i]; String _v = rs.getString(i+1); map.put(_k, _v); } // 推入list list.add(map); } while (rs.next()); rs.close(); ps.close(); // 记录sql this.sql = sql; return list; } catch (Exception e) { // 查询数据库失败 throw new CattSqlException("数据库查询失败 语句: " + sql); } } /** * 数据库查询 单条 * * select * table where k=v limit 1; * * @param table 表名 * @param k 键名 * @param v 键值 * @return 单条数据 键值对 * @throws CattSqlException 表名键名为空或查询异常 */ public Map<String, String> selectOne(String table, String k, String v) throws CattSqlException{ // 查询且仅查询一条数据 List<Map<String, String>> list = select(table, 1, 0, k, v); if(list != null) return list.get(0); else return null; } /** * 数据库查询 符合条件的全部 * * select * from table where k=v; * * @param table 表名 * @param k key * @param v value * @return 结果数组 */ public List<Map<String, String>> select(String table, String k, String v) throws CattSqlException{ return select(table, 0, 0, k, v); } /** * 数据库查询 无条件 限定条数 * * select * from table limit offset,num; * * @param table 表名 * @param num 数量 * @param offset 偏移 * @return 结果数组 */ public List<Map<String, String>> select(String table, int num, int offset) throws CattSqlException{ return select(table, num, offset, null, null); } /** * 取得所有数据 * * select * from table; * * @param table 表名 * @return 结果 */ public List<Map<String, String>> select(String table) throws CattSqlException{ return select(table, 0, 0, null, null); } /** * 插入记录 单条 * * insert into `table` (`k1`,`k2`,`k3`) values('v1','v2','v3'); * * @param table 表名 * @param data 键值对 * @return 返回主键 通常是自增ID 为了保险起见还是用String形式返回 * * @throws CattSqlException 抛出异常 */ public String insert(String table, Map<String, String> data) throws CattSqlException{ if(this.conn == null) connect(); // 表名判空 if(table == null || table.length() == 0) throw new CattSqlException("表名不能为空"); int len = data.size(); if(len == 0) return null; String kStr = ""; String vStr = ""; for (Map.Entry<String, String> entry : data.entrySet()){ kStr += ",`"+entry.getKey()+"`"; vStr += ",'"+entry.getValue()+"'"; } String sql = "insert into `"+table+"` ("; sql += kStr.substring(1); sql += ") values("; sql += vStr.substring(1); sql += ");"; try{ PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); String key = null; // 返回主键 if(ps.executeUpdate() > 0){ ResultSet rs = ps.getGeneratedKeys(); if(rs.next()){ key = rs.getString(1); } rs.close(); } ps.close(); // 记录sql this.sql = sql; return key; } catch (Exception e){ e.printStackTrace(); throw new CattSqlException("数据插入失败 QAQ"); } } /** * 插入记录 多条插入 * * insert into `table` (`k1`,`k2`,`k3`) values('v11','v12','v13'),('v21','v22','v23'),('v31','v32','v33'); * * @param table 表名 * @param list 字符串数组 * 约定第 0 行为键名 (`k1`,`k2`,`k3`) * 后面行均为键值 ('v11','v12','v13'),('v21','v22','v23'),('v31','v32','v33') * * @return 返回主键ID列表, 字符串类型 * 大概长这样 [27,28,29] * 或这样 [子鼠,丑牛,寅虎] * 取决于你的主键是什么 * * @throws CattSqlException 抛出异常 */ public List<String> insert(String table, String[][] list) throws CattSqlException{ if(this.conn == null) connect(); if(table == null || table.length() == 0) throw new CattSqlException("表名不能为空"); // 数组空 if(list == null) return null; int listSize = list.length; if(listSize <= 1) return null; int dataSize = list[0].length; String kStr = ""; // 拼接键名字符串 for(int i = 0; i < dataSize; i++){ kStr += ",`" + list[0][i] + "`"; } kStr = "(" + kStr.substring(1) + ")"; String vStr = ""; // 拼接键值字符串 for(int i = 1; i < listSize; i++){ String vTemp = ""; for(int j = 0; j < dataSize; j++){ vTemp += ",'" + list[i][j] + "'"; } vStr += ",(" + vTemp.substring(1) + ")"; } vStr = "value" + vStr.substring(1); String sql = "insert into `" + table + "`"; sql += " " + kStr; sql += " " + vStr; sql += ";"; try{ PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); List<String> key = null; // 记录主键 if(ps.executeUpdate() > 0){ key = new ArrayList<>(); ResultSet rs = ps.getGeneratedKeys(); while(rs.next()){ key.add(rs.getString(1)); } rs.close(); } ps.close(); this.sql = sql; return key; } catch (Exception e){ e.printStackTrace(); throw new CattSqlException("数据插入失败 QAQ"); } } /** * 更新记录 * * update `table` set `k2`='v2',`k3`='v3' where (`k1`='v1'); * @param table 表名 * @param k 键名 * @param v 键值 缺省为空字符串 * @param data 更新键值对 缺省则不更新 * @return 返回受影响条数 * * @throws CattSqlException 表名键名为空异常 数据库插入异常 */ public int update(String table, String k, String v, Map<String, String> data) throws CattSqlException{ // 参数判空 表名 键名 if(table == null || k == null || table.length() == 0 || k.length() == 0) throw new CattSqlException("表名和键名不能为空"); // 没有数据被传入 不需要更新 返回 0 条受到影响 if(data == null || data.size() == 0) return 0; // 键值缺省 空字符串 if(v == null || v.length() == 0) v = ""; Map<String, String> where = new HashMap<>(); where.put(k, v); return update(table, where, data); } /** * 多条件更新 * * update `table` set `k1`='v1',`k2`='v2' where (`wk1`='wv2' and `wk2`='wv2'); * * @param table 表名 * @param where 条件 键值对 * @param data 更新 键值对 * @return 受影响条数 * @throws CattSqlException 表名 条件为空异常, 数据库插入失败 */ public int update(String table, Map<String, String> where, Map<String, String> data) throws CattSqlException{ if(this.conn == null) connect(); // 参数判空 表名 键名 if(table == null || where == null || table.length() == 0 || where.size() == 0) throw new CattSqlException("表名和条件不能为空"); // 没有数据被传入 不需要更新 返回 0 条受到影响 if(data == null || data.size() == 0) return 0; // 构造更新段 String nStr = ""; for (Map.Entry<String, String> entry : data.entrySet()){ String k = entry.getKey(); String v = entry.getValue(); // 键值为空 跳过添加 if(k == null || k.length() == 0) continue; // 键名缺省 空字符串 if(v == null) v = ""; nStr += ",`" + k + "`='" + v + "'"; } // 没有内容需要更新 if(nStr.length() == 0) return 0; nStr = nStr.substring(1); // 构造条件段 String wStr = ""; for(Map.Entry<String, String> entry : where.entrySet()){ String k = entry.getKey(); String v = entry.getValue(); // 键名为空 跳过此次添加 if(k == null || k.length() == 0) continue; // 键值缺省空字符串 if(v == null) v = ""; wStr += " and `" + k + "`='" + v + "'"; } if (wStr.length() == 0) throw new CattSqlException("条件不能为空"); wStr = "where (" + wStr.substring(5) + ")"; String sql = "update `"+table+"` set"; sql += " " + nStr; sql += " " + wStr; sql += ";"; try{ PreparedStatement ps = conn.prepareStatement(sql); int re = ps.executeUpdate(); ps.close(); // 记录sql this.sql = sql; return re; } catch(Exception e){ e.printStackTrace(); throw new CattSqlException("数据库更新失败了 QAQ"); } } /** * 多条删除 * * delete from `table` where (`k1`='v1' or `k2`='v2' or `k3`='v3'); * * @param table 表名 * @param k 键名 * @param v 键值数组 * @return 受影响条数 * * @throws CattSqlException 表名为空, 键名为空, 执行异常 */ public int delete(String table, String k, String[] v) throws CattSqlException{ if(this.conn == null) connect(); if(table == null || table.length() == 0 || k == null || k.length() == 0) throw new CattSqlException("表名和键名不能为空"); // 没有数据需要被删除 if(v.length == 0) return 0; String wStr = ""; for(int i = 0; i < v.length; i++){ // 缺省 空字符 if(v[i] == null) v[i] = ""; wStr += " or `" + k + "`='" + v[i] + "'"; } wStr = "where (" + wStr.substring(4) + ")"; String sql = "delete from `" + table + "` " + wStr + ";"; try{ PreparedStatement ps = conn.prepareStatement(sql); int re = ps.executeUpdate(); ps.close(); // 记录sql this.sql = sql; return re; } catch(Exception e){ e.printStackTrace(); throw new CattSqlException("数据库更新失败了 QAQ"); } } /** * 单条删除 * * delete from `tt` where (`k`='v'); * * @param table 表名 * @param k 键名 * @param v 键值 * @return 受影响条数 * * @throws CattSqlException 异常 */ public int delete(String table, String k, String v) throws CattSqlException{ String[] vrr = {v}; return delete(table, k, vrr); } /** * 获取数据库表格列表 * * show tables; * * @return 表名列表 * @throws CattSqlException 数据库查询异常 */ public List<String> getTables() throws CattSqlException{ if(this.conn == null) connect(); String sql = "show tables;"; List<String> list = new ArrayList<>(); try{ PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()){ list.add(rs.getString(1)); } rs.close(); ps.close(); this.sql = sql; return list; } catch (Exception e){ e.printStackTrace(); throw new CattSqlException("数据库查询失败"); } } /** * 删除表格 * * drop table `table`; * * @param table 表名 * @throws CattSqlException 删除异常 通常是表名不存在 */ public void dropTable(String table) throws CattSqlException{ if(this.conn == null) connect(); String sql = "drop table `" + table + "`;"; try{ PreparedStatement ps = conn.prepareStatement(sql); ps.executeUpdate(); this.sql = sql; } catch (SQLException e) { e.printStackTrace(); throw new CattSqlException("删除数据库失败"); } } /** * 关闭数据库连接 */ public void release() throws CattSqlException{ if(this.conn == null) return; try { conn.close(); this.conn = null; } catch (SQLException e) { e.printStackTrace(); throw new CattSqlException("关闭连接失败"); } } /** * 获取数据库连接对象 * * 对于复杂的SQL语句, 可以通过获取Connection对象, 然后再执行SQL语句. * 这个connection是新的对象, 所以在使用后要记得释放掉 * * @return Connection 对象 * @throws CattSqlException */ public Connection getConn() throws CattSqlException{ if(conn != null){ String url = "jdbc:mysql://" + this.dbHost + ":" + this.dbPort + "/" + this.dbName; try { return DriverManager.getConnection(url, this.dbUser, this.dbPass); } catch (SQLException e) { e.printStackTrace(); throw new CattSqlException("数据库连接失败"); } } else throw new CattSqlException("数据库连接失败"); } }
CATT-L/CattSQL-Java
src/CattSQL.java
5,895
// 数据库名不能为空啊!
line_comment
zh-cn
import java.sql.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * ### 数据库类封装 * * 通过HashMap传参和返回,可以更加方便使用 * * 真的炒鸡方便 QAQ * * * * @author CATT-L * Created by CATT-L on 12/17/2017. * * --- * 2017-12-19 14:13:05 * 增加了`列出表`和`删除表` * * show tables; * drop table `table`; * * --- * 2017-12-18 12:17:45 * 增加了`更新记录`和`删除记录` * * 更新 * update `table` set `k1`='v1',`k2`='v2' where (`k`='v'); * update `table` set `k1`='v1',`k2`='v2' where (`wk1`='wv2' and `wk2`='wv2'); * * 删除 * delete from `table` where (`k`='v'); * delete from `table` where (`k1`='v1' or `k2`='v2' or `k3`='v3'); * * 今天天气好冷啊! 10℃ !!! 冷死了冷死了 QAQ * * --- * 2017-12-17 17:26:12 * 搞定了最基本的 `连接数据库`, 以及 `查找记录` 和 `插入记录` * 目前能实现如下语句 * * 查询 * select * from `table`; * select * from `table` limit offset,num; * select * from `table` where `key`='value'; * select * from `table` where `key`='value' limit 0,1; * select * from `table` where `key`='value' limit offset,num; * * 插入 * insert into `table` (`k1`,`k2`,`k3`) values('v1','v2','v3'); * insert into `table` (`k1`,`k2`,`k3`) values('v11','v12','v13'),('v21','v22','v23'),('v31','v32','v33'); * * 呃... 目前就这么多 吃饭吃饭! (๑و•̀ω•́)و * * */ public class CattSQL { /** * 静态常量 * * 供外部获取的键名 为了防止打错字 * 可以在其它类里通过常量的方式引用. * */ public static String KEY_HOST = "host"; public static String KEY_PORT = "port"; public static String KEY_NAME = "name"; public static String KEY_USER = "user"; public static String KEY_PASS = "pass"; /** * 私有成员 记录数据库基本信息 * * dbHost 主机地址 * dbPort 端口 * dbName 数据库名 * dbUser 用户名 * dbPass 密码 * * sql 上一条成功执行的SQL语句 * conn 数据库连接对象 * */ private String dbHost; private String dbPort; private String dbName; private String dbUser; private String dbPass; private String sql = ""; private Connection conn = null; /** * 构造函数 * @param data Map类型 键名键值都是字符串形式 * * 必须包含如下数据 * KEY_NAME,数据库名 * * 可缺省 缺省值 * KEY_HOST,主机地址 127.0.0.1 * KEY_PORT,端口号 3306 * KEY_USER,用户名 root * KEY_PASS,连接密码 无密码 */ public CattSQL(Map<String, String> data) throws CattSqlException{ this( data.get(KEY_HOST), data.get(KEY_PORT), data.get(KEY_NAME), data.get(KEY_USER), data.get(KEY_PASS) ); } /** * 构造函数 * @param host 主机地址 可以是IP也可以是域名 * @param port 端口号 字符串格式 * @param name 数据库名称 * @param user 用户名 * @param pass 密码 */ public CattSQL(String host, String port, String name, String user, String pass) throws CattSqlException{ this.dbHost = host; this.dbPort = port; this.dbName = name; this.dbUser = user; this.dbPass = pass; // 传参错误 抛出异常 paramCheck(); // 开始连接 loadDatabaseDriver(); connect(); } /** * 检查参数正确性 * * @throws CattSqlException 传参错误异常 */ private void paramCheck() throws CattSqlException{ // 地址缺省 127.0.0.1 if(this.dbHost == null || this.dbHost.length() == 0) this.dbHost = "127.0.0.1"; // 端口缺省 3306 if(this.dbPort == null || this.dbPort.length() == 0) this.dbPort = "3306"; // 数据 <SUF> if(this.dbName == null || this.dbName.length() == 0) throw new CattSqlException("数据库名不能为空"); // 用户名缺省 root if(this.dbUser == null || this.dbUser.length() == 0) this.dbUser = "root"; // 密码缺省 空 if(this.dbPass == null) this.dbPass = ""; } /** * 加载数据库驱动类 * * @throws CattSqlException 加载失败 */ private void loadDatabaseDriver() throws CattSqlException{ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new CattSqlException("加载数据库驱动失败!"); } } /** * 连接数据库 * * @throws CattSqlException 连接失败 */ private void connect() throws CattSqlException{ String url = "jdbc:mysql://" + this.dbHost + ":" + this.dbPort + "/" + this.dbName; try { this.conn = DriverManager.getConnection(url, this.dbUser, this.dbPass); } catch (SQLException e) { throw new CattSqlException("连接数据库失败"); } } /** * 获取上一步sql语句 * @return sql语句 */ public String lastSQL(){ return this.sql; } /** * 多条查询 * * 内部方法 能够实现 * select * from table; * select * from table where k=v; * select * from table limit offset,num; * select * from table where k=v limit offset,num; * * 不可缺省 * @param table 表名 * @param num 取出数量 0 为所有 * @param offset 偏移量 开始位置 * * 可缺省 * @param k 键名 * @param v 键值 * @return 键值对列表 * @throws CattSqlException 表名为空或查询异常 */ public List<Map<String, String>> select(String table, int num, int offset, String k, String v) throws CattSqlException{ if(this.conn == null) connect(); if(table == null || table.length() == 0) throw new CattSqlException("表名不能为空"); // sql 构造 String sql = "select * from `" + table + "`"; if(k != null && k.length() > 0){ sql += " where `" + k + "`='" + v + "'"; } if(num > 0){ // 偏移不能为负数 if(offset < 0) offset = 0; String limit = "limit " + offset + "," + num; sql += " " + limit; } sql += ";"; // System.out.println(sql); try { PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); // 空值 返回空 if(!rs.next()) return null; // 获取字段名 int colNum = rs.getMetaData().getColumnCount(); String[] colName = new String[colNum]; for(int i = 0; i < colNum; i++){ colName[i] = rs.getMetaData().getColumnName(i+1); } // 存放结果 List<Map<String, String>> list = new ArrayList<>(); do{ // 封装数据 Map<String, String> map = new HashMap<>(); for(int i = 0; i < colNum; i++){ String _k = colName[i]; String _v = rs.getString(i+1); map.put(_k, _v); } // 推入list list.add(map); } while (rs.next()); rs.close(); ps.close(); // 记录sql this.sql = sql; return list; } catch (Exception e) { // 查询数据库失败 throw new CattSqlException("数据库查询失败 语句: " + sql); } } /** * 数据库查询 单条 * * select * table where k=v limit 1; * * @param table 表名 * @param k 键名 * @param v 键值 * @return 单条数据 键值对 * @throws CattSqlException 表名键名为空或查询异常 */ public Map<String, String> selectOne(String table, String k, String v) throws CattSqlException{ // 查询且仅查询一条数据 List<Map<String, String>> list = select(table, 1, 0, k, v); if(list != null) return list.get(0); else return null; } /** * 数据库查询 符合条件的全部 * * select * from table where k=v; * * @param table 表名 * @param k key * @param v value * @return 结果数组 */ public List<Map<String, String>> select(String table, String k, String v) throws CattSqlException{ return select(table, 0, 0, k, v); } /** * 数据库查询 无条件 限定条数 * * select * from table limit offset,num; * * @param table 表名 * @param num 数量 * @param offset 偏移 * @return 结果数组 */ public List<Map<String, String>> select(String table, int num, int offset) throws CattSqlException{ return select(table, num, offset, null, null); } /** * 取得所有数据 * * select * from table; * * @param table 表名 * @return 结果 */ public List<Map<String, String>> select(String table) throws CattSqlException{ return select(table, 0, 0, null, null); } /** * 插入记录 单条 * * insert into `table` (`k1`,`k2`,`k3`) values('v1','v2','v3'); * * @param table 表名 * @param data 键值对 * @return 返回主键 通常是自增ID 为了保险起见还是用String形式返回 * * @throws CattSqlException 抛出异常 */ public String insert(String table, Map<String, String> data) throws CattSqlException{ if(this.conn == null) connect(); // 表名判空 if(table == null || table.length() == 0) throw new CattSqlException("表名不能为空"); int len = data.size(); if(len == 0) return null; String kStr = ""; String vStr = ""; for (Map.Entry<String, String> entry : data.entrySet()){ kStr += ",`"+entry.getKey()+"`"; vStr += ",'"+entry.getValue()+"'"; } String sql = "insert into `"+table+"` ("; sql += kStr.substring(1); sql += ") values("; sql += vStr.substring(1); sql += ");"; try{ PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); String key = null; // 返回主键 if(ps.executeUpdate() > 0){ ResultSet rs = ps.getGeneratedKeys(); if(rs.next()){ key = rs.getString(1); } rs.close(); } ps.close(); // 记录sql this.sql = sql; return key; } catch (Exception e){ e.printStackTrace(); throw new CattSqlException("数据插入失败 QAQ"); } } /** * 插入记录 多条插入 * * insert into `table` (`k1`,`k2`,`k3`) values('v11','v12','v13'),('v21','v22','v23'),('v31','v32','v33'); * * @param table 表名 * @param list 字符串数组 * 约定第 0 行为键名 (`k1`,`k2`,`k3`) * 后面行均为键值 ('v11','v12','v13'),('v21','v22','v23'),('v31','v32','v33') * * @return 返回主键ID列表, 字符串类型 * 大概长这样 [27,28,29] * 或这样 [子鼠,丑牛,寅虎] * 取决于你的主键是什么 * * @throws CattSqlException 抛出异常 */ public List<String> insert(String table, String[][] list) throws CattSqlException{ if(this.conn == null) connect(); if(table == null || table.length() == 0) throw new CattSqlException("表名不能为空"); // 数组空 if(list == null) return null; int listSize = list.length; if(listSize <= 1) return null; int dataSize = list[0].length; String kStr = ""; // 拼接键名字符串 for(int i = 0; i < dataSize; i++){ kStr += ",`" + list[0][i] + "`"; } kStr = "(" + kStr.substring(1) + ")"; String vStr = ""; // 拼接键值字符串 for(int i = 1; i < listSize; i++){ String vTemp = ""; for(int j = 0; j < dataSize; j++){ vTemp += ",'" + list[i][j] + "'"; } vStr += ",(" + vTemp.substring(1) + ")"; } vStr = "value" + vStr.substring(1); String sql = "insert into `" + table + "`"; sql += " " + kStr; sql += " " + vStr; sql += ";"; try{ PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); List<String> key = null; // 记录主键 if(ps.executeUpdate() > 0){ key = new ArrayList<>(); ResultSet rs = ps.getGeneratedKeys(); while(rs.next()){ key.add(rs.getString(1)); } rs.close(); } ps.close(); this.sql = sql; return key; } catch (Exception e){ e.printStackTrace(); throw new CattSqlException("数据插入失败 QAQ"); } } /** * 更新记录 * * update `table` set `k2`='v2',`k3`='v3' where (`k1`='v1'); * @param table 表名 * @param k 键名 * @param v 键值 缺省为空字符串 * @param data 更新键值对 缺省则不更新 * @return 返回受影响条数 * * @throws CattSqlException 表名键名为空异常 数据库插入异常 */ public int update(String table, String k, String v, Map<String, String> data) throws CattSqlException{ // 参数判空 表名 键名 if(table == null || k == null || table.length() == 0 || k.length() == 0) throw new CattSqlException("表名和键名不能为空"); // 没有数据被传入 不需要更新 返回 0 条受到影响 if(data == null || data.size() == 0) return 0; // 键值缺省 空字符串 if(v == null || v.length() == 0) v = ""; Map<String, String> where = new HashMap<>(); where.put(k, v); return update(table, where, data); } /** * 多条件更新 * * update `table` set `k1`='v1',`k2`='v2' where (`wk1`='wv2' and `wk2`='wv2'); * * @param table 表名 * @param where 条件 键值对 * @param data 更新 键值对 * @return 受影响条数 * @throws CattSqlException 表名 条件为空异常, 数据库插入失败 */ public int update(String table, Map<String, String> where, Map<String, String> data) throws CattSqlException{ if(this.conn == null) connect(); // 参数判空 表名 键名 if(table == null || where == null || table.length() == 0 || where.size() == 0) throw new CattSqlException("表名和条件不能为空"); // 没有数据被传入 不需要更新 返回 0 条受到影响 if(data == null || data.size() == 0) return 0; // 构造更新段 String nStr = ""; for (Map.Entry<String, String> entry : data.entrySet()){ String k = entry.getKey(); String v = entry.getValue(); // 键值为空 跳过添加 if(k == null || k.length() == 0) continue; // 键名缺省 空字符串 if(v == null) v = ""; nStr += ",`" + k + "`='" + v + "'"; } // 没有内容需要更新 if(nStr.length() == 0) return 0; nStr = nStr.substring(1); // 构造条件段 String wStr = ""; for(Map.Entry<String, String> entry : where.entrySet()){ String k = entry.getKey(); String v = entry.getValue(); // 键名为空 跳过此次添加 if(k == null || k.length() == 0) continue; // 键值缺省空字符串 if(v == null) v = ""; wStr += " and `" + k + "`='" + v + "'"; } if (wStr.length() == 0) throw new CattSqlException("条件不能为空"); wStr = "where (" + wStr.substring(5) + ")"; String sql = "update `"+table+"` set"; sql += " " + nStr; sql += " " + wStr; sql += ";"; try{ PreparedStatement ps = conn.prepareStatement(sql); int re = ps.executeUpdate(); ps.close(); // 记录sql this.sql = sql; return re; } catch(Exception e){ e.printStackTrace(); throw new CattSqlException("数据库更新失败了 QAQ"); } } /** * 多条删除 * * delete from `table` where (`k1`='v1' or `k2`='v2' or `k3`='v3'); * * @param table 表名 * @param k 键名 * @param v 键值数组 * @return 受影响条数 * * @throws CattSqlException 表名为空, 键名为空, 执行异常 */ public int delete(String table, String k, String[] v) throws CattSqlException{ if(this.conn == null) connect(); if(table == null || table.length() == 0 || k == null || k.length() == 0) throw new CattSqlException("表名和键名不能为空"); // 没有数据需要被删除 if(v.length == 0) return 0; String wStr = ""; for(int i = 0; i < v.length; i++){ // 缺省 空字符 if(v[i] == null) v[i] = ""; wStr += " or `" + k + "`='" + v[i] + "'"; } wStr = "where (" + wStr.substring(4) + ")"; String sql = "delete from `" + table + "` " + wStr + ";"; try{ PreparedStatement ps = conn.prepareStatement(sql); int re = ps.executeUpdate(); ps.close(); // 记录sql this.sql = sql; return re; } catch(Exception e){ e.printStackTrace(); throw new CattSqlException("数据库更新失败了 QAQ"); } } /** * 单条删除 * * delete from `tt` where (`k`='v'); * * @param table 表名 * @param k 键名 * @param v 键值 * @return 受影响条数 * * @throws CattSqlException 异常 */ public int delete(String table, String k, String v) throws CattSqlException{ String[] vrr = {v}; return delete(table, k, vrr); } /** * 获取数据库表格列表 * * show tables; * * @return 表名列表 * @throws CattSqlException 数据库查询异常 */ public List<String> getTables() throws CattSqlException{ if(this.conn == null) connect(); String sql = "show tables;"; List<String> list = new ArrayList<>(); try{ PreparedStatement ps = conn.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next()){ list.add(rs.getString(1)); } rs.close(); ps.close(); this.sql = sql; return list; } catch (Exception e){ e.printStackTrace(); throw new CattSqlException("数据库查询失败"); } } /** * 删除表格 * * drop table `table`; * * @param table 表名 * @throws CattSqlException 删除异常 通常是表名不存在 */ public void dropTable(String table) throws CattSqlException{ if(this.conn == null) connect(); String sql = "drop table `" + table + "`;"; try{ PreparedStatement ps = conn.prepareStatement(sql); ps.executeUpdate(); this.sql = sql; } catch (SQLException e) { e.printStackTrace(); throw new CattSqlException("删除数据库失败"); } } /** * 关闭数据库连接 */ public void release() throws CattSqlException{ if(this.conn == null) return; try { conn.close(); this.conn = null; } catch (SQLException e) { e.printStackTrace(); throw new CattSqlException("关闭连接失败"); } } /** * 获取数据库连接对象 * * 对于复杂的SQL语句, 可以通过获取Connection对象, 然后再执行SQL语句. * 这个connection是新的对象, 所以在使用后要记得释放掉 * * @return Connection 对象 * @throws CattSqlException */ public Connection getConn() throws CattSqlException{ if(conn != null){ String url = "jdbc:mysql://" + this.dbHost + ":" + this.dbPort + "/" + this.dbName; try { return DriverManager.getConnection(url, this.dbUser, this.dbPass); } catch (SQLException e) { e.printStackTrace(); throw new CattSqlException("数据库连接失败"); } } else throw new CattSqlException("数据库连接失败"); } }
1
13
1
29804_3
package com.cccll.proxy; import com.cccll.entity.RpcServiceProperties; import com.cccll.remoting.dto.RpcMessageChecker; import com.cccll.remoting.dto.RpcRequest; import com.cccll.remoting.dto.RpcResponse; import com.cccll.remoting.transport.ClientTransport; import com.cccll.remoting.transport.netty.client.NettyClientTransport; import com.cccll.remoting.transport.socket.SocketRpcClient; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.UUID; import java.util.concurrent.CompletableFuture; /** * 动态代理类。当动态代理对象调用一个方法的时候,实际调用的是下面的 invoke 方法。 * 正是因为动态代理才让客户端调用的远程方法像是调用本地方法一样(屏蔽了中间过程) * * @author cccll */ @Slf4j public class RpcClientProxy implements InvocationHandler { /** * 用于发送请求给服务端,对应socket和netty两种实现方式 */ private final ClientTransport clientTransport; private final RpcServiceProperties rpcServiceProperties; public RpcClientProxy(ClientTransport clientTransport, RpcServiceProperties rpcServiceProperties) { this.clientTransport = clientTransport; if (rpcServiceProperties.getGroup() == null) { rpcServiceProperties.setGroup(""); } if (rpcServiceProperties.getVersion() == null) { rpcServiceProperties.setVersion(""); } this.rpcServiceProperties = rpcServiceProperties; } public RpcClientProxy(ClientTransport clientTransport) { this.clientTransport = clientTransport; this.rpcServiceProperties = RpcServiceProperties.builder().group("").version("").build(); } /** * 通过 Proxy.newProxyInstance() 方法获取某个类的代理对象 */ @SuppressWarnings("unchecked") public <T> T getProxy(Class<T> clazz) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, this); } /** * 当你使用代理对象调用方法的时候实际会调用到这个方法。代理对象就是你通过上面的 getProxy 方法获取到的对象。 */ @SneakyThrows @SuppressWarnings("unchecked") @Override public Object invoke(Object proxy, Method method, Object[] args) { log.info("invoked method: [{}]", method.getName()); //构建rpc请求体 RpcRequest rpcRequest = RpcRequest.builder().methodName(method.getName()) .parameters(args) .interfaceName(method.getDeclaringClass().getName()) .paramTypes(method.getParameterTypes()) .requestId(UUID.randomUUID().toString()) .group(rpcServiceProperties.getGroup()) .version(rpcServiceProperties.getVersion()) .build(); RpcResponse<Object> rpcResponse = null; //根据clientTransport的实际类型,会以不同方式发送rpc请求体,然后得到其rpcResponse,返回 if (clientTransport instanceof NettyClientTransport) { CompletableFuture<RpcResponse<Object>> completableFuture = (CompletableFuture<RpcResponse<Object>>) clientTransport.sendRpcRequest(rpcRequest); //此处有可能会阻塞,但不会一直阻塞,如果请求发生错误,会在添加的 中调用CompletableFuture.completeExceptionally(future.cause()),即可解除阻塞 rpcResponse = completableFuture.get(); } if (clientTransport instanceof SocketRpcClient) { rpcResponse = (RpcResponse<Object>) clientTransport.sendRpcRequest(rpcRequest); } //校验 RpcResponse 和 RpcRequest RpcMessageChecker.check(rpcResponse, rpcRequest); return rpcResponse.getData(); } }
CCCLL/lrpc
lrpc-framework/src/main/java/com/cccll/proxy/RpcClientProxy.java
890
/** * 当你使用代理对象调用方法的时候实际会调用到这个方法。代理对象就是你通过上面的 getProxy 方法获取到的对象。 */
block_comment
zh-cn
package com.cccll.proxy; import com.cccll.entity.RpcServiceProperties; import com.cccll.remoting.dto.RpcMessageChecker; import com.cccll.remoting.dto.RpcRequest; import com.cccll.remoting.dto.RpcResponse; import com.cccll.remoting.transport.ClientTransport; import com.cccll.remoting.transport.netty.client.NettyClientTransport; import com.cccll.remoting.transport.socket.SocketRpcClient; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.UUID; import java.util.concurrent.CompletableFuture; /** * 动态代理类。当动态代理对象调用一个方法的时候,实际调用的是下面的 invoke 方法。 * 正是因为动态代理才让客户端调用的远程方法像是调用本地方法一样(屏蔽了中间过程) * * @author cccll */ @Slf4j public class RpcClientProxy implements InvocationHandler { /** * 用于发送请求给服务端,对应socket和netty两种实现方式 */ private final ClientTransport clientTransport; private final RpcServiceProperties rpcServiceProperties; public RpcClientProxy(ClientTransport clientTransport, RpcServiceProperties rpcServiceProperties) { this.clientTransport = clientTransport; if (rpcServiceProperties.getGroup() == null) { rpcServiceProperties.setGroup(""); } if (rpcServiceProperties.getVersion() == null) { rpcServiceProperties.setVersion(""); } this.rpcServiceProperties = rpcServiceProperties; } public RpcClientProxy(ClientTransport clientTransport) { this.clientTransport = clientTransport; this.rpcServiceProperties = RpcServiceProperties.builder().group("").version("").build(); } /** * 通过 Proxy.newProxyInstance() 方法获取某个类的代理对象 */ @SuppressWarnings("unchecked") public <T> T getProxy(Class<T> clazz) { return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, this); } /** * 当你使 <SUF>*/ @SneakyThrows @SuppressWarnings("unchecked") @Override public Object invoke(Object proxy, Method method, Object[] args) { log.info("invoked method: [{}]", method.getName()); //构建rpc请求体 RpcRequest rpcRequest = RpcRequest.builder().methodName(method.getName()) .parameters(args) .interfaceName(method.getDeclaringClass().getName()) .paramTypes(method.getParameterTypes()) .requestId(UUID.randomUUID().toString()) .group(rpcServiceProperties.getGroup()) .version(rpcServiceProperties.getVersion()) .build(); RpcResponse<Object> rpcResponse = null; //根据clientTransport的实际类型,会以不同方式发送rpc请求体,然后得到其rpcResponse,返回 if (clientTransport instanceof NettyClientTransport) { CompletableFuture<RpcResponse<Object>> completableFuture = (CompletableFuture<RpcResponse<Object>>) clientTransport.sendRpcRequest(rpcRequest); //此处有可能会阻塞,但不会一直阻塞,如果请求发生错误,会在添加的 中调用CompletableFuture.completeExceptionally(future.cause()),即可解除阻塞 rpcResponse = completableFuture.get(); } if (clientTransport instanceof SocketRpcClient) { rpcResponse = (RpcResponse<Object>) clientTransport.sendRpcRequest(rpcRequest); } //校验 RpcResponse 和 RpcRequest RpcMessageChecker.check(rpcResponse, rpcRequest); return rpcResponse.getData(); } }
1
76
1
65529_65
package com.example.lishidatiapp.fragment; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.lishidatiapp.R; import com.example.lishidatiapp.RegisterActivity; import com.example.lishidatiapp.activity.EventsAdapter; import com.example.lishidatiapp.bean.BigEvent; import com.example.lishidatiapp.bean.Const; import com.example.lishidatiapp.httpinfo.OkHttpUtils; import com.example.lishidatiapp.interfaces.OnCallBack; import com.example.lishidatiapp.util.JsonUtils; import com.example.lishidatiapp.util.ToastUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; //public class HomeFragment extends Fragment { // EventsAdapter medicationsAdapter; // List<BigEvent> bigEventList; // RecyclerView recyclerView; // View view; // public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // // view = inflater.inflate(R.layout.fragment_home, container, false); // bigEventList=new ArrayList<>(); // // 事件情况 // recyclerView = view.findViewById(R.id.event_recycle); // // ToLiShiList(); // // return view; // } // private void ToLiShiList() { // //// OkHttpUtils okHttpUtils = new OkHttpUtils(); //// okHttpUtils.requestDataFromeGet(Const.getHttpUrl(Const.sql)+"?query=getArticle&key=article"); //// okHttpUtils.setOnCallBack(new OnCallBack() { //// @Override //// public void callSuccessBack(String json) { //// //// try { //// JSONArray jsonArray = new JSONArray(json); //// //// int length = jsonArray.length(); //// int[] array = new int[length]; //// //// for (int i = 0; i < length; i++) { //// JSONObject object= (JSONObject) jsonArray.get(i); //// int id=object.getInt("id"); //// String shortname=object.getString("shortname"); //// String introduce=object.getString("introduce"); //// String photo=object.getString("photo"); //// BigEvent event=new BigEvent(); //// event.setId(id); //// event.setIntroduce(introduce); //// event.setShortname(shortname); //// event.setPhoto(photo); //// bigEventList.add(event); //// } //// LinearLayoutManager manager = new LinearLayoutManager(getContext()); //// manager.setOrientation(LinearLayoutManager.VERTICAL); //// medicationsAdapter = new EventsAdapter(getContext(), bigEventList); //// recyclerView.setAdapter(medicationsAdapter); //// recyclerView.setItemAnimator(new DefaultItemAnimator()); //// recyclerView.setLayoutManager(manager); //// recyclerView.addItemDecoration(new CustomItemDecoration()); //// }catch (Exception e){ //// e.printStackTrace(); //// //链接错误信息 //// ToastUtils.showToast(getContext(), e.toString()); //// } //// } //// @Override //// public void callErrorBack(String json) { //// //链接错误信息 //// ToastUtils.showToast(getContext(), json); //// } //// }); // // } // public static class CustomItemDecoration extends RecyclerView.ItemDecoration { // @Override // public void getItemOffsets(Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { // // 设置元素之间的偏移量为0,即去掉分割线 // outRect.set(0, 0, 0, 0); // } // } // private static final String ARG_PARAM1 = "param1"; // private static final String ARG_PARAM2 = "param2"; // public static HomeFragment newInstance( String param1, String param2) { // HomeFragment fragment = new HomeFragment(); // Bundle args = new Bundle(); // args.putString(ARG_PARAM1, param1); // args.putString(ARG_PARAM2, param2); // fragment.setArguments(args); // return fragment; // } // //} public class HomeFragment extends Fragment { private final List<BigEvent> bigEventList = new ArrayList<>(); EventsAdapter medicationsAdapter; View view; Context context; void initData() { @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable1 = getResources().getDrawable(R.drawable.mingchao); BigEvent bigEvent1 = new BigEvent(1, "明朝", "1368年-1644年", "明朝是中国历史上最后由汉族建立的大一统王朝, 历经12世、16位皇帝,国祚276年。", drawable1); bigEventList.add(bigEvent1); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable2 = getResources().getDrawable(R.drawable.jingnan); BigEvent bigEvent2 = new BigEvent(2, "靖难之役", "1399年8月6日", "靖难之役又称靖难之变是中国明朝初年建文帝在位时发生的一场因削藩政策引发的争夺皇位的内战。", drawable2); bigEventList.add(bigEvent2); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable3 = getResources().getDrawable(R.drawable.nuomandi); BigEvent bigEvent3 = new BigEvent(3, "诺曼底登陆", "1944年", "诺曼底登陆,代号海王行动,是第二次世界大战西方盟军在欧洲西线战场发起的一场大规模攻势。", drawable3); bigEventList.add(bigEvent3); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable4 = getResources().getDrawable(R.drawable.songlu); BigEvent bigEvent4 = new BigEvent(4, "淞沪会战", "1937年11月", "日军占领北平、天津后,在南方又集中兵力约28万人,陆海空三军联合猛烈进攻上海、南京地区。", drawable4); bigEventList.add(bigEvent4); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable5 = getResources().getDrawable(R.drawable.zhongtudao); BigEvent bigEvent5 = new BigEvent(5, "中途岛海战", "1942年", "中途岛海战是第二次世界大战中美国海军和日本海军在中途岛附近海域进行的一场大规模海战。", drawable5); bigEventList.add(bigEvent5); } public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_home, container, false); context = view.getContext(); // 事件情况 RecyclerView recyclerView = view.findViewById(R.id.event_recycle); initData(); LinearLayoutManager manager = new LinearLayoutManager(context); manager.setOrientation(LinearLayoutManager.VERTICAL); medicationsAdapter = new EventsAdapter(context, bigEventList); recyclerView.setAdapter(medicationsAdapter); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setLayoutManager(manager); recyclerView.addItemDecoration(new CustomItemDecoration()); return view; } @Override public void onDestroyView() { super.onDestroyView(); } public static class CustomItemDecoration extends RecyclerView.ItemDecoration { @Override public void getItemOffsets(Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { // 设置元素之间的偏移量为0,即去掉分割线 outRect.set(0, 0, 0, 0); } } private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; public static HomeFragment newInstance(String param1, String param2) { HomeFragment fragment = new HomeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } }
CCP101/visual-kg-history
android/app/src/main/java/com/example/lishidatiapp/fragment/HomeFragment.java
2,180
// 设置元素之间的偏移量为0,即去掉分割线
line_comment
zh-cn
package com.example.lishidatiapp.fragment; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.DefaultItemAnimator; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.example.lishidatiapp.R; import com.example.lishidatiapp.RegisterActivity; import com.example.lishidatiapp.activity.EventsAdapter; import com.example.lishidatiapp.bean.BigEvent; import com.example.lishidatiapp.bean.Const; import com.example.lishidatiapp.httpinfo.OkHttpUtils; import com.example.lishidatiapp.interfaces.OnCallBack; import com.example.lishidatiapp.util.JsonUtils; import com.example.lishidatiapp.util.ToastUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; //public class HomeFragment extends Fragment { // EventsAdapter medicationsAdapter; // List<BigEvent> bigEventList; // RecyclerView recyclerView; // View view; // public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // // view = inflater.inflate(R.layout.fragment_home, container, false); // bigEventList=new ArrayList<>(); // // 事件情况 // recyclerView = view.findViewById(R.id.event_recycle); // // ToLiShiList(); // // return view; // } // private void ToLiShiList() { // //// OkHttpUtils okHttpUtils = new OkHttpUtils(); //// okHttpUtils.requestDataFromeGet(Const.getHttpUrl(Const.sql)+"?query=getArticle&key=article"); //// okHttpUtils.setOnCallBack(new OnCallBack() { //// @Override //// public void callSuccessBack(String json) { //// //// try { //// JSONArray jsonArray = new JSONArray(json); //// //// int length = jsonArray.length(); //// int[] array = new int[length]; //// //// for (int i = 0; i < length; i++) { //// JSONObject object= (JSONObject) jsonArray.get(i); //// int id=object.getInt("id"); //// String shortname=object.getString("shortname"); //// String introduce=object.getString("introduce"); //// String photo=object.getString("photo"); //// BigEvent event=new BigEvent(); //// event.setId(id); //// event.setIntroduce(introduce); //// event.setShortname(shortname); //// event.setPhoto(photo); //// bigEventList.add(event); //// } //// LinearLayoutManager manager = new LinearLayoutManager(getContext()); //// manager.setOrientation(LinearLayoutManager.VERTICAL); //// medicationsAdapter = new EventsAdapter(getContext(), bigEventList); //// recyclerView.setAdapter(medicationsAdapter); //// recyclerView.setItemAnimator(new DefaultItemAnimator()); //// recyclerView.setLayoutManager(manager); //// recyclerView.addItemDecoration(new CustomItemDecoration()); //// }catch (Exception e){ //// e.printStackTrace(); //// //链接错误信息 //// ToastUtils.showToast(getContext(), e.toString()); //// } //// } //// @Override //// public void callErrorBack(String json) { //// //链接错误信息 //// ToastUtils.showToast(getContext(), json); //// } //// }); // // } // public static class CustomItemDecoration extends RecyclerView.ItemDecoration { // @Override // public void getItemOffsets(Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { // // 设置元素之间的偏移量为0,即去掉分割线 // outRect.set(0, 0, 0, 0); // } // } // private static final String ARG_PARAM1 = "param1"; // private static final String ARG_PARAM2 = "param2"; // public static HomeFragment newInstance( String param1, String param2) { // HomeFragment fragment = new HomeFragment(); // Bundle args = new Bundle(); // args.putString(ARG_PARAM1, param1); // args.putString(ARG_PARAM2, param2); // fragment.setArguments(args); // return fragment; // } // //} public class HomeFragment extends Fragment { private final List<BigEvent> bigEventList = new ArrayList<>(); EventsAdapter medicationsAdapter; View view; Context context; void initData() { @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable1 = getResources().getDrawable(R.drawable.mingchao); BigEvent bigEvent1 = new BigEvent(1, "明朝", "1368年-1644年", "明朝是中国历史上最后由汉族建立的大一统王朝, 历经12世、16位皇帝,国祚276年。", drawable1); bigEventList.add(bigEvent1); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable2 = getResources().getDrawable(R.drawable.jingnan); BigEvent bigEvent2 = new BigEvent(2, "靖难之役", "1399年8月6日", "靖难之役又称靖难之变是中国明朝初年建文帝在位时发生的一场因削藩政策引发的争夺皇位的内战。", drawable2); bigEventList.add(bigEvent2); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable3 = getResources().getDrawable(R.drawable.nuomandi); BigEvent bigEvent3 = new BigEvent(3, "诺曼底登陆", "1944年", "诺曼底登陆,代号海王行动,是第二次世界大战西方盟军在欧洲西线战场发起的一场大规模攻势。", drawable3); bigEventList.add(bigEvent3); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable4 = getResources().getDrawable(R.drawable.songlu); BigEvent bigEvent4 = new BigEvent(4, "淞沪会战", "1937年11月", "日军占领北平、天津后,在南方又集中兵力约28万人,陆海空三军联合猛烈进攻上海、南京地区。", drawable4); bigEventList.add(bigEvent4); @SuppressLint("UseCompatLoadingForDrawables") Drawable drawable5 = getResources().getDrawable(R.drawable.zhongtudao); BigEvent bigEvent5 = new BigEvent(5, "中途岛海战", "1942年", "中途岛海战是第二次世界大战中美国海军和日本海军在中途岛附近海域进行的一场大规模海战。", drawable5); bigEventList.add(bigEvent5); } public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_home, container, false); context = view.getContext(); // 事件情况 RecyclerView recyclerView = view.findViewById(R.id.event_recycle); initData(); LinearLayoutManager manager = new LinearLayoutManager(context); manager.setOrientation(LinearLayoutManager.VERTICAL); medicationsAdapter = new EventsAdapter(context, bigEventList); recyclerView.setAdapter(medicationsAdapter); recyclerView.setItemAnimator(new DefaultItemAnimator()); recyclerView.setLayoutManager(manager); recyclerView.addItemDecoration(new CustomItemDecoration()); return view; } @Override public void onDestroyView() { super.onDestroyView(); } public static class CustomItemDecoration extends RecyclerView.ItemDecoration { @Override public void getItemOffsets(Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { // 设置 <SUF> outRect.set(0, 0, 0, 0); } } private static final String ARG_PARAM1 = "param1"; private static final String ARG_PARAM2 = "param2"; public static HomeFragment newInstance(String param1, String param2) { HomeFragment fragment = new HomeFragment(); Bundle args = new Bundle(); args.putString(ARG_PARAM1, param1); args.putString(ARG_PARAM2, param2); fragment.setArguments(args); return fragment; } }
1
22
1
26634_2
// Product.java public class Product { public static String[] TYPES = { "全部", "电脑", "手机", "书籍" }; // 所有类型 private String id; //产品编号 private String name; // 名称 private String type; // 类型 private double price; // 价格 private int number; // 库存 public Product(String line) { String[] args = line.split(";"); id = args[0]; name = args[1]; type = args[2]; price = Double.parseDouble(args[3]); number = Integer.parseInt(args[4]); } public String toString() { return id + ";" + name + ";" + type + ";" + price + ";" + number; } public String getType() { return type; } public String getId() { return id; } public int getNumber() { return number; } }
CColike/Soochow-University-CS
Java/final/Project.java
238
//产品编号
line_comment
zh-cn
// Product.java public class Product { public static String[] TYPES = { "全部", "电脑", "手机", "书籍" }; // 所有类型 private String id; //产品 <SUF> private String name; // 名称 private String type; // 类型 private double price; // 价格 private int number; // 库存 public Product(String line) { String[] args = line.split(";"); id = args[0]; name = args[1]; type = args[2]; price = Double.parseDouble(args[3]); number = Integer.parseInt(args[4]); } public String toString() { return id + ";" + name + ";" + type + ";" + price + ";" + number; } public String getType() { return type; } public String getId() { return id; } public int getNumber() { return number; } }
1
6
1
56703_4
package art; import java.util.*; import faultZone.FaultZone; import faultZone.FaultZone_Point_Square; import util.*; /** * RRT(2004) * 论文:A revisit of adaptive random testing by restriction, * 大致方法: * 1. 随机选择一个用例进行测试 * 2. 设置一个限制倍数r * 3. 利用r计算以之前测试的用例为中心的排除半径 * 4. 将半径内的所有用例排除,生成新的测试用例域,从中随机选择下一个用例 */ public class RRT extends AbstractART{ double rate = 0.8; //用输入来初始化该算法 public RRT(DomainBoundary inputBoundary) { this.inputBoundary = inputBoundary; } public static void main(String args[]){ int times = 3000;//一次执行,该算法就重复3000次 long sums = 0;// 初始化使用的测试用例数 int temp = 0;// 初始化测试用例落在失效域的使用的测试用例的个数 ArrayList<Integer> result = new ArrayList<>(); //统一p=2,表示计算输入间距离按正常方法计算(各维度距离平方和开平方) double p = Parameters.lp; double failrate = 0.005; int dimension = 2; //二维输入(即一次输入两个参数),两个数值参数的上限(5000)、下限(5000)相同 DomainBoundary bd = new DomainBoundary(dimension, -5000, 5000); for (int i = 1; i <= times; i++) { //指定使用这种fault zone FaultZone fz = new FaultZone_Point_Square(bd, failrate); RRT rrt = new RRT(bd); //小run一下 temp = rrt.runWithFaultZone(fz); result.add(temp); System.out.println("第" + i + "次试验F_Measure:" + temp); sums += temp; } System.out.println("RRT当前参数:dimension = " + dimension + " lp = " + p + " failure-rate = " + failrate); System.out.println("Fm: " + sums / (double) times + " 且最后的Fart/Frt: " + sums / (double) times * failrate);// 平均每次使用的测试用例数 } public Double calR(double rate, Testcase tc){ ArrayList<Double>Tc=tc.list; Double size = Collections.max(Tc) - Collections.min(Tc); System.out.println(size); int len = Tc.size(); Double r = Math.pow(rate*size,1.0/len); return r; } @Override public Testcase bestCandidate() { this.candidate.clear(); Testcase tc = new Testcase(inputBoundary); DomainBoundary newBoundary = inputBoundary; double r = calR(rate , tc); int count = 0; while(count < inputBoundary.getList().size() && ((inputBoundary.getList().get(count).getMin() + r)> tc.getValue(count) || (inputBoundary.getList().get(count).getMax() - r) < tc.getValue(count))) { count++; tc = new Testcase(inputBoundary); } return tc; } @Override public void testEfficiency(int pointNum) { // 计算效率测试 Testcase testcase = new Testcase(inputBoundary); while (total.size() < pointNum) { // 随机生成n个候选的测试用例 total.add(testcase); candidate = new ArrayList<Testcase>(); for (int i = 0; i < 10; i++) { candidate.add(new Testcase(inputBoundary)); } testcase = bestCandidate(); } } }
CDHZAYN/numerical-program-ART
src/art/RRT.java
927
// 初始化测试用例落在失效域的使用的测试用例的个数
line_comment
zh-cn
package art; import java.util.*; import faultZone.FaultZone; import faultZone.FaultZone_Point_Square; import util.*; /** * RRT(2004) * 论文:A revisit of adaptive random testing by restriction, * 大致方法: * 1. 随机选择一个用例进行测试 * 2. 设置一个限制倍数r * 3. 利用r计算以之前测试的用例为中心的排除半径 * 4. 将半径内的所有用例排除,生成新的测试用例域,从中随机选择下一个用例 */ public class RRT extends AbstractART{ double rate = 0.8; //用输入来初始化该算法 public RRT(DomainBoundary inputBoundary) { this.inputBoundary = inputBoundary; } public static void main(String args[]){ int times = 3000;//一次执行,该算法就重复3000次 long sums = 0;// 初始化使用的测试用例数 int temp = 0;// 初始 <SUF> ArrayList<Integer> result = new ArrayList<>(); //统一p=2,表示计算输入间距离按正常方法计算(各维度距离平方和开平方) double p = Parameters.lp; double failrate = 0.005; int dimension = 2; //二维输入(即一次输入两个参数),两个数值参数的上限(5000)、下限(5000)相同 DomainBoundary bd = new DomainBoundary(dimension, -5000, 5000); for (int i = 1; i <= times; i++) { //指定使用这种fault zone FaultZone fz = new FaultZone_Point_Square(bd, failrate); RRT rrt = new RRT(bd); //小run一下 temp = rrt.runWithFaultZone(fz); result.add(temp); System.out.println("第" + i + "次试验F_Measure:" + temp); sums += temp; } System.out.println("RRT当前参数:dimension = " + dimension + " lp = " + p + " failure-rate = " + failrate); System.out.println("Fm: " + sums / (double) times + " 且最后的Fart/Frt: " + sums / (double) times * failrate);// 平均每次使用的测试用例数 } public Double calR(double rate, Testcase tc){ ArrayList<Double>Tc=tc.list; Double size = Collections.max(Tc) - Collections.min(Tc); System.out.println(size); int len = Tc.size(); Double r = Math.pow(rate*size,1.0/len); return r; } @Override public Testcase bestCandidate() { this.candidate.clear(); Testcase tc = new Testcase(inputBoundary); DomainBoundary newBoundary = inputBoundary; double r = calR(rate , tc); int count = 0; while(count < inputBoundary.getList().size() && ((inputBoundary.getList().get(count).getMin() + r)> tc.getValue(count) || (inputBoundary.getList().get(count).getMax() - r) < tc.getValue(count))) { count++; tc = new Testcase(inputBoundary); } return tc; } @Override public void testEfficiency(int pointNum) { // 计算效率测试 Testcase testcase = new Testcase(inputBoundary); while (total.size() < pointNum) { // 随机生成n个候选的测试用例 total.add(testcase); candidate = new ArrayList<Testcase>(); for (int i = 0; i < 10; i++) { candidate.add(new Testcase(inputBoundary)); } testcase = bestCandidate(); } } }
1
26
1
46999_3
package com.generatepdg.cfg; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import com.generatepdg.cfg.edge.CFGControlEdge; import com.generatepdg.cfg.edge.CFGEdge; import com.generatepdg.cfg.node.CFGBreakStatementNode; import com.generatepdg.cfg.node.CFGContinueStatementNode; import com.generatepdg.cfg.node.CFGJumpStatementNode; import com.generatepdg.cfg.node.CFGNode; import com.generatepdg.cfg.node.CFGNodeFactory; import com.generatepdg.cfg.node.CFGPseudoNode; import com.generatepdg.cfg.node.CFGSwitchCaseNode; import com.generatepdg.pe.BlockInfo; import com.generatepdg.pe.ExpressionInfo; import com.generatepdg.pe.MethodInfo; import com.generatepdg.pe.ProgramElementInfo; import com.generatepdg.pe.StatementInfo; public class CFG { final public ProgramElementInfo core; final private CFGNodeFactory nodeFactory; final protected SortedSet<CFGNode<? extends ProgramElementInfo>> nodes; protected CFGNode<? extends ProgramElementInfo> enterNode; final protected Set<CFGNode<? extends ProgramElementInfo>> exitNodes; final protected LinkedList<CFGBreakStatementNode> unhandledBreakStatementNodes; final protected LinkedList<CFGContinueStatementNode> unhandledContinueStatementNodes; protected boolean built; public CFG(final ProgramElementInfo core, final CFGNodeFactory nodeFactory) { assert null != nodeFactory : "\"nodeFactory\" is null."; this.core = core; this.nodeFactory = nodeFactory; this.nodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); this.enterNode = null; this.exitNodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); this.built = false; this.unhandledBreakStatementNodes = new LinkedList<CFGBreakStatementNode>(); this.unhandledContinueStatementNodes = new LinkedList<CFGContinueStatementNode>(); } public boolean isEmpty() { return 0 == this.nodes.size(); } public CFGNode<? extends ProgramElementInfo> getEnterNode() { return this.enterNode; } public SortedSet<CFGNode<? extends ProgramElementInfo>> getExitNodes() { final SortedSet<CFGNode<? extends ProgramElementInfo>> nodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); nodes.addAll(this.exitNodes); return nodes; } public SortedSet<CFGNode<? extends ProgramElementInfo>> getAllNodes() { final SortedSet<CFGNode<? extends ProgramElementInfo>> nodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); nodes.addAll(this.nodes); return nodes; } public void removeSwitchCases() { final Iterator<CFGNode<? extends ProgramElementInfo>> iterator = this.nodes .iterator(); while (iterator.hasNext()) { final CFGNode<? extends ProgramElementInfo> node = iterator.next(); if (node instanceof CFGSwitchCaseNode) { for (final CFGEdge edge : node.getBackwardEdges()) { final CFGNode<?> fromNode = edge.fromNode; for (final CFGNode<?> toNode : node.getForwardNodes()) { final CFGEdge newEdge; if (edge instanceof CFGControlEdge) { newEdge = CFGEdge.makeEdge(fromNode, toNode, ((CFGControlEdge) edge).control); } else { newEdge = CFGEdge.makeEdge(fromNode, toNode); } fromNode.addForwardEdge(newEdge); toNode.addBackwardEdge(newEdge); } } node.remove(); iterator.remove(); } } } public void removeJumpStatements() { final Iterator<CFGNode<? extends ProgramElementInfo>> iterator = this.nodes .iterator(); while (iterator.hasNext()) { final CFGNode<? extends ProgramElementInfo> node = iterator.next(); if (node instanceof CFGJumpStatementNode) { for (final CFGNode<?> fromNode : node.getBackwardNodes()) { for (final CFGNode<?> toNode : node.getForwardNodes()) { final CFGEdge newEdge = CFGEdge.makeJumpEdge(fromNode, toNode); fromNode.addForwardEdge(newEdge); toNode.addBackwardEdge(newEdge); } } node.remove(); iterator.remove(); } } } public void build() { assert !this.built : "this CFG has already built."; this.built = true; if (null == this.core) { final CFGNode<? extends ProgramElementInfo> node = nodeFactory .makeNormalNode(null); this.nodes.add(node); this.enterNode = node; this.exitNodes.add(node); } else if (this.core instanceof StatementInfo) { final StatementInfo coreStatement = (StatementInfo) this.core; switch (coreStatement.getCategory()) { case Catch: this.buildConditionalBlockCFG(coreStatement, false); break; case Do: this.buildDoBlockCFG(coreStatement); break; case For: this.buildForBlockCFG(coreStatement); break; case Foreach: this.buildConditionalBlockCFG(coreStatement, true); break; case If: this.buildIfBlockCFG(coreStatement); break; case Switch: this.buildSwitchBlockCFG(coreStatement); break; case Synchronized: this.buildConditionalBlockCFG(coreStatement, false); break; case TypeDeclaration: break; case Try: this.buildTryBlockCFG(coreStatement); break; case While: this.buildConditionalBlockCFG(coreStatement, true); break; case SimpleBlock: //hj add this.buildSimpleBlockCFG(coreStatement); //hj add break; default: final CFGNode<? extends ProgramElementInfo> node = this.nodeFactory .makeNormalNode(coreStatement); this.enterNode = node;//在不断的更新 if (StatementInfo.CATEGORY.Break == coreStatement.getCategory()) { this.unhandledBreakStatementNodes .addFirst((CFGBreakStatementNode) node); } else if (StatementInfo.CATEGORY.Continue == coreStatement .getCategory()) { this.unhandledContinueStatementNodes .addFirst((CFGContinueStatementNode) node); } else { this.exitNodes.add(node); } this.nodes.add(node); break; } } else if (this.core instanceof ExpressionInfo) { final ProgramElementInfo coreExpression = (ProgramElementInfo) this.core; final CFGNode<? extends ProgramElementInfo> node = this.nodeFactory .makeNormalNode(coreExpression); this.enterNode = node; this.exitNodes.add(node); this.nodes.add(node); } else if (this.core instanceof MethodInfo) { final MethodInfo coreMethod = (MethodInfo) this.core; this.buildSimpleBlockCFG(coreMethod); } else { assert false : "unexpected state."; } if (null != this.core) { this.removePseudoNodes();//处理错误的结点 } } private void buildDoBlockCFG(final StatementInfo statement) { final SequentialCFGs sequentialCFGs = new SequentialCFGs( statement.getStatements()); sequentialCFGs.build(); final ProgramElementInfo condition = statement.getCondition(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); this.enterNode = sequentialCFGs.enterNode; this.nodes.addAll(sequentialCFGs.nodes); this.nodes.add(conditionNode); this.exitNodes.add(conditionNode); this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); for (final CFGNode<?> exitNode : sequentialCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(exitNode, conditionNode); exitNode.addForwardEdge(edge); conditionNode.addBackwardEdge(edge); } final CFGEdge edge = CFGEdge.makeEdge(conditionNode, sequentialCFGs.enterNode, true); conditionNode.addForwardEdge(edge); sequentialCFGs.enterNode.addBackwardEdge(edge); this.connectCFGBreakStatementNode(statement); this.connectCFGContinueStatementNode(statement, this.enterNode); } private void buildForBlockCFG(final StatementInfo statement) { final SequentialCFGs sequentialCFGs = new SequentialCFGs( statement.getStatements()); sequentialCFGs.build(); final List<ProgramElementInfo> initializers = statement .getInitializers(); final ProgramElementInfo condition = statement.getCondition(); final List<ProgramElementInfo> updaters = statement.getUpdaters(); final SequentialCFGs initializerCFGs = new SequentialCFGs(initializers); initializerCFGs.build(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); final SequentialCFGs updaterCFGs = new SequentialCFGs(updaters); updaterCFGs.build(); this.enterNode = initializerCFGs.enterNode; this.exitNodes.add(conditionNode); this.nodes.addAll(sequentialCFGs.nodes); this.nodes.addAll(initializerCFGs.nodes); this.nodes.add(conditionNode); this.nodes.addAll(updaterCFGs.nodes); this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); for (final CFGNode<? extends ProgramElementInfo> initializerExitNode : initializerCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(initializerExitNode, conditionNode); initializerExitNode.addForwardEdge(edge); conditionNode.addBackwardEdge(edge); } { final CFGEdge controlEdge = CFGEdge.makeEdge(conditionNode, sequentialCFGs.enterNode, true); conditionNode.addForwardEdge(controlEdge); sequentialCFGs.enterNode.addBackwardEdge(controlEdge); } for (final CFGNode<? extends ProgramElementInfo> sequentialExitNode : sequentialCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(sequentialExitNode, updaterCFGs.enterNode); sequentialExitNode.addForwardEdge(edge); updaterCFGs.enterNode.addBackwardEdge(edge); } for (final CFGNode<? extends ProgramElementInfo> updaterExitNode : updaterCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(updaterExitNode, conditionNode); updaterExitNode.addForwardEdge(edge); conditionNode.addBackwardEdge(edge); } this.connectCFGBreakStatementNode(statement); this.connectCFGContinueStatementNode(statement, conditionNode); } private void buildConditionalBlockCFG(final StatementInfo statement, final boolean loop) { final List<StatementInfo> substatements = statement.getStatements(); final SequentialCFGs sequentialCFGs = new SequentialCFGs(substatements); sequentialCFGs.build(); final ProgramElementInfo condition = statement.getCondition(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); this.enterNode = conditionNode; this.nodes.addAll(sequentialCFGs.nodes); this.nodes.add(conditionNode); if (loop) { this.exitNodes.add(conditionNode); } else { this.exitNodes.addAll(sequentialCFGs.exitNodes); if (0 == substatements.size()) { this.exitNodes.add(conditionNode); } } this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); { final CFGEdge edge = CFGEdge.makeEdge(conditionNode, sequentialCFGs.enterNode, true); conditionNode.addForwardEdge(edge); sequentialCFGs.enterNode.addBackwardEdge(edge); } if (loop) { for (final CFGNode<?> exitNode : sequentialCFGs.exitNodes) { if (exitNode instanceof CFGBreakStatementNode) { this.exitNodes.add(exitNode); } else { final CFGEdge edge = CFGEdge.makeEdge(exitNode, conditionNode); exitNode.addForwardEdge(edge); conditionNode.addBackwardEdge(edge); } } this.connectCFGBreakStatementNode(statement); this.connectCFGContinueStatementNode(statement, conditionNode); } } private void buildIfBlockCFG(final StatementInfo statement) { this.buildConditionalBlockCFG(statement, false); final ProgramElementInfo condition = statement.getCondition(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); if (null != statement.getElseStatements()) { final List<StatementInfo> elseStatements = statement .getElseStatements(); final SequentialCFGs elseCFG = new SequentialCFGs(elseStatements); elseCFG.build(); this.nodes.addAll(elseCFG.nodes); this.exitNodes.addAll(elseCFG.exitNodes); if (0 == elseStatements.size()) { this.exitNodes.add(conditionNode); } { final CFGEdge edge = CFGEdge.makeEdge(conditionNode, elseCFG.enterNode, false); conditionNode.addForwardEdge(edge); elseCFG.enterNode.addBackwardEdge(edge); } this.unhandledBreakStatementNodes .addAll(elseCFG.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(elseCFG.unhandledContinueStatementNodes); } else { this.exitNodes.add(conditionNode); } } private void buildSimpleBlockCFG(final BlockInfo statement) { final List<StatementInfo> substatements = statement.getStatements();//得到所有的块信息 final SequentialCFGs sequentialCFGs = new SequentialCFGs(substatements); sequentialCFGs.build();//主要函数调用 创造 结点与边之间 this.enterNode = sequentialCFGs.enterNode; this.exitNodes.addAll(sequentialCFGs.exitNodes); this.nodes.addAll(sequentialCFGs.nodes); this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); } private void buildSwitchBlockCFG(final StatementInfo statement) { final ProgramElementInfo condition = statement.getCondition(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); this.enterNode = conditionNode; this.nodes.add(conditionNode); final List<StatementInfo> substatements = statement.getStatements(); final List<CFG> sequentialCFGs = new ArrayList<CFG>(); for (final StatementInfo substatement : substatements) { final CFG subCFG = new CFG(substatement, this.nodeFactory); subCFG.build(); sequentialCFGs.add(subCFG); this.nodes.addAll(subCFG.nodes); this.unhandledBreakStatementNodes .addAll(subCFG.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(subCFG.unhandledContinueStatementNodes); switch (substatement.getCategory()) { case Case: { final CFGEdge edge = CFGEdge.makeEdge(conditionNode, subCFG.enterNode, true); conditionNode.addForwardEdge(edge); subCFG.enterNode.addBackwardEdge(edge); break; } case Break: case Continue: { this.exitNodes.addAll(subCFG.exitNodes); break; } default: } } CFG: for (int index = 1; index < sequentialCFGs.size(); index++) { final CFG anteriorCFG = sequentialCFGs.get(index - 1); final CFG posteriorCFG = sequentialCFGs.get(index); final ProgramElementInfo anteriorCore = anteriorCFG.core; if (anteriorCore instanceof StatementInfo) { switch (((StatementInfo) anteriorCore).getCategory()) { case Break: case Continue: continue CFG; default: } } for (final CFGNode<? extends ProgramElementInfo> anteriorExitNode : anteriorCFG.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(anteriorExitNode, posteriorCFG.enterNode); anteriorExitNode.addForwardEdge(edge); posteriorCFG.enterNode.addBackwardEdge(edge); } } this.exitNodes .addAll(sequentialCFGs.get(sequentialCFGs.size() - 1).exitNodes); this.connectCFGBreakStatementNode(statement); } private void buildTryBlockCFG(final StatementInfo statement) { final List<StatementInfo> statements = statement.getStatements(); final SequentialCFGs sequentialCFGs = new SequentialCFGs(statements); sequentialCFGs.build(); final StatementInfo finallyBlock = statement.getFinallyStatement(); final CFG finallyCFG = new CFG(finallyBlock, this.nodeFactory); finallyCFG.build(); this.enterNode = sequentialCFGs.enterNode; this.nodes.addAll(sequentialCFGs.nodes); this.nodes.addAll(finallyCFG.exitNodes); this.exitNodes.addAll(finallyCFG.exitNodes); this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); for (final CFGNode<? extends ProgramElementInfo> sequentialExitNode : sequentialCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(sequentialExitNode, finallyCFG.enterNode); sequentialExitNode.addForwardEdge(edge); finallyCFG.enterNode.addBackwardEdge(edge); } for (final StatementInfo catchStatement : statement .getCatchStatements()) { final CFG catchCFG = new CFG(catchStatement, this.nodeFactory); catchCFG.build(); this.nodes.addAll(catchCFG.nodes); for (final CFGNode<? extends ProgramElementInfo> catchExitNode : catchCFG.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(catchExitNode, finallyCFG.enterNode); catchExitNode.addForwardEdge(edge); finallyCFG.enterNode.addBackwardEdge(edge); } } } private void removePseudoNodes() { final Iterator<CFGNode<? extends ProgramElementInfo>> iterator = this.nodes .iterator(); while (iterator.hasNext()) { final CFGNode<? extends ProgramElementInfo> node = iterator.next(); if (node instanceof CFGPseudoNode) { iterator.remove(); if (0 == node.compareTo(this.enterNode)) { if (0 < this.enterNode.getForwardEdges().size()) { this.enterNode = this.enterNode.getForwardNodes() .first(); } else { this.enterNode = null; } } if (this.exitNodes.contains(node)) { this.exitNodes.addAll(node.getBackwardNodes()); this.exitNodes.remove(node); } final SortedSet<CFGNode<? extends ProgramElementInfo>> backwardNodes = node .getBackwardNodes(); final SortedSet<CFGNode<? extends ProgramElementInfo>> forwardNodes = node .getForwardNodes(); for (final CFGNode<? extends ProgramElementInfo> backwardNode : backwardNodes) { backwardNode.removeForwardNode(node); } for (final CFGNode<? extends ProgramElementInfo> forwardNode : forwardNodes) { forwardNode.removeBackwardNode(node); } for (final CFGNode<? extends ProgramElementInfo> backwardNode : backwardNodes) { for (final CFGNode<? extends ProgramElementInfo> forwardNode : forwardNodes) { final CFGEdge edge = CFGEdge.makeEdge(backwardNode, forwardNode); backwardNode.addForwardEdge(edge); forwardNode.addBackwardEdge(edge); } } } } } private void connectCFGBreakStatementNode(final StatementInfo statement) { final Iterator<CFGBreakStatementNode> iterator = this.unhandledBreakStatementNodes .iterator(); while (iterator.hasNext()) { final CFGBreakStatementNode node = iterator.next(); final StatementInfo breakStatement = (StatementInfo) node.core; final String label = breakStatement.getJumpToLabel(); if (null == label) { this.exitNodes.add(node); iterator.remove(); } else { if (label.equals(statement.getLabel())) { this.exitNodes.add(node); iterator.remove(); } } } } private void connectCFGContinueStatementNode(final StatementInfo statement, final CFGNode<? extends ProgramElementInfo> distinationNode) { final Iterator<CFGContinueStatementNode> iterator = this.unhandledContinueStatementNodes .iterator(); while (iterator.hasNext()) { final CFGContinueStatementNode node = iterator.next(); final StatementInfo continueStatement = (StatementInfo) node.core; final String label = continueStatement.getJumpToLabel(); if (null == label) { final CFGEdge edge = CFGEdge.makeEdge(node, distinationNode); node.addForwardEdge(edge); distinationNode.addBackwardEdge(edge); iterator.remove(); } else { if (label.equals(statement.getLabel())) { final CFGEdge edge = CFGEdge .makeEdge(node, distinationNode); node.addForwardEdge(edge); distinationNode.addBackwardEdge(edge); iterator.remove(); } } } } private class SequentialCFGs extends CFG { final List<? extends ProgramElementInfo> elements; SequentialCFGs(final List<? extends ProgramElementInfo> elements) { super(null, CFG.this.nodeFactory); this.elements = elements; } @Override public void build() { assert !this.built : "this CFG has already built."; this.built = true; final LinkedList<CFG> sequencialCFGs = new LinkedList<CFG>(); for (final ProgramElementInfo element : this.elements) { final CFG blockCFG = new CFG(element, CFG.this.nodeFactory); blockCFG.build(); // TODO 分析每个块的信息 if (!blockCFG.isEmpty()) { sequencialCFGs.add(blockCFG); } } for (int index = 1; index < sequencialCFGs.size(); index++) { //建立边之间的关系 final CFG anteriorCFG = sequencialCFGs.get(index - 1);//前向 final CFG posteriorCFG = sequencialCFGs.get(index);//后向 for (final CFGNode<?> exitNode : anteriorCFG.exitNodes) { //以结束的边为基点 因为exitNodes中存储的是所有的边(好像是除了continue和break) final CFGEdge edge = CFGEdge.makeEdge(exitNode, posteriorCFG.enterNode);//前向的边与后向的边建立 边之间的联系 exitNode.addForwardEdge(edge); posteriorCFG.enterNode.addBackwardEdge(edge);//后向边 } } if (0 == sequencialCFGs.size()) { final CFG pseudoCFG = new CFG(null, CFG.this.nodeFactory); pseudoCFG.build(); sequencialCFGs.add(pseudoCFG); } this.enterNode = sequencialCFGs.getFirst().enterNode; this.exitNodes.addAll(sequencialCFGs.getLast().exitNodes); for (final CFG cfg : sequencialCFGs) { this.nodes.addAll(cfg.nodes); this.unhandledBreakStatementNodes .addAll(cfg.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(cfg.unhandledContinueStatementNodes); } } } public final SortedSet<CFGNode<? extends ProgramElementInfo>> getReachableNodes( final CFGNode<? extends ProgramElementInfo> startNode) { assert null != startNode : "\"startNode\" is null."; final SortedSet<CFGNode<? extends ProgramElementInfo>> nodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); this.getReachableNodes(startNode, nodes); return nodes; } private final void getReachableNodes( final CFGNode<? extends ProgramElementInfo> startNode, final SortedSet<CFGNode<? extends ProgramElementInfo>> nodes) { assert null != startNode : "\"startNode\" is null."; assert null != nodes : "\"nodes\" is null."; if (nodes.contains(startNode)) { return; } nodes.add(startNode); for (final CFGNode<? extends ProgramElementInfo> node : startNode .getForwardNodes()) { this.getReachableNodes(node, nodes); } } }
CGCL-codes/SCVDT
JVulDS/PDG/src/main/java/com/generatepdg/cfg/CFG.java
6,387
//处理错误的结点
line_comment
zh-cn
package com.generatepdg.cfg; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import com.generatepdg.cfg.edge.CFGControlEdge; import com.generatepdg.cfg.edge.CFGEdge; import com.generatepdg.cfg.node.CFGBreakStatementNode; import com.generatepdg.cfg.node.CFGContinueStatementNode; import com.generatepdg.cfg.node.CFGJumpStatementNode; import com.generatepdg.cfg.node.CFGNode; import com.generatepdg.cfg.node.CFGNodeFactory; import com.generatepdg.cfg.node.CFGPseudoNode; import com.generatepdg.cfg.node.CFGSwitchCaseNode; import com.generatepdg.pe.BlockInfo; import com.generatepdg.pe.ExpressionInfo; import com.generatepdg.pe.MethodInfo; import com.generatepdg.pe.ProgramElementInfo; import com.generatepdg.pe.StatementInfo; public class CFG { final public ProgramElementInfo core; final private CFGNodeFactory nodeFactory; final protected SortedSet<CFGNode<? extends ProgramElementInfo>> nodes; protected CFGNode<? extends ProgramElementInfo> enterNode; final protected Set<CFGNode<? extends ProgramElementInfo>> exitNodes; final protected LinkedList<CFGBreakStatementNode> unhandledBreakStatementNodes; final protected LinkedList<CFGContinueStatementNode> unhandledContinueStatementNodes; protected boolean built; public CFG(final ProgramElementInfo core, final CFGNodeFactory nodeFactory) { assert null != nodeFactory : "\"nodeFactory\" is null."; this.core = core; this.nodeFactory = nodeFactory; this.nodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); this.enterNode = null; this.exitNodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); this.built = false; this.unhandledBreakStatementNodes = new LinkedList<CFGBreakStatementNode>(); this.unhandledContinueStatementNodes = new LinkedList<CFGContinueStatementNode>(); } public boolean isEmpty() { return 0 == this.nodes.size(); } public CFGNode<? extends ProgramElementInfo> getEnterNode() { return this.enterNode; } public SortedSet<CFGNode<? extends ProgramElementInfo>> getExitNodes() { final SortedSet<CFGNode<? extends ProgramElementInfo>> nodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); nodes.addAll(this.exitNodes); return nodes; } public SortedSet<CFGNode<? extends ProgramElementInfo>> getAllNodes() { final SortedSet<CFGNode<? extends ProgramElementInfo>> nodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); nodes.addAll(this.nodes); return nodes; } public void removeSwitchCases() { final Iterator<CFGNode<? extends ProgramElementInfo>> iterator = this.nodes .iterator(); while (iterator.hasNext()) { final CFGNode<? extends ProgramElementInfo> node = iterator.next(); if (node instanceof CFGSwitchCaseNode) { for (final CFGEdge edge : node.getBackwardEdges()) { final CFGNode<?> fromNode = edge.fromNode; for (final CFGNode<?> toNode : node.getForwardNodes()) { final CFGEdge newEdge; if (edge instanceof CFGControlEdge) { newEdge = CFGEdge.makeEdge(fromNode, toNode, ((CFGControlEdge) edge).control); } else { newEdge = CFGEdge.makeEdge(fromNode, toNode); } fromNode.addForwardEdge(newEdge); toNode.addBackwardEdge(newEdge); } } node.remove(); iterator.remove(); } } } public void removeJumpStatements() { final Iterator<CFGNode<? extends ProgramElementInfo>> iterator = this.nodes .iterator(); while (iterator.hasNext()) { final CFGNode<? extends ProgramElementInfo> node = iterator.next(); if (node instanceof CFGJumpStatementNode) { for (final CFGNode<?> fromNode : node.getBackwardNodes()) { for (final CFGNode<?> toNode : node.getForwardNodes()) { final CFGEdge newEdge = CFGEdge.makeJumpEdge(fromNode, toNode); fromNode.addForwardEdge(newEdge); toNode.addBackwardEdge(newEdge); } } node.remove(); iterator.remove(); } } } public void build() { assert !this.built : "this CFG has already built."; this.built = true; if (null == this.core) { final CFGNode<? extends ProgramElementInfo> node = nodeFactory .makeNormalNode(null); this.nodes.add(node); this.enterNode = node; this.exitNodes.add(node); } else if (this.core instanceof StatementInfo) { final StatementInfo coreStatement = (StatementInfo) this.core; switch (coreStatement.getCategory()) { case Catch: this.buildConditionalBlockCFG(coreStatement, false); break; case Do: this.buildDoBlockCFG(coreStatement); break; case For: this.buildForBlockCFG(coreStatement); break; case Foreach: this.buildConditionalBlockCFG(coreStatement, true); break; case If: this.buildIfBlockCFG(coreStatement); break; case Switch: this.buildSwitchBlockCFG(coreStatement); break; case Synchronized: this.buildConditionalBlockCFG(coreStatement, false); break; case TypeDeclaration: break; case Try: this.buildTryBlockCFG(coreStatement); break; case While: this.buildConditionalBlockCFG(coreStatement, true); break; case SimpleBlock: //hj add this.buildSimpleBlockCFG(coreStatement); //hj add break; default: final CFGNode<? extends ProgramElementInfo> node = this.nodeFactory .makeNormalNode(coreStatement); this.enterNode = node;//在不断的更新 if (StatementInfo.CATEGORY.Break == coreStatement.getCategory()) { this.unhandledBreakStatementNodes .addFirst((CFGBreakStatementNode) node); } else if (StatementInfo.CATEGORY.Continue == coreStatement .getCategory()) { this.unhandledContinueStatementNodes .addFirst((CFGContinueStatementNode) node); } else { this.exitNodes.add(node); } this.nodes.add(node); break; } } else if (this.core instanceof ExpressionInfo) { final ProgramElementInfo coreExpression = (ProgramElementInfo) this.core; final CFGNode<? extends ProgramElementInfo> node = this.nodeFactory .makeNormalNode(coreExpression); this.enterNode = node; this.exitNodes.add(node); this.nodes.add(node); } else if (this.core instanceof MethodInfo) { final MethodInfo coreMethod = (MethodInfo) this.core; this.buildSimpleBlockCFG(coreMethod); } else { assert false : "unexpected state."; } if (null != this.core) { this.removePseudoNodes();//处理 <SUF> } } private void buildDoBlockCFG(final StatementInfo statement) { final SequentialCFGs sequentialCFGs = new SequentialCFGs( statement.getStatements()); sequentialCFGs.build(); final ProgramElementInfo condition = statement.getCondition(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); this.enterNode = sequentialCFGs.enterNode; this.nodes.addAll(sequentialCFGs.nodes); this.nodes.add(conditionNode); this.exitNodes.add(conditionNode); this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); for (final CFGNode<?> exitNode : sequentialCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(exitNode, conditionNode); exitNode.addForwardEdge(edge); conditionNode.addBackwardEdge(edge); } final CFGEdge edge = CFGEdge.makeEdge(conditionNode, sequentialCFGs.enterNode, true); conditionNode.addForwardEdge(edge); sequentialCFGs.enterNode.addBackwardEdge(edge); this.connectCFGBreakStatementNode(statement); this.connectCFGContinueStatementNode(statement, this.enterNode); } private void buildForBlockCFG(final StatementInfo statement) { final SequentialCFGs sequentialCFGs = new SequentialCFGs( statement.getStatements()); sequentialCFGs.build(); final List<ProgramElementInfo> initializers = statement .getInitializers(); final ProgramElementInfo condition = statement.getCondition(); final List<ProgramElementInfo> updaters = statement.getUpdaters(); final SequentialCFGs initializerCFGs = new SequentialCFGs(initializers); initializerCFGs.build(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); final SequentialCFGs updaterCFGs = new SequentialCFGs(updaters); updaterCFGs.build(); this.enterNode = initializerCFGs.enterNode; this.exitNodes.add(conditionNode); this.nodes.addAll(sequentialCFGs.nodes); this.nodes.addAll(initializerCFGs.nodes); this.nodes.add(conditionNode); this.nodes.addAll(updaterCFGs.nodes); this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); for (final CFGNode<? extends ProgramElementInfo> initializerExitNode : initializerCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(initializerExitNode, conditionNode); initializerExitNode.addForwardEdge(edge); conditionNode.addBackwardEdge(edge); } { final CFGEdge controlEdge = CFGEdge.makeEdge(conditionNode, sequentialCFGs.enterNode, true); conditionNode.addForwardEdge(controlEdge); sequentialCFGs.enterNode.addBackwardEdge(controlEdge); } for (final CFGNode<? extends ProgramElementInfo> sequentialExitNode : sequentialCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(sequentialExitNode, updaterCFGs.enterNode); sequentialExitNode.addForwardEdge(edge); updaterCFGs.enterNode.addBackwardEdge(edge); } for (final CFGNode<? extends ProgramElementInfo> updaterExitNode : updaterCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(updaterExitNode, conditionNode); updaterExitNode.addForwardEdge(edge); conditionNode.addBackwardEdge(edge); } this.connectCFGBreakStatementNode(statement); this.connectCFGContinueStatementNode(statement, conditionNode); } private void buildConditionalBlockCFG(final StatementInfo statement, final boolean loop) { final List<StatementInfo> substatements = statement.getStatements(); final SequentialCFGs sequentialCFGs = new SequentialCFGs(substatements); sequentialCFGs.build(); final ProgramElementInfo condition = statement.getCondition(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); this.enterNode = conditionNode; this.nodes.addAll(sequentialCFGs.nodes); this.nodes.add(conditionNode); if (loop) { this.exitNodes.add(conditionNode); } else { this.exitNodes.addAll(sequentialCFGs.exitNodes); if (0 == substatements.size()) { this.exitNodes.add(conditionNode); } } this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); { final CFGEdge edge = CFGEdge.makeEdge(conditionNode, sequentialCFGs.enterNode, true); conditionNode.addForwardEdge(edge); sequentialCFGs.enterNode.addBackwardEdge(edge); } if (loop) { for (final CFGNode<?> exitNode : sequentialCFGs.exitNodes) { if (exitNode instanceof CFGBreakStatementNode) { this.exitNodes.add(exitNode); } else { final CFGEdge edge = CFGEdge.makeEdge(exitNode, conditionNode); exitNode.addForwardEdge(edge); conditionNode.addBackwardEdge(edge); } } this.connectCFGBreakStatementNode(statement); this.connectCFGContinueStatementNode(statement, conditionNode); } } private void buildIfBlockCFG(final StatementInfo statement) { this.buildConditionalBlockCFG(statement, false); final ProgramElementInfo condition = statement.getCondition(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); if (null != statement.getElseStatements()) { final List<StatementInfo> elseStatements = statement .getElseStatements(); final SequentialCFGs elseCFG = new SequentialCFGs(elseStatements); elseCFG.build(); this.nodes.addAll(elseCFG.nodes); this.exitNodes.addAll(elseCFG.exitNodes); if (0 == elseStatements.size()) { this.exitNodes.add(conditionNode); } { final CFGEdge edge = CFGEdge.makeEdge(conditionNode, elseCFG.enterNode, false); conditionNode.addForwardEdge(edge); elseCFG.enterNode.addBackwardEdge(edge); } this.unhandledBreakStatementNodes .addAll(elseCFG.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(elseCFG.unhandledContinueStatementNodes); } else { this.exitNodes.add(conditionNode); } } private void buildSimpleBlockCFG(final BlockInfo statement) { final List<StatementInfo> substatements = statement.getStatements();//得到所有的块信息 final SequentialCFGs sequentialCFGs = new SequentialCFGs(substatements); sequentialCFGs.build();//主要函数调用 创造 结点与边之间 this.enterNode = sequentialCFGs.enterNode; this.exitNodes.addAll(sequentialCFGs.exitNodes); this.nodes.addAll(sequentialCFGs.nodes); this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); } private void buildSwitchBlockCFG(final StatementInfo statement) { final ProgramElementInfo condition = statement.getCondition(); final CFGNode<? extends ProgramElementInfo> conditionNode = this.nodeFactory .makeControlNode(condition); this.enterNode = conditionNode; this.nodes.add(conditionNode); final List<StatementInfo> substatements = statement.getStatements(); final List<CFG> sequentialCFGs = new ArrayList<CFG>(); for (final StatementInfo substatement : substatements) { final CFG subCFG = new CFG(substatement, this.nodeFactory); subCFG.build(); sequentialCFGs.add(subCFG); this.nodes.addAll(subCFG.nodes); this.unhandledBreakStatementNodes .addAll(subCFG.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(subCFG.unhandledContinueStatementNodes); switch (substatement.getCategory()) { case Case: { final CFGEdge edge = CFGEdge.makeEdge(conditionNode, subCFG.enterNode, true); conditionNode.addForwardEdge(edge); subCFG.enterNode.addBackwardEdge(edge); break; } case Break: case Continue: { this.exitNodes.addAll(subCFG.exitNodes); break; } default: } } CFG: for (int index = 1; index < sequentialCFGs.size(); index++) { final CFG anteriorCFG = sequentialCFGs.get(index - 1); final CFG posteriorCFG = sequentialCFGs.get(index); final ProgramElementInfo anteriorCore = anteriorCFG.core; if (anteriorCore instanceof StatementInfo) { switch (((StatementInfo) anteriorCore).getCategory()) { case Break: case Continue: continue CFG; default: } } for (final CFGNode<? extends ProgramElementInfo> anteriorExitNode : anteriorCFG.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(anteriorExitNode, posteriorCFG.enterNode); anteriorExitNode.addForwardEdge(edge); posteriorCFG.enterNode.addBackwardEdge(edge); } } this.exitNodes .addAll(sequentialCFGs.get(sequentialCFGs.size() - 1).exitNodes); this.connectCFGBreakStatementNode(statement); } private void buildTryBlockCFG(final StatementInfo statement) { final List<StatementInfo> statements = statement.getStatements(); final SequentialCFGs sequentialCFGs = new SequentialCFGs(statements); sequentialCFGs.build(); final StatementInfo finallyBlock = statement.getFinallyStatement(); final CFG finallyCFG = new CFG(finallyBlock, this.nodeFactory); finallyCFG.build(); this.enterNode = sequentialCFGs.enterNode; this.nodes.addAll(sequentialCFGs.nodes); this.nodes.addAll(finallyCFG.exitNodes); this.exitNodes.addAll(finallyCFG.exitNodes); this.unhandledBreakStatementNodes .addAll(sequentialCFGs.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(sequentialCFGs.unhandledContinueStatementNodes); for (final CFGNode<? extends ProgramElementInfo> sequentialExitNode : sequentialCFGs.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(sequentialExitNode, finallyCFG.enterNode); sequentialExitNode.addForwardEdge(edge); finallyCFG.enterNode.addBackwardEdge(edge); } for (final StatementInfo catchStatement : statement .getCatchStatements()) { final CFG catchCFG = new CFG(catchStatement, this.nodeFactory); catchCFG.build(); this.nodes.addAll(catchCFG.nodes); for (final CFGNode<? extends ProgramElementInfo> catchExitNode : catchCFG.exitNodes) { final CFGEdge edge = CFGEdge.makeEdge(catchExitNode, finallyCFG.enterNode); catchExitNode.addForwardEdge(edge); finallyCFG.enterNode.addBackwardEdge(edge); } } } private void removePseudoNodes() { final Iterator<CFGNode<? extends ProgramElementInfo>> iterator = this.nodes .iterator(); while (iterator.hasNext()) { final CFGNode<? extends ProgramElementInfo> node = iterator.next(); if (node instanceof CFGPseudoNode) { iterator.remove(); if (0 == node.compareTo(this.enterNode)) { if (0 < this.enterNode.getForwardEdges().size()) { this.enterNode = this.enterNode.getForwardNodes() .first(); } else { this.enterNode = null; } } if (this.exitNodes.contains(node)) { this.exitNodes.addAll(node.getBackwardNodes()); this.exitNodes.remove(node); } final SortedSet<CFGNode<? extends ProgramElementInfo>> backwardNodes = node .getBackwardNodes(); final SortedSet<CFGNode<? extends ProgramElementInfo>> forwardNodes = node .getForwardNodes(); for (final CFGNode<? extends ProgramElementInfo> backwardNode : backwardNodes) { backwardNode.removeForwardNode(node); } for (final CFGNode<? extends ProgramElementInfo> forwardNode : forwardNodes) { forwardNode.removeBackwardNode(node); } for (final CFGNode<? extends ProgramElementInfo> backwardNode : backwardNodes) { for (final CFGNode<? extends ProgramElementInfo> forwardNode : forwardNodes) { final CFGEdge edge = CFGEdge.makeEdge(backwardNode, forwardNode); backwardNode.addForwardEdge(edge); forwardNode.addBackwardEdge(edge); } } } } } private void connectCFGBreakStatementNode(final StatementInfo statement) { final Iterator<CFGBreakStatementNode> iterator = this.unhandledBreakStatementNodes .iterator(); while (iterator.hasNext()) { final CFGBreakStatementNode node = iterator.next(); final StatementInfo breakStatement = (StatementInfo) node.core; final String label = breakStatement.getJumpToLabel(); if (null == label) { this.exitNodes.add(node); iterator.remove(); } else { if (label.equals(statement.getLabel())) { this.exitNodes.add(node); iterator.remove(); } } } } private void connectCFGContinueStatementNode(final StatementInfo statement, final CFGNode<? extends ProgramElementInfo> distinationNode) { final Iterator<CFGContinueStatementNode> iterator = this.unhandledContinueStatementNodes .iterator(); while (iterator.hasNext()) { final CFGContinueStatementNode node = iterator.next(); final StatementInfo continueStatement = (StatementInfo) node.core; final String label = continueStatement.getJumpToLabel(); if (null == label) { final CFGEdge edge = CFGEdge.makeEdge(node, distinationNode); node.addForwardEdge(edge); distinationNode.addBackwardEdge(edge); iterator.remove(); } else { if (label.equals(statement.getLabel())) { final CFGEdge edge = CFGEdge .makeEdge(node, distinationNode); node.addForwardEdge(edge); distinationNode.addBackwardEdge(edge); iterator.remove(); } } } } private class SequentialCFGs extends CFG { final List<? extends ProgramElementInfo> elements; SequentialCFGs(final List<? extends ProgramElementInfo> elements) { super(null, CFG.this.nodeFactory); this.elements = elements; } @Override public void build() { assert !this.built : "this CFG has already built."; this.built = true; final LinkedList<CFG> sequencialCFGs = new LinkedList<CFG>(); for (final ProgramElementInfo element : this.elements) { final CFG blockCFG = new CFG(element, CFG.this.nodeFactory); blockCFG.build(); // TODO 分析每个块的信息 if (!blockCFG.isEmpty()) { sequencialCFGs.add(blockCFG); } } for (int index = 1; index < sequencialCFGs.size(); index++) { //建立边之间的关系 final CFG anteriorCFG = sequencialCFGs.get(index - 1);//前向 final CFG posteriorCFG = sequencialCFGs.get(index);//后向 for (final CFGNode<?> exitNode : anteriorCFG.exitNodes) { //以结束的边为基点 因为exitNodes中存储的是所有的边(好像是除了continue和break) final CFGEdge edge = CFGEdge.makeEdge(exitNode, posteriorCFG.enterNode);//前向的边与后向的边建立 边之间的联系 exitNode.addForwardEdge(edge); posteriorCFG.enterNode.addBackwardEdge(edge);//后向边 } } if (0 == sequencialCFGs.size()) { final CFG pseudoCFG = new CFG(null, CFG.this.nodeFactory); pseudoCFG.build(); sequencialCFGs.add(pseudoCFG); } this.enterNode = sequencialCFGs.getFirst().enterNode; this.exitNodes.addAll(sequencialCFGs.getLast().exitNodes); for (final CFG cfg : sequencialCFGs) { this.nodes.addAll(cfg.nodes); this.unhandledBreakStatementNodes .addAll(cfg.unhandledBreakStatementNodes); this.unhandledContinueStatementNodes .addAll(cfg.unhandledContinueStatementNodes); } } } public final SortedSet<CFGNode<? extends ProgramElementInfo>> getReachableNodes( final CFGNode<? extends ProgramElementInfo> startNode) { assert null != startNode : "\"startNode\" is null."; final SortedSet<CFGNode<? extends ProgramElementInfo>> nodes = new TreeSet<CFGNode<? extends ProgramElementInfo>>(); this.getReachableNodes(startNode, nodes); return nodes; } private final void getReachableNodes( final CFGNode<? extends ProgramElementInfo> startNode, final SortedSet<CFGNode<? extends ProgramElementInfo>> nodes) { assert null != startNode : "\"startNode\" is null."; assert null != nodes : "\"nodes\" is null."; if (nodes.contains(startNode)) { return; } nodes.add(startNode); for (final CFGNode<? extends ProgramElementInfo> node : startNode .getForwardNodes()) { this.getReachableNodes(node, nodes); } } }
1
10
1
41202_1
package works; public class Example12_1 { public static void main(String args[]) { //主线程 Speak speak1=new Speak("大象"); Speak speak2=new Speak("轿车"); Thread speakElephant =new Thread(speak1); Thread speakCar = new Thread(speak2); speakElephant.start(); //启动线程 speakCar.start(); //启动线程 for(int i=1;i<=15;i++) { System.out.print("主人"+i+" "); } } } class Speak implements Runnable { String name; Speak(String name) { this.name=name; } public void run() { for(int i=1;i<=20;i++) { System.out.print(name+i+" "); } } }
CHANGEA-code/JavaCode
JAVA实验1/src/works/Example12_1.java
222
//启动线程
line_comment
zh-cn
package works; public class Example12_1 { public static void main(String args[]) { //主线程 Speak speak1=new Speak("大象"); Speak speak2=new Speak("轿车"); Thread speakElephant =new Thread(speak1); Thread speakCar = new Thread(speak2); speakElephant.start(); //启动 <SUF> speakCar.start(); //启动线程 for(int i=1;i<=15;i++) { System.out.print("主人"+i+" "); } } } class Speak implements Runnable { String name; Speak(String name) { this.name=name; } public void run() { for(int i=1;i<=20;i++) { System.out.print(name+i+" "); } } }
1
7
1
63372_4
package pojo; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; public class BillSummary { private Integer totalCount=0;// 当日开桌数 private Double cash=0.0;// 现金 private Double mobilePay=0.0;// 移动支付 private Double byBank=0.0;// 刷卡 private Double debtorMoney=0.0;// 挂账 private Double discountMoney=0.0;// 折扣 private Double totalMoney=0.0;// 当日实际收入 private Double realMoney=0.0;// 实际收入 @JSONField(format="yyyy-MM-dd") private Date todayDate;// 当日日期 public BillSummary() { }; public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public Double getCash() { return cash; } public void setCash(Double cash) { this.cash = cash; } public Double getMobilePay() { return mobilePay; } public void setMobilePay(Double mobilePay) { this.mobilePay = mobilePay; } public Double getByBank() { return byBank; } public void setByBank(Double byBank) { this.byBank = byBank; } public Double getDebtorMoney() { return debtorMoney; } public void setDebtorMoney(Double debtor) { this.debtorMoney = debtor; } public Double getDiscountMoney() { return discountMoney; } public void setDiscountMoney(Double discountMoney) { this.discountMoney = discountMoney; } public Double getTotalMoney() { return totalMoney; } public void setTotalMoney(Double totalMoney) { this.totalMoney = totalMoney; } public Double getRealMoney() { return realMoney; } public void setRealMoney(Double realMoney) { this.realMoney = realMoney; } public Date getTodayDate() { return todayDate; } public void setTodayDate(Date todayDate) { this.todayDate = todayDate; } }
CHANGEX929/RCMS
src/pojo/BillSummary.java
588
// 当日日期
line_comment
zh-cn
package pojo; import java.util.Date; import com.alibaba.fastjson.annotation.JSONField; public class BillSummary { private Integer totalCount=0;// 当日开桌数 private Double cash=0.0;// 现金 private Double mobilePay=0.0;// 移动支付 private Double byBank=0.0;// 刷卡 private Double debtorMoney=0.0;// 挂账 private Double discountMoney=0.0;// 折扣 private Double totalMoney=0.0;// 当日实际收入 private Double realMoney=0.0;// 实际收入 @JSONField(format="yyyy-MM-dd") private Date todayDate;// 当日 <SUF> public BillSummary() { }; public Integer getTotalCount() { return totalCount; } public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } public Double getCash() { return cash; } public void setCash(Double cash) { this.cash = cash; } public Double getMobilePay() { return mobilePay; } public void setMobilePay(Double mobilePay) { this.mobilePay = mobilePay; } public Double getByBank() { return byBank; } public void setByBank(Double byBank) { this.byBank = byBank; } public Double getDebtorMoney() { return debtorMoney; } public void setDebtorMoney(Double debtor) { this.debtorMoney = debtor; } public Double getDiscountMoney() { return discountMoney; } public void setDiscountMoney(Double discountMoney) { this.discountMoney = discountMoney; } public Double getTotalMoney() { return totalMoney; } public void setTotalMoney(Double totalMoney) { this.totalMoney = totalMoney; } public Double getRealMoney() { return realMoney; } public void setRealMoney(Double realMoney) { this.realMoney = realMoney; } public Date getTodayDate() { return todayDate; } public void setTodayDate(Date todayDate) { this.todayDate = todayDate; } }
1
7
1
22536_8
package com.wzb.member.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; /** * <p> * * </p> * * @author wzb */ @Data @EqualsAndHashCode(callSuper = false) @TableName("tb_teacher") public class Teacher implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 教工号 */ private String tchNum; /** * 姓名 */ private String name; /** * email */ private String email; /** * 手机号码 */ private String mobile; /** * 办公室 */ private String office; /** * 职级 */ private Integer level; /** * 所在组号 */ private Integer teamId; /** * 账户id */ private Integer uid; /** * 所在组名 * * @TableField(exist = false): 标识它不是tb_teacher表中字段,不然会报错 */ @TableField(exist = false) private String teamName; }
CHRIS-WiNG/LAB-mms
wzb-member-api/src/main/java/com/wzb/member/entity/Teacher.java
362
/** * 所在组号 */
block_comment
zh-cn
package com.wzb.member.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; /** * <p> * * </p> * * @author wzb */ @Data @EqualsAndHashCode(callSuper = false) @TableName("tb_teacher") public class Teacher implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 教工号 */ private String tchNum; /** * 姓名 */ private String name; /** * email */ private String email; /** * 手机号码 */ private String mobile; /** * 办公室 */ private String office; /** * 职级 */ private Integer level; /** * 所在组 <SUF>*/ private Integer teamId; /** * 账户id */ private Integer uid; /** * 所在组名 * * @TableField(exist = false): 标识它不是tb_teacher表中字段,不然会报错 */ @TableField(exist = false) private String teamName; }
1
23
1
42269_4
/** * @Package: site.ckylin.tools.varutils * @author: CKylinMC * @description: * @date: 2020-08-11 13:05 */ package site.ckylin.tools.varutils; public class Is { /** * 判断字符串是否为空 * * @param value the value * @return the boolean */ public static boolean empty(String value) { if (value == null) return true; return value.trim().length() < 1; } /** * 检查字符串是否不是数字 * <a href="https://www.cnblogs.com/gaoyoubo/archive/2010/09/15/1965080.html">参考自 "Java实现isNaN - Me疯子_(~ 的博客"</a> * * @param value the value * @return the boolean */ public static boolean NaN(String value) { boolean flag = false; if (value != null && !"".equals(value.trim())) { //如果没有小数点 if (!value.contains(".")) { if (!value.matches("\\d+")) { //不是数字 flag = true; } } else if (value.indexOf(".") == 1) { String[] s_arr = value.split("\\."); String s1 = s_arr[0]; String s2 = s_arr[1]; if ((!s1.matches("\\d+")) || (!s2.matches("\\d+"))) { //不是数字 flag = true; } } } else { flag = true; } return flag; } }
CKylinMC/Helper
src/site/ckylin/tools/varutils/Is.java
400
//不是数字
line_comment
zh-cn
/** * @Package: site.ckylin.tools.varutils * @author: CKylinMC * @description: * @date: 2020-08-11 13:05 */ package site.ckylin.tools.varutils; public class Is { /** * 判断字符串是否为空 * * @param value the value * @return the boolean */ public static boolean empty(String value) { if (value == null) return true; return value.trim().length() < 1; } /** * 检查字符串是否不是数字 * <a href="https://www.cnblogs.com/gaoyoubo/archive/2010/09/15/1965080.html">参考自 "Java实现isNaN - Me疯子_(~ 的博客"</a> * * @param value the value * @return the boolean */ public static boolean NaN(String value) { boolean flag = false; if (value != null && !"".equals(value.trim())) { //如果没有小数点 if (!value.contains(".")) { if (!value.matches("\\d+")) { //不是 <SUF> flag = true; } } else if (value.indexOf(".") == 1) { String[] s_arr = value.split("\\."); String s1 = s_arr[0]; String s2 = s_arr[1]; if ((!s1.matches("\\d+")) || (!s2.matches("\\d+"))) { //不是数字 flag = true; } } } else { flag = true; } return flag; } }
1
6
1
40698_40
package src.client; import java.nio.file.Files; import java.nio.file.Paths; import java.io.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; //聊天功能 public class WorkChat implements Runnable{ DataOutputStream outputToClient = ClientMain.outputToServer; String friendName; JFrame frame = new JFrame(); JTextPane outframe = new JTextPane(); JTextField inframe = new JTextField(); JScrollPane scrollPane;//滚动输出框 JPanel inputPanel = new JPanel();//输入框 boolean isWindowOpen = false;//记录窗口是否打开 WorkChat(String friendName) { this.friendName = friendName; } //首次开启与对方的聊天窗口 public void run() { // 设置窗口 frame.setTitle(friendName); frame.setLocation(350, 200); frame.setLayout(new BorderLayout()); // 输出框 outframe.setEditable(false); scrollPane = new JScrollPane(outframe); frame.add(scrollPane, BorderLayout.CENTER); // 输入框 inputPanel.setLayout(new BorderLayout()); inputPanel.add(inframe, BorderLayout.CENTER); inframe.addActionListener(new inframeListener()); JButton fileButton = new JButton("选择文件"); fileButton.addActionListener(new FileButtonListener()); inputPanel.add(fileButton, BorderLayout.EAST); frame.add(inputPanel, BorderLayout.SOUTH); frame.addWindowListener(new CloseChat()); frame.setSize(600, 400); frame.setVisible(true); isWindowOpen = true; } //再次开启与对方的聊天窗口,组件不需要再设置 public void createWindow(){ // 设置窗口 frame.setTitle(friendName); frame.setLocation(350, 200); frame.setLayout(new BorderLayout()); // 输出框 frame.add(scrollPane, BorderLayout.CENTER); // 输入框 frame.add(inputPanel, BorderLayout.SOUTH); frame.setSize(600, 400); frame.setVisible(true); isWindowOpen = true; } // 监听输入框,负责发送信息 private class inframeListener implements ActionListener { public void actionPerformed(ActionEvent e) { String tempStr = inframe.getText().trim(); // 得到输入框输入的字符串 inframe.setText(""); try { //告诉服务端这是一个消息 outputToClient.writeUTF("send-message"); outputToClient.writeUTF(friendName); //消息内容 outputToClient.writeUTF(tempStr); outputToClient.flush(); //显示在自己的窗口上 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我:\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), tempStr+"\n\n", null); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } //响应按钮,负责发送文件 private class FileButtonListener implements ActionListener { public void actionPerformed(ActionEvent e){ JFileChooser fileChooser = new JFileChooser();//选择文件 fileChooser.setCurrentDirectory(new File("src/client/image")); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile();//选择好的文件 try { outputToClient.writeUTF("send-file"); //告诉服务器这是一个文件 outputToClient.writeUTF(friendName); byte[] fileBytes = Files.readAllBytes(file.toPath()); outputToClient.writeUTF(file.getName()); // 发送文件名 outputToClient.writeInt(fileBytes.length); // 发送文件长度 outputToClient.write(fileBytes); // 发送文件内容 outputToClient.flush(); //图片类型的文件需要显示 if(isImageFile(file.getName())){ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我: \n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); String imagePath = file.getPath(); showImage(imagePath); }else{ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我发送了文件: " + file.getName() + "\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } } catch (IOException e2) { e2.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } } //接收信息并展示 public void showMessage(String str) throws BadLocationException{ if(str.equals("quit")){//接收到quit说明对方关闭了聊天 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "系统消息:对方已退出聊天\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); }else{ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "对方:\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), str+"\n\n", null); } } //接收文件 public void handleFile(String fileName, int fileLength, byte[] fileBytes) throws IOException, BadLocationException{ //保存文件到本地 String savePath = "C:\\Users\\蔡乐\\Desktop\\" + fileName; Files.write(Paths.get(savePath), fileBytes); //若文件是图片,显示图片 if (isImageFile(fileName)) { outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "对方: \n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); showImage(savePath); } else outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "已接收到文件:" + fileName + "\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } //判断文件是否为图片 private boolean isImageFile(String fileName) { String extension = fileName.substring(fileName.lastIndexOf(".") + 1); return extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("bmp"); } //显示图片 private void showImage(String savePath) throws BadLocationException{ ImageIcon icon = new ImageIcon(savePath); // 创建图标,使用指定路径的图像文件 Image image = icon.getImage(); // 获取图标的图像 Image scaledImage = image.getScaledInstance(100, 100, Image.SCALE_SMOOTH); // 将图像缩放 ImageIcon scaledIcon = new ImageIcon(scaledImage); // 创建一个新的图标,使用缩放后的图像 JLabel imageLabel = new JLabel(scaledIcon); // 创建一个标签,用于显示 imageLabel.addMouseListener(new ImageClickListener(savePath)); // 点击放大图片 outframe.setCaretPosition(outframe.getDocument().getLength()); // 设置光标位置到末尾 outframe.insertComponent(imageLabel); // 图像标签添加到文本框中 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "\n\n", null); } //点击放大图片 private class ImageClickListener extends MouseAdapter { private String imagePath; public ImageClickListener(String path) { this.imagePath = path; } public void mouseClicked(MouseEvent e) { ImageIcon icon = new ImageIcon(imagePath); Image image = icon.getImage(); // 获取原始图片 int width = image.getWidth(null); // 获取原始图片宽度 int height = image.getHeight(null); // 获取原始图片高度 // 设置图片的最大宽度和高度 int maxWidth = 300; int maxHeight = 300; // 如果图片宽度或高度超过最大值,则按比例缩放 if (width > maxWidth || height > maxHeight) { if (width > height) { height = (int) (height * ((double) maxWidth / width)); width = maxWidth; } else { width = (int) (width * ((double) maxHeight / height)); height = maxHeight; } image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); } //弹出窗口展示放大图片 ImageIcon scaledIcon = new ImageIcon(image); JLabel label = new JLabel(); label.setIcon(scaledIcon); JOptionPane.showMessageDialog(null, label, "Scaled Image", JOptionPane.PLAIN_MESSAGE); } } //关闭聊天 class CloseChat extends WindowAdapter { public void windowClosing(WindowEvent e) { try { outputToClient.writeUTF("send-message"); outputToClient.writeUTF(friendName); outputToClient.writeUTF("quit"); outputToClient.flush(); isWindowOpen = false; outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "你退出了上次聊天\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } }
CLan-nad/CL
CL-javaChat/src/client/WorkChat.java
2,320
//点击放大图片
line_comment
zh-cn
package src.client; import java.nio.file.Files; import java.nio.file.Paths; import java.io.*; import java.awt.event.*; import java.awt.*; import javax.swing.*; import javax.swing.text.BadLocationException; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; //聊天功能 public class WorkChat implements Runnable{ DataOutputStream outputToClient = ClientMain.outputToServer; String friendName; JFrame frame = new JFrame(); JTextPane outframe = new JTextPane(); JTextField inframe = new JTextField(); JScrollPane scrollPane;//滚动输出框 JPanel inputPanel = new JPanel();//输入框 boolean isWindowOpen = false;//记录窗口是否打开 WorkChat(String friendName) { this.friendName = friendName; } //首次开启与对方的聊天窗口 public void run() { // 设置窗口 frame.setTitle(friendName); frame.setLocation(350, 200); frame.setLayout(new BorderLayout()); // 输出框 outframe.setEditable(false); scrollPane = new JScrollPane(outframe); frame.add(scrollPane, BorderLayout.CENTER); // 输入框 inputPanel.setLayout(new BorderLayout()); inputPanel.add(inframe, BorderLayout.CENTER); inframe.addActionListener(new inframeListener()); JButton fileButton = new JButton("选择文件"); fileButton.addActionListener(new FileButtonListener()); inputPanel.add(fileButton, BorderLayout.EAST); frame.add(inputPanel, BorderLayout.SOUTH); frame.addWindowListener(new CloseChat()); frame.setSize(600, 400); frame.setVisible(true); isWindowOpen = true; } //再次开启与对方的聊天窗口,组件不需要再设置 public void createWindow(){ // 设置窗口 frame.setTitle(friendName); frame.setLocation(350, 200); frame.setLayout(new BorderLayout()); // 输出框 frame.add(scrollPane, BorderLayout.CENTER); // 输入框 frame.add(inputPanel, BorderLayout.SOUTH); frame.setSize(600, 400); frame.setVisible(true); isWindowOpen = true; } // 监听输入框,负责发送信息 private class inframeListener implements ActionListener { public void actionPerformed(ActionEvent e) { String tempStr = inframe.getText().trim(); // 得到输入框输入的字符串 inframe.setText(""); try { //告诉服务端这是一个消息 outputToClient.writeUTF("send-message"); outputToClient.writeUTF(friendName); //消息内容 outputToClient.writeUTF(tempStr); outputToClient.flush(); //显示在自己的窗口上 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我:\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), tempStr+"\n\n", null); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } //响应按钮,负责发送文件 private class FileButtonListener implements ActionListener { public void actionPerformed(ActionEvent e){ JFileChooser fileChooser = new JFileChooser();//选择文件 fileChooser.setCurrentDirectory(new File("src/client/image")); int returnValue = fileChooser.showOpenDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile();//选择好的文件 try { outputToClient.writeUTF("send-file"); //告诉服务器这是一个文件 outputToClient.writeUTF(friendName); byte[] fileBytes = Files.readAllBytes(file.toPath()); outputToClient.writeUTF(file.getName()); // 发送文件名 outputToClient.writeInt(fileBytes.length); // 发送文件长度 outputToClient.write(fileBytes); // 发送文件内容 outputToClient.flush(); //图片类型的文件需要显示 if(isImageFile(file.getName())){ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我: \n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); String imagePath = file.getPath(); showImage(imagePath); }else{ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "我发送了文件: " + file.getName() + "\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } } catch (IOException e2) { e2.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } } //接收信息并展示 public void showMessage(String str) throws BadLocationException{ if(str.equals("quit")){//接收到quit说明对方关闭了聊天 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "系统消息:对方已退出聊天\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); }else{ outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "对方:\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), str+"\n\n", null); } } //接收文件 public void handleFile(String fileName, int fileLength, byte[] fileBytes) throws IOException, BadLocationException{ //保存文件到本地 String savePath = "C:\\Users\\蔡乐\\Desktop\\" + fileName; Files.write(Paths.get(savePath), fileBytes); //若文件是图片,显示图片 if (isImageFile(fileName)) { outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "对方: \n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); showImage(savePath); } else outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "已接收到文件:" + fileName + "\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } //判断文件是否为图片 private boolean isImageFile(String fileName) { String extension = fileName.substring(fileName.lastIndexOf(".") + 1); return extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("bmp"); } //显示图片 private void showImage(String savePath) throws BadLocationException{ ImageIcon icon = new ImageIcon(savePath); // 创建图标,使用指定路径的图像文件 Image image = icon.getImage(); // 获取图标的图像 Image scaledImage = image.getScaledInstance(100, 100, Image.SCALE_SMOOTH); // 将图像缩放 ImageIcon scaledIcon = new ImageIcon(scaledImage); // 创建一个新的图标,使用缩放后的图像 JLabel imageLabel = new JLabel(scaledIcon); // 创建一个标签,用于显示 imageLabel.addMouseListener(new ImageClickListener(savePath)); // 点击放大图片 outframe.setCaretPosition(outframe.getDocument().getLength()); // 设置光标位置到末尾 outframe.insertComponent(imageLabel); // 图像标签添加到文本框中 outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "\n\n", null); } //点击 <SUF> private class ImageClickListener extends MouseAdapter { private String imagePath; public ImageClickListener(String path) { this.imagePath = path; } public void mouseClicked(MouseEvent e) { ImageIcon icon = new ImageIcon(imagePath); Image image = icon.getImage(); // 获取原始图片 int width = image.getWidth(null); // 获取原始图片宽度 int height = image.getHeight(null); // 获取原始图片高度 // 设置图片的最大宽度和高度 int maxWidth = 300; int maxHeight = 300; // 如果图片宽度或高度超过最大值,则按比例缩放 if (width > maxWidth || height > maxHeight) { if (width > height) { height = (int) (height * ((double) maxWidth / width)); width = maxWidth; } else { width = (int) (width * ((double) maxHeight / height)); height = maxHeight; } image = image.getScaledInstance(width, height, Image.SCALE_SMOOTH); } //弹出窗口展示放大图片 ImageIcon scaledIcon = new ImageIcon(image); JLabel label = new JLabel(); label.setIcon(scaledIcon); JOptionPane.showMessageDialog(null, label, "Scaled Image", JOptionPane.PLAIN_MESSAGE); } } //关闭聊天 class CloseChat extends WindowAdapter { public void windowClosing(WindowEvent e) { try { outputToClient.writeUTF("send-message"); outputToClient.writeUTF(friendName); outputToClient.writeUTF("quit"); outputToClient.flush(); isWindowOpen = false; outframe.getStyledDocument().insertString(outframe.getStyledDocument().getLength(), "你退出了上次聊天\n\n", new SimpleAttributeSet(){{ StyleConstants.setForeground(this, Color.BLUE); }}); } catch (IOException e1) { e1.printStackTrace(); } catch (BadLocationException e1) { e1.printStackTrace(); } } } }
1
9
1
40904_4
package top.guoziyang.rpc.util; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * @author ziyang */ public class ReflectUtil { public static String getStackTrace() { StackTraceElement[] stack = new Throwable().getStackTrace(); return stack[stack.length - 1].getClassName(); } public static Set<Class<?>> getClasses(String packageName) { Set<Class<?>> classes = new LinkedHashSet<>(); boolean recursive = true; String packageDirName = packageName.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources( packageDirName); // 循环迭代下去 while (dirs.hasMoreElements()) { // 获取下一个元素 URL url = dirs.nextElement(); // 得到协议的名称 String protocol = url.getProtocol(); // 如果是以文件的形式保存在服务器上 if ("file".equals(protocol)) { // 获取包的物理路径 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); // 以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } else if ("jar".equals(protocol)) { // 如果是jar包文件 // 定义一个JarFile JarFile jar; try { // 获取jar jar = ((JarURLConnection) url.openConnection()) .getJarFile(); // 从此jar包 得到一个枚举类 Enumeration<JarEntry> entries = jar.entries(); // 同样的进行循环迭代 while (entries.hasMoreElements()) { // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries.nextElement(); String name = entry.getName(); // 如果是以/开头的 if (name.charAt(0) == '/') { // 获取后面的字符串 name = name.substring(1); } // 如果前半部分和定义的包名相同 if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); // 如果以"/"结尾 是一个包 if (idx != -1) { // 获取包名 把"/"替换成"." packageName = name.substring(0, idx) .replace('/', '.'); } // 如果可以迭代下去 并且是一个包 if ((idx != -1) || recursive) { // 如果是一个.class文件 而且不是目录 if (name.endsWith(".class") && !entry.isDirectory()) { // 去掉后面的".class" 获取真正的类名 String className = name.substring( packageName.length() + 1, name .length() - 6); try { // 添加到classes classes.add(Class .forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log // .error("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } } } catch (IOException e) { // log.error("在扫描用户定义视图时从jar包获取文件出错"); e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } return classes; } private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes) { // 获取此包的目录 建立一个File File dir = new File(packagePath); // 如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { // log.warn("用户定义包名 " + packageName + " 下没有任何文件"); return; } // 如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); // 循环所有文件 for (File file : dirfiles) { // 如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { // 如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { // 添加到集合中去 //classes.add(Class.forName(packageName + '.' + className)); //经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净 classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log.error("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } }
CN-GuoZiyang/My-RPC-Framework
rpc-common/src/main/java/top/guoziyang/rpc/util/ReflectUtil.java
1,282
// 如果是以文件的形式保存在服务器上
line_comment
zh-cn
package top.guoziyang.rpc.util; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.net.URLDecoder; import java.util.Enumeration; import java.util.LinkedHashSet; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * @author ziyang */ public class ReflectUtil { public static String getStackTrace() { StackTraceElement[] stack = new Throwable().getStackTrace(); return stack[stack.length - 1].getClassName(); } public static Set<Class<?>> getClasses(String packageName) { Set<Class<?>> classes = new LinkedHashSet<>(); boolean recursive = true; String packageDirName = packageName.replace('.', '/'); Enumeration<URL> dirs; try { dirs = Thread.currentThread().getContextClassLoader().getResources( packageDirName); // 循环迭代下去 while (dirs.hasMoreElements()) { // 获取下一个元素 URL url = dirs.nextElement(); // 得到协议的名称 String protocol = url.getProtocol(); // 如果 <SUF> if ("file".equals(protocol)) { // 获取包的物理路径 String filePath = URLDecoder.decode(url.getFile(), "UTF-8"); // 以文件的方式扫描整个包下的文件 并添加到集合中 findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes); } else if ("jar".equals(protocol)) { // 如果是jar包文件 // 定义一个JarFile JarFile jar; try { // 获取jar jar = ((JarURLConnection) url.openConnection()) .getJarFile(); // 从此jar包 得到一个枚举类 Enumeration<JarEntry> entries = jar.entries(); // 同样的进行循环迭代 while (entries.hasMoreElements()) { // 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件 JarEntry entry = entries.nextElement(); String name = entry.getName(); // 如果是以/开头的 if (name.charAt(0) == '/') { // 获取后面的字符串 name = name.substring(1); } // 如果前半部分和定义的包名相同 if (name.startsWith(packageDirName)) { int idx = name.lastIndexOf('/'); // 如果以"/"结尾 是一个包 if (idx != -1) { // 获取包名 把"/"替换成"." packageName = name.substring(0, idx) .replace('/', '.'); } // 如果可以迭代下去 并且是一个包 if ((idx != -1) || recursive) { // 如果是一个.class文件 而且不是目录 if (name.endsWith(".class") && !entry.isDirectory()) { // 去掉后面的".class" 获取真正的类名 String className = name.substring( packageName.length() + 1, name .length() - 6); try { // 添加到classes classes.add(Class .forName(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log // .error("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } } } catch (IOException e) { // log.error("在扫描用户定义视图时从jar包获取文件出错"); e.printStackTrace(); } } } } catch (IOException e) { e.printStackTrace(); } return classes; } private static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive, Set<Class<?>> classes) { // 获取此包的目录 建立一个File File dir = new File(packagePath); // 如果不存在或者 也不是目录就直接返回 if (!dir.exists() || !dir.isDirectory()) { // log.warn("用户定义包名 " + packageName + " 下没有任何文件"); return; } // 如果存在 就获取包下的所有文件 包括目录 File[] dirfiles = dir.listFiles(new FileFilter() { // 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件) public boolean accept(File file) { return (recursive && file.isDirectory()) || (file.getName().endsWith(".class")); } }); // 循环所有文件 for (File file : dirfiles) { // 如果是目录 则继续扫描 if (file.isDirectory()) { findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, classes); } else { // 如果是java类文件 去掉后面的.class 只留下类名 String className = file.getName().substring(0, file.getName().length() - 6); try { // 添加到集合中去 //classes.add(Class.forName(packageName + '.' + className)); //经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净 classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className)); } catch (ClassNotFoundException e) { // log.error("添加用户自定义视图类错误 找不到此类的.class文件"); e.printStackTrace(); } } } } }
1
19
1
20613_3
import android.media.MediaPlayer; import com.mandala.Exception.MediaPlayerProxyException; import java.util.ArrayList; import java.util.List; /** * 播放语音代理类 * 理论上这个类可以做下载,先获得文件后,再播放本地文件,减少流量使用 * 不做了 * Created by W_Q on 13-10-14. */ public class MediaPlayerProxy { private MediaPlayer player; private static MediaPlayerProxy proxy = new MediaPlayerProxy(); private List<PlayState> list; //单纯的播放动画集合 private PlayState mState; //正在播放的 private String mPlayPath; private String TAG = getClass().getSimpleName(); private PlayLengthListener playLengthListener; //播放时长监听器 private boolean isNew; //用于注销时长监听 private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if (MediaPlayerProxy.this.playLengthListener != null) { MediaPlayerProxy.this.playLengthListener.currentLength(player.getCurrentPosition()); sendEmptyMessageDelayed(0,1000); }else{ return; } } }; private MediaPlayerProxy(){ player = new MediaPlayer(); list = new ArrayList<PlayState>(); player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { player.start(); //准备结束后,开始播放 if (mState!=null){ mState.play(); MLog.e(TAG,"mState.play()"); } if (playLengthListener!=null){ handler.sendEmptyMessageDelayed(0,1000); } } }); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { player.stop();//播放结束 player.reset(); mPlayPath = null; playLengthListener = null; if (mState!=null){ mState.stop(); mState.setState(PlayState.NORMAL); } } }); } /** * 获得播放代理 * @return */ public static MediaPlayerProxy getProxy(){ return proxy; } /** * 仅仅在布局复用的时候调用 * @param mState * @param listener */ public void setPlayState(PlayState mState,PlayLengthListener listener){ this.mState = mState; this.playLengthListener = listener; } /** * 带有时长监听的播放 * @param state * @param listener * @param path * @return */ public boolean play(PlayState state,PlayLengthListener listener,String path){ this.playLengthListener = listener; isNew = true; return play(state, path); } /** * 播放(停止)语音 * @param state 播放对象接口 * @param path 播放路径 */ public boolean play(PlayState state,String path){ this.mState = state; mPlayPath = path; PlayState current = null; if (isNew){ isNew = false; }else { playLengthListener = null; } for (PlayState s:list){ if (s.getState() == PlayState.PLAY){ current = s; break; } } if (current!=null){ stop(); current.stop(); current.setState(PlayState.NORMAL);//停止后,再 if (current.equals(state))//再次点击还是自己,说明是想停止播放 return true; } boolean err = false; try { play(path); //实际播放 } catch (MediaPlayerProxyException e) { e.printStackTrace(); err = true; }finally { if (err){ //播放失败,调用停止播放的接口 state.setState(PlayState.NORMAL); state.stop(); return false; }else{ //设置播放状态 // list.add(state); state.setState(PlayState.PLAY); return true; } } } /** * 实际播放的方法 * @param path */ private void play(String path) throws MediaPlayerProxyException { boolean err = false; try { if (path == null||path.equals("")){ throw new MediaPlayerProxyException("路径有问题"); } MLog.i(TAG,"想要播放的音频路径"+path); player.setDataSource(path); } catch (Exception e) { err = true; //e.printStackTrace(); }finally { if (err){ player.reset(); try { player.setDataSource(path); } catch (Exception e) { //e.printStackTrace(); throw new MediaPlayerProxyException("路径有问题"); } } } player.prepareAsync(); //异步的准备 } /** * 这个路径是否正在播放 * @param path * @return */ public boolean isPlay(String path){ if (mState == null || mPlayPath == null || !mPlayPath.equals(path+"")){ return false; } if (mPlayPath.equals(path+"")){ // return mState.getState() == PlayState.PLAY; return true; } return false; } /** * 实际的停止方法 */ private void stop(){ player.reset(); } /** * 强制停止方法,用于界面跳转,或特殊场景 */ public void forceStop(){ PlayState mState = null; for (PlayState s:list){ if (s.getState() == PlayState.PLAY){ mState = s; break; } } if (mState!=null){ // 强制停止实现 stop(); mState.stop(); mPlayPath = null; playLengthListener = null; mState.setState(PlayState.NORMAL); } } /** * 添加后才可以播放,需要避免重复添加 * @param state */ public void add(PlayState state){ if (!list.contains(state)) list.add(state); } public void clear(){ list.clear(); } public interface PlayState{ /** * 播放 */ public static final int PLAY = 1; /** * 未播放 */ public static final int NORMAL = 0; /** * 这个方法为了停止动画 */ void stop(); /** * 这个方法为了开启动画 */ void play(); /** * 获取当前item的播放状态 * @return */ int getState(); /** * 设置播放状态 * @param state */ void setState(int state); } public interface PlayLengthListener{ /** * 当前播放到的时长 * @param time */ void currentLength(int time); } public List<PlayState> getList(){ return this.list; } }
CN-fox/MediaPlayerProxy
MediaPlayerProxy.java
1,623
//播放时长监听器
line_comment
zh-cn
import android.media.MediaPlayer; import com.mandala.Exception.MediaPlayerProxyException; import java.util.ArrayList; import java.util.List; /** * 播放语音代理类 * 理论上这个类可以做下载,先获得文件后,再播放本地文件,减少流量使用 * 不做了 * Created by W_Q on 13-10-14. */ public class MediaPlayerProxy { private MediaPlayer player; private static MediaPlayerProxy proxy = new MediaPlayerProxy(); private List<PlayState> list; //单纯的播放动画集合 private PlayState mState; //正在播放的 private String mPlayPath; private String TAG = getClass().getSimpleName(); private PlayLengthListener playLengthListener; //播放 <SUF> private boolean isNew; //用于注销时长监听 private Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { if (MediaPlayerProxy.this.playLengthListener != null) { MediaPlayerProxy.this.playLengthListener.currentLength(player.getCurrentPosition()); sendEmptyMessageDelayed(0,1000); }else{ return; } } }; private MediaPlayerProxy(){ player = new MediaPlayer(); list = new ArrayList<PlayState>(); player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { player.start(); //准备结束后,开始播放 if (mState!=null){ mState.play(); MLog.e(TAG,"mState.play()"); } if (playLengthListener!=null){ handler.sendEmptyMessageDelayed(0,1000); } } }); player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { player.stop();//播放结束 player.reset(); mPlayPath = null; playLengthListener = null; if (mState!=null){ mState.stop(); mState.setState(PlayState.NORMAL); } } }); } /** * 获得播放代理 * @return */ public static MediaPlayerProxy getProxy(){ return proxy; } /** * 仅仅在布局复用的时候调用 * @param mState * @param listener */ public void setPlayState(PlayState mState,PlayLengthListener listener){ this.mState = mState; this.playLengthListener = listener; } /** * 带有时长监听的播放 * @param state * @param listener * @param path * @return */ public boolean play(PlayState state,PlayLengthListener listener,String path){ this.playLengthListener = listener; isNew = true; return play(state, path); } /** * 播放(停止)语音 * @param state 播放对象接口 * @param path 播放路径 */ public boolean play(PlayState state,String path){ this.mState = state; mPlayPath = path; PlayState current = null; if (isNew){ isNew = false; }else { playLengthListener = null; } for (PlayState s:list){ if (s.getState() == PlayState.PLAY){ current = s; break; } } if (current!=null){ stop(); current.stop(); current.setState(PlayState.NORMAL);//停止后,再 if (current.equals(state))//再次点击还是自己,说明是想停止播放 return true; } boolean err = false; try { play(path); //实际播放 } catch (MediaPlayerProxyException e) { e.printStackTrace(); err = true; }finally { if (err){ //播放失败,调用停止播放的接口 state.setState(PlayState.NORMAL); state.stop(); return false; }else{ //设置播放状态 // list.add(state); state.setState(PlayState.PLAY); return true; } } } /** * 实际播放的方法 * @param path */ private void play(String path) throws MediaPlayerProxyException { boolean err = false; try { if (path == null||path.equals("")){ throw new MediaPlayerProxyException("路径有问题"); } MLog.i(TAG,"想要播放的音频路径"+path); player.setDataSource(path); } catch (Exception e) { err = true; //e.printStackTrace(); }finally { if (err){ player.reset(); try { player.setDataSource(path); } catch (Exception e) { //e.printStackTrace(); throw new MediaPlayerProxyException("路径有问题"); } } } player.prepareAsync(); //异步的准备 } /** * 这个路径是否正在播放 * @param path * @return */ public boolean isPlay(String path){ if (mState == null || mPlayPath == null || !mPlayPath.equals(path+"")){ return false; } if (mPlayPath.equals(path+"")){ // return mState.getState() == PlayState.PLAY; return true; } return false; } /** * 实际的停止方法 */ private void stop(){ player.reset(); } /** * 强制停止方法,用于界面跳转,或特殊场景 */ public void forceStop(){ PlayState mState = null; for (PlayState s:list){ if (s.getState() == PlayState.PLAY){ mState = s; break; } } if (mState!=null){ // 强制停止实现 stop(); mState.stop(); mPlayPath = null; playLengthListener = null; mState.setState(PlayState.NORMAL); } } /** * 添加后才可以播放,需要避免重复添加 * @param state */ public void add(PlayState state){ if (!list.contains(state)) list.add(state); } public void clear(){ list.clear(); } public interface PlayState{ /** * 播放 */ public static final int PLAY = 1; /** * 未播放 */ public static final int NORMAL = 0; /** * 这个方法为了停止动画 */ void stop(); /** * 这个方法为了开启动画 */ void play(); /** * 获取当前item的播放状态 * @return */ int getState(); /** * 设置播放状态 * @param state */ void setState(int state); } public interface PlayLengthListener{ /** * 当前播放到的时长 * @param time */ void currentLength(int time); } public List<PlayState> getList(){ return this.list; } }
1
10
1
58995_1
package ape.alarm.entity.transmission; import ape.alarm.entity.common.HasComCode; import ape.master.entity.code.ComCode; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.bklab.quark.util.json.GsonJsonObjectUtil; import org.slf4j.LoggerFactory; import java.time.LocalDateTime; import java.util.*; public class AlarmContact implements HasComCode<AlarmContact> { /** * 联系人ID */ private int id = -1; /** * 机构代码。AAAAAAAA 代表适用于全国。 */ private ComCode comCode; /** * 联系人名称 */ private String name; /** * PICC账号 */ private String account; /** * 联络渠道 JSON OBJECT 格式: <br/> * { <br/> * "邮件": ["[email protected]"], <br/> * "手机": ["13012345678", "19920212022"], <br/> * "微信": ["wechat_id_1", "wechat_id_2"], <br/> * "工单": ["work_sheet_id_1", "work_sheet_id_2"] <br/> * } <br/> */ private JsonObject channel = new JsonObject(); /** * 1=启用 0=禁用 */ private boolean effective = true; /** * 更新时间 */ private LocalDateTime updateTime; public AlarmContact() { } public String getChannelJson() { return Optional.ofNullable(channel).map(JsonObject::toString).orElse("{}"); } public List<String> getChannels(AlarmContactChannelTypeEnum channelEnum) { return getChannels(channelEnum.name()); } public String getFirstChannel(AlarmContactChannelTypeEnum channelEnum) { List<String> channels = getChannels(channelEnum); return channels == null || channels.isEmpty() ? null : channels.get(0); } public List<String> getChannels(String channelTypeName) { List<String> list = new ArrayList<>(); getChannelArray(channelTypeName).forEach(jsonElement -> { try { list.add(jsonElement.getAsString()); } catch (Exception ignore) { } }); return list; } public JsonArray getChannelArray(String channelTypeName) { JsonObject channel = getChannel(); try { if (!channel.has(channelTypeName) || !channel.get(channelTypeName).isJsonArray()) { channel.add(channelTypeName, new JsonArray()); } return channel.getAsJsonArray(channelTypeName); } catch (Exception e) { JsonArray array = new JsonArray(); channel.add(channelTypeName, array); return array; } } public AlarmContact addChannels(AlarmContactChannelTypeEnum channelType, String... address) { JsonArray array = getChannelArray(channelType.name()); for (String s : address) { array.add(s); } return this; } public AlarmContact setChannels(AlarmContactChannelTypeEnum channelType, Collection<String> address) { channel.add(channelType.name(), address.stream().collect(JsonArray::new, JsonArray::add, (a, b) -> b.forEach(a::add))); return this; } public int getId() { return id; } public AlarmContact setId(int id) { this.id = id; return this; } public ComCode getComCode() { return comCode; } public AlarmContact setComCode(ComCode comCode) { this.comCode = comCode; return this; } public String getName() { return name; } public AlarmContact setName(String name) { this.name = name; return this; } public String getAccount() { return account; } public AlarmContact setAccount(String account) { this.account = account; return this; } public JsonObject getChannel() { if (channel == null) channel = new JsonObject(); return channel; } public AlarmContact setChannel(String channel) { try { this.channel = new Gson().fromJson(channel, JsonObject.class); } catch (Exception e) { LoggerFactory.getLogger(getClass()).info(id + " channel value "); this.channel = new JsonObject(); } return this; } public AlarmContact setChannel(JsonObject channel) { this.channel = channel; return this; } public boolean isEffective() { return effective; } public AlarmContact setEffective(boolean effective) { this.effective = effective; return this; } public AlarmContact invertEffective() { this.effective = !this.effective; return this; } public LocalDateTime getUpdateTime() { return updateTime; } public AlarmContact setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AlarmContact that = (AlarmContact) o; return id >= 0 && id == that.id; } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return new GsonJsonObjectUtil(this).pretty(); } }
CNBroderick/picc-alarm-service
src/main/java/ape/alarm/entity/transmission/AlarmContact.java
1,268
/** * 机构代码。AAAAAAAA 代表适用于全国。 */
block_comment
zh-cn
package ape.alarm.entity.transmission; import ape.alarm.entity.common.HasComCode; import ape.master.entity.code.ComCode; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import org.bklab.quark.util.json.GsonJsonObjectUtil; import org.slf4j.LoggerFactory; import java.time.LocalDateTime; import java.util.*; public class AlarmContact implements HasComCode<AlarmContact> { /** * 联系人ID */ private int id = -1; /** * 机构代 <SUF>*/ private ComCode comCode; /** * 联系人名称 */ private String name; /** * PICC账号 */ private String account; /** * 联络渠道 JSON OBJECT 格式: <br/> * { <br/> * "邮件": ["[email protected]"], <br/> * "手机": ["13012345678", "19920212022"], <br/> * "微信": ["wechat_id_1", "wechat_id_2"], <br/> * "工单": ["work_sheet_id_1", "work_sheet_id_2"] <br/> * } <br/> */ private JsonObject channel = new JsonObject(); /** * 1=启用 0=禁用 */ private boolean effective = true; /** * 更新时间 */ private LocalDateTime updateTime; public AlarmContact() { } public String getChannelJson() { return Optional.ofNullable(channel).map(JsonObject::toString).orElse("{}"); } public List<String> getChannels(AlarmContactChannelTypeEnum channelEnum) { return getChannels(channelEnum.name()); } public String getFirstChannel(AlarmContactChannelTypeEnum channelEnum) { List<String> channels = getChannels(channelEnum); return channels == null || channels.isEmpty() ? null : channels.get(0); } public List<String> getChannels(String channelTypeName) { List<String> list = new ArrayList<>(); getChannelArray(channelTypeName).forEach(jsonElement -> { try { list.add(jsonElement.getAsString()); } catch (Exception ignore) { } }); return list; } public JsonArray getChannelArray(String channelTypeName) { JsonObject channel = getChannel(); try { if (!channel.has(channelTypeName) || !channel.get(channelTypeName).isJsonArray()) { channel.add(channelTypeName, new JsonArray()); } return channel.getAsJsonArray(channelTypeName); } catch (Exception e) { JsonArray array = new JsonArray(); channel.add(channelTypeName, array); return array; } } public AlarmContact addChannels(AlarmContactChannelTypeEnum channelType, String... address) { JsonArray array = getChannelArray(channelType.name()); for (String s : address) { array.add(s); } return this; } public AlarmContact setChannels(AlarmContactChannelTypeEnum channelType, Collection<String> address) { channel.add(channelType.name(), address.stream().collect(JsonArray::new, JsonArray::add, (a, b) -> b.forEach(a::add))); return this; } public int getId() { return id; } public AlarmContact setId(int id) { this.id = id; return this; } public ComCode getComCode() { return comCode; } public AlarmContact setComCode(ComCode comCode) { this.comCode = comCode; return this; } public String getName() { return name; } public AlarmContact setName(String name) { this.name = name; return this; } public String getAccount() { return account; } public AlarmContact setAccount(String account) { this.account = account; return this; } public JsonObject getChannel() { if (channel == null) channel = new JsonObject(); return channel; } public AlarmContact setChannel(String channel) { try { this.channel = new Gson().fromJson(channel, JsonObject.class); } catch (Exception e) { LoggerFactory.getLogger(getClass()).info(id + " channel value "); this.channel = new JsonObject(); } return this; } public AlarmContact setChannel(JsonObject channel) { this.channel = channel; return this; } public boolean isEffective() { return effective; } public AlarmContact setEffective(boolean effective) { this.effective = effective; return this; } public AlarmContact invertEffective() { this.effective = !this.effective; return this; } public LocalDateTime getUpdateTime() { return updateTime; } public AlarmContact setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AlarmContact that = (AlarmContact) o; return id >= 0 && id == that.id; } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return new GsonJsonObjectUtil(this).pretty(); } }
0
41
0
53194_30
package HW4; import HW2.Part3.Cal; import java.awt.*; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.temporal.TemporalField; import java.util.Arrays; import java.util.Calendar; import java.util.Date; /** * @Description * @Author: liuXuyang * @studentNo 15130110024 * @Emailaddress [email protected] * @Date: 2018/4/9 16:21 */ public class CalendarUtil { /** * 以下是15年的阴历信息 * 每年总共有5个15位 总计20个bits * 用0x04bd8举例: * 最后四位,即8代表改年闰月的月份,为0则没有闰月 * 前四位,即0,只有当改年有闰年的时候才有意义,即0表示闰月29天,1表示闰月30天 * 中间呢2位,代表每个月的天数 * * 阳历的1900年1月31日是阴历的1900年的正月初一 */ public static final int MIN_YEAR = 1900; //最小年份 public static final int MAX_YEAR = 2049; //最大年份 public static final String STARTOFDATE = "19000130"; public static boolean isLeapYear; public static final String CHINESENAME[] = { "初一","初二","初三","初四","初五","初六","初七","初八","初九","初十" ,"十一","十二","十三","十四","十五","十六","十七","十八","十九","二十" ,"二十一","二十二","二十三","二十四","二十五","二十六","二十七","二十八" ,"二十九","三十" }; public static final String[] MONTHNAME={ "正月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","腊月" }; public final static int[] LUNAR_INFO = { 0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2, 0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977, 0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970, 0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950, 0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557, 0x06ca0,0x0b550,0x15355,0x04da0,0x0a5d0,0x14573,0x052d0,0x0a9a8,0x0e950,0x06aa0, 0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0, 0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b5a0,0x195a6, 0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570, 0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x055c0,0x0ab60,0x096d5,0x092e0, 0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5, 0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930, 0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530, 0x05aa0,0x076a3,0x096d0,0x04bd7,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45, 0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0 }; //平年每个月的天数 public final static int[] DAYS = { 31,28,31,30,31,30,31,31,30,31,30,31 }; /** * 获得该年的月份 * @param calendar * @return */ public static int getMonthOfYear(Calendar calendar) { return calendar.get(Calendar.MONTH); } /** * 获得当前年份 * @param calendar * @return */ public static int getYear(Calendar calendar) { return calendar.get(Calendar.YEAR); } /** * 根据阳历获得阴历 * @param solarDate * @return * @throws Exception */ public static String solarToLunar(String solarDate) { int i; int temp = 0; int lunarYear; int lunarMonth; //农历月份 int lunarDay; //农历当月第几天 boolean leapMonthFlag =false; SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); Date myDate = null; Date startDate = null; try { myDate = formatter.parse(solarDate); startDate = formatter.parse(STARTOFDATE); } catch (ParseException e) { e.printStackTrace(); } int offset = daysBetween(startDate,myDate); for (i = MIN_YEAR; i <= MAX_YEAR; i++){ temp = getYearDays(i); //求当年农历年天数 if (offset - temp < 1){ break; }else{ offset -= temp; } } lunarYear = i; int leapMonth = getLeapMonth(lunarYear);//计算该年闰哪个月 //设定当年是否有闰月 if (leapMonth > 0){ isLeapYear = true; }else{ isLeapYear = false; } for (i = 1; i<=12; i++) { if(i==leapMonth+1 && isLeapYear){ temp = getLeapMonthDays(lunarYear); isLeapYear = false; leapMonthFlag = true; i--; }else{ temp = getMonthDays(lunarYear, i); } offset -= temp; if(offset<=0){ break; } } offset += temp; lunarMonth = i; lunarDay = offset; //"阴历:"+lunarYear+"年"+(leapMonthFlag&(lunarMonth==leapMonth)?"闰":"")+ return MONTHNAME[lunarMonth-1]+CHINESENAME[lunarDay-1]; } /** * 计算两个阳历日期相差的天数。 * @param startDate 开始时间 * @param endDate 截至时间 * @return (int)天数 * @author liu 2017-3-2 */ private static int daysBetween(Date startDate, Date endDate) { int days = 0; //将转换的两个时间对象转换成Calendar对象 Calendar can1 = Calendar.getInstance(); can1.setTime(startDate); Calendar can2 = Calendar.getInstance(); can2.setTime(endDate); //拿出两个年份 int year1 = can1.get(Calendar.YEAR); int year2 = can2.get(Calendar.YEAR); //天数 Calendar can = null; //如果can1 < can2 //减去小的时间在这一年已经过了的天数 //加上大的时间已过的天数 if(can1.before(can2)){ days -= can1.get(Calendar.DAY_OF_YEAR); days += can2.get(Calendar.DAY_OF_YEAR); can = can1; }else{ days -= can2.get(Calendar.DAY_OF_YEAR); days += can1.get(Calendar.DAY_OF_YEAR); can = can2; } for (int i = 0; i < Math.abs(year2-year1); i++) { //获取小的时间当前年的总天数 days += can.getActualMaximum(Calendar.DAY_OF_YEAR); //再计算下一年。 can.add(Calendar.YEAR, 1); } return days; } /** * 计算阴历{@code lunarYeay}年{@code month}月的天数 * @param lunarYeay 阴历年 * @param month 阴历月 * @return (int)该月天数 * @throws Exception * @author liu 2015-1-5 */ private static int getMonthDays(int lunarYeay, int month) { if ((month > 31) || (month < 0)) { // throw(new Exception("月份有错!")); System.out.println("月份有错"); return -1; } // 0X0FFFF[0000 {1111 1111 1111} 1111]中间12位代表12个月,1为大月,0为小月 int bit = 1 << (16-month); if(((LUNAR_INFO[lunarYeay - 1900] & 0x0FFFF)&bit)==0){ return 29; }else { return 30; } } /** * 计算阴历{@code year}年闰月多少天 * @param year 阴历年 * @return (int)天数 * @author liu 2015-1-5 */ private static int getLeapMonthDays(int year) { if(getLeapMonth(year)!=0){ if((LUNAR_INFO[year - 1900] & 0xf0000)==0){ return 29; }else { return 30; } }else{ return 0; } } /** * 计算阴历{@code year}年闰月多少天 * @param year 阴历年 * @return (int)天数 * @author liu 2015-1-5 */ private static int getLeapMonth(int year) { return (int) (LUNAR_INFO[year - 1900] & 0xf); } /** * 计算阴历{@code year}年的总天数 * @param year 阴历年 * @return (int)总天数 * @author liu 2015-1-5 */ private static int getYearDays(int year) { int sum = 29*12; for(int i=0x8000;i>=0x8;i>>=1){ if((LUNAR_INFO[year-1900]&0xfff0&i)!=0){ sum++; } } return sum+getLeapMonthDays(year); } /** * 判断是否是闰年 * @param year * @return */ public static boolean isLeapYear(int year) { if(year%100==0) { if(year%400==0) { return true; }else { return false; } }else{ if(year%4==0) { return true; }else{ return false; } } } /** * 获得上一个月的天数 * @param calendar * @return */ public static int getDaysOfPreMonth(Calendar calendar) { int currYear = calendar.get(Calendar.YEAR); int currMonth = calendar.get(Calendar.MONTH); int countDay = 0; if (currMonth!=0&&currMonth!=11){ //判断当前年是否是闰年 if (CalendarUtil.isLeapYear(currYear)) { //是否是二月 countDay=currMonth==1?CalendarUtil.DAYS[currMonth]+1:CalendarUtil.DAYS[currMonth]; }else{ countDay = CalendarUtil.DAYS[currMonth]; } }else if (currMonth==0){ currMonth = 11; countDay = CalendarUtil.DAYS[currMonth]; }else if (currMonth==11) { currMonth = 1; countDay = CalendarUtil.DAYS[currMonth]; } return countDay; } /** * 获得下一个月的天数 * @param calendar * @return */ public static int getDaysOfNextMonth(Calendar calendar) { int currYear = calendar.get(Calendar.YEAR); int currMonth = calendar.get(Calendar.MONTH); int countDay = 0; if (currMonth!=11){ //判断当前年是否是闰年 if (CalendarUtil.isLeapYear(currYear)) { //是否是二月 countDay=currMonth==1?CalendarUtil.DAYS[currMonth]+1:CalendarUtil.DAYS[currMonth]; }else{ countDay = CalendarUtil.DAYS[currMonth]; } }else if (currMonth==11){ currMonth = 0; countDay = CalendarUtil.DAYS[currMonth]; } return countDay; } /** * 获得某月第一天是周几 * * 1 表示周末 * 2 表示周一 * @param calendar * @return */ public static int getDateOfMonth(Calendar calendar) { calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),1,0,0); return calendar.get(Calendar.DAY_OF_WEEK); } /** * 判断是否需要扩充 * 当某一月的第一天是周六,并且该月不是二月 * 或者第一天是周五,并且该月有31天 * @param calendar * @return */ public static boolean isAdapter(Calendar calendar) { int daysOfMonth = CalendarUtil.DAYS[calendar.get(Calendar.MONTH)]; int dateOfMonth = CalendarUtil.getDateOfMonth(calendar); if ((daysOfMonth>=30&&dateOfMonth==7)||(daysOfMonth==31&&dateOfMonth==6)) { return true; }else{ return false; } } /** * 将timestamp转成Date类型 */ @SuppressWarnings("all") public static Date timeStamp2Date(Timestamp timestamp) throws ParseException { String string = timestamp.toString(); String[] dateString = string.split(" "); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.parse(dateString[0]); } }
CODERDRIVER/HW
src/main/java/HW4/CalendarUtil.java
4,294
//判断当前年是否是闰年
line_comment
zh-cn
package HW4; import HW2.Part3.Cal; import java.awt.*; import java.sql.Timestamp; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.temporal.TemporalField; import java.util.Arrays; import java.util.Calendar; import java.util.Date; /** * @Description * @Author: liuXuyang * @studentNo 15130110024 * @Emailaddress [email protected] * @Date: 2018/4/9 16:21 */ public class CalendarUtil { /** * 以下是15年的阴历信息 * 每年总共有5个15位 总计20个bits * 用0x04bd8举例: * 最后四位,即8代表改年闰月的月份,为0则没有闰月 * 前四位,即0,只有当改年有闰年的时候才有意义,即0表示闰月29天,1表示闰月30天 * 中间呢2位,代表每个月的天数 * * 阳历的1900年1月31日是阴历的1900年的正月初一 */ public static final int MIN_YEAR = 1900; //最小年份 public static final int MAX_YEAR = 2049; //最大年份 public static final String STARTOFDATE = "19000130"; public static boolean isLeapYear; public static final String CHINESENAME[] = { "初一","初二","初三","初四","初五","初六","初七","初八","初九","初十" ,"十一","十二","十三","十四","十五","十六","十七","十八","十九","二十" ,"二十一","二十二","二十三","二十四","二十五","二十六","二十七","二十八" ,"二十九","三十" }; public static final String[] MONTHNAME={ "正月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","腊月" }; public final static int[] LUNAR_INFO = { 0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2, 0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977, 0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970, 0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950, 0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557, 0x06ca0,0x0b550,0x15355,0x04da0,0x0a5d0,0x14573,0x052d0,0x0a9a8,0x0e950,0x06aa0, 0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0, 0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b5a0,0x195a6, 0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570, 0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x055c0,0x0ab60,0x096d5,0x092e0, 0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5, 0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930, 0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530, 0x05aa0,0x076a3,0x096d0,0x04bd7,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45, 0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0 }; //平年每个月的天数 public final static int[] DAYS = { 31,28,31,30,31,30,31,31,30,31,30,31 }; /** * 获得该年的月份 * @param calendar * @return */ public static int getMonthOfYear(Calendar calendar) { return calendar.get(Calendar.MONTH); } /** * 获得当前年份 * @param calendar * @return */ public static int getYear(Calendar calendar) { return calendar.get(Calendar.YEAR); } /** * 根据阳历获得阴历 * @param solarDate * @return * @throws Exception */ public static String solarToLunar(String solarDate) { int i; int temp = 0; int lunarYear; int lunarMonth; //农历月份 int lunarDay; //农历当月第几天 boolean leapMonthFlag =false; SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd"); Date myDate = null; Date startDate = null; try { myDate = formatter.parse(solarDate); startDate = formatter.parse(STARTOFDATE); } catch (ParseException e) { e.printStackTrace(); } int offset = daysBetween(startDate,myDate); for (i = MIN_YEAR; i <= MAX_YEAR; i++){ temp = getYearDays(i); //求当年农历年天数 if (offset - temp < 1){ break; }else{ offset -= temp; } } lunarYear = i; int leapMonth = getLeapMonth(lunarYear);//计算该年闰哪个月 //设定当年是否有闰月 if (leapMonth > 0){ isLeapYear = true; }else{ isLeapYear = false; } for (i = 1; i<=12; i++) { if(i==leapMonth+1 && isLeapYear){ temp = getLeapMonthDays(lunarYear); isLeapYear = false; leapMonthFlag = true; i--; }else{ temp = getMonthDays(lunarYear, i); } offset -= temp; if(offset<=0){ break; } } offset += temp; lunarMonth = i; lunarDay = offset; //"阴历:"+lunarYear+"年"+(leapMonthFlag&(lunarMonth==leapMonth)?"闰":"")+ return MONTHNAME[lunarMonth-1]+CHINESENAME[lunarDay-1]; } /** * 计算两个阳历日期相差的天数。 * @param startDate 开始时间 * @param endDate 截至时间 * @return (int)天数 * @author liu 2017-3-2 */ private static int daysBetween(Date startDate, Date endDate) { int days = 0; //将转换的两个时间对象转换成Calendar对象 Calendar can1 = Calendar.getInstance(); can1.setTime(startDate); Calendar can2 = Calendar.getInstance(); can2.setTime(endDate); //拿出两个年份 int year1 = can1.get(Calendar.YEAR); int year2 = can2.get(Calendar.YEAR); //天数 Calendar can = null; //如果can1 < can2 //减去小的时间在这一年已经过了的天数 //加上大的时间已过的天数 if(can1.before(can2)){ days -= can1.get(Calendar.DAY_OF_YEAR); days += can2.get(Calendar.DAY_OF_YEAR); can = can1; }else{ days -= can2.get(Calendar.DAY_OF_YEAR); days += can1.get(Calendar.DAY_OF_YEAR); can = can2; } for (int i = 0; i < Math.abs(year2-year1); i++) { //获取小的时间当前年的总天数 days += can.getActualMaximum(Calendar.DAY_OF_YEAR); //再计算下一年。 can.add(Calendar.YEAR, 1); } return days; } /** * 计算阴历{@code lunarYeay}年{@code month}月的天数 * @param lunarYeay 阴历年 * @param month 阴历月 * @return (int)该月天数 * @throws Exception * @author liu 2015-1-5 */ private static int getMonthDays(int lunarYeay, int month) { if ((month > 31) || (month < 0)) { // throw(new Exception("月份有错!")); System.out.println("月份有错"); return -1; } // 0X0FFFF[0000 {1111 1111 1111} 1111]中间12位代表12个月,1为大月,0为小月 int bit = 1 << (16-month); if(((LUNAR_INFO[lunarYeay - 1900] & 0x0FFFF)&bit)==0){ return 29; }else { return 30; } } /** * 计算阴历{@code year}年闰月多少天 * @param year 阴历年 * @return (int)天数 * @author liu 2015-1-5 */ private static int getLeapMonthDays(int year) { if(getLeapMonth(year)!=0){ if((LUNAR_INFO[year - 1900] & 0xf0000)==0){ return 29; }else { return 30; } }else{ return 0; } } /** * 计算阴历{@code year}年闰月多少天 * @param year 阴历年 * @return (int)天数 * @author liu 2015-1-5 */ private static int getLeapMonth(int year) { return (int) (LUNAR_INFO[year - 1900] & 0xf); } /** * 计算阴历{@code year}年的总天数 * @param year 阴历年 * @return (int)总天数 * @author liu 2015-1-5 */ private static int getYearDays(int year) { int sum = 29*12; for(int i=0x8000;i>=0x8;i>>=1){ if((LUNAR_INFO[year-1900]&0xfff0&i)!=0){ sum++; } } return sum+getLeapMonthDays(year); } /** * 判断是否是闰年 * @param year * @return */ public static boolean isLeapYear(int year) { if(year%100==0) { if(year%400==0) { return true; }else { return false; } }else{ if(year%4==0) { return true; }else{ return false; } } } /** * 获得上一个月的天数 * @param calendar * @return */ public static int getDaysOfPreMonth(Calendar calendar) { int currYear = calendar.get(Calendar.YEAR); int currMonth = calendar.get(Calendar.MONTH); int countDay = 0; if (currMonth!=0&&currMonth!=11){ //判断 <SUF> if (CalendarUtil.isLeapYear(currYear)) { //是否是二月 countDay=currMonth==1?CalendarUtil.DAYS[currMonth]+1:CalendarUtil.DAYS[currMonth]; }else{ countDay = CalendarUtil.DAYS[currMonth]; } }else if (currMonth==0){ currMonth = 11; countDay = CalendarUtil.DAYS[currMonth]; }else if (currMonth==11) { currMonth = 1; countDay = CalendarUtil.DAYS[currMonth]; } return countDay; } /** * 获得下一个月的天数 * @param calendar * @return */ public static int getDaysOfNextMonth(Calendar calendar) { int currYear = calendar.get(Calendar.YEAR); int currMonth = calendar.get(Calendar.MONTH); int countDay = 0; if (currMonth!=11){ //判断当前年是否是闰年 if (CalendarUtil.isLeapYear(currYear)) { //是否是二月 countDay=currMonth==1?CalendarUtil.DAYS[currMonth]+1:CalendarUtil.DAYS[currMonth]; }else{ countDay = CalendarUtil.DAYS[currMonth]; } }else if (currMonth==11){ currMonth = 0; countDay = CalendarUtil.DAYS[currMonth]; } return countDay; } /** * 获得某月第一天是周几 * * 1 表示周末 * 2 表示周一 * @param calendar * @return */ public static int getDateOfMonth(Calendar calendar) { calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),1,0,0); return calendar.get(Calendar.DAY_OF_WEEK); } /** * 判断是否需要扩充 * 当某一月的第一天是周六,并且该月不是二月 * 或者第一天是周五,并且该月有31天 * @param calendar * @return */ public static boolean isAdapter(Calendar calendar) { int daysOfMonth = CalendarUtil.DAYS[calendar.get(Calendar.MONTH)]; int dateOfMonth = CalendarUtil.getDateOfMonth(calendar); if ((daysOfMonth>=30&&dateOfMonth==7)||(daysOfMonth==31&&dateOfMonth==6)) { return true; }else{ return false; } } /** * 将timestamp转成Date类型 */ @SuppressWarnings("all") public static Date timeStamp2Date(Timestamp timestamp) throws ParseException { String string = timestamp.toString(); String[] dateString = string.split(" "); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.parse(dateString[0]); } }
1
12
1
19086_6
package com.cpucode.linked.list; /** * @author : cpucode * @date : 2021/3/13 * @time : 10:37 * @github : https://github.com/CPU-Code * @csdn : https://blog.csdn.net/qq_44226094 */ public class Josephu { public static void main(String[] args) { } } /** * 创建一个环形的单向链表 */ class CircleSingleLinkedList{ /** * 创建一个first节点,当前没有编号 */ private Boy first = null; /** * 添加小孩节点,构建成一个环形的链表 * @param nums */ public void addBoy(int nums){ // nums 做一个数据校验 if (nums < 1){ System.out.println("nums的值不正确"); return; } // 辅助指针,帮助构建环形链表 Boy curBoy = null; // 使用for来创建我们的环形链表 for (int i = 1; i < nums; i++) { // 根据编号,创建小孩节点 Boy boy = new Boy(i); // 如果是第一个小孩 if (i == 1){ first = boy; // 构成环 first.setNext(first); // 让curBoy指向第一个小孩 curBoy = first; }else { curBoy.setNext(boy); boy.setNext(first); curBoy = boy; } } } /** * 遍历当前的环形链表 */ public void showBoy(){ // 如果是第一个小孩 if (first == null){ System.out.println("没有任何小孩~~"); return; } // 因为first不能动,因此我们仍然使用一个辅助指针完成遍历 Boy curBoy = first; while (true){ System.out.printf("小孩的编号 %d \\n", curBoy.getNo()); // 说明已经遍历完毕 if (curBoy.getNext() == first){ break; } // curBoy后移 curBoy = curBoy.getNext(); } } /** * 根据用户的输入,计算出小孩出圈的顺序 * @param startNo 表示从第几个小孩开始数数 * @param countNum 表示数几下 * @param nums 表示最初有多少小孩在圈中 */ public void countBoy(int startNo, int countNum, int nums){ // 先对数据进行校验 if (first == null || startNo < 1 || startNo > nums){ System.out.println("参数输入有误, 请重新输入"); return; } // 创建要给辅助指针,帮助完成小孩出圈 Boy helper = first; // 需求创建一个辅助指针(变量) helper , 事先应该指向环形链表的最后这个节点 while (true){ if (helper.getNext() == first){ break; } helper = helper.getNext(); } //小孩报数前,先让 first 和 helper 移动 k - 1次 for(int j = 0; j < startNo - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //当小孩报数时,让first 和 helper 指针同时 的移动 m - 1 次, 然后出圈 //这里是一个循环操作,知道圈中只有一个节点 while(true) { if(helper == first) { //说明圈中只有一个节点 break; } //让 first 和 helper 指针同时 的移动 countNum - 1 for(int j = 0; j < countNum - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //这时first指向的节点,就是要出圈的小孩节点 System.out.printf("小孩%d出圈\n", first.getNo()); //这时将first指向的小孩节点出圈 first = first.getNext(); helper.setNext(first); } System.out.printf("最后留在圈中的小孩编号%d \n", first.getNo()); } } /** * 创建一个Boy类,表示一个节点 */ class Boy{ /** * 编号 */ private int no; /** * 指向下一个节点,默认null */ private Boy next; public Boy(int no){ this.no = no; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public Boy getNext() { return next; } public void setNext(Boy next) { this.next = next; } @Override public String toString() { return "Boy{" + "no=" + no + '}'; } }
CPU-Code/java
data_algorithm/link_list/src/main/java/com/cpucode/linked/list/Josephu.java
1,189
// 使用for来创建我们的环形链表
line_comment
zh-cn
package com.cpucode.linked.list; /** * @author : cpucode * @date : 2021/3/13 * @time : 10:37 * @github : https://github.com/CPU-Code * @csdn : https://blog.csdn.net/qq_44226094 */ public class Josephu { public static void main(String[] args) { } } /** * 创建一个环形的单向链表 */ class CircleSingleLinkedList{ /** * 创建一个first节点,当前没有编号 */ private Boy first = null; /** * 添加小孩节点,构建成一个环形的链表 * @param nums */ public void addBoy(int nums){ // nums 做一个数据校验 if (nums < 1){ System.out.println("nums的值不正确"); return; } // 辅助指针,帮助构建环形链表 Boy curBoy = null; // 使用 <SUF> for (int i = 1; i < nums; i++) { // 根据编号,创建小孩节点 Boy boy = new Boy(i); // 如果是第一个小孩 if (i == 1){ first = boy; // 构成环 first.setNext(first); // 让curBoy指向第一个小孩 curBoy = first; }else { curBoy.setNext(boy); boy.setNext(first); curBoy = boy; } } } /** * 遍历当前的环形链表 */ public void showBoy(){ // 如果是第一个小孩 if (first == null){ System.out.println("没有任何小孩~~"); return; } // 因为first不能动,因此我们仍然使用一个辅助指针完成遍历 Boy curBoy = first; while (true){ System.out.printf("小孩的编号 %d \\n", curBoy.getNo()); // 说明已经遍历完毕 if (curBoy.getNext() == first){ break; } // curBoy后移 curBoy = curBoy.getNext(); } } /** * 根据用户的输入,计算出小孩出圈的顺序 * @param startNo 表示从第几个小孩开始数数 * @param countNum 表示数几下 * @param nums 表示最初有多少小孩在圈中 */ public void countBoy(int startNo, int countNum, int nums){ // 先对数据进行校验 if (first == null || startNo < 1 || startNo > nums){ System.out.println("参数输入有误, 请重新输入"); return; } // 创建要给辅助指针,帮助完成小孩出圈 Boy helper = first; // 需求创建一个辅助指针(变量) helper , 事先应该指向环形链表的最后这个节点 while (true){ if (helper.getNext() == first){ break; } helper = helper.getNext(); } //小孩报数前,先让 first 和 helper 移动 k - 1次 for(int j = 0; j < startNo - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //当小孩报数时,让first 和 helper 指针同时 的移动 m - 1 次, 然后出圈 //这里是一个循环操作,知道圈中只有一个节点 while(true) { if(helper == first) { //说明圈中只有一个节点 break; } //让 first 和 helper 指针同时 的移动 countNum - 1 for(int j = 0; j < countNum - 1; j++) { first = first.getNext(); helper = helper.getNext(); } //这时first指向的节点,就是要出圈的小孩节点 System.out.printf("小孩%d出圈\n", first.getNo()); //这时将first指向的小孩节点出圈 first = first.getNext(); helper.setNext(first); } System.out.printf("最后留在圈中的小孩编号%d \n", first.getNo()); } } /** * 创建一个Boy类,表示一个节点 */ class Boy{ /** * 编号 */ private int no; /** * 指向下一个节点,默认null */ private Boy next; public Boy(int no){ this.no = no; } public int getNo() { return no; } public void setNo(int no) { this.no = no; } public Boy getNext() { return next; } public void setNext(Boy next) { this.next = next; } @Override public String toString() { return "Boy{" + "no=" + no + '}'; } }
1
18
1
32519_11
package com.huoniao.oc.xunfeivoice; /** * Created by Mr PJ.Lei 2018/02/04. */ import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.huoniao.oc.MyApplication; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SynthesizerListener; /** * 语音合成的类 发音人明细http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=367 * * @author kongqw */ public class KqwSpeechCompound { // Log标签 private static final String TAG = "KqwSpeechCompound"; // 上下文 private Context mContext; // 语音合成对象 private static SpeechSynthesizer mTts; /** * 发音人 */ public final static String[] COLOUD_VOICERS_ENTRIES = {"小燕", "小宇", "凯瑟琳", "亨利", "玛丽", "小研", "小琪", "小峰", "小梅", "小莉", "小蓉", "小芸", "小坤", "小强 ", "小莹", "小新", "楠楠", "老孙",}; public final static String[] COLOUD_VOICERS_VALUE = {"xiaoyan", "xiaoyu", "catherine", "henry", "vimary", "vixy", "xiaoqi", "vixf", "xiaomei", "xiaolin", "xiaorong", "xiaoqian", "xiaokun", "xiaoqiang", "vixying", "xiaoxin", "nannan", "vils",}; /** * 构造方法 * * @param context */ public KqwSpeechCompound(Context context) { Log.d("tag54", "初始化失败,错ss 误码:" ); // 上下文 mContext = context; // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(mContext, new InitListener() { @Override public void onInit(int code) { if (code != ErrorCode.SUCCESS) { Log.d("tag54", "初始化失败,错误码:" + code); } Log.d("tag54", "初始化失败,q错误码:" + code); } }); } /** * 开始合成 * * @param text */ public void speaking(String text) { // 非空判断 if (TextUtils.isEmpty(text)) { return; } if(mTts==null){ Toast.makeText(MyApplication.mContext, "创建对象失败", Toast.LENGTH_SHORT).show(); return; } int code = mTts.startSpeaking(text, mTtsListener); Log.d("tag54","-----"+code+"++++++++++"); if (code != ErrorCode.SUCCESS) { if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) { Toast.makeText(mContext, "没有安装语音+ code = " + code, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mContext, "语音合成失败,错误码: " + code, Toast.LENGTH_SHORT).show(); } } } /* * 停止语音播报 */ public static void stopSpeaking() { // 对象非空并且正在说话 if (null != mTts && mTts.isSpeaking()) { // 停止说话 mTts.stopSpeaking(); } } /** * 判断当前有没有说话 * * @return */ public static boolean isSpeaking() { if (null != mTts) { return mTts.isSpeaking(); } else { return false; } } /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { Log.i(TAG, "开始播放"); } @Override public void onSpeakPaused() { Log.i(TAG, "暂停播放"); } @Override public void onSpeakResumed() { Log.i(TAG, "继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // TODO 缓冲的进度 Log.i(TAG, "缓冲 : " + percent); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // TODO 说话的进度 Log.i(TAG, "合成 : " + percent); } @Override public void onCompleted(SpeechError error) { if (error == null) { Log.i(TAG, "播放完成"); } else if (error != null) { Log.i(TAG, error.getPlainDescription(true)); } } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { } }; /** * 参数设置 * * @return */ private void setParam() { // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); // 引擎类型 网络 mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, COLOUD_VOICERS_VALUE[0]); // 设置语速 mTts.setParameter(SpeechConstant.SPEED, "50"); // 设置音调 mTts.setParameter(SpeechConstant.PITCH, "50"); // 设置音量 mTts.setParameter(SpeechConstant.VOLUME, "100"); // 设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE, "3"); // mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/KRobot/wavaudio.pcm"); // 背景音乐 1有 0 无 // mTts.setParameter("bgs", "1"); } }
CQ173/Android_OC_1.14
app/src/main/java/com/huoniao/oc/xunfeivoice/KqwSpeechCompound.java
1,554
/* * 停止语音播报 */
block_comment
zh-cn
package com.huoniao.oc.xunfeivoice; /** * Created by Mr PJ.Lei 2018/02/04. */ import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.huoniao.oc.MyApplication; import com.iflytek.cloud.ErrorCode; import com.iflytek.cloud.InitListener; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechError; import com.iflytek.cloud.SpeechSynthesizer; import com.iflytek.cloud.SynthesizerListener; /** * 语音合成的类 发音人明细http://bbs.xfyun.cn/forum.php?mod=viewthread&tid=367 * * @author kongqw */ public class KqwSpeechCompound { // Log标签 private static final String TAG = "KqwSpeechCompound"; // 上下文 private Context mContext; // 语音合成对象 private static SpeechSynthesizer mTts; /** * 发音人 */ public final static String[] COLOUD_VOICERS_ENTRIES = {"小燕", "小宇", "凯瑟琳", "亨利", "玛丽", "小研", "小琪", "小峰", "小梅", "小莉", "小蓉", "小芸", "小坤", "小强 ", "小莹", "小新", "楠楠", "老孙",}; public final static String[] COLOUD_VOICERS_VALUE = {"xiaoyan", "xiaoyu", "catherine", "henry", "vimary", "vixy", "xiaoqi", "vixf", "xiaomei", "xiaolin", "xiaorong", "xiaoqian", "xiaokun", "xiaoqiang", "vixying", "xiaoxin", "nannan", "vils",}; /** * 构造方法 * * @param context */ public KqwSpeechCompound(Context context) { Log.d("tag54", "初始化失败,错ss 误码:" ); // 上下文 mContext = context; // 初始化合成对象 mTts = SpeechSynthesizer.createSynthesizer(mContext, new InitListener() { @Override public void onInit(int code) { if (code != ErrorCode.SUCCESS) { Log.d("tag54", "初始化失败,错误码:" + code); } Log.d("tag54", "初始化失败,q错误码:" + code); } }); } /** * 开始合成 * * @param text */ public void speaking(String text) { // 非空判断 if (TextUtils.isEmpty(text)) { return; } if(mTts==null){ Toast.makeText(MyApplication.mContext, "创建对象失败", Toast.LENGTH_SHORT).show(); return; } int code = mTts.startSpeaking(text, mTtsListener); Log.d("tag54","-----"+code+"++++++++++"); if (code != ErrorCode.SUCCESS) { if (code == ErrorCode.ERROR_COMPONENT_NOT_INSTALLED) { Toast.makeText(mContext, "没有安装语音+ code = " + code, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(mContext, "语音合成失败,错误码: " + code, Toast.LENGTH_SHORT).show(); } } } /* * 停止语 <SUF>*/ public static void stopSpeaking() { // 对象非空并且正在说话 if (null != mTts && mTts.isSpeaking()) { // 停止说话 mTts.stopSpeaking(); } } /** * 判断当前有没有说话 * * @return */ public static boolean isSpeaking() { if (null != mTts) { return mTts.isSpeaking(); } else { return false; } } /** * 合成回调监听。 */ private SynthesizerListener mTtsListener = new SynthesizerListener() { @Override public void onSpeakBegin() { Log.i(TAG, "开始播放"); } @Override public void onSpeakPaused() { Log.i(TAG, "暂停播放"); } @Override public void onSpeakResumed() { Log.i(TAG, "继续播放"); } @Override public void onBufferProgress(int percent, int beginPos, int endPos, String info) { // TODO 缓冲的进度 Log.i(TAG, "缓冲 : " + percent); } @Override public void onSpeakProgress(int percent, int beginPos, int endPos) { // TODO 说话的进度 Log.i(TAG, "合成 : " + percent); } @Override public void onCompleted(SpeechError error) { if (error == null) { Log.i(TAG, "播放完成"); } else if (error != null) { Log.i(TAG, error.getPlainDescription(true)); } } @Override public void onEvent(int eventType, int arg1, int arg2, Bundle obj) { } }; /** * 参数设置 * * @return */ private void setParam() { // 清空参数 mTts.setParameter(SpeechConstant.PARAMS, null); // 引擎类型 网络 mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD); // 设置发音人 mTts.setParameter(SpeechConstant.VOICE_NAME, COLOUD_VOICERS_VALUE[0]); // 设置语速 mTts.setParameter(SpeechConstant.SPEED, "50"); // 设置音调 mTts.setParameter(SpeechConstant.PITCH, "50"); // 设置音量 mTts.setParameter(SpeechConstant.VOLUME, "100"); // 设置播放器音频流类型 mTts.setParameter(SpeechConstant.STREAM_TYPE, "3"); // mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, Environment.getExternalStorageDirectory() + "/KRobot/wavaudio.pcm"); // 背景音乐 1有 0 无 // mTts.setParameter("bgs", "1"); } }
1
24
1
47493_6
package search; import android.os.Bundle; import android.widget.Button; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.PagerSnapHelper; import androidx.recyclerview.widget.RecyclerView; import com.example.smartstore.R; import java.util.ArrayList; import java.util.List; //import cn.student0.manager.RepeatLayoutManager; public class search extends AppCompatActivity { private RecyclerView recyclerView; private InfiniteScrollAdapter adapter; private List<info> dataList; private Button search_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); recyclerView = findViewById(R.id.recyclerView); search_btn = findViewById(R.id.search_return_btn); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 //动态添加收纳点 *************** InfiniteScrollLayoutManager layoutManager = new InfiniteScrollLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(layoutManager); //存储某一场景下,所拥有的空间数目 dataList = new ArrayList<>(); dataList.add(new info("小女儿的房间","可可爱爱的小女儿")); dataList.add(new info("阳台","适合休息,有花有草有小鸟")); dataList.add(new info("客厅","重要的门面,一定要保持干净")); dataList.add(new info("厕所","容易滋生细菌,要定期打扫")); // 设置无限循环的项数 int infiniteItemCount = 0; adapter = new InfiniteScrollAdapter(dataList, infiniteItemCount); // 设置适配器 recyclerView.setAdapter(adapter); PagerSnapHelper snapHelper = new PagerSnapHelper(); snapHelper.attachToRecyclerView(recyclerView); //更新界面 recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 } public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 } }); //动态添加收纳点 *************** //返回主界面 *************** search_btn.setOnClickListener(v -> { InfiniteScrollAdapter.tmp.clear(); finish(); }); } public void onBackPressed(){ InfiniteScrollAdapter.tmp.clear(); finish(); } //返回主界面 *************** }
CQU-computer/SmartStore
app/src/main/java/search/search.java
705
// 设置适配器
line_comment
zh-cn
package search; import android.os.Bundle; import android.widget.Button; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.PagerSnapHelper; import androidx.recyclerview.widget.RecyclerView; import com.example.smartstore.R; import java.util.ArrayList; import java.util.List; //import cn.student0.manager.RepeatLayoutManager; public class search extends AppCompatActivity { private RecyclerView recyclerView; private InfiniteScrollAdapter adapter; private List<info> dataList; private Button search_btn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search); recyclerView = findViewById(R.id.recyclerView); search_btn = findViewById(R.id.search_return_btn); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 //动态添加收纳点 *************** InfiniteScrollLayoutManager layoutManager = new InfiniteScrollLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(layoutManager); //存储某一场景下,所拥有的空间数目 dataList = new ArrayList<>(); dataList.add(new info("小女儿的房间","可可爱爱的小女儿")); dataList.add(new info("阳台","适合休息,有花有草有小鸟")); dataList.add(new info("客厅","重要的门面,一定要保持干净")); dataList.add(new info("厕所","容易滋生细菌,要定期打扫")); // 设置无限循环的项数 int infiniteItemCount = 0; adapter = new InfiniteScrollAdapter(dataList, infiniteItemCount); // 设置 <SUF> recyclerView.setAdapter(adapter); PagerSnapHelper snapHelper = new PagerSnapHelper(); snapHelper.attachToRecyclerView(recyclerView); //更新界面 recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 } public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); recyclerView.invalidate(); // 标记View为需要重新绘制 recyclerView.requestLayout(); // 请求重新测量和布局 } }); //动态添加收纳点 *************** //返回主界面 *************** search_btn.setOnClickListener(v -> { InfiniteScrollAdapter.tmp.clear(); finish(); }); } public void onBackPressed(){ InfiniteScrollAdapter.tmp.clear(); finish(); } //返回主界面 *************** }
1
8
1
18654_2
package CR553.Pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class History { private Long id; private String ds; //日期 private Long confirm;//累计确诊 private Long confirm_add;//今日累计确诊 private Long suspect;//疑似 private Long suspect_add;//今日新增疑似 private Long heal;//治愈 private Long heal_add;//当日新增治愈 private Long dead;//死亡 private Long dead_add;//今日新增死亡 }
CR553/Project01
src/main/java/CR553/Pojo/History.java
147
//今日新增疑似
line_comment
zh-cn
package CR553.Pojo; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class History { private Long id; private String ds; //日期 private Long confirm;//累计确诊 private Long confirm_add;//今日累计确诊 private Long suspect;//疑似 private Long suspect_add;//今日 <SUF> private Long heal;//治愈 private Long heal_add;//当日新增治愈 private Long dead;//死亡 private Long dead_add;//今日新增死亡 }
1
8
1
17737_6
package util; import java.io.File; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; public class ChangeNum { private static String result=""; public static void processString(String str){ String [] res=str.split("\t"); for (String string : res) { result=result+"<td align=\"left\">"+string+"</td>\r\n"; } result+="\r\n"; } public static void main(String args[]){ try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw /* 读入TXT文件 */ String pathname = "/Users/jessexu/Documents/Myeclipse/SQLvsNOSQL/input.txt"; // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径 File filename = new File(pathname); // 要读取以上路径的input。txt文件 InputStreamReader reader = new InputStreamReader( new FileInputStream(filename)); // 建立一个输入流对象reader BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言 String line = ""; line = br.readLine(); while (line != null) { line = br.readLine(); // 一次读入一行数据 if (line!=null) { processString(line.trim()); } } /* 写入Txt文件 */ File writename = new File("/Users/jessexu/Documents/Myeclipse/SQLvsNOSQL/output.txt"); // 相对路径,如果没有则要建立一个新的output。txt文件 writename.createNewFile(); // 创建新文件 BufferedWriter out = new BufferedWriter(new FileWriter(writename)); out.write(result); // \r\n即为换行 out.flush(); // 把缓存区内容压入文件 out.close(); // 最后记得关闭文件 } catch (Exception e) { e.printStackTrace(); } } }
CSC510/SQLvsNOSQL
ChangeNum.java
511
// 一次读入一行数据
line_comment
zh-cn
package util; import java.io.File; import java.io.InputStreamReader; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileWriter; public class ChangeNum { private static String result=""; public static void processString(String str){ String [] res=str.split("\t"); for (String string : res) { result=result+"<td align=\"left\">"+string+"</td>\r\n"; } result+="\r\n"; } public static void main(String args[]){ try { // 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw /* 读入TXT文件 */ String pathname = "/Users/jessexu/Documents/Myeclipse/SQLvsNOSQL/input.txt"; // 绝对路径或相对路径都可以,这里是绝对路径,写入文件时演示相对路径 File filename = new File(pathname); // 要读取以上路径的input。txt文件 InputStreamReader reader = new InputStreamReader( new FileInputStream(filename)); // 建立一个输入流对象reader BufferedReader br = new BufferedReader(reader); // 建立一个对象,它把文件内容转成计算机能读懂的语言 String line = ""; line = br.readLine(); while (line != null) { line = br.readLine(); // 一次 <SUF> if (line!=null) { processString(line.trim()); } } /* 写入Txt文件 */ File writename = new File("/Users/jessexu/Documents/Myeclipse/SQLvsNOSQL/output.txt"); // 相对路径,如果没有则要建立一个新的output。txt文件 writename.createNewFile(); // 创建新文件 BufferedWriter out = new BufferedWriter(new FileWriter(writename)); out.write(result); // \r\n即为换行 out.flush(); // 把缓存区内容压入文件 out.close(); // 最后记得关闭文件 } catch (Exception e) { e.printStackTrace(); } } }
1
13
1
37808_45
package com.crystalneko.toneko.event; import com.crystalneko.toneko.ToNeko; import com.crystalneko.toneko.api.NekoQuery; import com.crystalneko.toneko.utils.ConfigFileUtils; import com.crystalneko.tonekocommon.Stats; import org.bukkit.NamespacedKey; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.cneko.ctlib.common.util.ChatPrefix; import java.io.File; import java.util.Objects; import java.util.Random; public class PlayerEventListenerBase implements Listener { @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { NekoQuery query = new NekoQuery(event.getPlayer().getName()); Player player = event.getPlayer(); if(query.hasOwner()) { //添加前缀 ChatPrefix.addPrivatePrefix(player.getName(), ToNeko.getMessage("other.neko")); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event){ NekoQuery query = new NekoQuery(event.getPlayer().getName()); Player player = event.getPlayer(); if(query.hasOwner()) { //删除前缀 ChatPrefix.removePrivatePrefix(player.getName(), ToNeko.getMessage("other.neko")); } } @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { File dataFile = new File( "plugins/toNeko/nekos.yml"); // 加载数据文件 YamlConfiguration data = YamlConfiguration.loadConfiguration(dataFile); // 处理玩家死亡事件的逻辑 Player player = event.getEntity(); if (player.getKiller() instanceof Player) { // 获取击杀者 Player killer = player.getKiller(); // 获取击杀者使用的物品 ItemStack itemStack = killer.getInventory().getItemInMainHand(); // 获取物品的ItemMeta对象 ItemMeta itemMeta = itemStack.getItemMeta(); //定义NBT标签 NamespacedKey key = new NamespacedKey(ToNeko.pluginInstance, "neko"); // 检查物品是否含有该自定义NBT标签 if (itemMeta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { // 读取NBT标签的值 String nbtValue = itemMeta.getPersistentDataContainer().get(key, PersistentDataType.STRING); //判断NBT是否正确 if (Objects.equals(nbtValue, "true")){ //判断玩家是否为猫娘 if(data.getString(player.getName() + ".owner") != null) { //发送死亡提示 String deathMessage = "猫娘 " + player.getName() + " 被 " + killer.getName() + " §f撅死了!"; event.setDeathMessage(deathMessage); //判断是否为主人 if(killer.getName().equals(data.getString(player.getName() + ".owner"))){ //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(7) + 3; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //减去值 int xpValue = data.getInt(player.getName() + ".xp") - randomNumber; ConfigFileUtils.setValue(player.getName() + ".xp",xpValue,dataFile); player.sendMessage(ToNeko.getMessage("death.sub-xp",new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("death.sub-xp",new String[]{player.getName(), String.valueOf(randomNumber)})); } } } } } } @EventHandler public void onPlayerAttack(EntityDamageByEntityEvent event) { try { // 检查是否是玩家被攻击 if (event.getEntity() instanceof Player player) { if (event.getDamager() instanceof Player killer) { //创建数据文件实例 File dataFile = new File("plugins/toNeko/nekos.yml"); // 加载数据文件 YamlConfiguration data = YamlConfiguration.loadConfiguration(dataFile); // 获取击杀者 // 检查击杀者手中的物品是否为空或非武器 ItemStack itemStack = killer.getInventory().getItemInMainHand(); if (!itemStack.getType().isItem()) { return; } // 获取物品的ItemMeta对象 ItemMeta itemMeta = itemStack.getItemMeta(); //定义NBT标签 NamespacedKey key = new NamespacedKey(ToNeko.pluginInstance, "neko"); NamespacedKey key2 = new NamespacedKey(ToNeko.pluginInstance, "nekolevel"); // 检查物品是否含有该自定义NBT标签 if (itemMeta != null && itemMeta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { // 读取NBT标签的值 String nbtValue = itemMeta.getPersistentDataContainer().get(key, PersistentDataType.STRING); //判断NBT是否正确 if (Objects.requireNonNull(nbtValue).equalsIgnoreCase("true")) { if (data.getString(player.getName() + ".owner") != null) { PotionEffectType effectType = PotionEffectType.WEAKNESS; // 虚弱效果的类型 int duration = 200; // 持续时间 int amplifier = 0; // 效果强度 givePlayerPotionEffect(player, effectType, duration, amplifier); //判断是否为主人 if (killer.getName().equals(data.getString(player.getName() + ".owner"))) { //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(6) - 2; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //加上值 int xpValue = data.getInt(player.getName() + ".xp") + randomNumber; ConfigFileUtils.setValue(player.getName() + ".xp", xpValue, dataFile); player.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{player.getName(), String.valueOf(randomNumber)})); } //发送撅人音效 player.getWorld().playSound(player.getLocation(), "toneko.neko.stick", 1, 1); killer.getWorld().playSound(player.getLocation(), "toneko.neko.stick", 1, 1); // 添加统计 addStatistic(player.getName(), killer.getName()); } } } else if (itemMeta != null && itemMeta.getPersistentDataContainer().has(key2, PersistentDataType.INTEGER)) { int nbtValue2 = itemMeta.getPersistentDataContainer().get(key2, PersistentDataType.INTEGER); if (nbtValue2 == 2) { PotionEffectType effectType = PotionEffectType.WEAKNESS; // 虚弱效果的类型 PotionEffectType effectType2 = PotionEffectType.BLINDNESS; //失明 PotionEffectType effectType3 = PotionEffectType.SLOW; //缓慢 PotionEffectType effectType4 = PotionEffectType.DARKNESS; //黑暗 int duration = 1000; // 持续时间 int amplifier = 3; // 效果强度 givePlayerPotionEffect(player, effectType, duration, amplifier); givePlayerPotionEffect(player, effectType2, duration, amplifier); givePlayerPotionEffect(player, effectType3, duration, amplifier); givePlayerPotionEffect(player, effectType4, duration, amplifier); //判断是否为主人 if (killer.getName().equals(data.getString(player.getName() + ".owner"))) { //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(14) + 2; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //加上值 int xpValue = data.getInt(player.getName() + ".xp") + randomNumber + 10; ConfigFileUtils.setValue(player.getName() + ".xp", xpValue, dataFile); player.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{player.getName(), String.valueOf(randomNumber)})); // 添加统计 addStatistic(player.getName(), killer.getName()); } //发送撅人音效 player.getWorld().playSound(player.getLocation(), "toneko.neko.stick.level2", 1, 1); killer.getWorld().playSound(player.getLocation(), "toneko.neko.stick.level2", 1, 1); } } } } }catch(Exception ignored){ } } // 给予玩家药水效果的方法 private void givePlayerPotionEffect(Player player, PotionEffectType type, int duration, int amplifier) { PotionEffect effect = new PotionEffect(type, duration, amplifier); player.addPotionEffect(effect); } //判断是否满足统计条件 // 这段代码目前暂无用处 /*public static Boolean isStatistic(String name, int threshold){ if (!statistics.containsKey(name)) { statistics.put(name, 1); // 如果名称不存在,则将其赋值为1 } else { int value = statistics.get(name); // 获取名称对应的值 value++; // 假设每次更新值加1 statistics.put(name, value); // 更新值 // 判断值是否达到阈值 if (value >= threshold) { statistics.remove(name); // 清除值 return true; } } return false; }*/ public void addStatistic(String neko,String player ){ Stats.stick(player,neko); } }
CSneko/toNeko
src/main/java/com/crystalneko/toneko/event/PlayerEventListenerBase.java
2,557
// 给予玩家药水效果的方法
line_comment
zh-cn
package com.crystalneko.toneko.event; import com.crystalneko.toneko.ToNeko; import com.crystalneko.toneko.api.NekoQuery; import com.crystalneko.toneko.utils.ConfigFileUtils; import com.crystalneko.tonekocommon.Stats; import org.bukkit.NamespacedKey; import org.bukkit.configuration.file.YamlConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataType; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.cneko.ctlib.common.util.ChatPrefix; import java.io.File; import java.util.Objects; import java.util.Random; public class PlayerEventListenerBase implements Listener { @EventHandler public void onPlayerJoin(PlayerJoinEvent event) { NekoQuery query = new NekoQuery(event.getPlayer().getName()); Player player = event.getPlayer(); if(query.hasOwner()) { //添加前缀 ChatPrefix.addPrivatePrefix(player.getName(), ToNeko.getMessage("other.neko")); } } @EventHandler public void onPlayerQuit(PlayerQuitEvent event){ NekoQuery query = new NekoQuery(event.getPlayer().getName()); Player player = event.getPlayer(); if(query.hasOwner()) { //删除前缀 ChatPrefix.removePrivatePrefix(player.getName(), ToNeko.getMessage("other.neko")); } } @EventHandler public void onPlayerDeath(PlayerDeathEvent event) { File dataFile = new File( "plugins/toNeko/nekos.yml"); // 加载数据文件 YamlConfiguration data = YamlConfiguration.loadConfiguration(dataFile); // 处理玩家死亡事件的逻辑 Player player = event.getEntity(); if (player.getKiller() instanceof Player) { // 获取击杀者 Player killer = player.getKiller(); // 获取击杀者使用的物品 ItemStack itemStack = killer.getInventory().getItemInMainHand(); // 获取物品的ItemMeta对象 ItemMeta itemMeta = itemStack.getItemMeta(); //定义NBT标签 NamespacedKey key = new NamespacedKey(ToNeko.pluginInstance, "neko"); // 检查物品是否含有该自定义NBT标签 if (itemMeta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { // 读取NBT标签的值 String nbtValue = itemMeta.getPersistentDataContainer().get(key, PersistentDataType.STRING); //判断NBT是否正确 if (Objects.equals(nbtValue, "true")){ //判断玩家是否为猫娘 if(data.getString(player.getName() + ".owner") != null) { //发送死亡提示 String deathMessage = "猫娘 " + player.getName() + " 被 " + killer.getName() + " §f撅死了!"; event.setDeathMessage(deathMessage); //判断是否为主人 if(killer.getName().equals(data.getString(player.getName() + ".owner"))){ //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(7) + 3; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //减去值 int xpValue = data.getInt(player.getName() + ".xp") - randomNumber; ConfigFileUtils.setValue(player.getName() + ".xp",xpValue,dataFile); player.sendMessage(ToNeko.getMessage("death.sub-xp",new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("death.sub-xp",new String[]{player.getName(), String.valueOf(randomNumber)})); } } } } } } @EventHandler public void onPlayerAttack(EntityDamageByEntityEvent event) { try { // 检查是否是玩家被攻击 if (event.getEntity() instanceof Player player) { if (event.getDamager() instanceof Player killer) { //创建数据文件实例 File dataFile = new File("plugins/toNeko/nekos.yml"); // 加载数据文件 YamlConfiguration data = YamlConfiguration.loadConfiguration(dataFile); // 获取击杀者 // 检查击杀者手中的物品是否为空或非武器 ItemStack itemStack = killer.getInventory().getItemInMainHand(); if (!itemStack.getType().isItem()) { return; } // 获取物品的ItemMeta对象 ItemMeta itemMeta = itemStack.getItemMeta(); //定义NBT标签 NamespacedKey key = new NamespacedKey(ToNeko.pluginInstance, "neko"); NamespacedKey key2 = new NamespacedKey(ToNeko.pluginInstance, "nekolevel"); // 检查物品是否含有该自定义NBT标签 if (itemMeta != null && itemMeta.getPersistentDataContainer().has(key, PersistentDataType.STRING)) { // 读取NBT标签的值 String nbtValue = itemMeta.getPersistentDataContainer().get(key, PersistentDataType.STRING); //判断NBT是否正确 if (Objects.requireNonNull(nbtValue).equalsIgnoreCase("true")) { if (data.getString(player.getName() + ".owner") != null) { PotionEffectType effectType = PotionEffectType.WEAKNESS; // 虚弱效果的类型 int duration = 200; // 持续时间 int amplifier = 0; // 效果强度 givePlayerPotionEffect(player, effectType, duration, amplifier); //判断是否为主人 if (killer.getName().equals(data.getString(player.getName() + ".owner"))) { //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(6) - 2; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //加上值 int xpValue = data.getInt(player.getName() + ".xp") + randomNumber; ConfigFileUtils.setValue(player.getName() + ".xp", xpValue, dataFile); player.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{player.getName(), String.valueOf(randomNumber)})); } //发送撅人音效 player.getWorld().playSound(player.getLocation(), "toneko.neko.stick", 1, 1); killer.getWorld().playSound(player.getLocation(), "toneko.neko.stick", 1, 1); // 添加统计 addStatistic(player.getName(), killer.getName()); } } } else if (itemMeta != null && itemMeta.getPersistentDataContainer().has(key2, PersistentDataType.INTEGER)) { int nbtValue2 = itemMeta.getPersistentDataContainer().get(key2, PersistentDataType.INTEGER); if (nbtValue2 == 2) { PotionEffectType effectType = PotionEffectType.WEAKNESS; // 虚弱效果的类型 PotionEffectType effectType2 = PotionEffectType.BLINDNESS; //失明 PotionEffectType effectType3 = PotionEffectType.SLOW; //缓慢 PotionEffectType effectType4 = PotionEffectType.DARKNESS; //黑暗 int duration = 1000; // 持续时间 int amplifier = 3; // 效果强度 givePlayerPotionEffect(player, effectType, duration, amplifier); givePlayerPotionEffect(player, effectType2, duration, amplifier); givePlayerPotionEffect(player, effectType3, duration, amplifier); givePlayerPotionEffect(player, effectType4, duration, amplifier); //判断是否为主人 if (killer.getName().equals(data.getString(player.getName() + ".owner"))) { //生成随机数 Random random = new Random(); int randomNumber = random.nextInt(14) + 2; //检查配置是否存在 ConfigFileUtils.createNewKey(player.getName() + "." + "xp", 0, data, dataFile); //加上值 int xpValue = data.getInt(player.getName() + ".xp") + randomNumber + 10; ConfigFileUtils.setValue(player.getName() + ".xp", xpValue, dataFile); player.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{killer.getName(), String.valueOf(randomNumber)})); killer.sendMessage(ToNeko.getMessage("attack.add-xp", new String[]{player.getName(), String.valueOf(randomNumber)})); // 添加统计 addStatistic(player.getName(), killer.getName()); } //发送撅人音效 player.getWorld().playSound(player.getLocation(), "toneko.neko.stick.level2", 1, 1); killer.getWorld().playSound(player.getLocation(), "toneko.neko.stick.level2", 1, 1); } } } } }catch(Exception ignored){ } } // 给予 <SUF> private void givePlayerPotionEffect(Player player, PotionEffectType type, int duration, int amplifier) { PotionEffect effect = new PotionEffect(type, duration, amplifier); player.addPotionEffect(effect); } //判断是否满足统计条件 // 这段代码目前暂无用处 /*public static Boolean isStatistic(String name, int threshold){ if (!statistics.containsKey(name)) { statistics.put(name, 1); // 如果名称不存在,则将其赋值为1 } else { int value = statistics.get(name); // 获取名称对应的值 value++; // 假设每次更新值加1 statistics.put(name, value); // 更新值 // 判断值是否达到阈值 if (value >= threshold) { statistics.remove(name); // 清除值 return true; } } return false; }*/ public void addStatistic(String neko,String player ){ Stats.stick(player,neko); } }
1
14
1
45307_1
public class BubbleSort //它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。 //走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。 //速度:O(N^2) { public static void main (String[] args) { int[]arr = {7, 3, 13, 21, 9, 16, 5, 31}; mystery(arr); for (int i = 0; i < arr.length ; ++i) { System.out.print(arr [i] + " "); } } static void mystery(int[] a) { for (int stop = a.length - 1; stop > 0; --stop) { boolean inversion = false; for (int i = 0; i < stop;++i) //通过两两左右比较,把最大的放到最后一个位置上,在stop--,找到第二大 { if (a[i] > a[i+1]) //如果前者大于后者就swap { inversion = true; int tmp = a[i]; a[i] = a[i+1]; a[i+1] = tmp; } } if (!inversion) { break; } } } }
CU2018/CS445-Data-Structure-Java
Sort/BubbleSort.java
367
//走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
line_comment
zh-cn
public class BubbleSort //它重复地走访过要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。 //走访 <SUF> //速度:O(N^2) { public static void main (String[] args) { int[]arr = {7, 3, 13, 21, 9, 16, 5, 31}; mystery(arr); for (int i = 0; i < arr.length ; ++i) { System.out.print(arr [i] + " "); } } static void mystery(int[] a) { for (int stop = a.length - 1; stop > 0; --stop) { boolean inversion = false; for (int i = 0; i < stop;++i) //通过两两左右比较,把最大的放到最后一个位置上,在stop--,找到第二大 { if (a[i] > a[i+1]) //如果前者大于后者就swap { inversion = true; int tmp = a[i]; a[i] = a[i+1]; a[i+1] = tmp; } } if (!inversion) { break; } } } }
1
39
1
28421_0
import java.util.HashSet; public class Flight { public int flight_type=1; //=1代表是国内航班, // =2代表去区域1的航程, // =3代表去区域2的航程, // =4代表去区域3的航程, // =5除上述区域的地方 public String startPosition="中国"; public String endPosition="美国"; public int seat_type=1; //=1代表头等舱, // =2代表公务舱, // =3经济舱, // =4代表明珠经济舱, // 暂时不设婴儿舱 Flight(String startPosition,String endPosition,int seat_type){ this.seat_type=seat_type; HashSet AreaSet1=new HashSet(); HashSet AreaSet2=new HashSet(); HashSet AreaSet3=new HashSet(); AreaSet1.add("日本");AreaSet1.add("美洲");AreaSet1.add("澳新");AreaSet1.add("俄罗斯");AreaSet1.add("新加坡");AreaSet1.add("迪拜"); AreaSet2.add("乌兹别克斯坦");AreaSet2.add("塔吉克斯坦");AreaSet2.add("哈萨克斯坦");AreaSet2.add("吉尔吉斯斯坦");AreaSet2.add("土库曼斯坦");AreaSet2.add("伊朗"); AreaSet2.add("巴基斯坦");AreaSet2.add("阿塞拜疆");AreaSet2.add("格鲁吉亚"); AreaSet3.add("内罗毕");AreaSet3.add("土耳其"); if(startPosition.equals("中国(除兰州/乌鲁木齐)")){ if(endPosition.equals("中国(除兰州/乌鲁木齐)")){flight_type=1;} else if(AreaSet1.contains(endPosition)){flight_type=2;} else if(AreaSet2.contains(endPosition)){flight_type=3;} else if(AreaSet3.contains(endPosition)){flight_type=4;} else flight_type=5; } } }
CUGzca/CUGSECourses
软件测试/SoftwareTest1/src/Flight.java
542
//=1代表是国内航班,
line_comment
zh-cn
import java.util.HashSet; public class Flight { public int flight_type=1; //=1 <SUF> // =2代表去区域1的航程, // =3代表去区域2的航程, // =4代表去区域3的航程, // =5除上述区域的地方 public String startPosition="中国"; public String endPosition="美国"; public int seat_type=1; //=1代表头等舱, // =2代表公务舱, // =3经济舱, // =4代表明珠经济舱, // 暂时不设婴儿舱 Flight(String startPosition,String endPosition,int seat_type){ this.seat_type=seat_type; HashSet AreaSet1=new HashSet(); HashSet AreaSet2=new HashSet(); HashSet AreaSet3=new HashSet(); AreaSet1.add("日本");AreaSet1.add("美洲");AreaSet1.add("澳新");AreaSet1.add("俄罗斯");AreaSet1.add("新加坡");AreaSet1.add("迪拜"); AreaSet2.add("乌兹别克斯坦");AreaSet2.add("塔吉克斯坦");AreaSet2.add("哈萨克斯坦");AreaSet2.add("吉尔吉斯斯坦");AreaSet2.add("土库曼斯坦");AreaSet2.add("伊朗"); AreaSet2.add("巴基斯坦");AreaSet2.add("阿塞拜疆");AreaSet2.add("格鲁吉亚"); AreaSet3.add("内罗毕");AreaSet3.add("土耳其"); if(startPosition.equals("中国(除兰州/乌鲁木齐)")){ if(endPosition.equals("中国(除兰州/乌鲁木齐)")){flight_type=1;} else if(AreaSet1.contains(endPosition)){flight_type=2;} else if(AreaSet2.contains(endPosition)){flight_type=3;} else if(AreaSet3.contains(endPosition)){flight_type=4;} else flight_type=5; } } }
1
12
1
50319_6
package binarysearch.framework.right; /** * @Classname BinarySearch1的[闭区间版] * @Description [查询右边界] * 利用[统一东部]的思想 * [裁剪]解的部分获得解的下一个位置,left-1则为[最右解],刚好right=left-1 * @Compiler CVBear * @Date 2020/7/29 9:10 */ class BinarySearch2 { /** * 闭区间版[l,r] * * @param nums * @param target * @return */ public int indexOfRight(int[] nums, int target) { // 1.[定左右] int left = 0; int right = nums.length - 1;// 修改① // 3.[定区间] while (left <= right) {// [0,r] 修改② 双指针技巧 left→逃跑 逃跑<-right // 4.[取中值] int mid = left + (right - left) / 2; // 5.[裁剪与收缩] if (nums[mid] <= target) { // 修改③ < 修改为了 <= left = mid + 1;// [裁剪]后 [mid+1,right) } else { right = mid - 1;// 边界[收缩]至[left,mid-1] } } // 2.[检越] if (right < 0 || (left >= nums.length && target != nums[right])) return -1; // 6.[返边界] return right; } }
CVBear/Easy-Programming
Leetcode/Algorithms/src/main/java/binarysearch/framework/right/BinarySearch2.java
401
// 4.[取中值]
line_comment
zh-cn
package binarysearch.framework.right; /** * @Classname BinarySearch1的[闭区间版] * @Description [查询右边界] * 利用[统一东部]的思想 * [裁剪]解的部分获得解的下一个位置,left-1则为[最右解],刚好right=left-1 * @Compiler CVBear * @Date 2020/7/29 9:10 */ class BinarySearch2 { /** * 闭区间版[l,r] * * @param nums * @param target * @return */ public int indexOfRight(int[] nums, int target) { // 1.[定左右] int left = 0; int right = nums.length - 1;// 修改① // 3.[定区间] while (left <= right) {// [0,r] 修改② 双指针技巧 left→逃跑 逃跑<-right // 4. <SUF> int mid = left + (right - left) / 2; // 5.[裁剪与收缩] if (nums[mid] <= target) { // 修改③ < 修改为了 <= left = mid + 1;// [裁剪]后 [mid+1,right) } else { right = mid - 1;// 边界[收缩]至[left,mid-1] } } // 2.[检越] if (right < 0 || (left >= nums.length && target != nums[right])) return -1; // 6.[返边界] return right; } }
0
10
0
2203_6
package com.camnter.newlife.utils.cache; import java.util.LinkedHashMap; import java.util.Map; /** * A cache that holds strong references to a limited number of values. Each time * a value is accessed, it is moved to the head of a queue. When a value is * added to a full cache, the value at the end of that queue is evicted and may * become eligible for garbage collection. * * <p>If your cached values hold resources that need to be explicitly released, * override {@link #entryRemoved}. * * <p>If a cache miss should be computed on demand for the corresponding keys, * override {@link #create}. This simplifies the calling code, allowing it to * assume a value will always be returned, even when there's a cache miss. * * <p>By default, the cache size is measured in the number of entries. Override * {@link #sizeOf} to size the cache in different units. For example, this cache * is limited to 4MiB of bitmaps: * <pre> {@code * int cacheSize = 4 * 1024 * 1024; // 4MiB * LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) { * protected int sizeOf(String key, Bitmap value) { * return value.getByteCount(); * } * }}</pre> * * <p>This class is thread-safe. Perform multiple cache operations atomically by * synchronizing on the cache: <pre> {@code * synchronized (cache) { * if (cache.get(key) == null) { * cache.put(key, value); * } * }}</pre> * * <p>This class does not allow null to be used as a key or value. A return * value of null from {@link #get}, {@link #put} or {@link #remove} is * unambiguous: the key was not in the cache. * * <p>This class appeared in Android 3.1 (Honeycomb MR1); it's available as part * of <a href="http://developer.android.com/sdk/compatibility-library.html">Android's * Support Package</a> for earlier releases. */ public class LruCache<K, V> { private final LinkedHashMap<K, V> map; /** * 缓存大小的单位。不规定元素的数量。 */ // 已经存储的数据大小 private int size; // 最大存储大小 private int maxSize; // 调用put的次数 private int putCount; // 调用create的次数 private int createCount; // 收回的次数 (如果出现) private int evictionCount; // 命中的次数(取出数据的成功次数) private int hitCount; // 丢失的次数(取出数据的丢失次数) private int missCount; /** * LruCache的构造方法:需要传入最大缓存个数 */ public LruCache(int maxSize) { // 最大缓存个数小于0,会抛出IllegalArgumentException if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } this.maxSize = maxSize; /* * 初始化LinkedHashMap * 第一个参数:initialCapacity,初始大小 * 第二个参数:loadFactor,负载因子=0.75f * 第三个参数:accessOrder=true,基于访问顺序;accessOrder=false,基于插入顺序 */ this.map = new LinkedHashMap<K, V>(0, 0.75f, true); } /** * 设置缓存的大小。 */ public void resize(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } // 防止外部多线程的情况下设置缓存大小造成的线程不安全 synchronized (this) { this.maxSize = maxSize; } // 重整数据 trimToSize(maxSize); } /** * 根据key查询缓存,如果存在于缓存或者被create方法创建了。 * 如果值返回了,那么它将被移动到双向循环链表的的尾部。 * 如果如果没有缓存的值,则返回null。 */ public final V get(K key) { if (key == null) { throw new NullPointerException("key == null"); } V mapValue; synchronized (this) { // LinkHashMap 如果设置按照访问顺序的话,这里每次get都会重整数据顺序 mapValue = map.get(key); // 计算 命中次数 if (mapValue != null) { hitCount++; return mapValue; } // 计算 丢失次数 missCount++; } /* * 官方解释: * 尝试创建一个值,这可能需要很长时间,并且Map可能在create()返回的值时有所不同。如果在create()执行的时 * 候,一个冲突的值被添加到Map,我们在Map中删除这个值,释放被创造的值。 */ V createdValue = create(key); if (createdValue == null) { return null; } /*************************** * 不覆写create方法走不到下面 * ***************************/ /* * 正常情况走不到这里 * 走到这里的话 说明 实现了自定义的 create(K key) 逻辑 * 因为默认的 create(K key) 逻辑为null */ synchronized (this) { // 记录 create 的次数 createCount++; // 将自定义create创建的值,放入LinkedHashMap中,如果key已经存在,会返回 之前相同key 的值 mapValue = map.put(key, createdValue); // 如果之前存在相同key的value,即有冲突。 if (mapValue != null) { /* * 有冲突 * 所以 撤销 刚才的 操作 * 将 之前相同key 的值 重新放回去 */ map.put(key, mapValue); } else { // 拿到键值对,计算出在容量中的相对长度,然后加上 size += safeSizeOf(key, createdValue); } } // 如果上面 判断出了 将要放入的值发生冲突 if (mapValue != null) { /* * 刚才create的值被删除了,原来的 之前相同key 的值被重新添加回去了 * 告诉 自定义 的 entryRemoved 方法 */ entryRemoved(false, key, createdValue, mapValue); return mapValue; } else { // 上面 进行了 size += 操作 所以这里要重整长度 trimToSize(maxSize); return createdValue; } } /** * 给对应key缓存value,该value将被移动到队头。 */ public final V put(K key, V value) { if (key == null || value == null) { throw new NullPointerException("key == null || value == null"); } V previous; synchronized (this) { // 记录 put 的次数 putCount++; // 拿到键值对,计算出在容量中的相对长度,然后加上 size += safeSizeOf(key, value); /* * 放入 key value * 如果 之前存在key 则返回 之前key 的value * 记录在 previous */ previous = map.put(key, value); // 如果存在冲突 if (previous != null) { // 计算出 冲突键值 在容量中的相对长度,然后减去 size -= safeSizeOf(key, previous); } } // 如果上面发生冲突 if (previous != null) { /* * previous值被剔除了,此次添加的 value 已经作为key的 新值 * 告诉 自定义 的 entryRemoved 方法 */ entryRemoved(false, key, previous, value); } trimToSize(maxSize); return previous; } /** * 删除最旧的数据直到剩余的数据的总数以下要求的大小。 */ public void trimToSize(int maxSize) { /* * 这是一个死循环, * 1.只有 扩容 的情况下能立即跳出 * 2.非扩容的情况下,map的数据会一个一个删除,直到map里没有值了,就会跳出 */ while (true) { K key; V value; synchronized (this) { // 在重新调整容量大小前,本身容量就为空的话,会出异常的。 if (size < 0 || (map.isEmpty() && size != 0)) { throw new IllegalStateException( getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } // 如果是 扩容 或者 map为空了,就会中断,因为扩容不会涉及到丢弃数据的情况 if (size <= maxSize || map.isEmpty()) { break; } Map.Entry<K, V> toEvict = map.entrySet().iterator().next(); key = toEvict.getKey(); value = toEvict.getValue(); map.remove(key); // 拿到键值对,计算出在容量中的相对长度,然后减去。 size -= safeSizeOf(key, value); // 添加一次收回次数 evictionCount++; } /* * 将最后一次删除的最少访问数据回调出去 */ entryRemoved(true, key, value, null); } } /** * 如果对应key的entry存在,则删除。 */ public final V remove(K key) { if (key == null) { throw new NullPointerException("key == null"); } V previous; synchronized (this) { // 移除对应 键值对 ,并将移除的value 存放在 previous previous = map.remove(key); if (previous != null) { // 拿到键值对,计算出在容量中的相对长度,然后减去。 size -= safeSizeOf(key, previous); } } // 如果 Map 中存在 该key ,并且成功移除了 if (previous != null) { /* * 会通知 自定义的 entryRemoved * previous 已经被删除了 */ entryRemoved(false, key, previous, null); } return previous; } /** * 1.当被回收或者删掉时调用。该方法当value被回收释放存储空间时被remove调用 * 或者替换条目值时put调用,默认实现什么都没做。 * 2.该方法没用同步调用,如果其他线程访问缓存时,该方法也会执行。 * 3.evicted=true:如果该条目被删除空间 (表示 进行了trimToSize or remove) evicted=false:put冲突后 或 get里成功create后 * 导致 * 4.newValue!=null,那么则被put()或get()调用。 */ protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) { } /** * 1.缓存丢失之后计算相应的key的value后调用。 * 返回计算后的值,如果没有value可以计算返回null。 * 默认的实现返回null。 * 2.该方法没用同步调用,如果其他线程访问缓存时,该方法也会执行。 * 3.当这个方法返回的时候,如果对应key的value存在缓存内,被创建的value将会被entryRemoved()释放或者丢弃。 * 这情况可以发生在多线程在同一时间上请求相同key(导致多个value被创建了),或者单线程中调用了put()去创建一个 * 相同key的value */ protected V create(K key) { return null; } /** * 计算 该 键值对 的相对长度 * 如果不覆写 sizeOf 实现特殊逻辑的话,默认长度是1。 */ private int safeSizeOf(K key, V value) { int result = sizeOf(key, value); if (result < 0) { throw new IllegalStateException("Negative size: " + key + "=" + value); } return result; } /** * 返回条目在用户定义单位的大小。默认实现返回1,这样的大小是条目的数量并且最大的大小是条目的最大数量。 * 一个条目的大小必须不能在缓存中改变 */ protected int sizeOf(K key, V value) { return 1; } /** * Clear the cache, calling {@link #entryRemoved} on each removed entry. * 清理缓存 */ public final void evictAll() { trimToSize(-1); // -1 will evict 0-sized elements } /** * 对于这个缓存,如果不覆写sizeOf()方法,这个方法返回的是条目的在缓存中的数量。但是对于其他缓存,返回的是 * 条目在缓存中大小的总和。 */ public synchronized final int size() { return size; } /** * 对于这个缓存,如果不覆写sizeOf()方法,这个方法返回的是条目的在缓存中的最大数量。但是对于其他缓存,返回的是 * 条目在缓存中最大大小的总和。 */ public synchronized final int maxSize() { return maxSize; } /** * Returns the number of times {@link #get} returned a value that was * already present in the cache. * 返回的次数{@link #get}这是返回一个值在缓存中已经存在。 */ public synchronized final int hitCount() { return hitCount; } /** * 返回的次数{@link #get}返回null或需要一个新的要创建价值。 */ public synchronized final int missCount() { return missCount; } /** * 返回的次数{@link #create(Object)}返回一个值。 */ public synchronized final int createCount() { return createCount; } /** * 返回put的次数。 */ public synchronized final int putCount() { return putCount; } /** * 返回被收回的value数量。 */ public synchronized final int evictionCount() { return evictionCount; } /** * 返回当前缓存内容的一个副本,从最近很少访问到最最近经常访问。 */ public synchronized final Map<K, V> snapshot() { return new LinkedHashMap<K, V>(map); } @Override public synchronized final String toString() { int accesses = hitCount + missCount; int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0; return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]", maxSize, hitCount, missCount, hitPercent); } }
CaMnter/AndroidLife
app/src/main/java/com/camnter/newlife/utils/cache/LruCache.java
3,427
// 收回的次数 (如果出现)
line_comment
zh-cn
package com.camnter.newlife.utils.cache; import java.util.LinkedHashMap; import java.util.Map; /** * A cache that holds strong references to a limited number of values. Each time * a value is accessed, it is moved to the head of a queue. When a value is * added to a full cache, the value at the end of that queue is evicted and may * become eligible for garbage collection. * * <p>If your cached values hold resources that need to be explicitly released, * override {@link #entryRemoved}. * * <p>If a cache miss should be computed on demand for the corresponding keys, * override {@link #create}. This simplifies the calling code, allowing it to * assume a value will always be returned, even when there's a cache miss. * * <p>By default, the cache size is measured in the number of entries. Override * {@link #sizeOf} to size the cache in different units. For example, this cache * is limited to 4MiB of bitmaps: * <pre> {@code * int cacheSize = 4 * 1024 * 1024; // 4MiB * LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) { * protected int sizeOf(String key, Bitmap value) { * return value.getByteCount(); * } * }}</pre> * * <p>This class is thread-safe. Perform multiple cache operations atomically by * synchronizing on the cache: <pre> {@code * synchronized (cache) { * if (cache.get(key) == null) { * cache.put(key, value); * } * }}</pre> * * <p>This class does not allow null to be used as a key or value. A return * value of null from {@link #get}, {@link #put} or {@link #remove} is * unambiguous: the key was not in the cache. * * <p>This class appeared in Android 3.1 (Honeycomb MR1); it's available as part * of <a href="http://developer.android.com/sdk/compatibility-library.html">Android's * Support Package</a> for earlier releases. */ public class LruCache<K, V> { private final LinkedHashMap<K, V> map; /** * 缓存大小的单位。不规定元素的数量。 */ // 已经存储的数据大小 private int size; // 最大存储大小 private int maxSize; // 调用put的次数 private int putCount; // 调用create的次数 private int createCount; // 收回 <SUF> private int evictionCount; // 命中的次数(取出数据的成功次数) private int hitCount; // 丢失的次数(取出数据的丢失次数) private int missCount; /** * LruCache的构造方法:需要传入最大缓存个数 */ public LruCache(int maxSize) { // 最大缓存个数小于0,会抛出IllegalArgumentException if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } this.maxSize = maxSize; /* * 初始化LinkedHashMap * 第一个参数:initialCapacity,初始大小 * 第二个参数:loadFactor,负载因子=0.75f * 第三个参数:accessOrder=true,基于访问顺序;accessOrder=false,基于插入顺序 */ this.map = new LinkedHashMap<K, V>(0, 0.75f, true); } /** * 设置缓存的大小。 */ public void resize(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } // 防止外部多线程的情况下设置缓存大小造成的线程不安全 synchronized (this) { this.maxSize = maxSize; } // 重整数据 trimToSize(maxSize); } /** * 根据key查询缓存,如果存在于缓存或者被create方法创建了。 * 如果值返回了,那么它将被移动到双向循环链表的的尾部。 * 如果如果没有缓存的值,则返回null。 */ public final V get(K key) { if (key == null) { throw new NullPointerException("key == null"); } V mapValue; synchronized (this) { // LinkHashMap 如果设置按照访问顺序的话,这里每次get都会重整数据顺序 mapValue = map.get(key); // 计算 命中次数 if (mapValue != null) { hitCount++; return mapValue; } // 计算 丢失次数 missCount++; } /* * 官方解释: * 尝试创建一个值,这可能需要很长时间,并且Map可能在create()返回的值时有所不同。如果在create()执行的时 * 候,一个冲突的值被添加到Map,我们在Map中删除这个值,释放被创造的值。 */ V createdValue = create(key); if (createdValue == null) { return null; } /*************************** * 不覆写create方法走不到下面 * ***************************/ /* * 正常情况走不到这里 * 走到这里的话 说明 实现了自定义的 create(K key) 逻辑 * 因为默认的 create(K key) 逻辑为null */ synchronized (this) { // 记录 create 的次数 createCount++; // 将自定义create创建的值,放入LinkedHashMap中,如果key已经存在,会返回 之前相同key 的值 mapValue = map.put(key, createdValue); // 如果之前存在相同key的value,即有冲突。 if (mapValue != null) { /* * 有冲突 * 所以 撤销 刚才的 操作 * 将 之前相同key 的值 重新放回去 */ map.put(key, mapValue); } else { // 拿到键值对,计算出在容量中的相对长度,然后加上 size += safeSizeOf(key, createdValue); } } // 如果上面 判断出了 将要放入的值发生冲突 if (mapValue != null) { /* * 刚才create的值被删除了,原来的 之前相同key 的值被重新添加回去了 * 告诉 自定义 的 entryRemoved 方法 */ entryRemoved(false, key, createdValue, mapValue); return mapValue; } else { // 上面 进行了 size += 操作 所以这里要重整长度 trimToSize(maxSize); return createdValue; } } /** * 给对应key缓存value,该value将被移动到队头。 */ public final V put(K key, V value) { if (key == null || value == null) { throw new NullPointerException("key == null || value == null"); } V previous; synchronized (this) { // 记录 put 的次数 putCount++; // 拿到键值对,计算出在容量中的相对长度,然后加上 size += safeSizeOf(key, value); /* * 放入 key value * 如果 之前存在key 则返回 之前key 的value * 记录在 previous */ previous = map.put(key, value); // 如果存在冲突 if (previous != null) { // 计算出 冲突键值 在容量中的相对长度,然后减去 size -= safeSizeOf(key, previous); } } // 如果上面发生冲突 if (previous != null) { /* * previous值被剔除了,此次添加的 value 已经作为key的 新值 * 告诉 自定义 的 entryRemoved 方法 */ entryRemoved(false, key, previous, value); } trimToSize(maxSize); return previous; } /** * 删除最旧的数据直到剩余的数据的总数以下要求的大小。 */ public void trimToSize(int maxSize) { /* * 这是一个死循环, * 1.只有 扩容 的情况下能立即跳出 * 2.非扩容的情况下,map的数据会一个一个删除,直到map里没有值了,就会跳出 */ while (true) { K key; V value; synchronized (this) { // 在重新调整容量大小前,本身容量就为空的话,会出异常的。 if (size < 0 || (map.isEmpty() && size != 0)) { throw new IllegalStateException( getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } // 如果是 扩容 或者 map为空了,就会中断,因为扩容不会涉及到丢弃数据的情况 if (size <= maxSize || map.isEmpty()) { break; } Map.Entry<K, V> toEvict = map.entrySet().iterator().next(); key = toEvict.getKey(); value = toEvict.getValue(); map.remove(key); // 拿到键值对,计算出在容量中的相对长度,然后减去。 size -= safeSizeOf(key, value); // 添加一次收回次数 evictionCount++; } /* * 将最后一次删除的最少访问数据回调出去 */ entryRemoved(true, key, value, null); } } /** * 如果对应key的entry存在,则删除。 */ public final V remove(K key) { if (key == null) { throw new NullPointerException("key == null"); } V previous; synchronized (this) { // 移除对应 键值对 ,并将移除的value 存放在 previous previous = map.remove(key); if (previous != null) { // 拿到键值对,计算出在容量中的相对长度,然后减去。 size -= safeSizeOf(key, previous); } } // 如果 Map 中存在 该key ,并且成功移除了 if (previous != null) { /* * 会通知 自定义的 entryRemoved * previous 已经被删除了 */ entryRemoved(false, key, previous, null); } return previous; } /** * 1.当被回收或者删掉时调用。该方法当value被回收释放存储空间时被remove调用 * 或者替换条目值时put调用,默认实现什么都没做。 * 2.该方法没用同步调用,如果其他线程访问缓存时,该方法也会执行。 * 3.evicted=true:如果该条目被删除空间 (表示 进行了trimToSize or remove) evicted=false:put冲突后 或 get里成功create后 * 导致 * 4.newValue!=null,那么则被put()或get()调用。 */ protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) { } /** * 1.缓存丢失之后计算相应的key的value后调用。 * 返回计算后的值,如果没有value可以计算返回null。 * 默认的实现返回null。 * 2.该方法没用同步调用,如果其他线程访问缓存时,该方法也会执行。 * 3.当这个方法返回的时候,如果对应key的value存在缓存内,被创建的value将会被entryRemoved()释放或者丢弃。 * 这情况可以发生在多线程在同一时间上请求相同key(导致多个value被创建了),或者单线程中调用了put()去创建一个 * 相同key的value */ protected V create(K key) { return null; } /** * 计算 该 键值对 的相对长度 * 如果不覆写 sizeOf 实现特殊逻辑的话,默认长度是1。 */ private int safeSizeOf(K key, V value) { int result = sizeOf(key, value); if (result < 0) { throw new IllegalStateException("Negative size: " + key + "=" + value); } return result; } /** * 返回条目在用户定义单位的大小。默认实现返回1,这样的大小是条目的数量并且最大的大小是条目的最大数量。 * 一个条目的大小必须不能在缓存中改变 */ protected int sizeOf(K key, V value) { return 1; } /** * Clear the cache, calling {@link #entryRemoved} on each removed entry. * 清理缓存 */ public final void evictAll() { trimToSize(-1); // -1 will evict 0-sized elements } /** * 对于这个缓存,如果不覆写sizeOf()方法,这个方法返回的是条目的在缓存中的数量。但是对于其他缓存,返回的是 * 条目在缓存中大小的总和。 */ public synchronized final int size() { return size; } /** * 对于这个缓存,如果不覆写sizeOf()方法,这个方法返回的是条目的在缓存中的最大数量。但是对于其他缓存,返回的是 * 条目在缓存中最大大小的总和。 */ public synchronized final int maxSize() { return maxSize; } /** * Returns the number of times {@link #get} returned a value that was * already present in the cache. * 返回的次数{@link #get}这是返回一个值在缓存中已经存在。 */ public synchronized final int hitCount() { return hitCount; } /** * 返回的次数{@link #get}返回null或需要一个新的要创建价值。 */ public synchronized final int missCount() { return missCount; } /** * 返回的次数{@link #create(Object)}返回一个值。 */ public synchronized final int createCount() { return createCount; } /** * 返回put的次数。 */ public synchronized final int putCount() { return putCount; } /** * 返回被收回的value数量。 */ public synchronized final int evictionCount() { return evictionCount; } /** * 返回当前缓存内容的一个副本,从最近很少访问到最最近经常访问。 */ public synchronized final Map<K, V> snapshot() { return new LinkedHashMap<K, V>(map); } @Override public synchronized final String toString() { int accesses = hitCount + missCount; int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0; return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]", maxSize, hitCount, missCount, hitPercent); } }
1
15
1
5094_20
/* * {EasyGank} Copyright (C) {2015} {CaMnter} * * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, your program's commands * might be different; for a GUI interface, you would use an "about box". * * You should also get your employer (if you work as a programmer) or school, * if any, to sign a "copyright disclaimer" for the program, if necessary. * For more information on this, and how to apply and follow the GNU GPL, see * <http://www.gnu.org/licenses/>. * * The GNU General Public License does not permit incorporating your program * into proprietary programs. If your program is a subroutine library, you * may consider it more useful to permit linking proprietary applications with * the library. If this is what you want to do, use the GNU Lesser General * Public License instead of this License. But first, please read * <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ package com.camnter.easygank.presenter; import com.anupcowkur.reservoir.ReservoirGetCallback; import com.camnter.easygank.bean.BaseGankData; import com.camnter.easygank.bean.GankDaily; import com.camnter.easygank.constant.Constant; import com.camnter.easygank.core.mvp.BasePresenter; import com.camnter.easygank.gank.GankApi; import com.camnter.easygank.gank.GankType; import com.camnter.easygank.gank.GankTypeDict; import com.camnter.easygank.presenter.iview.MainView; import com.camnter.easygank.utils.DateUtils; import com.camnter.easygank.utils.ReservoirUtils; import com.google.gson.reflect.TypeToken; import com.orhanobut.logger.Logger; import java.io.Serializable; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import rx.Subscriber; /** * Description:MainPresenter * Created by:CaMnter * Time:2016-01-03 18:09 */ public class MainPresenter extends BasePresenter<MainView> { private EasyDate currentDate; private int page; private ReservoirUtils reservoirUtils; /** * 查每日干货需要的特殊的类 */ public class EasyDate implements Serializable { private Calendar calendar; public EasyDate(Calendar calendar) { this.calendar = calendar; } public int getYear() { return calendar.get(Calendar.YEAR); } public int getMonth() { return calendar.get(Calendar.MONTH) + 1; } public int getDay() { return calendar.get(Calendar.DAY_OF_MONTH); } public List<EasyDate> getPastTime() { List<EasyDate> easyDates = new ArrayList<>(); for (int i = 0; i < GankApi.DEFAULT_DAILY_SIZE; i++) { /* * - (page * DateUtils.ONE_DAY) 翻到哪页再找 一页有DEFAULT_DAILY_SIZE这么长 * - i * DateUtils.ONE_DAY 往前一天一天 找呀找 */ long time = this.calendar.getTimeInMillis() - ((page - 1) * GankApi.DEFAULT_DAILY_SIZE * DateUtils.ONE_DAY) - i * DateUtils.ONE_DAY; Calendar c = Calendar.getInstance(); c.setTimeInMillis(time); EasyDate date = new EasyDate(c); easyDates.add(date); } return easyDates; } } public MainPresenter() { this.reservoirUtils = new ReservoirUtils(); long time = System.currentTimeMillis(); Calendar mCalendar = Calendar.getInstance(); mCalendar.setTimeInMillis(time); this.currentDate = new EasyDate(mCalendar); this.page = 1; } /** * 设置查询第几页 * * @param page page */ public void setPage(int page) { this.page = page; } /** * 获取当前页数量 * * @return page */ public int getPage() { return page; } /** * 查询每日数据 * * @param refresh 是否是刷新 * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据 */ public void getDaily(final boolean refresh, final int oldPage) { /* * 切换数据源的话,尝试页数1 */ if (oldPage != GankTypeDict.DONT_SWITCH) { this.page = 1; } this.mCompositeSubscription.add(this.mDataManager.getDailyDataByNetwork(this.currentDate) .subscribe(new Subscriber<List<GankDaily>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } finally { if (refresh) { Type resultType = new TypeToken<List<GankDaily>>() { }.getType(); MainPresenter.this.reservoirUtils.get(GankType.daily + "", resultType, new ReservoirGetCallback<List<GankDaily>>() { @Override public void onSuccess(List<GankDaily> object) { // 有缓存显示缓存数据 if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily); } if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDailySuccess(object, refresh); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } @Override public void onFailure(Exception e) { MainPresenter.this.switchFailure(oldPage, e); } }); } else { // MainPresenter.this.switchFailure(oldPage, e); // 加载更多失败 MainPresenter.this.getMvpView().onFailure(e); } } } @Override public void onNext(List<GankDaily> dailyData) { /* * 如果是切换数据源 * page=1加载成功了 * 即刚才的loadPage */ if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily); } // 刷新缓存 if (refresh) MainPresenter.this.reservoirUtils.refresh(GankType.daily + "", dailyData); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDailySuccess(dailyData, refresh); } })); } /** * * 查询 ( Android、iOS、前端、拓展资源、福利、休息视频 ) * * @param type GankType * @param refresh 是否是刷新 * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据 */ public void getData(final int type, final boolean refresh, final int oldPage) { /* * 切换数据源的话,尝试页数1 */ if (oldPage != GankTypeDict.DONT_SWITCH) { this.page = 1; } String gankType = GankTypeDict.type2UrlTypeDict.get(type); if (gankType == null) return; this.mCompositeSubscription.add(this.mDataManager.getDataByNetWork(gankType, GankApi.DEFAULT_DATA_SIZE, this.page) .subscribe(new Subscriber<ArrayList<BaseGankData>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } finally { if (refresh) { Type resultType = new TypeToken<ArrayList<BaseGankData>>() { }.getType(); MainPresenter.this.reservoirUtils.get(type + "", resultType, new ReservoirGetCallback<ArrayList<BaseGankData>>() { @Override public void onSuccess(ArrayList<BaseGankData> object) { // 有缓存显示缓存数据 if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(type); } if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDataSuccess(object, refresh); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } @Override public void onFailure(Exception e) { MainPresenter.this.switchFailure(oldPage, e); } }); } else { // MainPresenter.this.switchFailure(oldPage, e); // 加载更多失败 MainPresenter.this.getMvpView().onFailure(e); } } } @Override public void onNext(ArrayList<BaseGankData> baseGankData) { /* * 如果是切换数据源 * page=1加载成功了 * 即刚才的loadPage */ if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(type); } // 刷新缓存 if (refresh) MainPresenter.this.reservoirUtils.refresh(type + "", baseGankData); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDataSuccess(baseGankData, refresh); } })); } public void switchType(int type) { /* * 记录没切换前的数据的页数 * 以防切换数据后,网络又跪导致的page对不上问题 */ int oldPage = this.page; switch (type) { case GankType.daily: this.getDaily(true, oldPage); break; case GankType.android: case GankType.ios: case GankType.js: case GankType.resources: case GankType.welfare: case GankType.video: case GankType.app: this.getData(type, true, oldPage); break; } } public void getDailyDetail(final GankDaily.DailyResults results) { this.mCompositeSubscription.add(this.mDataManager.getDailyDetailByDailyResults(results) .subscribe(new Subscriber<ArrayList<ArrayList<BaseGankData>>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } } @Override public void onNext(ArrayList<ArrayList<BaseGankData>> detail) { if (MainPresenter.this.getMvpView() != null) { // 相信福利一定有 MainPresenter.this.getMvpView().getDailyDetail( DateUtils.date2String(results.welfareData.get(0).publishedAt.getTime(), Constant.DAILY_DATE_FORMAT), detail ); } } })); } /** * 切换分类失败 * * @param oldPage oldPage */ private void switchFailure(int oldPage, Throwable e) { /* * 如果是切换数据源 * 刚才尝试的page=1失败了的请求 * 加载失败 * 会影响到原来页面的page * 在这里执行复原page操作 */ if (oldPage != GankTypeDict.DONT_SWITCH) MainPresenter.this.page = oldPage; if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } }
CaMnter/EasyGank
app/src/main/java/com/camnter/easygank/presenter/MainPresenter.java
3,126
/* * 记录没切换前的数据的页数 * 以防切换数据后,网络又跪导致的page对不上问题 */
block_comment
zh-cn
/* * {EasyGank} Copyright (C) {2015} {CaMnter} * * This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. * This is free software, and you are welcome to redistribute it * under certain conditions; type `show c' for details. * * The hypothetical commands `show w' and `show c' should show the appropriate * parts of the General Public License. Of course, your program's commands * might be different; for a GUI interface, you would use an "about box". * * You should also get your employer (if you work as a programmer) or school, * if any, to sign a "copyright disclaimer" for the program, if necessary. * For more information on this, and how to apply and follow the GNU GPL, see * <http://www.gnu.org/licenses/>. * * The GNU General Public License does not permit incorporating your program * into proprietary programs. If your program is a subroutine library, you * may consider it more useful to permit linking proprietary applications with * the library. If this is what you want to do, use the GNU Lesser General * Public License instead of this License. But first, please read * <http://www.gnu.org/philosophy/why-not-lgpl.html>. */ package com.camnter.easygank.presenter; import com.anupcowkur.reservoir.ReservoirGetCallback; import com.camnter.easygank.bean.BaseGankData; import com.camnter.easygank.bean.GankDaily; import com.camnter.easygank.constant.Constant; import com.camnter.easygank.core.mvp.BasePresenter; import com.camnter.easygank.gank.GankApi; import com.camnter.easygank.gank.GankType; import com.camnter.easygank.gank.GankTypeDict; import com.camnter.easygank.presenter.iview.MainView; import com.camnter.easygank.utils.DateUtils; import com.camnter.easygank.utils.ReservoirUtils; import com.google.gson.reflect.TypeToken; import com.orhanobut.logger.Logger; import java.io.Serializable; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import rx.Subscriber; /** * Description:MainPresenter * Created by:CaMnter * Time:2016-01-03 18:09 */ public class MainPresenter extends BasePresenter<MainView> { private EasyDate currentDate; private int page; private ReservoirUtils reservoirUtils; /** * 查每日干货需要的特殊的类 */ public class EasyDate implements Serializable { private Calendar calendar; public EasyDate(Calendar calendar) { this.calendar = calendar; } public int getYear() { return calendar.get(Calendar.YEAR); } public int getMonth() { return calendar.get(Calendar.MONTH) + 1; } public int getDay() { return calendar.get(Calendar.DAY_OF_MONTH); } public List<EasyDate> getPastTime() { List<EasyDate> easyDates = new ArrayList<>(); for (int i = 0; i < GankApi.DEFAULT_DAILY_SIZE; i++) { /* * - (page * DateUtils.ONE_DAY) 翻到哪页再找 一页有DEFAULT_DAILY_SIZE这么长 * - i * DateUtils.ONE_DAY 往前一天一天 找呀找 */ long time = this.calendar.getTimeInMillis() - ((page - 1) * GankApi.DEFAULT_DAILY_SIZE * DateUtils.ONE_DAY) - i * DateUtils.ONE_DAY; Calendar c = Calendar.getInstance(); c.setTimeInMillis(time); EasyDate date = new EasyDate(c); easyDates.add(date); } return easyDates; } } public MainPresenter() { this.reservoirUtils = new ReservoirUtils(); long time = System.currentTimeMillis(); Calendar mCalendar = Calendar.getInstance(); mCalendar.setTimeInMillis(time); this.currentDate = new EasyDate(mCalendar); this.page = 1; } /** * 设置查询第几页 * * @param page page */ public void setPage(int page) { this.page = page; } /** * 获取当前页数量 * * @return page */ public int getPage() { return page; } /** * 查询每日数据 * * @param refresh 是否是刷新 * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据 */ public void getDaily(final boolean refresh, final int oldPage) { /* * 切换数据源的话,尝试页数1 */ if (oldPage != GankTypeDict.DONT_SWITCH) { this.page = 1; } this.mCompositeSubscription.add(this.mDataManager.getDailyDataByNetwork(this.currentDate) .subscribe(new Subscriber<List<GankDaily>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } finally { if (refresh) { Type resultType = new TypeToken<List<GankDaily>>() { }.getType(); MainPresenter.this.reservoirUtils.get(GankType.daily + "", resultType, new ReservoirGetCallback<List<GankDaily>>() { @Override public void onSuccess(List<GankDaily> object) { // 有缓存显示缓存数据 if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily); } if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDailySuccess(object, refresh); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } @Override public void onFailure(Exception e) { MainPresenter.this.switchFailure(oldPage, e); } }); } else { // MainPresenter.this.switchFailure(oldPage, e); // 加载更多失败 MainPresenter.this.getMvpView().onFailure(e); } } } @Override public void onNext(List<GankDaily> dailyData) { /* * 如果是切换数据源 * page=1加载成功了 * 即刚才的loadPage */ if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(GankType.daily); } // 刷新缓存 if (refresh) MainPresenter.this.reservoirUtils.refresh(GankType.daily + "", dailyData); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDailySuccess(dailyData, refresh); } })); } /** * * 查询 ( Android、iOS、前端、拓展资源、福利、休息视频 ) * * @param type GankType * @param refresh 是否是刷新 * @param oldPage olaPage==GankTypeDict.DONT_SWITCH表示不是切换数据 */ public void getData(final int type, final boolean refresh, final int oldPage) { /* * 切换数据源的话,尝试页数1 */ if (oldPage != GankTypeDict.DONT_SWITCH) { this.page = 1; } String gankType = GankTypeDict.type2UrlTypeDict.get(type); if (gankType == null) return; this.mCompositeSubscription.add(this.mDataManager.getDataByNetWork(gankType, GankApi.DEFAULT_DATA_SIZE, this.page) .subscribe(new Subscriber<ArrayList<BaseGankData>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } finally { if (refresh) { Type resultType = new TypeToken<ArrayList<BaseGankData>>() { }.getType(); MainPresenter.this.reservoirUtils.get(type + "", resultType, new ReservoirGetCallback<ArrayList<BaseGankData>>() { @Override public void onSuccess(ArrayList<BaseGankData> object) { // 有缓存显示缓存数据 if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(type); } if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDataSuccess(object, refresh); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } @Override public void onFailure(Exception e) { MainPresenter.this.switchFailure(oldPage, e); } }); } else { // MainPresenter.this.switchFailure(oldPage, e); // 加载更多失败 MainPresenter.this.getMvpView().onFailure(e); } } } @Override public void onNext(ArrayList<BaseGankData> baseGankData) { /* * 如果是切换数据源 * page=1加载成功了 * 即刚才的loadPage */ if (oldPage != GankTypeDict.DONT_SWITCH) { if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onSwitchSuccess(type); } // 刷新缓存 if (refresh) MainPresenter.this.reservoirUtils.refresh(type + "", baseGankData); if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onGetDataSuccess(baseGankData, refresh); } })); } public void switchType(int type) { /* * 记录没 <SUF>*/ int oldPage = this.page; switch (type) { case GankType.daily: this.getDaily(true, oldPage); break; case GankType.android: case GankType.ios: case GankType.js: case GankType.resources: case GankType.welfare: case GankType.video: case GankType.app: this.getData(type, true, oldPage); break; } } public void getDailyDetail(final GankDaily.DailyResults results) { this.mCompositeSubscription.add(this.mDataManager.getDailyDetailByDailyResults(results) .subscribe(new Subscriber<ArrayList<ArrayList<BaseGankData>>>() { @Override public void onCompleted() { if (MainPresenter.this.mCompositeSubscription != null) MainPresenter.this.mCompositeSubscription.remove(this); } @Override public void onError(Throwable e) { try { Logger.d(e.getMessage()); } catch (Throwable e1) { e1.getMessage(); } } @Override public void onNext(ArrayList<ArrayList<BaseGankData>> detail) { if (MainPresenter.this.getMvpView() != null) { // 相信福利一定有 MainPresenter.this.getMvpView().getDailyDetail( DateUtils.date2String(results.welfareData.get(0).publishedAt.getTime(), Constant.DAILY_DATE_FORMAT), detail ); } } })); } /** * 切换分类失败 * * @param oldPage oldPage */ private void switchFailure(int oldPage, Throwable e) { /* * 如果是切换数据源 * 刚才尝试的page=1失败了的请求 * 加载失败 * 会影响到原来页面的page * 在这里执行复原page操作 */ if (oldPage != GankTypeDict.DONT_SWITCH) MainPresenter.this.page = oldPage; if (MainPresenter.this.getMvpView() != null) MainPresenter.this.getMvpView().onFailure(e); } }
1
74
1
58118_0
package com.caesar.bean.blocks; import com.caesar.bean.Base; import com.caesar.bean.common.Explodeable; import java.awt.*; public abstract class Block extends Base implements Explodeable { /** * 地图块依次为: * MEDIUM_WALL: 普通的墙 * TOUGHER_WALL: 坚固的墙 * HARD_WALL: 无法击毁的墙 * BUSH: 草丛 * HOME: 基地 */ public static final int MEDIUM_WALL = 0; public static final int TOUGHER_WALL = 1; public static final int HARD_WALL = 2; public static final int BUSH = 3; //因基地类有特有属性,故无法直接从此处创建实例对象 public static final int HOME = 4; protected Block(int x, int y, Image image) { super(x, y, image); } public static Block createBlock(int x, int y, int blockType){ Block block = null; switch (blockType) { case MEDIUM_WALL: case TOUGHER_WALL: block = new NormalWall(x, y, blockType); break; case HARD_WALL: block = new HardWall(x, y); break; case BUSH: block = new Bush(x, y); break; default: throw new IllegalStateException("Wrong block type :" + blockType); } return block; } }
Caesar-NoBug/TankWar
tankwar/src/com/caesar/bean/blocks/Block.java
372
/** * 地图块依次为: * MEDIUM_WALL: 普通的墙 * TOUGHER_WALL: 坚固的墙 * HARD_WALL: 无法击毁的墙 * BUSH: 草丛 * HOME: 基地 */
block_comment
zh-cn
package com.caesar.bean.blocks; import com.caesar.bean.Base; import com.caesar.bean.common.Explodeable; import java.awt.*; public abstract class Block extends Base implements Explodeable { /** * 地图块 <SUF>*/ public static final int MEDIUM_WALL = 0; public static final int TOUGHER_WALL = 1; public static final int HARD_WALL = 2; public static final int BUSH = 3; //因基地类有特有属性,故无法直接从此处创建实例对象 public static final int HOME = 4; protected Block(int x, int y, Image image) { super(x, y, image); } public static Block createBlock(int x, int y, int blockType){ Block block = null; switch (blockType) { case MEDIUM_WALL: case TOUGHER_WALL: block = new NormalWall(x, y, blockType); break; case HARD_WALL: block = new HardWall(x, y); break; case BUSH: block = new Bush(x, y); break; default: throw new IllegalStateException("Wrong block type :" + blockType); } return block; } }
0
134
0
18730_34
import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class App { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<User> list = new ArrayList<>(); while (true) { System.out.println("欢迎来到学生管理系统"); System.out.println("请选择操作:1.登录 2.注册 3.忘记密码"); String choose = sc.next(); switch (choose) { case "1" -> login(list); case "2" -> register(list); case "3" -> forgetPassword(list); case "4" -> { System.out.println("谢谢使用,再见"); System.exit(0); } default -> System.out.println("没有这个选项"); } } } private static void login(ArrayList<User> list) { Scanner sc = new Scanner(System.in); for (int i = 0; true; i++) { System.out.println("请输入用户名:"); String username = sc.next(); //判断用户名是否存在 boolean flag = contains(list, username); if (!flag) { System.out.println("用户名:" + username + "未注册,请先注册再登录!"); return; } System.out.println("请输入密码:"); String password = sc.next(); while (true) { String rightCode = getCode(); System.out.println("请输入当前正确的验证码为:" + rightCode); System.out.println(rightCode); System.out.println("请输入验证码:"); String code = sc.next(); if (code.equalsIgnoreCase(rightCode)) { System.out.println("验证码输入正确"); break; } else { System.out.println("验证码输入错误"); } } //验证用户名和密码是否正确 //判断集合中是否包含当前用户名和密码 //定义方法验证用户名和密码是否正确 //封装思想:把零散的数据封装成一个对象 //传递参数的时候传递一个整体就行,不需要管这些零散的数据 User useInfo = new User(username, password, null, null); boolean result = checkUserInfo(list, useInfo); if (result) { System.out.println("登录成功!进入学生管理系统."); //创建对象,调用方法,启动学生管理系统 StudentSystem ss = new StudentSystem(); ss.startStudentSystem(); break; } else { System.out.println("登录失败,用户名或密码错误!"); if (i == 2) { System.out.println("当前账号" + username + "被锁定,请联系客服:+86 17854255163"); //当前账户锁定之后,直接结束方法 return; } else { System.out.println("用户名或密码错误,还剩下" + (2 - i) + "次机会"); } } } } private static boolean checkUserInfo(ArrayList<User> list, User useInfo) { //遍历集合,判断用户是否存在,如果存在登录成功,如果不存在登录失败 for (User user : list) { if (user.getUsername().equals(useInfo.getUsername()) && user.getPassword().equals(useInfo.getPassword())) { return true; } } return false; } private static void register(ArrayList<User> list) { //1.键盘录入用户名 Scanner sc = new Scanner(System.in); String username; String password; String personID; String phoneNumber; while (true) { System.out.println("请输入用户名:"); username = sc.next(); //开发细节:先验证格式是否正确,再验证是否唯一 //所有的数据都是存在数据库中的 boolean flag = checkUsername(username); if (!flag) { System.out.println("用户名格式不满足条件,需重新输入:"); continue; } //此时格式满足,校验用户名是否唯一 //username到集合中判断是否有存在的 boolean flag2 = contains(list, username); if (flag2) { //用户名已存在,无法注册,需要重新注册 System.out.println("用户名" + username + "已存在,请重新输入"); } else { //不存在,用户名可以使用,继续录入其他数据 System.out.println("用户名" + username + "可用"); break; } } //2.键盘录入密码 while (true) { System.out.println("请输入要注册的密码:"); password = sc.next(); System.out.println("请再次输入一次密码:"); String againPassword = sc.next(); if (!password.equals(againPassword)) { System.out.println("两次密码输入错误,请重新输入"); } else { System.out.println("密码一致,继续录入其他数据"); break; } } //3.键盘录入身份证号码 while (true) { System.out.println("请输入身份证号码"); personID = sc.next(); boolean flag = checkPersonID(personID); if (flag) { System.out.println("身份证号码满足要求."); break; } else { System.out.println("身份证号码格式有误,请重新输入:"); } } //4.键盘录入手机号码 while (true) { System.out.println("请输入手机号码:"); phoneNumber = sc.next(); boolean flag = checkPhoneNumber(phoneNumber); if (flag) { System.out.println("手机号码格式正确"); break; } else { System.out.println("手机号码格式有误,请重新输入:"); } } //把用户信息添加到集合中 User u = new User(username, password, personID, phoneNumber); list.add(u); System.out.println("注册成功!"); printList(list); } private static void printList(ArrayList<User> list) { for (User user : list) { System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getPersonID() + ", " + user.getPhoneNumber()); } } private static boolean checkPhoneNumber(String phoneNumber) { //验证长度为11位 if (phoneNumber.length() != 11) { return false; } //不能以数字0为开头 if (phoneNumber.startsWith("0")) { return false; } //必须都是数字,遍历 for (int i = 0; i < phoneNumber.length(); i++) { char c = phoneNumber.charAt(i); if (!(c >= '0' && c <= '9')) { return false; } } return true; } private static void forgetPassword(ArrayList<User> list) { Scanner sc = new Scanner(System.in); System.out.println("请输入用户名:"); String username = sc.next(); boolean flag = contains(list, username); if (!flag) { System.out.println("当前用户" + username + "未注册,请先注册"); return; } //键盘录入身份证和手机号 System.out.println("请输入身份证号码:"); String personID = sc.next(); System.out.println("请输入手机号码:"); String phoneNumber = sc.next(); //比较输入的身份证和手机号是否正确 //取出用户对象by索引 int index = findIndex(list, username); User user = list.get(index); //比较用户对象中的手机号码和身份证 if (!user.getPersonID().equalsIgnoreCase(personID) && user.getPhoneNumber().equals(phoneNumber)) { System.out.println("身份证号码或手机号码有误,不能修改密码"); return; } //代码执行到这里,所有数据验证成功,直接修改密码即可. String password; while (true) { System.out.println("请输入新的密码"); password = sc.next(); System.out.println("请确认新密码"); String againPassword = sc.next(); if (password.equals(againPassword)) { System.out.println("两次密码输入一致"); break; } else { System.out.println("两次密码输入不一致,请重新输入"); } } //直接修改 user.setPassword(password); System.out.println("密码修改成功"); } private static int findIndex(ArrayList<User> list, String username) { for (int i = 0; i < list.size(); i++) { User user = list.get(i); if (user.getUsername().equals(username)) { return i; } } return -1; } private static boolean checkPersonID(String personID) { if (personID.length() != 18) { return false; } boolean flag = personID.startsWith("0"); if (flag) { return false; } for (int i = 0; i < personID.length() - 1; i++) { char c = personID.charAt(i); if (!(c >= '0' && c <= '9')) { return false; } } char endChar = personID.charAt(personID.length() - 1); return (endChar >= '0' && endChar <= '9') || (endChar == 'x') || (endChar == 'X'); } private static boolean contains(ArrayList<User> list, String username) { //循环遍历集合,得到每一个用户对象,拿出用户对象的用户名进行比较 for (User user : list) { String rightUsername = user.getUsername(); if (rightUsername.equals(username)) { return true; } } return false; } private static boolean checkUsername(String username) { //1.校验长度 int length = username.length(); if (length < 3 || length > 15) { return false; } //2.1长度符合要求,校验字母和数字的组合 // 循环得到每一个字符 for (int i = 0; i < username.length(); i++) { char c = username.charAt(i); if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))) { return false; } } //执行到这里,表示用户名满足长度和内容的要求(字母+数字) //2.2校验不能是纯数字 //统计在用户名中,有多少字母 int count = 0; for (int i = 0; i < username.length(); i++) { char c = username.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { count++; break; } } return count > 0; } private static String getCode() { //1.创建一个集合,添加所有的大小写字母 //不能加数字,结果会导致验证码数字出现多次 ArrayList<Character> list2 = new ArrayList<>(); for (int i = 0; i < 26; i++) { list2.add((char) ('a' + i)); list2.add((char) ('A' + i)); } //2.随机抽取四个字符 StringBuilder sb = new StringBuilder(); Random r = new Random(); for (int i = 0; i < 4; i++) { //获取随机索引 int index = r.nextInt(list2.size()); char c = list2.get(index); sb.append(c); } //3.把随机数字添加到末尾 int number = r.nextInt(10); sb.append(number); //4.修改字符串中的内容:将字符串变成字符数组,在数组中修改,再创建一个新的字符串 char[] arr = sb.toString().toCharArray(); int randomIndex = r.nextInt(5); //最大索引与随机索引的元素进行交换 char temp = arr[randomIndex]; arr[randomIndex] = arr[arr.length - 1]; arr[arr.length - 1] = temp; return new String(arr); } }
CaesarLT/StudentManagementSystem
App.java
2,862
//2.2校验不能是纯数字
line_comment
zh-cn
import java.util.ArrayList; import java.util.Random; import java.util.Scanner; public class App { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ArrayList<User> list = new ArrayList<>(); while (true) { System.out.println("欢迎来到学生管理系统"); System.out.println("请选择操作:1.登录 2.注册 3.忘记密码"); String choose = sc.next(); switch (choose) { case "1" -> login(list); case "2" -> register(list); case "3" -> forgetPassword(list); case "4" -> { System.out.println("谢谢使用,再见"); System.exit(0); } default -> System.out.println("没有这个选项"); } } } private static void login(ArrayList<User> list) { Scanner sc = new Scanner(System.in); for (int i = 0; true; i++) { System.out.println("请输入用户名:"); String username = sc.next(); //判断用户名是否存在 boolean flag = contains(list, username); if (!flag) { System.out.println("用户名:" + username + "未注册,请先注册再登录!"); return; } System.out.println("请输入密码:"); String password = sc.next(); while (true) { String rightCode = getCode(); System.out.println("请输入当前正确的验证码为:" + rightCode); System.out.println(rightCode); System.out.println("请输入验证码:"); String code = sc.next(); if (code.equalsIgnoreCase(rightCode)) { System.out.println("验证码输入正确"); break; } else { System.out.println("验证码输入错误"); } } //验证用户名和密码是否正确 //判断集合中是否包含当前用户名和密码 //定义方法验证用户名和密码是否正确 //封装思想:把零散的数据封装成一个对象 //传递参数的时候传递一个整体就行,不需要管这些零散的数据 User useInfo = new User(username, password, null, null); boolean result = checkUserInfo(list, useInfo); if (result) { System.out.println("登录成功!进入学生管理系统."); //创建对象,调用方法,启动学生管理系统 StudentSystem ss = new StudentSystem(); ss.startStudentSystem(); break; } else { System.out.println("登录失败,用户名或密码错误!"); if (i == 2) { System.out.println("当前账号" + username + "被锁定,请联系客服:+86 17854255163"); //当前账户锁定之后,直接结束方法 return; } else { System.out.println("用户名或密码错误,还剩下" + (2 - i) + "次机会"); } } } } private static boolean checkUserInfo(ArrayList<User> list, User useInfo) { //遍历集合,判断用户是否存在,如果存在登录成功,如果不存在登录失败 for (User user : list) { if (user.getUsername().equals(useInfo.getUsername()) && user.getPassword().equals(useInfo.getPassword())) { return true; } } return false; } private static void register(ArrayList<User> list) { //1.键盘录入用户名 Scanner sc = new Scanner(System.in); String username; String password; String personID; String phoneNumber; while (true) { System.out.println("请输入用户名:"); username = sc.next(); //开发细节:先验证格式是否正确,再验证是否唯一 //所有的数据都是存在数据库中的 boolean flag = checkUsername(username); if (!flag) { System.out.println("用户名格式不满足条件,需重新输入:"); continue; } //此时格式满足,校验用户名是否唯一 //username到集合中判断是否有存在的 boolean flag2 = contains(list, username); if (flag2) { //用户名已存在,无法注册,需要重新注册 System.out.println("用户名" + username + "已存在,请重新输入"); } else { //不存在,用户名可以使用,继续录入其他数据 System.out.println("用户名" + username + "可用"); break; } } //2.键盘录入密码 while (true) { System.out.println("请输入要注册的密码:"); password = sc.next(); System.out.println("请再次输入一次密码:"); String againPassword = sc.next(); if (!password.equals(againPassword)) { System.out.println("两次密码输入错误,请重新输入"); } else { System.out.println("密码一致,继续录入其他数据"); break; } } //3.键盘录入身份证号码 while (true) { System.out.println("请输入身份证号码"); personID = sc.next(); boolean flag = checkPersonID(personID); if (flag) { System.out.println("身份证号码满足要求."); break; } else { System.out.println("身份证号码格式有误,请重新输入:"); } } //4.键盘录入手机号码 while (true) { System.out.println("请输入手机号码:"); phoneNumber = sc.next(); boolean flag = checkPhoneNumber(phoneNumber); if (flag) { System.out.println("手机号码格式正确"); break; } else { System.out.println("手机号码格式有误,请重新输入:"); } } //把用户信息添加到集合中 User u = new User(username, password, personID, phoneNumber); list.add(u); System.out.println("注册成功!"); printList(list); } private static void printList(ArrayList<User> list) { for (User user : list) { System.out.println(user.getUsername() + ", " + user.getPassword() + ", " + user.getPersonID() + ", " + user.getPhoneNumber()); } } private static boolean checkPhoneNumber(String phoneNumber) { //验证长度为11位 if (phoneNumber.length() != 11) { return false; } //不能以数字0为开头 if (phoneNumber.startsWith("0")) { return false; } //必须都是数字,遍历 for (int i = 0; i < phoneNumber.length(); i++) { char c = phoneNumber.charAt(i); if (!(c >= '0' && c <= '9')) { return false; } } return true; } private static void forgetPassword(ArrayList<User> list) { Scanner sc = new Scanner(System.in); System.out.println("请输入用户名:"); String username = sc.next(); boolean flag = contains(list, username); if (!flag) { System.out.println("当前用户" + username + "未注册,请先注册"); return; } //键盘录入身份证和手机号 System.out.println("请输入身份证号码:"); String personID = sc.next(); System.out.println("请输入手机号码:"); String phoneNumber = sc.next(); //比较输入的身份证和手机号是否正确 //取出用户对象by索引 int index = findIndex(list, username); User user = list.get(index); //比较用户对象中的手机号码和身份证 if (!user.getPersonID().equalsIgnoreCase(personID) && user.getPhoneNumber().equals(phoneNumber)) { System.out.println("身份证号码或手机号码有误,不能修改密码"); return; } //代码执行到这里,所有数据验证成功,直接修改密码即可. String password; while (true) { System.out.println("请输入新的密码"); password = sc.next(); System.out.println("请确认新密码"); String againPassword = sc.next(); if (password.equals(againPassword)) { System.out.println("两次密码输入一致"); break; } else { System.out.println("两次密码输入不一致,请重新输入"); } } //直接修改 user.setPassword(password); System.out.println("密码修改成功"); } private static int findIndex(ArrayList<User> list, String username) { for (int i = 0; i < list.size(); i++) { User user = list.get(i); if (user.getUsername().equals(username)) { return i; } } return -1; } private static boolean checkPersonID(String personID) { if (personID.length() != 18) { return false; } boolean flag = personID.startsWith("0"); if (flag) { return false; } for (int i = 0; i < personID.length() - 1; i++) { char c = personID.charAt(i); if (!(c >= '0' && c <= '9')) { return false; } } char endChar = personID.charAt(personID.length() - 1); return (endChar >= '0' && endChar <= '9') || (endChar == 'x') || (endChar == 'X'); } private static boolean contains(ArrayList<User> list, String username) { //循环遍历集合,得到每一个用户对象,拿出用户对象的用户名进行比较 for (User user : list) { String rightUsername = user.getUsername(); if (rightUsername.equals(username)) { return true; } } return false; } private static boolean checkUsername(String username) { //1.校验长度 int length = username.length(); if (length < 3 || length > 15) { return false; } //2.1长度符合要求,校验字母和数字的组合 // 循环得到每一个字符 for (int i = 0; i < username.length(); i++) { char c = username.charAt(i); if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9'))) { return false; } } //执行到这里,表示用户名满足长度和内容的要求(字母+数字) //2. <SUF> //统计在用户名中,有多少字母 int count = 0; for (int i = 0; i < username.length(); i++) { char c = username.charAt(i); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { count++; break; } } return count > 0; } private static String getCode() { //1.创建一个集合,添加所有的大小写字母 //不能加数字,结果会导致验证码数字出现多次 ArrayList<Character> list2 = new ArrayList<>(); for (int i = 0; i < 26; i++) { list2.add((char) ('a' + i)); list2.add((char) ('A' + i)); } //2.随机抽取四个字符 StringBuilder sb = new StringBuilder(); Random r = new Random(); for (int i = 0; i < 4; i++) { //获取随机索引 int index = r.nextInt(list2.size()); char c = list2.get(index); sb.append(c); } //3.把随机数字添加到末尾 int number = r.nextInt(10); sb.append(number); //4.修改字符串中的内容:将字符串变成字符数组,在数组中修改,再创建一个新的字符串 char[] arr = sb.toString().toCharArray(); int randomIndex = r.nextInt(5); //最大索引与随机索引的元素进行交换 char temp = arr[randomIndex]; arr[randomIndex] = arr[arr.length - 1]; arr[arr.length - 1] = temp; return new String(arr); } }
1
14
1
60574_3
package com.abc.util; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; /** * 生成菜单树的工具类 * * 为避免线程安全问题,建议每次都new一个新对象出来,再调用menuList()方法 * */ public class MenuTree { public List<MenuResource> cache;//把菜单列表缓存起来 /** * 生成菜单树 * @param menus * @return */ public List<MenuResource> menuList(List<MenuResource> menus) { List<MenuResource> list = new ArrayList<>(); this.cache = menus; for (MenuResource m : menus) { //顶级菜单 if (StringUtils.isBlank(m.getParentId())) { MenuResource topMenu = new MenuResource(m); topMenu.setChildren(menuChild(m.getMenuId())); list.add(topMenu); } } return list; } /** * 给定一个父级菜单id,查找有所子菜单 * * @param id * @return */ private List<MenuResource> menuChild(String id) { List<MenuResource> lists = new ArrayList<>(); for (MenuResource m : cache) { if (StringUtils.equals(id,m.getParentId())) { MenuResource childMenu = new MenuResource(m); childMenu.setChildren(menuChild(m.getMenuId())); lists.add(childMenu); } } return lists; } }
CaiBaoHong/biu
server/src/main/java/com/abc/util/MenuTree.java
356
//顶级菜单
line_comment
zh-cn
package com.abc.util; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; /** * 生成菜单树的工具类 * * 为避免线程安全问题,建议每次都new一个新对象出来,再调用menuList()方法 * */ public class MenuTree { public List<MenuResource> cache;//把菜单列表缓存起来 /** * 生成菜单树 * @param menus * @return */ public List<MenuResource> menuList(List<MenuResource> menus) { List<MenuResource> list = new ArrayList<>(); this.cache = menus; for (MenuResource m : menus) { //顶级 <SUF> if (StringUtils.isBlank(m.getParentId())) { MenuResource topMenu = new MenuResource(m); topMenu.setChildren(menuChild(m.getMenuId())); list.add(topMenu); } } return list; } /** * 给定一个父级菜单id,查找有所子菜单 * * @param id * @return */ private List<MenuResource> menuChild(String id) { List<MenuResource> lists = new ArrayList<>(); for (MenuResource m : cache) { if (StringUtils.equals(id,m.getParentId())) { MenuResource childMenu = new MenuResource(m); childMenu.setChildren(menuChild(m.getMenuId())); lists.add(childMenu); } } return lists; } }
0
6
0
64712_8
package array; /** * 动态数组 * <p> * 思想: 新建一个新的数组,容量需要进行扩大, * 然后让成员变量数组指针指向新建的数组,原来的数组 * 没有指针指向,会被Java 垃圾回收器回收 * <p> * 时间复杂度分析: * 增: O(n) * 删: O(n) * 改: 已知索引O(1),未知索引:O(n) * 查:已知索引O(1),未知索引:O(n) * <p> * 添加操作: 均摊时间复杂度 * <p> * 复杂度震荡: capacity = n * addLast 扩容 之后紧接着 removeLast 两次时间复杂度 O(n) * removeLast * 原因: removeLast 时resize() 过于着急 * 解决方案:Lazy 缩容时候 当size == capacity/4 才将capacity减半 空间换时间 */ public class DynamicArray<E> { private E[] data; private int size; /** * @param capacity 传数组的容量 */ public DynamicArray(int capacity) { data = (E[]) new Object[capacity]; size = 0; } public DynamicArray() { this(10); } public DynamicArray(E[] eArray) { data = (E[]) new Object[eArray.length]; for (int i = 0; i < eArray.length; i++) { data[i] = eArray[i]; } size = eArray.length; } /** * @return 数组长度 */ public int getSize() { return size; } /** * @return 当前数组容量 */ public int getCapacity() { return data.length; } /** * @return 是否为空 */ public boolean isEmpty() { return size == 0; } /** * 均摊时间复杂度 * O(1) * * @param e 向所有元素后添加一个新元素 */ public void addLast(E e) { add(size, e); } /** * @param e 向所有元素第一个添加一个新元素 O(n) */ public void addFirst(E e) { add(0, e); } /** * 指定位置添加元素 * <p> * 时间复杂度,index取值的概率是一样的 * 每个元素期望是多少,平均时间度O(n/2) ~~ O(n), * 时间复杂度 : * 需要按照最坏的方案计算, * 考虑最好的意义不大 * * @param index 指定位置 * @param e 元素 */ public void add(int index, E e) { if (index < 0 || index > size) { throw new IllegalArgumentException("Add Failed"); } if (size == data.length) { resize(2 * data.length); } //每一个元素向后一个位置 for (int i = size - 1; i >= index; i--) { data[i + 1] = data[i]; } data[index] = e; size++; } /** * 数组扩容 : * 思想,数组当前长度或大或小,不理想,最好是倍数 * <p> * ArrayList 扩容是原来Size的1.5倍数 * <p> * 时间复杂度:O(n) * <p> * 均摊时间复杂度: 假设capacity = 8, 并且每一次添加操作都是用addLast, * 9次addLast 操作,触发一次resize,总共进行了17次基本操作,平均每次addLast * 就执行2次基本操作(扩容倍数), * 假设capacity = n,n+1次addLast,触发resize,总共进行2n+1次基本操作 * 平均每次addLast就执行2次基本操作(扩容倍数), * * @param newCapacity 新数组长度 */ private void resize(int newCapacity) { E[] newData = (E[]) new Object[newCapacity]; for (int i = 0; i < size; i++) { newData[i] = data[i]; } data = newData; } /** * 删除一个 * * @param e 删除元素 */ public void removeElement(E e) { int index = find(e); if (index != -1) { remove(index); } } /** * 时间复杂度:O(n) * * @return */ public E removeFirst() { return remove(0); } /** * 均摊时间复杂度 * O(1) * * @return */ public E removeLast() { return remove(size - 1); } /** * 时间复杂度:O(n) * * @param index 删除索引元素 */ public E remove(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Remove Failed"); } E ret = data[index]; for (int i = index + 1; i < size; i++) { data[i - 1] = data[i]; } size--; data[size] = null; if (size == data.length / 4 && data.length / 2 != 0) { resize(data.length / 2); } return ret; } /** * 时间复杂度:O(1): 支持随机索引 * * @param index 索引 * @param e 索引对应元素 */ public void set(int index, E e) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Set Failed"); } data[index] = e; } /** * @param index 索引 * @return 索引对应元素 */ public E get(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Get Failed"); } return data[index]; } public E getLast() { return get(size - 1); } public E getFirst() { return get(0); } /** * 时间复杂度:O(n) * * @return 是否包含 */ public boolean contains(E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return true; } } return false; } /** * 时间复杂度:O(n) * * @return 元素的索引 */ public int find(E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return i; } } return -1; } /** * 交换 */ public void swap(int i, int j) { if (i < 0 || i >= size || j < 0 || j >= size) { throw new IllegalArgumentException("Index is illegal"); } E temp = data[i]; data[i] = data[j]; data[j] = temp; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(String.format("Array:Size = %d , capacity = %d \n", size, data.length)); builder.append("["); for (int i = 0; i < size; i++) { builder.append(data[i]); if (i != size - 1) { builder.append(", "); } } builder.append("]"); return builder.toString(); } }
CaiPeng/JavaDataStructure
src/array/DynamicArray.java
1,857
//每一个元素向后一个位置
line_comment
zh-cn
package array; /** * 动态数组 * <p> * 思想: 新建一个新的数组,容量需要进行扩大, * 然后让成员变量数组指针指向新建的数组,原来的数组 * 没有指针指向,会被Java 垃圾回收器回收 * <p> * 时间复杂度分析: * 增: O(n) * 删: O(n) * 改: 已知索引O(1),未知索引:O(n) * 查:已知索引O(1),未知索引:O(n) * <p> * 添加操作: 均摊时间复杂度 * <p> * 复杂度震荡: capacity = n * addLast 扩容 之后紧接着 removeLast 两次时间复杂度 O(n) * removeLast * 原因: removeLast 时resize() 过于着急 * 解决方案:Lazy 缩容时候 当size == capacity/4 才将capacity减半 空间换时间 */ public class DynamicArray<E> { private E[] data; private int size; /** * @param capacity 传数组的容量 */ public DynamicArray(int capacity) { data = (E[]) new Object[capacity]; size = 0; } public DynamicArray() { this(10); } public DynamicArray(E[] eArray) { data = (E[]) new Object[eArray.length]; for (int i = 0; i < eArray.length; i++) { data[i] = eArray[i]; } size = eArray.length; } /** * @return 数组长度 */ public int getSize() { return size; } /** * @return 当前数组容量 */ public int getCapacity() { return data.length; } /** * @return 是否为空 */ public boolean isEmpty() { return size == 0; } /** * 均摊时间复杂度 * O(1) * * @param e 向所有元素后添加一个新元素 */ public void addLast(E e) { add(size, e); } /** * @param e 向所有元素第一个添加一个新元素 O(n) */ public void addFirst(E e) { add(0, e); } /** * 指定位置添加元素 * <p> * 时间复杂度,index取值的概率是一样的 * 每个元素期望是多少,平均时间度O(n/2) ~~ O(n), * 时间复杂度 : * 需要按照最坏的方案计算, * 考虑最好的意义不大 * * @param index 指定位置 * @param e 元素 */ public void add(int index, E e) { if (index < 0 || index > size) { throw new IllegalArgumentException("Add Failed"); } if (size == data.length) { resize(2 * data.length); } //每一 <SUF> for (int i = size - 1; i >= index; i--) { data[i + 1] = data[i]; } data[index] = e; size++; } /** * 数组扩容 : * 思想,数组当前长度或大或小,不理想,最好是倍数 * <p> * ArrayList 扩容是原来Size的1.5倍数 * <p> * 时间复杂度:O(n) * <p> * 均摊时间复杂度: 假设capacity = 8, 并且每一次添加操作都是用addLast, * 9次addLast 操作,触发一次resize,总共进行了17次基本操作,平均每次addLast * 就执行2次基本操作(扩容倍数), * 假设capacity = n,n+1次addLast,触发resize,总共进行2n+1次基本操作 * 平均每次addLast就执行2次基本操作(扩容倍数), * * @param newCapacity 新数组长度 */ private void resize(int newCapacity) { E[] newData = (E[]) new Object[newCapacity]; for (int i = 0; i < size; i++) { newData[i] = data[i]; } data = newData; } /** * 删除一个 * * @param e 删除元素 */ public void removeElement(E e) { int index = find(e); if (index != -1) { remove(index); } } /** * 时间复杂度:O(n) * * @return */ public E removeFirst() { return remove(0); } /** * 均摊时间复杂度 * O(1) * * @return */ public E removeLast() { return remove(size - 1); } /** * 时间复杂度:O(n) * * @param index 删除索引元素 */ public E remove(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Remove Failed"); } E ret = data[index]; for (int i = index + 1; i < size; i++) { data[i - 1] = data[i]; } size--; data[size] = null; if (size == data.length / 4 && data.length / 2 != 0) { resize(data.length / 2); } return ret; } /** * 时间复杂度:O(1): 支持随机索引 * * @param index 索引 * @param e 索引对应元素 */ public void set(int index, E e) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Set Failed"); } data[index] = e; } /** * @param index 索引 * @return 索引对应元素 */ public E get(int index) { if (index < 0 || index >= size) { throw new IllegalArgumentException("Get Failed"); } return data[index]; } public E getLast() { return get(size - 1); } public E getFirst() { return get(0); } /** * 时间复杂度:O(n) * * @return 是否包含 */ public boolean contains(E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return true; } } return false; } /** * 时间复杂度:O(n) * * @return 元素的索引 */ public int find(E e) { for (int i = 0; i < size; i++) { if (e.equals(data[i])) { return i; } } return -1; } /** * 交换 */ public void swap(int i, int j) { if (i < 0 || i >= size || j < 0 || j >= size) { throw new IllegalArgumentException("Index is illegal"); } E temp = data[i]; data[i] = data[j]; data[j] = temp; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append(String.format("Array:Size = %d , capacity = %d \n", size, data.length)); builder.append("["); for (int i = 0; i < size; i++) { builder.append(data[i]); if (i != size - 1) { builder.append(", "); } } builder.append("]"); return builder.toString(); } }
1
13
1
54948_47
package com.cgfay.landmark; /** * 关键点索引(106个关键点 + 扩展8个关键点) * Created by cain on 2017/11/10. */ public final class FaceLandmark { private FaceLandmark() {} // 左眉毛 public static int leftEyebrowRightCorner = 37; // 左眉毛右边角 public static int leftEyebrowLeftCorner = 33; // 左眉毛左边角 public static int leftEyebrowLeftTopCorner = 34; // 左眉毛左顶角 public static int leftEyebrowRightTopCorner = 36; // 左眉毛右顶角 public static int leftEyebrowUpperMiddle = 35; // 左眉毛上中心 public static int leftEyebrowLowerMiddle = 65; // 左眉毛下中心 // 右眉毛 public static int rightEyebrowRightCorner = 38; // 右眉毛右边角 public static int rightEyebrowLeftCorner = 42; // 右眉毛左上角 public static int rightEyebrowLeftTopCorner = 39; // 右眉毛左顶角 public static int rightEyebrowRightTopCorner = 41; // 右眉毛右顶角 public static int rightEyebrowUpperMiddle = 40; // 右眉毛上中心 public static int rightEyebrowLowerMiddle = 70; // 右眉毛下中心 // 左眼 public static int leftEyeTop = 72; // 左眼球上边 public static int leftEyeCenter = 74; // 左眼球中心 public static int leftEyeBottom = 73; // 左眼球下边 public static int leftEyeLeftCorner = 52; // 左眼左边角 public static int leftEyeRightCorner = 55; // 左眼右边角 // 右眼 public static int rightEyeTop = 75; // 右眼球上边 public static int rightEyeCenter = 77; // 右眼球中心 public static int rightEyeBottom = 76; // 右眼球下边 public static int rightEyeLeftCorner = 58; // 右眼左边角 public static int rightEyeRightCorner = 61; // 右眼右边角 public static int eyeCenter = 43; // 两眼中心 // 鼻子 public static int noseTop = 46; // 鼻尖 public static int noseLeft = 82; // 鼻子左边 public static int noseRight = 83; // 鼻子右边 public static int noseLowerMiddle = 49; // 两鼻孔中心 // 脸边沿 public static int leftCheekEdgeCenter = 4; // 左脸颊边沿中心 public static int rightCheekEdgeCenter = 28; // 右脸颊边沿中心 // 嘴巴 public static int mouthLeftCorner = 84; // 嘴唇左边 public static int mouthRightCorner = 90; // 嘴唇右边 public static int mouthUpperLipTop = 87; // 上嘴唇上中心 public static int mouthUpperLipBottom = 98; // 上嘴唇下中心 public static int mouthLowerLipTop = 102; // 下嘴唇上中心 public static int mouthLowerLipBottom = 93; // 下嘴唇下中心 // 下巴 public static int chinLeft = 14; // 下巴左边 public static int chinRight = 18; // 下巴右边 public static int chinCenter = 16; // 下巴中心 // 扩展的关键点(8个) public static int mouthCenter = 106; // 嘴巴中心 public static int leftEyebrowCenter = 107; // 左眉心 public static int rightEyebrowCenter = 108; // 右眉心 public static int leftHead = 109; // 额头左侧 public static int headCenter = 110; // 额头中心 public static int rightHead = 111; // 额头右侧 public static int leftCheekCenter = 112; // 左脸颊中心 public static int rightCheekCenter = 113; // 右脸颊中心 }
CainKernel/CainCamera
landmarklibrary/src/main/java/com/cgfay/landmark/FaceLandmark.java
1,152
// 额头右侧
line_comment
zh-cn
package com.cgfay.landmark; /** * 关键点索引(106个关键点 + 扩展8个关键点) * Created by cain on 2017/11/10. */ public final class FaceLandmark { private FaceLandmark() {} // 左眉毛 public static int leftEyebrowRightCorner = 37; // 左眉毛右边角 public static int leftEyebrowLeftCorner = 33; // 左眉毛左边角 public static int leftEyebrowLeftTopCorner = 34; // 左眉毛左顶角 public static int leftEyebrowRightTopCorner = 36; // 左眉毛右顶角 public static int leftEyebrowUpperMiddle = 35; // 左眉毛上中心 public static int leftEyebrowLowerMiddle = 65; // 左眉毛下中心 // 右眉毛 public static int rightEyebrowRightCorner = 38; // 右眉毛右边角 public static int rightEyebrowLeftCorner = 42; // 右眉毛左上角 public static int rightEyebrowLeftTopCorner = 39; // 右眉毛左顶角 public static int rightEyebrowRightTopCorner = 41; // 右眉毛右顶角 public static int rightEyebrowUpperMiddle = 40; // 右眉毛上中心 public static int rightEyebrowLowerMiddle = 70; // 右眉毛下中心 // 左眼 public static int leftEyeTop = 72; // 左眼球上边 public static int leftEyeCenter = 74; // 左眼球中心 public static int leftEyeBottom = 73; // 左眼球下边 public static int leftEyeLeftCorner = 52; // 左眼左边角 public static int leftEyeRightCorner = 55; // 左眼右边角 // 右眼 public static int rightEyeTop = 75; // 右眼球上边 public static int rightEyeCenter = 77; // 右眼球中心 public static int rightEyeBottom = 76; // 右眼球下边 public static int rightEyeLeftCorner = 58; // 右眼左边角 public static int rightEyeRightCorner = 61; // 右眼右边角 public static int eyeCenter = 43; // 两眼中心 // 鼻子 public static int noseTop = 46; // 鼻尖 public static int noseLeft = 82; // 鼻子左边 public static int noseRight = 83; // 鼻子右边 public static int noseLowerMiddle = 49; // 两鼻孔中心 // 脸边沿 public static int leftCheekEdgeCenter = 4; // 左脸颊边沿中心 public static int rightCheekEdgeCenter = 28; // 右脸颊边沿中心 // 嘴巴 public static int mouthLeftCorner = 84; // 嘴唇左边 public static int mouthRightCorner = 90; // 嘴唇右边 public static int mouthUpperLipTop = 87; // 上嘴唇上中心 public static int mouthUpperLipBottom = 98; // 上嘴唇下中心 public static int mouthLowerLipTop = 102; // 下嘴唇上中心 public static int mouthLowerLipBottom = 93; // 下嘴唇下中心 // 下巴 public static int chinLeft = 14; // 下巴左边 public static int chinRight = 18; // 下巴右边 public static int chinCenter = 16; // 下巴中心 // 扩展的关键点(8个) public static int mouthCenter = 106; // 嘴巴中心 public static int leftEyebrowCenter = 107; // 左眉心 public static int rightEyebrowCenter = 108; // 右眉心 public static int leftHead = 109; // 额头左侧 public static int headCenter = 110; // 额头中心 public static int rightHead = 111; // 额头 <SUF> public static int leftCheekCenter = 112; // 左脸颊中心 public static int rightCheekCenter = 113; // 右脸颊中心 }
1
7
1
56795_14
package ink.beibeil.testplugin; import ink.beibeil.testplugin.utils.HexCodeUtils; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerBedEnterEvent; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitScheduler; import java.util.List; public class ExamplePlugin extends JavaPlugin implements Listener { FileConfiguration config = getConfig(); // private List<Player> sleepingPlayers; @Override public void onEnable() { // 创建并保存配置文件 config.addDefault("enter-message-rewrite", false); config.addDefault("enabled", true); config.addDefault("fall-asleep-time", 60); // 一人眠模式 config.addDefault("one-player-mode", false); // 跳过黑夜所需的玩家百分比 config.addDefault("skip-percent", 50); // 是否在睡眠的同时把天气改为晴朗,默认关闭 config.addDefault("change-weather", false); // 晴朗天气持续时间,相当于/weather clear xxx,单位为tick config.addDefault("clear-weather-time", 10000); config.options().copyDefaults(true); saveConfig(); getServer().getPluginManager().registerEvents(this, this); getLogger().info("睡觉插件启动,Made by Cal0rie!"); } @EventHandler // 玩家加入游戏 public void onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent event) { // 修改玩家加入提示 if (!config.getBoolean("enter-message-rewrite")) return; event.setJoinMessage("玩家 " + HexCodeUtils.playerString(event.getPlayer().getName()) + " ,启动!"); } @EventHandler public void PlayerBedEnter(PlayerBedEnterEvent event) { if (!config.getBoolean("enabled")) return; // 轮询判断是否睡着 if (event.getBedEnterResult() == PlayerBedEnterEvent.BedEnterResult.OK) { Bukkit.broadcastMessage("玩家 " + HexCodeUtils.playerString(event.getPlayer().getName()) + " 要睡觉了!"); BukkitScheduler scheduler = Bukkit.getServer().getScheduler(); long time = config.getLong("fall-asleep-time"); // 睡眠到指定时间做判断 scheduler.scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { // 若未开启一人眠模式 if (!config.getBoolean("one-player-mode")) { // 床所在世界玩家 List<Player> players = event.getBed().getWorld().getPlayers(); int percent = config.getInt("skip-percent"); int sleepPlayerCount = 0; for (Player player : players) { // 如果该玩家在bed上,就认为该玩家正在睡觉 try { if (!player.getBedLocation().getBlock().isEmpty()) { sleepPlayerCount++; } } catch (Exception e) { // getLogger().info(e.getMessage()); } } if (sleepPlayerCount >= players.size() * percent / 100.0) { String s = "&b天要亮啦~"; Bukkit.broadcastMessage(HexCodeUtils.stringWithColor(s)); event.getBed().getWorld().setTime(100L); if(config.getBoolean("change-weather")) event.getBed().getWorld().setClearWeatherDuration(config.getInt("clear-weather-time")); } // 若开启一人眠模式 } else { try { event.getPlayer().getBedLocation(); String s = "玩家 " + HexCodeUtils.playerString(event.getPlayer().getName()) + " 睡着了,天要亮啦~"; Bukkit.broadcastMessage(HexCodeUtils.stringWithColor(s)); event.getBed().getWorld().setTime(100L); if(config.getBoolean("change-weather")) event.getBed().getWorld().setClearWeatherDuration(config.getInt("clear-weather-time")); } catch (Exception ignored) { } } } }, time); } } ; @EventHandler public void PlayerBedLeave(PlayerBedEnterEvent event) { // 将该玩家移出 sleepingPlayers // this.sleepingPlayers.remove(event.getPlayer()); } }
Cal0rie/OnePlayerSleep
src/main/java/ink/beibeil/testplugin/ExamplePlugin.java
1,092
// 若开启一人眠模式
line_comment
zh-cn
package ink.beibeil.testplugin; import ink.beibeil.testplugin.utils.HexCodeUtils; import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerBedEnterEvent; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitScheduler; import java.util.List; public class ExamplePlugin extends JavaPlugin implements Listener { FileConfiguration config = getConfig(); // private List<Player> sleepingPlayers; @Override public void onEnable() { // 创建并保存配置文件 config.addDefault("enter-message-rewrite", false); config.addDefault("enabled", true); config.addDefault("fall-asleep-time", 60); // 一人眠模式 config.addDefault("one-player-mode", false); // 跳过黑夜所需的玩家百分比 config.addDefault("skip-percent", 50); // 是否在睡眠的同时把天气改为晴朗,默认关闭 config.addDefault("change-weather", false); // 晴朗天气持续时间,相当于/weather clear xxx,单位为tick config.addDefault("clear-weather-time", 10000); config.options().copyDefaults(true); saveConfig(); getServer().getPluginManager().registerEvents(this, this); getLogger().info("睡觉插件启动,Made by Cal0rie!"); } @EventHandler // 玩家加入游戏 public void onPlayerJoin(org.bukkit.event.player.PlayerJoinEvent event) { // 修改玩家加入提示 if (!config.getBoolean("enter-message-rewrite")) return; event.setJoinMessage("玩家 " + HexCodeUtils.playerString(event.getPlayer().getName()) + " ,启动!"); } @EventHandler public void PlayerBedEnter(PlayerBedEnterEvent event) { if (!config.getBoolean("enabled")) return; // 轮询判断是否睡着 if (event.getBedEnterResult() == PlayerBedEnterEvent.BedEnterResult.OK) { Bukkit.broadcastMessage("玩家 " + HexCodeUtils.playerString(event.getPlayer().getName()) + " 要睡觉了!"); BukkitScheduler scheduler = Bukkit.getServer().getScheduler(); long time = config.getLong("fall-asleep-time"); // 睡眠到指定时间做判断 scheduler.scheduleSyncDelayedTask(this, new Runnable() { @Override public void run() { // 若未开启一人眠模式 if (!config.getBoolean("one-player-mode")) { // 床所在世界玩家 List<Player> players = event.getBed().getWorld().getPlayers(); int percent = config.getInt("skip-percent"); int sleepPlayerCount = 0; for (Player player : players) { // 如果该玩家在bed上,就认为该玩家正在睡觉 try { if (!player.getBedLocation().getBlock().isEmpty()) { sleepPlayerCount++; } } catch (Exception e) { // getLogger().info(e.getMessage()); } } if (sleepPlayerCount >= players.size() * percent / 100.0) { String s = "&b天要亮啦~"; Bukkit.broadcastMessage(HexCodeUtils.stringWithColor(s)); event.getBed().getWorld().setTime(100L); if(config.getBoolean("change-weather")) event.getBed().getWorld().setClearWeatherDuration(config.getInt("clear-weather-time")); } // 若开 <SUF> } else { try { event.getPlayer().getBedLocation(); String s = "玩家 " + HexCodeUtils.playerString(event.getPlayer().getName()) + " 睡着了,天要亮啦~"; Bukkit.broadcastMessage(HexCodeUtils.stringWithColor(s)); event.getBed().getWorld().setTime(100L); if(config.getBoolean("change-weather")) event.getBed().getWorld().setClearWeatherDuration(config.getInt("clear-weather-time")); } catch (Exception ignored) { } } } }, time); } } ; @EventHandler public void PlayerBedLeave(PlayerBedEnterEvent event) { // 将该玩家移出 sleepingPlayers // this.sleepingPlayers.remove(event.getPlayer()); } }
0
11
0
62224_2
package top.calivnhaynes.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; /** * @author CalvinHaynes * @date 2021/09/05 */ public class CookieDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); //解决网页中文显示乱码 resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); //服务器端从客户端获取Cookie Cookie[] cookies = req.getCookies(); //判断Cookie是否存在 if (cookies != null) { //存在cookie进行的测试:打印上一次访问此站的时间 out.write("本站的创始人是:"); for (Cookie cookie : cookies) { //判断Cookie名字非空拿到它的值并打印 if ("name".equals(cookie.getName())) { System.out.println(URLDecoder.decode(cookie.getValue(), "GBK")); out.write(URLDecoder.decode(cookie.getValue(), "GBK")); } } } else { out.write("这是您第一次访问本站"); } //创建Cookie Cookie name = new Cookie("name", URLEncoder.encode("马丁", "GBK")); //服务器响应给客户端Cookie resp.addCookie(name); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
CalvinHaynes/SSM-Study
SpringMVC-Study/6-Servlet-Cookie-Session/src/main/java/top/calivnhaynes/servlet/CookieDemo02.java
462
//解决网页中文显示乱码
line_comment
zh-cn
package top.calivnhaynes.servlet; import jakarta.servlet.ServletException; import jakarta.servlet.http.Cookie; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Date; /** * @author CalvinHaynes * @date 2021/09/05 */ public class CookieDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //解决中文乱码 req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); //解决 <SUF> resp.setContentType("text/html;charset=utf-8"); PrintWriter out = resp.getWriter(); //服务器端从客户端获取Cookie Cookie[] cookies = req.getCookies(); //判断Cookie是否存在 if (cookies != null) { //存在cookie进行的测试:打印上一次访问此站的时间 out.write("本站的创始人是:"); for (Cookie cookie : cookies) { //判断Cookie名字非空拿到它的值并打印 if ("name".equals(cookie.getName())) { System.out.println(URLDecoder.decode(cookie.getValue(), "GBK")); out.write(URLDecoder.decode(cookie.getValue(), "GBK")); } } } else { out.write("这是您第一次访问本站"); } //创建Cookie Cookie name = new Cookie("name", URLEncoder.encode("马丁", "GBK")); //服务器响应给客户端Cookie resp.addCookie(name); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
1
12
1
47018_17
package principal; public class PruebaTexto { public static void main(String[] args) { // String n="hello"; /// n contiene la referencia del objeto. n contiene el objeto. // n.toUpperCase(); // System.out.println(n); // muestra hello por inmutable, // n=n.toUpperCase(); // System.out.println(n);//el n original se convierte a basura. GC 它清理垃圾 这东西叫做GC. // // String a=new String("mitexto"); // String b=new String("mitexto"); // if(a==b) { // 不同的因为他们的只是显示LOCALES 但是不显示OBJETO 本身"==" // System.out.println("Iguales"); // }else { // System.out.println("Distintos"); // } // // String c=new String("mitextos"); // String d=new String("mitextos"); // if(c.equalsIgnoreCase(d)) { // System.out.println("Iguales"); // }else { // System.out.println("Distintos"); // } String a="mitextos"; //第一个JAVA 创造 第二个他不创造(NEW), JAVA 为了节省空间它会找有没有存在的TEXTO String b="mitextos";//所以第二个他就不创造了直接拿第一个的做代替 if(a==b) { System.out.println("Iguales"); }else { System.out.println("Distintos"); } } }
CaniShen/basicos_javase_2024
20_pruebas_string/src/principal/PruebaTexto.java
447
//第一个JAVA 创造 第二个他不创造(NEW), JAVA 为了节省空间它会找有没有存在的TEXTO
line_comment
zh-cn
package principal; public class PruebaTexto { public static void main(String[] args) { // String n="hello"; /// n contiene la referencia del objeto. n contiene el objeto. // n.toUpperCase(); // System.out.println(n); // muestra hello por inmutable, // n=n.toUpperCase(); // System.out.println(n);//el n original se convierte a basura. GC 它清理垃圾 这东西叫做GC. // // String a=new String("mitexto"); // String b=new String("mitexto"); // if(a==b) { // 不同的因为他们的只是显示LOCALES 但是不显示OBJETO 本身"==" // System.out.println("Iguales"); // }else { // System.out.println("Distintos"); // } // // String c=new String("mitextos"); // String d=new String("mitextos"); // if(c.equalsIgnoreCase(d)) { // System.out.println("Iguales"); // }else { // System.out.println("Distintos"); // } String a="mitextos"; //第一 <SUF> String b="mitextos";//所以第二个他就不创造了直接拿第一个的做代替 if(a==b) { System.out.println("Iguales"); }else { System.out.println("Distintos"); } } }
0
53
0
42248_2
package jz.cbq.demo3_4.hy; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Voter * * @author CBQ * @date 2023/11/16 0:47 * @since 1.0.0 */ @Data @AllArgsConstructor @NoArgsConstructor public class Voter { /** * 姓名 */ private String name; /** * 意见 */ private String answer; }
CaoBaoQi/JZJavaStudy
home-work/src/main/java/jz/cbq/demo3_4/hy/Voter.java
127
/** * 意见 */
block_comment
zh-cn
package jz.cbq.demo3_4.hy; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * Voter * * @author CBQ * @date 2023/11/16 0:47 * @since 1.0.0 */ @Data @AllArgsConstructor @NoArgsConstructor public class Voter { /** * 姓名 */ private String name; /** * 意见 <SUF>*/ private String answer; }
0
21
0
25360_1
package com.mine.collection; import com.mine.domain.Student; import org.junit.Test; import java.util.ArrayList; /** * @author CaoY * @date 2023-03-20 0:10 * @description 列表类测试 */ public class ArrayListTest { /** * 对于 ArrayList clone() 的测试,虽然拷贝出来的集合对象是两个完全不同的对象,但是 * 集合中存储的 对象元素 却是同一个,即还是浅拷贝,这点在对于list3 和 list4 的测试情况可以看出来 */ @Test public void testClone() { ArrayList<Integer> list1 = new ArrayList<>(); for (int i = 0; i < 10; i++) { list1.add(i + 1); } ArrayList<Integer> list2 = (ArrayList<Integer>) list1.clone(); System.out.println(list1 == list2); // 放的是 类对象 ArrayList<Student> list3 = new ArrayList<>(); list3.add(new Student(1, "aa", 12, "男", "地球", "[email protected]")); list3.add(new Student(2, "bb", 23, "女", "月球", "[email protected]")); System.out.println("探究元素是否是深拷贝的情况:"); ArrayList<Student> list4 = (ArrayList<Student>) list3.clone(); for (int i = 0; i < list3.size(); i++) { Student student1 = list3.get(i); Student student2 = list4.get(i); System.out.println(student1 == student2); } } }
CaoY123/java-base
src/com/mine/collection/ArrayListTest.java
419
/** * 对于 ArrayList clone() 的测试,虽然拷贝出来的集合对象是两个完全不同的对象,但是 * 集合中存储的 对象元素 却是同一个,即还是浅拷贝,这点在对于list3 和 list4 的测试情况可以看出来 */
block_comment
zh-cn
package com.mine.collection; import com.mine.domain.Student; import org.junit.Test; import java.util.ArrayList; /** * @author CaoY * @date 2023-03-20 0:10 * @description 列表类测试 */ public class ArrayListTest { /** * 对于 <SUF>*/ @Test public void testClone() { ArrayList<Integer> list1 = new ArrayList<>(); for (int i = 0; i < 10; i++) { list1.add(i + 1); } ArrayList<Integer> list2 = (ArrayList<Integer>) list1.clone(); System.out.println(list1 == list2); // 放的是 类对象 ArrayList<Student> list3 = new ArrayList<>(); list3.add(new Student(1, "aa", 12, "男", "地球", "[email protected]")); list3.add(new Student(2, "bb", 23, "女", "月球", "[email protected]")); System.out.println("探究元素是否是深拷贝的情况:"); ArrayList<Student> list4 = (ArrayList<Student>) list3.clone(); for (int i = 0; i < list3.size(); i++) { Student student1 = list3.get(i); Student student2 = list4.get(i); System.out.println(student1 == student2); } } }
0
130
0
27614_0
package com.cy.algorithm.leetcode.medium; /** * 题名 : 笨阶乘 * 题目 : 通常,正整数 n 的阶乘是所有小于或等于 n 的正整数的乘积。例如,factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1。 * 相反,我们设计了一个笨阶乘 clumsy:在整数的递减序列中,我们以一个固定顺序的操作符序列来依次替换原有的乘法操作符:乘法(*),除法(/),加法(+)和减法(-)。 * 例如,clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1。然而,这些运算仍然使用通常的算术运算顺序:我们在任何加、减步骤之前执行所有的乘法和除法步骤,并且按从左到右处理乘法和除法步骤。 * 另外,我们使用的除法是地板除法(floor division),所以 10 * 9 / 8 等于 11。这保证结果是一个整数。 * 实现上面定义的笨函数:给定一个整数 N,它返回 N 的笨阶乘。 * * 思路 : 不断往后递推 * @author clay * @date 19-3-10 10:48 */ public class Leetcode1006 { class Solution { public int clumsy(int N) { int sum = 0; while (true){ if (N == 0){ return sum; } if (N == 1){ if (sum == 0){ return 1; } return sum - 1; } if (N == 2){ if (sum == 0){ return 2; } return sum - 2; } if (N == 3){ if (sum == 0){ return 6; } return sum - 6; } if (sum == 0){ sum = N * (N - 1) / (N - 2) + (N - 3); }else { sum = sum - N * (N - 1) / (N - 2) + (N - 3); } N -= 4; } } } }
CaoYan1/JDCrawler
mainFile/Leetcode1006.java
591
/** * 题名 : 笨阶乘 * 题目 : 通常,正整数 n 的阶乘是所有小于或等于 n 的正整数的乘积。例如,factorial(10) = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1。 * 相反,我们设计了一个笨阶乘 clumsy:在整数的递减序列中,我们以一个固定顺序的操作符序列来依次替换原有的乘法操作符:乘法(*),除法(/),加法(+)和减法(-)。 * 例如,clumsy(10) = 10 * 9 / 8 + 7 - 6 * 5 / 4 + 3 - 2 * 1。然而,这些运算仍然使用通常的算术运算顺序:我们在任何加、减步骤之前执行所有的乘法和除法步骤,并且按从左到右处理乘法和除法步骤。 * 另外,我们使用的除法是地板除法(floor division),所以 10 * 9 / 8 等于 11。这保证结果是一个整数。 * 实现上面定义的笨函数:给定一个整数 N,它返回 N 的笨阶乘。 * * 思路 : 不断往后递推 * @author clay * @date 19-3-10 10:48 */
block_comment
zh-cn
package com.cy.algorithm.leetcode.medium; /** * 题名 <SUF>*/ public class Leetcode1006 { class Solution { public int clumsy(int N) { int sum = 0; while (true){ if (N == 0){ return sum; } if (N == 1){ if (sum == 0){ return 1; } return sum - 1; } if (N == 2){ if (sum == 0){ return 2; } return sum - 2; } if (N == 3){ if (sum == 0){ return 6; } return sum - 6; } if (sum == 0){ sum = N * (N - 1) / (N - 2) + (N - 3); }else { sum = sum - N * (N - 1) / (N - 2) + (N - 3); } N -= 4; } } } }
0
486
0
58470_15
/** * Description: car-eye车辆管理平台 * 文件名:MultiMedia.java * 版本信息:1.0 * 日期:2015-3-26 * Copyright car-eye 车辆管理平台 Copyright (c) 2015 * 版权所有 */ package com.careye.monitor.domain; /** * @项目名称:car-eye * @类名称:MultiMedia * @类描述: * @创建人:Yuqk * @创建时间:2015-3-26 下午03:22:34 * @修改人:Yuqk * @修改时间:2015-3-26 下午03:22:34 * @修改备注: * @version 1.0 */ public class MultiMedia { private Integer id; private Integer carid; /** 组织机构 **/ private Integer blocid; private String blocname; /** 用户ID **/ private Integer userid; /** 终端号码 **/ private String terminal; /** 车牌号 **/ private String carnumber; /** 多媒体数据ID **/ private Integer dataid; /** 多媒体类型 0:图像;1:音频;2:视频 **/ private Integer mediatype; /** 多媒体格式编码 0:JPEG;1:TIF;2:MP3;3:WAV;4:WMV;其他保留 **/ private Integer format; /** 事件项编码 0:平台下发指令; 1:定时动作; 2:抢劫报警触发; 3:碰撞侧翻报警触发; 4:司机上班签到 5:司机下班签退 6: 空车转重车 7:重车转空车**/ private Integer eventcode; /** * word导出时 显示 */ private String eventcodeStr; /** 通道ID **/ private Integer accessid; /** 摄像头立即拍摄记录表ID **/ private Integer msid; /** 多媒体数据保存路径 **/ private String multimediapath; /** 原始数据包 **/ private String data; /** 创建时间 **/ private String createtime; /** * 媒体id */ private Integer mediaid; private String stime; private String etime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getBlocid() { return blocid; } public void setBlocid(Integer blocid) { this.blocid = blocid; } public String getBlocname() { return blocname; } public void setBlocname(String blocname) { this.blocname = blocname; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getTerminal() { return terminal; } public void setTerminal(String terminal) { this.terminal = terminal; } public String getCarnumber() { return carnumber; } public void setCarnumber(String carnumber) { this.carnumber = carnumber; } public Integer getDataid() { return dataid; } public void setDataid(Integer dataid) { this.dataid = dataid; } public Integer getMediatype() { return mediatype; } public void setMediatype(Integer mediatype) { this.mediatype = mediatype; } public Integer getFormat() { return format; } public void setFormat(Integer format) { this.format = format; } public Integer getEventcode() { return eventcode; } public void setEventcode(Integer eventcode) { this.eventcode = eventcode; } public Integer getAccessid() { return accessid; } public void setAccessid(Integer accessid) { this.accessid = accessid; } public Integer getMsid() { return msid; } public void setMsid(Integer msid) { this.msid = msid; } public String getMultimediapath() { return multimediapath; } public void setMultimediapath(String multimediapath) { this.multimediapath = multimediapath; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public Integer getMediaid() { return mediaid; } public void setMediaid(Integer mediaid) { this.mediaid = mediaid; } public String getStime() { return stime; } public void setStime(String stime) { this.stime = stime; } public String getEtime() { return etime; } public void setEtime(String etime) { this.etime = etime; } public Integer getCarid() { return carid; } public void setCarid(Integer carid) { this.carid = carid; } public String getEventcodeStr() { return eventcodeStr; } public void setEventcodeStr(String eventcodeStr) { this.eventcodeStr = eventcodeStr; } }
Car-eye-team/Car-eye-server
car-server/web/CarEye/src/com/careye/monitor/domain/MultiMedia.java
1,474
/** 创建时间 **/
block_comment
zh-cn
/** * Description: car-eye车辆管理平台 * 文件名:MultiMedia.java * 版本信息:1.0 * 日期:2015-3-26 * Copyright car-eye 车辆管理平台 Copyright (c) 2015 * 版权所有 */ package com.careye.monitor.domain; /** * @项目名称:car-eye * @类名称:MultiMedia * @类描述: * @创建人:Yuqk * @创建时间:2015-3-26 下午03:22:34 * @修改人:Yuqk * @修改时间:2015-3-26 下午03:22:34 * @修改备注: * @version 1.0 */ public class MultiMedia { private Integer id; private Integer carid; /** 组织机构 **/ private Integer blocid; private String blocname; /** 用户ID **/ private Integer userid; /** 终端号码 **/ private String terminal; /** 车牌号 **/ private String carnumber; /** 多媒体数据ID **/ private Integer dataid; /** 多媒体类型 0:图像;1:音频;2:视频 **/ private Integer mediatype; /** 多媒体格式编码 0:JPEG;1:TIF;2:MP3;3:WAV;4:WMV;其他保留 **/ private Integer format; /** 事件项编码 0:平台下发指令; 1:定时动作; 2:抢劫报警触发; 3:碰撞侧翻报警触发; 4:司机上班签到 5:司机下班签退 6: 空车转重车 7:重车转空车**/ private Integer eventcode; /** * word导出时 显示 */ private String eventcodeStr; /** 通道ID **/ private Integer accessid; /** 摄像头立即拍摄记录表ID **/ private Integer msid; /** 多媒体数据保存路径 **/ private String multimediapath; /** 原始数据包 **/ private String data; /** 创建时 <SUF>*/ private String createtime; /** * 媒体id */ private Integer mediaid; private String stime; private String etime; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getBlocid() { return blocid; } public void setBlocid(Integer blocid) { this.blocid = blocid; } public String getBlocname() { return blocname; } public void setBlocname(String blocname) { this.blocname = blocname; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public String getTerminal() { return terminal; } public void setTerminal(String terminal) { this.terminal = terminal; } public String getCarnumber() { return carnumber; } public void setCarnumber(String carnumber) { this.carnumber = carnumber; } public Integer getDataid() { return dataid; } public void setDataid(Integer dataid) { this.dataid = dataid; } public Integer getMediatype() { return mediatype; } public void setMediatype(Integer mediatype) { this.mediatype = mediatype; } public Integer getFormat() { return format; } public void setFormat(Integer format) { this.format = format; } public Integer getEventcode() { return eventcode; } public void setEventcode(Integer eventcode) { this.eventcode = eventcode; } public Integer getAccessid() { return accessid; } public void setAccessid(Integer accessid) { this.accessid = accessid; } public Integer getMsid() { return msid; } public void setMsid(Integer msid) { this.msid = msid; } public String getMultimediapath() { return multimediapath; } public void setMultimediapath(String multimediapath) { this.multimediapath = multimediapath; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getCreatetime() { return createtime; } public void setCreatetime(String createtime) { this.createtime = createtime; } public Integer getMediaid() { return mediaid; } public void setMediaid(Integer mediaid) { this.mediaid = mediaid; } public String getStime() { return stime; } public void setStime(String stime) { this.stime = stime; } public String getEtime() { return etime; } public void setEtime(String etime) { this.etime = etime; } public Integer getCarid() { return carid; } public void setCarid(Integer carid) { this.carid = carid; } public String getEventcodeStr() { return eventcodeStr; } public void setEventcodeStr(String eventcodeStr) { this.eventcodeStr = eventcodeStr; } }
1
12
1
33607_11
package com.shuyu; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.webkit.DownloadListener; import android.webkit.JavascriptInterface; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.SslErrorHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.FrameLayout; import android.widget.Toast; import java.util.Set; /** * 演示WebView中的Api说明、js交互的方法,还有注意事项 * <p> * 1、内存泄漏防备 * 2、配置webView * 3、页面加载开始,错误,拦截请求,接受Error等 * 4、页面加载进度,title,图标,js弹框等 * 5、js交互与安全 */ public class APIWebViewActivity extends AppCompatActivity implements View.OnClickListener { FrameLayout mRootLayout; WebView mWebView; Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_api_webview); findViewById(R.id.call_js_function).setOnClickListener(this); //添加webView到布局中 addWebViewToLayout(); //set webView Setting setWebView(); //set webView Client setWebClient(); //set webView chrome setWebViewChromeClient(); //load web loadUrl(); } /** * 主动清空销毁来避免内存泄漏 */ @Override protected void onDestroy() { if (mWebView != null) { mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); mWebView.clearHistory(); ((ViewGroup) mWebView.getParent()).removeView(mWebView); mWebView.destroy(); mWebView = null; } super.onDestroy(); } /** * 1、不在xml中定义Webview,而是在需要的时候在Activity中创建 * 使用getApplicationgContext(),避免内存泄漏。 * <p> * 2、当然,你也可以配置webView所在Activity, * 在AndroidManifest中的进程为:android:process=":remote" * 避免泄漏影响主进程 **/ void addWebViewToLayout() { mRootLayout = (FrameLayout) findViewById(R.id.js_root_layout); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mWebView = new WebView(getApplicationContext()); mWebView.setLayoutParams(params); mRootLayout.addView(mWebView); } /** * 配置webView */ void setWebView() { //声明WebSettings子类 WebSettings webSettings = mWebView.getSettings(); //支持Javascript交互 webSettings.setJavaScriptEnabled(true); //设置自适应屏幕,两者合用 webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小 webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小 //缩放操作 webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。 webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放 webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件 //其他细节操作 //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存 webSettings.setAllowFileAccess(true); //设置可以访问文件 //对于不需要使用 file 协议的应用,禁用 file 协议;防止文件泄密,file协议即是file:// //webSettings.setAllowFileAccess(false); //webSettings.setAllowFileAccessFromFileURLs(false); //webSettings.setAllowUniversalAccessFromFileURLs(false); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口 webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片 webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式 mWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { //网页中触发下载动作 } }); //增加js交互接口 mWebView.addJavascriptInterface(new JsCallAndroidInterface(), "JSCallBackInterface"); } /** * 设置webView的Client,如页面加载开始,错误,拦截请求,接受Error等 */ void setWebClient() { mWebView.setWebViewClient(new WebViewClient() { //拦截页面中的url加载,21以下的 @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (resolveShouldLoadLogic(url)) { return true; } return super.shouldOverrideUrlLoading(view, url); } //拦截页面中的url加载,21以上的 @TargetApi(21) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (resolveShouldLoadLogic(request.getUrl().toString())) { return true; } return super.shouldOverrideUrlLoading(view, request); } //页面开始加载 @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } //页面加载完成 @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } //页面加载每一个资源,如图片 @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); } //监听WebView发出的请求并做相应的处理 //浏览器的渲染以及资源加载都是在一个线程中,如果在shouldInterceptRequest处理时间过长,WebView界面就会阻塞 //21以下的 @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { return super.shouldInterceptRequest(view, url); } //监听WebView发出的请求并做相应的处理 //浏览器的渲染以及资源加载都是在一个线程中,如果在shouldInterceptRequest处理时间过长,WebView界面就会阻塞 //21以上的 @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { return super.shouldInterceptRequest(view, request); } //页面加载出现错误,23以下的 @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); switch (errorCode) { case 404: //view.loadUrl("加载一个错误页面提示,优化体验"); break; } } //页面加载出现错误,23以上的 @TargetApi(23) @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); switch (error.getErrorCode()) { case 404: //view.loadUrl("加载一个错误页面提示,优化体验"); break; } } //https错误 @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); } }); } /** * 设置webView的辅助功能,如页面加载进度,title,图标,js弹框等 */ void setWebViewChromeClient() { mWebView.setWebChromeClient(new WebChromeClient() { //页面加载进度 @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); } //获取标题 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); } //获取图标 @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } //是否支持页面中的js警告弹出框 @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Toast.makeText(APIWebViewActivity.this, message, Toast.LENGTH_SHORT).show(); return super.onJsAlert(view, url, message, result); } //是否支持页面中的js确定弹出框 @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { return super.onJsConfirm(view, url, message, result); } //是否支持页面中的js输入弹出框 @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { /** * 有时候,为了安全考虑,js的参数回调,会通过这类地方回调回来,然后不弹出框。 */ if(resolveJSPrompt(message)) { return true; } return super.onJsPrompt(view, url, message, defaultValue, result); } }); } /** * 加载url */ void loadUrl() { // 格式规定为:file:///android_asset/文件名.html mWebView.loadUrl("file:///android_asset/localHtml.html"); //方式1. 加载远程网页: //mWebView.loadUrl("http://www.google.com/"); //方式2:加载asset的html页面 //mWebView.loadUrl("file:///android_asset/localHtml.html"); //方式3:加载手机SD的html页面 //mWebView.loadUrl("file:///mnt/sdcard/database/taobao.html"); } /** * 执行网页中的js方法 */ void callJsFunction() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mWebView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { //接受返回值 } }); } else { mWebView.loadUrl("javascript:callJS()"); } } /** * js与web交互1 * js 与 原生交互接口 */ private class JsCallAndroidInterface { //@JavascriptInterface注解方法,js端调用,4.2以后安全 //4.2以前,当JS拿到Android这个对象后,就可以调用这个Android对象中所有的方法,包括系统类(java.lang.Runtime 类),从而进行任意代码执行。 @JavascriptInterface public void callback(String msg) { Toast.makeText(APIWebViewActivity.this, "JS方法回调到web了 :" + msg, Toast.LENGTH_SHORT).show(); } } /** * js与web交互2 * 通过 shouldOverrideUrlLoading 与 js交互 */ private boolean resolveShouldLoadLogic(String url) { Uri uri = Uri.parse(url); //解析协议 if (uri.getScheme().equals("js")) { if (uri.getAuthority().equals("Authority")) { //你还可以继续接续参数 //Set<String> collection = uri.getQueryParameterNames(); Toast.makeText(APIWebViewActivity.this, "JS 2方法回调到web了", Toast.LENGTH_SHORT).show(); } return true; } return false; } /** * js与web交互3 * 通过 onJsPrompt 与 js交互 */ private boolean resolveJSPrompt(String message) { Uri uri = Uri.parse(message); if ( uri.getScheme().equals("js")) { if (uri.getAuthority().equals("Authority")) { //Set<String> collection = uri.getQueryParameterNames(); //参数result:代表消息框的返回值(输入值) //result.confirm("JS 3方法回调到web"); Toast.makeText(APIWebViewActivity.this, "JS 3方法回调到web了", Toast.LENGTH_SHORT).show(); } return true; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.call_js_function: callJsFunction(); break; } } }
CarGuo/CustomActionWebView
app/src/main/java/com/shuyu/APIWebViewActivity.java
3,037
//设置自适应屏幕,两者合用
line_comment
zh-cn
package com.shuyu; import android.annotation.TargetApi; import android.graphics.Bitmap; import android.net.Uri; import android.net.http.SslError; import android.os.Build; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.webkit.DownloadListener; import android.webkit.JavascriptInterface; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.SslErrorHandler; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebResourceError; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Button; import android.widget.FrameLayout; import android.widget.Toast; import java.util.Set; /** * 演示WebView中的Api说明、js交互的方法,还有注意事项 * <p> * 1、内存泄漏防备 * 2、配置webView * 3、页面加载开始,错误,拦截请求,接受Error等 * 4、页面加载进度,title,图标,js弹框等 * 5、js交互与安全 */ public class APIWebViewActivity extends AppCompatActivity implements View.OnClickListener { FrameLayout mRootLayout; WebView mWebView; Button mButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_api_webview); findViewById(R.id.call_js_function).setOnClickListener(this); //添加webView到布局中 addWebViewToLayout(); //set webView Setting setWebView(); //set webView Client setWebClient(); //set webView chrome setWebViewChromeClient(); //load web loadUrl(); } /** * 主动清空销毁来避免内存泄漏 */ @Override protected void onDestroy() { if (mWebView != null) { mWebView.loadDataWithBaseURL(null, "", "text/html", "utf-8", null); mWebView.clearHistory(); ((ViewGroup) mWebView.getParent()).removeView(mWebView); mWebView.destroy(); mWebView = null; } super.onDestroy(); } /** * 1、不在xml中定义Webview,而是在需要的时候在Activity中创建 * 使用getApplicationgContext(),避免内存泄漏。 * <p> * 2、当然,你也可以配置webView所在Activity, * 在AndroidManifest中的进程为:android:process=":remote" * 避免泄漏影响主进程 **/ void addWebViewToLayout() { mRootLayout = (FrameLayout) findViewById(R.id.js_root_layout); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); mWebView = new WebView(getApplicationContext()); mWebView.setLayoutParams(params); mRootLayout.addView(mWebView); } /** * 配置webView */ void setWebView() { //声明WebSettings子类 WebSettings webSettings = mWebView.getSettings(); //支持Javascript交互 webSettings.setJavaScriptEnabled(true); //设置 <SUF> webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小 webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小 //缩放操作 webSettings.setSupportZoom(true); //支持缩放,默认为true。是下面那个的前提。 webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false,则该WebView不可缩放 webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件 //其他细节操作 //webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK); //关闭webview中缓存 webSettings.setAllowFileAccess(true); //设置可以访问文件 //对于不需要使用 file 协议的应用,禁用 file 协议;防止文件泄密,file协议即是file:// //webSettings.setAllowFileAccess(false); //webSettings.setAllowFileAccessFromFileURLs(false); //webSettings.setAllowUniversalAccessFromFileURLs(false); webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口 webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片 webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式 mWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { //网页中触发下载动作 } }); //增加js交互接口 mWebView.addJavascriptInterface(new JsCallAndroidInterface(), "JSCallBackInterface"); } /** * 设置webView的Client,如页面加载开始,错误,拦截请求,接受Error等 */ void setWebClient() { mWebView.setWebViewClient(new WebViewClient() { //拦截页面中的url加载,21以下的 @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (resolveShouldLoadLogic(url)) { return true; } return super.shouldOverrideUrlLoading(view, url); } //拦截页面中的url加载,21以上的 @TargetApi(21) @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { if (resolveShouldLoadLogic(request.getUrl().toString())) { return true; } return super.shouldOverrideUrlLoading(view, request); } //页面开始加载 @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } //页面加载完成 @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); } //页面加载每一个资源,如图片 @Override public void onLoadResource(WebView view, String url) { super.onLoadResource(view, url); } //监听WebView发出的请求并做相应的处理 //浏览器的渲染以及资源加载都是在一个线程中,如果在shouldInterceptRequest处理时间过长,WebView界面就会阻塞 //21以下的 @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { return super.shouldInterceptRequest(view, url); } //监听WebView发出的请求并做相应的处理 //浏览器的渲染以及资源加载都是在一个线程中,如果在shouldInterceptRequest处理时间过长,WebView界面就会阻塞 //21以上的 @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { return super.shouldInterceptRequest(view, request); } //页面加载出现错误,23以下的 @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); switch (errorCode) { case 404: //view.loadUrl("加载一个错误页面提示,优化体验"); break; } } //页面加载出现错误,23以上的 @TargetApi(23) @Override public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) { super.onReceivedError(view, request, error); switch (error.getErrorCode()) { case 404: //view.loadUrl("加载一个错误页面提示,优化体验"); break; } } //https错误 @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { super.onReceivedSslError(view, handler, error); } }); } /** * 设置webView的辅助功能,如页面加载进度,title,图标,js弹框等 */ void setWebViewChromeClient() { mWebView.setWebChromeClient(new WebChromeClient() { //页面加载进度 @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); } //获取标题 @Override public void onReceivedTitle(WebView view, String title) { super.onReceivedTitle(view, title); } //获取图标 @Override public void onReceivedIcon(WebView view, Bitmap icon) { super.onReceivedIcon(view, icon); } //是否支持页面中的js警告弹出框 @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Toast.makeText(APIWebViewActivity.this, message, Toast.LENGTH_SHORT).show(); return super.onJsAlert(view, url, message, result); } //是否支持页面中的js确定弹出框 @Override public boolean onJsConfirm(WebView view, String url, String message, JsResult result) { return super.onJsConfirm(view, url, message, result); } //是否支持页面中的js输入弹出框 @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) { /** * 有时候,为了安全考虑,js的参数回调,会通过这类地方回调回来,然后不弹出框。 */ if(resolveJSPrompt(message)) { return true; } return super.onJsPrompt(view, url, message, defaultValue, result); } }); } /** * 加载url */ void loadUrl() { // 格式规定为:file:///android_asset/文件名.html mWebView.loadUrl("file:///android_asset/localHtml.html"); //方式1. 加载远程网页: //mWebView.loadUrl("http://www.google.com/"); //方式2:加载asset的html页面 //mWebView.loadUrl("file:///android_asset/localHtml.html"); //方式3:加载手机SD的html页面 //mWebView.loadUrl("file:///mnt/sdcard/database/taobao.html"); } /** * 执行网页中的js方法 */ void callJsFunction() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { mWebView.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() { @Override public void onReceiveValue(String value) { //接受返回值 } }); } else { mWebView.loadUrl("javascript:callJS()"); } } /** * js与web交互1 * js 与 原生交互接口 */ private class JsCallAndroidInterface { //@JavascriptInterface注解方法,js端调用,4.2以后安全 //4.2以前,当JS拿到Android这个对象后,就可以调用这个Android对象中所有的方法,包括系统类(java.lang.Runtime 类),从而进行任意代码执行。 @JavascriptInterface public void callback(String msg) { Toast.makeText(APIWebViewActivity.this, "JS方法回调到web了 :" + msg, Toast.LENGTH_SHORT).show(); } } /** * js与web交互2 * 通过 shouldOverrideUrlLoading 与 js交互 */ private boolean resolveShouldLoadLogic(String url) { Uri uri = Uri.parse(url); //解析协议 if (uri.getScheme().equals("js")) { if (uri.getAuthority().equals("Authority")) { //你还可以继续接续参数 //Set<String> collection = uri.getQueryParameterNames(); Toast.makeText(APIWebViewActivity.this, "JS 2方法回调到web了", Toast.LENGTH_SHORT).show(); } return true; } return false; } /** * js与web交互3 * 通过 onJsPrompt 与 js交互 */ private boolean resolveJSPrompt(String message) { Uri uri = Uri.parse(message); if ( uri.getScheme().equals("js")) { if (uri.getAuthority().equals("Authority")) { //Set<String> collection = uri.getQueryParameterNames(); //参数result:代表消息框的返回值(输入值) //result.confirm("JS 3方法回调到web"); Toast.makeText(APIWebViewActivity.this, "JS 3方法回调到web了", Toast.LENGTH_SHORT).show(); } return true; } return false; } @Override public void onClick(View v) { switch (v.getId()) { case R.id.call_js_function: callJsFunction(); break; } } }
1
14
1
1495_23
package com.example.gsyvideoplayer; import android.annotation.TargetApi; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.transition.Transition; import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.ViewCompat; import com.example.gsyvideoplayer.databinding.ActivityPlayBinding; import com.example.gsyvideoplayer.databinding.ActivityPlayTvBinding; import com.example.gsyvideoplayer.listener.OnTransitionListener; import com.example.gsyvideoplayer.model.SwitchVideoModel; import com.shuyu.gsyvideoplayer.GSYVideoManager; import com.shuyu.gsyvideoplayer.utils.OrientationUtils; import java.util.ArrayList; import java.util.List; /** * 单独的视频播放页面 * Created by Bill on 2023/7/25. */ public class PlayTVActivity extends AppCompatActivity { public final static String IMG_TRANSITION = "IMG_TRANSITION"; public final static String TRANSITION = "TRANSITION"; OrientationUtils orientationUtils; private boolean isTransition; private Transition transition; private ActivityPlayTvBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityPlayTvBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); isTransition = getIntent().getBooleanExtra(TRANSITION, false); init(); } private void init() { String url = "https://res.exexm.com/cw_145225549855002"; //String url = "http://7xse1z.com1.z0.glb.clouddn.com/1491813192"; //需要路径的 //videoPlayer.setUp(url, true, new File(FileUtils.getPath()), ""); //借用了jjdxm_ijkplayer的URL String source1 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear1/prog_index.m3u8"; String name = "普通"; SwitchVideoModel switchVideoModel = new SwitchVideoModel(name, source1); String source2 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear3/prog_index.m3u8"; String name2 = "清晰"; SwitchVideoModel switchVideoModel2 = new SwitchVideoModel(name2, source2); List<SwitchVideoModel> list = new ArrayList<>(); list.add(switchVideoModel); list.add(switchVideoModel2); binding.videoPlayerTv.setUp(list.get(0).getUrl(), false, "测试视频"); //增加封面 ImageView imageView = new ImageView(this); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.mipmap.xxx1); binding.videoPlayerTv.setThumbImageView(imageView); //增加title binding.videoPlayerTv.getTitleTextView().setVisibility(View.VISIBLE); //videoPlayer.setShowPauseCover(false); //videoPlayer.setSpeed(2f); //设置返回键 binding.videoPlayerTv.getBackButton().setVisibility(View.VISIBLE); //设置旋转 orientationUtils = new OrientationUtils(this, binding.videoPlayerTv); //设置全屏按键功能,这是使用的是选择屏幕,而不是全屏 binding.videoPlayerTv.getFullscreenButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ------- !!!如果不需要旋转屏幕,可以不调用!!!------- // 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false) orientationUtils.resolveByClick(); } }); //videoPlayer.setBottomProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setDialogVolumeProgressBar(getResources().getDrawable(R.drawable.video_new_volume_progress_bg)); //videoPlayer.setDialogProgressBar(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setBottomShowProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_seekbar_progress), //getResources().getDrawable(R.drawable.video_new_seekbar_thumb)); //videoPlayer.setDialogProgressColor(getResources().getColor(R.color.colorAccent), -11); //是否可以滑动调整 binding.videoPlayerTv.setIsTouchWiget(true); //设置返回按键功能 binding.videoPlayerTv.getBackButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); //过渡动画 initTransition(); } @Override protected void onPause() { super.onPause(); binding.videoPlayerTv.onVideoPause(); } @Override protected void onResume() { super.onResume(); binding.videoPlayerTv.onVideoResume(); } @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected void onDestroy() { super.onDestroy(); if (orientationUtils != null) orientationUtils.releaseListener(); } @Override public void onBackPressed() { //先返回正常状态 if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { binding.videoPlayerTv.getFullscreenButton().performClick(); return; } //释放所有 binding.videoPlayerTv.setVideoAllCallBack(null); GSYVideoManager.releaseAllVideos(); if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { super.onBackPressed(); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); overridePendingTransition(androidx.appcompat.R.anim.abc_fade_in, androidx.appcompat.R.anim.abc_fade_out); } }, 500); } } private void initTransition() { if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { postponeEnterTransition(); ViewCompat.setTransitionName(binding.videoPlayerTv, IMG_TRANSITION); addTransitionListener(); startPostponedEnterTransition(); } else { binding.videoPlayerTv.startPlayLogic(); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean addTransitionListener() { transition = getWindow().getSharedElementEnterTransition(); if (transition != null) { transition.addListener(new OnTransitionListener() { @Override public void onTransitionEnd(Transition transition) { super.onTransitionEnd(transition); binding.videoPlayerTv.startPlayLogic(); transition.removeListener(this); } }); return true; } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { binding.videoPlayerTv.onKeyDown(keyCode,event); return super.onKeyDown(keyCode, event); } }
CarGuo/GSYVideoPlayer
app/src/main/java/com/example/gsyvideoplayer/PlayTVActivity.java
1,745
//是否可以滑动调整
line_comment
zh-cn
package com.example.gsyvideoplayer; import android.annotation.TargetApi; import android.content.pm.ActivityInfo; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.transition.Transition; import android.view.KeyEvent; import android.view.View; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import androidx.core.view.ViewCompat; import com.example.gsyvideoplayer.databinding.ActivityPlayBinding; import com.example.gsyvideoplayer.databinding.ActivityPlayTvBinding; import com.example.gsyvideoplayer.listener.OnTransitionListener; import com.example.gsyvideoplayer.model.SwitchVideoModel; import com.shuyu.gsyvideoplayer.GSYVideoManager; import com.shuyu.gsyvideoplayer.utils.OrientationUtils; import java.util.ArrayList; import java.util.List; /** * 单独的视频播放页面 * Created by Bill on 2023/7/25. */ public class PlayTVActivity extends AppCompatActivity { public final static String IMG_TRANSITION = "IMG_TRANSITION"; public final static String TRANSITION = "TRANSITION"; OrientationUtils orientationUtils; private boolean isTransition; private Transition transition; private ActivityPlayTvBinding binding; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); binding = ActivityPlayTvBinding.inflate(getLayoutInflater()); View rootView = binding.getRoot(); setContentView(rootView); isTransition = getIntent().getBooleanExtra(TRANSITION, false); init(); } private void init() { String url = "https://res.exexm.com/cw_145225549855002"; //String url = "http://7xse1z.com1.z0.glb.clouddn.com/1491813192"; //需要路径的 //videoPlayer.setUp(url, true, new File(FileUtils.getPath()), ""); //借用了jjdxm_ijkplayer的URL String source1 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear1/prog_index.m3u8"; String name = "普通"; SwitchVideoModel switchVideoModel = new SwitchVideoModel(name, source1); String source2 = "http://devimages.apple.com.edgekey.net/streaming/examples/bipbop_4x3/gear3/prog_index.m3u8"; String name2 = "清晰"; SwitchVideoModel switchVideoModel2 = new SwitchVideoModel(name2, source2); List<SwitchVideoModel> list = new ArrayList<>(); list.add(switchVideoModel); list.add(switchVideoModel2); binding.videoPlayerTv.setUp(list.get(0).getUrl(), false, "测试视频"); //增加封面 ImageView imageView = new ImageView(this); imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); imageView.setImageResource(R.mipmap.xxx1); binding.videoPlayerTv.setThumbImageView(imageView); //增加title binding.videoPlayerTv.getTitleTextView().setVisibility(View.VISIBLE); //videoPlayer.setShowPauseCover(false); //videoPlayer.setSpeed(2f); //设置返回键 binding.videoPlayerTv.getBackButton().setVisibility(View.VISIBLE); //设置旋转 orientationUtils = new OrientationUtils(this, binding.videoPlayerTv); //设置全屏按键功能,这是使用的是选择屏幕,而不是全屏 binding.videoPlayerTv.getFullscreenButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // ------- !!!如果不需要旋转屏幕,可以不调用!!!------- // 不需要屏幕旋转,还需要设置 setNeedOrientationUtils(false) orientationUtils.resolveByClick(); } }); //videoPlayer.setBottomProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setDialogVolumeProgressBar(getResources().getDrawable(R.drawable.video_new_volume_progress_bg)); //videoPlayer.setDialogProgressBar(getResources().getDrawable(R.drawable.video_new_progress)); //videoPlayer.setBottomShowProgressBarDrawable(getResources().getDrawable(R.drawable.video_new_seekbar_progress), //getResources().getDrawable(R.drawable.video_new_seekbar_thumb)); //videoPlayer.setDialogProgressColor(getResources().getColor(R.color.colorAccent), -11); //是否 <SUF> binding.videoPlayerTv.setIsTouchWiget(true); //设置返回按键功能 binding.videoPlayerTv.getBackButton().setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); //过渡动画 initTransition(); } @Override protected void onPause() { super.onPause(); binding.videoPlayerTv.onVideoPause(); } @Override protected void onResume() { super.onResume(); binding.videoPlayerTv.onVideoResume(); } @TargetApi(Build.VERSION_CODES.KITKAT) @Override protected void onDestroy() { super.onDestroy(); if (orientationUtils != null) orientationUtils.releaseListener(); } @Override public void onBackPressed() { //先返回正常状态 if (orientationUtils.getScreenType() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) { binding.videoPlayerTv.getFullscreenButton().performClick(); return; } //释放所有 binding.videoPlayerTv.setVideoAllCallBack(null); GSYVideoManager.releaseAllVideos(); if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { super.onBackPressed(); } else { new Handler().postDelayed(new Runnable() { @Override public void run() { finish(); overridePendingTransition(androidx.appcompat.R.anim.abc_fade_in, androidx.appcompat.R.anim.abc_fade_out); } }, 500); } } private void initTransition() { if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { postponeEnterTransition(); ViewCompat.setTransitionName(binding.videoPlayerTv, IMG_TRANSITION); addTransitionListener(); startPostponedEnterTransition(); } else { binding.videoPlayerTv.startPlayLogic(); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean addTransitionListener() { transition = getWindow().getSharedElementEnterTransition(); if (transition != null) { transition.addListener(new OnTransitionListener() { @Override public void onTransitionEnd(Transition transition) { super.onTransitionEnd(transition); binding.videoPlayerTv.startPlayLogic(); transition.removeListener(this); } }); return true; } return false; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { binding.videoPlayerTv.onKeyDown(keyCode,event); return super.onKeyDown(keyCode, event); } }
1
10
1
55285_2
package scut.carson_ho.androidinterview.AlgorithmLearning; /** * Created by Carson_Ho on 17/11/23. */ public class Exam_56_1 { /** * 解题算法 */ public static int findOnceNumber(int[] intArray) throws Exception { // 判断输入数据的合法性 if (intArray == null || intArray.length < 1) { System.out.println("数组为空或者长度不足"); return 0; } // 将和的结果存储到1个大小 = 32的数组中 int[] bitSum = new int[32]; // 1. 将数组所有数字的二进制表示的每1位都加起来 // 将和的结果都放到数组中 for (int i : intArray) { int bitMask = 1; for (int j = 31; j >= 0; --j){ int bit = i & bitMask; if (bit != 0){ bitSum[j] += 1; } bitMask = bitMask << 1; } } //2. 对每1位的和 都对3取余 int result = 0; for (int i = 0; i < 32; i++){ result = result << 1; // 若能被3整除(余数 = 0),则说明包含该位数的数字出现了3次,即 只出现1次的数字二进制表示中对应那位 = 0 // 若不能被3整除(余数 = 1),则说明包含该位数的数字出现了1次,即 只出现1次的数字二进制表示中对应那位 = 1 result += bitSum[i] % 3; } return result; } /** * 测试用例 */ public static void main(String[] args) throws Exception { int[] array1 = {2,4,2,5,2,5,5}; System.out.println("数组中唯一出现一次数字是:" + findOnceNumber(array1)); } }
Carson-Ho/AndroidLearning
app/src/main/java/scut/carson_ho/androidinterview/AlgorithmLearning/Exam_56_1.java
493
// 判断输入数据的合法性
line_comment
zh-cn
package scut.carson_ho.androidinterview.AlgorithmLearning; /** * Created by Carson_Ho on 17/11/23. */ public class Exam_56_1 { /** * 解题算法 */ public static int findOnceNumber(int[] intArray) throws Exception { // 判断 <SUF> if (intArray == null || intArray.length < 1) { System.out.println("数组为空或者长度不足"); return 0; } // 将和的结果存储到1个大小 = 32的数组中 int[] bitSum = new int[32]; // 1. 将数组所有数字的二进制表示的每1位都加起来 // 将和的结果都放到数组中 for (int i : intArray) { int bitMask = 1; for (int j = 31; j >= 0; --j){ int bit = i & bitMask; if (bit != 0){ bitSum[j] += 1; } bitMask = bitMask << 1; } } //2. 对每1位的和 都对3取余 int result = 0; for (int i = 0; i < 32; i++){ result = result << 1; // 若能被3整除(余数 = 0),则说明包含该位数的数字出现了3次,即 只出现1次的数字二进制表示中对应那位 = 0 // 若不能被3整除(余数 = 1),则说明包含该位数的数字出现了1次,即 只出现1次的数字二进制表示中对应那位 = 1 result += bitSum[i] % 3; } return result; } /** * 测试用例 */ public static void main(String[] args) throws Exception { int[] array1 = {2,4,2,5,2,5,5}; System.out.println("数组中唯一出现一次数字是:" + findOnceNumber(array1)); } }
1
13
1
43679_9
package scut.carson_ho.shootatoffer; import java.util.ArrayList; /** * Created by Carson_Ho on 17/11/24. */ public class Exam_57_1 { /** * 解题算法 */ private static ArrayList<ArrayList<Integer>> findContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> result =new ArrayList<ArrayList<Integer>>(); // 用于存储结果 // 判断输入数据的合法性 if (sum < 3){ System.out.println("输入的数据不合法"); return result; } // 1. 用2个指针分别指向当前序列的最小值 & 最大值 // 指针1(small ): 初始化指向1 // 指针2(big ): 初始化指向2 int start = 1; int end = 2; int curSum = start + end; // 注:对于连续序列求和,考虑到每次操作前后的序列大部分数字相同,只是增加 / 减少1个数字 // 故此处不采用循环求和,而是采用在前1个序列的基础上进行操作,从而减少不必要的运算,提高效率 int mid = (sum + 1) / 2; // 2. 计算 指针1 ~ 指针2 之间数字的和(m) while (start < mid) { // 2.1 若m = 题目输入的s,即 指针1 ~ 指针2 之间数字 即为所求 = 1组解 // 则:输出指针1 ~ 指针2 之间的数字序列、指针2 往后移1位、重复步骤2,继续求解 if (curSum == sum) { // 求和 ArrayList<Integer> list = new ArrayList<>(); for (int i = start; i <= end; i++) { list.add(i); } result.add(list); } // 2.2 若m > 题目输入的s // 则:指针p1后移1位、重复步骤2,直到指针1(small) > (s+1)/2 为止 while (curSum > sum && start < mid) { curSum -= start; start++; if (curSum == sum) { // 求和 ArrayList<Integer> list = new ArrayList<>(); for (int i = start; i <= end; i++) { list.add(i); } result.add(list); } } // 2.3 若m < 题目输入的s // 则,指针p2后移1位、指针1 ~ 指针2 之间数字多1个使得 m 变大 靠近 s,重复步骤2 end++; curSum += end; } return result; } /** * 测试用例 */ public static void main(String[] args){ // 功能测试 System.out.println("功能测试"); System.out.println(findContinuousSequence(15)); // 边界值输入测试:连续序列最小和 = 3 System.out.println("边界值测试"); System.out.println(findContinuousSequence(3)); } }
Carson-Ho/ShootAtOffer
app/src/main/java/scut/carson_ho/shootatoffer/Exam_57_1.java
757
// 2. 计算 指针1 ~ 指针2 之间数字的和(m)
line_comment
zh-cn
package scut.carson_ho.shootatoffer; import java.util.ArrayList; /** * Created by Carson_Ho on 17/11/24. */ public class Exam_57_1 { /** * 解题算法 */ private static ArrayList<ArrayList<Integer>> findContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> result =new ArrayList<ArrayList<Integer>>(); // 用于存储结果 // 判断输入数据的合法性 if (sum < 3){ System.out.println("输入的数据不合法"); return result; } // 1. 用2个指针分别指向当前序列的最小值 & 最大值 // 指针1(small ): 初始化指向1 // 指针2(big ): 初始化指向2 int start = 1; int end = 2; int curSum = start + end; // 注:对于连续序列求和,考虑到每次操作前后的序列大部分数字相同,只是增加 / 减少1个数字 // 故此处不采用循环求和,而是采用在前1个序列的基础上进行操作,从而减少不必要的运算,提高效率 int mid = (sum + 1) / 2; // 2. <SUF> while (start < mid) { // 2.1 若m = 题目输入的s,即 指针1 ~ 指针2 之间数字 即为所求 = 1组解 // 则:输出指针1 ~ 指针2 之间的数字序列、指针2 往后移1位、重复步骤2,继续求解 if (curSum == sum) { // 求和 ArrayList<Integer> list = new ArrayList<>(); for (int i = start; i <= end; i++) { list.add(i); } result.add(list); } // 2.2 若m > 题目输入的s // 则:指针p1后移1位、重复步骤2,直到指针1(small) > (s+1)/2 为止 while (curSum > sum && start < mid) { curSum -= start; start++; if (curSum == sum) { // 求和 ArrayList<Integer> list = new ArrayList<>(); for (int i = start; i <= end; i++) { list.add(i); } result.add(list); } } // 2.3 若m < 题目输入的s // 则,指针p2后移1位、指针1 ~ 指针2 之间数字多1个使得 m 变大 靠近 s,重复步骤2 end++; curSum += end; } return result; } /** * 测试用例 */ public static void main(String[] args){ // 功能测试 System.out.println("功能测试"); System.out.println(findContinuousSequence(15)); // 边界值输入测试:连续序列最小和 = 3 System.out.println("边界值测试"); System.out.println(findContinuousSequence(3)); } }
1
28
1
9941_11
package 爬虫.模拟登录.模拟登录; import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.*; import java.net.*; import java.util.*; import java.util.List; // http://xk.henu.edu.cn/cas/login.action 教务系统网页访问返回信息. // http://xk.henu.edu.cn/cas/logon.action 点击登录后发送请求的连接,登录成功与否,根据此连接请求的返回信息确定. public class Henu extends JFrame { // main private static JLabel imageLabel ; private static Button button = new Button() ; private static TextField jusername = new TextField(); private static TextField jpassword = new TextField(); private static TextField randnumber = new TextField(); private static Frame frame = new Frame(); private static CloseableHttpClient closeableHttpClient = HttpClients.createDefault() ; public Henu() throws Exception { setSessionid(); this.setLayout(null); this.setBounds(120,80,500,130); jusername.setBounds(0,10,130,30); jpassword.setBounds(140,10,130,30); randnumber.setBounds(280,10,130,30); button.setLabel("Login"); button.setBounds(220,50,100,40); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { username = jusername.getText(); password = jpassword.getText() ; randNumber = randnumber.getText(); try { Login(); } catch (Exception e1) { e1.printStackTrace(); } } }); this.add(button); this.add(jusername); this.add(jpassword); this.add(randnumber); loadValidateCode(closeableHttpClient) ; imageLabel.setBounds(400,0,100,40); this.add(imageLabel) ; this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(-1); } }); this.setResizable(false); this.setVisible(true); } private static void loadValidateCode(CloseableHttpClient client) { String url = null; try { url = SiteConfig.BASIC_VALIDATE_CODE_URL + "?dateTime=" + URLEncoder.encode(new Date().toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } HttpGet get = new HttpGet(url); get.addHeader("Cookie","JSESSIONID="+sessionid); try (CloseableHttpResponse response = client.execute(get)) { ByteOutputStream byteOutputStream = new ByteOutputStream(); byteOutputStream.write(response.getEntity().getContent()); Image img = ImageIO.read(new ByteArrayInputStream(byteOutputStream.getBytes())); ImageIcon icon = new ImageIcon(img); imageLabel = new JLabel(icon); byteOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String []args) throws Exception{ System.out.println("http://xk.henu.edu.cn/cas/genValidateCode?dateTime=Mon%20Jul%2016%202018%2013:23:56%20GMT+0800%20(%D6%D0%B9%FA%B1%EA%D7%BC%CA%B1%BC%E4)"); Henu henu = new Henu(); } // 用户名 : username = base64encode(username+";;"+_sessionid); // 用户名是根据: 学号 加 两个冒号 加 sessionid值 后的字符串 ,再经过base64加密. // 学号+ " ::" + sessionid // sessionid值 是 在打开教务系统网站时(还没有点击登录),给定的cookie. private static String username = "" ; private static String sessionid = "" ; // 密码 密码是对密码进行md5加密,再对验证码进行md5加密 ,再对他们加密过后的字符串进行一次md5加密 // md5 ( md5(password) + md5(randnumber.toLowerCase()) ); private static String password = "" ; // 验证码 :" http://xk.henu.edu.cn/cas/genValidateCode?dateTime= " 后接一段字符串 就是验证码图片的链接 ,后接的字符串是根据当前时间来确定的 private static String randNumber = "" ; // 访问: public static void setSessionid() throws Exception { // 连接登录界面(还没有点击登录的那个界面) URL url = new URL("http://xk.henu.edu.cn/cas/login.action") ; HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); // 获取响应头,从中获取 Set-Cookie,再从Cookie中获取Sessionid(这个值与用户名有关); String CookieData = httpURLConnection.getHeaderField("Set-Cookie") ; // Set-Cookie 内容一般是 JSESSIONID=2DE25086A20F71F40694C938A6DF27D3.kingo154; Path=/ 这种 // 真正要取的是 2DE25086A20F71F40694C938A6DF27D3.kingo154 // 不过后面可能跟了 ; Path=/ 这种,要把这些去掉 // 所需的 sessionid 就是 JSESSIONID 对应的字符串 String arr[] = CookieData.split(";") ; arr[0] = arr[0].replaceAll("JSESSIONID=",""); // 此时 arr[0] 就是 JSESSIONID 的内容了 sessionid = arr[0] ; System.out.println("sessionid is :"+sessionid); } // 登录 : 在所以信息获取完成后,进行登录 public static void Login() throws Exception { // 获取验证码部分没有写 randNumber = jusername.getText(); // 设置点击登录按钮之后,http://xk.henu.edu.cn/cas/logon.action 发送往服务器的表单信息 /* 表单内容 : 表单不是有 value 和 key 值 吗 value 的值 是 根据 验证码 参考 表单数据.png(根目录下面) 比如 输入的验证码是8968 那么 用户名和密码 相关的表单数据 value 就是 _u + 验证码 _u8968: MTEyMTI7O0NFQjc5M0Y2NERDQzNBMjZCOTU1RERBNTYyMzBGREJFLmtpbmdvMTU0 (加密后的) _p8968: 0e90199d89318059c8b6adbbf6e58370 (加密后的) randnumber: 验证码(无需处理) isPasswordPolicy:1 (这个值虽然不知道是干什么的,但是设置为 1 ) */ //密码处理: password = MD5.string2MD5(MD5.string2MD5(password)+MD5.string2MD5(randNumber)) ; String p_username = "_u" + randNumber; String p_password = "_p" + randNumber; // 用户名 base64加密 username = BASE64.toBase64(username + ";;" + sessionid); // 发送请求 : System.out.println("p_username :"+username); System.out.println("p_password :"+password); // _u1234: MTYxMDEyMDAyMDs7RTgzNkQ1NkUwQUJCNDUwNTNFNjI1NTU1OEJFQTI1NTUua2luZ28xNTQ= // _p1234: 8b62ff217e50dc469a4d0f75fca19e5d HttpPost httpPost = new HttpPost("http://xk.henu.edu.cn/cas/logon.action"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(p_username, username)); nvps.add(new BasicNameValuePair(p_password, password)); nvps.add(new BasicNameValuePair("randnumber", randNumber)); // 此处验证码暂为空 nvps.add(new BasicNameValuePair("isPasswordPolicy", "1")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = closeableHttpClient.execute(httpPost); HttpEntity he = response.getEntity(); String index = EntityUtils.toString(he); // 打印返回信息 // 401 验证码输入错误 // 402 帐号或密码有误 // 登录成功 好像是5000 ...好像 System.out.println(index) ; } }
CasterWx/java-Crawler
src/爬虫/模拟登录/模拟登录/Henu.java
2,355
// 访问:
line_comment
zh-cn
package 爬虫.模拟登录.模拟登录; import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.*; import java.net.*; import java.util.*; import java.util.List; // http://xk.henu.edu.cn/cas/login.action 教务系统网页访问返回信息. // http://xk.henu.edu.cn/cas/logon.action 点击登录后发送请求的连接,登录成功与否,根据此连接请求的返回信息确定. public class Henu extends JFrame { // main private static JLabel imageLabel ; private static Button button = new Button() ; private static TextField jusername = new TextField(); private static TextField jpassword = new TextField(); private static TextField randnumber = new TextField(); private static Frame frame = new Frame(); private static CloseableHttpClient closeableHttpClient = HttpClients.createDefault() ; public Henu() throws Exception { setSessionid(); this.setLayout(null); this.setBounds(120,80,500,130); jusername.setBounds(0,10,130,30); jpassword.setBounds(140,10,130,30); randnumber.setBounds(280,10,130,30); button.setLabel("Login"); button.setBounds(220,50,100,40); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { username = jusername.getText(); password = jpassword.getText() ; randNumber = randnumber.getText(); try { Login(); } catch (Exception e1) { e1.printStackTrace(); } } }); this.add(button); this.add(jusername); this.add(jpassword); this.add(randnumber); loadValidateCode(closeableHttpClient) ; imageLabel.setBounds(400,0,100,40); this.add(imageLabel) ; this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(-1); } }); this.setResizable(false); this.setVisible(true); } private static void loadValidateCode(CloseableHttpClient client) { String url = null; try { url = SiteConfig.BASIC_VALIDATE_CODE_URL + "?dateTime=" + URLEncoder.encode(new Date().toString(), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } HttpGet get = new HttpGet(url); get.addHeader("Cookie","JSESSIONID="+sessionid); try (CloseableHttpResponse response = client.execute(get)) { ByteOutputStream byteOutputStream = new ByteOutputStream(); byteOutputStream.write(response.getEntity().getContent()); Image img = ImageIO.read(new ByteArrayInputStream(byteOutputStream.getBytes())); ImageIcon icon = new ImageIcon(img); imageLabel = new JLabel(icon); byteOutputStream.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String []args) throws Exception{ System.out.println("http://xk.henu.edu.cn/cas/genValidateCode?dateTime=Mon%20Jul%2016%202018%2013:23:56%20GMT+0800%20(%D6%D0%B9%FA%B1%EA%D7%BC%CA%B1%BC%E4)"); Henu henu = new Henu(); } // 用户名 : username = base64encode(username+";;"+_sessionid); // 用户名是根据: 学号 加 两个冒号 加 sessionid值 后的字符串 ,再经过base64加密. // 学号+ " ::" + sessionid // sessionid值 是 在打开教务系统网站时(还没有点击登录),给定的cookie. private static String username = "" ; private static String sessionid = "" ; // 密码 密码是对密码进行md5加密,再对验证码进行md5加密 ,再对他们加密过后的字符串进行一次md5加密 // md5 ( md5(password) + md5(randnumber.toLowerCase()) ); private static String password = "" ; // 验证码 :" http://xk.henu.edu.cn/cas/genValidateCode?dateTime= " 后接一段字符串 就是验证码图片的链接 ,后接的字符串是根据当前时间来确定的 private static String randNumber = "" ; // 访问 <SUF> public static void setSessionid() throws Exception { // 连接登录界面(还没有点击登录的那个界面) URL url = new URL("http://xk.henu.edu.cn/cas/login.action") ; HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection(); // 获取响应头,从中获取 Set-Cookie,再从Cookie中获取Sessionid(这个值与用户名有关); String CookieData = httpURLConnection.getHeaderField("Set-Cookie") ; // Set-Cookie 内容一般是 JSESSIONID=2DE25086A20F71F40694C938A6DF27D3.kingo154; Path=/ 这种 // 真正要取的是 2DE25086A20F71F40694C938A6DF27D3.kingo154 // 不过后面可能跟了 ; Path=/ 这种,要把这些去掉 // 所需的 sessionid 就是 JSESSIONID 对应的字符串 String arr[] = CookieData.split(";") ; arr[0] = arr[0].replaceAll("JSESSIONID=",""); // 此时 arr[0] 就是 JSESSIONID 的内容了 sessionid = arr[0] ; System.out.println("sessionid is :"+sessionid); } // 登录 : 在所以信息获取完成后,进行登录 public static void Login() throws Exception { // 获取验证码部分没有写 randNumber = jusername.getText(); // 设置点击登录按钮之后,http://xk.henu.edu.cn/cas/logon.action 发送往服务器的表单信息 /* 表单内容 : 表单不是有 value 和 key 值 吗 value 的值 是 根据 验证码 参考 表单数据.png(根目录下面) 比如 输入的验证码是8968 那么 用户名和密码 相关的表单数据 value 就是 _u + 验证码 _u8968: MTEyMTI7O0NFQjc5M0Y2NERDQzNBMjZCOTU1RERBNTYyMzBGREJFLmtpbmdvMTU0 (加密后的) _p8968: 0e90199d89318059c8b6adbbf6e58370 (加密后的) randnumber: 验证码(无需处理) isPasswordPolicy:1 (这个值虽然不知道是干什么的,但是设置为 1 ) */ //密码处理: password = MD5.string2MD5(MD5.string2MD5(password)+MD5.string2MD5(randNumber)) ; String p_username = "_u" + randNumber; String p_password = "_p" + randNumber; // 用户名 base64加密 username = BASE64.toBase64(username + ";;" + sessionid); // 发送请求 : System.out.println("p_username :"+username); System.out.println("p_password :"+password); // _u1234: MTYxMDEyMDAyMDs7RTgzNkQ1NkUwQUJCNDUwNTNFNjI1NTU1OEJFQTI1NTUua2luZ28xNTQ= // _p1234: 8b62ff217e50dc469a4d0f75fca19e5d HttpPost httpPost = new HttpPost("http://xk.henu.edu.cn/cas/logon.action"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair(p_username, username)); nvps.add(new BasicNameValuePair(p_password, password)); nvps.add(new BasicNameValuePair("randnumber", randNumber)); // 此处验证码暂为空 nvps.add(new BasicNameValuePair("isPasswordPolicy", "1")); httpPost.setEntity(new UrlEncodedFormEntity(nvps)); CloseableHttpResponse response = closeableHttpClient.execute(httpPost); HttpEntity he = response.getEntity(); String index = EntityUtils.toString(he); // 打印返回信息 // 401 验证码输入错误 // 402 帐号或密码有误 // 登录成功 好像是5000 ...好像 System.out.println(index) ; } }
0
6
0
62704_1
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Yet Another Pixel Dungeon * Copyright (C) 2015-2016 Considered Hamster * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.consideredhamster.yapdcn.items.herbs; import com.consideredhamster.yapdcn.actors.buffs.BuffActive; import com.consideredhamster.yapdcn.actors.buffs.bonuses.resistances.ColdResistance; import com.consideredhamster.yapdcn.actors.buffs.debuffs.Debuff; import com.consideredhamster.yapdcn.actors.buffs.debuffs.Frozen; import com.consideredhamster.yapdcn.actors.hero.Hero; import com.consideredhamster.yapdcn.items.food.MeatStewed; import com.consideredhamster.yapdcn.items.potions.PotionOfConfusionGas; import com.consideredhamster.yapdcn.items.potions.PotionOfFrigidVapours; import com.consideredhamster.yapdcn.items.potions.PotionOfInvisibility; import com.consideredhamster.yapdcn.visuals.sprites.ItemSprite; import com.consideredhamster.yapdcn.visuals.sprites.ItemSpriteSheet; public class IcecapHerb extends Herb { private static final ItemSprite.Glowing BLUE = new ItemSprite.Glowing( 0x2244FF ); { name = "冰冠草"; image = ItemSpriteSheet.HERB_ICECAP; cooking = MintyMeat.class; message = "吃起来像薄荷一样清新。"; mainPotion = PotionOfFrigidVapours.class; subPotions.add( PotionOfConfusionGas.class ); subPotions.add( PotionOfInvisibility.class ); } private static void onConsume( Hero hero, float duration ) { BuffActive.add( hero, ColdResistance.class, duration ); Debuff.remove( hero, Frozen.class ); } @Override public void onConsume( Hero hero ) { super.onConsume( hero ); onConsume( hero, DURATION_HERB ); } @Override public int price() { return 15 * quantity; } @Override public String desc() { return "冰冠草摸起来有些冷,有镇痛的功效。一些北方部落偶尔会服用冰冠草以防冻伤。\n\n"+ "冰冠草可以炼制_冰雾_、_隐形_、_幻气_药剂。直接服用则会解除_冻伤_状态并获得短时间的_冰寒属性_抗性。"; // return "[临时字串]可精炼冰雾/隐形/幻气药剂,直接食用可移除冻伤状态并获得寒冷抗性(短)"; // return "Icecap herbs feel cold to touch and have some numbing capabilities. Northern " + // "tribes sometimes use Icecap herbs as a food to keep themselves from frigid " + // "climate of their lands." + // "\n\n" + // "These herbs are used to brew potions of _Frigid Vapours_, _Invisibility_ and _Confusion Gas_. " + // "Consuming them will remove _chilling_ and grant a short buff to your _cold_ resistance."; } public static class MintyMeat extends MeatStewed { { name = "清爽炖肉"; spiceGlow = BLUE; message = "薄荷口味的炖肉,真棒!"; } @Override public void onConsume( Hero hero ) { super.onConsume( hero ); IcecapHerb.onConsume( hero, DURATION_MEAT ); } @Override public String desc() { return "一块与_冰冠草_一同煮熟的肉,闻起来有点薄荷味。食用后可解除_冻伤_状态并获得较长的_冰寒属性_抗性。"; // return "[临时字串]直接食用可移除冻伤状态并获得寒冷抗性(长)"; // return "This meat was stewed in a pot with an _Icecap_ herb. It smells somewhat minty. " + // "Consuming it will remove _chilling_ and grant a long buff to your _cold_ resistance."; } @Override public int price() { return 30 * quantity; } } }
CatAzreal/YetAnotherPixelDungeon-CN-master
app/src/main/java/com/consideredhamster/yapdcn/items/herbs/IcecapHerb.java
1,353
// return "[临时字串]可精炼冰雾/隐形/幻气药剂,直接食用可移除冻伤状态并获得寒冷抗性(短)";
line_comment
zh-cn
/* * Pixel Dungeon * Copyright (C) 2012-2015 Oleg Dolya * * Yet Another Pixel Dungeon * Copyright (C) 2015-2016 Considered Hamster * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package com.consideredhamster.yapdcn.items.herbs; import com.consideredhamster.yapdcn.actors.buffs.BuffActive; import com.consideredhamster.yapdcn.actors.buffs.bonuses.resistances.ColdResistance; import com.consideredhamster.yapdcn.actors.buffs.debuffs.Debuff; import com.consideredhamster.yapdcn.actors.buffs.debuffs.Frozen; import com.consideredhamster.yapdcn.actors.hero.Hero; import com.consideredhamster.yapdcn.items.food.MeatStewed; import com.consideredhamster.yapdcn.items.potions.PotionOfConfusionGas; import com.consideredhamster.yapdcn.items.potions.PotionOfFrigidVapours; import com.consideredhamster.yapdcn.items.potions.PotionOfInvisibility; import com.consideredhamster.yapdcn.visuals.sprites.ItemSprite; import com.consideredhamster.yapdcn.visuals.sprites.ItemSpriteSheet; public class IcecapHerb extends Herb { private static final ItemSprite.Glowing BLUE = new ItemSprite.Glowing( 0x2244FF ); { name = "冰冠草"; image = ItemSpriteSheet.HERB_ICECAP; cooking = MintyMeat.class; message = "吃起来像薄荷一样清新。"; mainPotion = PotionOfFrigidVapours.class; subPotions.add( PotionOfConfusionGas.class ); subPotions.add( PotionOfInvisibility.class ); } private static void onConsume( Hero hero, float duration ) { BuffActive.add( hero, ColdResistance.class, duration ); Debuff.remove( hero, Frozen.class ); } @Override public void onConsume( Hero hero ) { super.onConsume( hero ); onConsume( hero, DURATION_HERB ); } @Override public int price() { return 15 * quantity; } @Override public String desc() { return "冰冠草摸起来有些冷,有镇痛的功效。一些北方部落偶尔会服用冰冠草以防冻伤。\n\n"+ "冰冠草可以炼制_冰雾_、_隐形_、_幻气_药剂。直接服用则会解除_冻伤_状态并获得短时间的_冰寒属性_抗性。"; // re <SUF> // return "Icecap herbs feel cold to touch and have some numbing capabilities. Northern " + // "tribes sometimes use Icecap herbs as a food to keep themselves from frigid " + // "climate of their lands." + // "\n\n" + // "These herbs are used to brew potions of _Frigid Vapours_, _Invisibility_ and _Confusion Gas_. " + // "Consuming them will remove _chilling_ and grant a short buff to your _cold_ resistance."; } public static class MintyMeat extends MeatStewed { { name = "清爽炖肉"; spiceGlow = BLUE; message = "薄荷口味的炖肉,真棒!"; } @Override public void onConsume( Hero hero ) { super.onConsume( hero ); IcecapHerb.onConsume( hero, DURATION_MEAT ); } @Override public String desc() { return "一块与_冰冠草_一同煮熟的肉,闻起来有点薄荷味。食用后可解除_冻伤_状态并获得较长的_冰寒属性_抗性。"; // return "[临时字串]直接食用可移除冻伤状态并获得寒冷抗性(长)"; // return "This meat was stewed in a pot with an _Icecap_ herb. It smells somewhat minty. " + // "Consuming it will remove _chilling_ and grant a long buff to your _cold_ resistance."; } @Override public int price() { return 30 * quantity; } } }
0
60
0
40241_11
package com.itheima.mobilesafe.utils; import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.Toast; import com.itheima.mobilesafe.receivers.MyDeviceAdminReceiver; /** * Created by Catherine on 2016/8/24. * Soft-World Inc. * [email protected] */ public class MyAdminManager { private Context ctx; private DevicePolicyManager dpm; private ComponentName myAdmin; public MyAdminManager(Context ctx) { this.ctx = ctx; dpm = (DevicePolicyManager) ctx.getSystemService(Context.DEVICE_POLICY_SERVICE); myAdmin = new ComponentName(ctx, MyDeviceAdminReceiver.class); } /** * 取得管理员权限 */ public void getAdminPermission() { // Launch the activity to have the user enable our admin. Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, myAdmin); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "哥们开启我可以一键锁屏,解放按钮"); Activity activity = (Activity) ctx; activity.startActivityForResult(intent, Constants.REQUEST_CODE_ENABLE_ADMIN); } /** * 锁屏 */ public void lockScreen() { if (dpm.isAdminActive(myAdmin)) dpm.lockNow(); else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 重设锁屏密码 */ public void resetScreenPassword(String password) { if (dpm.isAdminActive(myAdmin)) dpm.resetPassword(password, 0); else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 清除锁屏密码 */ public void unlockScreen() { if (dpm.isAdminActive(myAdmin)) { dpm.resetPassword("", 0); } else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 清除数据 */ public void wipeData() { if (dpm.isAdminActive(myAdmin)) { dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);//清除sd card dpm.wipeData(0);//恢复出厂设置 } else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 卸载步骤: * 1. 先变成普通软件(清除管理员权限) * 2. 正常卸载 */ public void unInstall() { removeAdmin(); Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + ctx.getPackageName())); ctx.startActivity(intent); } /** * 检查管理员权限 * * @return */ public boolean isAdmin() { if (dpm.isAdminActive(myAdmin)) return true; else return false; } /** * 清除管理员权限 */ public void removeAdmin() { if (dpm.isAdminActive(myAdmin)) dpm.removeActiveAdmin(myAdmin); } }
Catherine22/MobileManager
app/src/main/java/com/itheima/mobilesafe/utils/MyAdminManager.java
852
/** * 清除管理员权限 */
block_comment
zh-cn
package com.itheima.mobilesafe.utils; import android.app.Activity; import android.app.admin.DevicePolicyManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.Toast; import com.itheima.mobilesafe.receivers.MyDeviceAdminReceiver; /** * Created by Catherine on 2016/8/24. * Soft-World Inc. * [email protected] */ public class MyAdminManager { private Context ctx; private DevicePolicyManager dpm; private ComponentName myAdmin; public MyAdminManager(Context ctx) { this.ctx = ctx; dpm = (DevicePolicyManager) ctx.getSystemService(Context.DEVICE_POLICY_SERVICE); myAdmin = new ComponentName(ctx, MyDeviceAdminReceiver.class); } /** * 取得管理员权限 */ public void getAdminPermission() { // Launch the activity to have the user enable our admin. Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN); intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, myAdmin); intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "哥们开启我可以一键锁屏,解放按钮"); Activity activity = (Activity) ctx; activity.startActivityForResult(intent, Constants.REQUEST_CODE_ENABLE_ADMIN); } /** * 锁屏 */ public void lockScreen() { if (dpm.isAdminActive(myAdmin)) dpm.lockNow(); else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 重设锁屏密码 */ public void resetScreenPassword(String password) { if (dpm.isAdminActive(myAdmin)) dpm.resetPassword(password, 0); else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 清除锁屏密码 */ public void unlockScreen() { if (dpm.isAdminActive(myAdmin)) { dpm.resetPassword("", 0); } else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 清除数据 */ public void wipeData() { if (dpm.isAdminActive(myAdmin)) { dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);//清除sd card dpm.wipeData(0);//恢复出厂设置 } else Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show(); } /** * 卸载步骤: * 1. 先变成普通软件(清除管理员权限) * 2. 正常卸载 */ public void unInstall() { removeAdmin(); Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + ctx.getPackageName())); ctx.startActivity(intent); } /** * 检查管理员权限 * * @return */ public boolean isAdmin() { if (dpm.isAdminActive(myAdmin)) return true; else return false; } /** * 清除管 <SUF>*/ public void removeAdmin() { if (dpm.isAdminActive(myAdmin)) dpm.removeActiveAdmin(myAdmin); } }
1
26
1
26641_4
package com.sxl.util; import java.io.*; import java.net.*; import java.security.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Client { /* * webservice服务器定义 */ //调用注册方法可能不成功。 //java.io.IOException: Server returned HTTP response code: 400 for URL: http://sdk2.zucp.net:8060/webservice.asmx。 //如果出现上述400错误,请参考第102行。 //如果您的系统是utf-8,收到的短信可能是乱码,请参考第102,295行 //可以根据您的需要自行解析下面的地址 //http://sdk2.zucp.net:8060/webservice.asmx?wsdl private String serviceURL = "http://sdk2.zucp.net:8060/webservice.asmx"; private String sn = "";// 序列号 private String password = ""; private String pwd = "";// 密码 /* * 构造函数 */ public Client(String sn, String password) throws UnsupportedEncodingException { this.sn = sn; this.password = password; this.pwd = this.getMD5(sn + password); } /* * 方法名称:getMD5 * 功 能:字符串MD5加密 * 参 数:待转换字符串 * 返 回 值:加密之后字符串 */ public String getMD5(String sourceStr) throws UnsupportedEncodingException { String resultStr = ""; try { byte[] temp = sourceStr.getBytes(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(temp); // resultStr = new String(md5.digest()); byte[] b = md5.digest(); for (int i = 0; i < b.length; i++) { char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] ob = new char[2]; ob[0] = digit[(b[i] >>> 4) & 0X0F]; ob[1] = digit[b[i] & 0X0F]; resultStr += new String(ob); } return resultStr; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /* * 方法名称:register * 功 能:注册 * 参 数:对应参数 省份,城市,行业,企业名称,联系人,电话,手机,电子邮箱,传真,地址,邮编 * 返 回 值:注册结果(String) */ public String register(String province, String city, String trade, String entname, String linkman, String phone, String mobile, String email, String fax, String address, String postcode) { String result = ""; String soapAction = "http://tempuri.org/Register"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"; xml += "<soap12:Body>"; xml += "<Register xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + password + "</pwd>"; xml += "<province>" + province + "</province>"; xml += "<city>" + city + "</city>"; xml += "<trade>" + trade + "</trade>"; xml += "<entname>" + entname + "</entname>"; xml += "<linkman>" + linkman + "</linkman>"; xml += "<phone>" + phone + "</phone>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<email>" + email + "</email>"; xml += "<fax>" + fax + "</fax>"; xml += "<address>" + address + "</address>"; xml += "<postcode>" + postcode + "</postcode>"; xml += "<sign></sign>"; xml += "</Register>"; xml += "</soap12:Body>"; xml += "</soap12:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); //bout.write(xml.getBytes("GBK")); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<RegisterResult>(.*)</RegisterResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); return new String(result.getBytes(), "utf-8"); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:chargeFee * 功 能:充值 * 参 数:充值卡号,充值密码 * 返 回 值:操作结果(String) */ public String chargeFee(String cardno, String cardpwd) { String result = ""; String soapAction = "http://tempuri.org/ChargUp"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"; xml += "<soap12:Body>"; xml += "<ChargUp xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + password + "</pwd>"; xml += "<cardno>" + cardno + "</cardno>"; xml += "<cardpwd>" + cardpwd + "</cardpwd>"; xml += "</ChargUp>"; xml += "</soap12:Body>"; xml += "</soap12:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<ChargUpResult>(.*)</ChargUpResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); // return result; return new String(result.getBytes(), "utf-8"); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:getBalance * 功 能:获取余额 * 参 数:无 * 返 回 值:余额(String) */ public String getBalance() { String result = ""; String soapAction = "http://tempuri.org/balance"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<balance xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "</balance>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<balanceResult>(.*)</balanceResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); return new String(result.getBytes()); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:mt * 功 能:发送短信 ,传多个手机号就是群发,一个手机号就是单条提交 * 参 数:mobile,content,ext,stime,rrid(手机号,内容,扩展码,定时时间,唯一标识) * 返 回 值:唯一标识,如果不填写rrid将返回系统生成的 */ public String mt(String mobile, String content, String ext, String stime, String rrid) { String result = ""; //System.out.print(pwd); String soapAction = "http://tempuri.org/mt"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<mt xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<content>" + content + "</content>"; xml += "<ext>" + ext + "</ext>"; xml += "<stime>" + stime + "</stime>"; xml += "<rrid>" + rrid + "</rrid>"; xml += "</mt>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); //bout.write(xml.getBytes()); bout.write(xml.getBytes("utf-8")); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");//这一句也关键 httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern.compile("<mtResult>(.*)</mtResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } return result; } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:mo * 功 能:接收短信 * 参 数:无 * 返 回 值:接收到的信息 */ public String mo() { String result = ""; String soapAction = "http://tempuri.org/mo"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<mo xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "</mo>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStream isr = httpconn.getInputStream(); StringBuffer buff = new StringBuffer(); byte[] byte_receive = new byte[10240]; for (int i = 0; (i = isr.read(byte_receive)) != -1;) { buff.append(new String(byte_receive, 0, i)); } isr.close(); String result_before = buff.toString(); int start = result_before.indexOf("<moResult>"); int end = result_before.indexOf("</moResult>"); result = result_before.substring(start + 10, end); return result; } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:gxmt 功 能:发送个性短信 ,即给不同的手机号发送不同的内容,手机号和内容用英文的逗号对应好 * 参数:mobile,content,ext,stime,rrid(手机号,内容,扩展码,定时时间,唯一标识) 返 回 * 值:唯一标识,如果不填写rrid将返回系统生成的 */ public String gxmt(String mobile, String content, String ext, String stime, String rrid) { String result = ""; String soapAction = "http://tempuri.org/gxmt"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<gxmt xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<content>" + content + "</content>"; xml += "<ext>" + ext + "</ext>"; xml += "<stime>" + stime + "</stime>"; xml += "<rrid>" + rrid + "</rrid>"; xml += "</gxmt>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<gxmtResult>(.*)</gxmtResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } return result; } catch (Exception e) { e.printStackTrace(); return ""; } } public String UnRegister() { String result = ""; String soapAction = "http://tempuri.org/UnRegister"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"; xml += "<soap12:Body>"; xml += "<UnRegister xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + password + "</pwd>"; xml += "</UnRegister>"; xml += "</soap12:Body>"; xml += "</soap12:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<UnRegisterResult>String</UnRegisterResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); return new String(result.getBytes()); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:UDPPwd * 功 能:修改密码 * 参 数:新密码 * 返 回 值:操作结果(String) */ public String UDPPwd(String newPwd) { String result = ""; String soapAction = "http://tempuri.org/UDPPwd"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"; xml += "<soap12:Body>"; xml += "<UDPPwd xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + password + "</pwd>"; xml += "<newpwd>" + newPwd + "</newpwd>"; xml += "</UDPPwd>"; xml += "</soap12:Body>"; xml += "</soap12:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<UDPPwdResult>(.*)</UDPPwdResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); // return result; return new String(result.getBytes(), "utf-8"); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:mdSmsSend_u * 功 能:发送短信 ,传多个手机号就是群发,一个手机号就是单条提交 * 参 数:mobile,content,ext,stime,rrid(手机号,URL_UT8编码内容,扩展码,定时时间,唯一标识) * 返 回 值:唯一标识,如果不填写rrid将返回系统生成的 */ public String mdSmsSend_u(String mobile, String content, String ext, String stime, String rrid) { String result = ""; String soapAction = "http://tempuri.org/mdSmsSend_u"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<mdSmsSend_u xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<content>" + content + "</content>"; xml += "<ext>" + ext + "</ext>"; xml += "<stime>" + stime + "</stime>"; xml += "<rrid>" + rrid + "</rrid>"; xml += "</mdSmsSend_u>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; //System.out.println(sn+" "+pwd+" "+mobile+" "+content); URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes("GBK")); //如果您的系统是utf-8,这里请改成bout.write(xml.getBytes("GBK")); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern.compile("<mdSmsSend_uResult>(.*)</mdSmsSend_uResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } return result; } catch (Exception e) { e.printStackTrace(); return ""; } } }
CatherineAming/-
src/com/sxl/util/Client.java
6,798
//如果您的系统是utf-8,收到的短信可能是乱码,请参考第102,295行
line_comment
zh-cn
package com.sxl.util; import java.io.*; import java.net.*; import java.security.*; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Client { /* * webservice服务器定义 */ //调用注册方法可能不成功。 //java.io.IOException: Server returned HTTP response code: 400 for URL: http://sdk2.zucp.net:8060/webservice.asmx。 //如果出现上述400错误,请参考第102行。 //如果 <SUF> //可以根据您的需要自行解析下面的地址 //http://sdk2.zucp.net:8060/webservice.asmx?wsdl private String serviceURL = "http://sdk2.zucp.net:8060/webservice.asmx"; private String sn = "";// 序列号 private String password = ""; private String pwd = "";// 密码 /* * 构造函数 */ public Client(String sn, String password) throws UnsupportedEncodingException { this.sn = sn; this.password = password; this.pwd = this.getMD5(sn + password); } /* * 方法名称:getMD5 * 功 能:字符串MD5加密 * 参 数:待转换字符串 * 返 回 值:加密之后字符串 */ public String getMD5(String sourceStr) throws UnsupportedEncodingException { String resultStr = ""; try { byte[] temp = sourceStr.getBytes(); MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(temp); // resultStr = new String(md5.digest()); byte[] b = md5.digest(); for (int i = 0; i < b.length; i++) { char[] digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; char[] ob = new char[2]; ob[0] = digit[(b[i] >>> 4) & 0X0F]; ob[1] = digit[b[i] & 0X0F]; resultStr += new String(ob); } return resultStr; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /* * 方法名称:register * 功 能:注册 * 参 数:对应参数 省份,城市,行业,企业名称,联系人,电话,手机,电子邮箱,传真,地址,邮编 * 返 回 值:注册结果(String) */ public String register(String province, String city, String trade, String entname, String linkman, String phone, String mobile, String email, String fax, String address, String postcode) { String result = ""; String soapAction = "http://tempuri.org/Register"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"; xml += "<soap12:Body>"; xml += "<Register xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + password + "</pwd>"; xml += "<province>" + province + "</province>"; xml += "<city>" + city + "</city>"; xml += "<trade>" + trade + "</trade>"; xml += "<entname>" + entname + "</entname>"; xml += "<linkman>" + linkman + "</linkman>"; xml += "<phone>" + phone + "</phone>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<email>" + email + "</email>"; xml += "<fax>" + fax + "</fax>"; xml += "<address>" + address + "</address>"; xml += "<postcode>" + postcode + "</postcode>"; xml += "<sign></sign>"; xml += "</Register>"; xml += "</soap12:Body>"; xml += "</soap12:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); //bout.write(xml.getBytes("GBK")); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<RegisterResult>(.*)</RegisterResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); return new String(result.getBytes(), "utf-8"); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:chargeFee * 功 能:充值 * 参 数:充值卡号,充值密码 * 返 回 值:操作结果(String) */ public String chargeFee(String cardno, String cardpwd) { String result = ""; String soapAction = "http://tempuri.org/ChargUp"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"; xml += "<soap12:Body>"; xml += "<ChargUp xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + password + "</pwd>"; xml += "<cardno>" + cardno + "</cardno>"; xml += "<cardpwd>" + cardpwd + "</cardpwd>"; xml += "</ChargUp>"; xml += "</soap12:Body>"; xml += "</soap12:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<ChargUpResult>(.*)</ChargUpResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); // return result; return new String(result.getBytes(), "utf-8"); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:getBalance * 功 能:获取余额 * 参 数:无 * 返 回 值:余额(String) */ public String getBalance() { String result = ""; String soapAction = "http://tempuri.org/balance"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<balance xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "</balance>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<balanceResult>(.*)</balanceResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); return new String(result.getBytes()); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:mt * 功 能:发送短信 ,传多个手机号就是群发,一个手机号就是单条提交 * 参 数:mobile,content,ext,stime,rrid(手机号,内容,扩展码,定时时间,唯一标识) * 返 回 值:唯一标识,如果不填写rrid将返回系统生成的 */ public String mt(String mobile, String content, String ext, String stime, String rrid) { String result = ""; //System.out.print(pwd); String soapAction = "http://tempuri.org/mt"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<mt xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<content>" + content + "</content>"; xml += "<ext>" + ext + "</ext>"; xml += "<stime>" + stime + "</stime>"; xml += "<rrid>" + rrid + "</rrid>"; xml += "</mt>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); //bout.write(xml.getBytes()); bout.write(xml.getBytes("utf-8")); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");//这一句也关键 httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern.compile("<mtResult>(.*)</mtResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } return result; } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:mo * 功 能:接收短信 * 参 数:无 * 返 回 值:接收到的信息 */ public String mo() { String result = ""; String soapAction = "http://tempuri.org/mo"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<mo xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "</mo>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStream isr = httpconn.getInputStream(); StringBuffer buff = new StringBuffer(); byte[] byte_receive = new byte[10240]; for (int i = 0; (i = isr.read(byte_receive)) != -1;) { buff.append(new String(byte_receive, 0, i)); } isr.close(); String result_before = buff.toString(); int start = result_before.indexOf("<moResult>"); int end = result_before.indexOf("</moResult>"); result = result_before.substring(start + 10, end); return result; } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:gxmt 功 能:发送个性短信 ,即给不同的手机号发送不同的内容,手机号和内容用英文的逗号对应好 * 参数:mobile,content,ext,stime,rrid(手机号,内容,扩展码,定时时间,唯一标识) 返 回 * 值:唯一标识,如果不填写rrid将返回系统生成的 */ public String gxmt(String mobile, String content, String ext, String stime, String rrid) { String result = ""; String soapAction = "http://tempuri.org/gxmt"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<gxmt xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<content>" + content + "</content>"; xml += "<ext>" + ext + "</ext>"; xml += "<stime>" + stime + "</stime>"; xml += "<rrid>" + rrid + "</rrid>"; xml += "</gxmt>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<gxmtResult>(.*)</gxmtResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } return result; } catch (Exception e) { e.printStackTrace(); return ""; } } public String UnRegister() { String result = ""; String soapAction = "http://tempuri.org/UnRegister"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"; xml += "<soap12:Body>"; xml += "<UnRegister xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + password + "</pwd>"; xml += "</UnRegister>"; xml += "</soap12:Body>"; xml += "</soap12:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<UnRegisterResult>String</UnRegisterResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); return new String(result.getBytes()); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:UDPPwd * 功 能:修改密码 * 参 数:新密码 * 返 回 值:操作结果(String) */ public String UDPPwd(String newPwd) { String result = ""; String soapAction = "http://tempuri.org/UDPPwd"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap12:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap12=\"http://www.w3.org/2003/05/soap-envelope\">"; xml += "<soap12:Body>"; xml += "<UDPPwd xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + password + "</pwd>"; xml += "<newpwd>" + newPwd + "</newpwd>"; xml += "</UDPPwd>"; xml += "</soap12:Body>"; xml += "</soap12:Envelope>"; URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes()); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern .compile("<UDPPwdResult>(.*)</UDPPwdResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } in.close(); // return result; return new String(result.getBytes(), "utf-8"); } catch (Exception e) { e.printStackTrace(); return ""; } } /* * 方法名称:mdSmsSend_u * 功 能:发送短信 ,传多个手机号就是群发,一个手机号就是单条提交 * 参 数:mobile,content,ext,stime,rrid(手机号,URL_UT8编码内容,扩展码,定时时间,唯一标识) * 返 回 值:唯一标识,如果不填写rrid将返回系统生成的 */ public String mdSmsSend_u(String mobile, String content, String ext, String stime, String rrid) { String result = ""; String soapAction = "http://tempuri.org/mdSmsSend_u"; String xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"; xml += "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"; xml += "<soap:Body>"; xml += "<mdSmsSend_u xmlns=\"http://tempuri.org/\">"; xml += "<sn>" + sn + "</sn>"; xml += "<pwd>" + pwd + "</pwd>"; xml += "<mobile>" + mobile + "</mobile>"; xml += "<content>" + content + "</content>"; xml += "<ext>" + ext + "</ext>"; xml += "<stime>" + stime + "</stime>"; xml += "<rrid>" + rrid + "</rrid>"; xml += "</mdSmsSend_u>"; xml += "</soap:Body>"; xml += "</soap:Envelope>"; //System.out.println(sn+" "+pwd+" "+mobile+" "+content); URL url; try { url = new URL(serviceURL); URLConnection connection = url.openConnection(); HttpURLConnection httpconn = (HttpURLConnection) connection; ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(xml.getBytes("GBK")); //如果您的系统是utf-8,这里请改成bout.write(xml.getBytes("GBK")); byte[] b = bout.toByteArray(); httpconn.setRequestProperty("Content-Length", String .valueOf(b.length)); httpconn.setRequestProperty("Content-Type", "text/xml; charset=gb2312"); httpconn.setRequestProperty("SOAPAction", soapAction); httpconn.setRequestMethod("POST"); httpconn.setDoInput(true); httpconn.setDoOutput(true); OutputStream out = httpconn.getOutputStream(); out.write(b); out.close(); InputStreamReader isr = new InputStreamReader(httpconn .getInputStream()); BufferedReader in = new BufferedReader(isr); String inputLine; while (null != (inputLine = in.readLine())) { Pattern pattern = Pattern.compile("<mdSmsSend_uResult>(.*)</mdSmsSend_uResult>"); Matcher matcher = pattern.matcher(inputLine); while (matcher.find()) { result = matcher.group(1); } } return result; } catch (Exception e) { e.printStackTrace(); return ""; } } }
0
39
0
10575_54
package com.ky.mainactivity; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import javax.crypto.spec.PSource; import com.ky.beaninfo.ColumnVedioInfo; import com.ky.db.VideoDowningDB; import com.ky.passenger.R; import com.ky.request.GetContentInfoRequest; import com.ky.request.HttpHomeLoadDataTask; import com.ky.response.GetContentInfoResponse; import com.ky.response.GetContentListResponse; import com.ky.utills.Configure; import com.lhl.callback.IUpdateData; import com.lhl.db.DowningVideoDB; import com.lidroid.xutils.exception.DbException; import com.lidroid.xutils.sample.download.DownloadManager; import com.lidroid.xutils.sample.download.DownloadService; import com.lidroid.xutils.util.LogUtils; import com.redbull.log.Logger; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * 视频详情 * * @author Catherine.Brain * */ public class VedioDetailActivity extends Activity implements OnClickListener { String TAG = "VedioDetailFragment"; // View view = null; TextView text_Daoyan, text_Actor, text_Year, text_Intro, text_Name; Button btn_Down; // btn_Last, btn_Next, public static String FRAGMENTNAME = "详情"; ImageView vedioImage; private Context mAppContext; Button btn_return; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.vedio_detail); initView(); mAppContext = getApplicationContext(); downloadManager = DownloadService.getDownloadManager(mAppContext); } // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // // TODO Auto-generated method stub // if (null == view) { // view = LayoutInflater.from(getActivity()).inflate( // R.layout.vedio_detail, null); // // } // ViewGroup p = (ViewGroup) view.getParent(); // if (p != null) { // p.removeView(view); // } // // return view; // } String actor, director, years, intro, title, thumb, down_url, url, id, type; // 得到小标,然后得到响应的图片 int position = 0; public void initView() { Configure.PAGER = 6; text_Actor = (TextView) findViewById(R.id.text_actor_name); text_Daoyan = (TextView) findViewById(R.id.text_daoyan_name); text_Year = (TextView) findViewById(R.id.text_years_time); text_Intro = (TextView) findViewById(R.id.text_intro); vedioImage = (ImageView) findViewById(R.id.video_image); text_Name = (TextView) findViewById(R.id.text_name_name); btn_return = (Button) findViewById(R.id.btn_return); btn_return.setOnClickListener(this); // btn_Last = (Button) view.findViewById(R.id.btn_last); // btn_Next = (Button) view.findViewById(R.id.btn_next); btn_Down = (Button) findViewById(R.id.btn_down); btn_Down.setOnClickListener(this); // btn_Last.setOnClickListener(this); // btn_Next.setOnClickListener(this); if (getIntent() != null) { title = getIntent().getStringExtra("title"); actor = getIntent().getStringExtra("actor"); intro = getIntent().getStringExtra("description"); years = getIntent().getStringExtra("years"); director = getIntent().getStringExtra("director"); thumb = getIntent().getStringExtra("thumb"); // down_url = getArguments().getString("down_url"); url = getIntent().getStringExtra("url"); id = getIntent().getStringExtra("id"); type = getIntent().getStringExtra("type"); position = getIntent().getIntExtra("pos", 0); System.out.println("the postion is===>" + position); Logger.d(TAG, "id:" + id + "--type:" + type + "--url:" + url); if (null == url) { text_Actor.setText("李连杰、周迅"); text_Daoyan.setText("徐克、张之亮"); text_Year.setText("2014年12月1日"); text_Intro.setText("《龙门飞甲》是《新龙门客栈》的续集,中国内地继香港后大中华区" + "的第一部真正意义上的3D武侠电影,也成为了继粤语后华语电影史上第一部获得官方认" + "证的IMAX 3D电影。由博纳影业集团出品,徐克、张之亮联合执导,徐克、" + "何冀平、朱雅欐合作编剧,李连杰、周迅、陈坤、李宇春、桂纶镁、刘雅婷(刘澍颖)及范晓" + "萱联袂主演该片讲述的是龙门客栈被烧毁三年后的故事,明朝西厂督主雨化田追杀怀了" + "龙胎的妃子和抗击朝廷的赵怀安而来到这处客栈,当年风骚的老板娘金镶玉早已神秘失踪," + "只剩下逃过火劫的伙计们重起炉灶,痴等老板娘回来。西厂密探、鞑靼商队等江湖各路人马" + ",再度相逢。几乎被世人遗忘的边关客栈,再次因缘际会地风起云涌"); } else { UpdateData(); } } else { UpdateData(); } vedioImage.setBackgroundResource(Configure.image_video_Icon[position % Configure.image_video_Icon.length]); // vedioImage.setBackgroundResource(R.drawable.image_novel_one); } public void UpdateData() { GetContentInfoRequest vedio_info = new GetContentInfoRequest(this, id, type, false); new HttpHomeLoadDataTask(this, VedioInfoCallBack, true, "", false) .execute(vedio_info); } ColumnVedioInfo videoInfo; IUpdateData VedioInfoCallBack = new IUpdateData() { @Override public void updateUi(Object o) { GetContentInfoResponse videoRes = new GetContentInfoResponse(); videoRes.paseRespones(o.toString()); videoInfo = new ColumnVedioInfo(); videoInfo.actor = videoRes.vedio.actor; videoInfo.director = videoRes.vedio.director; videoInfo.content = videoRes.vedio.content; videoInfo.title = videoRes.vedio.title; videoInfo.creat_time = videoRes.vedio.creat_time; videoInfo.name = videoRes.vedio.name; videoInfo.category_id = videoRes.vedio.category_id; videoInfo.years = videoRes.vedio.years; videoInfo.id = videoRes.vedio.id; // new BitmapThread(thumb).start(); text_Actor.setText(videoInfo.actor); text_Daoyan.setText(videoInfo.director); text_Intro.setText(videoInfo.content); text_Year.setText(videoInfo.years); text_Name.setText(videoInfo.title); } @Override public void handleErrorData(String info) { // TODO Auto-generated method stub } }; public class BitmapThread extends Thread { private String startBg; public BitmapThread(String start) { startBg = start; } @Override public void run() { try { Logger.log("startBg:" + startBg); URL url = new URL(startBg); Bitmap bitmap = BitmapFactory.decodeStream(url.openStream()); Logger.log("bitmap:" + bitmap + "----------------------------------------------"); // cache.put("startBitmap", bitmap); Message msg = new Message(); msg.obj = bitmap; imageHandler.sendMessage(msg); } catch (IOException e) { Logger.log("------------" + e.toString() + "<><><><><><>"); try { android.os.Debug .dumpHprofData("/mnt/sdcard/hljhomedump.hprof"); } catch (IOException e1) { e1.printStackTrace(); } } } } Handler imageHandler = new Handler() { @Override public void handleMessage(Message msg) { Bitmap bitmap = (Bitmap) msg.obj; // pre.setImageBitmap(bitmap); super.handleMessage(msg); } }; @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); } @Override public void onClick(View v) { // Fragment newContent; // BaseActivity base = (BaseActivity) getActivity(); switch (v.getId()) { case R.id.btn_down: // String path = Configure.VEDIOTEST; // // Logger.d(TAG, "点击下载了,the path is====" + encode2(path)); // path = encode2(path); // // String path = down_url; // System.out.println(Environment.getExternalStorageState() + // "------" // + Environment.MEDIA_MOUNTED); // // if (Environment.getExternalStorageState().equals( // Environment.MEDIA_MOUNTED)) { // // VideoDownDB videoDB = new VideoDownDB(getActivity()); // // if (videoDB.select(title) == 0) { // // videoDB.insert(path, title); // // } // Intent intent = new Intent(); // intent.setClass(getActivity(), DownloadFragment.class); // intent.putExtra("fromwhere", "vedio"); // intent.putExtra("path", path); // intent.putExtra("name", title); // startActivity(intent); // getActivity().finish(); // // } else { // // 显示SDCard错误信息 // Toast.makeText(getActivity(), R.string.sdcarderror, 1).show(); // } if (Down()) { Intent intent = new Intent(this, DownloadListActivity.class); intent.putExtra("fromWhere", 0); startActivity(intent); } else { Toast.makeText(this, "当前文件已经下载过了!", Toast.LENGTH_SHORT).show(); } break; default: break; case R.id.btn_return: finish(); break; } } // -------------------------------这是xUtils下载------------------------------------- // 声明一个db DowningVideoDB DowningDB = null; public String Flag = "mp4"; // 定义一个变量来得到当前需要下载的路径 private String path = ""; // 定义一个变量来得到需要下载文件的名字 private String down_filename = ""; private DownloadManager downloadManager; public boolean Down() { if (null == DowningDB) { DowningDB = new DowningVideoDB(this); } int i = (int) (Math.random() * 5 + 1); path = Configure.VedioPath[i]; down_filename = path.substring(path.lastIndexOf('/') + 1); // String target = "/sdcard/xUtils/" + // System.currentTimeMillis() // + "lzfile.apk"; System.out.println("将要下载的文件名为====》" + down_filename); String target = ""; if (down_filename.contains(".apk")) { target = Configure.GameFile + down_filename; Flag = "apk"; } else if (down_filename.contains(".mp4")) { target = Configure.VedioFile + down_filename; Flag = "mp4"; } else { target = Configure.NovelFile + down_filename; Flag = "novel"; } if (DowningDB.select(down_filename) == 0) { DowningDB.insert("0", path, down_filename, 0); try { downloadManager.addNewDownload(path.toString(), down_filename, target, true, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。 false, Flag, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。 null); } catch (DbException e) { LogUtils.e(e.getMessage(), e); } return true; } return false; } // ------------------------这是xUtils的下载需要的--------------------------- /** * 简单异或加密解密算法 * * @param str * 要加密的字符串 * @return */ private static String encode2(String str) { int code = 112; // 密钥 char[] charArray = str.toCharArray(); for (int i = 0; i < charArray.length; i++) { charArray[i] = (char) (charArray[i] ^ code); } return new String(charArray); } }
Catherinelhl/Passager
Passenger/src/com/ky/mainactivity/VedioDetailActivity.java
3,626
// 定义一个变量来得到需要下载文件的名字
line_comment
zh-cn
package com.ky.mainactivity; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import javax.crypto.spec.PSource; import com.ky.beaninfo.ColumnVedioInfo; import com.ky.db.VideoDowningDB; import com.ky.passenger.R; import com.ky.request.GetContentInfoRequest; import com.ky.request.HttpHomeLoadDataTask; import com.ky.response.GetContentInfoResponse; import com.ky.response.GetContentListResponse; import com.ky.utills.Configure; import com.lhl.callback.IUpdateData; import com.lhl.db.DowningVideoDB; import com.lidroid.xutils.exception.DbException; import com.lidroid.xutils.sample.download.DownloadManager; import com.lidroid.xutils.sample.download.DownloadService; import com.lidroid.xutils.util.LogUtils; import com.redbull.log.Logger; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; /** * 视频详情 * * @author Catherine.Brain * */ public class VedioDetailActivity extends Activity implements OnClickListener { String TAG = "VedioDetailFragment"; // View view = null; TextView text_Daoyan, text_Actor, text_Year, text_Intro, text_Name; Button btn_Down; // btn_Last, btn_Next, public static String FRAGMENTNAME = "详情"; ImageView vedioImage; private Context mAppContext; Button btn_return; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.vedio_detail); initView(); mAppContext = getApplicationContext(); downloadManager = DownloadService.getDownloadManager(mAppContext); } // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, // Bundle savedInstanceState) { // // TODO Auto-generated method stub // if (null == view) { // view = LayoutInflater.from(getActivity()).inflate( // R.layout.vedio_detail, null); // // } // ViewGroup p = (ViewGroup) view.getParent(); // if (p != null) { // p.removeView(view); // } // // return view; // } String actor, director, years, intro, title, thumb, down_url, url, id, type; // 得到小标,然后得到响应的图片 int position = 0; public void initView() { Configure.PAGER = 6; text_Actor = (TextView) findViewById(R.id.text_actor_name); text_Daoyan = (TextView) findViewById(R.id.text_daoyan_name); text_Year = (TextView) findViewById(R.id.text_years_time); text_Intro = (TextView) findViewById(R.id.text_intro); vedioImage = (ImageView) findViewById(R.id.video_image); text_Name = (TextView) findViewById(R.id.text_name_name); btn_return = (Button) findViewById(R.id.btn_return); btn_return.setOnClickListener(this); // btn_Last = (Button) view.findViewById(R.id.btn_last); // btn_Next = (Button) view.findViewById(R.id.btn_next); btn_Down = (Button) findViewById(R.id.btn_down); btn_Down.setOnClickListener(this); // btn_Last.setOnClickListener(this); // btn_Next.setOnClickListener(this); if (getIntent() != null) { title = getIntent().getStringExtra("title"); actor = getIntent().getStringExtra("actor"); intro = getIntent().getStringExtra("description"); years = getIntent().getStringExtra("years"); director = getIntent().getStringExtra("director"); thumb = getIntent().getStringExtra("thumb"); // down_url = getArguments().getString("down_url"); url = getIntent().getStringExtra("url"); id = getIntent().getStringExtra("id"); type = getIntent().getStringExtra("type"); position = getIntent().getIntExtra("pos", 0); System.out.println("the postion is===>" + position); Logger.d(TAG, "id:" + id + "--type:" + type + "--url:" + url); if (null == url) { text_Actor.setText("李连杰、周迅"); text_Daoyan.setText("徐克、张之亮"); text_Year.setText("2014年12月1日"); text_Intro.setText("《龙门飞甲》是《新龙门客栈》的续集,中国内地继香港后大中华区" + "的第一部真正意义上的3D武侠电影,也成为了继粤语后华语电影史上第一部获得官方认" + "证的IMAX 3D电影。由博纳影业集团出品,徐克、张之亮联合执导,徐克、" + "何冀平、朱雅欐合作编剧,李连杰、周迅、陈坤、李宇春、桂纶镁、刘雅婷(刘澍颖)及范晓" + "萱联袂主演该片讲述的是龙门客栈被烧毁三年后的故事,明朝西厂督主雨化田追杀怀了" + "龙胎的妃子和抗击朝廷的赵怀安而来到这处客栈,当年风骚的老板娘金镶玉早已神秘失踪," + "只剩下逃过火劫的伙计们重起炉灶,痴等老板娘回来。西厂密探、鞑靼商队等江湖各路人马" + ",再度相逢。几乎被世人遗忘的边关客栈,再次因缘际会地风起云涌"); } else { UpdateData(); } } else { UpdateData(); } vedioImage.setBackgroundResource(Configure.image_video_Icon[position % Configure.image_video_Icon.length]); // vedioImage.setBackgroundResource(R.drawable.image_novel_one); } public void UpdateData() { GetContentInfoRequest vedio_info = new GetContentInfoRequest(this, id, type, false); new HttpHomeLoadDataTask(this, VedioInfoCallBack, true, "", false) .execute(vedio_info); } ColumnVedioInfo videoInfo; IUpdateData VedioInfoCallBack = new IUpdateData() { @Override public void updateUi(Object o) { GetContentInfoResponse videoRes = new GetContentInfoResponse(); videoRes.paseRespones(o.toString()); videoInfo = new ColumnVedioInfo(); videoInfo.actor = videoRes.vedio.actor; videoInfo.director = videoRes.vedio.director; videoInfo.content = videoRes.vedio.content; videoInfo.title = videoRes.vedio.title; videoInfo.creat_time = videoRes.vedio.creat_time; videoInfo.name = videoRes.vedio.name; videoInfo.category_id = videoRes.vedio.category_id; videoInfo.years = videoRes.vedio.years; videoInfo.id = videoRes.vedio.id; // new BitmapThread(thumb).start(); text_Actor.setText(videoInfo.actor); text_Daoyan.setText(videoInfo.director); text_Intro.setText(videoInfo.content); text_Year.setText(videoInfo.years); text_Name.setText(videoInfo.title); } @Override public void handleErrorData(String info) { // TODO Auto-generated method stub } }; public class BitmapThread extends Thread { private String startBg; public BitmapThread(String start) { startBg = start; } @Override public void run() { try { Logger.log("startBg:" + startBg); URL url = new URL(startBg); Bitmap bitmap = BitmapFactory.decodeStream(url.openStream()); Logger.log("bitmap:" + bitmap + "----------------------------------------------"); // cache.put("startBitmap", bitmap); Message msg = new Message(); msg.obj = bitmap; imageHandler.sendMessage(msg); } catch (IOException e) { Logger.log("------------" + e.toString() + "<><><><><><>"); try { android.os.Debug .dumpHprofData("/mnt/sdcard/hljhomedump.hprof"); } catch (IOException e1) { e1.printStackTrace(); } } } } Handler imageHandler = new Handler() { @Override public void handleMessage(Message msg) { Bitmap bitmap = (Bitmap) msg.obj; // pre.setImageBitmap(bitmap); super.handleMessage(msg); } }; @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); } @Override public void onClick(View v) { // Fragment newContent; // BaseActivity base = (BaseActivity) getActivity(); switch (v.getId()) { case R.id.btn_down: // String path = Configure.VEDIOTEST; // // Logger.d(TAG, "点击下载了,the path is====" + encode2(path)); // path = encode2(path); // // String path = down_url; // System.out.println(Environment.getExternalStorageState() + // "------" // + Environment.MEDIA_MOUNTED); // // if (Environment.getExternalStorageState().equals( // Environment.MEDIA_MOUNTED)) { // // VideoDownDB videoDB = new VideoDownDB(getActivity()); // // if (videoDB.select(title) == 0) { // // videoDB.insert(path, title); // // } // Intent intent = new Intent(); // intent.setClass(getActivity(), DownloadFragment.class); // intent.putExtra("fromwhere", "vedio"); // intent.putExtra("path", path); // intent.putExtra("name", title); // startActivity(intent); // getActivity().finish(); // // } else { // // 显示SDCard错误信息 // Toast.makeText(getActivity(), R.string.sdcarderror, 1).show(); // } if (Down()) { Intent intent = new Intent(this, DownloadListActivity.class); intent.putExtra("fromWhere", 0); startActivity(intent); } else { Toast.makeText(this, "当前文件已经下载过了!", Toast.LENGTH_SHORT).show(); } break; default: break; case R.id.btn_return: finish(); break; } } // -------------------------------这是xUtils下载------------------------------------- // 声明一个db DowningVideoDB DowningDB = null; public String Flag = "mp4"; // 定义一个变量来得到当前需要下载的路径 private String path = ""; // 定义 <SUF> private String down_filename = ""; private DownloadManager downloadManager; public boolean Down() { if (null == DowningDB) { DowningDB = new DowningVideoDB(this); } int i = (int) (Math.random() * 5 + 1); path = Configure.VedioPath[i]; down_filename = path.substring(path.lastIndexOf('/') + 1); // String target = "/sdcard/xUtils/" + // System.currentTimeMillis() // + "lzfile.apk"; System.out.println("将要下载的文件名为====》" + down_filename); String target = ""; if (down_filename.contains(".apk")) { target = Configure.GameFile + down_filename; Flag = "apk"; } else if (down_filename.contains(".mp4")) { target = Configure.VedioFile + down_filename; Flag = "mp4"; } else { target = Configure.NovelFile + down_filename; Flag = "novel"; } if (DowningDB.select(down_filename) == 0) { DowningDB.insert("0", path, down_filename, 0); try { downloadManager.addNewDownload(path.toString(), down_filename, target, true, // 如果目标文件存在,接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。 false, Flag, // 如果从请求返回信息中获取到文件名,下载完成后自动重命名。 null); } catch (DbException e) { LogUtils.e(e.getMessage(), e); } return true; } return false; } // ------------------------这是xUtils的下载需要的--------------------------- /** * 简单异或加密解密算法 * * @param str * 要加密的字符串 * @return */ private static String encode2(String str) { int code = 112; // 密钥 char[] charArray = str.toCharArray(); for (int i = 0; i < charArray.length; i++) { charArray[i] = (char) (charArray[i] ^ code); } return new String(charArray); } }
1
21
1
42249_27
package Http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by 成刚 on 2016/4/5. */ public class WebService { private static String IP = "10.0.3.2:8080"; /* private static String IP = "192.168.254.1:8080";*/ /*private static String IP = "192.168.43.251:8080";*/ private static HttpURLConnection conn = null; private static InputStream is = null; //手机号+密码 登录功能 public static String executeHttpGet(String username, String password) { String path = "http://" + IP + "/MyProject/LogLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } //根据手机号查找用户 public static String executeHttpFindUserByPhone(String username) { String path = "http://" + IP + "/MyProject/FindUserLet"; path = path + "?username=" + username; return getConnection(path); } // 传入课程难度直接下载数据库课程信息通过Get方式获取HTTP服务器数据,再后来修改传参,可以控制要下载的课程 public static String executeHttpGetCourse(String hard) { String path = "http://" + IP + "/MyProject/GetCourseLet"; path = path + "?hard=" + hard; return getConnection(path); } //密码修改功能,传入手机号+新密码 public static String executeHttpNewPwd(String username, String password) { String path = "http://" + IP + "/MyProject/PwdLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } // 注册功能,传入手机号+密码 public static String executeHttpRegister(String username, String password) { String path = "http://" + IP + "/MyProject/RegLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } // 注册功能,传入手机号+意见 public static String executeHttpFeedBack(String username, String suggestion) { String path = "http://" + IP + "/MyProject/FeedBackLet"; path = path + "?username=" + username + "&suggestion=" + suggestion; return getConnection(path); } //传入手机号获取用户关注的课程 public static String executeHttpGetUserCourseInfo(String username) { String path = "http://" + IP + "/MyProject/GetUserCourseInfoLet"; path = path + "?username=" + username; return getConnection(path); } // 传入手机号+课程,修改用户关注课程的信息 public static String executeHttpSendUserCourseInfo(String username,String jsonstr) { String path = "http://" + IP + "/MyProject/SendUserCourseInfoLet"; path = path + "?jsonstr=" + jsonstr+ "&username=" + username; return getConnection(path); } //传入手机号获取用户测试记录 public static String executeHttpGetUserTestInfo(String username) { String path = "http://" + IP + "/MyProject/GetUserTestInfoLet"; path = path + "?username=" + username; return getConnection(path); } // 传入手机号+课程+时间+难度+得分 public static String executeHttpSendUserTestInfo(String username,String course,String time,int hard,String scores) { String path = "http://" + IP + "/MyProject/SendUserTestInfoLet"; path = path + "?username=" + username + "&course=" + course+ "&time=" + time+ "&hard=" + hard+ "&scores=" + scores; return getConnection(path); } // 在线获取最新app的版本号 public static String executeHttpGetVersion() { String path = "http://" + IP + "/MyProject/VersionLet"; return getConnection(path); } //传入用户的详细资料,添加到数据库 public static String executeHttpUserInfo(String username, String nickname, String introduce, String major, String email) { String path = "http://" + IP + "/MyProject/UserInfoLet"; path = path + "?username=" + username + "&nickname=" + nickname + "&introduce=" + introduce + "&major=" + major + "&email=" + email; return getConnection(path); } public static String getConnection(String path) { try { conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(3000); // 设置超时时间 conn.setReadTimeout(3000); conn.setDoInput(true); conn.setRequestMethod("GET"); // 设置获取信息方式 conn.setRequestProperty("Charset", "UTF-8"); // 设置接收数据编码格式 if (conn.getResponseCode() == 200) { is = conn.getInputStream(); return parseInfo(is); } } catch (Exception e) { e.printStackTrace(); } finally { // 意外退出时进行连接关闭保护 if (conn != null) { conn.disconnect(); } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } // 将输入流转化为 String 型 private static String parseInfo(InputStream inStream) throws Exception { byte[] data = read(inStream); // 转化为字符串 return new String(data, "UTF-8"); } // 将输入流转化为byte型 public static byte[] read(InputStream inStream) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } inStream.close(); return outputStream.toByteArray(); } }
CatterMCG/elearnApp
app/app/src/main/java/Http/WebService.java
1,417
// 设置超时时间
line_comment
zh-cn
package Http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by 成刚 on 2016/4/5. */ public class WebService { private static String IP = "10.0.3.2:8080"; /* private static String IP = "192.168.254.1:8080";*/ /*private static String IP = "192.168.43.251:8080";*/ private static HttpURLConnection conn = null; private static InputStream is = null; //手机号+密码 登录功能 public static String executeHttpGet(String username, String password) { String path = "http://" + IP + "/MyProject/LogLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } //根据手机号查找用户 public static String executeHttpFindUserByPhone(String username) { String path = "http://" + IP + "/MyProject/FindUserLet"; path = path + "?username=" + username; return getConnection(path); } // 传入课程难度直接下载数据库课程信息通过Get方式获取HTTP服务器数据,再后来修改传参,可以控制要下载的课程 public static String executeHttpGetCourse(String hard) { String path = "http://" + IP + "/MyProject/GetCourseLet"; path = path + "?hard=" + hard; return getConnection(path); } //密码修改功能,传入手机号+新密码 public static String executeHttpNewPwd(String username, String password) { String path = "http://" + IP + "/MyProject/PwdLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } // 注册功能,传入手机号+密码 public static String executeHttpRegister(String username, String password) { String path = "http://" + IP + "/MyProject/RegLet"; path = path + "?username=" + username + "&password=" + password; return getConnection(path); } // 注册功能,传入手机号+意见 public static String executeHttpFeedBack(String username, String suggestion) { String path = "http://" + IP + "/MyProject/FeedBackLet"; path = path + "?username=" + username + "&suggestion=" + suggestion; return getConnection(path); } //传入手机号获取用户关注的课程 public static String executeHttpGetUserCourseInfo(String username) { String path = "http://" + IP + "/MyProject/GetUserCourseInfoLet"; path = path + "?username=" + username; return getConnection(path); } // 传入手机号+课程,修改用户关注课程的信息 public static String executeHttpSendUserCourseInfo(String username,String jsonstr) { String path = "http://" + IP + "/MyProject/SendUserCourseInfoLet"; path = path + "?jsonstr=" + jsonstr+ "&username=" + username; return getConnection(path); } //传入手机号获取用户测试记录 public static String executeHttpGetUserTestInfo(String username) { String path = "http://" + IP + "/MyProject/GetUserTestInfoLet"; path = path + "?username=" + username; return getConnection(path); } // 传入手机号+课程+时间+难度+得分 public static String executeHttpSendUserTestInfo(String username,String course,String time,int hard,String scores) { String path = "http://" + IP + "/MyProject/SendUserTestInfoLet"; path = path + "?username=" + username + "&course=" + course+ "&time=" + time+ "&hard=" + hard+ "&scores=" + scores; return getConnection(path); } // 在线获取最新app的版本号 public static String executeHttpGetVersion() { String path = "http://" + IP + "/MyProject/VersionLet"; return getConnection(path); } //传入用户的详细资料,添加到数据库 public static String executeHttpUserInfo(String username, String nickname, String introduce, String major, String email) { String path = "http://" + IP + "/MyProject/UserInfoLet"; path = path + "?username=" + username + "&nickname=" + nickname + "&introduce=" + introduce + "&major=" + major + "&email=" + email; return getConnection(path); } public static String getConnection(String path) { try { conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(3000); // 设置 <SUF> conn.setReadTimeout(3000); conn.setDoInput(true); conn.setRequestMethod("GET"); // 设置获取信息方式 conn.setRequestProperty("Charset", "UTF-8"); // 设置接收数据编码格式 if (conn.getResponseCode() == 200) { is = conn.getInputStream(); return parseInfo(is); } } catch (Exception e) { e.printStackTrace(); } finally { // 意外退出时进行连接关闭保护 if (conn != null) { conn.disconnect(); } if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; } // 将输入流转化为 String 型 private static String parseInfo(InputStream inStream) throws Exception { byte[] data = read(inStream); // 转化为字符串 return new String(data, "UTF-8"); } // 将输入流转化为byte型 public static byte[] read(InputStream inStream) throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } inStream.close(); return outputStream.toByteArray(); } }
1
9
1
44537_4
package com.capton.sl; /** * 可以自由移动缩放的图片控件 * Created by capton on 2017/4/18. */ import android.content.Context; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.OnScaleGestureListener; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewConfiguration; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.ImageView; public class ScaleView extends ImageView implements OnGlobalLayoutListener, OnScaleGestureListener, OnTouchListener { /** 表示是否只有一次加载 */ private boolean isOnce = false; /** 初始时的缩放值 */ private float mInitScale; /** 双击时 的缩放值 */ private float mClickScale; /** 最大的缩放值 */ private float mMaxScale; /** 图片缩放矩阵 */ private Matrix mMatrix; /** 图片缩放手势 */ private ScaleGestureDetector mScaleGesture; // ----------------------------自由移动-------------------------------- /** 可移动最短距离限制,大于这个值时就可移动 */ private int mTouchSlop; /** 是否可以拖动 */ private boolean isCanDrag; // ----------------------------双击放大-------------------------------- private GestureDetector mGesture; // 是否自动缩放 private boolean isAutoScale; public ScaleView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ScaleView(Context context) { this(context, null); } public ScaleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // 必须设置才能触发 this.setOnTouchListener(this); mMatrix = new Matrix(); // 设置缩放模式 super.setScaleType(ScaleType.MATRIX); mScaleGesture = new ScaleGestureDetector(context, this); mGesture = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { // 如果正在缩放时,不能放大 if (isAutoScale) { return true; } float px = e.getX(); float py = e.getY(); // 只有小于最大缩放比例才能放大 float scale = getScale(); if (scale < mClickScale) { // mMatrix.postScale(mClickScale/scale, mClickScale/scale, // px, py); postDelayed(new ScaleRunnale(px, py, mClickScale), 16); isAutoScale = true; } else { // mMatrix.postScale(mInitScale/scale, mInitScale/scale, px, // py); postDelayed(new ScaleRunnale(px, py, mInitScale), 16); isAutoScale = true; } // setImageMatrix(mMatrix); return true; } }); /** * 是一个距离,表示滑动的时候,手的移动要大于这个距离才开始移动控件。如果小于这个距离就不触发移动控件,如viewpager * 就是用这个距离来判断用户是否翻页。 */ mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } private class ScaleRunnale implements Runnable { // 放大值 private static final float BIGGER = 1.08f; // 缩小值 private static final float SMALLER = 0.96f; private float x; private float y; private float mTargetScale; private float mTempScale; public ScaleRunnale(float x, float y, float mTargetScale) { super(); this.x = x; this.y = y; this.mTargetScale = mTargetScale; if (getScale() < mTargetScale) { mTempScale = BIGGER; } else if (getScale() > mTargetScale) { mTempScale = SMALLER; } } @Override public void run() { // 先进行缩放 mMatrix.postScale(mTempScale, mTempScale, x, y); checkSideAndCenterWhenScale(); setImageMatrix(mMatrix); float currentScale = getScale(); // 如果想放大,并且当前的缩放值小于目标值 if ((mTempScale > 1.0f && currentScale < mTargetScale) || (mTempScale < 1.0f && currentScale > mTargetScale)) { // 递归执行run方法 postDelayed(this, 16); } else { float scale = mTargetScale / currentScale; mMatrix.postScale(scale, scale, x, y); checkSideAndCenterWhenScale(); setImageMatrix(mMatrix); isAutoScale = false; } } } @Override public void onGlobalLayout() { // 如果还没有加载图片 if (!isOnce) { // 获得控件的宽高 int width = getWidth(); int height = getHeight(); Drawable drawable = getDrawable(); if (drawable == null) { return; } // 获得图片的宽高 int bitmapWidth = drawable.getIntrinsicWidth(); int bitmapHeight = drawable.getIntrinsicHeight(); // 设定比例值 float scale = 0.0f; // 如果图片的宽度>控件的宽度,缩小 if (bitmapWidth > width && bitmapHeight < height) { scale = width * 1.0f / bitmapWidth; } // 如果图片的高度>控件的高度,缩小 if (bitmapHeight > height && bitmapWidth < width) { scale = height * 1.0f / bitmapHeight; } // 如果图片的宽高度>控件的宽高度,缩小 或者 如果图片的宽高度<控件的宽高度,放大 if ((bitmapWidth > width && bitmapHeight > height) || (bitmapWidth < width && bitmapHeight < height)) { float f1 = width * 1.0f / bitmapWidth; float f2 = height * 1.0f / bitmapHeight; scale = Math.min(f1, f2); } // 初始化缩放值 mInitScale = scale; mClickScale = mInitScale * 2; mMaxScale = mInitScale * 4; // 得到移动的距离 int dx = width / 2 - bitmapWidth / 2; int dy = height / 2 - bitmapHeight / 2; // 平移 mMatrix.postTranslate(dx, dy); // 在控件的中心缩放 mMatrix.postScale(scale, scale, width / 2, height / 2); // 设置矩阵 setImageMatrix(mMatrix); // 关于matrix,就是个3*3的矩阵 /** * xscale xskew xtrans yskew yscale ytrans 0 0 0 */ isOnce = true; } } /** * 注册全局事件 */ @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); getViewTreeObserver().addOnGlobalLayoutListener(this); } /** * 移除全局事件 */ @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); getViewTreeObserver().removeGlobalOnLayoutListener(this); } /** * 获得缩放值 * * @return */ public float getScale() { /** * xscale xskew xtrans yskew yscale ytrans 0 0 0 */ float[] values = new float[9]; mMatrix.getValues(values); return values[Matrix.MSCALE_X]; } @Override public boolean onScale(ScaleGestureDetector detector) { // 如果没有图片,返回 if (getDrawable() == null) { return true; } // 缩放因子,>0表示正在放大,<0表示正在缩小 float intentScale = detector.getScaleFactor(); float scale = getScale(); // 进行缩放范围的控制 // 判断,如果<最大缩放值,表示可以放大,如果》最小缩放,说明可以缩小 if ((scale < mMaxScale && intentScale > 1.0f) || (scale > mInitScale && intentScale < 1.0f)) { // scale 变小时, intentScale变小 if (scale * intentScale < mInitScale) { // intentScale * scale = mInitScale ; intentScale = mInitScale / scale; } // scale 变大时, intentScale变大 if (scale * intentScale > mMaxScale) { // intentScale * scale = mMaxScale ; intentScale = mMaxScale / scale; } // 以控件为中心缩放 // mMatrix.postScale(intentScale, intentScale, getWidth()/2, // getHeight()/2); // 以手势为中心缩放 mMatrix.postScale(intentScale, intentScale, detector.getFocusX(), detector.getFocusY()); // 检测边界与中心点 checkSideAndCenterWhenScale(); setImageMatrix(mMatrix); } return true; } /** * 获得图片缩放后的矩阵 * * @return */ public RectF getMatrixRectF() { Matrix matrix = mMatrix; RectF rectF = new RectF(); Drawable drawable = getDrawable(); if (drawable != null) { // 初始化矩阵 rectF.set(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); // 移动s matrix.mapRect(rectF); } return rectF; } private void checkSideAndCenterWhenScale() { RectF rectF = getMatrixRectF(); float deltaX = 0f; float deltaY = 0f; int width = getWidth(); int height = getHeight(); // 情况1, 如果图片的宽度大于控件的宽度 if (rectF.width() >= width) { if (rectF.left > 0) { deltaX = -rectF.left;// 如果图片没有左边对齐,就往左边移动 } if (rectF.right < width) { deltaX = width - rectF.right;// 如果图片没有右边对齐,就往右边移动 } } // 情况2, 如果图片的宽度大于控件的宽度 if (rectF.height() >= height) { if (rectF.top > 0) { deltaY = -rectF.top;// } if (rectF.bottom < height) { deltaY = height - rectF.bottom;// 往底部移动 } } // 情况3,如图图片在控件内,则让其居中 if (rectF.width() < width) { // deltaX = width/2-rectF.left - rectF.width()/2; // 或 deltaX = width / 2f - rectF.right + rectF.width() / 2f; } if (rectF.height() < height) { deltaY = height / 2f - rectF.bottom + rectF.height() / 2f; } mMatrix.postTranslate(deltaX, deltaY); } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { // TODO Auto-generated method stub return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { // TODO Auto-generated method stub } private float mLastX; private float mLastY; /** 上次手指的数量 */ private int mLastPointerCount; /** 判断是否检测了x,y轴 */ private boolean isCheckX; private boolean isCheckY; @Override public boolean onTouch(View v, MotionEvent event) { // 把事件传递给双击手势 if (mGesture.onTouchEvent(event)) { return true; } // 把事件传递给缩放手势 mScaleGesture.onTouchEvent(event); float x = event.getX(); float y = event.getY(); int pointerCount = event.getPointerCount(); for (int i = 0; i < pointerCount; i++) { x += event.getX(i); y += event.getY(i); } x /= pointerCount; y /= pointerCount; // 说明手指改变 if (mLastPointerCount != pointerCount) { isCanDrag = false; mLastX = x; mLastY = y; } mLastPointerCount = pointerCount; RectF rectF = getMatrixRectF(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (rectF.width() > getWidth()) { getParent().requestDisallowInterceptTouchEvent(true); } break; case MotionEvent.ACTION_MOVE: if (rectF.width() > getWidth()) { getParent().requestDisallowInterceptTouchEvent(true); } float dx = x - mLastX; float dy = y - mLastY; if (!isCanDrag) { isCanDrag = isMoveAction(dx, dy); } /** * 如果能移动 */ if (isCanDrag) { //RectF rectF = getMatrixRectF(); if (getDrawable() == null) { return true; } isCheckX = isCheckY = true; // 如果图片在控件内,不允许移动 if (rectF.width() < getWidth()) { isCheckX = false; dx = 0f; } if (rectF.height() < getHeight()) { isCheckY = false; dy = 0f; } mMatrix.postTranslate(dx, dy); // 移动事检测边界 checkSideAndCenterWhenTransate(); setImageMatrix(mMatrix); } mLastX = x; mLastY = y; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: // 清楚手指 mLastPointerCount = 0; break; } return true; } private void checkSideAndCenterWhenTransate() { RectF rectF = getMatrixRectF(); float deltaX = 0f; float deltaY = 0f; int width = getWidth(); int height = getHeight(); if (rectF.top > 0 && isCheckY) { deltaY = -rectF.top;// 往上边移动 } if (rectF.bottom < height && isCheckY) { deltaY = height - rectF.bottom;// 往底部移动 } if (rectF.left > 0 && isCheckX) { deltaX = -rectF.left;// 往左边移动 } if (rectF.right < width && isCheckX) { deltaX = width - rectF.right;// 往右边移动 } // 移动 mMatrix.postTranslate(deltaX, deltaY); } private boolean isMoveAction(float dx, float dy) { // 求得两点的距离 return Math.sqrt(dx * dx + dy * dy) > mTouchSlop; } }
Ccapton/Android-ScaleView
ScaleView.java
3,594
/** 最大的缩放值 */
block_comment
zh-cn
package com.capton.sl; /** * 可以自由移动缩放的图片控件 * Created by capton on 2017/4/18. */ import android.content.Context; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.view.ScaleGestureDetector.OnScaleGestureListener; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewConfiguration; import android.view.ViewTreeObserver.OnGlobalLayoutListener; import android.widget.ImageView; public class ScaleView extends ImageView implements OnGlobalLayoutListener, OnScaleGestureListener, OnTouchListener { /** 表示是否只有一次加载 */ private boolean isOnce = false; /** 初始时的缩放值 */ private float mInitScale; /** 双击时 的缩放值 */ private float mClickScale; /** 最大的 <SUF>*/ private float mMaxScale; /** 图片缩放矩阵 */ private Matrix mMatrix; /** 图片缩放手势 */ private ScaleGestureDetector mScaleGesture; // ----------------------------自由移动-------------------------------- /** 可移动最短距离限制,大于这个值时就可移动 */ private int mTouchSlop; /** 是否可以拖动 */ private boolean isCanDrag; // ----------------------------双击放大-------------------------------- private GestureDetector mGesture; // 是否自动缩放 private boolean isAutoScale; public ScaleView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public ScaleView(Context context) { this(context, null); } public ScaleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // 必须设置才能触发 this.setOnTouchListener(this); mMatrix = new Matrix(); // 设置缩放模式 super.setScaleType(ScaleType.MATRIX); mScaleGesture = new ScaleGestureDetector(context, this); mGesture = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { // 如果正在缩放时,不能放大 if (isAutoScale) { return true; } float px = e.getX(); float py = e.getY(); // 只有小于最大缩放比例才能放大 float scale = getScale(); if (scale < mClickScale) { // mMatrix.postScale(mClickScale/scale, mClickScale/scale, // px, py); postDelayed(new ScaleRunnale(px, py, mClickScale), 16); isAutoScale = true; } else { // mMatrix.postScale(mInitScale/scale, mInitScale/scale, px, // py); postDelayed(new ScaleRunnale(px, py, mInitScale), 16); isAutoScale = true; } // setImageMatrix(mMatrix); return true; } }); /** * 是一个距离,表示滑动的时候,手的移动要大于这个距离才开始移动控件。如果小于这个距离就不触发移动控件,如viewpager * 就是用这个距离来判断用户是否翻页。 */ mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } private class ScaleRunnale implements Runnable { // 放大值 private static final float BIGGER = 1.08f; // 缩小值 private static final float SMALLER = 0.96f; private float x; private float y; private float mTargetScale; private float mTempScale; public ScaleRunnale(float x, float y, float mTargetScale) { super(); this.x = x; this.y = y; this.mTargetScale = mTargetScale; if (getScale() < mTargetScale) { mTempScale = BIGGER; } else if (getScale() > mTargetScale) { mTempScale = SMALLER; } } @Override public void run() { // 先进行缩放 mMatrix.postScale(mTempScale, mTempScale, x, y); checkSideAndCenterWhenScale(); setImageMatrix(mMatrix); float currentScale = getScale(); // 如果想放大,并且当前的缩放值小于目标值 if ((mTempScale > 1.0f && currentScale < mTargetScale) || (mTempScale < 1.0f && currentScale > mTargetScale)) { // 递归执行run方法 postDelayed(this, 16); } else { float scale = mTargetScale / currentScale; mMatrix.postScale(scale, scale, x, y); checkSideAndCenterWhenScale(); setImageMatrix(mMatrix); isAutoScale = false; } } } @Override public void onGlobalLayout() { // 如果还没有加载图片 if (!isOnce) { // 获得控件的宽高 int width = getWidth(); int height = getHeight(); Drawable drawable = getDrawable(); if (drawable == null) { return; } // 获得图片的宽高 int bitmapWidth = drawable.getIntrinsicWidth(); int bitmapHeight = drawable.getIntrinsicHeight(); // 设定比例值 float scale = 0.0f; // 如果图片的宽度>控件的宽度,缩小 if (bitmapWidth > width && bitmapHeight < height) { scale = width * 1.0f / bitmapWidth; } // 如果图片的高度>控件的高度,缩小 if (bitmapHeight > height && bitmapWidth < width) { scale = height * 1.0f / bitmapHeight; } // 如果图片的宽高度>控件的宽高度,缩小 或者 如果图片的宽高度<控件的宽高度,放大 if ((bitmapWidth > width && bitmapHeight > height) || (bitmapWidth < width && bitmapHeight < height)) { float f1 = width * 1.0f / bitmapWidth; float f2 = height * 1.0f / bitmapHeight; scale = Math.min(f1, f2); } // 初始化缩放值 mInitScale = scale; mClickScale = mInitScale * 2; mMaxScale = mInitScale * 4; // 得到移动的距离 int dx = width / 2 - bitmapWidth / 2; int dy = height / 2 - bitmapHeight / 2; // 平移 mMatrix.postTranslate(dx, dy); // 在控件的中心缩放 mMatrix.postScale(scale, scale, width / 2, height / 2); // 设置矩阵 setImageMatrix(mMatrix); // 关于matrix,就是个3*3的矩阵 /** * xscale xskew xtrans yskew yscale ytrans 0 0 0 */ isOnce = true; } } /** * 注册全局事件 */ @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); getViewTreeObserver().addOnGlobalLayoutListener(this); } /** * 移除全局事件 */ @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); getViewTreeObserver().removeGlobalOnLayoutListener(this); } /** * 获得缩放值 * * @return */ public float getScale() { /** * xscale xskew xtrans yskew yscale ytrans 0 0 0 */ float[] values = new float[9]; mMatrix.getValues(values); return values[Matrix.MSCALE_X]; } @Override public boolean onScale(ScaleGestureDetector detector) { // 如果没有图片,返回 if (getDrawable() == null) { return true; } // 缩放因子,>0表示正在放大,<0表示正在缩小 float intentScale = detector.getScaleFactor(); float scale = getScale(); // 进行缩放范围的控制 // 判断,如果<最大缩放值,表示可以放大,如果》最小缩放,说明可以缩小 if ((scale < mMaxScale && intentScale > 1.0f) || (scale > mInitScale && intentScale < 1.0f)) { // scale 变小时, intentScale变小 if (scale * intentScale < mInitScale) { // intentScale * scale = mInitScale ; intentScale = mInitScale / scale; } // scale 变大时, intentScale变大 if (scale * intentScale > mMaxScale) { // intentScale * scale = mMaxScale ; intentScale = mMaxScale / scale; } // 以控件为中心缩放 // mMatrix.postScale(intentScale, intentScale, getWidth()/2, // getHeight()/2); // 以手势为中心缩放 mMatrix.postScale(intentScale, intentScale, detector.getFocusX(), detector.getFocusY()); // 检测边界与中心点 checkSideAndCenterWhenScale(); setImageMatrix(mMatrix); } return true; } /** * 获得图片缩放后的矩阵 * * @return */ public RectF getMatrixRectF() { Matrix matrix = mMatrix; RectF rectF = new RectF(); Drawable drawable = getDrawable(); if (drawable != null) { // 初始化矩阵 rectF.set(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); // 移动s matrix.mapRect(rectF); } return rectF; } private void checkSideAndCenterWhenScale() { RectF rectF = getMatrixRectF(); float deltaX = 0f; float deltaY = 0f; int width = getWidth(); int height = getHeight(); // 情况1, 如果图片的宽度大于控件的宽度 if (rectF.width() >= width) { if (rectF.left > 0) { deltaX = -rectF.left;// 如果图片没有左边对齐,就往左边移动 } if (rectF.right < width) { deltaX = width - rectF.right;// 如果图片没有右边对齐,就往右边移动 } } // 情况2, 如果图片的宽度大于控件的宽度 if (rectF.height() >= height) { if (rectF.top > 0) { deltaY = -rectF.top;// } if (rectF.bottom < height) { deltaY = height - rectF.bottom;// 往底部移动 } } // 情况3,如图图片在控件内,则让其居中 if (rectF.width() < width) { // deltaX = width/2-rectF.left - rectF.width()/2; // 或 deltaX = width / 2f - rectF.right + rectF.width() / 2f; } if (rectF.height() < height) { deltaY = height / 2f - rectF.bottom + rectF.height() / 2f; } mMatrix.postTranslate(deltaX, deltaY); } @Override public boolean onScaleBegin(ScaleGestureDetector detector) { // TODO Auto-generated method stub return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { // TODO Auto-generated method stub } private float mLastX; private float mLastY; /** 上次手指的数量 */ private int mLastPointerCount; /** 判断是否检测了x,y轴 */ private boolean isCheckX; private boolean isCheckY; @Override public boolean onTouch(View v, MotionEvent event) { // 把事件传递给双击手势 if (mGesture.onTouchEvent(event)) { return true; } // 把事件传递给缩放手势 mScaleGesture.onTouchEvent(event); float x = event.getX(); float y = event.getY(); int pointerCount = event.getPointerCount(); for (int i = 0; i < pointerCount; i++) { x += event.getX(i); y += event.getY(i); } x /= pointerCount; y /= pointerCount; // 说明手指改变 if (mLastPointerCount != pointerCount) { isCanDrag = false; mLastX = x; mLastY = y; } mLastPointerCount = pointerCount; RectF rectF = getMatrixRectF(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (rectF.width() > getWidth()) { getParent().requestDisallowInterceptTouchEvent(true); } break; case MotionEvent.ACTION_MOVE: if (rectF.width() > getWidth()) { getParent().requestDisallowInterceptTouchEvent(true); } float dx = x - mLastX; float dy = y - mLastY; if (!isCanDrag) { isCanDrag = isMoveAction(dx, dy); } /** * 如果能移动 */ if (isCanDrag) { //RectF rectF = getMatrixRectF(); if (getDrawable() == null) { return true; } isCheckX = isCheckY = true; // 如果图片在控件内,不允许移动 if (rectF.width() < getWidth()) { isCheckX = false; dx = 0f; } if (rectF.height() < getHeight()) { isCheckY = false; dy = 0f; } mMatrix.postTranslate(dx, dy); // 移动事检测边界 checkSideAndCenterWhenTransate(); setImageMatrix(mMatrix); } mLastX = x; mLastY = y; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: // 清楚手指 mLastPointerCount = 0; break; } return true; } private void checkSideAndCenterWhenTransate() { RectF rectF = getMatrixRectF(); float deltaX = 0f; float deltaY = 0f; int width = getWidth(); int height = getHeight(); if (rectF.top > 0 && isCheckY) { deltaY = -rectF.top;// 往上边移动 } if (rectF.bottom < height && isCheckY) { deltaY = height - rectF.bottom;// 往底部移动 } if (rectF.left > 0 && isCheckX) { deltaX = -rectF.left;// 往左边移动 } if (rectF.right < width && isCheckX) { deltaX = width - rectF.right;// 往右边移动 } // 移动 mMatrix.postTranslate(deltaX, deltaY); } private boolean isMoveAction(float dx, float dy) { // 求得两点的距离 return Math.sqrt(dx * dx + dy * dy) > mTouchSlop; } }
1
13
1
8203_0
package me.jbusdriver.ui.widget; import android.opengl.GLES10; public class SampleSizeUtil { private static int textureSize = 0; //存在第二次拿拿不到的情况,所以把拿到的数据用一个static变量保存下来 public static final int getTextureSize() { if (textureSize > 0) { return textureSize; } int[] params = new int[1]; GLES10.glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE, params, 0); textureSize = params[0]; return textureSize; } // 将x向上对齐到2的幂指数 private static int roundup2n(int x) { if ((x & (x - 1)) == 0) { return x; } int pos = 0; while (x > 0) { x >>= 1; ++pos; } return 1 << pos; } }
Ccixyj/JBusDriver
app/src/main/java/me/jbusdriver/ui/widget/SampleSizeUtil.java
231
//存在第二次拿拿不到的情况,所以把拿到的数据用一个static变量保存下来
line_comment
zh-cn
package me.jbusdriver.ui.widget; import android.opengl.GLES10; public class SampleSizeUtil { private static int textureSize = 0; //存在 <SUF> public static final int getTextureSize() { if (textureSize > 0) { return textureSize; } int[] params = new int[1]; GLES10.glGetIntegerv(GLES10.GL_MAX_TEXTURE_SIZE, params, 0); textureSize = params[0]; return textureSize; } // 将x向上对齐到2的幂指数 private static int roundup2n(int x) { if ((x & (x - 1)) == 0) { return x; } int pos = 0; while (x > 0) { x >>= 1; ++pos; } return 1 << pos; } }
1
38
1
14421_2
package com.example.mylibrary; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity { /** * * library 中 * 1、初始化使用R2 * 2、单击事件中不能使用swith case * 3、switch case 转换成if else 如下 * */ /** * 特别注意:当副Module使用R2时候可会报红,没关系,rebuild 就好了 * 强烈建议大家 用插件 Android ButterKnife Zelezny 生成 然后在library中根据每个地方修改成R2 */ /** * 关于资源文件,layout、res 下的资源文件 每一个module 命名必须不同,如果相同运行后跑程序将以主Module资源为准 * 也就是library中资源、布局将会被替换或者忽视。 */ @BindView(R2.id.button) Button button; @BindView(R2.id.button2) Button button2; @BindView(R2.id.textView) TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_library); ButterKnife.bind(this); } /** * 单击事件 * @param view */ @OnClick({R2.id.button, R2.id.button2}) public void onViewClicked(View view) { int i = view.getId(); if (i == R.id.button) { Toast.makeText(MainActivity.this,"点击了副Module",Toast.LENGTH_SHORT).show(); } else if (i == R.id.button2) { finish(); } } }
CeleryIce/ButterKnifeDemo
mylibrary/src/main/java/com/example/mylibrary/MainActivity.java
466
/** * 关于资源文件,layout、res 下的资源文件 每一个module 命名必须不同,如果相同运行后跑程序将以主Module资源为准 * 也就是library中资源、布局将会被替换或者忽视。 */
block_comment
zh-cn
package com.example.mylibrary; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class MainActivity extends AppCompatActivity { /** * * library 中 * 1、初始化使用R2 * 2、单击事件中不能使用swith case * 3、switch case 转换成if else 如下 * */ /** * 特别注意:当副Module使用R2时候可会报红,没关系,rebuild 就好了 * 强烈建议大家 用插件 Android ButterKnife Zelezny 生成 然后在library中根据每个地方修改成R2 */ /** * 关于资 <SUF>*/ @BindView(R2.id.button) Button button; @BindView(R2.id.button2) Button button2; @BindView(R2.id.textView) TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main_library); ButterKnife.bind(this); } /** * 单击事件 * @param view */ @OnClick({R2.id.button, R2.id.button2}) public void onViewClicked(View view) { int i = view.getId(); if (i == R.id.button) { Toast.makeText(MainActivity.this,"点击了副Module",Toast.LENGTH_SHORT).show(); } else if (i == R.id.button2) { finish(); } } }
1
118
1
40952_1
package com.centurywar; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TimerTask; import com.centurywar.control.ArduinoControl; //定时运行的程序 public class TimingTask extends TimerTask { /** * 从数据为库中查出要运行的程序 */ public static void getTimingBehave() { } public static void insertTimingBehave() { // Behave be = new Behave(); } public void run() { // ArduinoControl.doCommand(1, "34_1_3_3"); Behave be = new Behave(0); // 检测缓存中有木有超时需要加入冲发表的 // this.checkCachedCommands(6, be); List<Behave> needsend = be.getNeedRunInfo(); List<Integer> hasSend = new ArrayList<Integer>(); for (int i = 0; i < needsend.size(); i++) { Behave tembe = needsend.get(i); ArduinoControl.doCommand(tembe.gameuid, tembe.behaveString); hasSend.add(tembe.id); } be.delInfo(hasSend); System.out.println("定时操作发送中……"); } public void clearSocket() { System.out.println("清空没用的连接。。。。"); Main.clearTem(); Main.clearArduino(); Main.clearAndroid(); } /** * 检查缓存中超时的命令,写入send_log表 * * @param timeout * 设置超时时间 单位为秒 * @param behave * behave对象,随时写入重发表 */ public void checkCachedCommands(int timeout, Behave behave) { // 取出缓存的集合 Set<String> cachedKeys = Redis.hkeys("cachedCommands"); // for循环遍历: for (String key : cachedKeys) { String timeStr = Redis.hget("cachedCommands", key); System.out.println(timeStr); Integer sendTime = Integer.parseInt(timeStr); Integer nowTime = new Integer( (int) (System.currentTimeMillis() / 1000)); if (nowTime - sendTime > timeout) { System.out.println("反馈超时,写入重发表:" + key); Redis.hdel("cachedCommands", key); String params[] = key.split(":"); behave.newInfo(Integer.parseInt(params[0]), 11, sendTime, params[1]); } } } }
CenturyWarDesign/Intelligent_Server
src/com/centurywar/TimingTask.java
654
/** * 从数据为库中查出要运行的程序 */
block_comment
zh-cn
package com.centurywar; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TimerTask; import com.centurywar.control.ArduinoControl; //定时运行的程序 public class TimingTask extends TimerTask { /** * 从数据 <SUF>*/ public static void getTimingBehave() { } public static void insertTimingBehave() { // Behave be = new Behave(); } public void run() { // ArduinoControl.doCommand(1, "34_1_3_3"); Behave be = new Behave(0); // 检测缓存中有木有超时需要加入冲发表的 // this.checkCachedCommands(6, be); List<Behave> needsend = be.getNeedRunInfo(); List<Integer> hasSend = new ArrayList<Integer>(); for (int i = 0; i < needsend.size(); i++) { Behave tembe = needsend.get(i); ArduinoControl.doCommand(tembe.gameuid, tembe.behaveString); hasSend.add(tembe.id); } be.delInfo(hasSend); System.out.println("定时操作发送中……"); } public void clearSocket() { System.out.println("清空没用的连接。。。。"); Main.clearTem(); Main.clearArduino(); Main.clearAndroid(); } /** * 检查缓存中超时的命令,写入send_log表 * * @param timeout * 设置超时时间 单位为秒 * @param behave * behave对象,随时写入重发表 */ public void checkCachedCommands(int timeout, Behave behave) { // 取出缓存的集合 Set<String> cachedKeys = Redis.hkeys("cachedCommands"); // for循环遍历: for (String key : cachedKeys) { String timeStr = Redis.hget("cachedCommands", key); System.out.println(timeStr); Integer sendTime = Integer.parseInt(timeStr); Integer nowTime = new Integer( (int) (System.currentTimeMillis() / 1000)); if (nowTime - sendTime > timeout) { System.out.println("反馈超时,写入重发表:" + key); Redis.hdel("cachedCommands", key); String params[] = key.split(":"); behave.newInfo(Integer.parseInt(params[0]), 11, sendTime, params[1]); } } } }
1
27
1
26834_3
package ceuilisa.mirai.response; public class LrcResponse { /** * sgc : true * sfy : true * qfy : false * lrc : {"version":10,"lyric":"[00:21.760]行くあてない街 ひとり先を歩く\n[00:31.140]夕日に照らされた 失いそうな心\n[00:41.470]変わっていくなんて 思いもしなかった\n[00:51.500]君と重ねた夢 いつの間に\n[00:58.780]違う方へと歩いてたんだね\n[01:05.170]そしていま ふたりは\n[01:10.210]遠すぎる世界 見つめて\n[01:15.600]そしていま ほら響くよ\n[01:20.470]君が教えてくれた歌 この空に\n[01:37.300]正座して並んで みんなで撮った写真\n[01:46.490]心に呼びかける 懐かしい笑顔\n[01:56.830]遠く離れてても 同じ夢の未来\n[02:06.940]繋がってるよね 信じてる\n[02:14.800]誓い合った 約束の場所\n[02:20.290]そしていま ふたりは\n[02:25.410]それぞれの道を 見つめて\n[02:30.460]そしていま また歌うよ\n[02:36.100]ふたつの想いが めぐり会う その日まで\n[03:04.450]迷いながらも\n[03:08.870]夢の色重ねる\n[03:13.940]君を想うからこそ\n[03:16.660]強くなれるよ\n[03:19.210]きっと\n[03:20.670]終わらせない\n[03:24.320]そしていま私は\n[03:29.329]君に続く空 見上げて\n[03:34.190]そしていま また歌うよ\n[03:39.730]どこにいたって 届くはずだね\n[03:44.640]そしていま ふたりは\n[03:49.710]輝く明日を 見つめて\n[03:54.720]そしていま ほら響くよ\n[04:00.240]君が教えてくれた歌 この空に\n"} * klyric : {"version":0,"lyric":null} * tlyric : {"version":2,"lyric":"[00:21.760]向着无名的街道 形单影只地前进着\n[00:31.140]被夕阳照得通红的 近乎遗失的心灵\n[00:41.470]却逐渐发生了变化 我万万也没有想到\n[00:51.500]与你在一起的梦境 不觉之间\n[00:58.780]我们却已走向了不同的道路呢\n[01:05.170]于是此刻你们两人\n[01:10.210]凝望着遥不可及的世界\n[01:15.600]于是此刻 你听 歌声响彻\n[01:20.470]你曾经教会我唱的歌谣 回响于这片天空\n[01:37.300]大家一起并肩端坐 拍下的照片\n[01:46.490]号召心中的 令人怀念的笑容\n[01:56.830]尽管彼此相距甚远 我依然相信\n[02:06.940]两人共同梦想的未来仍紧连着\n[02:14.800]在那个相互发誓的约定之地\n[02:20.290]于是此刻你们两人\n[02:25.410]凝望着各自不同的道路\n[02:30.460]于是此刻我又放声歌唱\n[02:36.100]直到两人的思念相邂逅的那天为止\n[03:04.450]在迷惘之中\n[03:08.870]也不放弃追逐梦想\n[03:13.940]正因为我思念你\n[03:16.660]才能变得坚强\n[03:19.210]一定\n[03:20.670]不会就这样结束\n[03:24.320]于是此刻我举头仰望\n[03:29.329]延伸到你身旁的天空\n[03:34.190]于是此刻我又放声歌唱\n[03:39.730]无论身处何方也应该传递得到\n[03:44.640]于是此刻你们两人\n[03:49.710]凝望着光辉闪烁的明天\n[03:54.720]于是此刻 你听 歌声响彻\n[04:00.240]你曾经教会我唱的歌谣 回响于这片天空"} * code : 200 */ private boolean sgc; private boolean uncollected; private boolean nolyric; private boolean sfy; private boolean qfy; private LrcBean lrc; private KlyricBean klyric; private TlyricBean tlyric; private int code; public boolean isUncollected() { return uncollected; } public void setUncollected(boolean uncollected) { this.uncollected = uncollected; } public boolean isNolyric() { return nolyric; } public void setNolyric(boolean nolyric) { this.nolyric = nolyric; } public boolean isSgc() { return sgc; } public void setSgc(boolean sgc) { this.sgc = sgc; } public boolean isSfy() { return sfy; } public void setSfy(boolean sfy) { this.sfy = sfy; } public boolean isQfy() { return qfy; } public void setQfy(boolean qfy) { this.qfy = qfy; } public LrcBean getLrc() { return lrc; } public void setLrc(LrcBean lrc) { this.lrc = lrc; } public KlyricBean getKlyric() { return klyric; } public void setKlyric(KlyricBean klyric) { this.klyric = klyric; } public TlyricBean getTlyric() { return tlyric; } public void setTlyric(TlyricBean tlyric) { this.tlyric = tlyric; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public static class LrcBean { /** * version : 10 * lyric : [00:21.760]行くあてない街 ひとり先を歩く * [00:31.140]夕日に照らされた 失いそうな心 * [00:41.470]変わっていくなんて 思いもしなかった * [00:51.500]君と重ねた夢 いつの間に * [00:58.780]違う方へと歩いてたんだね * [01:05.170]そしていま ふたりは * [01:10.210]遠すぎる世界 見つめて * [01:15.600]そしていま ほら響くよ * [01:20.470]君が教えてくれた歌 この空に * [01:37.300]正座して並んで みんなで撮った写真 * [01:46.490]心に呼びかける 懐かしい笑顔 * [01:56.830]遠く離れてても 同じ夢の未来 * [02:06.940]繋がってるよね 信じてる * [02:14.800]誓い合った 約束の場所 * [02:20.290]そしていま ふたりは * [02:25.410]それぞれの道を 見つめて * [02:30.460]そしていま また歌うよ * [02:36.100]ふたつの想いが めぐり会う その日まで * [03:04.450]迷いながらも * [03:08.870]夢の色重ねる * [03:13.940]君を想うからこそ * [03:16.660]強くなれるよ * [03:19.210]きっと * [03:20.670]終わらせない * [03:24.320]そしていま私は * [03:29.329]君に続く空 見上げて * [03:34.190]そしていま また歌うよ * [03:39.730]どこにいたって 届くはずだね * [03:44.640]そしていま ふたりは * [03:49.710]輝く明日を 見つめて * [03:54.720]そしていま ほら響くよ * [04:00.240]君が教えてくれた歌 この空に */ private int version; private String lyric; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getLyric() { return lyric; } public void setLyric(String lyric) { this.lyric = lyric; } } public static class KlyricBean { /** * version : 0 * lyric : null */ private int version; private Object lyric; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public Object getLyric() { return lyric; } public void setLyric(Object lyric) { this.lyric = lyric; } } public static class TlyricBean { /** * version : 2 * lyric : [00:21.760]向着无名的街道 形单影只地前进着 * [00:31.140]被夕阳照得通红的 近乎遗失的心灵 * [00:41.470]却逐渐发生了变化 我万万也没有想到 * [00:51.500]与你在一起的梦境 不觉之间 * [00:58.780]我们却已走向了不同的道路呢 * [01:05.170]于是此刻你们两人 * [01:10.210]凝望着遥不可及的世界 * [01:15.600]于是此刻 你听 歌声响彻 * [01:20.470]你曾经教会我唱的歌谣 回响于这片天空 * [01:37.300]大家一起并肩端坐 拍下的照片 * [01:46.490]号召心中的 令人怀念的笑容 * [01:56.830]尽管彼此相距甚远 我依然相信 * [02:06.940]两人共同梦想的未来仍紧连着 * [02:14.800]在那个相互发誓的约定之地 * [02:20.290]于是此刻你们两人 * [02:25.410]凝望着各自不同的道路 * [02:30.460]于是此刻我又放声歌唱 * [02:36.100]直到两人的思念相邂逅的那天为止 * [03:04.450]在迷惘之中 * [03:08.870]也不放弃追逐梦想 * [03:13.940]正因为我思念你 * [03:16.660]才能变得坚强 * [03:19.210]一定 * [03:20.670]不会就这样结束 * [03:24.320]于是此刻我举头仰望 * [03:29.329]延伸到你身旁的天空 * [03:34.190]于是此刻我又放声歌唱 * [03:39.730]无论身处何方也应该传递得到 * [03:44.640]于是此刻你们两人 * [03:49.710]凝望着光辉闪烁的明天 * [03:54.720]于是此刻 你听 歌声响彻 * [04:00.240]你曾经教会我唱的歌谣 回响于这片天空 */ private int version; private String lyric; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getLyric() { return lyric; } public void setLyric(String lyric) { this.lyric = lyric; } } }
CeuiLiSA/Emilia
app/src/main/java/ceuilisa/mirai/response/LrcResponse.java
4,052
/** * version : 2 * lyric : [00:21.760]向着无名的街道 形单影只地前进着 * [00:31.140]被夕阳照得通红的 近乎遗失的心灵 * [00:41.470]却逐渐发生了变化 我万万也没有想到 * [00:51.500]与你在一起的梦境 不觉之间 * [00:58.780]我们却已走向了不同的道路呢 * [01:05.170]于是此刻你们两人 * [01:10.210]凝望着遥不可及的世界 * [01:15.600]于是此刻 你听 歌声响彻 * [01:20.470]你曾经教会我唱的歌谣 回响于这片天空 * [01:37.300]大家一起并肩端坐 拍下的照片 * [01:46.490]号召心中的 令人怀念的笑容 * [01:56.830]尽管彼此相距甚远 我依然相信 * [02:06.940]两人共同梦想的未来仍紧连着 * [02:14.800]在那个相互发誓的约定之地 * [02:20.290]于是此刻你们两人 * [02:25.410]凝望着各自不同的道路 * [02:30.460]于是此刻我又放声歌唱 * [02:36.100]直到两人的思念相邂逅的那天为止 * [03:04.450]在迷惘之中 * [03:08.870]也不放弃追逐梦想 * [03:13.940]正因为我思念你 * [03:16.660]才能变得坚强 * [03:19.210]一定 * [03:20.670]不会就这样结束 * [03:24.320]于是此刻我举头仰望 * [03:29.329]延伸到你身旁的天空 * [03:34.190]于是此刻我又放声歌唱 * [03:39.730]无论身处何方也应该传递得到 * [03:44.640]于是此刻你们两人 * [03:49.710]凝望着光辉闪烁的明天 * [03:54.720]于是此刻 你听 歌声响彻 * [04:00.240]你曾经教会我唱的歌谣 回响于这片天空 */
block_comment
zh-cn
package ceuilisa.mirai.response; public class LrcResponse { /** * sgc : true * sfy : true * qfy : false * lrc : {"version":10,"lyric":"[00:21.760]行くあてない街 ひとり先を歩く\n[00:31.140]夕日に照らされた 失いそうな心\n[00:41.470]変わっていくなんて 思いもしなかった\n[00:51.500]君と重ねた夢 いつの間に\n[00:58.780]違う方へと歩いてたんだね\n[01:05.170]そしていま ふたりは\n[01:10.210]遠すぎる世界 見つめて\n[01:15.600]そしていま ほら響くよ\n[01:20.470]君が教えてくれた歌 この空に\n[01:37.300]正座して並んで みんなで撮った写真\n[01:46.490]心に呼びかける 懐かしい笑顔\n[01:56.830]遠く離れてても 同じ夢の未来\n[02:06.940]繋がってるよね 信じてる\n[02:14.800]誓い合った 約束の場所\n[02:20.290]そしていま ふたりは\n[02:25.410]それぞれの道を 見つめて\n[02:30.460]そしていま また歌うよ\n[02:36.100]ふたつの想いが めぐり会う その日まで\n[03:04.450]迷いながらも\n[03:08.870]夢の色重ねる\n[03:13.940]君を想うからこそ\n[03:16.660]強くなれるよ\n[03:19.210]きっと\n[03:20.670]終わらせない\n[03:24.320]そしていま私は\n[03:29.329]君に続く空 見上げて\n[03:34.190]そしていま また歌うよ\n[03:39.730]どこにいたって 届くはずだね\n[03:44.640]そしていま ふたりは\n[03:49.710]輝く明日を 見つめて\n[03:54.720]そしていま ほら響くよ\n[04:00.240]君が教えてくれた歌 この空に\n"} * klyric : {"version":0,"lyric":null} * tlyric : {"version":2,"lyric":"[00:21.760]向着无名的街道 形单影只地前进着\n[00:31.140]被夕阳照得通红的 近乎遗失的心灵\n[00:41.470]却逐渐发生了变化 我万万也没有想到\n[00:51.500]与你在一起的梦境 不觉之间\n[00:58.780]我们却已走向了不同的道路呢\n[01:05.170]于是此刻你们两人\n[01:10.210]凝望着遥不可及的世界\n[01:15.600]于是此刻 你听 歌声响彻\n[01:20.470]你曾经教会我唱的歌谣 回响于这片天空\n[01:37.300]大家一起并肩端坐 拍下的照片\n[01:46.490]号召心中的 令人怀念的笑容\n[01:56.830]尽管彼此相距甚远 我依然相信\n[02:06.940]两人共同梦想的未来仍紧连着\n[02:14.800]在那个相互发誓的约定之地\n[02:20.290]于是此刻你们两人\n[02:25.410]凝望着各自不同的道路\n[02:30.460]于是此刻我又放声歌唱\n[02:36.100]直到两人的思念相邂逅的那天为止\n[03:04.450]在迷惘之中\n[03:08.870]也不放弃追逐梦想\n[03:13.940]正因为我思念你\n[03:16.660]才能变得坚强\n[03:19.210]一定\n[03:20.670]不会就这样结束\n[03:24.320]于是此刻我举头仰望\n[03:29.329]延伸到你身旁的天空\n[03:34.190]于是此刻我又放声歌唱\n[03:39.730]无论身处何方也应该传递得到\n[03:44.640]于是此刻你们两人\n[03:49.710]凝望着光辉闪烁的明天\n[03:54.720]于是此刻 你听 歌声响彻\n[04:00.240]你曾经教会我唱的歌谣 回响于这片天空"} * code : 200 */ private boolean sgc; private boolean uncollected; private boolean nolyric; private boolean sfy; private boolean qfy; private LrcBean lrc; private KlyricBean klyric; private TlyricBean tlyric; private int code; public boolean isUncollected() { return uncollected; } public void setUncollected(boolean uncollected) { this.uncollected = uncollected; } public boolean isNolyric() { return nolyric; } public void setNolyric(boolean nolyric) { this.nolyric = nolyric; } public boolean isSgc() { return sgc; } public void setSgc(boolean sgc) { this.sgc = sgc; } public boolean isSfy() { return sfy; } public void setSfy(boolean sfy) { this.sfy = sfy; } public boolean isQfy() { return qfy; } public void setQfy(boolean qfy) { this.qfy = qfy; } public LrcBean getLrc() { return lrc; } public void setLrc(LrcBean lrc) { this.lrc = lrc; } public KlyricBean getKlyric() { return klyric; } public void setKlyric(KlyricBean klyric) { this.klyric = klyric; } public TlyricBean getTlyric() { return tlyric; } public void setTlyric(TlyricBean tlyric) { this.tlyric = tlyric; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public static class LrcBean { /** * version : 10 * lyric : [00:21.760]行くあてない街 ひとり先を歩く * [00:31.140]夕日に照らされた 失いそうな心 * [00:41.470]変わっていくなんて 思いもしなかった * [00:51.500]君と重ねた夢 いつの間に * [00:58.780]違う方へと歩いてたんだね * [01:05.170]そしていま ふたりは * [01:10.210]遠すぎる世界 見つめて * [01:15.600]そしていま ほら響くよ * [01:20.470]君が教えてくれた歌 この空に * [01:37.300]正座して並んで みんなで撮った写真 * [01:46.490]心に呼びかける 懐かしい笑顔 * [01:56.830]遠く離れてても 同じ夢の未来 * [02:06.940]繋がってるよね 信じてる * [02:14.800]誓い合った 約束の場所 * [02:20.290]そしていま ふたりは * [02:25.410]それぞれの道を 見つめて * [02:30.460]そしていま また歌うよ * [02:36.100]ふたつの想いが めぐり会う その日まで * [03:04.450]迷いながらも * [03:08.870]夢の色重ねる * [03:13.940]君を想うからこそ * [03:16.660]強くなれるよ * [03:19.210]きっと * [03:20.670]終わらせない * [03:24.320]そしていま私は * [03:29.329]君に続く空 見上げて * [03:34.190]そしていま また歌うよ * [03:39.730]どこにいたって 届くはずだね * [03:44.640]そしていま ふたりは * [03:49.710]輝く明日を 見つめて * [03:54.720]そしていま ほら響くよ * [04:00.240]君が教えてくれた歌 この空に */ private int version; private String lyric; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getLyric() { return lyric; } public void setLyric(String lyric) { this.lyric = lyric; } } public static class KlyricBean { /** * version : 0 * lyric : null */ private int version; private Object lyric; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public Object getLyric() { return lyric; } public void setLyric(Object lyric) { this.lyric = lyric; } } public static class TlyricBean { /** * ver <SUF>*/ private int version; private String lyric; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getLyric() { return lyric; } public void setLyric(String lyric) { this.lyric = lyric; } } }
0
1,151
0
4271_1
package ceui.lisa.page.animation; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Iterator; /** * Created by newbiechen on 17-7-23. * 原理:仿照ListView源码实现的上下滑动效果 * Alter by: zeroAngus * <p> * 问题: * 1. 向上翻页,重复的问题 (完成) * 2. 滑动卡顿的问题。原因:由于绘制的数据过多造成的卡顿问题。 (主要是文字绘制需要的时长比较多) 解决办法:做文字缓冲 * 3. 弱网环境下,显示的问题 */ public class ScrollPageAnim extends PageAnimation { private static final String TAG = "ScrollAnimation"; // 滑动追踪的时间 private static final int VELOCITY_DURATION = 1000; BitmapView tmpView; private VelocityTracker mVelocity; // 整个Bitmap的背景显示 private Bitmap mBgBitmap; // 下一个展示的图片 private Bitmap mNextBitmap; // 被废弃的图片列表 private ArrayDeque<BitmapView> mScrapViews; // 正在被利用的图片列表 private final ArrayList<BitmapView> mActiveViews = new ArrayList<>(2); // 是否处于刷新阶段 private boolean isRefresh = true; // 底部填充 private Iterator<BitmapView> downIt; private Iterator<BitmapView> upIt; public ScrollPageAnim(int w, int h, int marginWidth, int marginHeight, View view, OnPageChangeListener listener) { super(w, h, marginWidth, marginHeight, view, listener); // 创建两个BitmapView initWidget(); } private void initWidget() { mBgBitmap = Bitmap.createBitmap(mScreenWidth, mScreenHeight, Bitmap.Config.RGB_565); mScrapViews = new ArrayDeque<>(2); for (int i = 0; i < 2; ++i) { BitmapView view = new BitmapView(); view.bitmap = Bitmap.createBitmap(mViewWidth, mViewHeight, Bitmap.Config.RGB_565); view.srcRect = new Rect(0, 0, mViewWidth, mViewHeight); view.destRect = new Rect(0, 0, mViewWidth, mViewHeight); view.top = 0; view.bottom = view.bitmap.getHeight(); mScrapViews.push(view); } onLayout(); isRefresh = false; } // 修改布局,填充内容 private void onLayout() { // 如果还没有开始加载,则从上到下进行绘制 if (mActiveViews.size() == 0) { fillDown(0, 0); mDirection = Direction.NONE; } else { int offset = (int) (mTouchY - mLastY); // 判断是下滑还是上拉 (下滑) if (offset > 0) { int topEdge = mActiveViews.get(0).top; fillUp(topEdge, offset); } // 上拉 else { // 底部的距离 = 当前底部的距离 + 滑动的距离 (因为上滑,得到的值肯定是负的) int bottomEdge = mActiveViews.get(mActiveViews.size() - 1).bottom; fillDown(bottomEdge, offset); } } } /** * 创建View填充底部空白部分 * * @param bottomEdge :当前最后一个View的底部,在整个屏幕上的位置,即相对于屏幕顶部的距离 * @param offset :滑动的偏移量 */ private void fillDown(int bottomEdge, int offset) { downIt = mActiveViews.iterator(); BitmapView view; // 进行删除 while (downIt.hasNext()) { view = downIt.next(); view.top = view.top + offset; view.bottom = view.bottom + offset; // 设置允许显示的范围 view.destRect.top = view.top; view.destRect.bottom = view.bottom; // 判断是否越界了 if (view.bottom <= 0) { // 添加到废弃的View中 mScrapViews.add(view); // 从Active中移除 downIt.remove(); // 如果原先是从上加载,现在变成从下加载,则表示取消 if (mDirection == Direction.UP) { mListener.pageCancel(); mDirection = Direction.NONE; } } } // 滑动之后的最后一个 View 的距离屏幕顶部上的实际位置 int realEdge = bottomEdge + offset; // 进行填充 while (realEdge < mViewHeight && mActiveViews.size() < 2) { // 从废弃的Views中获取一个 view = mScrapViews.getFirst(); /* //擦除其Bitmap(重新创建会不会更好一点) eraseBitmap(view.bitmap,view.bitmap.getWidth(),view.bitmap.getHeight(),0,0);*/ if (view == null) return; Bitmap cancelBitmap = mNextBitmap; mNextBitmap = view.bitmap; if (!isRefresh) { boolean hasNext = mListener.hasNext(true); //如果不成功则无法滑动 // 如果不存在next,则进行还原 if (!hasNext) { mNextBitmap = cancelBitmap; for (BitmapView activeView : mActiveViews) { activeView.top = 0; activeView.bottom = mViewHeight; // 设置允许显示的范围 activeView.destRect.top = activeView.top; activeView.destRect.bottom = activeView.bottom; } abortAnim(); return; } } // 如果加载成功,那么就将View从ScrapViews中移除 mScrapViews.removeFirst(); // 添加到存活的Bitmap中 mActiveViews.add(view); mDirection = Direction.DOWN; // 设置Bitmap的范围 view.top = realEdge; view.bottom = realEdge + view.bitmap.getHeight(); // 设置允许显示的范围 view.destRect.top = view.top; view.destRect.bottom = view.bottom; realEdge += view.bitmap.getHeight(); } } /** * 创建View填充顶部空白部分 * * @param topEdge : 当前第一个View的顶部,到屏幕顶部的距离 * @param offset : 滑动的偏移量 */ private void fillUp(int topEdge, int offset) { // 首先进行布局的调整 upIt = mActiveViews.iterator(); BitmapView view; while (upIt.hasNext()) { view = upIt.next(); view.top = view.top + offset; view.bottom = view.bottom + offset; //设置允许显示的范围 view.destRect.top = view.top; view.destRect.bottom = view.bottom; // 判断是否越界了 if (view.top >= mViewHeight) { // 添加到废弃的View中 mScrapViews.add(view); // 从Active中移除 upIt.remove(); // 如果原先是下,现在变成从上加载了,则表示取消加载 if (mDirection == Direction.DOWN) { mListener.pageCancel(); mDirection = Direction.NONE; } } } // 滑动之后,第一个 View 的顶部距离屏幕顶部的实际位置。 int realEdge = topEdge + offset; // 对布局进行View填充 while (realEdge > 0 && mActiveViews.size() < 2) { // 从废弃的Views中获取一个 view = mScrapViews.getFirst(); if (view == null) return; // 判断是否存在上一章节 Bitmap cancelBitmap = mNextBitmap; mNextBitmap = view.bitmap; if (!isRefresh) { boolean hasPrev = mListener.hasPrev(true); // 如果不成功则无法滑动 // 如果不存在next,则进行还原 if (!hasPrev) { mNextBitmap = cancelBitmap; for (BitmapView activeView : mActiveViews) { activeView.top = 0; activeView.bottom = mViewHeight; // 设置允许显示的范围 activeView.destRect.top = activeView.top; activeView.destRect.bottom = activeView.bottom; } abortAnim(); return; } } // 如果加载成功,那么就将View从ScrapViews中移除 mScrapViews.removeFirst(); // 加入到存活的对象中 mActiveViews.add(0, view); mDirection = Direction.UP; // 设置Bitmap的范围 view.top = realEdge - view.bitmap.getHeight(); view.bottom = realEdge; // 设置允许显示的范围 view.destRect.top = view.top; view.destRect.bottom = view.bottom; realEdge -= view.bitmap.getHeight(); } } /** * 对Bitmap进行擦除 * * @param b * @param width * @param height * @param paddingLeft * @param paddingTop */ private void eraseBitmap(Bitmap b, int width, int height, int paddingLeft, int paddingTop) { /* if (mInitBitmapPix == null) return; b.setPixels(mInitBitmapPix, 0, width, paddingLeft, paddingTop, width, height);*/ } /** * 重置位移 */ public void resetBitmap() { isRefresh = true; // 将所有的Active加入到Scrap中 for (BitmapView view : mActiveViews) { mScrapViews.add(view); } // 清除所有的Active mActiveViews.clear(); // 重新进行布局 onLayout(); isRefresh = false; } @Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); // 初始化速度追踪器 if (mVelocity == null) { mVelocity = VelocityTracker.obtain(); } mVelocity.addMovement(event); // 设置触碰点 setTouchPoint(x, y); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: isRunning = false; // 设置起始点 setStartPoint(x, y); // 停止动画 abortAnim(); break; case MotionEvent.ACTION_MOVE: mVelocity.computeCurrentVelocity(VELOCITY_DURATION); isRunning = true; // 进行刷新 mView.postInvalidate(); break; case MotionEvent.ACTION_UP: isRunning = false; // 开启动画 startAnim(); // 删除检测器 mVelocity.recycle(); mVelocity = null; break; case MotionEvent.ACTION_CANCEL: try { mVelocity.recycle(); // if velocityTracker won't be used should be recycled mVelocity = null; } catch (Exception e) { e.printStackTrace(); } break; } return true; } @Override public void draw(Canvas canvas) { //进行布局 onLayout(); //绘制背景 canvas.drawBitmap(mBgBitmap, 0, 0, null); //绘制内容 canvas.save(); //移动位置 canvas.translate(0, mMarginHeight); //裁剪显示区域 canvas.clipRect(0, 0, mViewWidth, mViewHeight); /* //设置背景透明 canvas.drawColor(0x40);*/ //绘制Bitmap for (int i = 0; i < mActiveViews.size(); ++i) { tmpView = mActiveViews.get(i); canvas.drawBitmap(tmpView.bitmap, tmpView.srcRect, tmpView.destRect, null); } canvas.restore(); } @Override public synchronized void startAnim() { isRunning = true; mScroller.fling(0, (int) mTouchY, 0, (int) mVelocity.getYVelocity() , 0, 0, Integer.MAX_VALUE * -1, Integer.MAX_VALUE); } @Override public void scrollAnim() { if (mScroller.computeScrollOffset()) { int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); setTouchPoint(x, y); if (mScroller.getFinalX() == x && mScroller.getFinalY() == y) { isRunning = false; autoPageIsRunning = false; } mView.postInvalidate(); } } @Override public void abortAnim() { if (!mScroller.isFinished()) { mScroller.abortAnimation(); isRunning = false; autoPageIsRunning = false; } } @Override public Bitmap getBgBitmap() { return mBgBitmap; } @Override public Bitmap getNextBitmap() { return mNextBitmap; } private static class BitmapView { Bitmap bitmap; Rect srcRect; Rect destRect; int top; int bottom; } }
CeuiLiSA/Pixiv-Shaft
app/src/main/java/ceui/lisa/page/animation/ScrollPageAnim.java
3,140
// 滑动追踪的时间
line_comment
zh-cn
package ceui.lisa.page.animation; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Rect; import android.view.MotionEvent; import android.view.VelocityTracker; import android.view.View; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Iterator; /** * Created by newbiechen on 17-7-23. * 原理:仿照ListView源码实现的上下滑动效果 * Alter by: zeroAngus * <p> * 问题: * 1. 向上翻页,重复的问题 (完成) * 2. 滑动卡顿的问题。原因:由于绘制的数据过多造成的卡顿问题。 (主要是文字绘制需要的时长比较多) 解决办法:做文字缓冲 * 3. 弱网环境下,显示的问题 */ public class ScrollPageAnim extends PageAnimation { private static final String TAG = "ScrollAnimation"; // 滑动 <SUF> private static final int VELOCITY_DURATION = 1000; BitmapView tmpView; private VelocityTracker mVelocity; // 整个Bitmap的背景显示 private Bitmap mBgBitmap; // 下一个展示的图片 private Bitmap mNextBitmap; // 被废弃的图片列表 private ArrayDeque<BitmapView> mScrapViews; // 正在被利用的图片列表 private final ArrayList<BitmapView> mActiveViews = new ArrayList<>(2); // 是否处于刷新阶段 private boolean isRefresh = true; // 底部填充 private Iterator<BitmapView> downIt; private Iterator<BitmapView> upIt; public ScrollPageAnim(int w, int h, int marginWidth, int marginHeight, View view, OnPageChangeListener listener) { super(w, h, marginWidth, marginHeight, view, listener); // 创建两个BitmapView initWidget(); } private void initWidget() { mBgBitmap = Bitmap.createBitmap(mScreenWidth, mScreenHeight, Bitmap.Config.RGB_565); mScrapViews = new ArrayDeque<>(2); for (int i = 0; i < 2; ++i) { BitmapView view = new BitmapView(); view.bitmap = Bitmap.createBitmap(mViewWidth, mViewHeight, Bitmap.Config.RGB_565); view.srcRect = new Rect(0, 0, mViewWidth, mViewHeight); view.destRect = new Rect(0, 0, mViewWidth, mViewHeight); view.top = 0; view.bottom = view.bitmap.getHeight(); mScrapViews.push(view); } onLayout(); isRefresh = false; } // 修改布局,填充内容 private void onLayout() { // 如果还没有开始加载,则从上到下进行绘制 if (mActiveViews.size() == 0) { fillDown(0, 0); mDirection = Direction.NONE; } else { int offset = (int) (mTouchY - mLastY); // 判断是下滑还是上拉 (下滑) if (offset > 0) { int topEdge = mActiveViews.get(0).top; fillUp(topEdge, offset); } // 上拉 else { // 底部的距离 = 当前底部的距离 + 滑动的距离 (因为上滑,得到的值肯定是负的) int bottomEdge = mActiveViews.get(mActiveViews.size() - 1).bottom; fillDown(bottomEdge, offset); } } } /** * 创建View填充底部空白部分 * * @param bottomEdge :当前最后一个View的底部,在整个屏幕上的位置,即相对于屏幕顶部的距离 * @param offset :滑动的偏移量 */ private void fillDown(int bottomEdge, int offset) { downIt = mActiveViews.iterator(); BitmapView view; // 进行删除 while (downIt.hasNext()) { view = downIt.next(); view.top = view.top + offset; view.bottom = view.bottom + offset; // 设置允许显示的范围 view.destRect.top = view.top; view.destRect.bottom = view.bottom; // 判断是否越界了 if (view.bottom <= 0) { // 添加到废弃的View中 mScrapViews.add(view); // 从Active中移除 downIt.remove(); // 如果原先是从上加载,现在变成从下加载,则表示取消 if (mDirection == Direction.UP) { mListener.pageCancel(); mDirection = Direction.NONE; } } } // 滑动之后的最后一个 View 的距离屏幕顶部上的实际位置 int realEdge = bottomEdge + offset; // 进行填充 while (realEdge < mViewHeight && mActiveViews.size() < 2) { // 从废弃的Views中获取一个 view = mScrapViews.getFirst(); /* //擦除其Bitmap(重新创建会不会更好一点) eraseBitmap(view.bitmap,view.bitmap.getWidth(),view.bitmap.getHeight(),0,0);*/ if (view == null) return; Bitmap cancelBitmap = mNextBitmap; mNextBitmap = view.bitmap; if (!isRefresh) { boolean hasNext = mListener.hasNext(true); //如果不成功则无法滑动 // 如果不存在next,则进行还原 if (!hasNext) { mNextBitmap = cancelBitmap; for (BitmapView activeView : mActiveViews) { activeView.top = 0; activeView.bottom = mViewHeight; // 设置允许显示的范围 activeView.destRect.top = activeView.top; activeView.destRect.bottom = activeView.bottom; } abortAnim(); return; } } // 如果加载成功,那么就将View从ScrapViews中移除 mScrapViews.removeFirst(); // 添加到存活的Bitmap中 mActiveViews.add(view); mDirection = Direction.DOWN; // 设置Bitmap的范围 view.top = realEdge; view.bottom = realEdge + view.bitmap.getHeight(); // 设置允许显示的范围 view.destRect.top = view.top; view.destRect.bottom = view.bottom; realEdge += view.bitmap.getHeight(); } } /** * 创建View填充顶部空白部分 * * @param topEdge : 当前第一个View的顶部,到屏幕顶部的距离 * @param offset : 滑动的偏移量 */ private void fillUp(int topEdge, int offset) { // 首先进行布局的调整 upIt = mActiveViews.iterator(); BitmapView view; while (upIt.hasNext()) { view = upIt.next(); view.top = view.top + offset; view.bottom = view.bottom + offset; //设置允许显示的范围 view.destRect.top = view.top; view.destRect.bottom = view.bottom; // 判断是否越界了 if (view.top >= mViewHeight) { // 添加到废弃的View中 mScrapViews.add(view); // 从Active中移除 upIt.remove(); // 如果原先是下,现在变成从上加载了,则表示取消加载 if (mDirection == Direction.DOWN) { mListener.pageCancel(); mDirection = Direction.NONE; } } } // 滑动之后,第一个 View 的顶部距离屏幕顶部的实际位置。 int realEdge = topEdge + offset; // 对布局进行View填充 while (realEdge > 0 && mActiveViews.size() < 2) { // 从废弃的Views中获取一个 view = mScrapViews.getFirst(); if (view == null) return; // 判断是否存在上一章节 Bitmap cancelBitmap = mNextBitmap; mNextBitmap = view.bitmap; if (!isRefresh) { boolean hasPrev = mListener.hasPrev(true); // 如果不成功则无法滑动 // 如果不存在next,则进行还原 if (!hasPrev) { mNextBitmap = cancelBitmap; for (BitmapView activeView : mActiveViews) { activeView.top = 0; activeView.bottom = mViewHeight; // 设置允许显示的范围 activeView.destRect.top = activeView.top; activeView.destRect.bottom = activeView.bottom; } abortAnim(); return; } } // 如果加载成功,那么就将View从ScrapViews中移除 mScrapViews.removeFirst(); // 加入到存活的对象中 mActiveViews.add(0, view); mDirection = Direction.UP; // 设置Bitmap的范围 view.top = realEdge - view.bitmap.getHeight(); view.bottom = realEdge; // 设置允许显示的范围 view.destRect.top = view.top; view.destRect.bottom = view.bottom; realEdge -= view.bitmap.getHeight(); } } /** * 对Bitmap进行擦除 * * @param b * @param width * @param height * @param paddingLeft * @param paddingTop */ private void eraseBitmap(Bitmap b, int width, int height, int paddingLeft, int paddingTop) { /* if (mInitBitmapPix == null) return; b.setPixels(mInitBitmapPix, 0, width, paddingLeft, paddingTop, width, height);*/ } /** * 重置位移 */ public void resetBitmap() { isRefresh = true; // 将所有的Active加入到Scrap中 for (BitmapView view : mActiveViews) { mScrapViews.add(view); } // 清除所有的Active mActiveViews.clear(); // 重新进行布局 onLayout(); isRefresh = false; } @Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); // 初始化速度追踪器 if (mVelocity == null) { mVelocity = VelocityTracker.obtain(); } mVelocity.addMovement(event); // 设置触碰点 setTouchPoint(x, y); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: isRunning = false; // 设置起始点 setStartPoint(x, y); // 停止动画 abortAnim(); break; case MotionEvent.ACTION_MOVE: mVelocity.computeCurrentVelocity(VELOCITY_DURATION); isRunning = true; // 进行刷新 mView.postInvalidate(); break; case MotionEvent.ACTION_UP: isRunning = false; // 开启动画 startAnim(); // 删除检测器 mVelocity.recycle(); mVelocity = null; break; case MotionEvent.ACTION_CANCEL: try { mVelocity.recycle(); // if velocityTracker won't be used should be recycled mVelocity = null; } catch (Exception e) { e.printStackTrace(); } break; } return true; } @Override public void draw(Canvas canvas) { //进行布局 onLayout(); //绘制背景 canvas.drawBitmap(mBgBitmap, 0, 0, null); //绘制内容 canvas.save(); //移动位置 canvas.translate(0, mMarginHeight); //裁剪显示区域 canvas.clipRect(0, 0, mViewWidth, mViewHeight); /* //设置背景透明 canvas.drawColor(0x40);*/ //绘制Bitmap for (int i = 0; i < mActiveViews.size(); ++i) { tmpView = mActiveViews.get(i); canvas.drawBitmap(tmpView.bitmap, tmpView.srcRect, tmpView.destRect, null); } canvas.restore(); } @Override public synchronized void startAnim() { isRunning = true; mScroller.fling(0, (int) mTouchY, 0, (int) mVelocity.getYVelocity() , 0, 0, Integer.MAX_VALUE * -1, Integer.MAX_VALUE); } @Override public void scrollAnim() { if (mScroller.computeScrollOffset()) { int x = mScroller.getCurrX(); int y = mScroller.getCurrY(); setTouchPoint(x, y); if (mScroller.getFinalX() == x && mScroller.getFinalY() == y) { isRunning = false; autoPageIsRunning = false; } mView.postInvalidate(); } } @Override public void abortAnim() { if (!mScroller.isFinished()) { mScroller.abortAnimation(); isRunning = false; autoPageIsRunning = false; } } @Override public Bitmap getBgBitmap() { return mBgBitmap; } @Override public Bitmap getNextBitmap() { return mNextBitmap; } private static class BitmapView { Bitmap bitmap; Rect srcRect; Rect destRect; int top; int bottom; } }
1
10
1
31115_4
package com.code.study.structure.queue; /** * @author chaiyym * @createTime 2021/7/19 14:56 */ public class QueueArray implements Queue { //数组的默认容量 public static final int CAPACITY = 1000; //数组的实际容量 protected int capacity; //对象数组 protected Object[] Q; //队首元素的位置 protected int f = 0; //队尾元素的位置 protected int r = 0; public QueueArray() { this(CAPACITY); } public QueueArray(int capacity) { Q = new Object[capacity]; } @Override public int getSize() { return (capacity - f + r) % capacity; } @Override public boolean isEmpty() { return (f == r); } @Override public Object front() throws Exception { if (isEmpty()) { throw new Exception("意外:队列空"); } return Q[f]; } @Override public void enqueue(Object obj) throws Exception { if (getSize() == capacity - 1) { throw new Exception("Queue overflow."); } Q[r] = obj; r = (r + 1) % capacity; } @Override public Object dequeue() throws Exception { Object elem; if (isEmpty()) { throw new Exception("意外:队列空"); } elem = Q[f]; Q[f] = null; f = (f + 1) % capacity; return elem; } @Override public void traversal() { for (int i = f; i < r; i++) { System.out.print(Q[i] + " "); } System.out.println(); } }
Chaiyym/structure_algorithm
src/com/code/study/structure/queue/QueueArray.java
416
//队首元素的位置
line_comment
zh-cn
package com.code.study.structure.queue; /** * @author chaiyym * @createTime 2021/7/19 14:56 */ public class QueueArray implements Queue { //数组的默认容量 public static final int CAPACITY = 1000; //数组的实际容量 protected int capacity; //对象数组 protected Object[] Q; //队首 <SUF> protected int f = 0; //队尾元素的位置 protected int r = 0; public QueueArray() { this(CAPACITY); } public QueueArray(int capacity) { Q = new Object[capacity]; } @Override public int getSize() { return (capacity - f + r) % capacity; } @Override public boolean isEmpty() { return (f == r); } @Override public Object front() throws Exception { if (isEmpty()) { throw new Exception("意外:队列空"); } return Q[f]; } @Override public void enqueue(Object obj) throws Exception { if (getSize() == capacity - 1) { throw new Exception("Queue overflow."); } Q[r] = obj; r = (r + 1) % capacity; } @Override public Object dequeue() throws Exception { Object elem; if (isEmpty()) { throw new Exception("意外:队列空"); } elem = Q[f]; Q[f] = null; f = (f + 1) % capacity; return elem; } @Override public void traversal() { for (int i = f; i < r; i++) { System.out.print(Q[i] + " "); } System.out.println(); } }
1
9
1
21411_10
package com.time.enums; /** * 特殊时间表达转换(转换特殊时间表达为可解析的时间表达) * * @author Xianjie Wu [email protected] * @date 2019年7月18日 下午6:06:05 */ public enum SpTimeExp { // 大前天(上上上一天) LAST_LAST_LAST_DAY(new String[] { "大前天" }), // 前天(上上一天) LAST_LAST_DAY(new String[] { "前天", "上上日" }), // 昨天(上一天) LAST_DAY(new String[] { "昨天", "昨日", "前一天" }), // 上上上月(上上上一月) // LAST_LAST_LAST_MONTH(new String[] { "去年", "前一年", "上一年" }), // 上上月(上上一月) LAST_LAST_MONTH(new String[] { "上上个月", "上上月" }), // 上月(上一月) LAST_MONTH(new String[] { "上个月", "上一个月", "上一月" }), // 大前年(上上上一年) LAST_LAST_LAST_YEAR(new String[] { "大前年" }), // 前年(上上一年) LAST_LAST_YEAR(new String[] { "前年", "上上一年" }), // 去年(上一年) LAST_YEAR(new String[] {"去年底", "去年", "前一年", "上一年" }); private String[] exps; private SpTimeExp(String[] exps) { this.exps = exps; } public String[] getExps() { return exps; } }
Challenging6/TimePeriod-NLP
src/com/time/enums/SpTimeExp.java
470
// 去年(上一年)
line_comment
zh-cn
package com.time.enums; /** * 特殊时间表达转换(转换特殊时间表达为可解析的时间表达) * * @author Xianjie Wu [email protected] * @date 2019年7月18日 下午6:06:05 */ public enum SpTimeExp { // 大前天(上上上一天) LAST_LAST_LAST_DAY(new String[] { "大前天" }), // 前天(上上一天) LAST_LAST_DAY(new String[] { "前天", "上上日" }), // 昨天(上一天) LAST_DAY(new String[] { "昨天", "昨日", "前一天" }), // 上上上月(上上上一月) // LAST_LAST_LAST_MONTH(new String[] { "去年", "前一年", "上一年" }), // 上上月(上上一月) LAST_LAST_MONTH(new String[] { "上上个月", "上上月" }), // 上月(上一月) LAST_MONTH(new String[] { "上个月", "上一个月", "上一月" }), // 大前年(上上上一年) LAST_LAST_LAST_YEAR(new String[] { "大前年" }), // 前年(上上一年) LAST_LAST_YEAR(new String[] { "前年", "上上一年" }), // 去年 <SUF> LAST_YEAR(new String[] {"去年底", "去年", "前一年", "上一年" }); private String[] exps; private SpTimeExp(String[] exps) { this.exps = exps; } public String[] getExps() { return exps; } }
1
10
1
54653_0
package net.createlight.champrin.simplegame.games; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.entity.Entity; import cn.nukkit.event.EventHandler; import cn.nukkit.event.EventPriority; import cn.nukkit.event.Listener; import cn.nukkit.event.block.BlockBreakEvent; import cn.nukkit.event.entity.EntityInventoryChangeEvent; import cn.nukkit.item.Item; import net.createlight.champrin.simplegame.Room; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Random; public class MakeItem extends Games implements Listener { public LinkedHashMap<String, ArrayList<Integer>> project = new LinkedHashMap<>(); private int type; private String item_repeat_make; public MakeItem(Room room) { super(room); this.type = new Random().nextInt(3)+1; this.item_repeat_make = room.plugin.config.getString("item-repeat-make"); } public boolean isCraft(String name, int itemId) { return project.get(name).contains(itemId); } //Material:干草块,铁块,原石,木头,红石块,金块 //Target:面包 铁砧 熔炉 音乐盒 充能铁轨 public void MakeItem_1(Player player, int item) { String name = player.getName(); if (isCraft(name, item)) { player.sendMessage(item_repeat_make); return; } if (item == Item.BREAD || item == Item.ANVIL || item == Item.FURNACE || item == Item.NOTEBLOCK || item == Item.POWERED_RAIL) { room.addPoint(player, 1); project.get(name).add(item); } } //Material:金块 钻石块 南瓜 木头 煤块 铁块 红石块 原石 //Target:金剑 钻石甲 南瓜灯 活塞 运输矿车 public void MakeItem_2(Player player, int item) { String name = player.getName(); if (isCraft(name, item)) { player.sendMessage(item_repeat_make); return; } if (item == Item.GOLD_SWORD || item == Item.DIAMOND_CHESTPLATE || item == Item.JACK_O_LANTERN || item == Item.PISTON || item == Item.MINECART_WITH_CHEST) { room.addPoint(player, 1); project.get(name).add(item); } } //Material:木头 干草块 铁块 原石 粘液块 //Target:门 漏斗矿车 面包 剪刀 粘性活塞 public void MakeItem_3(Player player, int item) { String name = player.getName(); if (isCraft(name, item)) { player.sendMessage(item_repeat_make); return; } if (item == Item.DOOR_BLOCK || item == Item.MINECART_WITH_HOPPER || item == Item.BREAD || item == Item.SHEARS || item == Item.STICKY_PISTON) { room.addPoint(player, 1); project.get(name).add(item); } } @EventHandler(priority = EventPriority.MONITOR) public void onPickup(EntityInventoryChangeEvent event) { if (room.gameType.equals("MakeItem")) { Entity player = event.getEntity(); if (player instanceof Player) { if (room.gamePlayer.contains((Player) player)) { if (this.type == 1) { this.MakeItem_1((Player) player, event.getNewItem().getId()); } else if (this.type == 2) { this.MakeItem_2((Player) player, event.getNewItem().getId()); } else if (this.type == 3) { this.MakeItem_3((Player) player, event.getNewItem().getId()); } if (this.room.rank.get(((Player) player).getName()) == 5) { gameFinish((Player) player); } } } } } @EventHandler(priority = EventPriority.MONITOR) public void onBreak(BlockBreakEvent event) { if (room.gameType.equals("MakeItem")) { Player player = event.getPlayer(); if (room.gamePlayer.contains(player)) { Block block = event.getBlock(); event.setDrops(null); player.getInventory().addItem(Item.get(block.getId(), block.getDamage())); event.setCancelled(true); } } } @Override public void madeArena() { this.type = new Random().nextInt(3)+1; } }
Champrin/SimpleGame
src/net/createlight/champrin/simplegame/games/MakeItem.java
1,199
//Material:干草块,铁块,原石,木头,红石块,金块
line_comment
zh-cn
package net.createlight.champrin.simplegame.games; import cn.nukkit.Player; import cn.nukkit.block.Block; import cn.nukkit.entity.Entity; import cn.nukkit.event.EventHandler; import cn.nukkit.event.EventPriority; import cn.nukkit.event.Listener; import cn.nukkit.event.block.BlockBreakEvent; import cn.nukkit.event.entity.EntityInventoryChangeEvent; import cn.nukkit.item.Item; import net.createlight.champrin.simplegame.Room; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Random; public class MakeItem extends Games implements Listener { public LinkedHashMap<String, ArrayList<Integer>> project = new LinkedHashMap<>(); private int type; private String item_repeat_make; public MakeItem(Room room) { super(room); this.type = new Random().nextInt(3)+1; this.item_repeat_make = room.plugin.config.getString("item-repeat-make"); } public boolean isCraft(String name, int itemId) { return project.get(name).contains(itemId); } //Ma <SUF> //Target:面包 铁砧 熔炉 音乐盒 充能铁轨 public void MakeItem_1(Player player, int item) { String name = player.getName(); if (isCraft(name, item)) { player.sendMessage(item_repeat_make); return; } if (item == Item.BREAD || item == Item.ANVIL || item == Item.FURNACE || item == Item.NOTEBLOCK || item == Item.POWERED_RAIL) { room.addPoint(player, 1); project.get(name).add(item); } } //Material:金块 钻石块 南瓜 木头 煤块 铁块 红石块 原石 //Target:金剑 钻石甲 南瓜灯 活塞 运输矿车 public void MakeItem_2(Player player, int item) { String name = player.getName(); if (isCraft(name, item)) { player.sendMessage(item_repeat_make); return; } if (item == Item.GOLD_SWORD || item == Item.DIAMOND_CHESTPLATE || item == Item.JACK_O_LANTERN || item == Item.PISTON || item == Item.MINECART_WITH_CHEST) { room.addPoint(player, 1); project.get(name).add(item); } } //Material:木头 干草块 铁块 原石 粘液块 //Target:门 漏斗矿车 面包 剪刀 粘性活塞 public void MakeItem_3(Player player, int item) { String name = player.getName(); if (isCraft(name, item)) { player.sendMessage(item_repeat_make); return; } if (item == Item.DOOR_BLOCK || item == Item.MINECART_WITH_HOPPER || item == Item.BREAD || item == Item.SHEARS || item == Item.STICKY_PISTON) { room.addPoint(player, 1); project.get(name).add(item); } } @EventHandler(priority = EventPriority.MONITOR) public void onPickup(EntityInventoryChangeEvent event) { if (room.gameType.equals("MakeItem")) { Entity player = event.getEntity(); if (player instanceof Player) { if (room.gamePlayer.contains((Player) player)) { if (this.type == 1) { this.MakeItem_1((Player) player, event.getNewItem().getId()); } else if (this.type == 2) { this.MakeItem_2((Player) player, event.getNewItem().getId()); } else if (this.type == 3) { this.MakeItem_3((Player) player, event.getNewItem().getId()); } if (this.room.rank.get(((Player) player).getName()) == 5) { gameFinish((Player) player); } } } } } @EventHandler(priority = EventPriority.MONITOR) public void onBreak(BlockBreakEvent event) { if (room.gameType.equals("MakeItem")) { Player player = event.getPlayer(); if (room.gamePlayer.contains(player)) { Block block = event.getBlock(); event.setDrops(null); player.getInventory().addItem(Item.get(block.getId(), block.getDamage())); event.setCancelled(true); } } } @Override public void madeArena() { this.type = new Random().nextInt(3)+1; } }
0
31
0
35717_4
package com.cbq.yatori.core.action.canghui.entity.exam; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @description: TODO 用于装选项的 * @author 长白崎 * @date 2023/11/27 23:26 * @version 1.0 */ @Data @AllArgsConstructor @NoArgsConstructor public class ExamItem { private String key; //选项的名称 private String value; //选项对应的值 private Integer score; //不知道啥玩意 private Boolean isCorrect; //是否是真确答案,如果是true则代表这个选项是答案 }
Changbaiqi/yatori
yatori-core/src/main/java/com/cbq/yatori/core/action/canghui/entity/exam/ExamItem.java
169
//是否是真确答案,如果是true则代表这个选项是答案
line_comment
zh-cn
package com.cbq.yatori.core.action.canghui.entity.exam; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @description: TODO 用于装选项的 * @author 长白崎 * @date 2023/11/27 23:26 * @version 1.0 */ @Data @AllArgsConstructor @NoArgsConstructor public class ExamItem { private String key; //选项的名称 private String value; //选项对应的值 private Integer score; //不知道啥玩意 private Boolean isCorrect; //是否 <SUF> }
0
27
0
56054_2
package com.qianxu.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.nio.charset.Charset; import java.util.List; //@Configuration public class CustomMVCConfiguration extends WebMvcConfigurationSupport { @Bean public HttpMessageConverter<String> responseBodyConverter() { return new StringHttpMessageConverter(Charset.forName("UTF-8")); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(responseBodyConverter()); // 这里必须加上加载默认转换器,不然bug玩死人,并且该bug目前在网络上似乎没有解决方案 // 百度,谷歌,各大论坛等。你可以试试去掉。 addDefaultHttpMessageConverters(converters); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } }
ChangfengHU/qianxu-app-spring
src/main/java/com/qianxu/config/CustomMVCConfiguration.java
301
// 百度,谷歌,各大论坛等。你可以试试去掉。
line_comment
zh-cn
package com.qianxu.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; import java.nio.charset.Charset; import java.util.List; //@Configuration public class CustomMVCConfiguration extends WebMvcConfigurationSupport { @Bean public HttpMessageConverter<String> responseBodyConverter() { return new StringHttpMessageConverter(Charset.forName("UTF-8")); } @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(responseBodyConverter()); // 这里必须加上加载默认转换器,不然bug玩死人,并且该bug目前在网络上似乎没有解决方案 // 百度 <SUF> addDefaultHttpMessageConverters(converters); } @Override public void configureContentNegotiation(ContentNegotiationConfigurer configurer) { configurer.favorPathExtension(false); } }
0
23
0
26197_1
package com.chanven.lib.cptr.loadmore; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ListView; import com.chanven.lib.cptr.loadmore.ILoadMoreViewFactory.FootViewAdder; import com.chanven.lib.cptr.loadmore.ILoadMoreViewFactory.ILoadMoreView; public class ListViewHandler implements LoadMoreHandler { private ListView mListView; private View mFooter; @Override public boolean handleSetAdapter(View contentView, ILoadMoreView loadMoreView, OnClickListener onClickLoadMoreListener) { final ListView listView = (ListView) contentView; mListView = listView; boolean hasInit = false; if (loadMoreView != null) { final Context context = listView.getContext().getApplicationContext(); loadMoreView.init(new FootViewAdder() { @Override public View addFootView(int layoutId) { View view = LayoutInflater.from(context).inflate(layoutId, listView, false); mFooter = view; return addFootView(view); } @Override public View addFootView(View view) { listView.addFooterView(view); return view; } }, onClickLoadMoreListener); hasInit = true; } return hasInit; } @Override public void setOnScrollBottomListener(View contentView, OnScrollBottomListener onScrollBottomListener) { ListView listView = (ListView) contentView; listView.setOnScrollListener(new ListViewOnScrollListener(onScrollBottomListener)); listView.setOnItemSelectedListener(new ListViewOnItemSelectedListener(onScrollBottomListener)); } @Override public void removeFooter() { if (mListView.getFooterViewsCount() > 0 && null != mFooter) { mListView.removeFooterView(mFooter); } } @Override public void addFooter() { if (mListView.getFooterViewsCount() <= 0 && null != mFooter) { mListView.addFooterView(mFooter); } } /** * 针对于电视 选择到了底部项的时候自动加载更多数据 */ private class ListViewOnItemSelectedListener implements OnItemSelectedListener { private OnScrollBottomListener onScrollBottomListener; public ListViewOnItemSelectedListener(OnScrollBottomListener onScrollBottomListener) { super(); this.onScrollBottomListener = onScrollBottomListener; } @Override public void onItemSelected(AdapterView<?> listView, View view, int position, long id) { if (listView.getLastVisiblePosition() + 1 == listView.getCount()) {// 如果滚动到最后一行 if (onScrollBottomListener != null) { onScrollBottomListener.onScorllBootom(); } } } @Override public void onNothingSelected(AdapterView<?> parent) { } } ; /** * 滚动到底部自动加载更多数据 */ private static class ListViewOnScrollListener implements OnScrollListener { private OnScrollBottomListener onScrollBottomListener; public ListViewOnScrollListener(OnScrollBottomListener onScrollBottomListener) { super(); this.onScrollBottomListener = onScrollBottomListener; } @Override public void onScrollStateChanged(AbsListView listView, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && listView.getLastVisiblePosition() + 1 == listView.getCount()) {// 如果滚动到最后一行 if (onScrollBottomListener != null) { onScrollBottomListener.onScorllBootom(); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } } ; }
Chanven/CommonPullToRefresh
cptr/src/com/chanven/lib/cptr/loadmore/ListViewHandler.java
918
// 如果滚动到最后一行
line_comment
zh-cn
package com.chanven.lib.cptr.loadmore; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ListView; import com.chanven.lib.cptr.loadmore.ILoadMoreViewFactory.FootViewAdder; import com.chanven.lib.cptr.loadmore.ILoadMoreViewFactory.ILoadMoreView; public class ListViewHandler implements LoadMoreHandler { private ListView mListView; private View mFooter; @Override public boolean handleSetAdapter(View contentView, ILoadMoreView loadMoreView, OnClickListener onClickLoadMoreListener) { final ListView listView = (ListView) contentView; mListView = listView; boolean hasInit = false; if (loadMoreView != null) { final Context context = listView.getContext().getApplicationContext(); loadMoreView.init(new FootViewAdder() { @Override public View addFootView(int layoutId) { View view = LayoutInflater.from(context).inflate(layoutId, listView, false); mFooter = view; return addFootView(view); } @Override public View addFootView(View view) { listView.addFooterView(view); return view; } }, onClickLoadMoreListener); hasInit = true; } return hasInit; } @Override public void setOnScrollBottomListener(View contentView, OnScrollBottomListener onScrollBottomListener) { ListView listView = (ListView) contentView; listView.setOnScrollListener(new ListViewOnScrollListener(onScrollBottomListener)); listView.setOnItemSelectedListener(new ListViewOnItemSelectedListener(onScrollBottomListener)); } @Override public void removeFooter() { if (mListView.getFooterViewsCount() > 0 && null != mFooter) { mListView.removeFooterView(mFooter); } } @Override public void addFooter() { if (mListView.getFooterViewsCount() <= 0 && null != mFooter) { mListView.addFooterView(mFooter); } } /** * 针对于电视 选择到了底部项的时候自动加载更多数据 */ private class ListViewOnItemSelectedListener implements OnItemSelectedListener { private OnScrollBottomListener onScrollBottomListener; public ListViewOnItemSelectedListener(OnScrollBottomListener onScrollBottomListener) { super(); this.onScrollBottomListener = onScrollBottomListener; } @Override public void onItemSelected(AdapterView<?> listView, View view, int position, long id) { if (listView.getLastVisiblePosition() + 1 == listView.getCount()) {// 如果 <SUF> if (onScrollBottomListener != null) { onScrollBottomListener.onScorllBootom(); } } } @Override public void onNothingSelected(AdapterView<?> parent) { } } ; /** * 滚动到底部自动加载更多数据 */ private static class ListViewOnScrollListener implements OnScrollListener { private OnScrollBottomListener onScrollBottomListener; public ListViewOnScrollListener(OnScrollBottomListener onScrollBottomListener) { super(); this.onScrollBottomListener = onScrollBottomListener; } @Override public void onScrollStateChanged(AbsListView listView, int scrollState) { if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && listView.getLastVisiblePosition() + 1 == listView.getCount()) {// 如果滚动到最后一行 if (onScrollBottomListener != null) { onScrollBottomListener.onScorllBootom(); } } } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { } } ; }
0
12
0
37339_0
package com.cpbpc.telegram; import com.cpbpc.comms.AppProperties; import com.cpbpc.comms.DBUtil; import com.cpbpc.comms.NumberConverter; import com.cpbpc.comms.PunctuationTool; import com.cpbpc.comms.SecretUtil; import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.time.YearMonth; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GenTelegramExcel { private static final Properties appProperties = AppProperties.getConfig(); private static final String theme = "The Book of Leviticus"; private static final String writer = "Rev Dr Quek Suan Yew"; private static final String year = "2024"; private static final String month = "06"; private static final String language = "english"; private static final boolean isTest = false; /* ✝️ 你们在基督里是完整的 💭 不要害怕 📖 彼得前书三章13-16节,诗篇25篇1-9节 ✍🏻 阮贤牧师 🗣 https://bit.ly/3svxA8d 📝 https://bit.ly/47R6ad6 */ private static final String pattern = "(https://bit\\.ly/[0-9A-za-z]+)"; private static final String[] hyphens_unicode = new String[]{"\\u002d", "\\u2010", "\\u2011", "\\u2012", "\\u2013", "\\u2015", "\\u2212"}; private static final Map<String, String> abbre = new HashMap(); private static final String query = "select \n" + " cjv.summary, cjv.description, cj.catid, cjr.rp_id, \n" + " DATE_FORMAT(cjr.startrepeat, \"%Y_%m\") as `month`, \n" + " DATE_FORMAT(cjr.startrepeat, \"%Y%m%d\") as `date` \n" + " from cpbpc_jevents_vevdetail cjv\n" + " left join cpbpc_jevents_vevent cj on cj.ev_id = cjv.evdet_id\n" + " left join cpbpc_categories cc on cc.id = cj.catid\n" + " left join cpbpc_jevents_repetition cjr on cjr.eventdetail_id = cjv.evdet_id\n" + " where cc.id =? \n" + // " and DATE_FORMAT(cjr.startrepeat, \"%Y-%m-%d\")=? \n" + " and DATE_FORMAT(cjr.startrepeat, \"%Y-%m\")=? \n" + " order by cjr.startrepeat asc \n"; public static void main(String args[]) throws IOException, SQLException { AppProperties.loadConfig(System.getProperty("app.properties", "/Users/liuchaochih/Documents/GitHub/churchrpg/src/main/resources/app-"+language+".properties")); initAbbre(); LocalDate currentDate = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 01); LocalDate lastDayOfMonth = YearMonth.from(currentDate).atEndOfMonth(); List<Map<String, String>> rows = fetchData(); // Create a new Excel workbook Workbook workbook = new XSSFWorkbook(); CreationHelper creationHelper = workbook.getCreationHelper(); // Create a new Excel sheet within the workbook Sheet sheet = workbook.createSheet("Sheet 1"); // Create rows and cells and set values for (Map<String, String> dataRow : rows) { int rowNumber = rows.indexOf(dataRow); Row row = sheet.createRow(rowNumber); Cell cell = row.createCell(0); RichTextString richText = creationHelper.createRichTextString( genEmojiCross() + " " + theme + "\n" + "\uD83D\uDCAD" + " " + capitalize(StringUtils.lowerCase(dataRow.get("summary"))) + "\n" + "\uD83D\uDCD6" + " " + grepThemeVerses(dataRow) + "\n" + genEmojiWritingHand() + " " + writer + "\n" + "\n" + "\uD83D\uDDE3" + " " + shortenURL(genAudioLink(dataRow), isTest) + "\n" + "\n" + "\uD83D\uDCDD" + " " + shortenURL(genArticleLink(dataRow), isTest) ); cell.setCellValue(richText); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setWrapText(true); cell.setCellStyle(cellStyle); } System.out.println( "text url:" ); System.out.println(StringUtils.join(textUrls, System.lineSeparator())); System.out.println( "audio url:" ); System.out.println(StringUtils.join(audioURLs, System.lineSeparator())); // // Save the workbook to a file or stream try (FileOutputStream fileOut = new FileOutputStream("example.xlsx")) { workbook.write(fileOut); } catch (IOException e) { e.printStackTrace(); } } private static String formatSummary(String input) { String result = input; if( StringUtils.contains(result, ":") ){ result = result.replace(":", ": "); } return result; } private static String capitalize(String summary) { String result = ""; String[] strs = StringUtils.split(summary, " "); for (String str : strs) { result += StringUtils.capitalize(str); } return result; } private static String shortenURL(String link, boolean isTest) throws UnsupportedEncodingException { if(isTest){ return link; } String accessKey = SecretUtil.getBitlyKey(); String requestBody = "{\"long_url\":\"" + link + "\", \"domain\":\"bit.ly\", \"group_guid\":\"Bn7fexZnrBp\"}"; StringEntity entity = new StringEntity(requestBody); HttpClient httpClient = HttpClientBuilder.create().build(); // Create an HttpGet request with the API endpoint URL HttpPost request = new HttpPost("https://api-ssl.bitly.com/v4/shorten"); request.setEntity(entity); // Set the Authorization header with the access key request.setHeader("Authorization", "Bearer " + accessKey); request.setHeader("Content-Type", "application/json"); try { // Execute the request and get the response HttpResponse response = httpClient.execute(request); String responseBody = EntityUtils.toString(response.getEntity()); return extractLink(responseBody); // Process the response as needed // Here, you can extract the shortened URL from the response and use it } catch (Exception e) { e.printStackTrace(); } return ""; } private static String extractLink(String responseBody) { Pattern p = Pattern.compile(pattern); String result = ""; Matcher matcher = p.matcher(responseBody); if (matcher.find()) { result = matcher.group(0); } return result; } private static List<String> audioURLs = new ArrayList<>(); private static String genAudioLink(Map<String, String> dataRow) { String url = ""; if (AppProperties.isChinese()) { url = genChAudioLink(dataRow); audioURLs.add(url); return url; } url = genEngAudioLink(dataRow); audioURLs.add(url); return url; } private static String genChAudioLink(Map<String, String> dataRow) { return "https://cpbpc-rpg-audio.s3.ap-southeast-1.amazonaws.com/rpg-chinese/" + dataRow.get("month") + "/crpg" + dataRow.get("date") + ".mp3"; } private static String genEngAudioLink(Map<String, String> dataRow) { return "https://cpbpc-rpg-audio.s3.ap-southeast-1.amazonaws.com/rpg/" + dataRow.get("month") + "/arpg" + dataRow.get("date") + ".mp3"; } private static List<String> textUrls = new ArrayList<>(); private static String genArticleLink(Map<String, String> dataRow) { String url = ""; if (AppProperties.isChinese()) { url = genChArticleLink(dataRow); textUrls.add(url); return url; } url = genEngArticleLink(dataRow); textUrls.add(url); return url; } //https://calvarypandan.sg/resources/rpg/calendar/eventdetail/69825/86/israel-worshipped-in-thanksgiving private static String genEngArticleLink(Map<String, String> dataRow) { return "https://calvarypandan.sg/resources/rpg/calendar/eventdetail/" + dataRow.get("rp_id") + "/" + dataRow.get("catid") + "/" + RegExUtils.replaceAll(StringUtils.lowerCase(dataRow.get("summary")), " ", "-"); } //https://mandarin.calvarypandan.sg/%E8%B5%84%E6%BA%90/%E8%AF%BB,%E7%A5%B7,%E9%95%BF-%E6%97%A5%E5%8E%86/eventdetail/67101 private static String genChArticleLink(Map<String, String> dataRow) { // return "https://mandarin.calvarypandan.sg/"+URLDecoder.decode("%E8%B5%84%E6%BA%90")+"/"+ URLDecoder.decode("%E8%AF%BB,%E7%A5%B7,%E9%95%BF-%E6%97%A5%E5%8E%86") +"/eventdetail/"+dataRow.get("rp_id"); return "https://mandarin.calvarypandan.sg/%E8%B5%84%E6%BA%90/%E8%AF%BB,%E7%A5%B7,%E9%95%BF-%E6%97%A5%E5%8E%86/eventdetail/" + dataRow.get("rp_id"); } private static String genEmojiCross() { char char1 = '\u271D'; char char2 = '\uFE0F'; char[] emojiModifier = {char1, char2}; return new String(emojiModifier); } private static String genEmojiWritingHand() { char writingHand = '\u270D'; char highSurrogate = '\uD83C'; // High surrogate pair char lowSurrogate = '\uDFFB'; // Low surrogate pair char[] emojiModifier = {writingHand, highSurrogate, lowSurrogate}; return new String(emojiModifier); } private static String grepThemeVerses(Map<String, String> dataRow) { List<String> result = new ArrayList<>(); String content = dataRow.get("description"); String summary = dataRow.get("summary"); int anchorPoint = content.indexOf(summary); String p = generateVersePattern(); if (AppProperties.isChinese()) { p = generateTopicVersePattern(); } Pattern versePattern = Pattern.compile(p); Matcher matcher = versePattern.matcher(content); int position = 0; while (matcher.find(position)) { String bookNChapter = matcher.group(0).trim(); position = matcher.start() + bookNChapter.length(); if (position >= anchorPoint) { break; } String completeVerse = appendNextCharTillCompleteVerse(content, bookNChapter, 0); result.add(completeVerse); } return StringUtils.join(result, "; "); } private static String generateTopicVersePattern() { //雅各书一章1节 使徒行传十二章1-2节 哥林多后书6章14-7章1节 //诗篇一百二十七至一百二十八篇 StringBuilder builder = new StringBuilder("(("); Set<String> keySet = abbre.keySet(); for (String key : keySet) { builder.append(key.toString()).append("|") .append(key.toString()).append("&nbsp;|") .append(key.replace(" ", "&nbsp;")).append("|") ; } if (builder.toString().endsWith("|")) { builder.delete(builder.length() - 1, builder.length()); } builder.append(")\\s{0,}[0-9一二三四五六七八九十百千零至到]{1,}\\s{0,}[章|篇])"); System.out.println(builder.toString()); return builder.toString(); } private static String appendNextCharTillCompleteVerse(String content, String ref, int startFrom) { if (content == null || content.trim().length() <= 0 || ref == null || ref.trim().length() <= 0) { return ""; } content = PunctuationTool.changeFullCharacter(content); int position = content.indexOf(ref, startFrom) + ref.length(); StringBuilder builder = new StringBuilder(ref); List<String> verseParts = new ArrayList<>(); List<String> punctuations = new ArrayList<>(); punctuations.addAll(List.of(":", ",", " ", ";", "节", "節", "章", "篇", "十")); for (String hyphen_unicode : hyphens_unicode) { punctuations.add(StringEscapeUtils.unescapeJava(hyphen_unicode)); } verseParts.addAll(punctuations); for (int i = 0; i < 10; i++) { verseParts.add(String.valueOf(i)); verseParts.add(NumberConverter.toChineseNumber(i)); } System.out.println("verseParts : " + verseParts.toString()); for (int i = position; i < content.length(); i++) { String nextChar = content.substring(i, i + 1); if (!verseParts.contains(nextChar)) { break; } builder.append(nextChar); } String result = builder.toString(); // if( punctuations.contains(result.substring(result.length()-1, result.length())) ){ // result = result.substring(0, result.length()-1); // } return result; } private static String generateVersePattern() { StringBuilder builder = new StringBuilder("(("); Set<String> keySet = abbre.keySet(); for (String key : keySet) { builder.append(key.toString()).append("|") .append(key.toString()).append("&nbsp;|") .append(key.replace(" ", "&nbsp;")).append("|") ; } if (builder.toString().endsWith("|")) { builder.delete(builder.length() - 1, builder.length()); } builder.append(")[.]{0,1}\\s{0,}[0-9]{1,3})"); return builder.toString(); } private static void initAbbre() throws SQLException { Connection conn = DBUtil.createConnection(appProperties); PreparedStatement state = conn.prepareStatement("select * from cpbpc_abbreviation order by seq_no asc, length(short_form) desc"); ResultSet rs = state.executeQuery(); while (rs.next()) { String group = rs.getString("group"); String shortForm = rs.getString("short_form"); String completeForm = rs.getString("complete_form"); if ("bible".toLowerCase().equals(group.toLowerCase())) { abbre.put(shortForm, completeForm); } } conn.close(); } private static List<Map<String, String>> fetchData() throws SQLException { List<Map<String, String>> list = new ArrayList<>(); String category = URLDecoder.decode(appProperties.getProperty("content_category")); Connection conn = DBUtil.createConnection(appProperties); PreparedStatement stat = conn.prepareStatement(query); stat.setString(1, category); stat.setString(2, year + "-" + month); // stat.setString(2, "2024-02-10"); ResultSet rs = stat.executeQuery(); while (rs.next()) { Map row = new HashMap(); list.add(row); row.put("summary", rs.getString("summary")); row.put("description", rs.getString("description")); row.put("catid", rs.getString("catid")); row.put("rp_id", rs.getString("rp_id")); row.put("month", rs.getString("month")); row.put("date", rs.getString("date")); } conn.close(); return list; } /* select DATE_FORMAT(cjr.startrepeat , "%Y-%m-%d") as startrepeat, cc.alias, cjv.* from cpbpc_jevents_vevdetail cjv left join cpbpc_jevents_vevent cj on cj.ev_id = cjv.evdet_id left join cpbpc_categories cc on cc.id = cj.catid left join cpbpc_jevents_repetition cjr on cjr.eventdetail_id = cjv.evdet_id where cc.title in ( '读祷长' ) and DATE_FORMAT(cjr.startrepeat, "%Y-%m-%d")=? */ /* select DATE_FORMAT(cjr.startrepeat , "%Y-%m-%d") as startrepeat, cc.alias, cjv.* from cpbpc_jevents_vevdetail cjv left join cpbpc_jevents_vevent cj on cj.ev_id = cjv.evdet_id left join cpbpc_categories cc on cc.id = cj.catid left join cpbpc_jevents_repetition cjr on cjr.eventdetail_id = cjv.evdet_id where cc.title in ( 'RPG Adult' ) and DATE_FORMAT(cjr.startrepeat, "%Y-%m-%d")=? */ }
ChaoChihLiu/churchrpg
src/main/java/com/cpbpc/telegram/GenTelegramExcel.java
4,710
/* ✝️ 你们在基督里是完整的 💭 不要害怕 📖 彼得前书三章13-16节,诗篇25篇1-9节 ✍🏻 阮贤牧师 🗣 https://bit.ly/3svxA8d 📝 https://bit.ly/47R6ad6 */
block_comment
zh-cn
package com.cpbpc.telegram; import com.cpbpc.comms.AppProperties; import com.cpbpc.comms.DBUtil; import com.cpbpc.comms.NumberConverter; import com.cpbpc.comms.PunctuationTool; import com.cpbpc.comms.SecretUtil; import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.LocalDate; import java.time.YearMonth; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; public class GenTelegramExcel { private static final Properties appProperties = AppProperties.getConfig(); private static final String theme = "The Book of Leviticus"; private static final String writer = "Rev Dr Quek Suan Yew"; private static final String year = "2024"; private static final String month = "06"; private static final String language = "english"; private static final boolean isTest = false; /* ✝️ <SUF>*/ private static final String pattern = "(https://bit\\.ly/[0-9A-za-z]+)"; private static final String[] hyphens_unicode = new String[]{"\\u002d", "\\u2010", "\\u2011", "\\u2012", "\\u2013", "\\u2015", "\\u2212"}; private static final Map<String, String> abbre = new HashMap(); private static final String query = "select \n" + " cjv.summary, cjv.description, cj.catid, cjr.rp_id, \n" + " DATE_FORMAT(cjr.startrepeat, \"%Y_%m\") as `month`, \n" + " DATE_FORMAT(cjr.startrepeat, \"%Y%m%d\") as `date` \n" + " from cpbpc_jevents_vevdetail cjv\n" + " left join cpbpc_jevents_vevent cj on cj.ev_id = cjv.evdet_id\n" + " left join cpbpc_categories cc on cc.id = cj.catid\n" + " left join cpbpc_jevents_repetition cjr on cjr.eventdetail_id = cjv.evdet_id\n" + " where cc.id =? \n" + // " and DATE_FORMAT(cjr.startrepeat, \"%Y-%m-%d\")=? \n" + " and DATE_FORMAT(cjr.startrepeat, \"%Y-%m\")=? \n" + " order by cjr.startrepeat asc \n"; public static void main(String args[]) throws IOException, SQLException { AppProperties.loadConfig(System.getProperty("app.properties", "/Users/liuchaochih/Documents/GitHub/churchrpg/src/main/resources/app-"+language+".properties")); initAbbre(); LocalDate currentDate = LocalDate.of(Integer.parseInt(year), Integer.parseInt(month), 01); LocalDate lastDayOfMonth = YearMonth.from(currentDate).atEndOfMonth(); List<Map<String, String>> rows = fetchData(); // Create a new Excel workbook Workbook workbook = new XSSFWorkbook(); CreationHelper creationHelper = workbook.getCreationHelper(); // Create a new Excel sheet within the workbook Sheet sheet = workbook.createSheet("Sheet 1"); // Create rows and cells and set values for (Map<String, String> dataRow : rows) { int rowNumber = rows.indexOf(dataRow); Row row = sheet.createRow(rowNumber); Cell cell = row.createCell(0); RichTextString richText = creationHelper.createRichTextString( genEmojiCross() + " " + theme + "\n" + "\uD83D\uDCAD" + " " + capitalize(StringUtils.lowerCase(dataRow.get("summary"))) + "\n" + "\uD83D\uDCD6" + " " + grepThemeVerses(dataRow) + "\n" + genEmojiWritingHand() + " " + writer + "\n" + "\n" + "\uD83D\uDDE3" + " " + shortenURL(genAudioLink(dataRow), isTest) + "\n" + "\n" + "\uD83D\uDCDD" + " " + shortenURL(genArticleLink(dataRow), isTest) ); cell.setCellValue(richText); CellStyle cellStyle = workbook.createCellStyle(); cellStyle.setWrapText(true); cell.setCellStyle(cellStyle); } System.out.println( "text url:" ); System.out.println(StringUtils.join(textUrls, System.lineSeparator())); System.out.println( "audio url:" ); System.out.println(StringUtils.join(audioURLs, System.lineSeparator())); // // Save the workbook to a file or stream try (FileOutputStream fileOut = new FileOutputStream("example.xlsx")) { workbook.write(fileOut); } catch (IOException e) { e.printStackTrace(); } } private static String formatSummary(String input) { String result = input; if( StringUtils.contains(result, ":") ){ result = result.replace(":", ": "); } return result; } private static String capitalize(String summary) { String result = ""; String[] strs = StringUtils.split(summary, " "); for (String str : strs) { result += StringUtils.capitalize(str); } return result; } private static String shortenURL(String link, boolean isTest) throws UnsupportedEncodingException { if(isTest){ return link; } String accessKey = SecretUtil.getBitlyKey(); String requestBody = "{\"long_url\":\"" + link + "\", \"domain\":\"bit.ly\", \"group_guid\":\"Bn7fexZnrBp\"}"; StringEntity entity = new StringEntity(requestBody); HttpClient httpClient = HttpClientBuilder.create().build(); // Create an HttpGet request with the API endpoint URL HttpPost request = new HttpPost("https://api-ssl.bitly.com/v4/shorten"); request.setEntity(entity); // Set the Authorization header with the access key request.setHeader("Authorization", "Bearer " + accessKey); request.setHeader("Content-Type", "application/json"); try { // Execute the request and get the response HttpResponse response = httpClient.execute(request); String responseBody = EntityUtils.toString(response.getEntity()); return extractLink(responseBody); // Process the response as needed // Here, you can extract the shortened URL from the response and use it } catch (Exception e) { e.printStackTrace(); } return ""; } private static String extractLink(String responseBody) { Pattern p = Pattern.compile(pattern); String result = ""; Matcher matcher = p.matcher(responseBody); if (matcher.find()) { result = matcher.group(0); } return result; } private static List<String> audioURLs = new ArrayList<>(); private static String genAudioLink(Map<String, String> dataRow) { String url = ""; if (AppProperties.isChinese()) { url = genChAudioLink(dataRow); audioURLs.add(url); return url; } url = genEngAudioLink(dataRow); audioURLs.add(url); return url; } private static String genChAudioLink(Map<String, String> dataRow) { return "https://cpbpc-rpg-audio.s3.ap-southeast-1.amazonaws.com/rpg-chinese/" + dataRow.get("month") + "/crpg" + dataRow.get("date") + ".mp3"; } private static String genEngAudioLink(Map<String, String> dataRow) { return "https://cpbpc-rpg-audio.s3.ap-southeast-1.amazonaws.com/rpg/" + dataRow.get("month") + "/arpg" + dataRow.get("date") + ".mp3"; } private static List<String> textUrls = new ArrayList<>(); private static String genArticleLink(Map<String, String> dataRow) { String url = ""; if (AppProperties.isChinese()) { url = genChArticleLink(dataRow); textUrls.add(url); return url; } url = genEngArticleLink(dataRow); textUrls.add(url); return url; } //https://calvarypandan.sg/resources/rpg/calendar/eventdetail/69825/86/israel-worshipped-in-thanksgiving private static String genEngArticleLink(Map<String, String> dataRow) { return "https://calvarypandan.sg/resources/rpg/calendar/eventdetail/" + dataRow.get("rp_id") + "/" + dataRow.get("catid") + "/" + RegExUtils.replaceAll(StringUtils.lowerCase(dataRow.get("summary")), " ", "-"); } //https://mandarin.calvarypandan.sg/%E8%B5%84%E6%BA%90/%E8%AF%BB,%E7%A5%B7,%E9%95%BF-%E6%97%A5%E5%8E%86/eventdetail/67101 private static String genChArticleLink(Map<String, String> dataRow) { // return "https://mandarin.calvarypandan.sg/"+URLDecoder.decode("%E8%B5%84%E6%BA%90")+"/"+ URLDecoder.decode("%E8%AF%BB,%E7%A5%B7,%E9%95%BF-%E6%97%A5%E5%8E%86") +"/eventdetail/"+dataRow.get("rp_id"); return "https://mandarin.calvarypandan.sg/%E8%B5%84%E6%BA%90/%E8%AF%BB,%E7%A5%B7,%E9%95%BF-%E6%97%A5%E5%8E%86/eventdetail/" + dataRow.get("rp_id"); } private static String genEmojiCross() { char char1 = '\u271D'; char char2 = '\uFE0F'; char[] emojiModifier = {char1, char2}; return new String(emojiModifier); } private static String genEmojiWritingHand() { char writingHand = '\u270D'; char highSurrogate = '\uD83C'; // High surrogate pair char lowSurrogate = '\uDFFB'; // Low surrogate pair char[] emojiModifier = {writingHand, highSurrogate, lowSurrogate}; return new String(emojiModifier); } private static String grepThemeVerses(Map<String, String> dataRow) { List<String> result = new ArrayList<>(); String content = dataRow.get("description"); String summary = dataRow.get("summary"); int anchorPoint = content.indexOf(summary); String p = generateVersePattern(); if (AppProperties.isChinese()) { p = generateTopicVersePattern(); } Pattern versePattern = Pattern.compile(p); Matcher matcher = versePattern.matcher(content); int position = 0; while (matcher.find(position)) { String bookNChapter = matcher.group(0).trim(); position = matcher.start() + bookNChapter.length(); if (position >= anchorPoint) { break; } String completeVerse = appendNextCharTillCompleteVerse(content, bookNChapter, 0); result.add(completeVerse); } return StringUtils.join(result, "; "); } private static String generateTopicVersePattern() { //雅各书一章1节 使徒行传十二章1-2节 哥林多后书6章14-7章1节 //诗篇一百二十七至一百二十八篇 StringBuilder builder = new StringBuilder("(("); Set<String> keySet = abbre.keySet(); for (String key : keySet) { builder.append(key.toString()).append("|") .append(key.toString()).append("&nbsp;|") .append(key.replace(" ", "&nbsp;")).append("|") ; } if (builder.toString().endsWith("|")) { builder.delete(builder.length() - 1, builder.length()); } builder.append(")\\s{0,}[0-9一二三四五六七八九十百千零至到]{1,}\\s{0,}[章|篇])"); System.out.println(builder.toString()); return builder.toString(); } private static String appendNextCharTillCompleteVerse(String content, String ref, int startFrom) { if (content == null || content.trim().length() <= 0 || ref == null || ref.trim().length() <= 0) { return ""; } content = PunctuationTool.changeFullCharacter(content); int position = content.indexOf(ref, startFrom) + ref.length(); StringBuilder builder = new StringBuilder(ref); List<String> verseParts = new ArrayList<>(); List<String> punctuations = new ArrayList<>(); punctuations.addAll(List.of(":", ",", " ", ";", "节", "節", "章", "篇", "十")); for (String hyphen_unicode : hyphens_unicode) { punctuations.add(StringEscapeUtils.unescapeJava(hyphen_unicode)); } verseParts.addAll(punctuations); for (int i = 0; i < 10; i++) { verseParts.add(String.valueOf(i)); verseParts.add(NumberConverter.toChineseNumber(i)); } System.out.println("verseParts : " + verseParts.toString()); for (int i = position; i < content.length(); i++) { String nextChar = content.substring(i, i + 1); if (!verseParts.contains(nextChar)) { break; } builder.append(nextChar); } String result = builder.toString(); // if( punctuations.contains(result.substring(result.length()-1, result.length())) ){ // result = result.substring(0, result.length()-1); // } return result; } private static String generateVersePattern() { StringBuilder builder = new StringBuilder("(("); Set<String> keySet = abbre.keySet(); for (String key : keySet) { builder.append(key.toString()).append("|") .append(key.toString()).append("&nbsp;|") .append(key.replace(" ", "&nbsp;")).append("|") ; } if (builder.toString().endsWith("|")) { builder.delete(builder.length() - 1, builder.length()); } builder.append(")[.]{0,1}\\s{0,}[0-9]{1,3})"); return builder.toString(); } private static void initAbbre() throws SQLException { Connection conn = DBUtil.createConnection(appProperties); PreparedStatement state = conn.prepareStatement("select * from cpbpc_abbreviation order by seq_no asc, length(short_form) desc"); ResultSet rs = state.executeQuery(); while (rs.next()) { String group = rs.getString("group"); String shortForm = rs.getString("short_form"); String completeForm = rs.getString("complete_form"); if ("bible".toLowerCase().equals(group.toLowerCase())) { abbre.put(shortForm, completeForm); } } conn.close(); } private static List<Map<String, String>> fetchData() throws SQLException { List<Map<String, String>> list = new ArrayList<>(); String category = URLDecoder.decode(appProperties.getProperty("content_category")); Connection conn = DBUtil.createConnection(appProperties); PreparedStatement stat = conn.prepareStatement(query); stat.setString(1, category); stat.setString(2, year + "-" + month); // stat.setString(2, "2024-02-10"); ResultSet rs = stat.executeQuery(); while (rs.next()) { Map row = new HashMap(); list.add(row); row.put("summary", rs.getString("summary")); row.put("description", rs.getString("description")); row.put("catid", rs.getString("catid")); row.put("rp_id", rs.getString("rp_id")); row.put("month", rs.getString("month")); row.put("date", rs.getString("date")); } conn.close(); return list; } /* select DATE_FORMAT(cjr.startrepeat , "%Y-%m-%d") as startrepeat, cc.alias, cjv.* from cpbpc_jevents_vevdetail cjv left join cpbpc_jevents_vevent cj on cj.ev_id = cjv.evdet_id left join cpbpc_categories cc on cc.id = cj.catid left join cpbpc_jevents_repetition cjr on cjr.eventdetail_id = cjv.evdet_id where cc.title in ( '读祷长' ) and DATE_FORMAT(cjr.startrepeat, "%Y-%m-%d")=? */ /* select DATE_FORMAT(cjr.startrepeat , "%Y-%m-%d") as startrepeat, cc.alias, cjv.* from cpbpc_jevents_vevdetail cjv left join cpbpc_jevents_vevent cj on cj.ev_id = cjv.evdet_id left join cpbpc_categories cc on cc.id = cj.catid left join cpbpc_jevents_repetition cjr on cjr.eventdetail_id = cjv.evdet_id where cc.title in ( 'RPG Adult' ) and DATE_FORMAT(cjr.startrepeat, "%Y-%m-%d")=? */ }
0
143
0
5380_3
package com.example.testQRCode; import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.MatrixToImageConfig; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; public class QRCode { public static void main(String[] args) throws IOException, WriterException { encode("没事,黑白就能体现出我的高冷风了", "E:/QRCode.png", "E:/load.png"); // encode("没事,黑白就能体现出我的高冷风了", "E:/QRCode.png"); String s = decode("E:/QRCode.png"); System.out.println(s); } private static void encode(String content, String path) throws WriterException, IOException { int x = 500; int y = 500; //0x为16位标识 FF 随后6位为色值 int onColor = 0xFF000000; int offColor = 0xFFFFFFA; String format = "png"; File out = new File(path); HashMap<EncodeHintType, Object> map = new HashMap<>(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//Decode 出错,可以适当调节排错率 map.put(EncodeHintType.MARGIN, 1); BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, x, y, map); MatrixToImageWriter.writeToPath(encode, format, out.toPath(), new MatrixToImageConfig(onColor, offColor)); } private static void encode(String content, String path, String logoPath) throws WriterException, IOException { int x = 1000; int y = 1000; //0x为16位标识 FF 随后6位为色值 int onColor = 0xFF000000; int offColor = 0xFFFFFFA; String format = "png"; File out = new File(path); HashMap<EncodeHintType, Object> map = new HashMap<>(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//Decode 出错,可以适当调节排错率 map.put(EncodeHintType.MARGIN, 1); BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, x, y, map); BufferedImage qrCode = MatrixToImageWriter.toBufferedImage(encode, new MatrixToImageConfig(onColor, offColor)); Graphics2D graphics = qrCode.createGraphics(); BufferedImage logo = ImageIO.read(new File(logoPath)); graphics.drawImage(logo, (qrCode.getWidth() - logo.getWidth()) / 2, (qrCode.getHeight() - logo.getHeight()) / 2, null); graphics.dispose(); logo.flush(); ImageIO.write(qrCode, format, out); } public static String decode(String path) throws IOException { File in = new File(path); BufferedImage qrCode = ImageIO.read(in); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(qrCode))); HashMap<DecodeHintType, Object> map = new HashMap<>(); map.put(DecodeHintType.CHARACTER_SET, "utf-8"); try { Result decode = new MultiFormatReader().decode(binaryBitmap, map); return decode.toString(); } catch (NotFoundException e) { return ""; } } }
ChaoSBYNN/Tools
Java/TestDemo/QRCode/QRCode.java
990
//0x为16位标识 FF 随后6位为色值
line_comment
zh-cn
package com.example.testQRCode; import com.google.zxing.*; import com.google.zxing.client.j2se.BufferedImageLuminanceSource; import com.google.zxing.client.j2se.MatrixToImageConfig; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.common.HybridBinarizer; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.HashMap; public class QRCode { public static void main(String[] args) throws IOException, WriterException { encode("没事,黑白就能体现出我的高冷风了", "E:/QRCode.png", "E:/load.png"); // encode("没事,黑白就能体现出我的高冷风了", "E:/QRCode.png"); String s = decode("E:/QRCode.png"); System.out.println(s); } private static void encode(String content, String path) throws WriterException, IOException { int x = 500; int y = 500; //0x为16位标识 FF 随后6位为色值 int onColor = 0xFF000000; int offColor = 0xFFFFFFA; String format = "png"; File out = new File(path); HashMap<EncodeHintType, Object> map = new HashMap<>(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//Decode 出错,可以适当调节排错率 map.put(EncodeHintType.MARGIN, 1); BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, x, y, map); MatrixToImageWriter.writeToPath(encode, format, out.toPath(), new MatrixToImageConfig(onColor, offColor)); } private static void encode(String content, String path, String logoPath) throws WriterException, IOException { int x = 1000; int y = 1000; //0x <SUF> int onColor = 0xFF000000; int offColor = 0xFFFFFFA; String format = "png"; File out = new File(path); HashMap<EncodeHintType, Object> map = new HashMap<>(); map.put(EncodeHintType.CHARACTER_SET, "utf-8"); map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//Decode 出错,可以适当调节排错率 map.put(EncodeHintType.MARGIN, 1); BitMatrix encode = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, x, y, map); BufferedImage qrCode = MatrixToImageWriter.toBufferedImage(encode, new MatrixToImageConfig(onColor, offColor)); Graphics2D graphics = qrCode.createGraphics(); BufferedImage logo = ImageIO.read(new File(logoPath)); graphics.drawImage(logo, (qrCode.getWidth() - logo.getWidth()) / 2, (qrCode.getHeight() - logo.getHeight()) / 2, null); graphics.dispose(); logo.flush(); ImageIO.write(qrCode, format, out); } public static String decode(String path) throws IOException { File in = new File(path); BufferedImage qrCode = ImageIO.read(in); BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(qrCode))); HashMap<DecodeHintType, Object> map = new HashMap<>(); map.put(DecodeHintType.CHARACTER_SET, "utf-8"); try { Result decode = new MultiFormatReader().decode(binaryBitmap, map); return decode.toString(); } catch (NotFoundException e) { return ""; } } }
1
21
1
61499_72
package com.chaos.chaoscompass; import android.animation.PropertyValuesHolder; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Camera; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RadialGradient; import android.graphics.Rect; import android.graphics.Shader; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * Created by yc.Zhao on 2017/12/27 0027. * 指南针View,new */ public class ChaosCompassView extends View{ private Canvas mCanvas; private Context mContext; //View矩形的宽度 private int width; //指南针圆心点坐标 private int mCenterX; private int mCenterY; //外圆半径 private int mOutSideRadius; //外接圆半径 private int mCircumRadius; //指南针文字大小空间高度 private int mTextHeight; //暗红色 外圈笔 private Paint mDarkRedPaint; //深灰 外圈笔 private Paint mDeepGrayPaint; //外三角笔 private Paint mOutSideCircumPaint; //浅灰 外圈笔 private Paint mLightGrayPaint; //指南针上面 文字笔 private Paint mTextPaint; //外接圆,三角形笔 private Paint mCircumPaint; //指南针上面文字的外接矩形,用来测文字大小让文字居中 private Rect mTextRect; //外圈小三角形的Path private Path mOutsideTriangle; //外接圆小三角形的Path private Path mCircumTriangle; //NESW 文字笔 和文字外接矩形 private Paint mNorthPaint; private Paint mOthersPaint; private Rect mPositionRect; //小刻度文字大小矩形和画笔 private Paint mSamllDegreePaint; //两位数的 private Rect mSencondRect; //三位数的 private Rect mThirdRect; //圆心数字矩形 private Rect mCenterTextRect; //中心文字笔 private Paint mCenterPaint; //内心圆是一个颜色辐射渐变的圆 private Shader mInnerShader; private Paint mInnerPaint; //定义个点击属性动画 private ValueAnimator mValueAnimator; // camera绕X轴旋转的角度 private float mCameraRotateX; // camera绕Y轴旋转的角度 private float mCameraRotateY; //camera最大旋转角度 private float mMaxCameraRotate = 10; // camera绕X轴旋转的角度 private float mCameraTranslateX; // camera绕Y轴旋转的角度 private float mCameraTranslateY; //camera最大旋转角度 private float mMaxCameraTranslate; //camera矩阵 private Matrix mCameraMatrix; //设置camera private Camera mCamera; private float val=0f; private float valCompare; //偏转角度红线笔 private Paint mAnglePaint; //方位文字 private String text="北"; public float getVal() { return val; } public void setVal(float val) { this.val = val; invalidate(); } public ChaosCompassView(Context context) { this(context,null); } public ChaosCompassView(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public ChaosCompassView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; mDarkRedPaint = new Paint(); mDarkRedPaint.setStyle(Paint.Style.STROKE); mDarkRedPaint.setAntiAlias(true); mDarkRedPaint.setColor(context.getResources().getColor(R.color.darkRed)); mDeepGrayPaint = new Paint(); mDeepGrayPaint.setStyle(Paint.Style.STROKE); mDeepGrayPaint.setAntiAlias(true); mDeepGrayPaint.setColor(context.getResources().getColor(R.color.deepGray)); mLightGrayPaint = new Paint(); mLightGrayPaint.setStyle(Paint.Style.FILL); mLightGrayPaint.setAntiAlias(true); mLightGrayPaint.setColor(context.getResources().getColor(R.color.lightGray)); mTextPaint = new Paint(); mTextPaint.setStyle(Paint.Style.STROKE); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(80); mTextPaint.setColor(context.getResources().getColor(R.color.white)); mCircumPaint = new Paint(); mCircumPaint.setStyle(Paint.Style.FILL); mCircumPaint.setAntiAlias(true); mCircumPaint.setColor(context.getResources().getColor(R.color.red)); mOutSideCircumPaint = new Paint(); mOutSideCircumPaint.setStyle(Paint.Style.FILL); mOutSideCircumPaint.setAntiAlias(true); mOutSideCircumPaint.setColor(context.getResources().getColor(R.color.lightGray)); mTextRect = new Rect(); mOutsideTriangle = new Path(); mCircumTriangle = new Path(); mNorthPaint = new Paint(); mNorthPaint.setStyle(Paint.Style.STROKE); mNorthPaint.setAntiAlias(true); mNorthPaint.setTextSize(40); mNorthPaint.setColor(context.getResources().getColor(R.color.red)); mOthersPaint = new Paint(); mOthersPaint.setStyle(Paint.Style.STROKE); mOthersPaint.setAntiAlias(true); mOthersPaint.setTextSize(40); mOthersPaint.setColor(context.getResources().getColor(R.color.white)); mPositionRect = new Rect(); mCenterTextRect = new Rect(); mCenterPaint = new Paint(); mCenterPaint.setStyle(Paint.Style.STROKE); mCenterPaint.setAntiAlias(true); mCenterPaint.setTextSize(120); mCenterPaint.setColor(context.getResources().getColor(R.color.white)); mSamllDegreePaint = new Paint(); mSamllDegreePaint.setStyle(Paint.Style.STROKE); mSamllDegreePaint.setAntiAlias(true); mSamllDegreePaint.setTextSize(30); mSamllDegreePaint.setColor(context.getResources().getColor(R.color.lightGray)); mSencondRect = new Rect(); mThirdRect = new Rect(); mInnerPaint = new Paint(); mInnerPaint.setStyle(Paint.Style.FILL); mInnerPaint.setAntiAlias(true); mAnglePaint = new Paint(); mAnglePaint.setStyle(Paint.Style.STROKE); mAnglePaint.setAntiAlias(true); mAnglePaint.setColor(context.getResources().getColor(R.color.red)); mCameraMatrix = new Matrix(); mCamera = new Camera(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mCanvas = canvas; //设置Camera矩阵 实现3D效果 set3DMetrix(); //画文字 drawText(); //画指南针外圈 drawCompassOutSide(); //画指南针外接圆 drawCompassCircum(); //画内部渐变颜色圆 drawInnerCricle(); //画指南针内部刻度 drawCompassDegreeScale(); //画圆心数字 drawCenterText(); } /** * 设置camera相关 */ private void set3DMetrix() { mCameraMatrix.reset(); mCamera.save(); mCamera.rotateX(mCameraRotateX); mCamera.rotateY(mCameraRotateY); mCamera.getMatrix(mCameraMatrix); mCamera.restore(); //camera默认旋转是View左上角为旋转中心 //所以动作之前要,设置矩阵位置 -mTextHeight-mOutSideRadius mCameraMatrix.preTranslate(-getWidth()/2,-getHeight()/2); //动作之后恢复位置 mCameraMatrix.postTranslate(getWidth()/2,getHeight()/2); mCanvas.concat(mCameraMatrix); } private void drawInnerCricle() { mInnerShader = new RadialGradient(width/2,mOutSideRadius+mTextHeight,mCircumRadius-40, Color.parseColor("#323232"), Color.parseColor("#000000"),Shader.TileMode.CLAMP); mInnerPaint.setShader(mInnerShader); mCanvas.drawCircle(width/2,mOutSideRadius+mTextHeight,mCircumRadius-40,mInnerPaint); } private void drawCenterText() { String centerText=String.valueOf((int) val+"°"); mCenterPaint.getTextBounds(centerText,0,centerText.length(),mCenterTextRect); int centerTextWidth = mCenterTextRect.width(); int centerTextHeight = mCenterTextRect.height(); mCanvas.drawText(centerText,width/2-centerTextWidth/2,mTextHeight+mOutSideRadius+centerTextHeight/5,mCenterPaint); } private void drawCompassDegreeScale() { mCanvas.save(); //获取N文字的宽度 mNorthPaint.getTextBounds("N",0,1,mPositionRect); int mPositionTextWidth = mPositionRect.width(); int mPositionTextHeight = mPositionRect.height(); //获取W文字宽度,因为W比较宽 所以要单独获取 mNorthPaint.getTextBounds("W",0,1,mPositionRect); int mWPositionTextWidth = mPositionRect.width(); int mWPositionTextHeight = mPositionRect.height(); //获取小刻度,两位数的宽度 mSamllDegreePaint.getTextBounds("30",0,1,mSencondRect); int mSencondTextWidth = mSencondRect.width(); int mSencondTextHeight = mSencondRect.height(); //获取小刻度,3位数的宽度 mSamllDegreePaint.getTextBounds("30",0,1,mThirdRect); int mThirdTextWidth = mThirdRect.width(); int mThirdTextHeight = mThirdRect.height(); mCanvas.rotate(-val,width/2,mOutSideRadius+mTextHeight); //画刻度线 for (int i = 0; i < 240; i++) { if (i==0||i==60||i==120||i==180){ mCanvas.drawLine(getWidth() / 2, mTextHeight+mOutSideRadius-mCircumRadius+10, getWidth() / 2, mTextHeight+mOutSideRadius-mCircumRadius+30, mDeepGrayPaint); }else{ mCanvas.drawLine(getWidth() / 2, mTextHeight+mOutSideRadius-mCircumRadius+10, getWidth() / 2, mTextHeight+mOutSideRadius-mCircumRadius+30, mLightGrayPaint); } if (i==0){ mCanvas.drawText("N", this.width /2-mPositionTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mPositionTextHeight,mNorthPaint); }else if (i==60){ mCanvas.drawText("E", this.width /2-mPositionTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mPositionTextHeight,mOthersPaint); }else if (i==120){ mCanvas.drawText("S", this.width /2-mPositionTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mPositionTextHeight,mOthersPaint); }else if (i==180){ mCanvas.drawText("W", this.width /2-mWPositionTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mWPositionTextHeight,mOthersPaint); }else if (i==20){ mCanvas.drawText("30", this.width /2-mSencondTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mSencondTextHeight,mSamllDegreePaint); }else if (i==40){ mCanvas.drawText("60", this.width /2-mSencondTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mSencondTextHeight,mSamllDegreePaint); }else if (i==80){ mCanvas.drawText("120", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==100){ mCanvas.drawText("150", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==140){ mCanvas.drawText("210", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==160){ mCanvas.drawText("240", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==200){ mCanvas.drawText("300", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==220){ mCanvas.drawText("330", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); } mCanvas.rotate(1.5f, mCenterX, mOutSideRadius+mTextHeight); } mCanvas.restore(); } /** * 指南针外接圆,和外部圆换道理差不多 */ private void drawCompassCircum() { mCanvas.save(); //外接圆小三角形的高度 int mTriangleHeight=(mOutSideRadius-mCircumRadius)/2; mCanvas.rotate(-val,width/2,mOutSideRadius+mTextHeight); mCircumTriangle.moveTo(width/2,mTriangleHeight+mTextHeight); //内接三角形的边长,简单数学运算 float mTriangleSide = (float) ((mTriangleHeight/(Math.sqrt(3)))*2); mCircumTriangle.lineTo(width/2-mTriangleSide/2,mTextHeight+mTriangleHeight*2); mCircumTriangle.lineTo(width/2+mTriangleSide/2,mTextHeight+mTriangleHeight*2); mCircumTriangle.close(); mCanvas.drawPath(mCircumTriangle,mCircumPaint); mCanvas.drawArc(width/2-mCircumRadius,mTextHeight+mOutSideRadius-mCircumRadius, width/2+mCircumRadius,mTextHeight+mOutSideRadius+mCircumRadius,-85,350,false,mDeepGrayPaint); mAnglePaint.setStrokeWidth(5f); if (val<=180){ valCompare = val; mCanvas.drawArc(width/2-mCircumRadius,mTextHeight+mOutSideRadius-mCircumRadius, width/2+mCircumRadius,mTextHeight+mOutSideRadius+mCircumRadius,-85,valCompare,false,mAnglePaint); }else{ valCompare = 360-val; mCanvas.drawArc(width/2-mCircumRadius,mTextHeight+mOutSideRadius-mCircumRadius, width/2+mCircumRadius,mTextHeight+mOutSideRadius+mCircumRadius,-95,-valCompare,false,mAnglePaint); } mCanvas.restore(); } /** * 指南针外部可简单分为两部分 * 1、用Path实现小三角形 * 2、两个圆弧 */ private void drawCompassOutSide() { mCanvas.save(); //小三角形的高度 int mTriangleHeight=40; //定义Path画小三角形 mOutsideTriangle.moveTo(width/2,mTextHeight-mTriangleHeight); //小三角形的边长 float mTriangleSide = 46.18f; //画出小三角形 mOutsideTriangle.lineTo(width/2-mTriangleSide/2,mTextHeight); mOutsideTriangle.lineTo(width/2+mTriangleSide/2,mTextHeight); mOutsideTriangle.close(); mCanvas.drawPath(mOutsideTriangle,mOutSideCircumPaint); //画圆弧 mDarkRedPaint.setStrokeWidth((float) 5); mLightGrayPaint.setStrokeWidth((float)5); mDeepGrayPaint.setStrokeWidth((float)3); mLightGrayPaint.setStyle(Paint.Style.STROKE); mCanvas.drawArc(width/2-mOutSideRadius,mTextHeight,width/2+mOutSideRadius,mTextHeight+mOutSideRadius*2,-80,120,false,mLightGrayPaint); mCanvas.drawArc(width/2-mOutSideRadius,mTextHeight,width/2+mOutSideRadius,mTextHeight+mOutSideRadius*2,40,20,false,mDeepGrayPaint); mCanvas.drawArc(width/2-mOutSideRadius,mTextHeight,width/2+mOutSideRadius,mTextHeight+mOutSideRadius*2,-100,-20,false,mLightGrayPaint); mCanvas.drawArc(width/2-mOutSideRadius,mTextHeight,width/2+mOutSideRadius,mTextHeight+mOutSideRadius*2,-120,-120,false,mDarkRedPaint); mCanvas.restore(); } private void drawText() { if (val<=15||val>=345){ text = "北"; }else if (val>15&&val<=75){ text= "东北"; }else if (val>75&&val<=105){ text= "东"; }else if (val>105&&val<=165){ text="东南"; }else if (val>165&&val<=195){ text = "南"; }else if (val>195&&val<=255){ text = "西南"; }else if (val>255&&val<=285){ text = "西"; }else if (val>285&&val<345){ text="西北"; } mTextPaint.getTextBounds(text,0,text.length(),mTextRect); //文字宽度 int mTextWidth = mTextRect.width(); //让文字水平居中显示 mCanvas.drawText(text,width/2-mTextWidth/2,mTextHeight/2,mTextPaint); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); width = Math.min(widthSize, heightSize); if (widthMode == MeasureSpec.UNSPECIFIED) { width = heightSize; } else if (heightMode == MeasureSpec.UNSPECIFIED) { width = widthSize; } //为指南针上面的文字预留空间,定为1/3边张 mTextHeight = width/3; //设置圆心点坐标 mCenterX = width/2; mCenterY = width/2+mTextHeight; //外部圆的外径 mOutSideRadius = width*3/8; //外接圆的半径 mCircumRadius = mOutSideRadius*4/5; //camera最大平移距离 mMaxCameraTranslate = 0.02f*mOutSideRadius; setMeasuredDimension(width, width+width/3 ); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: if (mValueAnimator!=null&&mValueAnimator.isRunning()){ mValueAnimator.cancel(); } //3D 效果让Camera旋转,获取旋转偏移大小 getCameraRotate(event); //获取平移大小 getCameraTranslate(event); break; case MotionEvent.ACTION_MOVE: //3D 效果让Camera旋转,获取旋转偏移大小 getCameraRotate(event); //获取平移大小 getCameraTranslate(event); break; case MotionEvent.ACTION_UP: //松开手 复原动画 startRestore(); break; } return true; } private void startRestore() { final String cameraRotateXName = "cameraRotateX"; final String cameraRotateYName = "cameraRotateY"; final String canvasTranslateXName = "canvasTranslateX"; final String canvasTranslateYName = "canvasTranslateY"; PropertyValuesHolder cameraRotateXHolder = PropertyValuesHolder.ofFloat(cameraRotateXName, mCameraRotateX, 0); PropertyValuesHolder cameraRotateYHolder = PropertyValuesHolder.ofFloat(cameraRotateYName, mCameraRotateY, 0); PropertyValuesHolder canvasTranslateXHolder = PropertyValuesHolder.ofFloat(canvasTranslateXName, mCameraTranslateX, 0); PropertyValuesHolder canvasTranslateYHolder = PropertyValuesHolder.ofFloat(canvasTranslateYName, mCameraTranslateY, 0); mValueAnimator = ValueAnimator.ofPropertyValuesHolder(cameraRotateXHolder, cameraRotateYHolder, canvasTranslateXHolder, canvasTranslateYHolder); mValueAnimator.setInterpolator(new TimeInterpolator() { @Override public float getInterpolation(float input) { float f = 0.571429f; return (float) (Math.pow(2, -2 * input) * Math.sin((input - f / 4) * (2 * Math.PI) / f) + 1); } }); mValueAnimator.setDuration(1000); mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mCameraRotateX = (float) animation.getAnimatedValue(cameraRotateXName); mCameraRotateY = (float) animation.getAnimatedValue(cameraRotateYName); mCameraTranslateX = (float) animation.getAnimatedValue(canvasTranslateXName); mCameraTranslateX = (float) animation.getAnimatedValue(canvasTranslateYName); } }); mValueAnimator.start(); } /** * 获取Camera,平移大小 * @param event */ private void getCameraTranslate(MotionEvent event) { float translateX = (event.getX() - getWidth() / 2); float translateY = (event.getY() - getHeight()/2); //求出此时位移的大小与半径之比 float[] percentArr = getPercent(translateX, translateY); //最终位移的大小按比例匀称改变 mCameraTranslateX = percentArr[0] * mMaxCameraTranslate; mCameraTranslateY = percentArr[1] * mMaxCameraTranslate; } /** * 让Camera旋转,获取旋转偏移大小 * @param event */ private void getCameraRotate(MotionEvent event) { float mRotateX = -(event.getY()-(getHeight())/2); float mRotateY = (event.getX()-getWidth()/2); //求出旋转大小与半径之比 float[] percentArr = getPercent(mRotateX,mRotateY); mCameraRotateX = percentArr[0]*mMaxCameraRotate; mCameraRotateY = percentArr[1]*mMaxCameraRotate; } /** * 获取比例 * @param mCameraRotateX * @param mCameraRotateY * @return */ private float[] getPercent(float mCameraRotateX, float mCameraRotateY) { float[] percentArr = new float[2]; float percentX = mCameraRotateX/width; float percentY = mCameraRotateY/width; //处理一下比例值 if (percentX > 1) { percentX = 1; } else if (percentX < -1) { percentX = -1; } if (percentY > 1) { percentY = 1; } else if (percentY < -1) { percentY = -1; } percentArr[0] = percentX; percentArr[1] = percentY; return percentArr; } }
ChaosOctopus/ChaosCompass
app/src/main/java/com/chaos/chaoscompass/ChaosCompassView.java
6,084
//最终位移的大小按比例匀称改变
line_comment
zh-cn
package com.chaos.chaoscompass; import android.animation.PropertyValuesHolder; import android.animation.TimeInterpolator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Camera; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RadialGradient; import android.graphics.Rect; import android.graphics.Shader; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * Created by yc.Zhao on 2017/12/27 0027. * 指南针View,new */ public class ChaosCompassView extends View{ private Canvas mCanvas; private Context mContext; //View矩形的宽度 private int width; //指南针圆心点坐标 private int mCenterX; private int mCenterY; //外圆半径 private int mOutSideRadius; //外接圆半径 private int mCircumRadius; //指南针文字大小空间高度 private int mTextHeight; //暗红色 外圈笔 private Paint mDarkRedPaint; //深灰 外圈笔 private Paint mDeepGrayPaint; //外三角笔 private Paint mOutSideCircumPaint; //浅灰 外圈笔 private Paint mLightGrayPaint; //指南针上面 文字笔 private Paint mTextPaint; //外接圆,三角形笔 private Paint mCircumPaint; //指南针上面文字的外接矩形,用来测文字大小让文字居中 private Rect mTextRect; //外圈小三角形的Path private Path mOutsideTriangle; //外接圆小三角形的Path private Path mCircumTriangle; //NESW 文字笔 和文字外接矩形 private Paint mNorthPaint; private Paint mOthersPaint; private Rect mPositionRect; //小刻度文字大小矩形和画笔 private Paint mSamllDegreePaint; //两位数的 private Rect mSencondRect; //三位数的 private Rect mThirdRect; //圆心数字矩形 private Rect mCenterTextRect; //中心文字笔 private Paint mCenterPaint; //内心圆是一个颜色辐射渐变的圆 private Shader mInnerShader; private Paint mInnerPaint; //定义个点击属性动画 private ValueAnimator mValueAnimator; // camera绕X轴旋转的角度 private float mCameraRotateX; // camera绕Y轴旋转的角度 private float mCameraRotateY; //camera最大旋转角度 private float mMaxCameraRotate = 10; // camera绕X轴旋转的角度 private float mCameraTranslateX; // camera绕Y轴旋转的角度 private float mCameraTranslateY; //camera最大旋转角度 private float mMaxCameraTranslate; //camera矩阵 private Matrix mCameraMatrix; //设置camera private Camera mCamera; private float val=0f; private float valCompare; //偏转角度红线笔 private Paint mAnglePaint; //方位文字 private String text="北"; public float getVal() { return val; } public void setVal(float val) { this.val = val; invalidate(); } public ChaosCompassView(Context context) { this(context,null); } public ChaosCompassView(Context context, @Nullable AttributeSet attrs) { this(context, attrs,0); } public ChaosCompassView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; mDarkRedPaint = new Paint(); mDarkRedPaint.setStyle(Paint.Style.STROKE); mDarkRedPaint.setAntiAlias(true); mDarkRedPaint.setColor(context.getResources().getColor(R.color.darkRed)); mDeepGrayPaint = new Paint(); mDeepGrayPaint.setStyle(Paint.Style.STROKE); mDeepGrayPaint.setAntiAlias(true); mDeepGrayPaint.setColor(context.getResources().getColor(R.color.deepGray)); mLightGrayPaint = new Paint(); mLightGrayPaint.setStyle(Paint.Style.FILL); mLightGrayPaint.setAntiAlias(true); mLightGrayPaint.setColor(context.getResources().getColor(R.color.lightGray)); mTextPaint = new Paint(); mTextPaint.setStyle(Paint.Style.STROKE); mTextPaint.setAntiAlias(true); mTextPaint.setTextSize(80); mTextPaint.setColor(context.getResources().getColor(R.color.white)); mCircumPaint = new Paint(); mCircumPaint.setStyle(Paint.Style.FILL); mCircumPaint.setAntiAlias(true); mCircumPaint.setColor(context.getResources().getColor(R.color.red)); mOutSideCircumPaint = new Paint(); mOutSideCircumPaint.setStyle(Paint.Style.FILL); mOutSideCircumPaint.setAntiAlias(true); mOutSideCircumPaint.setColor(context.getResources().getColor(R.color.lightGray)); mTextRect = new Rect(); mOutsideTriangle = new Path(); mCircumTriangle = new Path(); mNorthPaint = new Paint(); mNorthPaint.setStyle(Paint.Style.STROKE); mNorthPaint.setAntiAlias(true); mNorthPaint.setTextSize(40); mNorthPaint.setColor(context.getResources().getColor(R.color.red)); mOthersPaint = new Paint(); mOthersPaint.setStyle(Paint.Style.STROKE); mOthersPaint.setAntiAlias(true); mOthersPaint.setTextSize(40); mOthersPaint.setColor(context.getResources().getColor(R.color.white)); mPositionRect = new Rect(); mCenterTextRect = new Rect(); mCenterPaint = new Paint(); mCenterPaint.setStyle(Paint.Style.STROKE); mCenterPaint.setAntiAlias(true); mCenterPaint.setTextSize(120); mCenterPaint.setColor(context.getResources().getColor(R.color.white)); mSamllDegreePaint = new Paint(); mSamllDegreePaint.setStyle(Paint.Style.STROKE); mSamllDegreePaint.setAntiAlias(true); mSamllDegreePaint.setTextSize(30); mSamllDegreePaint.setColor(context.getResources().getColor(R.color.lightGray)); mSencondRect = new Rect(); mThirdRect = new Rect(); mInnerPaint = new Paint(); mInnerPaint.setStyle(Paint.Style.FILL); mInnerPaint.setAntiAlias(true); mAnglePaint = new Paint(); mAnglePaint.setStyle(Paint.Style.STROKE); mAnglePaint.setAntiAlias(true); mAnglePaint.setColor(context.getResources().getColor(R.color.red)); mCameraMatrix = new Matrix(); mCamera = new Camera(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mCanvas = canvas; //设置Camera矩阵 实现3D效果 set3DMetrix(); //画文字 drawText(); //画指南针外圈 drawCompassOutSide(); //画指南针外接圆 drawCompassCircum(); //画内部渐变颜色圆 drawInnerCricle(); //画指南针内部刻度 drawCompassDegreeScale(); //画圆心数字 drawCenterText(); } /** * 设置camera相关 */ private void set3DMetrix() { mCameraMatrix.reset(); mCamera.save(); mCamera.rotateX(mCameraRotateX); mCamera.rotateY(mCameraRotateY); mCamera.getMatrix(mCameraMatrix); mCamera.restore(); //camera默认旋转是View左上角为旋转中心 //所以动作之前要,设置矩阵位置 -mTextHeight-mOutSideRadius mCameraMatrix.preTranslate(-getWidth()/2,-getHeight()/2); //动作之后恢复位置 mCameraMatrix.postTranslate(getWidth()/2,getHeight()/2); mCanvas.concat(mCameraMatrix); } private void drawInnerCricle() { mInnerShader = new RadialGradient(width/2,mOutSideRadius+mTextHeight,mCircumRadius-40, Color.parseColor("#323232"), Color.parseColor("#000000"),Shader.TileMode.CLAMP); mInnerPaint.setShader(mInnerShader); mCanvas.drawCircle(width/2,mOutSideRadius+mTextHeight,mCircumRadius-40,mInnerPaint); } private void drawCenterText() { String centerText=String.valueOf((int) val+"°"); mCenterPaint.getTextBounds(centerText,0,centerText.length(),mCenterTextRect); int centerTextWidth = mCenterTextRect.width(); int centerTextHeight = mCenterTextRect.height(); mCanvas.drawText(centerText,width/2-centerTextWidth/2,mTextHeight+mOutSideRadius+centerTextHeight/5,mCenterPaint); } private void drawCompassDegreeScale() { mCanvas.save(); //获取N文字的宽度 mNorthPaint.getTextBounds("N",0,1,mPositionRect); int mPositionTextWidth = mPositionRect.width(); int mPositionTextHeight = mPositionRect.height(); //获取W文字宽度,因为W比较宽 所以要单独获取 mNorthPaint.getTextBounds("W",0,1,mPositionRect); int mWPositionTextWidth = mPositionRect.width(); int mWPositionTextHeight = mPositionRect.height(); //获取小刻度,两位数的宽度 mSamllDegreePaint.getTextBounds("30",0,1,mSencondRect); int mSencondTextWidth = mSencondRect.width(); int mSencondTextHeight = mSencondRect.height(); //获取小刻度,3位数的宽度 mSamllDegreePaint.getTextBounds("30",0,1,mThirdRect); int mThirdTextWidth = mThirdRect.width(); int mThirdTextHeight = mThirdRect.height(); mCanvas.rotate(-val,width/2,mOutSideRadius+mTextHeight); //画刻度线 for (int i = 0; i < 240; i++) { if (i==0||i==60||i==120||i==180){ mCanvas.drawLine(getWidth() / 2, mTextHeight+mOutSideRadius-mCircumRadius+10, getWidth() / 2, mTextHeight+mOutSideRadius-mCircumRadius+30, mDeepGrayPaint); }else{ mCanvas.drawLine(getWidth() / 2, mTextHeight+mOutSideRadius-mCircumRadius+10, getWidth() / 2, mTextHeight+mOutSideRadius-mCircumRadius+30, mLightGrayPaint); } if (i==0){ mCanvas.drawText("N", this.width /2-mPositionTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mPositionTextHeight,mNorthPaint); }else if (i==60){ mCanvas.drawText("E", this.width /2-mPositionTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mPositionTextHeight,mOthersPaint); }else if (i==120){ mCanvas.drawText("S", this.width /2-mPositionTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mPositionTextHeight,mOthersPaint); }else if (i==180){ mCanvas.drawText("W", this.width /2-mWPositionTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mWPositionTextHeight,mOthersPaint); }else if (i==20){ mCanvas.drawText("30", this.width /2-mSencondTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mSencondTextHeight,mSamllDegreePaint); }else if (i==40){ mCanvas.drawText("60", this.width /2-mSencondTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mSencondTextHeight,mSamllDegreePaint); }else if (i==80){ mCanvas.drawText("120", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==100){ mCanvas.drawText("150", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==140){ mCanvas.drawText("210", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==160){ mCanvas.drawText("240", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==200){ mCanvas.drawText("300", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); }else if (i==220){ mCanvas.drawText("330", this.width /2-mThirdTextWidth/2,mTextHeight+mOutSideRadius-mCircumRadius+40+mThirdTextHeight,mSamllDegreePaint); } mCanvas.rotate(1.5f, mCenterX, mOutSideRadius+mTextHeight); } mCanvas.restore(); } /** * 指南针外接圆,和外部圆换道理差不多 */ private void drawCompassCircum() { mCanvas.save(); //外接圆小三角形的高度 int mTriangleHeight=(mOutSideRadius-mCircumRadius)/2; mCanvas.rotate(-val,width/2,mOutSideRadius+mTextHeight); mCircumTriangle.moveTo(width/2,mTriangleHeight+mTextHeight); //内接三角形的边长,简单数学运算 float mTriangleSide = (float) ((mTriangleHeight/(Math.sqrt(3)))*2); mCircumTriangle.lineTo(width/2-mTriangleSide/2,mTextHeight+mTriangleHeight*2); mCircumTriangle.lineTo(width/2+mTriangleSide/2,mTextHeight+mTriangleHeight*2); mCircumTriangle.close(); mCanvas.drawPath(mCircumTriangle,mCircumPaint); mCanvas.drawArc(width/2-mCircumRadius,mTextHeight+mOutSideRadius-mCircumRadius, width/2+mCircumRadius,mTextHeight+mOutSideRadius+mCircumRadius,-85,350,false,mDeepGrayPaint); mAnglePaint.setStrokeWidth(5f); if (val<=180){ valCompare = val; mCanvas.drawArc(width/2-mCircumRadius,mTextHeight+mOutSideRadius-mCircumRadius, width/2+mCircumRadius,mTextHeight+mOutSideRadius+mCircumRadius,-85,valCompare,false,mAnglePaint); }else{ valCompare = 360-val; mCanvas.drawArc(width/2-mCircumRadius,mTextHeight+mOutSideRadius-mCircumRadius, width/2+mCircumRadius,mTextHeight+mOutSideRadius+mCircumRadius,-95,-valCompare,false,mAnglePaint); } mCanvas.restore(); } /** * 指南针外部可简单分为两部分 * 1、用Path实现小三角形 * 2、两个圆弧 */ private void drawCompassOutSide() { mCanvas.save(); //小三角形的高度 int mTriangleHeight=40; //定义Path画小三角形 mOutsideTriangle.moveTo(width/2,mTextHeight-mTriangleHeight); //小三角形的边长 float mTriangleSide = 46.18f; //画出小三角形 mOutsideTriangle.lineTo(width/2-mTriangleSide/2,mTextHeight); mOutsideTriangle.lineTo(width/2+mTriangleSide/2,mTextHeight); mOutsideTriangle.close(); mCanvas.drawPath(mOutsideTriangle,mOutSideCircumPaint); //画圆弧 mDarkRedPaint.setStrokeWidth((float) 5); mLightGrayPaint.setStrokeWidth((float)5); mDeepGrayPaint.setStrokeWidth((float)3); mLightGrayPaint.setStyle(Paint.Style.STROKE); mCanvas.drawArc(width/2-mOutSideRadius,mTextHeight,width/2+mOutSideRadius,mTextHeight+mOutSideRadius*2,-80,120,false,mLightGrayPaint); mCanvas.drawArc(width/2-mOutSideRadius,mTextHeight,width/2+mOutSideRadius,mTextHeight+mOutSideRadius*2,40,20,false,mDeepGrayPaint); mCanvas.drawArc(width/2-mOutSideRadius,mTextHeight,width/2+mOutSideRadius,mTextHeight+mOutSideRadius*2,-100,-20,false,mLightGrayPaint); mCanvas.drawArc(width/2-mOutSideRadius,mTextHeight,width/2+mOutSideRadius,mTextHeight+mOutSideRadius*2,-120,-120,false,mDarkRedPaint); mCanvas.restore(); } private void drawText() { if (val<=15||val>=345){ text = "北"; }else if (val>15&&val<=75){ text= "东北"; }else if (val>75&&val<=105){ text= "东"; }else if (val>105&&val<=165){ text="东南"; }else if (val>165&&val<=195){ text = "南"; }else if (val>195&&val<=255){ text = "西南"; }else if (val>255&&val<=285){ text = "西"; }else if (val>285&&val<345){ text="西北"; } mTextPaint.getTextBounds(text,0,text.length(),mTextRect); //文字宽度 int mTextWidth = mTextRect.width(); //让文字水平居中显示 mCanvas.drawText(text,width/2-mTextWidth/2,mTextHeight/2,mTextPaint); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); width = Math.min(widthSize, heightSize); if (widthMode == MeasureSpec.UNSPECIFIED) { width = heightSize; } else if (heightMode == MeasureSpec.UNSPECIFIED) { width = widthSize; } //为指南针上面的文字预留空间,定为1/3边张 mTextHeight = width/3; //设置圆心点坐标 mCenterX = width/2; mCenterY = width/2+mTextHeight; //外部圆的外径 mOutSideRadius = width*3/8; //外接圆的半径 mCircumRadius = mOutSideRadius*4/5; //camera最大平移距离 mMaxCameraTranslate = 0.02f*mOutSideRadius; setMeasuredDimension(width, width+width/3 ); } @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()){ case MotionEvent.ACTION_DOWN: if (mValueAnimator!=null&&mValueAnimator.isRunning()){ mValueAnimator.cancel(); } //3D 效果让Camera旋转,获取旋转偏移大小 getCameraRotate(event); //获取平移大小 getCameraTranslate(event); break; case MotionEvent.ACTION_MOVE: //3D 效果让Camera旋转,获取旋转偏移大小 getCameraRotate(event); //获取平移大小 getCameraTranslate(event); break; case MotionEvent.ACTION_UP: //松开手 复原动画 startRestore(); break; } return true; } private void startRestore() { final String cameraRotateXName = "cameraRotateX"; final String cameraRotateYName = "cameraRotateY"; final String canvasTranslateXName = "canvasTranslateX"; final String canvasTranslateYName = "canvasTranslateY"; PropertyValuesHolder cameraRotateXHolder = PropertyValuesHolder.ofFloat(cameraRotateXName, mCameraRotateX, 0); PropertyValuesHolder cameraRotateYHolder = PropertyValuesHolder.ofFloat(cameraRotateYName, mCameraRotateY, 0); PropertyValuesHolder canvasTranslateXHolder = PropertyValuesHolder.ofFloat(canvasTranslateXName, mCameraTranslateX, 0); PropertyValuesHolder canvasTranslateYHolder = PropertyValuesHolder.ofFloat(canvasTranslateYName, mCameraTranslateY, 0); mValueAnimator = ValueAnimator.ofPropertyValuesHolder(cameraRotateXHolder, cameraRotateYHolder, canvasTranslateXHolder, canvasTranslateYHolder); mValueAnimator.setInterpolator(new TimeInterpolator() { @Override public float getInterpolation(float input) { float f = 0.571429f; return (float) (Math.pow(2, -2 * input) * Math.sin((input - f / 4) * (2 * Math.PI) / f) + 1); } }); mValueAnimator.setDuration(1000); mValueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { mCameraRotateX = (float) animation.getAnimatedValue(cameraRotateXName); mCameraRotateY = (float) animation.getAnimatedValue(cameraRotateYName); mCameraTranslateX = (float) animation.getAnimatedValue(canvasTranslateXName); mCameraTranslateX = (float) animation.getAnimatedValue(canvasTranslateYName); } }); mValueAnimator.start(); } /** * 获取Camera,平移大小 * @param event */ private void getCameraTranslate(MotionEvent event) { float translateX = (event.getX() - getWidth() / 2); float translateY = (event.getY() - getHeight()/2); //求出此时位移的大小与半径之比 float[] percentArr = getPercent(translateX, translateY); //最终 <SUF> mCameraTranslateX = percentArr[0] * mMaxCameraTranslate; mCameraTranslateY = percentArr[1] * mMaxCameraTranslate; } /** * 让Camera旋转,获取旋转偏移大小 * @param event */ private void getCameraRotate(MotionEvent event) { float mRotateX = -(event.getY()-(getHeight())/2); float mRotateY = (event.getX()-getWidth()/2); //求出旋转大小与半径之比 float[] percentArr = getPercent(mRotateX,mRotateY); mCameraRotateX = percentArr[0]*mMaxCameraRotate; mCameraRotateY = percentArr[1]*mMaxCameraRotate; } /** * 获取比例 * @param mCameraRotateX * @param mCameraRotateY * @return */ private float[] getPercent(float mCameraRotateX, float mCameraRotateY) { float[] percentArr = new float[2]; float percentX = mCameraRotateX/width; float percentY = mCameraRotateY/width; //处理一下比例值 if (percentX > 1) { percentX = 1; } else if (percentX < -1) { percentX = -1; } if (percentY > 1) { percentY = 1; } else if (percentY < -1) { percentY = -1; } percentArr[0] = percentX; percentArr[1] = percentY; return percentArr; } }
1
16
1