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
44765_70
/** * <li>文件名:ResponseMessage.java * <li>说明: * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2011-11-11 * <li>修改人: * <li>修改日期: */ package com.jason.server; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jason.Config; import com.jason.util.MyStringUtil; import com.jason.util.CoderUtils; /** * <li>类型名称: * <li>说明:处理后的响应信息 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2011-11-11 * <li>修改人: * <li>修改日期: */ public class Response { private static Log log = LogFactory.getLog(Response.class);// 日志记录器 private String header;// 响应头信息 private String body;// 响应信息体 private String filePath;// 文件路径 private ConcurrentLinkedQueue<ByteBuffer> currentBufferQueue;// 当前正在传输的缓存区队列 private AtomicBoolean isBuffered = new AtomicBoolean(false);// 是否将内容放入缓存,默认为没有 private boolean isWriteFinished = false;// 是否完成传输处理 private long transelateSize = 0;// 已经传输的文件的长度 private FileInputStream fileInput = null;// 文件流 private FileChannel fileChannel = null;// 文件传输通道 private static int callMax = 100000;// 最大呼叫10万次 private volatile AtomicInteger callCount = new AtomicInteger(0); private ByteBuffer currentByteBuffer = null;// 当前的bytebuffer private Response parent = null;// 是否有父亲 private AtomicInteger subResponse = new AtomicInteger(0);// 是否将内容放入缓存,默认为没有 private ByteBuffer currentBuffer = null;// 当前缓冲区 private String requestIndex;// 请求索引 private static Boolean cahceInMemory = Config.getBoolean("cacheInMemory"); public ByteBuffer getCurrentBuffer() { return currentBuffer; } public void setCurrentBuffer(ByteBuffer currentBuffer) { this.currentBuffer = currentBuffer; } public Response getParent() { return parent; } public void setParent(Response parent) { this.parent = parent; } public AtomicInteger getSubResponse() { return subResponse; } public void setSubResponse(AtomicInteger subResponse) { this.subResponse = subResponse; } public void codeMsg(Client client){ try{ client.getCoderHandler().broundMsg(client, this); }catch(IOException e){ e.printStackTrace(); } } /** * * <li>方法名:parentProcess * <li> * <li>返回类型:void * <li>说明:释放缓冲区 * <li>创建人:CshBBrain, 技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-11-12 * <li>修改人: * <li>修改日期: */ public void parentRelease(){ if(this.subResponse.decrementAndGet() <= 0){ // 获取下一个缓冲区进行传输 ByteBuffer buffer = this.currentBufferQueue.poll(); while(buffer != null){ buffer.clear(); BufferPool.getInstance().releaseBuffer(buffer);// 将用完的缓冲区放回缓冲区池 buffer = this.currentBufferQueue.poll();// 从队列中删除缓冲区 } } } /** * * <li>方法名:msgRespose * <li>@param response * <li>@return * <li>返回类型:Response * <li>说明:根据消息创建消息 * <li>创建人:CshBBrain, 技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-11-12 * <li>修改人: * <li>修改日期: */ public static Response msgRespose(Response response){ Response msg = new Response(); msg.filePath = response.filePath; msg.parent = response; response.getSubResponse().incrementAndGet();// 加1 msg.isBuffered.set(true); msg.currentBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>(); Iterator<ByteBuffer> it = response.currentBufferQueue.iterator(); while(it.hasNext()){ msg.currentBufferQueue.add(it.next().asReadOnlyBuffer()); } return msg; } // 只有body public static Response msgOnlyBody(String body){ Response responseMessage = new Response(); responseMessage.setBody(body); return responseMessage; } // 只有file public static Response msgOnlyFile(String filePath){ Response responseMessage = new Response(); if(cahceInMemory){// 将文件缓存到内存中参数开启 ByteBuffer buffer = FileMapper.getInstance().getBuffer(filePath); if(buffer == null){ responseMessage.setFilePath(filePath); }else{ responseMessage.addBuffer(buffer); } }else{// 不缓存文件到内存中 responseMessage.setFilePath(filePath); } return responseMessage; } // header 和 file public static Response msgHeaderFile(String header, String filePath){ Response responseMessage = new Response(); responseMessage.setHeader(header); responseMessage.setFilePath(filePath); return responseMessage; } // body 和 file public static Response msgBodyFile(String body, String filePath){ Response responseMessage = new Response(); responseMessage.setBody(body); responseMessage.setFilePath(filePath); return responseMessage; } // header public static Response msgOnlyHeader(String header){ Response responseMessage = new Response(); responseMessage.setHeader(header); return responseMessage; } // body 和 file public static Response msgHeaderBody(String header, String body){ Response responseMessage = new Response(); responseMessage.setBody(body); responseMessage.setHeader(header); return responseMessage; } // header,body 和 file public static Response msgBodyFile(String header, String body, String filePath){ Response responseMessage = new Response(); responseMessage.setHeader(header); responseMessage.setBody(body); responseMessage.setFilePath(filePath); return responseMessage; } public Response(){ } /** * * <li>方法名:write * <li>@param sk * <li>@return * <li>返回类型:Integer,-1:传输过程中出现异常,1:顺利的传输完所有数据,2:没有传输完毕数据,连接的缓冲区已满 * <li>说明:返回true表示传输没有发生异常,返回false表示发生异常 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-3-10 * <li>修改人: * <li>修改日期: */ public Integer write(Client sk){ SocketChannel socketChannel =sk.getChannel(); this.bufferedContent();// 将内容放入到缓冲区中去 if(this.currentBuffer == null){// 第一次获取缓存,写入数据 this.currentBuffer = this.currentBufferQueue.poll(); if(this.currentBuffer != null){ log.info("the postion of the data in write: " + this.currentBuffer.position()); //this.currentBuffer.flip();// 反转缓存区 } } // 处理响应头,响应体的传输 if(this.currentBuffer != null){ while(this.currentBuffer != null){ int transCount = 0; try{ transCount = socketChannel.write(this.currentBuffer); log.info("translate size:" + transCount); }catch(IOException e){ e.printStackTrace(); this.closeChannel(); sk.close(); return -1; }// 非阻塞的sockect连接一次可能写不完数据 //this.callCount.incrementAndGet();//回写计数器 if(this.currentBuffer.position() + transCount >= this.currentBuffer.limit()){// 传完 this.currentBuffer.clear(); BufferPool.getInstance().releaseBuffer(this.currentBuffer);// 将用完的缓冲区放回缓冲区池 //this.currentBufferQueue.poll();// 从队列中删除缓冲区 // 获取下一个缓冲区进行传输 this.currentBuffer = this.currentBufferQueue.poll(); if(this.currentBuffer != null){ this.currentBuffer.flip();// 反转缓存区 } }else if(transCount > 0){// 没有传完,下次再传输 this.currentBuffer.position(this.currentBuffer.position() + transCount); }else if(transCount <= 0){// 缓冲区已满,无法写入更多的数据 this.callCount.incrementAndGet();//回写计数器 return 2; } log.info("向客户端传输数据的长度 : " + transCount); } } // 如果有文件则传输文件 if(!MyStringUtil.isBlank(this.filePath)){ try{ if(this.fileChannel == null){ this.createFileChannel();// 处理文件不存在的问题 } // 直接通过文件管道将文件内容输出到客户端 if(transelateSize < fileChannel.size()){ Long transferLength = fileChannel.transferTo(transelateSize, (fileChannel.size() - transelateSize), socketChannel); //Long transferLength = fileChannel.transferTo(transelateSize, ((fileChannel.size() - transelateSize) > 64 * 1024 ? 1024 * 64 : (fileChannel.size() - transelateSize)), socketChannel); transelateSize += transferLength; if(transelateSize >= fileChannel.size()){ this.closeChannel(); this.isWriteFinished = true; } }else{// 文件传输完毕 this.closeChannel(); this.isWriteFinished = true; } this.callCount.incrementAndGet();//回写计数器 }catch(IOException e){ e.printStackTrace(); this.closeChannel();// 关闭文件 sk.close(); return -1; } }else{ this.isWriteFinished = true; } if(this.isWriteFinished){ if(this.parent != null){ this.parent.parentRelease(); } return 1;// 正常处理 }else{ return 2;// 没有传输完数据 } } /** * * <li>方法名:createFileChannel * <li>@return * <li>返回类型:boolean * <li>说明:创建通道 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ private boolean createFileChannel(){ File requestedFile = new File(this.filePath); if(requestedFile != null && requestedFile.exists()){ try { // 直接通过文件管道将文件内容输出到客户端 this.fileInput = new FileInputStream(requestedFile); this.fileChannel = fileInput.getChannel(); } catch (IOException e) { e.printStackTrace(); this.closeChannel(); } return true; } return false; } /** * * <li>方法名:closeChannel * <li> * <li>返回类型:void * <li>说明:删除文件通道和文件流 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ private void closeChannel(){ try { if(this.fileInput != null){ this.fileInput.close(); this.fileInput = null; } if(this.fileChannel != null){ this.fileChannel.close(); this.fileChannel = null; } }catch (IOException ex) { ex.printStackTrace(); } } /** * * <li>方法名:bufferedContent * <li> * <li>返回类型:void * <li>说明:将响应头和响应体内容放入到缓存中 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ public void bufferedContent(){ if(this.isBuffered.compareAndSet(false, true)){// 如果已经做的缓存就不做处理了 this.currentByteBuffer = null;// 将当前缓冲区置空 this.currentBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>();// 当前正在处理的缓冲区队列 ByteBuffer headerBuffer = processBuffered(this.header); ByteBuffer bodyBuffer = processBuffered(headerBuffer, this.body); if(bodyBuffer != null){ this.currentBufferQueue.add(bodyBuffer); } } } /** * * <li>方法名:addBuffer * <li>@param buffers * <li>返回类型:void * <li>说明:添加缓存区 * <li>创建人:陈嗣洪 * <li>创建日期:2013-1-26 * <li>修改人: * <li>修改日期: */ public void addBuffer(ByteBuffer...buffers){ if(buffers != null && buffers.length > 0){ this.currentBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>();// 当前正在处理的缓冲区队列 for(ByteBuffer buffer : buffers){ this.currentBufferQueue.add(buffer); } this.isBuffered.set(true); } } /** * * <li>方法名:getBuffer * <li>@return * <li>返回类型:ByteBuffer * <li>说明: * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-9-18 * <li>修改人: * <li>修改日期: */ public ByteBuffer getBuffer(){ if(this.currentBufferQueue == null){ this.currentBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>();// 当前正在处理的缓冲区队列 } if(this.currentByteBuffer == null || this.currentByteBuffer.remaining() <= 0){ this.currentByteBuffer = BufferPool.getInstance().getBuffer(); this.currentBufferQueue.add(this.currentByteBuffer); } return this.currentByteBuffer; } /** * * <li>方法名:appendBytes * <li>@param datas * <li>返回类型:void * <li>说明:将数据放入到缓冲区中 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-9-19 * <li>修改人: * <li>修改日期: */ public void appendBytes(byte...datas){ this.isBuffered.set(true); ByteBuffer buffer = this.getBuffer(); if(buffer.remaining() >= datas.length){// 缓冲区的空间大于数据的长度 buffer.put(datas); log.info("the postion of the data: " + buffer.position()); }else{// 缓冲区的空间小于数据的长度 int offset = 0;// 初始相对位移为0 int length = buffer.remaining();// 初始传递的数据长度为缓冲区的剩余长度 do{ buffer.put(datas, offset, length); offset += length; if(offset < datas.length){ buffer = this.getBuffer(); length = (buffer.remaining() > (datas.length - offset) ? (datas.length - offset) : buffer.remaining()); }else{ break; } }while(true); } } /** * * <li>方法名:resetCurrentBuffer * <li> * <li>返回类型:void * <li>说明:重置当前缓冲区 * <li>创建人:CshBBrain, 技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-11-12 * <li>修改人: * <li>修改日期: */ public void resetCurrentBuffer(){ this.currentByteBuffer = null; } /** * * <li>方法名:processBuffered * <li>@param msg * <li>@return * <li>返回类型:ByteBuffer * <li>说明:将内容放入到缓存,默认设置缓冲区为空 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ private ByteBuffer processBuffered(String msg){ return this.processBuffered(null, msg); } /** * * <li>方法名:processBuffered * <li>@param bb * <li>@param msg * <li>@return * <li>返回类型:ByteBuffer * <li>说明:带缓冲区的将内容放入到缓冲区 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ private ByteBuffer processBuffered(ByteBuffer bb, String msg){ // 处理没有内容的情况 if(msg == null){ return bb; } byte[] header = CoderUtils.toByte(msg); //byte[] header = Utf8Coder.toNormalByte(msg); int cotentLength = header.length; int count = 0; if(bb == null){// 如果缓冲区为空,则创建一个缓冲区 bb = BufferPool.getInstance().getBuffer(); } do{ int mark = cotentLength - count;// 设置往缓冲区写入字节数组的上限下标 boolean newBuffer = false; // 下次循环是否重新获取缓冲区标识符 if(mark > bb.remaining()){// 如果字节数组剩余的内容大于缓存区的大小取缓冲区的剩余大小为字节数组 mark = bb.remaining(); newBuffer = true; } bb.put(header, count, mark); count += mark; if(newBuffer){ this.currentBufferQueue.add(bb);// 将放满内容的缓冲区放入到队列中 bb = BufferPool.getInstance().getBuffer(); }else{ return bb; } }while(cotentLength > count); return null; } /** * * <li>方法名:isException * <li>@return * <li>返回类型:boolean * <li>说明:判断传输是否出现了异常 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-24 * <li>修改人: * <li>修改日期: */ public boolean isException(){ boolean isExc = callCount.incrementAndGet() > callMax; if(isExc){ this.closeChannel(); } return isExc; } public Response(String header){ this.header = header; } public Response(String header,String body){ this.header = header; this.body = body; } public Response(String header,String body,String filePath){ this.header = header; this.body = body; this.filePath = filePath; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } public ConcurrentLinkedQueue<ByteBuffer> getCurrentBufferQueue() { return currentBufferQueue; } public void setCurrentBufferQueue( ConcurrentLinkedQueue<ByteBuffer> currentBufferQueue) { this.currentBufferQueue = currentBufferQueue; } public boolean isWriteFinished() { return isWriteFinished; } public void setWriteFinished(boolean isWriteFinished) { this.isWriteFinished = isWriteFinished; } public long getTranselateSize() { return transelateSize; } public void setTranselateSize(long transelateSize) { this.transelateSize = transelateSize; } public AtomicInteger getCallCount() { return callCount; } public void setCallCount(AtomicInteger callCount) { this.callCount = callCount; } public ByteBuffer getCurrentByteBuffer() { return currentByteBuffer; } public void setCurrentByteBuffer(ByteBuffer currentByteBuffer) { this.currentByteBuffer = currentByteBuffer; } public AtomicBoolean getIsBuffered() { return isBuffered; } public void setIsBuffered(AtomicBoolean isBuffered) { this.isBuffered = isBuffered; } public String getRequestIndex() { return requestIndex; } public void setRequestIndex(String requestIndex) { this.requestIndex = requestIndex; } }
CshBBrain/CshBBrainPP
src/com/jason/server/Response.java
5,668
// 缓冲区的空间小于数据的长度
line_comment
zh-cn
/** * <li>文件名:ResponseMessage.java * <li>说明: * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2011-11-11 * <li>修改人: * <li>修改日期: */ package com.jason.server; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.SocketChannel; import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.jason.Config; import com.jason.util.MyStringUtil; import com.jason.util.CoderUtils; /** * <li>类型名称: * <li>说明:处理后的响应信息 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2011-11-11 * <li>修改人: * <li>修改日期: */ public class Response { private static Log log = LogFactory.getLog(Response.class);// 日志记录器 private String header;// 响应头信息 private String body;// 响应信息体 private String filePath;// 文件路径 private ConcurrentLinkedQueue<ByteBuffer> currentBufferQueue;// 当前正在传输的缓存区队列 private AtomicBoolean isBuffered = new AtomicBoolean(false);// 是否将内容放入缓存,默认为没有 private boolean isWriteFinished = false;// 是否完成传输处理 private long transelateSize = 0;// 已经传输的文件的长度 private FileInputStream fileInput = null;// 文件流 private FileChannel fileChannel = null;// 文件传输通道 private static int callMax = 100000;// 最大呼叫10万次 private volatile AtomicInteger callCount = new AtomicInteger(0); private ByteBuffer currentByteBuffer = null;// 当前的bytebuffer private Response parent = null;// 是否有父亲 private AtomicInteger subResponse = new AtomicInteger(0);// 是否将内容放入缓存,默认为没有 private ByteBuffer currentBuffer = null;// 当前缓冲区 private String requestIndex;// 请求索引 private static Boolean cahceInMemory = Config.getBoolean("cacheInMemory"); public ByteBuffer getCurrentBuffer() { return currentBuffer; } public void setCurrentBuffer(ByteBuffer currentBuffer) { this.currentBuffer = currentBuffer; } public Response getParent() { return parent; } public void setParent(Response parent) { this.parent = parent; } public AtomicInteger getSubResponse() { return subResponse; } public void setSubResponse(AtomicInteger subResponse) { this.subResponse = subResponse; } public void codeMsg(Client client){ try{ client.getCoderHandler().broundMsg(client, this); }catch(IOException e){ e.printStackTrace(); } } /** * * <li>方法名:parentProcess * <li> * <li>返回类型:void * <li>说明:释放缓冲区 * <li>创建人:CshBBrain, 技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-11-12 * <li>修改人: * <li>修改日期: */ public void parentRelease(){ if(this.subResponse.decrementAndGet() <= 0){ // 获取下一个缓冲区进行传输 ByteBuffer buffer = this.currentBufferQueue.poll(); while(buffer != null){ buffer.clear(); BufferPool.getInstance().releaseBuffer(buffer);// 将用完的缓冲区放回缓冲区池 buffer = this.currentBufferQueue.poll();// 从队列中删除缓冲区 } } } /** * * <li>方法名:msgRespose * <li>@param response * <li>@return * <li>返回类型:Response * <li>说明:根据消息创建消息 * <li>创建人:CshBBrain, 技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-11-12 * <li>修改人: * <li>修改日期: */ public static Response msgRespose(Response response){ Response msg = new Response(); msg.filePath = response.filePath; msg.parent = response; response.getSubResponse().incrementAndGet();// 加1 msg.isBuffered.set(true); msg.currentBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>(); Iterator<ByteBuffer> it = response.currentBufferQueue.iterator(); while(it.hasNext()){ msg.currentBufferQueue.add(it.next().asReadOnlyBuffer()); } return msg; } // 只有body public static Response msgOnlyBody(String body){ Response responseMessage = new Response(); responseMessage.setBody(body); return responseMessage; } // 只有file public static Response msgOnlyFile(String filePath){ Response responseMessage = new Response(); if(cahceInMemory){// 将文件缓存到内存中参数开启 ByteBuffer buffer = FileMapper.getInstance().getBuffer(filePath); if(buffer == null){ responseMessage.setFilePath(filePath); }else{ responseMessage.addBuffer(buffer); } }else{// 不缓存文件到内存中 responseMessage.setFilePath(filePath); } return responseMessage; } // header 和 file public static Response msgHeaderFile(String header, String filePath){ Response responseMessage = new Response(); responseMessage.setHeader(header); responseMessage.setFilePath(filePath); return responseMessage; } // body 和 file public static Response msgBodyFile(String body, String filePath){ Response responseMessage = new Response(); responseMessage.setBody(body); responseMessage.setFilePath(filePath); return responseMessage; } // header public static Response msgOnlyHeader(String header){ Response responseMessage = new Response(); responseMessage.setHeader(header); return responseMessage; } // body 和 file public static Response msgHeaderBody(String header, String body){ Response responseMessage = new Response(); responseMessage.setBody(body); responseMessage.setHeader(header); return responseMessage; } // header,body 和 file public static Response msgBodyFile(String header, String body, String filePath){ Response responseMessage = new Response(); responseMessage.setHeader(header); responseMessage.setBody(body); responseMessage.setFilePath(filePath); return responseMessage; } public Response(){ } /** * * <li>方法名:write * <li>@param sk * <li>@return * <li>返回类型:Integer,-1:传输过程中出现异常,1:顺利的传输完所有数据,2:没有传输完毕数据,连接的缓冲区已满 * <li>说明:返回true表示传输没有发生异常,返回false表示发生异常 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-3-10 * <li>修改人: * <li>修改日期: */ public Integer write(Client sk){ SocketChannel socketChannel =sk.getChannel(); this.bufferedContent();// 将内容放入到缓冲区中去 if(this.currentBuffer == null){// 第一次获取缓存,写入数据 this.currentBuffer = this.currentBufferQueue.poll(); if(this.currentBuffer != null){ log.info("the postion of the data in write: " + this.currentBuffer.position()); //this.currentBuffer.flip();// 反转缓存区 } } // 处理响应头,响应体的传输 if(this.currentBuffer != null){ while(this.currentBuffer != null){ int transCount = 0; try{ transCount = socketChannel.write(this.currentBuffer); log.info("translate size:" + transCount); }catch(IOException e){ e.printStackTrace(); this.closeChannel(); sk.close(); return -1; }// 非阻塞的sockect连接一次可能写不完数据 //this.callCount.incrementAndGet();//回写计数器 if(this.currentBuffer.position() + transCount >= this.currentBuffer.limit()){// 传完 this.currentBuffer.clear(); BufferPool.getInstance().releaseBuffer(this.currentBuffer);// 将用完的缓冲区放回缓冲区池 //this.currentBufferQueue.poll();// 从队列中删除缓冲区 // 获取下一个缓冲区进行传输 this.currentBuffer = this.currentBufferQueue.poll(); if(this.currentBuffer != null){ this.currentBuffer.flip();// 反转缓存区 } }else if(transCount > 0){// 没有传完,下次再传输 this.currentBuffer.position(this.currentBuffer.position() + transCount); }else if(transCount <= 0){// 缓冲区已满,无法写入更多的数据 this.callCount.incrementAndGet();//回写计数器 return 2; } log.info("向客户端传输数据的长度 : " + transCount); } } // 如果有文件则传输文件 if(!MyStringUtil.isBlank(this.filePath)){ try{ if(this.fileChannel == null){ this.createFileChannel();// 处理文件不存在的问题 } // 直接通过文件管道将文件内容输出到客户端 if(transelateSize < fileChannel.size()){ Long transferLength = fileChannel.transferTo(transelateSize, (fileChannel.size() - transelateSize), socketChannel); //Long transferLength = fileChannel.transferTo(transelateSize, ((fileChannel.size() - transelateSize) > 64 * 1024 ? 1024 * 64 : (fileChannel.size() - transelateSize)), socketChannel); transelateSize += transferLength; if(transelateSize >= fileChannel.size()){ this.closeChannel(); this.isWriteFinished = true; } }else{// 文件传输完毕 this.closeChannel(); this.isWriteFinished = true; } this.callCount.incrementAndGet();//回写计数器 }catch(IOException e){ e.printStackTrace(); this.closeChannel();// 关闭文件 sk.close(); return -1; } }else{ this.isWriteFinished = true; } if(this.isWriteFinished){ if(this.parent != null){ this.parent.parentRelease(); } return 1;// 正常处理 }else{ return 2;// 没有传输完数据 } } /** * * <li>方法名:createFileChannel * <li>@return * <li>返回类型:boolean * <li>说明:创建通道 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ private boolean createFileChannel(){ File requestedFile = new File(this.filePath); if(requestedFile != null && requestedFile.exists()){ try { // 直接通过文件管道将文件内容输出到客户端 this.fileInput = new FileInputStream(requestedFile); this.fileChannel = fileInput.getChannel(); } catch (IOException e) { e.printStackTrace(); this.closeChannel(); } return true; } return false; } /** * * <li>方法名:closeChannel * <li> * <li>返回类型:void * <li>说明:删除文件通道和文件流 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ private void closeChannel(){ try { if(this.fileInput != null){ this.fileInput.close(); this.fileInput = null; } if(this.fileChannel != null){ this.fileChannel.close(); this.fileChannel = null; } }catch (IOException ex) { ex.printStackTrace(); } } /** * * <li>方法名:bufferedContent * <li> * <li>返回类型:void * <li>说明:将响应头和响应体内容放入到缓存中 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ public void bufferedContent(){ if(this.isBuffered.compareAndSet(false, true)){// 如果已经做的缓存就不做处理了 this.currentByteBuffer = null;// 将当前缓冲区置空 this.currentBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>();// 当前正在处理的缓冲区队列 ByteBuffer headerBuffer = processBuffered(this.header); ByteBuffer bodyBuffer = processBuffered(headerBuffer, this.body); if(bodyBuffer != null){ this.currentBufferQueue.add(bodyBuffer); } } } /** * * <li>方法名:addBuffer * <li>@param buffers * <li>返回类型:void * <li>说明:添加缓存区 * <li>创建人:陈嗣洪 * <li>创建日期:2013-1-26 * <li>修改人: * <li>修改日期: */ public void addBuffer(ByteBuffer...buffers){ if(buffers != null && buffers.length > 0){ this.currentBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>();// 当前正在处理的缓冲区队列 for(ByteBuffer buffer : buffers){ this.currentBufferQueue.add(buffer); } this.isBuffered.set(true); } } /** * * <li>方法名:getBuffer * <li>@return * <li>返回类型:ByteBuffer * <li>说明: * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-9-18 * <li>修改人: * <li>修改日期: */ public ByteBuffer getBuffer(){ if(this.currentBufferQueue == null){ this.currentBufferQueue = new ConcurrentLinkedQueue<ByteBuffer>();// 当前正在处理的缓冲区队列 } if(this.currentByteBuffer == null || this.currentByteBuffer.remaining() <= 0){ this.currentByteBuffer = BufferPool.getInstance().getBuffer(); this.currentBufferQueue.add(this.currentByteBuffer); } return this.currentByteBuffer; } /** * * <li>方法名:appendBytes * <li>@param datas * <li>返回类型:void * <li>说明:将数据放入到缓冲区中 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-9-19 * <li>修改人: * <li>修改日期: */ public void appendBytes(byte...datas){ this.isBuffered.set(true); ByteBuffer buffer = this.getBuffer(); if(buffer.remaining() >= datas.length){// 缓冲区的空间大于数据的长度 buffer.put(datas); log.info("the postion of the data: " + buffer.position()); }else{// 缓冲 <SUF> int offset = 0;// 初始相对位移为0 int length = buffer.remaining();// 初始传递的数据长度为缓冲区的剩余长度 do{ buffer.put(datas, offset, length); offset += length; if(offset < datas.length){ buffer = this.getBuffer(); length = (buffer.remaining() > (datas.length - offset) ? (datas.length - offset) : buffer.remaining()); }else{ break; } }while(true); } } /** * * <li>方法名:resetCurrentBuffer * <li> * <li>返回类型:void * <li>说明:重置当前缓冲区 * <li>创建人:CshBBrain, 技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-11-12 * <li>修改人: * <li>修改日期: */ public void resetCurrentBuffer(){ this.currentByteBuffer = null; } /** * * <li>方法名:processBuffered * <li>@param msg * <li>@return * <li>返回类型:ByteBuffer * <li>说明:将内容放入到缓存,默认设置缓冲区为空 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ private ByteBuffer processBuffered(String msg){ return this.processBuffered(null, msg); } /** * * <li>方法名:processBuffered * <li>@param bb * <li>@param msg * <li>@return * <li>返回类型:ByteBuffer * <li>说明:带缓冲区的将内容放入到缓冲区 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-3 * <li>修改人: * <li>修改日期: */ private ByteBuffer processBuffered(ByteBuffer bb, String msg){ // 处理没有内容的情况 if(msg == null){ return bb; } byte[] header = CoderUtils.toByte(msg); //byte[] header = Utf8Coder.toNormalByte(msg); int cotentLength = header.length; int count = 0; if(bb == null){// 如果缓冲区为空,则创建一个缓冲区 bb = BufferPool.getInstance().getBuffer(); } do{ int mark = cotentLength - count;// 设置往缓冲区写入字节数组的上限下标 boolean newBuffer = false; // 下次循环是否重新获取缓冲区标识符 if(mark > bb.remaining()){// 如果字节数组剩余的内容大于缓存区的大小取缓冲区的剩余大小为字节数组 mark = bb.remaining(); newBuffer = true; } bb.put(header, count, mark); count += mark; if(newBuffer){ this.currentBufferQueue.add(bb);// 将放满内容的缓冲区放入到队列中 bb = BufferPool.getInstance().getBuffer(); }else{ return bb; } }while(cotentLength > count); return null; } /** * * <li>方法名:isException * <li>@return * <li>返回类型:boolean * <li>说明:判断传输是否出现了异常 * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/ * <li>创建日期:2012-2-24 * <li>修改人: * <li>修改日期: */ public boolean isException(){ boolean isExc = callCount.incrementAndGet() > callMax; if(isExc){ this.closeChannel(); } return isExc; } public Response(String header){ this.header = header; } public Response(String header,String body){ this.header = header; this.body = body; } public Response(String header,String body,String filePath){ this.header = header; this.body = body; this.filePath = filePath; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getHeader() { return header; } public void setHeader(String header) { this.header = header; } public ConcurrentLinkedQueue<ByteBuffer> getCurrentBufferQueue() { return currentBufferQueue; } public void setCurrentBufferQueue( ConcurrentLinkedQueue<ByteBuffer> currentBufferQueue) { this.currentBufferQueue = currentBufferQueue; } public boolean isWriteFinished() { return isWriteFinished; } public void setWriteFinished(boolean isWriteFinished) { this.isWriteFinished = isWriteFinished; } public long getTranselateSize() { return transelateSize; } public void setTranselateSize(long transelateSize) { this.transelateSize = transelateSize; } public AtomicInteger getCallCount() { return callCount; } public void setCallCount(AtomicInteger callCount) { this.callCount = callCount; } public ByteBuffer getCurrentByteBuffer() { return currentByteBuffer; } public void setCurrentByteBuffer(ByteBuffer currentByteBuffer) { this.currentByteBuffer = currentByteBuffer; } public AtomicBoolean getIsBuffered() { return isBuffered; } public void setIsBuffered(AtomicBoolean isBuffered) { this.isBuffered = isBuffered; } public String getRequestIndex() { return requestIndex; } public void setRequestIndex(String requestIndex) { this.requestIndex = requestIndex; } }
1
17
1
46751_25
package care; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.melnykov.fab.sample.R; import com.melnykov.fab.sample.tools.IMApplication; import com.melnykov.fab.sample.tools.crmMyDatabaseHelper; import com.ricky.database.CenterDatabase; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by dell on 2015/8/25. */ public class care_add extends Activity implements View.OnTouchListener{ private Button btn01; private EditText et01; private EditText et02; public static final String KEY_USER_ID="KEY_USER_ID"; public static final String KEY_USER_PASSWORD="KEY_USER_PASSWORD"; private List<String> list = new ArrayList<String>(); private ArrayAdapter<String> adapter; private List<String> list2 = new ArrayList<String>(); private ArrayAdapter<String> adapter2; private Spinner spinner_type; //private I TextView queding,text_care_time,text_care_time2; EditText care_note; // ImageView care_choose_time,care_choose_time2; RelativeLayout back; private String type="生日关爱",time=" ",time2,note="",isokflag=""; String userid; String care_id; String User_id; public crmMyDatabaseHelper dbHelper; String fff; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.care_dialog); CenterDatabase centerDatabase = new CenterDatabase(this, null); userid = centerDatabase.getUID(); centerDatabase.close(); User_id = IMApplication.getUserid(this); dbHelper = new crmMyDatabaseHelper(this, "customer.db3", 1); spinner_type=(Spinner)findViewById(R.id.spinner_type); //spinner_remind=(Spinner)findViewById(R.id.spinner_remind); text_care_time=(TextView)findViewById(R.id.care_time); text_care_time2=(TextView)findViewById(R.id.care_time2); care_note=(EditText)findViewById(R.id.care_note); back=(RelativeLayout)findViewById(R.id.ImageButton_back); queding=(TextView)findViewById(R.id.care_submit); text_care_time.setFocusable(true);text_care_time.setClickable(true); text_care_time2.setFocusable(true);text_care_time2.setClickable(true); text_care_time.setOnTouchListener(this);text_care_time2.setOnTouchListener(this); /* care_choose_time=(ImageView)findViewById(R.id.care_choose_time); care_choose_time2=(ImageView)findViewById(R.id.care_choose_time2);*/ queding.setFocusable(true);queding.setClickable(true); /* care_choose_time.setFocusable(true);care_choose_time.setClickable(true); care_choose_time.setOnTouchListener(this); care_choose_time2.setFocusable(true);care_choose_time2.setClickable(true); care_choose_time2.setOnTouchListener(this);*/ back.setFocusable(true);back.setClickable(true); back.setOnTouchListener(this); queding.setOnTouchListener(this); if(getIntent().getAction()=="edite"){ queding.setText("修改"); care_id= getIntent().getExtras().getString("_id"); // Toast.makeText(care_add.this, "修改id:" + care_id, Toast.LENGTH_LONG).show(); Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from care_table where _id=" + care_id, null); while (cursor.moveToNext()){ // Toast.makeText(care_add.this, "修改查询出来为:" + cursor.getString(1), Toast.LENGTH_LONG).show(); note=cursor.getString(5); care_note.setText(note); time=cursor.getString(3); text_care_time.setText(time); time2=cursor.getString(4); text_care_time2.setText(time2); } // Toast.makeText(care_add.this, "修改查询出来为:" + cursor.getString(1), Toast.LENGTH_LONG).show(); }else if(getIntent().getAction()=="lianxirenadd"){ } else{ /* Calendar calendar=Calendar.getInstance(); int year=calendar.get(Calendar.HOUR); int minute=calendar.get(Calendar.MINUTE); int second=calendar.get(Calendar.SECOND); Time time=new Time();*/ Date date=new Date(); DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time22=format.format(date); text_care_time.setText(time22); time=time22; } //第一步:添加一个下拉列表项的list,这里添加的项就是下拉列表的菜单项 list.add("生日"); list.add("节日"); list.add("庆祝日"); list.add("其他"); //第二步:为下拉列表定义一个适配器,这里就用到里前面定义的list。 adapter = new ArrayAdapter<String>(this,R.layout.myspinner_item, list); //第三步:为适配器设置下拉列表下拉时的菜单样式。 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //第四步:将适配器添加到下拉列表上 spinner_type.setAdapter(adapter); //第五步:为下拉列表设置各种事件的响应,这个事响应菜单被选中 spinner_type.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub type=adapter.getItem(arg2); /* 将mySpinner 显示*/ arg0.setVisibility(View.VISIBLE); } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub arg0.setVisibility(View.VISIBLE); } }); /*下拉菜单弹出的内容选项触屏事件处理*/ spinner_type.setOnTouchListener(new Spinner.OnTouchListener(){ public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return false; } }); /*下拉菜单弹出的内容选项焦点改变事件处理*/ spinner_type.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { // TODO Auto-generated method stub } }); } int ii=0; @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (v.getId() == R.id.care_time||v.getId() == R.id.care_time2) { // Toast.makeText(care_add.this,"1",Toast.LENGTH_SHORT).show(); if(v.getId() == R.id.care_time) ii=1;else ii=2; AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = View.inflate(this, R.layout.date_time_dialog, null); final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker); final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker); builder.setView(view); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); timePicker.setIs24HourView(true); timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(Calendar.MINUTE); builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { StringBuffer sb = new StringBuffer(); sb.append(String.format("%d-%02d-%02d", datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth())); sb.append(" "); sb.append(String.format("%02d:%02d", timePicker.getCurrentHour(), timePicker.getCurrentMinute())); if(ii==1) { text_care_time.setText(sb); time = sb.toString(); } else { text_care_time2.setText(sb); time2 = sb.toString(); } dialog.cancel(); } }); Dialog dialog = builder.create(); dialog.show(); } } if(event.getAction()==MotionEvent.ACTION_UP){ if(v.getId()== R.id.ImageButton_back){ new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage("确定退出填写吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { care_add.this.setResult(0); dialog.dismiss(); care_add.this.finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } else if(v.getId()== R.id.care_submit){ if(type==null||time==null||time2==null) { new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage("请完善信息!") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); }else if(getIntent().getAction()=="lianxirenadd"){ dbHelper.getWritableDatabase().execSQL("insert into care_table(uid,type,time,time2,note,fname,fsex,fphone,fid)" + " values(?,?,?,?,?,?,?,?,?)", new String[]{User_id,type ,time ,time2 , note, getIntent().getStringExtra("username"),getIntent().getStringExtra("sex"), getIntent().getStringExtra("phone"), getIntent().getStringExtra("lianxirenid")}); care_add.this.finish(); } else{ if (getIntent().getAction()!=null){ fff="确定修改?"; } else{ fff="确定提交?"; } /* new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage(fff) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {*/ note=care_note.getText().toString().trim(); if (fff.equals("确定提交?")) { Intent mIntent = new Intent(); mIntent.putExtra("type", type); mIntent.putExtra("time", time); mIntent.putExtra("time2",time2); mIntent.putExtra("note",note ); // 设置结果,并进行传送 care_add.this.setResult(1, mIntent); } else { /* dbHelper.getReadableDatabase().rawQuery("update care_table set type="+type+",time="+time+",remind="+remind+",note="+note+" where" + "uid="+userid,null);*/ dbHelper.getWritableDatabase().execSQL("update care_table set type = ?,time = ?,time2 = ?,note = ? where _id=?", new String[]{type, time, time2,note,care_id}); // Toast.makeText(care_add.this,"_id"+care_id,Toast.LENGTH_SHORT).show(); for (int i=0;i<100;i++){ if(aa.remindid[i][0]==care_id){ aa.cancelRemind(aa.remindid[i][1], care_add.this); aa.setRemind(time2,type+" "+time+note,"care_remind",0,2, care_add.this); } } Log.e("更新关爱信息","成功"); startActivity(new Intent().setClass(care_add.this, care_main.class)); } care_add.this.finish(); } } } return false; } }
CsterKuroi/CRM-Android
crmlianxi/src/main/java/care/care_add.java
3,231
// 设置结果,并进行传送
line_comment
zh-cn
package care; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.melnykov.fab.sample.R; import com.melnykov.fab.sample.tools.IMApplication; import com.melnykov.fab.sample.tools.crmMyDatabaseHelper; import com.ricky.database.CenterDatabase; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Created by dell on 2015/8/25. */ public class care_add extends Activity implements View.OnTouchListener{ private Button btn01; private EditText et01; private EditText et02; public static final String KEY_USER_ID="KEY_USER_ID"; public static final String KEY_USER_PASSWORD="KEY_USER_PASSWORD"; private List<String> list = new ArrayList<String>(); private ArrayAdapter<String> adapter; private List<String> list2 = new ArrayList<String>(); private ArrayAdapter<String> adapter2; private Spinner spinner_type; //private I TextView queding,text_care_time,text_care_time2; EditText care_note; // ImageView care_choose_time,care_choose_time2; RelativeLayout back; private String type="生日关爱",time=" ",time2,note="",isokflag=""; String userid; String care_id; String User_id; public crmMyDatabaseHelper dbHelper; String fff; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.care_dialog); CenterDatabase centerDatabase = new CenterDatabase(this, null); userid = centerDatabase.getUID(); centerDatabase.close(); User_id = IMApplication.getUserid(this); dbHelper = new crmMyDatabaseHelper(this, "customer.db3", 1); spinner_type=(Spinner)findViewById(R.id.spinner_type); //spinner_remind=(Spinner)findViewById(R.id.spinner_remind); text_care_time=(TextView)findViewById(R.id.care_time); text_care_time2=(TextView)findViewById(R.id.care_time2); care_note=(EditText)findViewById(R.id.care_note); back=(RelativeLayout)findViewById(R.id.ImageButton_back); queding=(TextView)findViewById(R.id.care_submit); text_care_time.setFocusable(true);text_care_time.setClickable(true); text_care_time2.setFocusable(true);text_care_time2.setClickable(true); text_care_time.setOnTouchListener(this);text_care_time2.setOnTouchListener(this); /* care_choose_time=(ImageView)findViewById(R.id.care_choose_time); care_choose_time2=(ImageView)findViewById(R.id.care_choose_time2);*/ queding.setFocusable(true);queding.setClickable(true); /* care_choose_time.setFocusable(true);care_choose_time.setClickable(true); care_choose_time.setOnTouchListener(this); care_choose_time2.setFocusable(true);care_choose_time2.setClickable(true); care_choose_time2.setOnTouchListener(this);*/ back.setFocusable(true);back.setClickable(true); back.setOnTouchListener(this); queding.setOnTouchListener(this); if(getIntent().getAction()=="edite"){ queding.setText("修改"); care_id= getIntent().getExtras().getString("_id"); // Toast.makeText(care_add.this, "修改id:" + care_id, Toast.LENGTH_LONG).show(); Cursor cursor = dbHelper.getReadableDatabase().rawQuery("select * from care_table where _id=" + care_id, null); while (cursor.moveToNext()){ // Toast.makeText(care_add.this, "修改查询出来为:" + cursor.getString(1), Toast.LENGTH_LONG).show(); note=cursor.getString(5); care_note.setText(note); time=cursor.getString(3); text_care_time.setText(time); time2=cursor.getString(4); text_care_time2.setText(time2); } // Toast.makeText(care_add.this, "修改查询出来为:" + cursor.getString(1), Toast.LENGTH_LONG).show(); }else if(getIntent().getAction()=="lianxirenadd"){ } else{ /* Calendar calendar=Calendar.getInstance(); int year=calendar.get(Calendar.HOUR); int minute=calendar.get(Calendar.MINUTE); int second=calendar.get(Calendar.SECOND); Time time=new Time();*/ Date date=new Date(); DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time22=format.format(date); text_care_time.setText(time22); time=time22; } //第一步:添加一个下拉列表项的list,这里添加的项就是下拉列表的菜单项 list.add("生日"); list.add("节日"); list.add("庆祝日"); list.add("其他"); //第二步:为下拉列表定义一个适配器,这里就用到里前面定义的list。 adapter = new ArrayAdapter<String>(this,R.layout.myspinner_item, list); //第三步:为适配器设置下拉列表下拉时的菜单样式。 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); //第四步:将适配器添加到下拉列表上 spinner_type.setAdapter(adapter); //第五步:为下拉列表设置各种事件的响应,这个事响应菜单被选中 spinner_type.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){ public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub type=adapter.getItem(arg2); /* 将mySpinner 显示*/ arg0.setVisibility(View.VISIBLE); } public void onNothingSelected(AdapterView<?> arg0) { // TODO Auto-generated method stub arg0.setVisibility(View.VISIBLE); } }); /*下拉菜单弹出的内容选项触屏事件处理*/ spinner_type.setOnTouchListener(new Spinner.OnTouchListener(){ public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub return false; } }); /*下拉菜单弹出的内容选项焦点改变事件处理*/ spinner_type.setOnFocusChangeListener(new Spinner.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { // TODO Auto-generated method stub } }); } int ii=0; @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { if (v.getId() == R.id.care_time||v.getId() == R.id.care_time2) { // Toast.makeText(care_add.this,"1",Toast.LENGTH_SHORT).show(); if(v.getId() == R.id.care_time) ii=1;else ii=2; AlertDialog.Builder builder = new AlertDialog.Builder(this); View view = View.inflate(this, R.layout.date_time_dialog, null); final DatePicker datePicker = (DatePicker) view.findViewById(R.id.date_picker); final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker); builder.setView(view); Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(System.currentTimeMillis()); datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); timePicker.setIs24HourView(true); timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY)); timePicker.setCurrentMinute(Calendar.MINUTE); builder.setPositiveButton("确 定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { StringBuffer sb = new StringBuffer(); sb.append(String.format("%d-%02d-%02d", datePicker.getYear(), datePicker.getMonth() + 1, datePicker.getDayOfMonth())); sb.append(" "); sb.append(String.format("%02d:%02d", timePicker.getCurrentHour(), timePicker.getCurrentMinute())); if(ii==1) { text_care_time.setText(sb); time = sb.toString(); } else { text_care_time2.setText(sb); time2 = sb.toString(); } dialog.cancel(); } }); Dialog dialog = builder.create(); dialog.show(); } } if(event.getAction()==MotionEvent.ACTION_UP){ if(v.getId()== R.id.ImageButton_back){ new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage("确定退出填写吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { care_add.this.setResult(0); dialog.dismiss(); care_add.this.finish(); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); } else if(v.getId()== R.id.care_submit){ if(type==null||time==null||time2==null) { new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage("请完善信息!") .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).show(); }else if(getIntent().getAction()=="lianxirenadd"){ dbHelper.getWritableDatabase().execSQL("insert into care_table(uid,type,time,time2,note,fname,fsex,fphone,fid)" + " values(?,?,?,?,?,?,?,?,?)", new String[]{User_id,type ,time ,time2 , note, getIntent().getStringExtra("username"),getIntent().getStringExtra("sex"), getIntent().getStringExtra("phone"), getIntent().getStringExtra("lianxirenid")}); care_add.this.finish(); } else{ if (getIntent().getAction()!=null){ fff="确定修改?"; } else{ fff="确定提交?"; } /* new AlertDialog.Builder(care_add.this) .setTitle("提醒") .setMessage(fff) .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {*/ note=care_note.getText().toString().trim(); if (fff.equals("确定提交?")) { Intent mIntent = new Intent(); mIntent.putExtra("type", type); mIntent.putExtra("time", time); mIntent.putExtra("time2",time2); mIntent.putExtra("note",note ); // 设置 <SUF> care_add.this.setResult(1, mIntent); } else { /* dbHelper.getReadableDatabase().rawQuery("update care_table set type="+type+",time="+time+",remind="+remind+",note="+note+" where" + "uid="+userid,null);*/ dbHelper.getWritableDatabase().execSQL("update care_table set type = ?,time = ?,time2 = ?,note = ? where _id=?", new String[]{type, time, time2,note,care_id}); // Toast.makeText(care_add.this,"_id"+care_id,Toast.LENGTH_SHORT).show(); for (int i=0;i<100;i++){ if(aa.remindid[i][0]==care_id){ aa.cancelRemind(aa.remindid[i][1], care_add.this); aa.setRemind(time2,type+" "+time+note,"care_remind",0,2, care_add.this); } } Log.e("更新关爱信息","成功"); startActivity(new Intent().setClass(care_add.this, care_main.class)); } care_add.this.finish(); } } } return false; } }
1
13
1
57160_3
package poor; import java.util.concurrent.*; public class testca { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executor = new ThreadPoolExecutor(3 , 5 , 8 , TimeUnit.SECONDS , new ArrayBlockingQueue<>(5) , Executors.defaultThreadFactory() , new ThreadPoolExecutor.AbortPolicy()); Future<String> future1 = executor.submit(new ca()); Future<String> future2 = executor.submit(new ca()); Future<String> future3 = executor.submit(new ca()); Future<String> future4 = executor.submit(new ca()); Future<String> future5 = executor.submit(new ca()); System.out.println(future1.get()); System.out.println(future2.get()); System.out.println(future3.get()); System.out.println(future4.get()); System.out.println(future5.get()); executor.shutdown(); } } //成为一名中国共产党党员意味着坚定地信仰共产主义理想,对马克思主义理论具有深刻理解和认识,并致力于为人民服务,始终保持对党的忠诚。入党不仅是一种荣誉,更是一份责任和使命,要时刻准备着为实现中国特色社会主义伟大事业和最终实现共产主义理想贡献力量。 // //要成长为一名合格的学生党员,首先,需要在思想上坚定理想信念,深入学习和理解马克思列宁主义、毛泽东思想、邓小平理论、“三个代表”重要思想、科学发展观等党的基本理论,树立正确的世界观、人生观、价值观,做到对马克思主义信仰的虔诚执着和深厚。 // //其次,学生党员应在学习生活中积极进取,将学习视为首要任务,不断提升自身综合素质,包括专业知识技能、思想政治素养以及道德品质修养。在实践中锻炼自己,积极参与社会实践、志愿服务等活动,尤其要在基层一线经受历练,提高解决实际问题的能力和与人民群众的血肉联系。 // //再次,青年党员要具备强烈的历史使命感和社会责任感,积极响应党组织的号召,志存高远,脚踏实地,以实际行动投身于改革发展的各项事业之中,充分发挥先锋模范作用。 // //最后,学生党员还要严格遵守党的纪律和规矩,自觉践行“三严三实”,接受组织的教育和监督,不断进行自我反省、自我革命,永葆共产党人的先进性和纯洁性。同时,要在同学中起到表率作用,团结带领广大同学共同进步,共同成长。
Cthaat/JavaPro
multithreaded/src/poor/testca.java
767
//再次,青年党员要具备强烈的历史使命感和社会责任感,积极响应党组织的号召,志存高远,脚踏实地,以实际行动投身于改革发展的各项事业之中,充分发挥先锋模范作用。
line_comment
zh-cn
package poor; import java.util.concurrent.*; public class testca { public static void main(String[] args) throws ExecutionException, InterruptedException { ExecutorService executor = new ThreadPoolExecutor(3 , 5 , 8 , TimeUnit.SECONDS , new ArrayBlockingQueue<>(5) , Executors.defaultThreadFactory() , new ThreadPoolExecutor.AbortPolicy()); Future<String> future1 = executor.submit(new ca()); Future<String> future2 = executor.submit(new ca()); Future<String> future3 = executor.submit(new ca()); Future<String> future4 = executor.submit(new ca()); Future<String> future5 = executor.submit(new ca()); System.out.println(future1.get()); System.out.println(future2.get()); System.out.println(future3.get()); System.out.println(future4.get()); System.out.println(future5.get()); executor.shutdown(); } } //成为一名中国共产党党员意味着坚定地信仰共产主义理想,对马克思主义理论具有深刻理解和认识,并致力于为人民服务,始终保持对党的忠诚。入党不仅是一种荣誉,更是一份责任和使命,要时刻准备着为实现中国特色社会主义伟大事业和最终实现共产主义理想贡献力量。 // //要成长为一名合格的学生党员,首先,需要在思想上坚定理想信念,深入学习和理解马克思列宁主义、毛泽东思想、邓小平理论、“三个代表”重要思想、科学发展观等党的基本理论,树立正确的世界观、人生观、价值观,做到对马克思主义信仰的虔诚执着和深厚。 // //其次,学生党员应在学习生活中积极进取,将学习视为首要任务,不断提升自身综合素质,包括专业知识技能、思想政治素养以及道德品质修养。在实践中锻炼自己,积极参与社会实践、志愿服务等活动,尤其要在基层一线经受历练,提高解决实际问题的能力和与人民群众的血肉联系。 // //再次 <SUF> // //最后,学生党员还要严格遵守党的纪律和规矩,自觉践行“三严三实”,接受组织的教育和监督,不断进行自我反省、自我革命,永葆共产党人的先进性和纯洁性。同时,要在同学中起到表率作用,团结带领广大同学共同进步,共同成长。
0
79
0
34755_5
package com.cui.rectprogress; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * Created by CZH on 2017/6/15. * RectProgress */ public class RectProgress extends View { private final int VERTICAL = 1; private final int HORIZONTAL = 2; private final int defaultBgColor = 0xFf000000; private final int defaultProgressColor = 0xFFFF4081; private int bgColor = defaultBgColor; private int progressColor = defaultProgressColor; /*圆角弧度*/ private float rectRadius = 20f; /*画背景使用的Rect*/ private RectF bgRect = new RectF(); /*画进度使用的Rect*/ private RectF progressRect = new RectF(); /*背景画笔*/ private Paint bgPaint; /*进度画笔*/ private Paint progressPaint; /*进度方向*/ private int orientation = VERTICAL; private int max = 100; private int progress = 15; private Bitmap bitmap; /*icon显示区域Rect*/ private Rect srcRect; /*icon显示位置Rect*/ private Rect dstRect; private float iconPadding; /*进度百分比*/ private int percent = 0; public RectProgress(Context context) { super(context); init(context, null); } public RectProgress(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs); } public RectProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { //关闭硬件加速,不然setXfermode()可能会不生效 setLayerType(View.LAYER_TYPE_SOFTWARE, null); if (attrs != null) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RectProgress); bgColor = typedArray.getColor(R.styleable.RectProgress_bgColor, defaultBgColor); progressColor = typedArray.getColor(R.styleable.RectProgress_progressColor, defaultProgressColor); progress = typedArray.getInteger(R.styleable.RectProgress_progressValue, progress); max = typedArray.getInteger(R.styleable.RectProgress_progressMax, max); if (max <= 0) throw new RuntimeException("Max 必须大于 0"); orientation = typedArray.getInteger(R.styleable.RectProgress_progressOrientation, VERTICAL); int imgSrc = typedArray.getResourceId(R.styleable.RectProgress_iconSrc, 0); iconPadding = typedArray.getDimensionPixelSize(R.styleable.RectProgress_iconPadding, 10); rectRadius = typedArray.getDimensionPixelSize(R.styleable.RectProgress_rectRadius, 20); if (max < progress) { progress = max; } typedArray.recycle(); if (imgSrc != 0) { bitmap = ((BitmapDrawable) getResources().getDrawable(imgSrc)).getBitmap(); } } bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); bgPaint.setColor(bgColor); progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG); progressPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); progressPaint.setColor(progressColor); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); bgRect.set(getPaddingLeft() , getPaddingTop() , getWidth() - getPaddingRight() , getHeight() - getPaddingBottom()); computeProgressRect(); if (bitmap != null) { srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); int iconSideLength; if (orientation == VERTICAL) { iconSideLength = (int) (bgRect.width() - iconPadding * 2); dstRect = new Rect((int) bgRect.left + (int) iconPadding , (int) (bgRect.bottom - iconSideLength - iconPadding) , (int) bgRect.right - (int) iconPadding , (int) bgRect.bottom - (int) iconPadding); } else { iconSideLength = (int) (bgRect.height() - iconPadding * 2); dstRect = new Rect((int) bgRect.left + (int) iconPadding , (int) (bgRect.bottom - iconPadding - iconSideLength) , (int) (bgRect.left + iconPadding + iconSideLength) , (int) (bgRect.bottom - iconPadding)); } } } @Override protected void onDraw(Canvas canvas) { int canvasWidth = canvas.getWidth(); int canvasHeight = canvas.getHeight(); int layerId = canvas.saveLayer(0, 0, canvasWidth, canvasHeight, null, Canvas.ALL_SAVE_FLAG); { bgPaint.setColor(bgColor); // draw the background of progress canvas.drawRoundRect(bgRect, rectRadius, rectRadius, bgPaint); // draw progress canvas.drawRect(progressRect, progressPaint); bgPaint.setXfermode(null); if (bitmap != null) { //draw icon canvas.drawBitmap(bitmap, srcRect, dstRect, bgPaint); } } canvas.restoreToCount(layerId); // TODO: 弄明白为什么在xml预览中,canvas.restoreToCount // TODO: 会导致后续的canvas对象为空 但canvas.restore方法则不会导致这个问题 // canvas.restore(); // canvas.save(); } @Override public boolean onTouchEvent(MotionEvent event) { //在家进度条内才执行操作 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (bgRect.contains(event.getX(), event.getY())) { //按下时,在进度内才执行操作 handleTouch(event); invalidate(); return true; } break; case MotionEvent.ACTION_MOVE: handleTouch(event); invalidate(); break; } invalidate(); return super.onTouchEvent(event); } private void handleTouch(MotionEvent event) { if (orientation == VERTICAL) { if (event.getY() < bgRect.top) { //触点超出Progress顶部 progressRect.top = bgRect.top; } else if (event.getY() > bgRect.bottom) { //触点超过Progress底部 progressRect.top = bgRect.bottom; } else { progressRect.top = event.getY(); } int tmp = (int) ((progressRect.height() / bgRect.height()) * 100); if (percent != tmp) { percent = tmp; progress = percent * max / 100; if (changedListener != null) changedListener.onProgressChanged(progress, percent); } } else { if (event.getX() > bgRect.right) { //触点超出Progress右端 progressRect.right = bgRect.right; } else if (event.getX() < bgRect.left) { //触点超出Progress左端 progressRect.right = bgRect.left; } else { progressRect.right = event.getX(); } int tmp = (int) ((progressRect.width() / bgRect.width()) * 100); if (percent != tmp) { percent = tmp; progress = percent * max / 100; if (changedListener != null) changedListener.onProgressChanged(progress, percent); } } } private OnProgressChangedListener changedListener; public void setChangedListener(OnProgressChangedListener changedListener) { this.changedListener = changedListener; } public interface OnProgressChangedListener { void onProgressChanged(int currentValue, int percent); } public void setMax(int m) { if (max <= 0) throw new RuntimeException("Max 必须大于 0"); max = m; } public void setProgress(int p) { int oldProgress = progress; progress = p; if (max < progress) { progress = max; } else if (progress < 0) progress = 0; startProgressAnim(oldProgress); } private ValueAnimator valueAnimator; /**/ private void startProgressAnim(int oldProgress) { if (valueAnimator != null && valueAnimator.isRunning()) { valueAnimator.cancel(); } valueAnimator = ValueAnimator.ofInt(oldProgress, progress); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { progress = (int) animation.getAnimatedValue(); computeProgressRect(); invalidate(); } }); valueAnimator.setDuration(1000); valueAnimator.start(); } /** * 计算进度Progress */ private void computeProgressRect() { if (orientation == VERTICAL) { progressRect.set(bgRect.left , bgRect.bottom - progress * bgRect.height() / max , bgRect.right , bgRect.bottom); } else { progressRect.set(bgRect.left , bgRect.top , bgRect.left + progress * bgRect.width() / max , bgRect.bottom); } } }
CuiZhaoHui/IOS11RectProgress
rectprogress/src/main/java/com/cui/rectprogress/RectProgress.java
2,370
/*进度画笔*/
block_comment
zh-cn
package com.cui.rectprogress; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.drawable.BitmapDrawable; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; /** * Created by CZH on 2017/6/15. * RectProgress */ public class RectProgress extends View { private final int VERTICAL = 1; private final int HORIZONTAL = 2; private final int defaultBgColor = 0xFf000000; private final int defaultProgressColor = 0xFFFF4081; private int bgColor = defaultBgColor; private int progressColor = defaultProgressColor; /*圆角弧度*/ private float rectRadius = 20f; /*画背景使用的Rect*/ private RectF bgRect = new RectF(); /*画进度使用的Rect*/ private RectF progressRect = new RectF(); /*背景画笔*/ private Paint bgPaint; /*进度画 <SUF>*/ private Paint progressPaint; /*进度方向*/ private int orientation = VERTICAL; private int max = 100; private int progress = 15; private Bitmap bitmap; /*icon显示区域Rect*/ private Rect srcRect; /*icon显示位置Rect*/ private Rect dstRect; private float iconPadding; /*进度百分比*/ private int percent = 0; public RectProgress(Context context) { super(context); init(context, null); } public RectProgress(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs); } public RectProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } private void init(Context context, AttributeSet attrs) { //关闭硬件加速,不然setXfermode()可能会不生效 setLayerType(View.LAYER_TYPE_SOFTWARE, null); if (attrs != null) { TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RectProgress); bgColor = typedArray.getColor(R.styleable.RectProgress_bgColor, defaultBgColor); progressColor = typedArray.getColor(R.styleable.RectProgress_progressColor, defaultProgressColor); progress = typedArray.getInteger(R.styleable.RectProgress_progressValue, progress); max = typedArray.getInteger(R.styleable.RectProgress_progressMax, max); if (max <= 0) throw new RuntimeException("Max 必须大于 0"); orientation = typedArray.getInteger(R.styleable.RectProgress_progressOrientation, VERTICAL); int imgSrc = typedArray.getResourceId(R.styleable.RectProgress_iconSrc, 0); iconPadding = typedArray.getDimensionPixelSize(R.styleable.RectProgress_iconPadding, 10); rectRadius = typedArray.getDimensionPixelSize(R.styleable.RectProgress_rectRadius, 20); if (max < progress) { progress = max; } typedArray.recycle(); if (imgSrc != 0) { bitmap = ((BitmapDrawable) getResources().getDrawable(imgSrc)).getBitmap(); } } bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG); bgPaint.setColor(bgColor); progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG); progressPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)); progressPaint.setColor(progressColor); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); bgRect.set(getPaddingLeft() , getPaddingTop() , getWidth() - getPaddingRight() , getHeight() - getPaddingBottom()); computeProgressRect(); if (bitmap != null) { srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); int iconSideLength; if (orientation == VERTICAL) { iconSideLength = (int) (bgRect.width() - iconPadding * 2); dstRect = new Rect((int) bgRect.left + (int) iconPadding , (int) (bgRect.bottom - iconSideLength - iconPadding) , (int) bgRect.right - (int) iconPadding , (int) bgRect.bottom - (int) iconPadding); } else { iconSideLength = (int) (bgRect.height() - iconPadding * 2); dstRect = new Rect((int) bgRect.left + (int) iconPadding , (int) (bgRect.bottom - iconPadding - iconSideLength) , (int) (bgRect.left + iconPadding + iconSideLength) , (int) (bgRect.bottom - iconPadding)); } } } @Override protected void onDraw(Canvas canvas) { int canvasWidth = canvas.getWidth(); int canvasHeight = canvas.getHeight(); int layerId = canvas.saveLayer(0, 0, canvasWidth, canvasHeight, null, Canvas.ALL_SAVE_FLAG); { bgPaint.setColor(bgColor); // draw the background of progress canvas.drawRoundRect(bgRect, rectRadius, rectRadius, bgPaint); // draw progress canvas.drawRect(progressRect, progressPaint); bgPaint.setXfermode(null); if (bitmap != null) { //draw icon canvas.drawBitmap(bitmap, srcRect, dstRect, bgPaint); } } canvas.restoreToCount(layerId); // TODO: 弄明白为什么在xml预览中,canvas.restoreToCount // TODO: 会导致后续的canvas对象为空 但canvas.restore方法则不会导致这个问题 // canvas.restore(); // canvas.save(); } @Override public boolean onTouchEvent(MotionEvent event) { //在家进度条内才执行操作 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: if (bgRect.contains(event.getX(), event.getY())) { //按下时,在进度内才执行操作 handleTouch(event); invalidate(); return true; } break; case MotionEvent.ACTION_MOVE: handleTouch(event); invalidate(); break; } invalidate(); return super.onTouchEvent(event); } private void handleTouch(MotionEvent event) { if (orientation == VERTICAL) { if (event.getY() < bgRect.top) { //触点超出Progress顶部 progressRect.top = bgRect.top; } else if (event.getY() > bgRect.bottom) { //触点超过Progress底部 progressRect.top = bgRect.bottom; } else { progressRect.top = event.getY(); } int tmp = (int) ((progressRect.height() / bgRect.height()) * 100); if (percent != tmp) { percent = tmp; progress = percent * max / 100; if (changedListener != null) changedListener.onProgressChanged(progress, percent); } } else { if (event.getX() > bgRect.right) { //触点超出Progress右端 progressRect.right = bgRect.right; } else if (event.getX() < bgRect.left) { //触点超出Progress左端 progressRect.right = bgRect.left; } else { progressRect.right = event.getX(); } int tmp = (int) ((progressRect.width() / bgRect.width()) * 100); if (percent != tmp) { percent = tmp; progress = percent * max / 100; if (changedListener != null) changedListener.onProgressChanged(progress, percent); } } } private OnProgressChangedListener changedListener; public void setChangedListener(OnProgressChangedListener changedListener) { this.changedListener = changedListener; } public interface OnProgressChangedListener { void onProgressChanged(int currentValue, int percent); } public void setMax(int m) { if (max <= 0) throw new RuntimeException("Max 必须大于 0"); max = m; } public void setProgress(int p) { int oldProgress = progress; progress = p; if (max < progress) { progress = max; } else if (progress < 0) progress = 0; startProgressAnim(oldProgress); } private ValueAnimator valueAnimator; /**/ private void startProgressAnim(int oldProgress) { if (valueAnimator != null && valueAnimator.isRunning()) { valueAnimator.cancel(); } valueAnimator = ValueAnimator.ofInt(oldProgress, progress); valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { progress = (int) animation.getAnimatedValue(); computeProgressRect(); invalidate(); } }); valueAnimator.setDuration(1000); valueAnimator.start(); } /** * 计算进度Progress */ private void computeProgressRect() { if (orientation == VERTICAL) { progressRect.set(bgRect.left , bgRect.bottom - progress * bgRect.height() / max , bgRect.right , bgRect.bottom); } else { progressRect.set(bgRect.left , bgRect.top , bgRect.left + progress * bgRect.width() / max , bgRect.bottom); } } }
1
8
1
59813_1
package com.cuiyq.enum_; /** * @author Cuiyq * @version 1.0 * describe: 11.8 * 学习自定义枚举类 */ public class Enumeration01 { public static void main(String[] args) { System.out.println(Season.SPRING); System.out.println(Season.AUTUMN); Season.test(); } } //季节类 class Season { static int x = 3; private String name = null;//季节名称 private String description = null; //季节描述 public static final Season SPRING = new Season("春天", "温暖"); public static final Season WINTER = new Season("冬天", "寒冷"); public static final Season AUTUMN = new Season("秋天", "凉爽"); public static final Season SUMMER = new Season("夏天", "炎热"); private Season(String name, String description) { this.name = name; this.description = description; } public String getName() { return name; } public String getDescription() { return description; } @Override public String toString() { return "Season{" + "name='" + name + '\'' + ", description='" + description + '\'' + '}'; } public static void test() { System.out.println(x); } }
Cuiyq110/learnjava
src/com/cuiyq/enum_/Enumeration01.java
345
//季节类
line_comment
zh-cn
package com.cuiyq.enum_; /** * @author Cuiyq * @version 1.0 * describe: 11.8 * 学习自定义枚举类 */ public class Enumeration01 { public static void main(String[] args) { System.out.println(Season.SPRING); System.out.println(Season.AUTUMN); Season.test(); } } //季节 <SUF> class Season { static int x = 3; private String name = null;//季节名称 private String description = null; //季节描述 public static final Season SPRING = new Season("春天", "温暖"); public static final Season WINTER = new Season("冬天", "寒冷"); public static final Season AUTUMN = new Season("秋天", "凉爽"); public static final Season SUMMER = new Season("夏天", "炎热"); private Season(String name, String description) { this.name = name; this.description = description; } public String getName() { return name; } public String getDescription() { return description; } @Override public String toString() { return "Season{" + "name='" + name + '\'' + ", description='" + description + '\'' + '}'; } public static void test() { System.out.println(x); } }
0
5
0
49287_2
//给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。 // //我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。 //说明: n 的范围为 [1, 10,000]。 import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; public class NotIncreArr { //n-1 public static boolean checkPossibility(int[] nums) { int count = 0; for (int i = 1; i < nums.length; i++) { if (nums[i] < nums[i - 1]) { count++; if (count > 1) { return false; } int privous = i > 1 ? nums[i - 2] : 0; int after = i < nums.length - 1 ? nums[i + 1] : 10000; if (nums[i - 1] > after && nums[i] < privous) { return false; } } } return true; } public static void main(String[] args) { // Scanner in = new Scanner(System.in); // String inputStr = in.nextLine(); // StringTokenizer stringTokenizer = new StringTokenizer(inputStr," ",false); // ArrayList<String> arr = new ArrayList<>(); // while(stringTokenizer.hasMoreElements()){ // arr.add(stringTokenizer.nextToken()); // } // int[] arr = {4,2,3}; System.out.println(checkPossibility(arr)); //checkPossibility(arr); } }
Currycurrycurry/FDSS_Algorithm
java/src/NotIncreArr.java
438
//说明: n 的范围为 [1, 10,000]。
line_comment
zh-cn
//给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。 // //我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。 //说明 <SUF> import java.util.ArrayList; import java.util.Scanner; import java.util.StringTokenizer; public class NotIncreArr { //n-1 public static boolean checkPossibility(int[] nums) { int count = 0; for (int i = 1; i < nums.length; i++) { if (nums[i] < nums[i - 1]) { count++; if (count > 1) { return false; } int privous = i > 1 ? nums[i - 2] : 0; int after = i < nums.length - 1 ? nums[i + 1] : 10000; if (nums[i - 1] > after && nums[i] < privous) { return false; } } } return true; } public static void main(String[] args) { // Scanner in = new Scanner(System.in); // String inputStr = in.nextLine(); // StringTokenizer stringTokenizer = new StringTokenizer(inputStr," ",false); // ArrayList<String> arr = new ArrayList<>(); // while(stringTokenizer.hasMoreElements()){ // arr.add(stringTokenizer.nextToken()); // } // int[] arr = {4,2,3}; System.out.println(checkPossibility(arr)); //checkPossibility(arr); } }
1
26
1
41830_0
package com.example.lukedict; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class ChatActivity extends AppCompatActivity { private List<Msg> msgList = new ArrayList<>(); private EditText inputText; private Button send; private RecyclerView msgRecyclerView; private MsgAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); initMsgs();//初始化消息数据 inputText = (EditText)findViewById(R.id.input_text); send = (Button) findViewById(R.id.send); msgRecyclerView = (RecyclerView)findViewById(R.id.msg_recycler_view); LinearLayoutManager layoutManager = new LinearLayoutManager(this); msgRecyclerView.setLayoutManager(layoutManager); layoutManager.setOrientation(RecyclerView.VERTICAL); adapter = new MsgAdapter(msgList); msgRecyclerView.setAdapter(adapter); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String content = inputText.getText().toString(); if(!"".equals(content)){ Msg msg = new Msg(content,Msg.TYPE_SENT); msgList.add(msg); adapter.notifyItemInserted(msgList.size() - 1); //当有新消息时,刷新RecycleView中的显示 msgRecyclerView.scrollToPosition(msgList.size() - 1); //将RecycleView定位到最后一行 inputText.setText("");//清空输入框中的内容 } } }); showActionbar(); } private void showActionbar() { ActionBar actionBar = this.getSupportActionBar();//定义actionbar上的返回箭头 actionBar.setTitle("客服"); actionBar.setDisplayHomeAsUpEnabled(true); } public boolean onOptionsItemSelected(MenuItem item) {//定义actionbar上的返回箭头 if(item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } public class Msg{ public static final int TYPE_RECEIVED = 0; public static final int TYPE_SENT = 1; private String content; private int type; public Msg(String content, int type){ this.content = content; this.type = type; } public String getContent(){ return content; } public int getType(){ return type; } } private void initMsgs(){ Msg msg1 = new Msg("你好!",Msg.TYPE_RECEIVED); msgList.add(msg1); Msg msg2 = new Msg("欢迎使用Luke English!",Msg.TYPE_RECEIVED); msgList.add(msg2); Msg msg3 = new Msg("我是客服小苏,很高兴为你服务!有事请留言,我会尽快回复",Msg.TYPE_RECEIVED); msgList.add(msg3); } }
Curzsu/LukeDict
app/src/main/java/com/example/lukedict/ChatActivity.java
794
//初始化消息数据
line_comment
zh-cn
package com.example.lukedict; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class ChatActivity extends AppCompatActivity { private List<Msg> msgList = new ArrayList<>(); private EditText inputText; private Button send; private RecyclerView msgRecyclerView; private MsgAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); initMsgs();//初始 <SUF> inputText = (EditText)findViewById(R.id.input_text); send = (Button) findViewById(R.id.send); msgRecyclerView = (RecyclerView)findViewById(R.id.msg_recycler_view); LinearLayoutManager layoutManager = new LinearLayoutManager(this); msgRecyclerView.setLayoutManager(layoutManager); layoutManager.setOrientation(RecyclerView.VERTICAL); adapter = new MsgAdapter(msgList); msgRecyclerView.setAdapter(adapter); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String content = inputText.getText().toString(); if(!"".equals(content)){ Msg msg = new Msg(content,Msg.TYPE_SENT); msgList.add(msg); adapter.notifyItemInserted(msgList.size() - 1); //当有新消息时,刷新RecycleView中的显示 msgRecyclerView.scrollToPosition(msgList.size() - 1); //将RecycleView定位到最后一行 inputText.setText("");//清空输入框中的内容 } } }); showActionbar(); } private void showActionbar() { ActionBar actionBar = this.getSupportActionBar();//定义actionbar上的返回箭头 actionBar.setTitle("客服"); actionBar.setDisplayHomeAsUpEnabled(true); } public boolean onOptionsItemSelected(MenuItem item) {//定义actionbar上的返回箭头 if(item.getItemId() == android.R.id.home) { finish(); return true; } return super.onOptionsItemSelected(item); } public class Msg{ public static final int TYPE_RECEIVED = 0; public static final int TYPE_SENT = 1; private String content; private int type; public Msg(String content, int type){ this.content = content; this.type = type; } public String getContent(){ return content; } public int getType(){ return type; } } private void initMsgs(){ Msg msg1 = new Msg("你好!",Msg.TYPE_RECEIVED); msgList.add(msg1); Msg msg2 = new Msg("欢迎使用Luke English!",Msg.TYPE_RECEIVED); msgList.add(msg2); Msg msg3 = new Msg("我是客服小苏,很高兴为你服务!有事请留言,我会尽快回复",Msg.TYPE_RECEIVED); msgList.add(msg3); } }
1
9
1
18610_1
package top.strelitzia.service; import net.mamoe.mirai.Bot; import net.mamoe.mirai.contact.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import top.angelinaBot.annotation.AngelinaFriend; import top.angelinaBot.annotation.AngelinaGroup; import top.angelinaBot.model.MessageInfo; import top.angelinaBot.model.ReplayInfo; import top.strelitzia.dao.AdminUserMapper; import top.strelitzia.dao.GroupAdminInfoMapper; import top.strelitzia.dao.UserFoundMapper; import top.strelitzia.model.AdminUserInfo; import top.strelitzia.model.UserFoundInfo; import top.strelitzia.util.AdminUtil; import java.util.List; import java.util.Random; import java.util.stream.Collectors; /** * @author Cuthbert * @Date 2022/6/21 22:56 **/ @Service public class TodayWife { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TodayWife.class); @Autowired private UserFoundMapper userFoundMapper; @Autowired private AdminUserMapper adminUserMapper; /*编辑指令用法 * *所有功能都需要在最前面加上bot名今日老婆,且需要有step权限 * 重置:将你的wife以及wife的群号设置为0 * qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号 * 重置+qq号:将指定qq的wife以及wife的群号设置为0 * qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号 * qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号 * */ @AngelinaFriend(keyWords = "老婆") @AngelinaGroup(keyWords = "今日老婆" , description = "从本群中随机挑选一位幸运群友作为你今日的老婆") public ReplayInfo todayWife(MessageInfo messageInfo) { //准备工作 ReplayInfo replayInfo = new ReplayInfo(messageInfo); StringBuilder reply = new StringBuilder("*警告:请勿用此功能刷屏*\n" + messageInfo.getName() + ",\n"); UserFoundInfo userFoundInfo = userFoundMapper.selectUserFoundByQQ(messageInfo.getQq()); if (userFoundInfo == null) { userFoundInfo = new UserFoundInfo(); userFoundInfo.setQq(messageInfo.getQq()); userFoundInfo.setFoundCount(0); userFoundInfo.setTodayCount(0); userFoundInfo.setTodayWife(0L); userFoundInfo.setWifeGroup(0L); } //判断是否为编辑指令 if (messageInfo.getArgs().size() == 2) { String str = messageInfo.getArgs().get(1); if (str.equals("菜单")){ reply = new StringBuilder( "编辑指令用法\n" + " *所有功能都需要在最前面加上bot名今日老婆\n" + " *所有功能仅有群主和管理员,或step权限者才能使用\n" + " 重置:将你的wife以及wife的群号设置为0\n" + " qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号\n" + " 重置+qq号:将指定qq的wife以及wife的群号设置为0\n" + " qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号\n" + " qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号\n" + "eg.稀音今日老婆 重置 11111\n 稀音今日老婆 11111 22222" ); }else { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) { if (str.equals("重置") || str.equals("reset")) { userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), 0L, 0L); reply.append("你的今日老婆已经重置啦"); } else if (str.equals("重置本群")) { userFoundMapper.resetGroupWife(messageInfo.getGroupId()); reply = new StringBuilder("已重置本群"); } else { Long qq = Long.valueOf(str); userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId()); reply = new StringBuilder("设置完成"); } } else { reply = new StringBuilder("您没有权限编辑哦"); } } } else if (messageInfo.getArgs().size() == 3) { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) { String str1 = messageInfo.getArgs().get(1); String str2 = messageInfo.getArgs().get(2); if (str1.equals("重置") || str1.equals("reset")){ Long qq = Long.valueOf(str2); userFoundMapper.updateTodayWifeByQq(qq, 0L, 0L); reply = new StringBuilder("重置完成"); }else { Long qq = Long.valueOf(str1); Long wife = Long.valueOf(str2); userFoundMapper.updateTodayWifeByQq(qq, wife, messageInfo.getGroupId()); reply = new StringBuilder("设置完成"); } } else { reply = new StringBuilder("您没有权限编辑哦"); } } else if (messageInfo.getArgs().size() == 4) { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b) { Long qq = Long.valueOf(messageInfo.getArgs().get(1)); Long wife = Long.valueOf(messageInfo.getArgs().get(2)); Long group = Long.valueOf(messageInfo.getArgs().get(3)); userFoundMapper.updateTodayWifeByQq(qq, wife, group); reply = new StringBuilder("设置完成"); } else { reply = new StringBuilder("您没有权限编辑哦"); } }else { //查询今日是否抽取过老婆 Long today = userFoundInfo.getTodayWife(); Long group = userFoundInfo.getWifeGroup(); if (group.equals(messageInfo.getGroupId()) || group.equals(0L)) { Long qq = null; if (group.equals(0L)) { //今日未抽取 //获取MemberList并通过stream流提取qq,随机抽取一个 ContactList<NormalMember> qqList = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).getMembers(); List<Long> list = qqList.stream().map(Member::getId).collect(Collectors.toList()); list.add(messageInfo.getLoginQq()); Random random = new Random(); int n = random.nextInt(list.size()); qq = list.get(n); reply.append("你今天的老婆是:"); userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId()); } else if (group.equals(messageInfo.getGroupId())) { //在本群抽取过了 qq = userFoundInfo.getTodayWife(); reply.append("你今天已经抽取过老婆啦!" + "你的老婆是:"); } replayInfo.setReplayImg("http://q.qlogo.cn/headimg_dl?dst_uin=" + qq + "&spec=5"); String name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getNameCard(); if (name.isEmpty()) { name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getRemark(); } reply.append(name + "(" + qq + ")"); } else { //在其他群抽取过了 String groupName = Bot.getInstance(messageInfo.getLoginQq()).getGroup(group).getName(); reply.append("你今天已经在别的群(" + groupName + ")抽取过老婆啦"); } } replayInfo.setReplayMessage(reply.toString()); return replayInfo; } }
CuthbertTsao/SceneBot
src/main/java/top/strelitzia/service/TodayWife.java
2,238
/*编辑指令用法 * *所有功能都需要在最前面加上bot名今日老婆,且需要有step权限 * 重置:将你的wife以及wife的群号设置为0 * qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号 * 重置+qq号:将指定qq的wife以及wife的群号设置为0 * qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号 * qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号 * */
block_comment
zh-cn
package top.strelitzia.service; import net.mamoe.mirai.Bot; import net.mamoe.mirai.contact.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import top.angelinaBot.annotation.AngelinaFriend; import top.angelinaBot.annotation.AngelinaGroup; import top.angelinaBot.model.MessageInfo; import top.angelinaBot.model.ReplayInfo; import top.strelitzia.dao.AdminUserMapper; import top.strelitzia.dao.GroupAdminInfoMapper; import top.strelitzia.dao.UserFoundMapper; import top.strelitzia.model.AdminUserInfo; import top.strelitzia.model.UserFoundInfo; import top.strelitzia.util.AdminUtil; import java.util.List; import java.util.Random; import java.util.stream.Collectors; /** * @author Cuthbert * @Date 2022/6/21 22:56 **/ @Service public class TodayWife { private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(TodayWife.class); @Autowired private UserFoundMapper userFoundMapper; @Autowired private AdminUserMapper adminUserMapper; /*编辑指 <SUF>*/ @AngelinaFriend(keyWords = "老婆") @AngelinaGroup(keyWords = "今日老婆" , description = "从本群中随机挑选一位幸运群友作为你今日的老婆") public ReplayInfo todayWife(MessageInfo messageInfo) { //准备工作 ReplayInfo replayInfo = new ReplayInfo(messageInfo); StringBuilder reply = new StringBuilder("*警告:请勿用此功能刷屏*\n" + messageInfo.getName() + ",\n"); UserFoundInfo userFoundInfo = userFoundMapper.selectUserFoundByQQ(messageInfo.getQq()); if (userFoundInfo == null) { userFoundInfo = new UserFoundInfo(); userFoundInfo.setQq(messageInfo.getQq()); userFoundInfo.setFoundCount(0); userFoundInfo.setTodayCount(0); userFoundInfo.setTodayWife(0L); userFoundInfo.setWifeGroup(0L); } //判断是否为编辑指令 if (messageInfo.getArgs().size() == 2) { String str = messageInfo.getArgs().get(1); if (str.equals("菜单")){ reply = new StringBuilder( "编辑指令用法\n" + " *所有功能都需要在最前面加上bot名今日老婆\n" + " *所有功能仅有群主和管理员,或step权限者才能使用\n" + " 重置:将你的wife以及wife的群号设置为0\n" + " qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号\n" + " 重置+qq号:将指定qq的wife以及wife的群号设置为0\n" + " qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号\n" + " qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号\n" + "eg.稀音今日老婆 重置 11111\n 稀音今日老婆 11111 22222" ); }else { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) { if (str.equals("重置") || str.equals("reset")) { userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), 0L, 0L); reply.append("你的今日老婆已经重置啦"); } else if (str.equals("重置本群")) { userFoundMapper.resetGroupWife(messageInfo.getGroupId()); reply = new StringBuilder("已重置本群"); } else { Long qq = Long.valueOf(str); userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId()); reply = new StringBuilder("设置完成"); } } else { reply = new StringBuilder("您没有权限编辑哦"); } } } else if (messageInfo.getArgs().size() == 3) { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) { String str1 = messageInfo.getArgs().get(1); String str2 = messageInfo.getArgs().get(2); if (str1.equals("重置") || str1.equals("reset")){ Long qq = Long.valueOf(str2); userFoundMapper.updateTodayWifeByQq(qq, 0L, 0L); reply = new StringBuilder("重置完成"); }else { Long qq = Long.valueOf(str1); Long wife = Long.valueOf(str2); userFoundMapper.updateTodayWifeByQq(qq, wife, messageInfo.getGroupId()); reply = new StringBuilder("设置完成"); } } else { reply = new StringBuilder("您没有权限编辑哦"); } } else if (messageInfo.getArgs().size() == 4) { List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin(); boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins); if (b) { Long qq = Long.valueOf(messageInfo.getArgs().get(1)); Long wife = Long.valueOf(messageInfo.getArgs().get(2)); Long group = Long.valueOf(messageInfo.getArgs().get(3)); userFoundMapper.updateTodayWifeByQq(qq, wife, group); reply = new StringBuilder("设置完成"); } else { reply = new StringBuilder("您没有权限编辑哦"); } }else { //查询今日是否抽取过老婆 Long today = userFoundInfo.getTodayWife(); Long group = userFoundInfo.getWifeGroup(); if (group.equals(messageInfo.getGroupId()) || group.equals(0L)) { Long qq = null; if (group.equals(0L)) { //今日未抽取 //获取MemberList并通过stream流提取qq,随机抽取一个 ContactList<NormalMember> qqList = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).getMembers(); List<Long> list = qqList.stream().map(Member::getId).collect(Collectors.toList()); list.add(messageInfo.getLoginQq()); Random random = new Random(); int n = random.nextInt(list.size()); qq = list.get(n); reply.append("你今天的老婆是:"); userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId()); } else if (group.equals(messageInfo.getGroupId())) { //在本群抽取过了 qq = userFoundInfo.getTodayWife(); reply.append("你今天已经抽取过老婆啦!" + "你的老婆是:"); } replayInfo.setReplayImg("http://q.qlogo.cn/headimg_dl?dst_uin=" + qq + "&spec=5"); String name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getNameCard(); if (name.isEmpty()) { name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getRemark(); } reply.append(name + "(" + qq + ")"); } else { //在其他群抽取过了 String groupName = Bot.getInstance(messageInfo.getLoginQq()).getGroup(group).getName(); reply.append("你今天已经在别的群(" + groupName + ")抽取过老婆啦"); } } replayInfo.setReplayMessage(reply.toString()); return replayInfo; } }
1
299
1
16450_3
package org.cweili.wray.util; import java.util.Calendar; /** * Wray 常量 * * @author Cweili * @version 2013-4-9 下午4:16:00 * */ public class Constant { /** * 调试状态 */ public static final boolean DEBUG = false; /** * 默认字符集 */ public static final String CHARSET = "UTF-8"; /** * 分页最大值 */ public static final int MAX_PAGE_SIZE = Integer.MAX_VALUE; /** * 客户端缓存时间 */ public static final int CACHE_MAX_AGE = 31536000; /** * 管理面板分页大小 */ public static final int ADMIN_LIST_SIZE = 12; /** * 当前年份 */ public static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); /** * 当前月份 */ public static final int CURRENT_MONTH = Calendar.getInstance().get(Calendar.MONTH) + 1; /** * 验证码 */ public static final String CAPTCHA = "captcha"; /** * 提交成功 */ public static final String SUBMIT_SUCCESS = "success"; /** * 提交失败 */ public static final String SUBMIT_FAILED = ""; /** * 登陆验证时间 */ public static final String AUTHORITY_TIME = "wray_t"; /** * 登陆验证令牌 */ public static final String AUTHORITY_TOKEN = "wray_k"; /** * COOKIE 保存用户名 */ public static final String AUTHORITY_NAME = "wray_n"; /** * 危险 html 标签 */ public static final String[] DANGEROUS_TAGS = new String[] { "applet", "body", "embed", "frame", "script", "frameset", "html", "iframe", "object", "meta", "style", "layer", "link", "ilayer", "form", "input", "textarea", "select", "button" }; /** * 皮肤界面 label 数组 */ public static final String[] LABELS = new String[] { "firstPageLabel", "lastPageLabel", "previousPageLabel", "nextPageLabel", "sumLabel", "pageLabel", "noticeBoardLabel", "recentCommentsLabel", "mostCommentArticlesLabel", "mostViewCountArticlesLabel", "popTagsLabel", "archiveLabel", "linkLabel", "atomLabel", "homeLabel", "commentLabel", "moreLabel", "returnLabel", "tagLabel", "searchLabel", "viewLabel", "commentAuthorLabel", "commentEmailLabel", "commentLinkLabel", "submmitCommentLabel", "requiredErrorLabel", "inputErrorLabel", "maxlengthErrorLabel", "allTagsLabel" }; /** * 皮肤扩展名 */ public static final String SKIN_EXT = ".ftl"; /** * 皮肤路径 */ public static final String SKIN_PATH = "skin/"; /** * Wray 版本 */ public static final String WRAY_VERSION = "0.1.0"; /** * 创建工具 */ public static final String GENERATOR = "WRAY " + WRAY_VERSION; }
Cweili/wray
src/main/java/org/cweili/wray/util/Constant.java
819
/** * 分页最大值 */
block_comment
zh-cn
package org.cweili.wray.util; import java.util.Calendar; /** * Wray 常量 * * @author Cweili * @version 2013-4-9 下午4:16:00 * */ public class Constant { /** * 调试状态 */ public static final boolean DEBUG = false; /** * 默认字符集 */ public static final String CHARSET = "UTF-8"; /** * 分页最 <SUF>*/ public static final int MAX_PAGE_SIZE = Integer.MAX_VALUE; /** * 客户端缓存时间 */ public static final int CACHE_MAX_AGE = 31536000; /** * 管理面板分页大小 */ public static final int ADMIN_LIST_SIZE = 12; /** * 当前年份 */ public static final int CURRENT_YEAR = Calendar.getInstance().get(Calendar.YEAR); /** * 当前月份 */ public static final int CURRENT_MONTH = Calendar.getInstance().get(Calendar.MONTH) + 1; /** * 验证码 */ public static final String CAPTCHA = "captcha"; /** * 提交成功 */ public static final String SUBMIT_SUCCESS = "success"; /** * 提交失败 */ public static final String SUBMIT_FAILED = ""; /** * 登陆验证时间 */ public static final String AUTHORITY_TIME = "wray_t"; /** * 登陆验证令牌 */ public static final String AUTHORITY_TOKEN = "wray_k"; /** * COOKIE 保存用户名 */ public static final String AUTHORITY_NAME = "wray_n"; /** * 危险 html 标签 */ public static final String[] DANGEROUS_TAGS = new String[] { "applet", "body", "embed", "frame", "script", "frameset", "html", "iframe", "object", "meta", "style", "layer", "link", "ilayer", "form", "input", "textarea", "select", "button" }; /** * 皮肤界面 label 数组 */ public static final String[] LABELS = new String[] { "firstPageLabel", "lastPageLabel", "previousPageLabel", "nextPageLabel", "sumLabel", "pageLabel", "noticeBoardLabel", "recentCommentsLabel", "mostCommentArticlesLabel", "mostViewCountArticlesLabel", "popTagsLabel", "archiveLabel", "linkLabel", "atomLabel", "homeLabel", "commentLabel", "moreLabel", "returnLabel", "tagLabel", "searchLabel", "viewLabel", "commentAuthorLabel", "commentEmailLabel", "commentLinkLabel", "submmitCommentLabel", "requiredErrorLabel", "inputErrorLabel", "maxlengthErrorLabel", "allTagsLabel" }; /** * 皮肤扩展名 */ public static final String SKIN_EXT = ".ftl"; /** * 皮肤路径 */ public static final String SKIN_PATH = "skin/"; /** * Wray 版本 */ public static final String WRAY_VERSION = "0.1.0"; /** * 创建工具 */ public static final String GENERATOR = "WRAY " + WRAY_VERSION; }
0
18
0
29284_0
/** * 题目描述 * 给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1,m<=n),每段绳子的长度记为k[1],...,k[m]。请问k[1]x...xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。 * 输入描述: * 输入一个数n,意义见题面。(2 <= n <= 60) * 返回值描述: * 输出答案。 * 示例1 * 输入 * 8 * 返回值 * 18 */ public class Solution { public int cutRope(int target) { if (target<2){ return 0; }if(target==2){ return 1; }if (target==3){ return 2; } int result = 1; for(int i=0;i<target/3-1;i++){ result *=3; } if (target%3==1){ result*=4; }else if(target%3==2){ result*=6; }else { result*=3; } return result; } }
Cweiping/AlgorithmInterview
codingInterviews/CutRope.java
338
/** * 题目描述 * 给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1,m<=n),每段绳子的长度记为k[1],...,k[m]。请问k[1]x...xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。 * 输入描述: * 输入一个数n,意义见题面。(2 <= n <= 60) * 返回值描述: * 输出答案。 * 示例1 * 输入 * 8 * 返回值 * 18 */
block_comment
zh-cn
/** * 题目描 <SUF>*/ public class Solution { public int cutRope(int target) { if (target<2){ return 0; }if(target==2){ return 1; }if (target==3){ return 2; } int result = 1; for(int i=0;i<target/3-1;i++){ result *=3; } if (target%3==1){ result*=4; }else if(target%3==2){ result*=6; }else { result*=3; } return result; } }
1
252
1
22898_6
/** * Copyright (C), 2018-2019, csust * FileName: Conn * Author: Cwolf9 * Date: 2019/06/21 14:54 * Description: * History: * <author> <time> <version> <desc> * Cwolf9 2019/06/21 2018.3 * <p> * 〈可怕的是比你强的人比你还努力〉 * 〈〉 * * @author Cwolf9 * @create 2019/06/21 * @since 1.0.0 */ /** * 〈可怕的是比你强的人比你还努力〉 * 〈〉 * * @author Cwolf9 * @create 2019/06/21 * @since 1.0.0 */ package com.demo.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /* * 数据库连接 lhroot */ public class Conn { public static void main(String[] args) { Connection con; //jdbc驱动 String driver="com.mysql.cj.jdbc.Driver"; //这里我的数据库是bookcity String url="jdbc:mysql://localhost:3306/bookcity?useSSL=false&serverTimezone=UTC"; String user="root"; String password="lhroot"; try { //注册JDBC驱动程序 Class.forName(driver); //建立连接 con = DriverManager.getConnection(url, user, password); if (!con.isClosed()) { System.out.println("数据库连接成功"); } con.close(); } catch (ClassNotFoundException e) { System.out.println("数据库驱动没有安装"); } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } } }
Cwolf9/bookcity
src/main/java/com/demo/util/Conn.java
502
//注册JDBC驱动程序
line_comment
zh-cn
/** * Copyright (C), 2018-2019, csust * FileName: Conn * Author: Cwolf9 * Date: 2019/06/21 14:54 * Description: * History: * <author> <time> <version> <desc> * Cwolf9 2019/06/21 2018.3 * <p> * 〈可怕的是比你强的人比你还努力〉 * 〈〉 * * @author Cwolf9 * @create 2019/06/21 * @since 1.0.0 */ /** * 〈可怕的是比你强的人比你还努力〉 * 〈〉 * * @author Cwolf9 * @create 2019/06/21 * @since 1.0.0 */ package com.demo.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /* * 数据库连接 lhroot */ public class Conn { public static void main(String[] args) { Connection con; //jdbc驱动 String driver="com.mysql.cj.jdbc.Driver"; //这里我的数据库是bookcity String url="jdbc:mysql://localhost:3306/bookcity?useSSL=false&serverTimezone=UTC"; String user="root"; String password="lhroot"; try { //注册 <SUF> Class.forName(driver); //建立连接 con = DriverManager.getConnection(url, user, password); if (!con.isClosed()) { System.out.println("数据库连接成功"); } con.close(); } catch (ClassNotFoundException e) { System.out.println("数据库驱动没有安装"); } catch (SQLException e) { e.printStackTrace(); System.out.println("数据库连接失败"); } } }
1
12
1
37563_1
package com.dao; import com.entity.Video; import com.util.JdbcUtils; import java.sql.ResultSet; import java.sql.SQLException; public class VideoImpl implements Dao<Video>{ @Override public boolean insert(Video video) throws SQLException { String sql = "INSERT INTO Music(videoName,videoURL,fileType,emotion) VALUES (?,?,?,?)"; Object[] params = new Object[]{video.getFileName(),video.getUrl(),video.getFileType(),video.getEmotion()}; return JdbcUtils.update(sql, params); } @Override public boolean delete(String key,String keyword) throws SQLException{ String sql = "DELETE FROM Video WHERE "+key+" ='"+keyword+"'"; return JdbcUtils.update(sql); } /** * * @param fields :需要更新的字段,例如,Object[] fields = new Object[]{musicName,musicURL,fileType,emotion} * @param values :字段对应的值,例如,Object[] values = new Object[]{"你还要我这样",http://...","音乐","开心"} * @param key :关键字段 * @param keyword:关键字段对应的值 * @return * @throws SQLException */ @Override public boolean update(Object[] fields, Object[] values, String key, String keyword) throws SQLException { StringBuilder sb = new StringBuilder(); for (int x = 0; x < fields.length; x++) { if (x < fields.length - 1) sb.append(fields[x]).append("=?,"); else sb.append(fields[x]).append("=?"); } String params = sb.toString(); String sql = "UPDATE Video SET " + params + " WHERE " + key + " = '" + keyword + "'"; return JdbcUtils.update(sql, values); } //求求你了用返回对象重构这些方法吧我求你了 @Override public Video query(String key, String keyword) throws SQLException{ ResultSet rs = null; try { rs = JdbcUtils.query("SELECT * FROM Video WHERE "+key+"='"+keyword+"'"); }catch (NullPointerException e){ e.printStackTrace(); } Video video = new Video(); if (rs.next()) { video.setUrl(rs.getString("videourl")); } video.decodeEmotion(); video.decodeFileName(); video.decodeFileType(); return video; } }
CyberspaceStudio/FinalTest
src/com/dao/VideoImpl.java
551
//求求你了用返回对象重构这些方法吧我求你了
line_comment
zh-cn
package com.dao; import com.entity.Video; import com.util.JdbcUtils; import java.sql.ResultSet; import java.sql.SQLException; public class VideoImpl implements Dao<Video>{ @Override public boolean insert(Video video) throws SQLException { String sql = "INSERT INTO Music(videoName,videoURL,fileType,emotion) VALUES (?,?,?,?)"; Object[] params = new Object[]{video.getFileName(),video.getUrl(),video.getFileType(),video.getEmotion()}; return JdbcUtils.update(sql, params); } @Override public boolean delete(String key,String keyword) throws SQLException{ String sql = "DELETE FROM Video WHERE "+key+" ='"+keyword+"'"; return JdbcUtils.update(sql); } /** * * @param fields :需要更新的字段,例如,Object[] fields = new Object[]{musicName,musicURL,fileType,emotion} * @param values :字段对应的值,例如,Object[] values = new Object[]{"你还要我这样",http://...","音乐","开心"} * @param key :关键字段 * @param keyword:关键字段对应的值 * @return * @throws SQLException */ @Override public boolean update(Object[] fields, Object[] values, String key, String keyword) throws SQLException { StringBuilder sb = new StringBuilder(); for (int x = 0; x < fields.length; x++) { if (x < fields.length - 1) sb.append(fields[x]).append("=?,"); else sb.append(fields[x]).append("=?"); } String params = sb.toString(); String sql = "UPDATE Video SET " + params + " WHERE " + key + " = '" + keyword + "'"; return JdbcUtils.update(sql, values); } //求求 <SUF> @Override public Video query(String key, String keyword) throws SQLException{ ResultSet rs = null; try { rs = JdbcUtils.query("SELECT * FROM Video WHERE "+key+"='"+keyword+"'"); }catch (NullPointerException e){ e.printStackTrace(); } Video video = new Video(); if (rs.next()) { video.setUrl(rs.getString("videourl")); } video.decodeEmotion(); video.decodeFileName(); video.decodeFileType(); return video; } }
0
22
0
12341_3
package com.chad.baserecyclerviewadapterhelper.utils; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; public class Tips { /** * 显示 Toast * @param message 提示信息 */ public static void show(String message) { show(message, Toast.LENGTH_SHORT); } /** * 显示 Toast * @param message 提示信息 * @param duration 显示时间长短 */ public static void show(String message, int duration) { Toast toast = new Toast(AppUtils.INSTANCE.getApp()); toast.setDuration(duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(createTextToastView(message)); toast.show(); } /** * 创建自定义 Toast View * * @param message 文本消息 * @return View */ private static View createTextToastView(String message) { // 画圆角矩形背景 float rc = dp2px(6); RoundRectShape shape = new RoundRectShape(new float[]{rc, rc, rc, rc, rc, rc, rc, rc}, null, null); ShapeDrawable drawable = new ShapeDrawable(shape); drawable.getPaint().setColor(Color.argb(225, 240, 240, 240)); drawable.getPaint().setStyle(Paint.Style.FILL); drawable.getPaint().setAntiAlias(true); drawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG); // 创建View FrameLayout layout = new FrameLayout(AppUtils.INSTANCE.getApp()); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layout.setLayoutParams(layoutParams); layout.setPadding(dp2px(16), dp2px(12), dp2px(16), dp2px(12)); layout.setBackground(drawable); TextView textView = new TextView(AppUtils.INSTANCE.getApp()); textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)); textView.setTextSize(15); textView.setText(message); textView.setLineSpacing(dp2px(4), 1f); textView.setTextColor(Color.BLACK); layout.addView(textView); return layout; } private static int dp2px(float dpValue) { final float scale = AppUtils.INSTANCE.getApp().getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }
CymChad/BaseRecyclerViewAdapterHelper
app/src/main/java/com/chad/baserecyclerviewadapterhelper/utils/Tips.java
680
// 画圆角矩形背景
line_comment
zh-cn
package com.chad.baserecyclerviewadapterhelper.utils; import android.graphics.Color; import android.graphics.Paint; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.RoundRectShape; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; public class Tips { /** * 显示 Toast * @param message 提示信息 */ public static void show(String message) { show(message, Toast.LENGTH_SHORT); } /** * 显示 Toast * @param message 提示信息 * @param duration 显示时间长短 */ public static void show(String message, int duration) { Toast toast = new Toast(AppUtils.INSTANCE.getApp()); toast.setDuration(duration); toast.setGravity(Gravity.CENTER, 0, 0); toast.setView(createTextToastView(message)); toast.show(); } /** * 创建自定义 Toast View * * @param message 文本消息 * @return View */ private static View createTextToastView(String message) { // 画圆 <SUF> float rc = dp2px(6); RoundRectShape shape = new RoundRectShape(new float[]{rc, rc, rc, rc, rc, rc, rc, rc}, null, null); ShapeDrawable drawable = new ShapeDrawable(shape); drawable.getPaint().setColor(Color.argb(225, 240, 240, 240)); drawable.getPaint().setStyle(Paint.Style.FILL); drawable.getPaint().setAntiAlias(true); drawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG); // 创建View FrameLayout layout = new FrameLayout(AppUtils.INSTANCE.getApp()); ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); layout.setLayoutParams(layoutParams); layout.setPadding(dp2px(16), dp2px(12), dp2px(16), dp2px(12)); layout.setBackground(drawable); TextView textView = new TextView(AppUtils.INSTANCE.getApp()); textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)); textView.setTextSize(15); textView.setText(message); textView.setLineSpacing(dp2px(4), 1f); textView.setTextColor(Color.BLACK); layout.addView(textView); return layout; } private static int dp2px(float dpValue) { final float scale = AppUtils.INSTANCE.getApp().getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }
1
10
1
32886_18
/* * Copyright 2022 CyrilFeng * * 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.github.qcalculator.core.permutation; import com.github.qcalculator.core.aware.CalculatorRouter; import com.github.qcalculator.core.discount.Calculator; import cn.qmai.discount.core.model.common.*; import com.github.qcalculator.core.model.common.*; import com.github.qcalculator.core.model.goods.GoodsItem; import com.google.common.collect.Collections2; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.collections4.CollectionUtils; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * 全排列计算引擎 * @author: CyrilFeng * @date: 2022/8 */ @SuppressWarnings("all") public abstract class Permutation<T extends GoodsItem> { /** * 根据注解路由到目标Calculator */ private CalculatorRouter calculatorRouter; /** * 上下文 */ private DiscountContext<T> context; /** * 必须使用的优惠,比如用户手动选择的优惠 */ private final Set<Byte> mustUseSet = Sets.newHashSet(); /** * 缓存,key是calcKey生成的数字,value是保存点 */ private final Map<Integer, CalcState<T>> cache = Maps.newHashMap(); /** * 将calculatorRouter绑定到当前Permutation * @param calculatorRouter 路由器 * @return */ public Permutation<T> build(CalculatorRouter calculatorRouter){ this.calculatorRouter=calculatorRouter; return this; } /** * 1-SUPPORTEDSIZE 之间所有排列组合的记录 */ private final static Map<Integer,Collection<List<Byte>>> PERMUTATIONS = Maps.newHashMap(); /** * 最大支持的共享组长度 */ public final static int SUPPORTEDSIZE = 7; static{ //前置计算 1-SUPPORTEDSIZE 之间所有排列组合 for(byte i=1;i<=SUPPORTEDSIZE;i++){ PERMUTATIONS.put((int)i,Collections2.permutations(IntStream.range(0,i).boxed() .map(x->(byte)x.intValue()).collect(Collectors.toList()))); } } /** * 计算用户选择的优惠组合是否有可行解 * @param context 上下文 * @return */ public boolean findSolution(DiscountContext<T> context){ int size=context.getDiscountWrappers().size(); this.context=context; if(size==0){ return false; } Collection<List<Byte>> list = PERMUTATIONS.get(size); for(List<Byte> a:list){ if(findSolution(context,a)){ return true; } } cache.clear(); mustUseSet.clear(); return false; } /** * 计算最优解 * @param context 上下文 * @return */ public void perm(DiscountContext<T> context){ int size=context.getDiscountWrappers().size(); this.context = context; loadMustUseDiscount(); if(size==0){ return ; } Collection<List<Byte>> list = PERMUTATIONS.get(size); for(List<Byte> a:list) { boolean isBetter = executeCalc(this.context, a); if (isBetter) { //若出现比当前结果更优的结果则替换 updateRecord(this.context.getCalcResult()); } } cache.clear(); mustUseSet.clear(); } private void loadMustUseDiscount(){ for(int i=0;i<context.getDiscountWrappers().size();i++){ if(context.getDiscountWrappers().get(i).isMustUse()){ this.mustUseSet.add((byte)i); } } } /** * 根据byte数组生成唯一数字作为Map的key,避免字符串拼接等低效操作 */ private static Integer calcKey(List<Byte> a){ return a.size()>=3?(a.get(0) << 6)+ (a.get(1) << 3) + a.get(2):0; } /** * 若出现比当前结果更优的结果则替换 * @param result 当前的计算结果 */ private void updateRecord(CalcResult result){ result.setFinalPrice(result.getCurFinalPrice()); System.arraycopy(result.getCurStages(),0,result.getStages(),0,result.getStages().length); } /** * 找到可行解,这种情况list中所有优惠必须被使用 * @param context 上下文 * @param a 当前计算的排列 */ private boolean findSolution(DiscountContext<T> context,List<Byte> a){ Integer k = calcKey(a); boolean canOptimize = enableOptimize(a)&&cache.containsKey(k); initInner(canOptimize,k); for(int i=canOptimize?3:0;i<a.size();i++){ DiscountWrapper wrapper = context.getDiscountWrappers().get(a.get(i)); Calculator<T> calculator = (Calculator<T>)calculatorRouter.getService(wrapper.getType()); //路由目标的计算器实现 if(canOptimize&&checkIfWakeUpJump(context.getDiscountWrappers().get(a.get(2)),wrapper)){ //还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出 break; } if (Objects.nonNull(calculator)) { //执行计算器 if(!calcInner(calculator,wrapper,a,i)){ return false; } CalcStage cs = context.getCalcResult().getCurStages()[i]; if(Objects.isNull(cs)){ //执行当前排列,若存在未使用的优惠则证明当前排列不可行 return false; } //优惠长度为5、6、7 将开启优化,只缓存走到第3个节点的部分 cacheSnapshot(a,i,k); } } return true; } private void cacheSnapshot(List<Byte> a,int i,Integer k){ if(enableOptimize(a)&&i==2&&!cache.containsKey(k)){ cache.put(k,makeSnapshot(context.getGoodsItems())); } } private void initInner(boolean canOptimize,Integer k){ if(canOptimize){ //若可优化则还原之前的保存点 backToSnapshot(k); }else{ //若不可优化则老老实实初始化 initCtx(); } } private boolean calcInner(Calculator<T> calculator,DiscountWrapper wrapper,List<Byte> a,int i){ long price = calculator.calcWarp(context, wrapper, context.getRecords(), a.get(i), i); if (price < 0) { return false; } if(i<a.size()-1) { int order = wrapper.getDiscountConfig().getCalculateGroup(); int nextOrder = context.getDiscountWrappers().get(a.get(i+1)).getDiscountConfig().getCalculateGroup(); if(order>nextOrder){ //优先级不符合则跳出 return false; } } return true; } /** * 根据数组顺序执行计算器 */ public boolean executeCalc(DiscountContext<T> context,List<Byte> a){ Integer k = calcKey(a); boolean canOptimize = enableOptimize(a)&&cache.containsKey(k); initInner(canOptimize,k); for(int i=canOptimize?3:0;i<a.size();i++){ DiscountWrapper wrapper = context.getDiscountWrappers().get(a.get(i)); Calculator<T> calculator = (Calculator<T>) calculatorRouter.getService(wrapper.getType()); //路由目标的计算器实现 if(canOptimize&&checkIfWakeUpJump(context.getDiscountWrappers().get(a.get(2)),wrapper)){ //还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出 break; } if(Objects.nonNull(calculator)){ //执行计算器 if(!calcInner(calculator,wrapper,a,i)){ return false; } //优惠长度为5、6、7 将开启优化,只缓存走到第3个节点的部分 cacheSnapshot(a,i,k); } } long curPrice = context.getCalcResult().getCurPrice(); context.getCalcResult().setCurFinalPrice(curPrice); CalcStage[] stages = context.getCalcResult().getCurStages(); return curPrice<context.getCalcResult().getFinalPrice()&&(CollectionUtils.isEmpty(this.mustUseSet) || isMustUse(stages, this.mustUseSet))|| //相同最优解处理逻辑 curPrice==context.getCalcResult().getFinalPrice()&&(CollectionUtils.isEmpty(this.mustUseSet) || isMustUse(stages, this.mustUseSet))&&sameOptimumCondition(stages); } /** * 还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出 * @param cachedWrap 保存点的最后一个优惠节点 * @param wrapper 当前优惠节点 */ private boolean checkIfWakeUpJump(DiscountWrapper cachedWrap,DiscountWrapper wrapper){ return cachedWrap.getDiscountConfig().getCalculateGroup()>wrapper.getDiscountConfig().getCalculateGroup(); } /** * 全排列计算后判断位置是否匹配 * @param stages 当前stage数组 * @param pos 必须使用的优惠索引 * @return */ private boolean isMustUse(CalcStage[] stages,Set<Byte> pos){ int c=0; for(CalcStage stage:stages){ if(Objects.isNull(stage)){ continue; } if(pos.contains(stage.getIndex())){ c++; } } return c==pos.size(); } /** * 初始化上下文,清理上一排列留下的脏数据 */ private void initCtx(){ context.getCalcResult().setCurPrice(context.getOriginalPrice()); CalcStage[] curArr =context.getCalcResult().getCurStages(); //每次排列计算前初始化curStages为null Arrays.fill(curArr,null); //每次排列计算前reset usedList 中的单品价格,并清空 context.getGoodsItems().forEach(this::resetItems); //清空黑名单 context.getRecords().clear(); //初始化Context resetContext(context); } /** * 构建保存点 * @param goods 商品列表 */ private CalcState<T> makeSnapshot(List<T> goods){ CalcState<T> state = new CalcState<>(); state.setCurPrice(context.getCalcResult().getCurPrice()); state.setCurStages(copyStage(context.getCalcResult().getCurStages())); state.setRecords(copyRecord(context.getRecords())); makeSnapshot(state,context); return state; } /** * 返回保存点 * @param k 缓存的key */ private void backToSnapshot(Integer k){ CalcState<T> state=(CalcState<T>)cache.get(k); context.getCalcResult().setCurPrice(state.getCurPrice()); context.getCalcResult().setCurStages(copyStage(state.getCurStages())); context.setRecords(copyRecord(state.getRecords())); backToSnapshot(state,context); } /** * 复制stages * @param curStages 当前stages */ private CalcStage[] copyStage(CalcStage[] curStages){ CalcStage[] cs=new CalcStage[curStages.length]; System.arraycopy(curStages,0,cs,0,curStages.length); return cs; } /** * clone商品当前状态,转成map便于查找 * @param goods 商品列表 * @return */ protected Map<Long,T> copyGoods(List<T> goods){ Map<Long,T> map=Maps.newHashMap(); for(T good:goods){ try { map.put(good.getCalculateId(),(T)good.clone()); } catch (Exception ignore) { } } return map; } /** * 复制享受过优惠的商品记录,只用到calculateId,因此不对对象进行clone * @param records 享受过优惠的商品记录 */ private Map<Long,T> copyRecord(Map<Long,T> records){ return Maps.newHashMap(records); } /** * 相同最优解的处理逻辑,交给业务来实现 * @param stages 最终的stage数组 * @param curStages 当前的stage数组 * @return */ protected abstract boolean sameOptimumCondition(CalcStage[] curStages); /** * context参数的重置逻辑,交给业务来实现 * @param context 上下文 */ protected abstract void resetContext(DiscountContext<T> context); /** * 开启缓存的条件,如 a.size>4 * @param a 优惠排列 */ protected abstract boolean enableOptimize(List<Byte> a); /** * 商品参数的重置逻辑,交给业务来实现 * @param item 单品 */ protected abstract void resetItems(T item); /** * 业务将状态记录到保存点 * @param state 保存点对象 */ protected abstract void makeSnapshot(CalcState<T> state,DiscountContext<T> context); /** * 业务返回保存点状态 * @param state 保存点对象 */ protected abstract void backToSnapshot(CalcState<T> state,DiscountContext<T> context); }
CyrilFeng/Q-calculator
src/main/java/com/github/qcalculator/core/permutation/Permutation.java
3,394
//执行计算器
line_comment
zh-cn
/* * Copyright 2022 CyrilFeng * * 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.github.qcalculator.core.permutation; import com.github.qcalculator.core.aware.CalculatorRouter; import com.github.qcalculator.core.discount.Calculator; import cn.qmai.discount.core.model.common.*; import com.github.qcalculator.core.model.common.*; import com.github.qcalculator.core.model.goods.GoodsItem; import com.google.common.collect.Collections2; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import org.apache.commons.collections4.CollectionUtils; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * 全排列计算引擎 * @author: CyrilFeng * @date: 2022/8 */ @SuppressWarnings("all") public abstract class Permutation<T extends GoodsItem> { /** * 根据注解路由到目标Calculator */ private CalculatorRouter calculatorRouter; /** * 上下文 */ private DiscountContext<T> context; /** * 必须使用的优惠,比如用户手动选择的优惠 */ private final Set<Byte> mustUseSet = Sets.newHashSet(); /** * 缓存,key是calcKey生成的数字,value是保存点 */ private final Map<Integer, CalcState<T>> cache = Maps.newHashMap(); /** * 将calculatorRouter绑定到当前Permutation * @param calculatorRouter 路由器 * @return */ public Permutation<T> build(CalculatorRouter calculatorRouter){ this.calculatorRouter=calculatorRouter; return this; } /** * 1-SUPPORTEDSIZE 之间所有排列组合的记录 */ private final static Map<Integer,Collection<List<Byte>>> PERMUTATIONS = Maps.newHashMap(); /** * 最大支持的共享组长度 */ public final static int SUPPORTEDSIZE = 7; static{ //前置计算 1-SUPPORTEDSIZE 之间所有排列组合 for(byte i=1;i<=SUPPORTEDSIZE;i++){ PERMUTATIONS.put((int)i,Collections2.permutations(IntStream.range(0,i).boxed() .map(x->(byte)x.intValue()).collect(Collectors.toList()))); } } /** * 计算用户选择的优惠组合是否有可行解 * @param context 上下文 * @return */ public boolean findSolution(DiscountContext<T> context){ int size=context.getDiscountWrappers().size(); this.context=context; if(size==0){ return false; } Collection<List<Byte>> list = PERMUTATIONS.get(size); for(List<Byte> a:list){ if(findSolution(context,a)){ return true; } } cache.clear(); mustUseSet.clear(); return false; } /** * 计算最优解 * @param context 上下文 * @return */ public void perm(DiscountContext<T> context){ int size=context.getDiscountWrappers().size(); this.context = context; loadMustUseDiscount(); if(size==0){ return ; } Collection<List<Byte>> list = PERMUTATIONS.get(size); for(List<Byte> a:list) { boolean isBetter = executeCalc(this.context, a); if (isBetter) { //若出现比当前结果更优的结果则替换 updateRecord(this.context.getCalcResult()); } } cache.clear(); mustUseSet.clear(); } private void loadMustUseDiscount(){ for(int i=0;i<context.getDiscountWrappers().size();i++){ if(context.getDiscountWrappers().get(i).isMustUse()){ this.mustUseSet.add((byte)i); } } } /** * 根据byte数组生成唯一数字作为Map的key,避免字符串拼接等低效操作 */ private static Integer calcKey(List<Byte> a){ return a.size()>=3?(a.get(0) << 6)+ (a.get(1) << 3) + a.get(2):0; } /** * 若出现比当前结果更优的结果则替换 * @param result 当前的计算结果 */ private void updateRecord(CalcResult result){ result.setFinalPrice(result.getCurFinalPrice()); System.arraycopy(result.getCurStages(),0,result.getStages(),0,result.getStages().length); } /** * 找到可行解,这种情况list中所有优惠必须被使用 * @param context 上下文 * @param a 当前计算的排列 */ private boolean findSolution(DiscountContext<T> context,List<Byte> a){ Integer k = calcKey(a); boolean canOptimize = enableOptimize(a)&&cache.containsKey(k); initInner(canOptimize,k); for(int i=canOptimize?3:0;i<a.size();i++){ DiscountWrapper wrapper = context.getDiscountWrappers().get(a.get(i)); Calculator<T> calculator = (Calculator<T>)calculatorRouter.getService(wrapper.getType()); //路由目标的计算器实现 if(canOptimize&&checkIfWakeUpJump(context.getDiscountWrappers().get(a.get(2)),wrapper)){ //还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出 break; } if (Objects.nonNull(calculator)) { //执行 <SUF> if(!calcInner(calculator,wrapper,a,i)){ return false; } CalcStage cs = context.getCalcResult().getCurStages()[i]; if(Objects.isNull(cs)){ //执行当前排列,若存在未使用的优惠则证明当前排列不可行 return false; } //优惠长度为5、6、7 将开启优化,只缓存走到第3个节点的部分 cacheSnapshot(a,i,k); } } return true; } private void cacheSnapshot(List<Byte> a,int i,Integer k){ if(enableOptimize(a)&&i==2&&!cache.containsKey(k)){ cache.put(k,makeSnapshot(context.getGoodsItems())); } } private void initInner(boolean canOptimize,Integer k){ if(canOptimize){ //若可优化则还原之前的保存点 backToSnapshot(k); }else{ //若不可优化则老老实实初始化 initCtx(); } } private boolean calcInner(Calculator<T> calculator,DiscountWrapper wrapper,List<Byte> a,int i){ long price = calculator.calcWarp(context, wrapper, context.getRecords(), a.get(i), i); if (price < 0) { return false; } if(i<a.size()-1) { int order = wrapper.getDiscountConfig().getCalculateGroup(); int nextOrder = context.getDiscountWrappers().get(a.get(i+1)).getDiscountConfig().getCalculateGroup(); if(order>nextOrder){ //优先级不符合则跳出 return false; } } return true; } /** * 根据数组顺序执行计算器 */ public boolean executeCalc(DiscountContext<T> context,List<Byte> a){ Integer k = calcKey(a); boolean canOptimize = enableOptimize(a)&&cache.containsKey(k); initInner(canOptimize,k); for(int i=canOptimize?3:0;i<a.size();i++){ DiscountWrapper wrapper = context.getDiscountWrappers().get(a.get(i)); Calculator<T> calculator = (Calculator<T>) calculatorRouter.getService(wrapper.getType()); //路由目标的计算器实现 if(canOptimize&&checkIfWakeUpJump(context.getDiscountWrappers().get(a.get(2)),wrapper)){ //还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出 break; } if(Objects.nonNull(calculator)){ //执行计算器 if(!calcInner(calculator,wrapper,a,i)){ return false; } //优惠长度为5、6、7 将开启优化,只缓存走到第3个节点的部分 cacheSnapshot(a,i,k); } } long curPrice = context.getCalcResult().getCurPrice(); context.getCalcResult().setCurFinalPrice(curPrice); CalcStage[] stages = context.getCalcResult().getCurStages(); return curPrice<context.getCalcResult().getFinalPrice()&&(CollectionUtils.isEmpty(this.mustUseSet) || isMustUse(stages, this.mustUseSet))|| //相同最优解处理逻辑 curPrice==context.getCalcResult().getFinalPrice()&&(CollectionUtils.isEmpty(this.mustUseSet) || isMustUse(stages, this.mustUseSet))&&sameOptimumCondition(stages); } /** * 还原保存点后,比较保存点的最后一个优惠节点和当前优惠的优先级,如不符合则跳出 * @param cachedWrap 保存点的最后一个优惠节点 * @param wrapper 当前优惠节点 */ private boolean checkIfWakeUpJump(DiscountWrapper cachedWrap,DiscountWrapper wrapper){ return cachedWrap.getDiscountConfig().getCalculateGroup()>wrapper.getDiscountConfig().getCalculateGroup(); } /** * 全排列计算后判断位置是否匹配 * @param stages 当前stage数组 * @param pos 必须使用的优惠索引 * @return */ private boolean isMustUse(CalcStage[] stages,Set<Byte> pos){ int c=0; for(CalcStage stage:stages){ if(Objects.isNull(stage)){ continue; } if(pos.contains(stage.getIndex())){ c++; } } return c==pos.size(); } /** * 初始化上下文,清理上一排列留下的脏数据 */ private void initCtx(){ context.getCalcResult().setCurPrice(context.getOriginalPrice()); CalcStage[] curArr =context.getCalcResult().getCurStages(); //每次排列计算前初始化curStages为null Arrays.fill(curArr,null); //每次排列计算前reset usedList 中的单品价格,并清空 context.getGoodsItems().forEach(this::resetItems); //清空黑名单 context.getRecords().clear(); //初始化Context resetContext(context); } /** * 构建保存点 * @param goods 商品列表 */ private CalcState<T> makeSnapshot(List<T> goods){ CalcState<T> state = new CalcState<>(); state.setCurPrice(context.getCalcResult().getCurPrice()); state.setCurStages(copyStage(context.getCalcResult().getCurStages())); state.setRecords(copyRecord(context.getRecords())); makeSnapshot(state,context); return state; } /** * 返回保存点 * @param k 缓存的key */ private void backToSnapshot(Integer k){ CalcState<T> state=(CalcState<T>)cache.get(k); context.getCalcResult().setCurPrice(state.getCurPrice()); context.getCalcResult().setCurStages(copyStage(state.getCurStages())); context.setRecords(copyRecord(state.getRecords())); backToSnapshot(state,context); } /** * 复制stages * @param curStages 当前stages */ private CalcStage[] copyStage(CalcStage[] curStages){ CalcStage[] cs=new CalcStage[curStages.length]; System.arraycopy(curStages,0,cs,0,curStages.length); return cs; } /** * clone商品当前状态,转成map便于查找 * @param goods 商品列表 * @return */ protected Map<Long,T> copyGoods(List<T> goods){ Map<Long,T> map=Maps.newHashMap(); for(T good:goods){ try { map.put(good.getCalculateId(),(T)good.clone()); } catch (Exception ignore) { } } return map; } /** * 复制享受过优惠的商品记录,只用到calculateId,因此不对对象进行clone * @param records 享受过优惠的商品记录 */ private Map<Long,T> copyRecord(Map<Long,T> records){ return Maps.newHashMap(records); } /** * 相同最优解的处理逻辑,交给业务来实现 * @param stages 最终的stage数组 * @param curStages 当前的stage数组 * @return */ protected abstract boolean sameOptimumCondition(CalcStage[] curStages); /** * context参数的重置逻辑,交给业务来实现 * @param context 上下文 */ protected abstract void resetContext(DiscountContext<T> context); /** * 开启缓存的条件,如 a.size>4 * @param a 优惠排列 */ protected abstract boolean enableOptimize(List<Byte> a); /** * 商品参数的重置逻辑,交给业务来实现 * @param item 单品 */ protected abstract void resetItems(T item); /** * 业务将状态记录到保存点 * @param state 保存点对象 */ protected abstract void makeSnapshot(CalcState<T> state,DiscountContext<T> context); /** * 业务返回保存点状态 * @param state 保存点对象 */ protected abstract void backToSnapshot(CalcState<T> state,DiscountContext<T> context); }
1
7
1
56731_17
package blackjack.enums; /** * 基础的游戏事件,应用于适配器通信和UI层 */ public enum GameEvent { /** * 玩家加入 */ PLAYER_JOIN, /** * 玩家离开游戏 */ PLAYER_LEAVE, /** * 游戏结束,结算 */ GAME_RESULT, /** * 玩家回合开始 */ TURN_START, /** * 玩家回合结束 */ TURN_END, /** * 初始发牌 */ INIT_CARD, /** * 切换到分牌后的新手牌 */ NEW_HAND, /** * 更新上下文玩家列表 */ LIST_CARD, /** * 错误请求 */ ERROR_REQUEST, /** * 庄家结算前的反复摸牌 */ DEALER_DEAL, /** * 仅仅用于前端显示和刷新按钮,适用于所有消息发生之后 */ SHOW_BUTTON, /** * 重置客户端玩家数据,适用于单局游戏结束后 */ PLAYER_RESET, // 操作 /** * 摸牌 */ HIT, /** * 停牌 */ STAND, /** * 分牌 */ SPLIT, /** * 加倍 */ DOUBLE, /** * 保险 */ INSURANCE, /** * 投降 */ SURRENDER, /** * 玩家下注 */ BET, /** * 发送玩家Id */ SENDID, }
D-Sketon/ECNU-OOAD-LAB
Blackjack/src/main/java/blackjack/enums/GameEvent.java
386
/** * 保险 */
block_comment
zh-cn
package blackjack.enums; /** * 基础的游戏事件,应用于适配器通信和UI层 */ public enum GameEvent { /** * 玩家加入 */ PLAYER_JOIN, /** * 玩家离开游戏 */ PLAYER_LEAVE, /** * 游戏结束,结算 */ GAME_RESULT, /** * 玩家回合开始 */ TURN_START, /** * 玩家回合结束 */ TURN_END, /** * 初始发牌 */ INIT_CARD, /** * 切换到分牌后的新手牌 */ NEW_HAND, /** * 更新上下文玩家列表 */ LIST_CARD, /** * 错误请求 */ ERROR_REQUEST, /** * 庄家结算前的反复摸牌 */ DEALER_DEAL, /** * 仅仅用于前端显示和刷新按钮,适用于所有消息发生之后 */ SHOW_BUTTON, /** * 重置客户端玩家数据,适用于单局游戏结束后 */ PLAYER_RESET, // 操作 /** * 摸牌 */ HIT, /** * 停牌 */ STAND, /** * 分牌 */ SPLIT, /** * 加倍 */ DOUBLE, /** * 保险 <SUF>*/ INSURANCE, /** * 投降 */ SURRENDER, /** * 玩家下注 */ BET, /** * 发送玩家Id */ SENDID, }
0
21
0
41236_3
package liuyuboo; import java.util.LinkedList; public class JZ27 { class Node { public int val; public Node left; public Node right; public Node() { } public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right) { val = _val; left = _left; right = _right; } } //目的:转化成排序的循环双向链表 Node head = new Node(); public Node treeToDoublyList(Node root) { //结果形式--和中序遍历类似 //结果链表是一个由中序顺序组织的链表 //所谓链表和bst都是节点靠指针维护的,这个结构是一致的,所以存在就地转换的可能 //这个处理工程,只涉及两个点角色之间的指针调整,其他部分不需要===》需要head cur两个小弟 //cur 代表当前节点,而这个当前节点是中序顺序组织的节点;也就是中序遍历框架中间位置,会自然拿到当前节点 //head 这里就要记录前一个节点 //前一个节点与当前节点的互动,只有三部分:两部分指针调整-前一个后指针指向下一个;后一个前指针指向前一个;记得更新head,来保证始终维持root的前一个节点 Node begin = head; inOrder(root); Node cur = ret; while (cur.left != begin) { cur = cur.left; } return cur; } Node ret = null; public void inOrder(Node root) { if (root == null) { return; } inOrder(root.left); head.right = root; root.left = head; head = head.right; ret = root; inOrder(root.right); } //分化瓦解--三个部分,每个部分都具有和上级同样的问题实质 /* Node lastNode = null; convertNode(root,lastNode); Node headNode = lastNode; while (headNode != null && headNode.left != null) { headNode = headNode.left; } return headNode; } public void convertNode(Node root,Node lastNode) { if (root == null) { return; } Node current = root; if (current.left != null) { convertNode(current.left,lastNode); } current.left = lastNode; if (lastNode != null) { lastNode.right = current; } lastNode = current; if (current.right != null) { convertNode(current.right,lastNode); } }*/ /* if (root.left == null) //小问题:左子树 leftTo(root.left).right = root; //小问题:右子树 rightTo(root.right).left = root; return root; } //返回左子树最大节点 public Node leftTo(Node root) { if(root.left == null && root.right == null) { return root; } leftTo(root.left).right = root; rightTo(root.right).left = root; return findMax(root.right); } public Node findMax(Node root) { if(root.right == null) { return root; } return findMax(root.right); } public Node findMin(Node root) { if (root.left == null) { return root; } return findMin(root.left); } //返回右子树最小节点 public Node rightTo(Node root) { if(root.left == null && root.right == null) { return root; } leftTo(root.left).right = root; rightTo(root.right).left = root; return findMin(root.left); } */ }
DA-MO-WANG/leetcode
java/src/liuyuboo/JZ27.java
918
//所谓链表和bst都是节点靠指针维护的,这个结构是一致的,所以存在就地转换的可能
line_comment
zh-cn
package liuyuboo; import java.util.LinkedList; public class JZ27 { class Node { public int val; public Node left; public Node right; public Node() { } public Node(int _val) { val = _val; } public Node(int _val, Node _left, Node _right) { val = _val; left = _left; right = _right; } } //目的:转化成排序的循环双向链表 Node head = new Node(); public Node treeToDoublyList(Node root) { //结果形式--和中序遍历类似 //结果链表是一个由中序顺序组织的链表 //所谓 <SUF> //这个处理工程,只涉及两个点角色之间的指针调整,其他部分不需要===》需要head cur两个小弟 //cur 代表当前节点,而这个当前节点是中序顺序组织的节点;也就是中序遍历框架中间位置,会自然拿到当前节点 //head 这里就要记录前一个节点 //前一个节点与当前节点的互动,只有三部分:两部分指针调整-前一个后指针指向下一个;后一个前指针指向前一个;记得更新head,来保证始终维持root的前一个节点 Node begin = head; inOrder(root); Node cur = ret; while (cur.left != begin) { cur = cur.left; } return cur; } Node ret = null; public void inOrder(Node root) { if (root == null) { return; } inOrder(root.left); head.right = root; root.left = head; head = head.right; ret = root; inOrder(root.right); } //分化瓦解--三个部分,每个部分都具有和上级同样的问题实质 /* Node lastNode = null; convertNode(root,lastNode); Node headNode = lastNode; while (headNode != null && headNode.left != null) { headNode = headNode.left; } return headNode; } public void convertNode(Node root,Node lastNode) { if (root == null) { return; } Node current = root; if (current.left != null) { convertNode(current.left,lastNode); } current.left = lastNode; if (lastNode != null) { lastNode.right = current; } lastNode = current; if (current.right != null) { convertNode(current.right,lastNode); } }*/ /* if (root.left == null) //小问题:左子树 leftTo(root.left).right = root; //小问题:右子树 rightTo(root.right).left = root; return root; } //返回左子树最大节点 public Node leftTo(Node root) { if(root.left == null && root.right == null) { return root; } leftTo(root.left).right = root; rightTo(root.right).left = root; return findMax(root.right); } public Node findMax(Node root) { if(root.right == null) { return root; } return findMax(root.right); } public Node findMin(Node root) { if (root.left == null) { return root; } return findMin(root.left); } //返回右子树最小节点 public Node rightTo(Node root) { if(root.left == null && root.right == null) { return root; } leftTo(root.left).right = root; rightTo(root.right).left = root; return findMin(root.left); } */ }
1
41
1
24906_4
import java.lang.reflect.Array; public class Knapsack { /** * 一个拥有 20 格的背包 */ private String[] knapsack = new String[20]; Knapsack() { // knapsack[0] = "★★★★ 匣里龙吟"; } public static void main(String[] args) {} /** * 列出背包内容 */ public void getKnapsackList() { System.out.println("当前背包内容:"); for (int i = 0; i < knapsack.length; i++) { if ( knapsack[i] != null ) { System.out.println(knapsack[i]); } } } /** * 将物品装入背包 * @param item 要装入的物品 */ public void addItem(String item) { for (int i = 0; i < knapsack.length; i++) { if ( knapsack[i] == null ) { knapsack[i] = item; System.out.println("你获得了:" + item); break; } } } /** * 丢弃背包中的物品 * @param item 传入要丢弃物品的格子编号 */ public void removeItem(int item) { System.out.println("你丢弃了" + knapsack[item]); knapsack[item] = null; } }
DAHE-JINYI/JavaXiuXian
src/main/java/Knapsack.java
374
/** * 丢弃背包中的物品 * @param item 传入要丢弃物品的格子编号 */
block_comment
zh-cn
import java.lang.reflect.Array; public class Knapsack { /** * 一个拥有 20 格的背包 */ private String[] knapsack = new String[20]; Knapsack() { // knapsack[0] = "★★★★ 匣里龙吟"; } public static void main(String[] args) {} /** * 列出背包内容 */ public void getKnapsackList() { System.out.println("当前背包内容:"); for (int i = 0; i < knapsack.length; i++) { if ( knapsack[i] != null ) { System.out.println(knapsack[i]); } } } /** * 将物品装入背包 * @param item 要装入的物品 */ public void addItem(String item) { for (int i = 0; i < knapsack.length; i++) { if ( knapsack[i] == null ) { knapsack[i] = item; System.out.println("你获得了:" + item); break; } } } /** * 丢弃背 <SUF>*/ public void removeItem(int item) { System.out.println("你丢弃了" + knapsack[item]); knapsack[item] = null; } }
0
59
0
26029_36
package compile; import entity.MultiComment; import entity.SingleComment; import entity.TokenList; import frame.OutText; import frame.ReadText; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * @description 这是词法分析的具体实现 */ @SuppressWarnings("all") public class Lexer extends MainComplier{ //词法分析解释规则,定义字符数组 String[] keyWords = {"if", "else", "while", "read", "write", "int", "double","for"}; //关键字数组 String[] operator = {"+", "-", "*", "/"};//运算符数组 String[] roperator = {">", "<", "==", "<>"};//关系运算符数组 String[] sepretor = {";", "{", "}", "(", ")", "."};//分隔符数组 String RegexToId = "^[a-zA-Z]([a-zA-Z_0-9])*[a-zA-Z0-9]$||[a-zA-Z]";//标识符的正则表达式 String RegexToNumber = "^^-?\\d+$";//整数的正则表达式 String RegexToFloat = "^(-?\\d+)(\\.\\d+)?$";//浮点数的正则表达式 String RegexToArray = "[a-zA-Z]+(\\[[0-9][1-9]*\\])+";//数组变量的正则表达式 //将父类的readText, outText继承过来 public Lexer(ReadText readText, OutText outText) throws HeadlessException { super(readText, outText); } //分析过程,此处为语法分析和词法分析提供已经修饰过的源程序 public List<TokenList> getTokens() { List<TokenList> tokenLists = new ArrayList<>();//用于记录Token的信息 String inputText = readText.getText(); StringTokenizer totalStrt = new StringTokenizer(inputText, "\r\n"); int row = 0;//行号 //获取所有的记号以及记号的信息 while (totalStrt.hasMoreTokens()) { List<String> Tokens = new ArrayList<>();//行记号 StringTokenizer rowOfStrt = new StringTokenizer(totalStrt.nextToken(), " \n\r\t;(){}\"\'+-<>/=*", true); //所有可能的界符,初步得到所有的Token,但需要进一步的合并 while (rowOfStrt.hasMoreTokens()) { Tokens.add(rowOfStrt.nextToken()); } TokenList tokenList = new TokenList(row, Tokens); tokenLists.add(tokenList); row++; } //对于初步得到的记号集合的进一步判断与整合,用于区别注释和*,/;以及=与==,以及<与<> for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组 for (int j = 0; j < tokenList.size() - 1; j++) { if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("/")) { //单行注释记号的识别 tokenList.set(j, "//"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("*")) { //多行注释的识别 tokenList.set(j, "/*"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("*") && tokenList.get(j + 1).equals("/")) { //多行注释的识别 tokenList.set(j, "*/"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("=") && tokenList.get(j + 1).equals("=")) { tokenList.set(j, "=="); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("<") && tokenList.get(j + 1).equals(">")) { tokenList.set(j, "<>"); tokenList.remove(j + 1);//判断不等于符号 } } } //第二次对记号进行判断整合,主要用于去除各种分隔符 for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组 String Pattern = "\\s+|\t|\r\n"; int j = 0; while(j<tokenList.size()) { if(tokenList.get(j).matches(Pattern)) { tokenList.remove(j); } else { j++; } } } //第三次对记号进行去除注释,得到真正的完整的记号 List<MultiComment> multiComments = new ArrayList<>();//存放多行注释的位置信息 List<SingleComment> singleComments = new ArrayList<>();//存放单行注释的位置信息 for (int i = 0; i < tokenLists.size(); i++)//多行注释的记号获取 { List<String> TokenOfrow = tokenLists.get(i).getTokenList(); int rowCount = tokenLists.get(i).getRow();//多行注释行号 for (int j = 0; j < TokenOfrow.size(); j++) { if (TokenOfrow.get(j).equals("//")) { SingleComment singleComment = new SingleComment(rowCount, j); singleComments.add(singleComment);//记录单行注释位置 } if (TokenOfrow.get(j).equals("/*")) { MultiComment multiComment = new MultiComment(rowCount, j, "/*");//j为列号 multiComments.add(multiComment); } else if (TokenOfrow.get(j).equals("*/")) { MultiComment multiComment = new MultiComment(rowCount, j, "*/"); multiComments.add(multiComment); } } } for (int i = 0; i < multiComments.size(); i = i + 2)//去除多行注释中的整行注释 { if ((multiComments.size() % 2) == 0 && i <= multiComments.size() - 2)//判断注释是否未闭合 { if (multiComments.get(i).getComment().equals("/*") && multiComments.get(i + 1).getComment().equals("*/")) { for (int j = multiComments.get(i).getRow() + 1; j < multiComments.get(i + 1).getRow(); j++) { tokenLists.remove(j); } List<String> StartLine = tokenLists.get(multiComments.get(i).getRow()).getTokenList();//注释行起始 List<String> EndLine = tokenLists.get(multiComments.get(i + 1).getRow()).getTokenList();//注释行结束 for (int j = multiComments.get(i).getColumn(); j < StartLine.size(); )//因为随着元素的删除减少,size大小也会发生改变 { StartLine.remove(j); } int position = multiComments.get(i).getColumn();//位置指针 for (int j = 0; j <= position; )//同理,元素的数量的减少导致size改变 { EndLine.remove(j); position--; } } } else { outText.append("无法继续分析"); outText.append("第" + multiComments.get(i).getRow() + "行第" + multiComments.get(i).getColumn() + "处的注释未闭合"); break; } } for (int i = 0; i < singleComments.size(); i++) { List<String> SignleLine = tokenLists.get(singleComments.get(i).getRow()).getTokenList(); for (int j = singleComments.get(i).getColumn(); j < SignleLine.size(); ) { SignleLine.remove(j);//去除单行注释 } } return tokenLists; } //所有的记号处理都做好,此处纯分析记号 public void Analysis() { List<TokenList> tokenLists = getTokens(); for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList(); outText.append("--------------------------------------------------分析第" + (i + 1) + "行--------------------------------------------------" + "\r\n"); for (int j = 0; j < tokenList.size(); j++) { int Count = 0; for (int k = 0; k < keyWords.length; k++) { if (tokenList.get(j).equals(keyWords[k])) { outText.append(tokenList.get(j) + " 是关键字" + "\r\n"); Count++; } } for (int k = 0; k < operator.length; k++) { if (tokenList.get(j).equals(operator[k])) { outText.append(tokenList.get(j) + " 是运算符" + "\r\n"); Count++; } } for (int k = 0; k < roperator.length; k++) { if (tokenList.get(j).equals(roperator[k])) { outText.append(tokenList.get(j) + " 是关系运算符" + "\r\n"); Count++; } } for (int k = 0; k < sepretor.length; k++) { if (tokenList.get(j).equals(sepretor[k])) { outText.append(tokenList.get(j) + " 是分隔符" + "\r\n"); Count++; } } if (tokenList.get(j).matches(RegexToId) && (Count == 0)) { outText.append(tokenList.get(j) + " 是标识符" + "\r\n"); } else if (tokenList.get(j).matches(RegexToNumber)) { outText.append(tokenList.get(j) + " 是整数" + "\r\n"); } else if (tokenList.get(j).matches(RegexToFloat)) { outText.append(tokenList.get(j) + " 是浮点数" + "\r\n"); } else if (tokenList.get(j).matches(RegexToArray)) { outText.append(tokenList.get(j) + " 是数组变量" + "\r\n"); } else if (tokenList.get(j).equals("=")) { outText.append(tokenList.get(j) + " 是等于号" + "\r\n"); } else if (Count == 0) { outText.append(tokenList.get(j) + " 标识符命名错误" + "\r\n"); } } } } }
DAQ121/Lexer-Parser
src/compile/Lexer.java
2,586
//注释行起始
line_comment
zh-cn
package compile; import entity.MultiComment; import entity.SingleComment; import entity.TokenList; import frame.OutText; import frame.ReadText; import java.awt.*; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * @description 这是词法分析的具体实现 */ @SuppressWarnings("all") public class Lexer extends MainComplier{ //词法分析解释规则,定义字符数组 String[] keyWords = {"if", "else", "while", "read", "write", "int", "double","for"}; //关键字数组 String[] operator = {"+", "-", "*", "/"};//运算符数组 String[] roperator = {">", "<", "==", "<>"};//关系运算符数组 String[] sepretor = {";", "{", "}", "(", ")", "."};//分隔符数组 String RegexToId = "^[a-zA-Z]([a-zA-Z_0-9])*[a-zA-Z0-9]$||[a-zA-Z]";//标识符的正则表达式 String RegexToNumber = "^^-?\\d+$";//整数的正则表达式 String RegexToFloat = "^(-?\\d+)(\\.\\d+)?$";//浮点数的正则表达式 String RegexToArray = "[a-zA-Z]+(\\[[0-9][1-9]*\\])+";//数组变量的正则表达式 //将父类的readText, outText继承过来 public Lexer(ReadText readText, OutText outText) throws HeadlessException { super(readText, outText); } //分析过程,此处为语法分析和词法分析提供已经修饰过的源程序 public List<TokenList> getTokens() { List<TokenList> tokenLists = new ArrayList<>();//用于记录Token的信息 String inputText = readText.getText(); StringTokenizer totalStrt = new StringTokenizer(inputText, "\r\n"); int row = 0;//行号 //获取所有的记号以及记号的信息 while (totalStrt.hasMoreTokens()) { List<String> Tokens = new ArrayList<>();//行记号 StringTokenizer rowOfStrt = new StringTokenizer(totalStrt.nextToken(), " \n\r\t;(){}\"\'+-<>/=*", true); //所有可能的界符,初步得到所有的Token,但需要进一步的合并 while (rowOfStrt.hasMoreTokens()) { Tokens.add(rowOfStrt.nextToken()); } TokenList tokenList = new TokenList(row, Tokens); tokenLists.add(tokenList); row++; } //对于初步得到的记号集合的进一步判断与整合,用于区别注释和*,/;以及=与==,以及<与<> for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组 for (int j = 0; j < tokenList.size() - 1; j++) { if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("/")) { //单行注释记号的识别 tokenList.set(j, "//"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("*")) { //多行注释的识别 tokenList.set(j, "/*"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("*") && tokenList.get(j + 1).equals("/")) { //多行注释的识别 tokenList.set(j, "*/"); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("=") && tokenList.get(j + 1).equals("=")) { tokenList.set(j, "=="); tokenList.remove(j + 1); } else if (tokenList.get(j).equals("<") && tokenList.get(j + 1).equals(">")) { tokenList.set(j, "<>"); tokenList.remove(j + 1);//判断不等于符号 } } } //第二次对记号进行判断整合,主要用于去除各种分隔符 for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组 String Pattern = "\\s+|\t|\r\n"; int j = 0; while(j<tokenList.size()) { if(tokenList.get(j).matches(Pattern)) { tokenList.remove(j); } else { j++; } } } //第三次对记号进行去除注释,得到真正的完整的记号 List<MultiComment> multiComments = new ArrayList<>();//存放多行注释的位置信息 List<SingleComment> singleComments = new ArrayList<>();//存放单行注释的位置信息 for (int i = 0; i < tokenLists.size(); i++)//多行注释的记号获取 { List<String> TokenOfrow = tokenLists.get(i).getTokenList(); int rowCount = tokenLists.get(i).getRow();//多行注释行号 for (int j = 0; j < TokenOfrow.size(); j++) { if (TokenOfrow.get(j).equals("//")) { SingleComment singleComment = new SingleComment(rowCount, j); singleComments.add(singleComment);//记录单行注释位置 } if (TokenOfrow.get(j).equals("/*")) { MultiComment multiComment = new MultiComment(rowCount, j, "/*");//j为列号 multiComments.add(multiComment); } else if (TokenOfrow.get(j).equals("*/")) { MultiComment multiComment = new MultiComment(rowCount, j, "*/"); multiComments.add(multiComment); } } } for (int i = 0; i < multiComments.size(); i = i + 2)//去除多行注释中的整行注释 { if ((multiComments.size() % 2) == 0 && i <= multiComments.size() - 2)//判断注释是否未闭合 { if (multiComments.get(i).getComment().equals("/*") && multiComments.get(i + 1).getComment().equals("*/")) { for (int j = multiComments.get(i).getRow() + 1; j < multiComments.get(i + 1).getRow(); j++) { tokenLists.remove(j); } List<String> StartLine = tokenLists.get(multiComments.get(i).getRow()).getTokenList();//注释 <SUF> List<String> EndLine = tokenLists.get(multiComments.get(i + 1).getRow()).getTokenList();//注释行结束 for (int j = multiComments.get(i).getColumn(); j < StartLine.size(); )//因为随着元素的删除减少,size大小也会发生改变 { StartLine.remove(j); } int position = multiComments.get(i).getColumn();//位置指针 for (int j = 0; j <= position; )//同理,元素的数量的减少导致size改变 { EndLine.remove(j); position--; } } } else { outText.append("无法继续分析"); outText.append("第" + multiComments.get(i).getRow() + "行第" + multiComments.get(i).getColumn() + "处的注释未闭合"); break; } } for (int i = 0; i < singleComments.size(); i++) { List<String> SignleLine = tokenLists.get(singleComments.get(i).getRow()).getTokenList(); for (int j = singleComments.get(i).getColumn(); j < SignleLine.size(); ) { SignleLine.remove(j);//去除单行注释 } } return tokenLists; } //所有的记号处理都做好,此处纯分析记号 public void Analysis() { List<TokenList> tokenLists = getTokens(); for (int i = 0; i < tokenLists.size(); i++) { List<String> tokenList = tokenLists.get(i).getTokenList(); outText.append("--------------------------------------------------分析第" + (i + 1) + "行--------------------------------------------------" + "\r\n"); for (int j = 0; j < tokenList.size(); j++) { int Count = 0; for (int k = 0; k < keyWords.length; k++) { if (tokenList.get(j).equals(keyWords[k])) { outText.append(tokenList.get(j) + " 是关键字" + "\r\n"); Count++; } } for (int k = 0; k < operator.length; k++) { if (tokenList.get(j).equals(operator[k])) { outText.append(tokenList.get(j) + " 是运算符" + "\r\n"); Count++; } } for (int k = 0; k < roperator.length; k++) { if (tokenList.get(j).equals(roperator[k])) { outText.append(tokenList.get(j) + " 是关系运算符" + "\r\n"); Count++; } } for (int k = 0; k < sepretor.length; k++) { if (tokenList.get(j).equals(sepretor[k])) { outText.append(tokenList.get(j) + " 是分隔符" + "\r\n"); Count++; } } if (tokenList.get(j).matches(RegexToId) && (Count == 0)) { outText.append(tokenList.get(j) + " 是标识符" + "\r\n"); } else if (tokenList.get(j).matches(RegexToNumber)) { outText.append(tokenList.get(j) + " 是整数" + "\r\n"); } else if (tokenList.get(j).matches(RegexToFloat)) { outText.append(tokenList.get(j) + " 是浮点数" + "\r\n"); } else if (tokenList.get(j).matches(RegexToArray)) { outText.append(tokenList.get(j) + " 是数组变量" + "\r\n"); } else if (tokenList.get(j).equals("=")) { outText.append(tokenList.get(j) + " 是等于号" + "\r\n"); } else if (Count == 0) { outText.append(tokenList.get(j) + " 标识符命名错误" + "\r\n"); } } } } }
1
7
1
41648_11
package tk.dcmmc.sorting.Algorithms; import tk.dcmmc.fundamentals.Algorithms.DoubleLinkedList; /** * 希尔排序法 * Created on 2017/8/5 * @author DCMMC * @since 1.5 */ class ShellSort extends Sort { /** * 在最糟糕的情况下时间复杂度为O(N^1.5), 一个小小的改进就能从InsertionSort的O(N^2)降低到O(N^1.5)(而且是最坏情况) * 平均下的时间复杂度不确定, 取决于increment sequence的选取. * * InsertionSort在每一轮插入的时候需要跟相邻的元素一个一个交换, 这样很消耗资源, 希尔排序作为插入排序的扩展, * 每次比较并交换的间隔不再是1(h=1这一特殊情况下h-sorting就是InsertionSort), 而是大于1的不同的步长. * 定义(Def.): h-sorting * 如果数组中的元素任意间隔h都是有序的, 那就称为h-sorting array, e.g., 1 2 3 4 5 6 7, * 取h为2, 则子序列1 3 5 7和子序列2 4 6分别都是有序的(即有h个互相独立有序的子序列交错组合在一起), 则该数组是h-sorted array * h-sorting即以h为间隔对子序列进行排序, e.g., 对序列 1 5 8 2 3 4 6 7 6 8 9 (共11个元素), 以h = 3进行h-sorting, * 首先这个序列拆分为一下3个子序列: 1 2 6 7和5 3 7 9和8 6 4, 然后依次对这三个子序列进行InsertionSort, 得到1 2 6 7, 3 5 7 9 * 和4 6 8这三个子序列, 合并之后为: 1 3 4 2 5 6 6 7 8 7 9, 这个序列就被称为原序列以h=3的h-sorted array * 一个更好的理解就是把序列放在一个h列的表中, 然后对其形成的二维表的每一列进行InsertionSort: * 1 5 8 2 3 4 6 7 6 8 9以h=3 * 1 5 8 * 2 3 4 * 6 7 6 * 8 9 * 然后依次对第一第二第三第四列进行InsertionSort: * 1 3 4 * 2 5 6 * 6 7 8 * 7 9 * * * ShellSort大体的原理是以一系列值(increment sequence)作为h(又叫步长), 由大的h到小的h来对序列进行h-sorting, 只要该h序列最后的h是1, * 就一定能得出排序好的序列, 比如 5 3 1就是一个h序列, 先以h=5对原序列进行h-sorting, 然后再以h=3进行h-sorting, 最后以h=1进行h-sorting. * 不过从1开始然后不断乘以2这样的序列的效率很低,因为1后面都是偶数,彼此h-sorting排序都是错开的的. * * 而公认的最好步长序列是由Sedgewick(本书作者)提出的(1, 5, 19, 41, 109,...),该序列的项来自9x4^i-9x2^i+1和2^(i+2)x(2^(i+2)-3)+1 * 这两个算式.用这样步长序列的希尔排序比插入排序要快,甚至在小数组中比快速排序和堆排序还快,但是在涉及大量数据时希尔排序还是比快速排序慢。 * * 另一个在大数组中表现优异的步长序列是(斐波那契数列除去0和1将剩余的数以黄金分区比的两倍的幂进行运算得到的数列) * * 不过一般使用的序列是Knuth提出的由递推公式h = h*3 + 1确定的数列(转成通项公式即为1/2(3^k-1)), 这个序列在元素数量比较大的时候, * 相比于SelectionSort和InsertionSort, 性能按照数组大小以2的次幂递增. * 使用Knuth提出序列的比较次数大概为N的若干倍再乘以这个序列的长度(差不多约为N^1.5, 由大量N很大的实验可以估算出) * * 虽然使用最优的序列的时候, 在对小数组排序性能有时候可以超过heapsort和quicksort, 不过在大量数据的时候还是慢于后两个, 不过相比于 * 后两者复杂一些的实现, ShellSort只需少量代码而且对资源的消耗也比较小, 所以适合用在嵌入式系统这些比较重视资源的场景中. */ public static void shellSort(Comparable[] a) { //先确定一个不大于a.length/3的一个数作为h序列的最大项 int h = 1; while (h < a.length/3) h = h*3 + 1;//by Knuth //Ex 2.1.11 //还可以把上述生成的increment sequence 保存在数组中 //DoubleLinkedList<Integer> list = new DoubleLinkedList<>(); //list.addLast(1); //while (h < a.length / 3) // list.addLast(list.get(list.getSize() - 1) * 3 + 1); //int[] incrementSeq = list.toArray(); //以这个h构成一个后项是前项的1/3(约)的序列 while (h >= 1) { //以当前h做h-sorting for (int i = h; i < a.length; i++) { for (int j = i; j >= h && less(a[j], a[j - h]); j -= h) exch(a, j, j - h); } h /= 3; } } }///~
DCMMC/Java-Algorithms-Learning
Algorithms/tk/dcmmc/sorting/Algorithms/ShellSort.java
1,626
//以这个h构成一个后项是前项的1/3(约)的序列
line_comment
zh-cn
package tk.dcmmc.sorting.Algorithms; import tk.dcmmc.fundamentals.Algorithms.DoubleLinkedList; /** * 希尔排序法 * Created on 2017/8/5 * @author DCMMC * @since 1.5 */ class ShellSort extends Sort { /** * 在最糟糕的情况下时间复杂度为O(N^1.5), 一个小小的改进就能从InsertionSort的O(N^2)降低到O(N^1.5)(而且是最坏情况) * 平均下的时间复杂度不确定, 取决于increment sequence的选取. * * InsertionSort在每一轮插入的时候需要跟相邻的元素一个一个交换, 这样很消耗资源, 希尔排序作为插入排序的扩展, * 每次比较并交换的间隔不再是1(h=1这一特殊情况下h-sorting就是InsertionSort), 而是大于1的不同的步长. * 定义(Def.): h-sorting * 如果数组中的元素任意间隔h都是有序的, 那就称为h-sorting array, e.g., 1 2 3 4 5 6 7, * 取h为2, 则子序列1 3 5 7和子序列2 4 6分别都是有序的(即有h个互相独立有序的子序列交错组合在一起), 则该数组是h-sorted array * h-sorting即以h为间隔对子序列进行排序, e.g., 对序列 1 5 8 2 3 4 6 7 6 8 9 (共11个元素), 以h = 3进行h-sorting, * 首先这个序列拆分为一下3个子序列: 1 2 6 7和5 3 7 9和8 6 4, 然后依次对这三个子序列进行InsertionSort, 得到1 2 6 7, 3 5 7 9 * 和4 6 8这三个子序列, 合并之后为: 1 3 4 2 5 6 6 7 8 7 9, 这个序列就被称为原序列以h=3的h-sorted array * 一个更好的理解就是把序列放在一个h列的表中, 然后对其形成的二维表的每一列进行InsertionSort: * 1 5 8 2 3 4 6 7 6 8 9以h=3 * 1 5 8 * 2 3 4 * 6 7 6 * 8 9 * 然后依次对第一第二第三第四列进行InsertionSort: * 1 3 4 * 2 5 6 * 6 7 8 * 7 9 * * * ShellSort大体的原理是以一系列值(increment sequence)作为h(又叫步长), 由大的h到小的h来对序列进行h-sorting, 只要该h序列最后的h是1, * 就一定能得出排序好的序列, 比如 5 3 1就是一个h序列, 先以h=5对原序列进行h-sorting, 然后再以h=3进行h-sorting, 最后以h=1进行h-sorting. * 不过从1开始然后不断乘以2这样的序列的效率很低,因为1后面都是偶数,彼此h-sorting排序都是错开的的. * * 而公认的最好步长序列是由Sedgewick(本书作者)提出的(1, 5, 19, 41, 109,...),该序列的项来自9x4^i-9x2^i+1和2^(i+2)x(2^(i+2)-3)+1 * 这两个算式.用这样步长序列的希尔排序比插入排序要快,甚至在小数组中比快速排序和堆排序还快,但是在涉及大量数据时希尔排序还是比快速排序慢。 * * 另一个在大数组中表现优异的步长序列是(斐波那契数列除去0和1将剩余的数以黄金分区比的两倍的幂进行运算得到的数列) * * 不过一般使用的序列是Knuth提出的由递推公式h = h*3 + 1确定的数列(转成通项公式即为1/2(3^k-1)), 这个序列在元素数量比较大的时候, * 相比于SelectionSort和InsertionSort, 性能按照数组大小以2的次幂递增. * 使用Knuth提出序列的比较次数大概为N的若干倍再乘以这个序列的长度(差不多约为N^1.5, 由大量N很大的实验可以估算出) * * 虽然使用最优的序列的时候, 在对小数组排序性能有时候可以超过heapsort和quicksort, 不过在大量数据的时候还是慢于后两个, 不过相比于 * 后两者复杂一些的实现, ShellSort只需少量代码而且对资源的消耗也比较小, 所以适合用在嵌入式系统这些比较重视资源的场景中. */ public static void shellSort(Comparable[] a) { //先确定一个不大于a.length/3的一个数作为h序列的最大项 int h = 1; while (h < a.length/3) h = h*3 + 1;//by Knuth //Ex 2.1.11 //还可以把上述生成的increment sequence 保存在数组中 //DoubleLinkedList<Integer> list = new DoubleLinkedList<>(); //list.addLast(1); //while (h < a.length / 3) // list.addLast(list.get(list.getSize() - 1) * 3 + 1); //int[] incrementSeq = list.toArray(); //以这 <SUF> while (h >= 1) { //以当前h做h-sorting for (int i = h; i < a.length; i++) { for (int j = i; j >= h && less(a[j], a[j - h]); j -= h) exch(a, j, j - h); } h /= 3; } } }///~
1
25
1
53256_12
//请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, //numberOfUnitsPerBoxi] : // // // numberOfBoxesi 是类型 i 的箱子的数量。 // numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。 // // // 整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。 // // 返回卡车可以装载 单元 的 最大 总数。 // // // // 示例 1: // // //输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 //输出:8 //解释:箱子的情况如下: //- 1 个第一类的箱子,里面含 3 个单元。 //- 2 个第二类的箱子,每个里面含 2 个单元。 //- 3 个第三类的箱子,每个里面含 1 个单元。 //可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。 //单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8 // // 示例 2: // // //输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 //输出:91 // // // // // 提示: // // // 1 <= boxTypes.length <= 1000 // 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000 // 1 <= truckSize <= 10⁶ // // // Related Topics 贪心 数组 排序 👍 78 👎 0 import java.util.Arrays; import java.util.Comparator; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int maximumUnits(int[][] boxTypes, int truckSize) { int len = boxTypes.length; Integer[][] arr = new Integer[len][2]; for (int i = 0; i < len; i++) { arr[i][0] = boxTypes[i][0]; arr[i][1] = boxTypes[i][1]; } Arrays.sort(arr, new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { return -o1[1] + o2[1]; } }); int sum = 0; int i = 0; while (truckSize > 0 && i < len) { if (truckSize - arr[i][0] >= 0) { truckSize -= arr[i][0]; sum += arr[i][0] * arr[i][1]; } else { sum += truckSize * arr[i][1]; truckSize = 0; } i++; } return sum; } } //leetcode submit region end(Prohibit modification and deletion)
DEAiFISH/LeetCode
editor/cn/[1710]卡车上的最大单元数.java
781
//- 3 个第三类的箱子,每个里面含 1 个单元。
line_comment
zh-cn
//请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi, //numberOfUnitsPerBoxi] : // // // numberOfBoxesi 是类型 i 的箱子的数量。 // numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。 // // // 整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。 // // 返回卡车可以装载 单元 的 最大 总数。 // // // // 示例 1: // // //输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4 //输出:8 //解释:箱子的情况如下: //- 1 个第一类的箱子,里面含 3 个单元。 //- 2 个第二类的箱子,每个里面含 2 个单元。 //- <SUF> //可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。 //单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8 // // 示例 2: // // //输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10 //输出:91 // // // // // 提示: // // // 1 <= boxTypes.length <= 1000 // 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000 // 1 <= truckSize <= 10⁶ // // // Related Topics 贪心 数组 排序 👍 78 👎 0 import java.util.Arrays; import java.util.Comparator; //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int maximumUnits(int[][] boxTypes, int truckSize) { int len = boxTypes.length; Integer[][] arr = new Integer[len][2]; for (int i = 0; i < len; i++) { arr[i][0] = boxTypes[i][0]; arr[i][1] = boxTypes[i][1]; } Arrays.sort(arr, new Comparator<Integer[]>() { @Override public int compare(Integer[] o1, Integer[] o2) { return -o1[1] + o2[1]; } }); int sum = 0; int i = 0; while (truckSize > 0 && i < len) { if (truckSize - arr[i][0] >= 0) { truckSize -= arr[i][0]; sum += arr[i][0] * arr[i][1]; } else { sum += truckSize * arr[i][1]; truckSize = 0; } i++; } return sum; } } //leetcode submit region end(Prohibit modification and deletion)
1
26
1
58548_7
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GoListener extends MouseAdapter implements ActionListener, GoData{ JRadioButton[] modelForm; String gameModel = "pvp";// 人机 人人 int chessFlag;// 0 不能下棋 1 黑棋 2 白棋 Graphics g; @Override public void actionPerformed(ActionEvent e){ if(modelForm[0].isSelected ()){ gameModel = "pve"; } else if(modelForm[1].isSelected ()){ gameModel = "pvp"; } String btnStr = e.getActionCommand (); JButton btn = (JButton) e.getSource (); if(btnStr.equals ("开始游戏")){ btn.setText ("结束对局"); chessFlag = 1; } else if(btnStr.equals ("悔棋")){ // 悔棋 } else if(btnStr.equals ("退出")){ System.exit (0); } else if(btnStr.equals ("结束对局")){ btn.setText ("开始游戏"); chessFlag = 0; } } @Override public void mousePressed(MouseEvent e){ int x = e.getX (); int y = e.getY (); if(chessFlag == 0){ JOptionPane.showConfirmDialog (null, "请先开始游戏", "提示", JOptionPane.DEFAULT_OPTION); return; } // System.out.println("x:" + x + " y:" + y); // 求行列值 int r = (y - Y + SIZE / 2) / SIZE; // 行 int c = (x - X + SIZE / 2) / SIZE; // 列 // System.out.println (r + " " + c); if(x < 25 || y < 25 || r < 0 || r >= ROWS || c < 0 || c >= COLS){ JOptionPane.showMessageDialog (null, "请下在棋盘内", "提示", JOptionPane.DEFAULT_OPTION); return; } if(chessArr[r][c]!=0){ JOptionPane.showMessageDialog (null, "此处已有棋子", "提示", JOptionPane.DEFAULT_OPTION); return; } if(gameModel.equals ("pvp")){ // 存储棋子 chessArr[r][c] = chessFlag; boolean ifwin = ChessJudge.checkWin(r, c, chessFlag); System.out.println("ifwin:" + ifwin); if(chessFlag == 1){ g.setColor (Color.BLACK); chessFlag = 2; } else{ g.setColor (Color.WHITE); chessFlag = 1; } // 还原坐标 int chessX = X + c * SIZE - SIZE / 2; int chessY = Y + r * SIZE - SIZE / 2; g.fillOval (chessX, chessY, SIZE, SIZE); // 判断输赢 } else{ } } }
DHUAVY/AIGo
GoListener.java
713
// 判断输赢
line_comment
zh-cn
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GoListener extends MouseAdapter implements ActionListener, GoData{ JRadioButton[] modelForm; String gameModel = "pvp";// 人机 人人 int chessFlag;// 0 不能下棋 1 黑棋 2 白棋 Graphics g; @Override public void actionPerformed(ActionEvent e){ if(modelForm[0].isSelected ()){ gameModel = "pve"; } else if(modelForm[1].isSelected ()){ gameModel = "pvp"; } String btnStr = e.getActionCommand (); JButton btn = (JButton) e.getSource (); if(btnStr.equals ("开始游戏")){ btn.setText ("结束对局"); chessFlag = 1; } else if(btnStr.equals ("悔棋")){ // 悔棋 } else if(btnStr.equals ("退出")){ System.exit (0); } else if(btnStr.equals ("结束对局")){ btn.setText ("开始游戏"); chessFlag = 0; } } @Override public void mousePressed(MouseEvent e){ int x = e.getX (); int y = e.getY (); if(chessFlag == 0){ JOptionPane.showConfirmDialog (null, "请先开始游戏", "提示", JOptionPane.DEFAULT_OPTION); return; } // System.out.println("x:" + x + " y:" + y); // 求行列值 int r = (y - Y + SIZE / 2) / SIZE; // 行 int c = (x - X + SIZE / 2) / SIZE; // 列 // System.out.println (r + " " + c); if(x < 25 || y < 25 || r < 0 || r >= ROWS || c < 0 || c >= COLS){ JOptionPane.showMessageDialog (null, "请下在棋盘内", "提示", JOptionPane.DEFAULT_OPTION); return; } if(chessArr[r][c]!=0){ JOptionPane.showMessageDialog (null, "此处已有棋子", "提示", JOptionPane.DEFAULT_OPTION); return; } if(gameModel.equals ("pvp")){ // 存储棋子 chessArr[r][c] = chessFlag; boolean ifwin = ChessJudge.checkWin(r, c, chessFlag); System.out.println("ifwin:" + ifwin); if(chessFlag == 1){ g.setColor (Color.BLACK); chessFlag = 2; } else{ g.setColor (Color.WHITE); chessFlag = 1; } // 还原坐标 int chessX = X + c * SIZE - SIZE / 2; int chessY = Y + r * SIZE - SIZE / 2; g.fillOval (chessX, chessY, SIZE, SIZE); // 判断 <SUF> } else{ } } }
1
7
1
17596_3
package code.DrawPad.src; import javax.swing.*; import java.awt.*; public class ImagePro extends JFrame{ ImageListen imageListen = new ImageListen (); public ImagePro(){ JFrame jf = new JFrame (); jf.setTitle ("图片处理"); jf.setSize (1000, 900); jf.setDefaultCloseOperation (EXIT_ON_CLOSE); jf.setVisible (true); ShowPanel showPanel = new ShowPanel ();// 显示图片的面板 // 初始化图层 showPanel.setBuffImgList (imageListen.buffImgList); imageListen.setShowPanel (showPanel); showPanel.addMouseListener (imageListen);//鼠标监听 showPanel.addMouseMotionListener (imageListen);// 鼠标移动监听 JPanel imgPanel = new JPanel ();// 图片选择的面板 ControlPanel controlPanel = new ControlPanel (imageListen);// 滤镜操作面板 jf.add (showPanel, BorderLayout.CENTER); jf.add (controlPanel, BorderLayout.SOUTH); JMenuBar jmb = new JMenuBar ();// 菜单栏 JMenu jm = new JMenu ("文件");// 菜单 JMenuItem jmiOpen = new JMenuItem ("打开");// 菜单项 JMenuItem jmiSave = new JMenuItem ("保存");// 菜单项 jmiOpen.addActionListener (imageListen); jmiSave.addActionListener (imageListen); jmiOpen.setActionCommand ("FileOP"); jmiSave.setActionCommand ("FileOP"); jm.add (jmiOpen); jm.add (jmiSave); jmb.add (jm); jf.setJMenuBar (jmb); jf.setVisible (true); } public static void main(String[] args){ new ImagePro (); } }
DHUAVY/DrawPad
src/ImagePro.java
421
// 鼠标移动监听
line_comment
zh-cn
package code.DrawPad.src; import javax.swing.*; import java.awt.*; public class ImagePro extends JFrame{ ImageListen imageListen = new ImageListen (); public ImagePro(){ JFrame jf = new JFrame (); jf.setTitle ("图片处理"); jf.setSize (1000, 900); jf.setDefaultCloseOperation (EXIT_ON_CLOSE); jf.setVisible (true); ShowPanel showPanel = new ShowPanel ();// 显示图片的面板 // 初始化图层 showPanel.setBuffImgList (imageListen.buffImgList); imageListen.setShowPanel (showPanel); showPanel.addMouseListener (imageListen);//鼠标监听 showPanel.addMouseMotionListener (imageListen);// 鼠标 <SUF> JPanel imgPanel = new JPanel ();// 图片选择的面板 ControlPanel controlPanel = new ControlPanel (imageListen);// 滤镜操作面板 jf.add (showPanel, BorderLayout.CENTER); jf.add (controlPanel, BorderLayout.SOUTH); JMenuBar jmb = new JMenuBar ();// 菜单栏 JMenu jm = new JMenu ("文件");// 菜单 JMenuItem jmiOpen = new JMenuItem ("打开");// 菜单项 JMenuItem jmiSave = new JMenuItem ("保存");// 菜单项 jmiOpen.addActionListener (imageListen); jmiSave.addActionListener (imageListen); jmiOpen.setActionCommand ("FileOP"); jmiSave.setActionCommand ("FileOP"); jm.add (jmiOpen); jm.add (jmiSave); jmb.add (jm); jf.setJMenuBar (jmb); jf.setVisible (true); } public static void main(String[] args){ new ImagePro (); } }
1
9
1
16669_54
package com.cheng.improve151suggest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ListView; import java.util.Arrays; import java.util.Date; import java.util.Random; import com.cheng.highqualitycodestudy.R; import com.cheng.improve151suggest.adapter.I151SuggestListAdapter; import com.cheng.improve151suggest.model.Client; /** 第1章 java开发中通用的方法和准则/1 建议1: 不要在常量和变量中出现易混淆的字母/2 建议2: 莫让常量蜕变成变量/2 建议3: 三元操作符的类型务必一致/3 建议4: 避免带有变长参数的方法重载/4 建议5: 别让null值和空值威胁到变长方法/6 建议6: 覆写变长方法也循规蹈矩/7 建议7: 警惕自增的陷阱/8 建议8: 不要让旧语法困扰你/10 建议9: 少用静态导入/11 建议10: 不要在本类中覆盖静态导入的变量和方法/13 建议11: 养成良好习惯,显式声明uid/14 建议12: 避免用序列化类在构造函数中为不变量赋值/17 建议13: 避免为final变量复杂赋值/19 建议14: 使用序列化类的私有方法巧妙解决部分属性持久化问题/20 建议15: break万万不可忘/23 建议16: 易变业务使用脚本语言编写/25 建议17: 慎用动态编译/27 建议18: 避免instanceof非预期结果/29 建议19: 断言绝对不是鸡肋/31 建议20: 不要只替换一个类/33 */ public class I151SChapter01Activity extends AppCompatActivity { private static final String TAG = "I151SChapter01Activity"; private ListView mChapterLV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_i151suggestchapter); initView(); initData(); } private void initView() { this.mChapterLV = (ListView) findViewById(R.id.isi_chapter_lv); } private void initData() { String[] suggests = getResources().getStringArray(R.array.i151schapter1); I151SuggestListAdapter adapter = new I151SuggestListAdapter(this, Arrays.asList(suggests)); mChapterLV.setAdapter(adapter); } /** * 建议1: 不要在常量和变量中出现易混淆的字母 */ private void suggest1() { long i = 1l; Log.e(TAG, "i的两倍是:" + (i+i)); //2 // 查看输出结果:i的两倍是:2(不是22) /** * 注意 * 字母“l”作为长整型标志时务必大写 * 字母“O”与数字混合使用的时候请添加注释 */ } /** * 建议2: 莫让常量蜕变成变量 */ private void suggest2() { Log.e(TAG, "常量会变哦:" + Const.RAND_CONST); /** * 注意 * 务必让常量的值在运行期保持不变 */ } /*接口常量*/ interface Const { // 这还是常量吗? static final int RAND_CONST = new Random().nextInt(); } /** * 建议3: 三元操作符的类型务必一致 */ private void suggest3() { int i = 80; String s = String.valueOf(i<100?90:100); String s1 = String.valueOf(i<100?90:100.0); Log.e(TAG, "两者是否相等" + s.equals(s1)); // false // 这里涉及三元操作符类型的转换规则: /* 若两个操作数不可转换,则不做转换,返回值为Object类型 若两个操作数是明确类型的表达式(比如变量),则按照正常的二进制数字来转换, int类型转换为long,long转化为float 若两个操作数中有一个数字S,另一个是表达式,且其类型标示为T,那么,若数字 S在T的范围内,则转换为T类型;若S超出了T类型的范围,则T转换为S类型 若两个操作数都是直接量数字,则返回值类型为范围较大者 */ /** * 注意 * 保证三元操作符中的两个操作数类型一致,可减少可能错误的发生 */ } /** * 建议4: 避免带有变长参数的方法重载 */ private void suggest4() { Client client = new Client(); // 499 元的货物,打75折 client.calPrice(49900, 75); // 调用 calPrice(int price,int discount) /** * 注意 * 慎重考虑变长参数的方法重载 */ } /** * 建议5: 别让null值和空值威胁到变长方法 */ private void suggest5() { Client client = new Client(); client.methodA("China", 0); client.methodA("China", "People"); // client.methodA("China"); // client.methodA("China", null); // 上面这两处编译通不过,提示是相同的:方法模糊不清,编译器不知道调用哪一个方法, // 但这两次代码反映的代码味道可是不同的 // 对于methodA("China")方法,根据实参"China"(Stirng类型), // 两个方法都符合形参格式,编译器不知道该调用哪个方法,于是报错 // 这是Client类的设计者违反了KISS原则(Keep It Simple, Stupid,即懒人原则), // 按照此规则设计的方法应该很容易调用 // 对于client.methodA("China", null)方法,直接量null是没有类型的,虽然两个methodA // 方法都符合调用请求,但不知道调用哪一个,于是报错了 // 该方法除了不符合上面的懒人原则外,这里还有一个非常不好的编码习惯,即调用者隐藏了实参 // 类型,这是非常危险的,不仅仅调用者需要“猜测”该调用哪个方法,而且被调用者也可能产生内 // 部逻辑混乱的情况 // 对于本例来说应该做如下修改: String[] strs = null; client.methodA("China", strs); // 也就是说让编译器知道这个null值是String[]类型的,编译即可通过,也就减少了错误的发生 /** * 注意 * 类的设计应该按照KISS(Keep It Simple, Stupid,即懒人原则) */ } /** * 建议6: 覆写变长方法也循规蹈矩 */ private void suggest6() { // 向上转型 Base base = new Sub(); base.fun(100, 50); // 不转型 Sub sub = new Sub(); // sub.fun(100, 50); // 上面这行编译通不过,问题出在什么地方呢? // @Override注解吗?非也,覆写是正确的,因为父类的calPrice编译成字节码后的形参是一个 // int类型的形参加上一个int数组类型的形参,子类的参数列表也与此相同,那覆写是理所当然 // 了,所以加上@Override注解没有问题。错误提示是上面这句找不到fun(int, int)方法 // 这太奇怪了:子类继承了父类的所有属性和方法,甭管是私有的还是公有的访问权限,同样的 // 参数、同样的方法名,通过父类调用没有任何问题,通过子类调用却编译通不过,为啥?难道 // 是没有继承下来?或者子类缩小了父类方法的前置条件? // 事实上,base对象是把子类对象Sub做了向上转型,形参列表是由父类决定的,由于是变长参数, // 在编译时,“base.fun(100, 50)”中的“50”这个实参会被编译器“猜测”而编译成“{50}”数组, // 再由子类Sub执行。再来看看直接调用子类的情况,这时编译器并不会把“50”做类型转换,因为 // 数组本身也是一个对象,编译器还没有聪明到要在两个没有继承关系的类之间做转换,要知道 // Java是要求严格类型匹配的,类型不匹配编译器自然就会拒绝执行,并给予错误提示。 /** * 覆写必须满足的条件: * 重写方法不能缩小访问权限 * 参数列表必须与被重写方法相同 * 返回类型必须与被重写方法的相同或是其子类 * 重写方法不能抛出新的异常,或者超出父类范围的异常,但是可以抛出更少、更有限的异常,或者不抛出异常 */ /** * 注意 * 覆写的方法参数与父类相同,不仅仅是类型、数量,还包括显示形式 */ } // 基类 class Base{ void fun(int price,int... discounts){ System.out.println("Base……fun"); } } // 子类,覆写父类方法 class Sub extends Base{ @Override void fun(int price,int[] discounts){ System.out.println("Sub……fun"); } } /** * 建议7: 警惕自增的陷阱 */ private void suggest7() { int count = 0; for (int i = 0; i < 10; i++) { count = count++; } Log.e(TAG, "count=" + count); // 0 // 这个程序输出的count等于几?答案等于10?错了,运行结果是count等于0,为什么呢? /* count++ 是一个表达式,是有返回值的,它的返回值就是count自加前的值,Java对自加是这样处理的: 首先把count的值(注意是值,不是引用)拷贝到一个临时变量区,然后对count变量加1,最后返回临时 变量区的值。程序第一次循环时的详细处理步骤如下: 步骤1 JVM把count值(其值是0)拷贝到临时变量区 步骤2 count值加1,这时候count的值是1 步骤3 返回临时变量区的值,注意这个值是0,没有修改过 步骤4 返回值给count,此时count值被重置成0 “count = count++;”这条语句可以按照如下代码来理解: // 先保存初始值 int temp = count; // 做自增操作 count = count + 1; // 返回原始值 return temp; 解决方法很简单,修改为“count++”即可。 该问题在不同的语音环境有不同的实现:C++中“count=count++”与“count++”是等效的,而在PHP中则 保持着与Java相同的处理方式。每种语言对自增的实现方式各不同。 */ /** * 注意 * i++表达式的返回值是i自加之前的值 */ } /** * 建议8: 不要让旧语法困扰你 */ private void suggest8() { // 数据定义及初始化 int fee = 200; // 其他业务处理 saveDefault:save(fee); /* “saveDefault:save(fee)” 此句代码很神奇,编译没有错,运行也很正常。Java中竟然有冒号操作符? 原来是goto语句。Java中抛弃了goto语法,但还是保留了该关键字,只是不进行语义处理而已。Java中 虽然没有了goto关键字,但是扩展了break和continue关键字,它们的后面都可以加上标号做跳转,完全 实现了goto功能,同时也把goto的诟病带了进来,很少看到这样使用。 */ /** * 注意 * Java没有goto * 为了可读性少用break、continue,就算要使用也不能加上标号做跳转 */ } void saveDefault() { } void save(int fee) { } /** * 建议9: 少用静态导入 */ private void sugget9() { /** * 注意 * 对于静态导入,一定要遵循两个规则: * 不使用*(星号)通配符,除非是导入静态常量类(只包含常量的类或接口) * 方法名是具有明确、清晰表象意义的工具类 */ } /** * 建议10: 不要在本类中覆盖静态导入的变量和方法 */ private void suggest10() { /** * 注意 * 编译器有一个“最短路径”原则:如果能够在本类中查找到的变量、常量、方法,就不会到其他包或 * 父类、接口中查找,以确保本类中的属性、方法优先 * 如果要变更一个被静态导入的方法,最好的办法是在原始类中重构,而不是在本类中覆盖 */ } /** * 建议11: 养成良好习惯,显式声明uid */ private void suggest11() { /* 在序列化和反序列化的类不一致的情形下,反序列化时会报一个InvalidClassException异常,原因 是序列化和反序列化所对应的类版本发生了变化,JVM不能把数据流转换为实例对象。那JVM是根据什 么来判断一个类版本的呢? 好问题,通过SerialVersionUID,也叫做流标识符(Stream Unique Identifier),即类的版本 定义的,它可以显式声明也可以隐式声明。显式声明格式如下: private static final long serialVersionUID = xxxxL; 而隐式声明则是我不声明,由编译器在编译的时候帮我生成。生成的依据是通过包名、类名、继承关系、 非私有的方法和属性,以及参数、返回值等诸多因子计算得出的,极度复杂,基本上计算出来的这个值 是唯一的。 再来看看serialVersionUID的作用。JVM在反序列化时,会比较数据流中的serialVersionUID与类的 serialVersionUID是否相同,如果相同,则认为类没有发生改变,可以把数据流load为实例对象;如果 不相同,抛个异常InvalidClassException。这是一个非常好的校验机制,可以保证一个对象即使在网络 或磁盘中“滚过”一次,仍能做到“出淤泥而不染”,完美地实现类的一致性 */ /** * 注意 * 显示声明serialVersionUID可以避免对象不一致,提高代码的健壮性,可在关键时候发挥作用, * 但是尽量不要以这种方式向JVM“撒谎” */ } /** * 建议12: 避免用序列化类在构造函数中为不变量赋值 */ private void suggest12() { /* 我们知道带有final标识的属性是不变量,也就是说只能赋值一次,不能重复赋值,但是在序列化类中就 有点复杂了。 如果final属性是一个直接量,在反序列化时就会重新计算,这是基本规则。final变量另一种赋值方式: 通过构造函数赋值,这里触及了反序列化的另一个规则:反序列化时构造函数不会执行。 反序列化的执行过程是这样的:JVM从数据流中获取一个Object对象,然后根据数据流中的类文件描述信息 (在序列化时,保存到磁盘的对象文件中包含了类描述信息,注意是类描述信息,不是类)查看,发现是 final变量,需要重新计算,于是引用Person类中的name值,而此时JVM又发现name竟然没有赋值(在构造 函数中赋的值),不能引用,于是它就不再初始化,保持原值状态。 这很容易出现反序列化生成的final变量值与新产生的实例值不相同的情况,于是业务异常就产生了。 */ /** * 注意 * 在序列化类中,不要使用构造函数为final变量赋值 */ } /** * 建议13: 避免为final变量复杂赋值 */ private void suggest13() { /* 为final变量赋值还有一种方式:通过方法赋值,即直接在声明时通过方法返回值赋值,这也会有final变量 没有重新赋值的问题。 上个建议所说final会被重新赋值,其中的“值”值的是简单对象。简单对象包括:8个基本类型,以及数组、 字符串(字符串情况很复杂,不通过new关键字生成Sting对象的情况下,final变量的赋值与基本类型相同), 但不能方法赋值。 其中的原理是这样的,保存到磁盘上(或者网络传输)的对象文件包括两部分: (1)类描述信息 包括包路径、继承关系、访问权限、变量描述、变量访问权限、方法签名、返回值,以及变量的关联类信息。要 注意的一点是,它并不是class文件的翻版,它不记录方法、构造函数、static变量等的具体实现。之所以类 描述会被保存,很简单,是因为能去也能回嘛,这保证反序列化的健壮运行 (2)非瞬态(transient关键字)和非静态(static关键字)的实例变量值 */ /** * 注意 * 反序列化时final变量在以下情况下不会被重新赋值: * 通过构造函数为final变量赋值 * 通过方法返回值为final变量赋值 * final修饰的属性不是基本类型 */ } /** * 建议14: 使用序列化类的私有方法巧妙解决部分属性持久化问题 */ private void suggest14() { /* 在Person类中增加了writeObject和readObject两个方法,并且访问权限都是私有级别,这可以改变Person 序列化的行为,为什么呢?其实这里使用了序列化独有的机制:序列化回调。Java调用ObjectOutputStream 类把一个对象转换成流数据时,会通过反射检查被序列化的类是否有writeObject方法,并且检查其是否符合 私有、无返回值的特性。若有,则会委托该方法进行对象序列化,若没有,则由ObjectOutputStream按照默认 规则继续序列化。同样,在从流数据恢复成实例对象时,也会检查是否有一个私有的readObject方法,如果有, 则会通过该方法读取属性值。此处有几个关键点要说明: (1)out.defaultWriteObject() 告知JVM按照默认的规则写入对象,惯例的写法是写在第一句话里 (2)in.defaultReadObject() 告知JVM按照默认的规则读入对象,惯例的写法也是写在第一句话里 (3)out.writeXX和in.readXX 分别是写入和读取相应的值,类似一个队列,先进先出,如果此处有复杂的数据逻辑,建议按封装Collection 对象处理 */ /** * 注意 * 实现了Serializable接口的类可以实现两个私有方法:writeObject和readObject,以影响和控制序列化 * 和反序列化的过程 */ } /** * 建议15: break万万不可忘 */ private void suggest15() { Log.e(TAG, "2=" + toChineseNumberCase(2)); /** * 注意 * 忘记写break会导致很隐蔽的bug * 对于此类问题,有一个简单的解决办法:修改IDE的警告级别 */ } //把阿拉伯数字翻译成中文大写数字 private String toChineseNumberCase(int n) { String chineseNumber = ""; switch (n) { case 0:chineseNumber = "零"; case 1:chineseNumber = "壹"; case 2:chineseNumber = "贰"; case 3:chineseNumber = "叁"; case 4:chineseNumber = "肆"; case 5:chineseNumber = "伍"; case 6:chineseNumber = "陆"; case 7:chineseNumber = "柒"; case 8:chineseNumber = "捌"; case 9:chineseNumber = "玖"; } return chineseNumber; } /** * 建议16: 易变业务使用脚本语言编写 */ private void suggest16() { /* //获得一个javascript的执行引擎 ScriptEngine engine=new ScriptEngineManager().getEngineByName("javascript"); //建立上下文变量 Bindings bind=engine.createBindings(); bind.put("factor", 1); //绑定上下文,作用域是当前引擎范围 engine.setBindings(bind,ScriptContext.ENGINE_SCOPE); Scanner input = new Scanner(System.in); while(input.hasNextInt()){ int first = input.nextInt(); int sec = input.nextInt(); System.out.println("输入参数是:"+first+","+sec); //执行js代码 engine.eval(new FileReader("c:/model.js")); //是否可调用方法 if(engine instanceof Invocable){ Invocable in=(Invocable)engine; //执行js中的函数 Double result = (Double)in.invokeFunction("formula",first,sec); System.out.println("运算结果:"+result.intValue()); } } */ /** * 注意 * 可以在Java中使用脚本语言来实现经常变动的需求 */ } /** * 建议17: 慎用动态编译 */ private void suggest17() { /* 动态编译虽然是很好的工具,但是使用的还是很少,因为静态编译已经能够解决大部分问题,甚至全部 问题,即使真的需要动态编译,也有很好的替代方案,如JRuby、Groovy等无缝的脚本语言 */ /** * 注意 * (1)在框架中谨慎使用 * (2)不要在要求高性能的项目使用 * (3)动态编译要考虑安全问题 * (4)记录动态编译过程 */ } /** * 建议18: 避免instanceof非预期结果 */ private void suggest18() { //String对象是否是Object的实例 boolean b1 = "Sting" instanceof Object; //String对象是否是String的实例 boolean b2 = new String() instanceof String; //Object对象是否是String的实例 boolean b3 = new Object() instanceof String; //拆箱类型是否是装箱类型的实例 // boolean b4 = 'A' instanceof Character; //空对象是否是String的实例 boolean b5 = null instanceof String; //类型转换后的空对象是否是String的实例 /* flase 不要看这里有个强制类型转换就认为结果是true,不是的,null是一个万用类型, 也可以说它没有类型,即使类型转换还是个null */ boolean b6 = (String)null instanceof String; //Date对象是否是String的实例 // boolean b7 = new Date() instanceof String; //在泛型类中判断String对象是否是Date的实例 boolean b8 = new GenericClass<String>().isDateInstance(""); // false /** * 注意 * instanceof 只能用于对象的判断,不能用于基本类型的判断 * instanceof 特有的规则:若左操作数是null,结果就直接返回false,不再运算右操作数是什么类 */ } class GenericClass<T>{ //判断是否是Date类型 public boolean isDateInstance(T t){ return t instanceof Date; } } /** * 建议19: 断言绝对不是鸡肋 */ private void suggest19() { /* 在防御式编程中经常会用断言(Assertion)对参数和环境做出判断,避免程序因不当的输入或错误的 环境而产生逻辑异常。在Java中断言使用的是assert关键字,其基本的用法如下: assert <布尔表达式> assert <布尔表达式> : <错误信息> 在布尔表达式为假时,抛出AssertionError错误,并附带了错误信息。assert的语法较简单,有以下 两个特性: (1)assert默认是不启用的 (2)assert抛出的异常AssertionError是继承自Error的 assert虽然是做断言的,但不能将其等价于if...else...这样的条件判断,以下情况不可使用: (1)在对外公开的方法中 (2)在执行逻辑代码的情况下 assert的支持是可选的,在开发时可以让它运行,但在生产系统中则不需要其运行了,因此在assert的 布尔表达式中不能执行逻辑代码,否则会因为环境不同而产生不同的逻辑 在什么情况下能够使用assert呢?一句话:按照正常执行逻辑不可能到达的代码区域可以放置assert。 具体分为三种情况: (1)在私有方法中放置asser作为参数的校验 (2)流程控制中不可能达到的区域 (3)建立程序探针 */ } /** * 建议20: 不要只替换一个类 */ private void suggest20() { /** * 注意 * 发布应用系统时禁止使用类文件替换方式,整体war包发布才是万全之策 */ } }
DIY-green/AndroidStudyDemo
HighQualityCodeStudy/src/main/java/com/cheng/improve151suggest/I151SChapter01Activity.java
6,211
// 这个程序输出的count等于几?答案等于10?错了,运行结果是count等于0,为什么呢?
line_comment
zh-cn
package com.cheng.improve151suggest; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.ListView; import java.util.Arrays; import java.util.Date; import java.util.Random; import com.cheng.highqualitycodestudy.R; import com.cheng.improve151suggest.adapter.I151SuggestListAdapter; import com.cheng.improve151suggest.model.Client; /** 第1章 java开发中通用的方法和准则/1 建议1: 不要在常量和变量中出现易混淆的字母/2 建议2: 莫让常量蜕变成变量/2 建议3: 三元操作符的类型务必一致/3 建议4: 避免带有变长参数的方法重载/4 建议5: 别让null值和空值威胁到变长方法/6 建议6: 覆写变长方法也循规蹈矩/7 建议7: 警惕自增的陷阱/8 建议8: 不要让旧语法困扰你/10 建议9: 少用静态导入/11 建议10: 不要在本类中覆盖静态导入的变量和方法/13 建议11: 养成良好习惯,显式声明uid/14 建议12: 避免用序列化类在构造函数中为不变量赋值/17 建议13: 避免为final变量复杂赋值/19 建议14: 使用序列化类的私有方法巧妙解决部分属性持久化问题/20 建议15: break万万不可忘/23 建议16: 易变业务使用脚本语言编写/25 建议17: 慎用动态编译/27 建议18: 避免instanceof非预期结果/29 建议19: 断言绝对不是鸡肋/31 建议20: 不要只替换一个类/33 */ public class I151SChapter01Activity extends AppCompatActivity { private static final String TAG = "I151SChapter01Activity"; private ListView mChapterLV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_i151suggestchapter); initView(); initData(); } private void initView() { this.mChapterLV = (ListView) findViewById(R.id.isi_chapter_lv); } private void initData() { String[] suggests = getResources().getStringArray(R.array.i151schapter1); I151SuggestListAdapter adapter = new I151SuggestListAdapter(this, Arrays.asList(suggests)); mChapterLV.setAdapter(adapter); } /** * 建议1: 不要在常量和变量中出现易混淆的字母 */ private void suggest1() { long i = 1l; Log.e(TAG, "i的两倍是:" + (i+i)); //2 // 查看输出结果:i的两倍是:2(不是22) /** * 注意 * 字母“l”作为长整型标志时务必大写 * 字母“O”与数字混合使用的时候请添加注释 */ } /** * 建议2: 莫让常量蜕变成变量 */ private void suggest2() { Log.e(TAG, "常量会变哦:" + Const.RAND_CONST); /** * 注意 * 务必让常量的值在运行期保持不变 */ } /*接口常量*/ interface Const { // 这还是常量吗? static final int RAND_CONST = new Random().nextInt(); } /** * 建议3: 三元操作符的类型务必一致 */ private void suggest3() { int i = 80; String s = String.valueOf(i<100?90:100); String s1 = String.valueOf(i<100?90:100.0); Log.e(TAG, "两者是否相等" + s.equals(s1)); // false // 这里涉及三元操作符类型的转换规则: /* 若两个操作数不可转换,则不做转换,返回值为Object类型 若两个操作数是明确类型的表达式(比如变量),则按照正常的二进制数字来转换, int类型转换为long,long转化为float 若两个操作数中有一个数字S,另一个是表达式,且其类型标示为T,那么,若数字 S在T的范围内,则转换为T类型;若S超出了T类型的范围,则T转换为S类型 若两个操作数都是直接量数字,则返回值类型为范围较大者 */ /** * 注意 * 保证三元操作符中的两个操作数类型一致,可减少可能错误的发生 */ } /** * 建议4: 避免带有变长参数的方法重载 */ private void suggest4() { Client client = new Client(); // 499 元的货物,打75折 client.calPrice(49900, 75); // 调用 calPrice(int price,int discount) /** * 注意 * 慎重考虑变长参数的方法重载 */ } /** * 建议5: 别让null值和空值威胁到变长方法 */ private void suggest5() { Client client = new Client(); client.methodA("China", 0); client.methodA("China", "People"); // client.methodA("China"); // client.methodA("China", null); // 上面这两处编译通不过,提示是相同的:方法模糊不清,编译器不知道调用哪一个方法, // 但这两次代码反映的代码味道可是不同的 // 对于methodA("China")方法,根据实参"China"(Stirng类型), // 两个方法都符合形参格式,编译器不知道该调用哪个方法,于是报错 // 这是Client类的设计者违反了KISS原则(Keep It Simple, Stupid,即懒人原则), // 按照此规则设计的方法应该很容易调用 // 对于client.methodA("China", null)方法,直接量null是没有类型的,虽然两个methodA // 方法都符合调用请求,但不知道调用哪一个,于是报错了 // 该方法除了不符合上面的懒人原则外,这里还有一个非常不好的编码习惯,即调用者隐藏了实参 // 类型,这是非常危险的,不仅仅调用者需要“猜测”该调用哪个方法,而且被调用者也可能产生内 // 部逻辑混乱的情况 // 对于本例来说应该做如下修改: String[] strs = null; client.methodA("China", strs); // 也就是说让编译器知道这个null值是String[]类型的,编译即可通过,也就减少了错误的发生 /** * 注意 * 类的设计应该按照KISS(Keep It Simple, Stupid,即懒人原则) */ } /** * 建议6: 覆写变长方法也循规蹈矩 */ private void suggest6() { // 向上转型 Base base = new Sub(); base.fun(100, 50); // 不转型 Sub sub = new Sub(); // sub.fun(100, 50); // 上面这行编译通不过,问题出在什么地方呢? // @Override注解吗?非也,覆写是正确的,因为父类的calPrice编译成字节码后的形参是一个 // int类型的形参加上一个int数组类型的形参,子类的参数列表也与此相同,那覆写是理所当然 // 了,所以加上@Override注解没有问题。错误提示是上面这句找不到fun(int, int)方法 // 这太奇怪了:子类继承了父类的所有属性和方法,甭管是私有的还是公有的访问权限,同样的 // 参数、同样的方法名,通过父类调用没有任何问题,通过子类调用却编译通不过,为啥?难道 // 是没有继承下来?或者子类缩小了父类方法的前置条件? // 事实上,base对象是把子类对象Sub做了向上转型,形参列表是由父类决定的,由于是变长参数, // 在编译时,“base.fun(100, 50)”中的“50”这个实参会被编译器“猜测”而编译成“{50}”数组, // 再由子类Sub执行。再来看看直接调用子类的情况,这时编译器并不会把“50”做类型转换,因为 // 数组本身也是一个对象,编译器还没有聪明到要在两个没有继承关系的类之间做转换,要知道 // Java是要求严格类型匹配的,类型不匹配编译器自然就会拒绝执行,并给予错误提示。 /** * 覆写必须满足的条件: * 重写方法不能缩小访问权限 * 参数列表必须与被重写方法相同 * 返回类型必须与被重写方法的相同或是其子类 * 重写方法不能抛出新的异常,或者超出父类范围的异常,但是可以抛出更少、更有限的异常,或者不抛出异常 */ /** * 注意 * 覆写的方法参数与父类相同,不仅仅是类型、数量,还包括显示形式 */ } // 基类 class Base{ void fun(int price,int... discounts){ System.out.println("Base……fun"); } } // 子类,覆写父类方法 class Sub extends Base{ @Override void fun(int price,int[] discounts){ System.out.println("Sub……fun"); } } /** * 建议7: 警惕自增的陷阱 */ private void suggest7() { int count = 0; for (int i = 0; i < 10; i++) { count = count++; } Log.e(TAG, "count=" + count); // 0 // 这个 <SUF> /* count++ 是一个表达式,是有返回值的,它的返回值就是count自加前的值,Java对自加是这样处理的: 首先把count的值(注意是值,不是引用)拷贝到一个临时变量区,然后对count变量加1,最后返回临时 变量区的值。程序第一次循环时的详细处理步骤如下: 步骤1 JVM把count值(其值是0)拷贝到临时变量区 步骤2 count值加1,这时候count的值是1 步骤3 返回临时变量区的值,注意这个值是0,没有修改过 步骤4 返回值给count,此时count值被重置成0 “count = count++;”这条语句可以按照如下代码来理解: // 先保存初始值 int temp = count; // 做自增操作 count = count + 1; // 返回原始值 return temp; 解决方法很简单,修改为“count++”即可。 该问题在不同的语音环境有不同的实现:C++中“count=count++”与“count++”是等效的,而在PHP中则 保持着与Java相同的处理方式。每种语言对自增的实现方式各不同。 */ /** * 注意 * i++表达式的返回值是i自加之前的值 */ } /** * 建议8: 不要让旧语法困扰你 */ private void suggest8() { // 数据定义及初始化 int fee = 200; // 其他业务处理 saveDefault:save(fee); /* “saveDefault:save(fee)” 此句代码很神奇,编译没有错,运行也很正常。Java中竟然有冒号操作符? 原来是goto语句。Java中抛弃了goto语法,但还是保留了该关键字,只是不进行语义处理而已。Java中 虽然没有了goto关键字,但是扩展了break和continue关键字,它们的后面都可以加上标号做跳转,完全 实现了goto功能,同时也把goto的诟病带了进来,很少看到这样使用。 */ /** * 注意 * Java没有goto * 为了可读性少用break、continue,就算要使用也不能加上标号做跳转 */ } void saveDefault() { } void save(int fee) { } /** * 建议9: 少用静态导入 */ private void sugget9() { /** * 注意 * 对于静态导入,一定要遵循两个规则: * 不使用*(星号)通配符,除非是导入静态常量类(只包含常量的类或接口) * 方法名是具有明确、清晰表象意义的工具类 */ } /** * 建议10: 不要在本类中覆盖静态导入的变量和方法 */ private void suggest10() { /** * 注意 * 编译器有一个“最短路径”原则:如果能够在本类中查找到的变量、常量、方法,就不会到其他包或 * 父类、接口中查找,以确保本类中的属性、方法优先 * 如果要变更一个被静态导入的方法,最好的办法是在原始类中重构,而不是在本类中覆盖 */ } /** * 建议11: 养成良好习惯,显式声明uid */ private void suggest11() { /* 在序列化和反序列化的类不一致的情形下,反序列化时会报一个InvalidClassException异常,原因 是序列化和反序列化所对应的类版本发生了变化,JVM不能把数据流转换为实例对象。那JVM是根据什 么来判断一个类版本的呢? 好问题,通过SerialVersionUID,也叫做流标识符(Stream Unique Identifier),即类的版本 定义的,它可以显式声明也可以隐式声明。显式声明格式如下: private static final long serialVersionUID = xxxxL; 而隐式声明则是我不声明,由编译器在编译的时候帮我生成。生成的依据是通过包名、类名、继承关系、 非私有的方法和属性,以及参数、返回值等诸多因子计算得出的,极度复杂,基本上计算出来的这个值 是唯一的。 再来看看serialVersionUID的作用。JVM在反序列化时,会比较数据流中的serialVersionUID与类的 serialVersionUID是否相同,如果相同,则认为类没有发生改变,可以把数据流load为实例对象;如果 不相同,抛个异常InvalidClassException。这是一个非常好的校验机制,可以保证一个对象即使在网络 或磁盘中“滚过”一次,仍能做到“出淤泥而不染”,完美地实现类的一致性 */ /** * 注意 * 显示声明serialVersionUID可以避免对象不一致,提高代码的健壮性,可在关键时候发挥作用, * 但是尽量不要以这种方式向JVM“撒谎” */ } /** * 建议12: 避免用序列化类在构造函数中为不变量赋值 */ private void suggest12() { /* 我们知道带有final标识的属性是不变量,也就是说只能赋值一次,不能重复赋值,但是在序列化类中就 有点复杂了。 如果final属性是一个直接量,在反序列化时就会重新计算,这是基本规则。final变量另一种赋值方式: 通过构造函数赋值,这里触及了反序列化的另一个规则:反序列化时构造函数不会执行。 反序列化的执行过程是这样的:JVM从数据流中获取一个Object对象,然后根据数据流中的类文件描述信息 (在序列化时,保存到磁盘的对象文件中包含了类描述信息,注意是类描述信息,不是类)查看,发现是 final变量,需要重新计算,于是引用Person类中的name值,而此时JVM又发现name竟然没有赋值(在构造 函数中赋的值),不能引用,于是它就不再初始化,保持原值状态。 这很容易出现反序列化生成的final变量值与新产生的实例值不相同的情况,于是业务异常就产生了。 */ /** * 注意 * 在序列化类中,不要使用构造函数为final变量赋值 */ } /** * 建议13: 避免为final变量复杂赋值 */ private void suggest13() { /* 为final变量赋值还有一种方式:通过方法赋值,即直接在声明时通过方法返回值赋值,这也会有final变量 没有重新赋值的问题。 上个建议所说final会被重新赋值,其中的“值”值的是简单对象。简单对象包括:8个基本类型,以及数组、 字符串(字符串情况很复杂,不通过new关键字生成Sting对象的情况下,final变量的赋值与基本类型相同), 但不能方法赋值。 其中的原理是这样的,保存到磁盘上(或者网络传输)的对象文件包括两部分: (1)类描述信息 包括包路径、继承关系、访问权限、变量描述、变量访问权限、方法签名、返回值,以及变量的关联类信息。要 注意的一点是,它并不是class文件的翻版,它不记录方法、构造函数、static变量等的具体实现。之所以类 描述会被保存,很简单,是因为能去也能回嘛,这保证反序列化的健壮运行 (2)非瞬态(transient关键字)和非静态(static关键字)的实例变量值 */ /** * 注意 * 反序列化时final变量在以下情况下不会被重新赋值: * 通过构造函数为final变量赋值 * 通过方法返回值为final变量赋值 * final修饰的属性不是基本类型 */ } /** * 建议14: 使用序列化类的私有方法巧妙解决部分属性持久化问题 */ private void suggest14() { /* 在Person类中增加了writeObject和readObject两个方法,并且访问权限都是私有级别,这可以改变Person 序列化的行为,为什么呢?其实这里使用了序列化独有的机制:序列化回调。Java调用ObjectOutputStream 类把一个对象转换成流数据时,会通过反射检查被序列化的类是否有writeObject方法,并且检查其是否符合 私有、无返回值的特性。若有,则会委托该方法进行对象序列化,若没有,则由ObjectOutputStream按照默认 规则继续序列化。同样,在从流数据恢复成实例对象时,也会检查是否有一个私有的readObject方法,如果有, 则会通过该方法读取属性值。此处有几个关键点要说明: (1)out.defaultWriteObject() 告知JVM按照默认的规则写入对象,惯例的写法是写在第一句话里 (2)in.defaultReadObject() 告知JVM按照默认的规则读入对象,惯例的写法也是写在第一句话里 (3)out.writeXX和in.readXX 分别是写入和读取相应的值,类似一个队列,先进先出,如果此处有复杂的数据逻辑,建议按封装Collection 对象处理 */ /** * 注意 * 实现了Serializable接口的类可以实现两个私有方法:writeObject和readObject,以影响和控制序列化 * 和反序列化的过程 */ } /** * 建议15: break万万不可忘 */ private void suggest15() { Log.e(TAG, "2=" + toChineseNumberCase(2)); /** * 注意 * 忘记写break会导致很隐蔽的bug * 对于此类问题,有一个简单的解决办法:修改IDE的警告级别 */ } //把阿拉伯数字翻译成中文大写数字 private String toChineseNumberCase(int n) { String chineseNumber = ""; switch (n) { case 0:chineseNumber = "零"; case 1:chineseNumber = "壹"; case 2:chineseNumber = "贰"; case 3:chineseNumber = "叁"; case 4:chineseNumber = "肆"; case 5:chineseNumber = "伍"; case 6:chineseNumber = "陆"; case 7:chineseNumber = "柒"; case 8:chineseNumber = "捌"; case 9:chineseNumber = "玖"; } return chineseNumber; } /** * 建议16: 易变业务使用脚本语言编写 */ private void suggest16() { /* //获得一个javascript的执行引擎 ScriptEngine engine=new ScriptEngineManager().getEngineByName("javascript"); //建立上下文变量 Bindings bind=engine.createBindings(); bind.put("factor", 1); //绑定上下文,作用域是当前引擎范围 engine.setBindings(bind,ScriptContext.ENGINE_SCOPE); Scanner input = new Scanner(System.in); while(input.hasNextInt()){ int first = input.nextInt(); int sec = input.nextInt(); System.out.println("输入参数是:"+first+","+sec); //执行js代码 engine.eval(new FileReader("c:/model.js")); //是否可调用方法 if(engine instanceof Invocable){ Invocable in=(Invocable)engine; //执行js中的函数 Double result = (Double)in.invokeFunction("formula",first,sec); System.out.println("运算结果:"+result.intValue()); } } */ /** * 注意 * 可以在Java中使用脚本语言来实现经常变动的需求 */ } /** * 建议17: 慎用动态编译 */ private void suggest17() { /* 动态编译虽然是很好的工具,但是使用的还是很少,因为静态编译已经能够解决大部分问题,甚至全部 问题,即使真的需要动态编译,也有很好的替代方案,如JRuby、Groovy等无缝的脚本语言 */ /** * 注意 * (1)在框架中谨慎使用 * (2)不要在要求高性能的项目使用 * (3)动态编译要考虑安全问题 * (4)记录动态编译过程 */ } /** * 建议18: 避免instanceof非预期结果 */ private void suggest18() { //String对象是否是Object的实例 boolean b1 = "Sting" instanceof Object; //String对象是否是String的实例 boolean b2 = new String() instanceof String; //Object对象是否是String的实例 boolean b3 = new Object() instanceof String; //拆箱类型是否是装箱类型的实例 // boolean b4 = 'A' instanceof Character; //空对象是否是String的实例 boolean b5 = null instanceof String; //类型转换后的空对象是否是String的实例 /* flase 不要看这里有个强制类型转换就认为结果是true,不是的,null是一个万用类型, 也可以说它没有类型,即使类型转换还是个null */ boolean b6 = (String)null instanceof String; //Date对象是否是String的实例 // boolean b7 = new Date() instanceof String; //在泛型类中判断String对象是否是Date的实例 boolean b8 = new GenericClass<String>().isDateInstance(""); // false /** * 注意 * instanceof 只能用于对象的判断,不能用于基本类型的判断 * instanceof 特有的规则:若左操作数是null,结果就直接返回false,不再运算右操作数是什么类 */ } class GenericClass<T>{ //判断是否是Date类型 public boolean isDateInstance(T t){ return t instanceof Date; } } /** * 建议19: 断言绝对不是鸡肋 */ private void suggest19() { /* 在防御式编程中经常会用断言(Assertion)对参数和环境做出判断,避免程序因不当的输入或错误的 环境而产生逻辑异常。在Java中断言使用的是assert关键字,其基本的用法如下: assert <布尔表达式> assert <布尔表达式> : <错误信息> 在布尔表达式为假时,抛出AssertionError错误,并附带了错误信息。assert的语法较简单,有以下 两个特性: (1)assert默认是不启用的 (2)assert抛出的异常AssertionError是继承自Error的 assert虽然是做断言的,但不能将其等价于if...else...这样的条件判断,以下情况不可使用: (1)在对外公开的方法中 (2)在执行逻辑代码的情况下 assert的支持是可选的,在开发时可以让它运行,但在生产系统中则不需要其运行了,因此在assert的 布尔表达式中不能执行逻辑代码,否则会因为环境不同而产生不同的逻辑 在什么情况下能够使用assert呢?一句话:按照正常执行逻辑不可能到达的代码区域可以放置assert。 具体分为三种情况: (1)在私有方法中放置asser作为参数的校验 (2)流程控制中不可能达到的区域 (3)建立程序探针 */ } /** * 建议20: 不要只替换一个类 */ private void suggest20() { /** * 注意 * 发布应用系统时禁止使用类文件替换方式,整体war包发布才是万全之策 */ } }
0
48
0
32125_3
package edu.dlnu.oa.sse; import edu.dlnu.oa.utils.RedisUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * @author wuhan * @date 2019/11/8 20:14 */ @Controller @RequestMapping(value = "/getCount") public class SSEController { @Autowired private RedisUtils redisUtils; private Logger log = LoggerFactory.getLogger(this.getClass()); @ResponseBody @RequestMapping("/clearCount") public void clearCount(HttpServletRequest request){ String empId = request.getSession().getAttribute("empId").toString(); redisUtils.clearLeaveApplyCount(empId); } /** * 回复消息控制器 * @param response response * @param request request * @return 返回用户的被回复次数 */ @ResponseBody @RequestMapping(value="/push",produces="text/event-stream;charset=UTF-8") public String push(HttpServletResponse response, HttpServletRequest request){ //从session里获取用户id String empId = request.getSession().getAttribute("empId").toString(); Map<String,Object> param = new HashMap<>(); //SSE要求的头信息如下 response.setHeader("Access-Control-Allow-Origin","*"); int count = 0; try { count= redisUtils.getLeaveApplyCount(Integer.parseInt(empId)); } catch (Exception e) { e.printStackTrace(); } // int atMeCounts = (int) (Math.random()*10); log.info("at me count = " + count); //这里我再次承认,写的不优雅,只要返回count给前端就好,省流量 //这里爬了约莫一个小时的坑,提醒个位同学,末尾的\n\n一定要加啊QAQ return "data: "+ count +" \nevent:like\n retry:15000\n\n"; } }
DLNUOA/OA
src/main/java/edu/dlnu/oa/sse/SSEController.java
571
//SSE要求的头信息如下
line_comment
zh-cn
package edu.dlnu.oa.sse; import edu.dlnu.oa.utils.RedisUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * @author wuhan * @date 2019/11/8 20:14 */ @Controller @RequestMapping(value = "/getCount") public class SSEController { @Autowired private RedisUtils redisUtils; private Logger log = LoggerFactory.getLogger(this.getClass()); @ResponseBody @RequestMapping("/clearCount") public void clearCount(HttpServletRequest request){ String empId = request.getSession().getAttribute("empId").toString(); redisUtils.clearLeaveApplyCount(empId); } /** * 回复消息控制器 * @param response response * @param request request * @return 返回用户的被回复次数 */ @ResponseBody @RequestMapping(value="/push",produces="text/event-stream;charset=UTF-8") public String push(HttpServletResponse response, HttpServletRequest request){ //从session里获取用户id String empId = request.getSession().getAttribute("empId").toString(); Map<String,Object> param = new HashMap<>(); //SS <SUF> response.setHeader("Access-Control-Allow-Origin","*"); int count = 0; try { count= redisUtils.getLeaveApplyCount(Integer.parseInt(empId)); } catch (Exception e) { e.printStackTrace(); } // int atMeCounts = (int) (Math.random()*10); log.info("at me count = " + count); //这里我再次承认,写的不优雅,只要返回count给前端就好,省流量 //这里爬了约莫一个小时的坑,提醒个位同学,末尾的\n\n一定要加啊QAQ return "data: "+ count +" \nevent:like\n retry:15000\n\n"; } }
0
13
0
15444_6
/** * wechatdonal */ package ui; import im.Chating; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.jivesoftware.smack.XMPPConnection; import tools.AppManager; import tools.ImageUtils; import tools.Logger; import tools.StringUtils; import tools.UIHelper; import ui.adapter.FieldAdapter; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.media.ExifInterface; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.provider.MediaStore.Images.Media; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import bean.KeyValue; import bean.UserEntity; import bean.UserInfo; import com.donal.wechat.R; import config.ApiClent; import config.ApiClent.ClientCallback; import config.AppActivity; import config.CommonValue; import config.FriendManager; import config.MessageManager; import config.NoticeManager; import config.XmppConnectionManager; /** * wechat * * @author donal * */ public class Me extends AppActivity{ private ImageView avatarView; private TextView nameTV; private ListView iphoneTreeView; private List<KeyValue> datas = new ArrayList<KeyValue>(); private FieldAdapter fieldAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wechat); initUI(); } private void initUI() { initTextEditDialog(); initdesDialog(); LayoutInflater inflater = LayoutInflater.from(this); iphoneTreeView = (ListView) findViewById(R.id.xlistview); View header = inflater.inflate(R.layout.more_headerview, null); avatarView = (ImageView) header.findViewById(R.id.avatar); nameTV = (TextView) header.findViewById(R.id.title); imageLoader.displayImage(CommonValue.BASE_URL+appContext.getLoginUserHead(), avatarView, CommonValue.DisplayOptions.avatar_options); iphoneTreeView.addHeaderView(header); View footer = inflater.inflate(R.layout.me_footer, null); iphoneTreeView.addFooterView(footer); fieldAdapter = new FieldAdapter(datas, this); iphoneTreeView.setAdapter(fieldAdapter); setInfo(); iphoneTreeView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { if (position == 1) { textDialog.show(); } else if (position == 2) { text1Dialog.show(); } } }); } private void setInfo() { UserEntity user = appContext.getLoginInfo(); datas.add(new KeyValue("昵称", user.userInfo.nickName)); datas.add(new KeyValue("个性签名", user.userInfo.description)); fieldAdapter.notifyDataSetChanged(); } @Override public void onBackPressed() { isExit(); } public void ButtonClick(View v) { switch (v.getId()) { case R.id.exit: XMPPConnection connection = XmppConnectionManager.getInstance().getConnection(); if (connection.isConnected()) { connection.disconnect(); } stopService(); MessageManager.destroy(); NoticeManager.destroy(); FriendManager.destroy(); appContext.setUserLogout(); AppManager.getAppManager().finishAllActivity(); startActivity(new Intent(this, Login.class)); break; default: PhotoChooseOption(); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } String newPhotoPath; switch (requestCode) { case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA: if (StringUtils.notEmpty(theLarge)) { File file = new File(theLarge); File dir = new File( ImageUtils.CACHE_IMAGE_FILE_PATH); if (!dir.exists()) { dir.mkdirs(); } String imagePathAfterCompass = ImageUtils.CACHE_IMAGE_FILE_PATH + file.getName(); try { ExifInterface sourceExif = new ExifInterface(theLarge); String orientation = sourceExif.getAttribute(ExifInterface.TAG_ORIENTATION); ImageUtils.saveImageToSD(imagePathAfterCompass, ImageUtils.getSmallBitmap(theLarge, 200), 80); ExifInterface exif = new ExifInterface(imagePathAfterCompass); exif.setAttribute(ExifInterface.TAG_ORIENTATION, orientation); exif.saveAttributes(); newPhotoPath = imagePathAfterCompass; uploadPhotoService(newPhotoPath); } catch (IOException e) { // Crashlytics.logException(e); } } break; case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD: if(data == null) return; Uri thisUri = data.getData(); String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(thisUri); if(StringUtils.empty(thePath)) { newPhotoPath = ImageUtils.getAbsoluteImagePath(this,thisUri); } else { newPhotoPath = thePath; } File file = new File(newPhotoPath); File dir = new File( ImageUtils.CACHE_IMAGE_FILE_PATH); if (!dir.exists()) { dir.mkdirs(); } String imagePathAfterCompass = ImageUtils.CACHE_IMAGE_FILE_PATH + file.getName(); try { ExifInterface sourceExif = new ExifInterface(newPhotoPath); String orientation = sourceExif.getAttribute(ExifInterface.TAG_ORIENTATION); ImageUtils.saveImageToSD(imagePathAfterCompass, ImageUtils.getSmallBitmap(newPhotoPath, 200), 80); ExifInterface exif = new ExifInterface(imagePathAfterCompass); exif.setAttribute(ExifInterface.TAG_ORIENTATION, orientation); exif.saveAttributes(); newPhotoPath = imagePathAfterCompass; uploadPhotoService(newPhotoPath); } catch (IOException e) { // Crashlytics.logException(e); } break; } } private String theLarge; private void PhotoChooseOption() { closeInput(); CharSequence[] item = {"相册", "拍照"}; AlertDialog imageDialog = new AlertDialog.Builder(this).setTitle(null).setIcon(android.R.drawable.btn_star).setItems(item, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int item) { //手机选图 if( item == 0 ) { Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI); startActivityForResult(Intent.createChooser(intent, "选择图片"),ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD); } //拍照 else if( item == 1 ) { String savePath = ""; //判断是否挂载了SD卡 String storageState = Environment.getExternalStorageState(); if(storageState.equals(Environment.MEDIA_MOUNTED)){ savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + ImageUtils.DCIM;//存放照片的文件夹 File savedir = new File(savePath); if (!savedir.exists()) { savedir.mkdirs(); } } //没有挂载SD卡,无法保存文件 if(StringUtils.empty(savePath)){ UIHelper.ToastMessage(Me.this, "无法保存照片,请检查SD卡是否挂载", Toast.LENGTH_SHORT); return; } String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String fileName = "c_" + timeStamp + ".jpg";//照片命名 File out = new File(savePath, fileName); Uri uri = Uri.fromFile(out); theLarge = savePath + fileName;//该照片的绝对路径 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA); } }}).create(); imageDialog.show(); } private void uploadPhotoService(String file) { pg = UIHelper.showProgress(this, "", "上传头像", true); imageLoader.displayImage("file:///"+file, avatarView, CommonValue.DisplayOptions.avatar_options); ApiClent.uploadFile(appContext.getLoginApiKey(), file, new ClientCallback() { @Override public void onSuccess(Object data) { UIHelper.dismissProgress(pg); String head = (String) data; modify("", head, ""); } @Override public void onFailure(String message) { UIHelper.dismissProgress(pg); } @Override public void onError(Exception e) { UIHelper.dismissProgress(pg); } }); } private void modify(String nickname, String head, String des) { pg = UIHelper.showProgress(this, "", "保存中", true); ApiClent.modifiedUser(appContext, appContext.getLoginApiKey(), nickname, head, des, new ClientCallback() { @Override public void onSuccess(Object data) { UIHelper.dismissProgress(pg); showToast((String)data); } @Override public void onFailure(String message) { UIHelper.dismissProgress(pg); } @Override public void onError(Exception e) { UIHelper.dismissProgress(pg); } }); } private AlertDialog textDialog; private void initTextEditDialog() { LayoutInflater inFlater = LayoutInflater.from(this); View textDialogView = inFlater.inflate(R.layout.lovecode_edit_edittext_dialog, null); final EditText ed = (EditText) textDialogView.findViewById(R.id.text); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle("编辑昵称"); builder.setView(textDialogView); builder.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (StringUtils.empty(ed.getText().toString())) { return; } datas.set(0, new KeyValue("昵称", ed.getText().toString())); fieldAdapter.notifyDataSetChanged(); modify(ed.getText().toString(), "", ""); } }); builder.setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); textDialog = builder.create(); } private AlertDialog text1Dialog; private void initdesDialog() { LayoutInflater inFlater = LayoutInflater.from(this); View textDialogView = inFlater.inflate(R.layout.lovecode_edit_edittext_dialog, null); final EditText ed = (EditText) textDialogView.findViewById(R.id.text); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle("编辑个性签名"); builder.setView(textDialogView); builder.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (StringUtils.empty(ed.getText().toString())) { return; } datas.set(1, new KeyValue("个性签名", ed.getText().toString())); fieldAdapter.notifyDataSetChanged(); modify("", "", ed.getText().toString()); } }); builder.setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); text1Dialog = builder.create(); } }
DLTech21/wechat
src/ui/Me.java
3,214
//存放照片的文件夹
line_comment
zh-cn
/** * wechatdonal */ package ui; import im.Chating; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.jivesoftware.smack.XMPPConnection; import tools.AppManager; import tools.ImageUtils; import tools.Logger; import tools.StringUtils; import tools.UIHelper; import ui.adapter.FieldAdapter; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.media.ExifInterface; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.provider.MediaStore.Images.Media; import android.view.LayoutInflater; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import bean.KeyValue; import bean.UserEntity; import bean.UserInfo; import com.donal.wechat.R; import config.ApiClent; import config.ApiClent.ClientCallback; import config.AppActivity; import config.CommonValue; import config.FriendManager; import config.MessageManager; import config.NoticeManager; import config.XmppConnectionManager; /** * wechat * * @author donal * */ public class Me extends AppActivity{ private ImageView avatarView; private TextView nameTV; private ListView iphoneTreeView; private List<KeyValue> datas = new ArrayList<KeyValue>(); private FieldAdapter fieldAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wechat); initUI(); } private void initUI() { initTextEditDialog(); initdesDialog(); LayoutInflater inflater = LayoutInflater.from(this); iphoneTreeView = (ListView) findViewById(R.id.xlistview); View header = inflater.inflate(R.layout.more_headerview, null); avatarView = (ImageView) header.findViewById(R.id.avatar); nameTV = (TextView) header.findViewById(R.id.title); imageLoader.displayImage(CommonValue.BASE_URL+appContext.getLoginUserHead(), avatarView, CommonValue.DisplayOptions.avatar_options); iphoneTreeView.addHeaderView(header); View footer = inflater.inflate(R.layout.me_footer, null); iphoneTreeView.addFooterView(footer); fieldAdapter = new FieldAdapter(datas, this); iphoneTreeView.setAdapter(fieldAdapter); setInfo(); iphoneTreeView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) { if (position == 1) { textDialog.show(); } else if (position == 2) { text1Dialog.show(); } } }); } private void setInfo() { UserEntity user = appContext.getLoginInfo(); datas.add(new KeyValue("昵称", user.userInfo.nickName)); datas.add(new KeyValue("个性签名", user.userInfo.description)); fieldAdapter.notifyDataSetChanged(); } @Override public void onBackPressed() { isExit(); } public void ButtonClick(View v) { switch (v.getId()) { case R.id.exit: XMPPConnection connection = XmppConnectionManager.getInstance().getConnection(); if (connection.isConnected()) { connection.disconnect(); } stopService(); MessageManager.destroy(); NoticeManager.destroy(); FriendManager.destroy(); appContext.setUserLogout(); AppManager.getAppManager().finishAllActivity(); startActivity(new Intent(this, Login.class)); break; default: PhotoChooseOption(); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode != RESULT_OK) { return; } String newPhotoPath; switch (requestCode) { case ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA: if (StringUtils.notEmpty(theLarge)) { File file = new File(theLarge); File dir = new File( ImageUtils.CACHE_IMAGE_FILE_PATH); if (!dir.exists()) { dir.mkdirs(); } String imagePathAfterCompass = ImageUtils.CACHE_IMAGE_FILE_PATH + file.getName(); try { ExifInterface sourceExif = new ExifInterface(theLarge); String orientation = sourceExif.getAttribute(ExifInterface.TAG_ORIENTATION); ImageUtils.saveImageToSD(imagePathAfterCompass, ImageUtils.getSmallBitmap(theLarge, 200), 80); ExifInterface exif = new ExifInterface(imagePathAfterCompass); exif.setAttribute(ExifInterface.TAG_ORIENTATION, orientation); exif.saveAttributes(); newPhotoPath = imagePathAfterCompass; uploadPhotoService(newPhotoPath); } catch (IOException e) { // Crashlytics.logException(e); } } break; case ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD: if(data == null) return; Uri thisUri = data.getData(); String thePath = ImageUtils.getAbsolutePathFromNoStandardUri(thisUri); if(StringUtils.empty(thePath)) { newPhotoPath = ImageUtils.getAbsoluteImagePath(this,thisUri); } else { newPhotoPath = thePath; } File file = new File(newPhotoPath); File dir = new File( ImageUtils.CACHE_IMAGE_FILE_PATH); if (!dir.exists()) { dir.mkdirs(); } String imagePathAfterCompass = ImageUtils.CACHE_IMAGE_FILE_PATH + file.getName(); try { ExifInterface sourceExif = new ExifInterface(newPhotoPath); String orientation = sourceExif.getAttribute(ExifInterface.TAG_ORIENTATION); ImageUtils.saveImageToSD(imagePathAfterCompass, ImageUtils.getSmallBitmap(newPhotoPath, 200), 80); ExifInterface exif = new ExifInterface(imagePathAfterCompass); exif.setAttribute(ExifInterface.TAG_ORIENTATION, orientation); exif.saveAttributes(); newPhotoPath = imagePathAfterCompass; uploadPhotoService(newPhotoPath); } catch (IOException e) { // Crashlytics.logException(e); } break; } } private String theLarge; private void PhotoChooseOption() { closeInput(); CharSequence[] item = {"相册", "拍照"}; AlertDialog imageDialog = new AlertDialog.Builder(this).setTitle(null).setIcon(android.R.drawable.btn_star).setItems(item, new DialogInterface.OnClickListener(){ public void onClick(DialogInterface dialog, int item) { //手机选图 if( item == 0 ) { Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI); startActivityForResult(Intent.createChooser(intent, "选择图片"),ImageUtils.REQUEST_CODE_GETIMAGE_BYSDCARD); } //拍照 else if( item == 1 ) { String savePath = ""; //判断是否挂载了SD卡 String storageState = Environment.getExternalStorageState(); if(storageState.equals(Environment.MEDIA_MOUNTED)){ savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + ImageUtils.DCIM;//存放 <SUF> File savedir = new File(savePath); if (!savedir.exists()) { savedir.mkdirs(); } } //没有挂载SD卡,无法保存文件 if(StringUtils.empty(savePath)){ UIHelper.ToastMessage(Me.this, "无法保存照片,请检查SD卡是否挂载", Toast.LENGTH_SHORT); return; } String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); String fileName = "c_" + timeStamp + ".jpg";//照片命名 File out = new File(savePath, fileName); Uri uri = Uri.fromFile(out); theLarge = savePath + fileName;//该照片的绝对路径 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); startActivityForResult(intent, ImageUtils.REQUEST_CODE_GETIMAGE_BYCAMERA); } }}).create(); imageDialog.show(); } private void uploadPhotoService(String file) { pg = UIHelper.showProgress(this, "", "上传头像", true); imageLoader.displayImage("file:///"+file, avatarView, CommonValue.DisplayOptions.avatar_options); ApiClent.uploadFile(appContext.getLoginApiKey(), file, new ClientCallback() { @Override public void onSuccess(Object data) { UIHelper.dismissProgress(pg); String head = (String) data; modify("", head, ""); } @Override public void onFailure(String message) { UIHelper.dismissProgress(pg); } @Override public void onError(Exception e) { UIHelper.dismissProgress(pg); } }); } private void modify(String nickname, String head, String des) { pg = UIHelper.showProgress(this, "", "保存中", true); ApiClent.modifiedUser(appContext, appContext.getLoginApiKey(), nickname, head, des, new ClientCallback() { @Override public void onSuccess(Object data) { UIHelper.dismissProgress(pg); showToast((String)data); } @Override public void onFailure(String message) { UIHelper.dismissProgress(pg); } @Override public void onError(Exception e) { UIHelper.dismissProgress(pg); } }); } private AlertDialog textDialog; private void initTextEditDialog() { LayoutInflater inFlater = LayoutInflater.from(this); View textDialogView = inFlater.inflate(R.layout.lovecode_edit_edittext_dialog, null); final EditText ed = (EditText) textDialogView.findViewById(R.id.text); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle("编辑昵称"); builder.setView(textDialogView); builder.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (StringUtils.empty(ed.getText().toString())) { return; } datas.set(0, new KeyValue("昵称", ed.getText().toString())); fieldAdapter.notifyDataSetChanged(); modify(ed.getText().toString(), "", ""); } }); builder.setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); textDialog = builder.create(); } private AlertDialog text1Dialog; private void initdesDialog() { LayoutInflater inFlater = LayoutInflater.from(this); View textDialogView = inFlater.inflate(R.layout.lovecode_edit_edittext_dialog, null); final EditText ed = (EditText) textDialogView.findViewById(R.id.text); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle("编辑个性签名"); builder.setView(textDialogView); builder.setPositiveButton(R.string.sure, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); if (StringUtils.empty(ed.getText().toString())) { return; } datas.set(1, new KeyValue("个性签名", ed.getText().toString())); fieldAdapter.notifyDataSetChanged(); modify("", "", ed.getText().toString()); } }); builder.setNegativeButton(R.string.cancle, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); text1Dialog = builder.create(); } }
1
10
1
56981_19
package com.jackie.crawler.doubanmovie.crawl; /** * Created by Jackie on 2016/9/24 0024. */ import com.jackie.crawler.doubanmovie.constants.Constants; import com.jackie.crawler.doubanmovie.entity.Comments; import com.jackie.crawler.doubanmovie.entity.Movie; import org.htmlparser.Node; import org.htmlparser.Parser; import org.htmlparser.filters.HasAttributeFilter; import org.htmlparser.tags.LinkTag; import org.htmlparser.util.NodeList; import org.htmlparser.util.ParserException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import javax.annotation.Resource; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DouBanParsePage { protected static Movie movie; protected static Comments comments; public static int movieId = 0; public static int commentId = 0; public static void parseFromString(String content, Connection conn) throws Exception { Parser parser = new Parser(content); HasAttributeFilter filter = new HasAttributeFilter("href"); String sql1 = null; ResultSet rs1 = null; PreparedStatement pstmt1 = null; Statement stmt1 = null; List<String> nextLinkList = new ArrayList<String>(); int rowCount = 0; sql1 = "select count(*) as rowCount from record"; stmt1 = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs1 = stmt1.executeQuery(sql1); if (rs1.next()) { rowCount = rs1.getString("rowCount") != null ? Integer.parseInt(rs1.getString("rowCount")) : 0; } if (rowCount <= Constants.maxCycle) { //once rowCount is bigger than maxCycle, the new crawled link will not insert into record table try { NodeList list = parser.parse(filter); int count = list.size(); //process every link on this page for (int i = 0; i < count; i++) { Node node = list.elementAt(i); if (node instanceof LinkTag) { LinkTag link = (LinkTag) node; String nextLink = link.extractLink(); String mainUrl = Constants.MAINURL; if (nextLink.startsWith(mainUrl)) { //check if the link already exists in the database sql1 = "SELECT * FROM record WHERE URL = '" + nextLink + "'"; stmt1 = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs1 = stmt1.executeQuery(sql1); if (rs1.next()) { } else { Pattern moviePattern = Pattern.compile(Constants.MOVIE_REGULAR_EXP); Matcher movieMatcher = moviePattern.matcher(nextLink); Pattern commentPattern = Pattern.compile(Constants.COMMENT_REGULAR_EXP); Matcher commentMatcher = commentPattern.matcher(nextLink); if (movieMatcher.find() || commentMatcher.find()) { nextLinkList.add(nextLink); } } } } } if (nextLinkList.size() > 0) { conn.setAutoCommit(false); //if the link does not exist in the database, insert it sql1 = "INSERT INTO record (URL, crawled) VALUES (?,0)"; pstmt1 = conn.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS); for (String nextLinkStr : nextLinkList) { pstmt1.setString(1, nextLinkStr); pstmt1.addBatch(); System.out.println(nextLinkStr); } pstmt1.executeBatch(); conn.commit(); } } catch (Exception e) { //handle the exceptions e.printStackTrace(); System.out.println("SQLException: " + e.getMessage()); } finally { //close and release the resources of PreparedStatement, ResultSet and Statement if (pstmt1 != null) { try { pstmt1.close(); } catch (SQLException e2) { } } pstmt1 = null; if (rs1 != null) { try { rs1.close(); } catch (SQLException e1) { } } rs1 = null; if (stmt1 != null) { try { stmt1.close(); } catch (SQLException e3) { } } stmt1 = null; } } } public static void extractMovie(String url, String content, Connection conn) { System.out.println("==========Parse Movie:" + url + "============"); Document doc = Jsoup.parse(content); String sql = null; ResultSet rs = null; PreparedStatement pstmt = null; Statement stmt = null; //parse movie detail page Pattern moviePattern = Pattern.compile(Constants.MOVIE_REGULAR_EXP); Matcher movieMatcher = moviePattern.matcher(url); if (movieMatcher.find()) { Document movieDoc = Jsoup.parse(content); //if the page is movie detail page, then parse the page if (movieDoc.html().contains("导演") && movieDoc.html().contains("主演") && movieDoc.html().contains("类型") && movieDoc.html().contains("语言") && doc.getElementById("info") != null) { // String name = movieDoc.getElementById("content").getElementsByAttributeValue("property", "v:itemreviewed").text(); Elements infos = doc.getElementById("info").children(); movie = new Movie(movieId++); for (Element info : infos) { if (info.childNodeSize() > 0) { String key = info.getElementsByAttributeValue("class", "pl").text(); if ("导演".equals(key)) { movie.setDirector(info.getElementsByAttributeValue("class", "attrs").text()); } else if ("编剧".equals(key)) { movie.setScenarist(info.getElementsByAttributeValue("class", "attrs").text()); } else if ("主演".equals(key)) { movie.setActors(info.getElementsByAttributeValue("class", "attrs").text()); } else if ("类型:".equals(key)) { movie.setType(doc.getElementsByAttributeValue("property", "v:genre").text()); } else if ("制片国家/地区:".equals(key)) { Pattern patternCountry = Pattern.compile(".制片国家/地区:</span>.+[\\u4e00-\\u9fa5]+.+[\\u4e00-\\u9fa5]+\\s+<br>"); Matcher matcherCountry = patternCountry.matcher(doc.html()); if (matcherCountry.find()) { movie.setCountry(matcherCountry.group().split("</span>")[1].split("<br>")[0].trim());// for example: >制片国家/地区:</span> 中国大陆 / 香港 <br> } } else if ("语言:".equals(key)) { Pattern patternLanguage = Pattern.compile(".语言:</span>.+[\\u4e00-\\u9fa5]+.+[\\u4e00-\\u9fa5]+\\s+<br>"); Matcher matcherLanguage = patternLanguage.matcher(doc.html()); if (matcherLanguage.find()) { movie.setLanguage(matcherLanguage.group().split("</span>")[1].split("<br>")[0].trim()); } } else if ("上映日期:".equals(key)) { movie.setReleaseDate(doc.getElementsByAttributeValue("property", "v:initialReleaseDate").text()); } else if ("片长:".equals(key)) { movie.setRuntime(doc.getElementsByAttributeValue("property", "v:runtime").text()); } } } movie.setTags(doc.getElementsByClass("tags-body").text()); movie.setName(doc.getElementsByAttributeValue("property", "v:itemreviewed").text()); movie.setRatingNum(doc.getElementsByAttributeValue("property", "v:average").text()); } //add if condition for resume crawling for example the last crawl was stopped, and now resume crawling, the method extractMovie was executed, but movie was null, it will throw null exception if (movie != null) { //save the movie record try { sql = "SELECT * FROM movie WHERE name = '" + movie.getName() + "'"; stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(sql); if (rs.next()) { System.out.println(movie.getName() + "is already existed!!!"); } else { //if the link does not exist in the database, insert it sql = "INSERT INTO movie (name, director, scenarist, actors, type, country, language, releaseDate, runtime, ratingNum, tags) VALUES " + "('" + movie.getName() + "','" + movie.getDirector() + "', '" + movie.getScenarist() + "', '" + movie.getActors() + "'" + ", '" + movie.getType() + "', '" + movie.getCountry() + "', '" + movie.getLanguage() + "', '" + movie.getReleaseDate() + "'" + ", '" + movie.getRuntime() + "', '" + movie.getRatingNum() + "', '" + movie.getTags() + "')"; pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.execute(); System.out.println(">>>>>>saving " + movie.getName() + "<<<<<<"); } } catch (SQLException e) { //handle the exceptions System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); } finally { //close and release the resources of PreparedStatement, ResultSet and Statement if (pstmt != null) { try { pstmt.close(); } catch (SQLException e2) { } } pstmt = null; if (rs != null) { try { rs.close(); } catch (SQLException e1) { } } rs = null; if (stmt != null) { try { stmt.close(); } catch (SQLException e3) { } } stmt = null; } } } } public static void extractComment(String url, String content, Connection conn) { System.out.println("==========Parse Comment:" + url + "============"); String sql = null; ResultSet rs = null; PreparedStatement pstmt = null; Statement stmt = null; //parse comment page Pattern commentPattern = Pattern.compile(Constants.COMMENT_REGULAR_EXP); Matcher commentMatcher = commentPattern.matcher(url); if (commentMatcher.find()) { Document commentDoc = Jsoup.parse(content); if (commentDoc.getElementById("comments") != null) { // add to avoid exception like https://movie.douban.com/subject/25842478/comments Elements commentsElements = commentDoc.getElementById("comments").children(); comments = new Comments(commentId++); for (Element comment : commentsElements) { if (comment.getElementsByClass("fold-bd").size() < 1 && comment.children().get(1).getElementsByTag("p").size() > 0) { // to make sure the current item is the comment item rather than other info item && 检测fold-bd是查看是否有折叠,如果是折叠的评论则有fold-bd,折叠评论是指账号有异常的 String[] movies = commentDoc.getElementsByTag("h1").text().replace(" ", "").split("短评"); String commentForMovie = null; for (String movie : movies) { commentForMovie = movie; } comments.setCommentForMovie(commentForMovie); comments.setCommentInfo(comment.children().get(1).getElementsByTag("p").text());//use "comment.children().get(1).text()" can get all commentInfo like "1819 有用 桃桃淘电影 2016-10-29 即便评分再高也完全喜欢不来。我们还是太热衷主题与意义了,以至于忽视了传递主题的方式与合理性。影片为了所谓的人性深度,而刻意设计剧情和人物转折,忽视基本的人物行为轨迹,都非常让人不舒服。喜欢有深度的电影,但希望能以更巧妙的方式讲出来,而不该是现在这样。以及形式上,这不就是舞台搬演么" if (comment.getElementsByAttributeValue("class", "votes pr5").text().length() > 0) { comments.setCommentVote(Integer.parseInt(comment.getElementsByAttributeValue("class", "votes pr5").text())); } comments.setCommentAuthor(comment.getElementsByAttribute("href").get(2).text()); comments.setCommentAuthorImgUrl(comment.getElementsByAttribute("href").get(2).attr("href")); //save comment record try { sql = "SELECT * FROM comments WHERE commentInfo = '" + comments.getCommentInfo() + "'"; stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(sql); if (rs.next()) { System.out.println(comments.getCommentAuthor() + "'s comment has been saved!!!"); } else { //if the link does not exist in the database, insert it sql = "INSERT INTO comments (commentInfo, commentAuthor, commentAuthorImgUrl, commentVote, commentForMovie) VALUES " + "('" + comments.getCommentInfo() + "','" + comments.getCommentAuthor() + "', '" + comments.getCommentAuthorImgUrl() + "'" + ", '" + comments.getCommentVote() + "', '" + comments.getCommentForMovie() + "')"; pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.execute(); System.out.println(">>>>>>saving comment for " + comments.getCommentForMovie() + " by:" + comments.getCommentAuthor() + "<<<<<<"); } } catch (SQLException e) { //handle the exceptions System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); } finally { //close and release the resources of PreparedStatement, ResultSet and Statement if (pstmt != null) { try { pstmt.close(); } catch (SQLException e2) { } } pstmt = null; if (rs != null) { try { rs.close(); } catch (SQLException e1) { } } rs = null; if (stmt != null) { try { stmt.close(); } catch (SQLException e3) { } } stmt = null; } } } } } } }
DMinerJackie/JewelCrawler
src/main/java/com/jackie/crawler/doubanmovie/crawl/DouBanParsePage.java
3,572
//use "comment.children().get(1).text()" can get all commentInfo like "1819 有用 桃桃淘电影 2016-10-29 即便评分再高也完全喜欢不来。我们还是太热衷主题与意义了,以至于忽视了传递主题的方式与合理性。影片为了所谓的人性深度,而刻意设计剧情和人物转折,忽视基本的人物行为轨迹,都非常让人不舒服。喜欢有深度的电影,但希望能以更巧妙的方式讲出来,而不该是现在这样。以及形式上,这不就是舞台搬演么"
line_comment
zh-cn
package com.jackie.crawler.doubanmovie.crawl; /** * Created by Jackie on 2016/9/24 0024. */ import com.jackie.crawler.doubanmovie.constants.Constants; import com.jackie.crawler.doubanmovie.entity.Comments; import com.jackie.crawler.doubanmovie.entity.Movie; import org.htmlparser.Node; import org.htmlparser.Parser; import org.htmlparser.filters.HasAttributeFilter; import org.htmlparser.tags.LinkTag; import org.htmlparser.util.NodeList; import org.htmlparser.util.ParserException; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import javax.annotation.Resource; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DouBanParsePage { protected static Movie movie; protected static Comments comments; public static int movieId = 0; public static int commentId = 0; public static void parseFromString(String content, Connection conn) throws Exception { Parser parser = new Parser(content); HasAttributeFilter filter = new HasAttributeFilter("href"); String sql1 = null; ResultSet rs1 = null; PreparedStatement pstmt1 = null; Statement stmt1 = null; List<String> nextLinkList = new ArrayList<String>(); int rowCount = 0; sql1 = "select count(*) as rowCount from record"; stmt1 = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs1 = stmt1.executeQuery(sql1); if (rs1.next()) { rowCount = rs1.getString("rowCount") != null ? Integer.parseInt(rs1.getString("rowCount")) : 0; } if (rowCount <= Constants.maxCycle) { //once rowCount is bigger than maxCycle, the new crawled link will not insert into record table try { NodeList list = parser.parse(filter); int count = list.size(); //process every link on this page for (int i = 0; i < count; i++) { Node node = list.elementAt(i); if (node instanceof LinkTag) { LinkTag link = (LinkTag) node; String nextLink = link.extractLink(); String mainUrl = Constants.MAINURL; if (nextLink.startsWith(mainUrl)) { //check if the link already exists in the database sql1 = "SELECT * FROM record WHERE URL = '" + nextLink + "'"; stmt1 = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs1 = stmt1.executeQuery(sql1); if (rs1.next()) { } else { Pattern moviePattern = Pattern.compile(Constants.MOVIE_REGULAR_EXP); Matcher movieMatcher = moviePattern.matcher(nextLink); Pattern commentPattern = Pattern.compile(Constants.COMMENT_REGULAR_EXP); Matcher commentMatcher = commentPattern.matcher(nextLink); if (movieMatcher.find() || commentMatcher.find()) { nextLinkList.add(nextLink); } } } } } if (nextLinkList.size() > 0) { conn.setAutoCommit(false); //if the link does not exist in the database, insert it sql1 = "INSERT INTO record (URL, crawled) VALUES (?,0)"; pstmt1 = conn.prepareStatement(sql1, Statement.RETURN_GENERATED_KEYS); for (String nextLinkStr : nextLinkList) { pstmt1.setString(1, nextLinkStr); pstmt1.addBatch(); System.out.println(nextLinkStr); } pstmt1.executeBatch(); conn.commit(); } } catch (Exception e) { //handle the exceptions e.printStackTrace(); System.out.println("SQLException: " + e.getMessage()); } finally { //close and release the resources of PreparedStatement, ResultSet and Statement if (pstmt1 != null) { try { pstmt1.close(); } catch (SQLException e2) { } } pstmt1 = null; if (rs1 != null) { try { rs1.close(); } catch (SQLException e1) { } } rs1 = null; if (stmt1 != null) { try { stmt1.close(); } catch (SQLException e3) { } } stmt1 = null; } } } public static void extractMovie(String url, String content, Connection conn) { System.out.println("==========Parse Movie:" + url + "============"); Document doc = Jsoup.parse(content); String sql = null; ResultSet rs = null; PreparedStatement pstmt = null; Statement stmt = null; //parse movie detail page Pattern moviePattern = Pattern.compile(Constants.MOVIE_REGULAR_EXP); Matcher movieMatcher = moviePattern.matcher(url); if (movieMatcher.find()) { Document movieDoc = Jsoup.parse(content); //if the page is movie detail page, then parse the page if (movieDoc.html().contains("导演") && movieDoc.html().contains("主演") && movieDoc.html().contains("类型") && movieDoc.html().contains("语言") && doc.getElementById("info") != null) { // String name = movieDoc.getElementById("content").getElementsByAttributeValue("property", "v:itemreviewed").text(); Elements infos = doc.getElementById("info").children(); movie = new Movie(movieId++); for (Element info : infos) { if (info.childNodeSize() > 0) { String key = info.getElementsByAttributeValue("class", "pl").text(); if ("导演".equals(key)) { movie.setDirector(info.getElementsByAttributeValue("class", "attrs").text()); } else if ("编剧".equals(key)) { movie.setScenarist(info.getElementsByAttributeValue("class", "attrs").text()); } else if ("主演".equals(key)) { movie.setActors(info.getElementsByAttributeValue("class", "attrs").text()); } else if ("类型:".equals(key)) { movie.setType(doc.getElementsByAttributeValue("property", "v:genre").text()); } else if ("制片国家/地区:".equals(key)) { Pattern patternCountry = Pattern.compile(".制片国家/地区:</span>.+[\\u4e00-\\u9fa5]+.+[\\u4e00-\\u9fa5]+\\s+<br>"); Matcher matcherCountry = patternCountry.matcher(doc.html()); if (matcherCountry.find()) { movie.setCountry(matcherCountry.group().split("</span>")[1].split("<br>")[0].trim());// for example: >制片国家/地区:</span> 中国大陆 / 香港 <br> } } else if ("语言:".equals(key)) { Pattern patternLanguage = Pattern.compile(".语言:</span>.+[\\u4e00-\\u9fa5]+.+[\\u4e00-\\u9fa5]+\\s+<br>"); Matcher matcherLanguage = patternLanguage.matcher(doc.html()); if (matcherLanguage.find()) { movie.setLanguage(matcherLanguage.group().split("</span>")[1].split("<br>")[0].trim()); } } else if ("上映日期:".equals(key)) { movie.setReleaseDate(doc.getElementsByAttributeValue("property", "v:initialReleaseDate").text()); } else if ("片长:".equals(key)) { movie.setRuntime(doc.getElementsByAttributeValue("property", "v:runtime").text()); } } } movie.setTags(doc.getElementsByClass("tags-body").text()); movie.setName(doc.getElementsByAttributeValue("property", "v:itemreviewed").text()); movie.setRatingNum(doc.getElementsByAttributeValue("property", "v:average").text()); } //add if condition for resume crawling for example the last crawl was stopped, and now resume crawling, the method extractMovie was executed, but movie was null, it will throw null exception if (movie != null) { //save the movie record try { sql = "SELECT * FROM movie WHERE name = '" + movie.getName() + "'"; stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(sql); if (rs.next()) { System.out.println(movie.getName() + "is already existed!!!"); } else { //if the link does not exist in the database, insert it sql = "INSERT INTO movie (name, director, scenarist, actors, type, country, language, releaseDate, runtime, ratingNum, tags) VALUES " + "('" + movie.getName() + "','" + movie.getDirector() + "', '" + movie.getScenarist() + "', '" + movie.getActors() + "'" + ", '" + movie.getType() + "', '" + movie.getCountry() + "', '" + movie.getLanguage() + "', '" + movie.getReleaseDate() + "'" + ", '" + movie.getRuntime() + "', '" + movie.getRatingNum() + "', '" + movie.getTags() + "')"; pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.execute(); System.out.println(">>>>>>saving " + movie.getName() + "<<<<<<"); } } catch (SQLException e) { //handle the exceptions System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); } finally { //close and release the resources of PreparedStatement, ResultSet and Statement if (pstmt != null) { try { pstmt.close(); } catch (SQLException e2) { } } pstmt = null; if (rs != null) { try { rs.close(); } catch (SQLException e1) { } } rs = null; if (stmt != null) { try { stmt.close(); } catch (SQLException e3) { } } stmt = null; } } } } public static void extractComment(String url, String content, Connection conn) { System.out.println("==========Parse Comment:" + url + "============"); String sql = null; ResultSet rs = null; PreparedStatement pstmt = null; Statement stmt = null; //parse comment page Pattern commentPattern = Pattern.compile(Constants.COMMENT_REGULAR_EXP); Matcher commentMatcher = commentPattern.matcher(url); if (commentMatcher.find()) { Document commentDoc = Jsoup.parse(content); if (commentDoc.getElementById("comments") != null) { // add to avoid exception like https://movie.douban.com/subject/25842478/comments Elements commentsElements = commentDoc.getElementById("comments").children(); comments = new Comments(commentId++); for (Element comment : commentsElements) { if (comment.getElementsByClass("fold-bd").size() < 1 && comment.children().get(1).getElementsByTag("p").size() > 0) { // to make sure the current item is the comment item rather than other info item && 检测fold-bd是查看是否有折叠,如果是折叠的评论则有fold-bd,折叠评论是指账号有异常的 String[] movies = commentDoc.getElementsByTag("h1").text().replace(" ", "").split("短评"); String commentForMovie = null; for (String movie : movies) { commentForMovie = movie; } comments.setCommentForMovie(commentForMovie); comments.setCommentInfo(comment.children().get(1).getElementsByTag("p").text());//us <SUF> if (comment.getElementsByAttributeValue("class", "votes pr5").text().length() > 0) { comments.setCommentVote(Integer.parseInt(comment.getElementsByAttributeValue("class", "votes pr5").text())); } comments.setCommentAuthor(comment.getElementsByAttribute("href").get(2).text()); comments.setCommentAuthorImgUrl(comment.getElementsByAttribute("href").get(2).attr("href")); //save comment record try { sql = "SELECT * FROM comments WHERE commentInfo = '" + comments.getCommentInfo() + "'"; stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE); rs = stmt.executeQuery(sql); if (rs.next()) { System.out.println(comments.getCommentAuthor() + "'s comment has been saved!!!"); } else { //if the link does not exist in the database, insert it sql = "INSERT INTO comments (commentInfo, commentAuthor, commentAuthorImgUrl, commentVote, commentForMovie) VALUES " + "('" + comments.getCommentInfo() + "','" + comments.getCommentAuthor() + "', '" + comments.getCommentAuthorImgUrl() + "'" + ", '" + comments.getCommentVote() + "', '" + comments.getCommentForMovie() + "')"; pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); pstmt.execute(); System.out.println(">>>>>>saving comment for " + comments.getCommentForMovie() + " by:" + comments.getCommentAuthor() + "<<<<<<"); } } catch (SQLException e) { //handle the exceptions System.out.println("SQLException: " + e.getMessage()); System.out.println("SQLState: " + e.getSQLState()); System.out.println("VendorError: " + e.getErrorCode()); } finally { //close and release the resources of PreparedStatement, ResultSet and Statement if (pstmt != null) { try { pstmt.close(); } catch (SQLException e2) { } } pstmt = null; if (rs != null) { try { rs.close(); } catch (SQLException e1) { } } rs = null; if (stmt != null) { try { stmt.close(); } catch (SQLException e3) { } } stmt = null; } } } } } } }
0
237
0
55587_1
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.chunjun.cdc; import com.dtstack.chunjun.cdc.ddl.definition.TableIdentifier; import com.dtstack.chunjun.cdc.handler.CacheHandler; import com.dtstack.chunjun.cdc.handler.DDLHandler; import com.dtstack.chunjun.cdc.worker.WorkerManager; import com.dtstack.chunjun.element.ColumnRowData; import com.dtstack.chunjun.throwable.ChunJunRuntimeException; import org.apache.flink.api.common.functions.RichFlatMapFunction; import org.apache.flink.configuration.Configuration; import org.apache.flink.table.data.RowData; import org.apache.flink.table.data.StringData; import org.apache.flink.util.Collector; import java.util.Objects; /** * 数据(不论ddl还是dml数据)下发到对应表名下的unblock队列中,worker在轮询过程中,处理unblock数据队列中的数据,在遇到ddl数据之后,将数据队列置为block状态,并将队 * 列引用交给store处理,store在拿到队列引用之后,将队列头部的ddl数据下发到外部存储中, 并监听外部存储对ddl的反馈情况(监听工作由store中额外的线程来执行), * 此时,队列仍然处于block状态;在收到外部存储的反馈之后,将数据队列头部的ddl数据移除,同时将队列状 态回归为unblock状态,队列引用还给worker。 */ public class RestorationFlatMap extends RichFlatMapFunction<RowData, RowData> { private static final long serialVersionUID = -1936334572949200754L; private final QueuesChamberlain chamberlain; private final WorkerManager workerManager; public RestorationFlatMap(DDLHandler ddlHandler, CacheHandler cacheHandler, CdcConfig conf) { this.chamberlain = new QueuesChamberlain(ddlHandler, cacheHandler); this.workerManager = new WorkerManager(chamberlain, conf); } @Override public void open(Configuration parameters) throws Exception { workerManager.open(); chamberlain.open(); } @Override public void close() throws Exception { workerManager.close(); chamberlain.close(); } @Override public void flatMap(RowData value, Collector<RowData> out) { if (workerManager.getCollector() == null) { WrapCollector<RowData> wrapCollector = new WrapCollector<>(out); chamberlain.setCollector(wrapCollector); workerManager.setCollector(out); } if (!workerManager.isAlive()) { throw new ChunJunRuntimeException(workerManager.getException()); } put(value); } private void put(RowData rowData) { TableIdentifier tableIdentifier = getTableIdentifierFromColumnData(rowData); chamberlain.add(rowData, tableIdentifier); } /** * 从 RowData 获取对应的tableIdentifier * * @param data column row data. * @return table identifier. */ private TableIdentifier getTableIdentifierFromColumnData(RowData data) { String[] headers; if (data instanceof DdlRowData) { headers = ((DdlRowData) data).getHeaders(); } else { headers = ((ColumnRowData) data).getHeaders(); } int databaseIndex = -1; int schemaIndex = -1; int tableIndex = -1; for (int i = 0; i < Objects.requireNonNull(headers).length; i++) { if ("database".equalsIgnoreCase(headers[i])) { databaseIndex = i; continue; } if ("schema".equalsIgnoreCase(headers[i])) { schemaIndex = i; continue; } if ("table".equalsIgnoreCase(headers[i])) { tableIndex = i; } } String database = getDataFromIndex(databaseIndex, data); String schema = getDataFromIndex(schemaIndex, data); String table = getDataFromIndex(tableIndex, data); return new TableIdentifier(database, schema, table); } private String getDataFromIndex(int index, RowData data) { if (index >= 0) { StringData stringData = data.getString(index); if (null != stringData) { return stringData.toString(); } } return null; } }
DTStack/chunjun
chunjun-core/src/main/java/com/dtstack/chunjun/cdc/RestorationFlatMap.java
1,219
/** * 数据(不论ddl还是dml数据)下发到对应表名下的unblock队列中,worker在轮询过程中,处理unblock数据队列中的数据,在遇到ddl数据之后,将数据队列置为block状态,并将队 * 列引用交给store处理,store在拿到队列引用之后,将队列头部的ddl数据下发到外部存储中, 并监听外部存储对ddl的反馈情况(监听工作由store中额外的线程来执行), * 此时,队列仍然处于block状态;在收到外部存储的反馈之后,将数据队列头部的ddl数据移除,同时将队列状 态回归为unblock状态,队列引用还给worker。 */
block_comment
zh-cn
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.chunjun.cdc; import com.dtstack.chunjun.cdc.ddl.definition.TableIdentifier; import com.dtstack.chunjun.cdc.handler.CacheHandler; import com.dtstack.chunjun.cdc.handler.DDLHandler; import com.dtstack.chunjun.cdc.worker.WorkerManager; import com.dtstack.chunjun.element.ColumnRowData; import com.dtstack.chunjun.throwable.ChunJunRuntimeException; import org.apache.flink.api.common.functions.RichFlatMapFunction; import org.apache.flink.configuration.Configuration; import org.apache.flink.table.data.RowData; import org.apache.flink.table.data.StringData; import org.apache.flink.util.Collector; import java.util.Objects; /** * 数据( <SUF>*/ public class RestorationFlatMap extends RichFlatMapFunction<RowData, RowData> { private static final long serialVersionUID = -1936334572949200754L; private final QueuesChamberlain chamberlain; private final WorkerManager workerManager; public RestorationFlatMap(DDLHandler ddlHandler, CacheHandler cacheHandler, CdcConfig conf) { this.chamberlain = new QueuesChamberlain(ddlHandler, cacheHandler); this.workerManager = new WorkerManager(chamberlain, conf); } @Override public void open(Configuration parameters) throws Exception { workerManager.open(); chamberlain.open(); } @Override public void close() throws Exception { workerManager.close(); chamberlain.close(); } @Override public void flatMap(RowData value, Collector<RowData> out) { if (workerManager.getCollector() == null) { WrapCollector<RowData> wrapCollector = new WrapCollector<>(out); chamberlain.setCollector(wrapCollector); workerManager.setCollector(out); } if (!workerManager.isAlive()) { throw new ChunJunRuntimeException(workerManager.getException()); } put(value); } private void put(RowData rowData) { TableIdentifier tableIdentifier = getTableIdentifierFromColumnData(rowData); chamberlain.add(rowData, tableIdentifier); } /** * 从 RowData 获取对应的tableIdentifier * * @param data column row data. * @return table identifier. */ private TableIdentifier getTableIdentifierFromColumnData(RowData data) { String[] headers; if (data instanceof DdlRowData) { headers = ((DdlRowData) data).getHeaders(); } else { headers = ((ColumnRowData) data).getHeaders(); } int databaseIndex = -1; int schemaIndex = -1; int tableIndex = -1; for (int i = 0; i < Objects.requireNonNull(headers).length; i++) { if ("database".equalsIgnoreCase(headers[i])) { databaseIndex = i; continue; } if ("schema".equalsIgnoreCase(headers[i])) { schemaIndex = i; continue; } if ("table".equalsIgnoreCase(headers[i])) { tableIndex = i; } } String database = getDataFromIndex(databaseIndex, data); String schema = getDataFromIndex(schemaIndex, data); String table = getDataFromIndex(tableIndex, data); return new TableIdentifier(database, schema, table); } private String getDataFromIndex(int index, RowData data) { if (index >= 0) { StringData stringData = data.getString(index); if (null != stringData) { return stringData.toString(); } } return null; } }
1
282
1
9593_5
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flink.sql.localTest; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.alibaba.fastjson.JSONObject; import com.dtstack.flink.sql.Main; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; /** * @author tiezhu * @Date 2020/7/8 Wed * Company dtstack */ public class LocalTest { private static final Logger LOG = LoggerFactory.getLogger(LocalTest.class); public static void main(String[] args) throws Exception { setLogLevel("INFO"); List<String> propertiesList = new ArrayList<>(); String sqlPath = "/Users/wtz/dtstack/sql/test/FileDemoOne.sql"; Map<String, Object> conf = new HashMap<>(); JSONObject properties = new JSONObject(); //其他参数配置 properties.put("time.characteristic", "eventTime"); properties.put("timezone", TimeZone.getDefault()); properties.put("early.trigger", "1"); // 任务配置参数 conf.put("-sql", URLEncoder.encode(readSQL(sqlPath), StandardCharsets.UTF_8.name())); conf.put("-mode", "local"); conf.put("-name", "flinkStreamSQLLocalTest"); conf.put("-confProp", properties.toString()); conf.put("-pluginLoadMode", "LocalTest"); // conf.put("-checkResource", "true"); conf.put("-dirtyProperties", buildDirtyStr()); for (Map.Entry<String, Object> keyValue : conf.entrySet()) { propertiesList.add(keyValue.getKey()); propertiesList.add(keyValue.getValue().toString()); } Main.main(propertiesList.toArray(new String[0])); } private static String buildDirtyStr() { JSONObject jsonObject = new JSONObject(); jsonObject.put("type", "console"); // 多少条数据打印一次 jsonObject.put("printLimit", "100"); jsonObject.put("url", "jdbc:mysql://localhost:3306/tiezhu"); jsonObject.put("userName", "root"); jsonObject.put("password", "abc123"); jsonObject.put("isCreateTable", "false"); // 多少条数据写入一次 jsonObject.put("batchSize", "1"); jsonObject.put("tableName", "dirtyData"); return jsonObject.toJSONString(); } private static String readSQL(String sqlPath) { try { byte[] array = Files.readAllBytes(Paths.get(sqlPath)); return new String(array, StandardCharsets.UTF_8); } catch (IOException ioe) { LOG.error("Can not get the job info !!!", ioe); throw new RuntimeException(ioe); } } private static void setLogLevel(String level) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); ch.qos.logback.classic.Logger logger = loggerContext.getLogger("root"); logger.setLevel(Level.toLevel(level)); } }
DTStack/flinkStreamSQL
localTest/src/main/java/com/dtstack/flink/sql/localTest/LocalTest.java
985
// 多少条数据打印一次
line_comment
zh-cn
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dtstack.flink.sql.localTest; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.alibaba.fastjson.JSONObject; import com.dtstack.flink.sql.Main; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; /** * @author tiezhu * @Date 2020/7/8 Wed * Company dtstack */ public class LocalTest { private static final Logger LOG = LoggerFactory.getLogger(LocalTest.class); public static void main(String[] args) throws Exception { setLogLevel("INFO"); List<String> propertiesList = new ArrayList<>(); String sqlPath = "/Users/wtz/dtstack/sql/test/FileDemoOne.sql"; Map<String, Object> conf = new HashMap<>(); JSONObject properties = new JSONObject(); //其他参数配置 properties.put("time.characteristic", "eventTime"); properties.put("timezone", TimeZone.getDefault()); properties.put("early.trigger", "1"); // 任务配置参数 conf.put("-sql", URLEncoder.encode(readSQL(sqlPath), StandardCharsets.UTF_8.name())); conf.put("-mode", "local"); conf.put("-name", "flinkStreamSQLLocalTest"); conf.put("-confProp", properties.toString()); conf.put("-pluginLoadMode", "LocalTest"); // conf.put("-checkResource", "true"); conf.put("-dirtyProperties", buildDirtyStr()); for (Map.Entry<String, Object> keyValue : conf.entrySet()) { propertiesList.add(keyValue.getKey()); propertiesList.add(keyValue.getValue().toString()); } Main.main(propertiesList.toArray(new String[0])); } private static String buildDirtyStr() { JSONObject jsonObject = new JSONObject(); jsonObject.put("type", "console"); // 多少 <SUF> jsonObject.put("printLimit", "100"); jsonObject.put("url", "jdbc:mysql://localhost:3306/tiezhu"); jsonObject.put("userName", "root"); jsonObject.put("password", "abc123"); jsonObject.put("isCreateTable", "false"); // 多少条数据写入一次 jsonObject.put("batchSize", "1"); jsonObject.put("tableName", "dirtyData"); return jsonObject.toJSONString(); } private static String readSQL(String sqlPath) { try { byte[] array = Files.readAllBytes(Paths.get(sqlPath)); return new String(array, StandardCharsets.UTF_8); } catch (IOException ioe) { LOG.error("Can not get the job info !!!", ioe); throw new RuntimeException(ioe); } } private static void setLogLevel(String level) { LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory(); ch.qos.logback.classic.Logger logger = loggerContext.getLogger("root"); logger.setLevel(Level.toLevel(level)); } }
1
12
1
54132_2
package com.njfu.model; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import com.njfu.entity.Player; import com.njfu.service.PlayerService; public class PlayerModel extends AbstractTableModel{ /** * */ private static final long serialVersionUID = 1L; //定义两个集合,一个用于装表头,一个用于装数据 ArrayList rowData,columnNames; PlayerService playerService = new PlayerService(); public PlayerModel(){ columnNames = new ArrayList<>(); columnNames.add("id"); columnNames.add("账号"); columnNames.add("密码"); columnNames.add("手机"); columnNames.add("状态"); columnNames.add("金币"); columnNames.add("钻石"); columnNames.add("等级"); columnNames.add("经验"); //装数据 List <Player> list = PlayerService.showDatabase(); rowData = new ArrayList(); for(int i = 0; i< list.size();i++){ //新建一个集合---排序 ArrayList array = new ArrayList(); array.add(list.get(i).getId()); array.add(list.get(i).getAccount()); array.add(list.get(i).getPassword()); array.add(list.get(i).getPhonenum()); array.add(list.get(i).getStation()); array.add(list.get(i).getGoldnum()); array.add(list.get(i).getDiamondnum()); array.add(list.get(i).getLv()); array.add(list.get(i).getEpx()); //将集合可添加到集合 rowData.add(array); } } @Override public int getRowCount() { return this.rowData.size(); } @Override public int getColumnCount() { return this.columnNames.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return ((ArrayList)this.rowData.get(rowIndex)).get(columnIndex); } @Override public String getColumnName(int column) { return (String) this.columnNames.get(column); } }
DVKunion/Knight
src/com/njfu/model/PlayerModel.java
576
//新建一个集合---排序
line_comment
zh-cn
package com.njfu.model; import java.util.ArrayList; import java.util.List; import javax.swing.table.AbstractTableModel; import com.njfu.entity.Player; import com.njfu.service.PlayerService; public class PlayerModel extends AbstractTableModel{ /** * */ private static final long serialVersionUID = 1L; //定义两个集合,一个用于装表头,一个用于装数据 ArrayList rowData,columnNames; PlayerService playerService = new PlayerService(); public PlayerModel(){ columnNames = new ArrayList<>(); columnNames.add("id"); columnNames.add("账号"); columnNames.add("密码"); columnNames.add("手机"); columnNames.add("状态"); columnNames.add("金币"); columnNames.add("钻石"); columnNames.add("等级"); columnNames.add("经验"); //装数据 List <Player> list = PlayerService.showDatabase(); rowData = new ArrayList(); for(int i = 0; i< list.size();i++){ //新建 <SUF> ArrayList array = new ArrayList(); array.add(list.get(i).getId()); array.add(list.get(i).getAccount()); array.add(list.get(i).getPassword()); array.add(list.get(i).getPhonenum()); array.add(list.get(i).getStation()); array.add(list.get(i).getGoldnum()); array.add(list.get(i).getDiamondnum()); array.add(list.get(i).getLv()); array.add(list.get(i).getEpx()); //将集合可添加到集合 rowData.add(array); } } @Override public int getRowCount() { return this.rowData.size(); } @Override public int getColumnCount() { return this.columnNames.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return ((ArrayList)this.rowData.get(rowIndex)).get(columnIndex); } @Override public String getColumnName(int column) { return (String) this.columnNames.get(column); } }
1
13
1
13527_2
package com.dengzhou.sms; import com.dengzhou.utils.ESClient; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.get.GetIndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.query.Operator; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; public class create_sms_index { String index = "sms_logs_index"; String type = "sms_logs_type"; @Test public void create_index() throws IOException { Settings.Builder settings = Settings.builder() .put("number_of_shards", 3) .put("number_of_replicas", 1); XContentBuilder mappings = JsonXContent.contentBuilder() .startObject() .startObject("properties") .startObject("createDate") .field("type", "date") .field("format","yyyy-MM-dd") .endObject() .startObject("sendDate") .field("type", "date") .field("format", "yyyy-MM-dd") .endObject() .startObject("longCode") .field("type", "keyword") .endObject() .startObject("mobile") .field("type", "keyword") .endObject() .startObject("corpName") .field("type", "keyword") .endObject() .startObject("smsContent") .field("type", "text") .field("analyzer", "ik_max_word") .endObject() .startObject("state") .field("type", "integer") .endObject() .startObject("operatorid") .field("type", "integer") .endObject() .startObject("province") .field("type", "keyword") .endObject() .startObject("ipAddr") .field("type", "ip") .endObject() .startObject("replyTotal") .field("type", "integer") .endObject() .startObject("fee") .field("type", "long") .endObject() .endObject() .endObject(); CreateIndexRequest request = new CreateIndexRequest(index) .settings(settings) .mapping(type,mappings); RestHighLevelClient client = ESClient.getClient(); CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); System.out.println(response.toString()); } @Test public void exists() throws IOException { GetIndexRequest request = new GetIndexRequest(); request.indices(index); RestHighLevelClient client = ESClient.getClient(); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists); } @Test public void testQuery() throws IOException { // 1 创建Request对象 SearchRequest request = new SearchRequest(index); request.types(type); // 2 指定查询条件 SearchSourceBuilder builder = new SearchSourceBuilder(); builder.from(0); builder.size(5); builder.query(QueryBuilders.termQuery("province", "河北")); request.source(builder); // 3 执行查询 RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 4 获取到_source中的数据 for (SearchHit hit : response.getHits().getHits()) { Map<String, Object> result = hit.getSourceAsMap(); System.out.println(result); } } @Test public void test_terms() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.termsQuery("province","河北","河南")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse resp = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : resp.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_all() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchAllQuery()); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_field() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("smsContext","打车")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_boolean() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND)); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_multi_match() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); //builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND)); builder.query(QueryBuilders.multiMatchQuery("河北", "province", "smsContext")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()) { System.out.println(hit); } } }
DW-Zhou/ES-6.5.4
src/main/java/com/dengzhou/sms/create_sms_index.java
1,647
// 3 执行查询
line_comment
zh-cn
package com.dengzhou.sms; import com.dengzhou.utils.ESClient; import org.elasticsearch.action.admin.indices.create.CreateIndexRequest; import org.elasticsearch.action.admin.indices.create.CreateIndexResponse; import org.elasticsearch.action.admin.indices.get.GetIndexRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.json.JsonXContent; import org.elasticsearch.index.query.Operator; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.builder.SearchSourceBuilder; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Map; public class create_sms_index { String index = "sms_logs_index"; String type = "sms_logs_type"; @Test public void create_index() throws IOException { Settings.Builder settings = Settings.builder() .put("number_of_shards", 3) .put("number_of_replicas", 1); XContentBuilder mappings = JsonXContent.contentBuilder() .startObject() .startObject("properties") .startObject("createDate") .field("type", "date") .field("format","yyyy-MM-dd") .endObject() .startObject("sendDate") .field("type", "date") .field("format", "yyyy-MM-dd") .endObject() .startObject("longCode") .field("type", "keyword") .endObject() .startObject("mobile") .field("type", "keyword") .endObject() .startObject("corpName") .field("type", "keyword") .endObject() .startObject("smsContent") .field("type", "text") .field("analyzer", "ik_max_word") .endObject() .startObject("state") .field("type", "integer") .endObject() .startObject("operatorid") .field("type", "integer") .endObject() .startObject("province") .field("type", "keyword") .endObject() .startObject("ipAddr") .field("type", "ip") .endObject() .startObject("replyTotal") .field("type", "integer") .endObject() .startObject("fee") .field("type", "long") .endObject() .endObject() .endObject(); CreateIndexRequest request = new CreateIndexRequest(index) .settings(settings) .mapping(type,mappings); RestHighLevelClient client = ESClient.getClient(); CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT); System.out.println(response.toString()); } @Test public void exists() throws IOException { GetIndexRequest request = new GetIndexRequest(); request.indices(index); RestHighLevelClient client = ESClient.getClient(); boolean exists = client.indices().exists(request, RequestOptions.DEFAULT); System.out.println(exists); } @Test public void testQuery() throws IOException { // 1 创建Request对象 SearchRequest request = new SearchRequest(index); request.types(type); // 2 指定查询条件 SearchSourceBuilder builder = new SearchSourceBuilder(); builder.from(0); builder.size(5); builder.query(QueryBuilders.termQuery("province", "河北")); request.source(builder); // 3 <SUF> RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); // 4 获取到_source中的数据 for (SearchHit hit : response.getHits().getHits()) { Map<String, Object> result = hit.getSourceAsMap(); System.out.println(result); } } @Test public void test_terms() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.termsQuery("province","河北","河南")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse resp = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : resp.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_all() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchAllQuery()); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_field() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("smsContext","打车")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_match_boolean() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND)); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()){ System.out.println(hit); } } @Test public void test_multi_match() throws IOException { SearchRequest request = new SearchRequest(index); request.types(type); SearchSourceBuilder builder = new SearchSourceBuilder(); //builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND)); builder.query(QueryBuilders.multiMatchQuery("河北", "province", "smsContext")); request.source(builder); RestHighLevelClient client = ESClient.getClient(); SearchResponse response = client.search(request, RequestOptions.DEFAULT); for (SearchHit hit : response.getHits().getHits()) { System.out.println(hit); } } }
1
16
1
40745_0
package connections; import java.util.Scanner; // 这是初衷,可惜 // 方便后续改成玩网络连接 public class Connections { private static Scanner scanner; private static Connections instance; private Connections() { scanner = new Scanner(System.in); } public static Connections getInstance(){ if (instance == null){ instance = new Connections(); } return instance; } public void sendData(String data){ System.out.println(data); } public void sendData(String []data){ for (var val : data){ System.out.println(val); } } public String getData(){ return scanner.next(); } }
DaTouJun/ISETrain2023_BackEnd
v0.1/src/main/java/connections/Connections.java
169
// 这是初衷,可惜
line_comment
zh-cn
package connections; import java.util.Scanner; // 这是 <SUF> // 方便后续改成玩网络连接 public class Connections { private static Scanner scanner; private static Connections instance; private Connections() { scanner = new Scanner(System.in); } public static Connections getInstance(){ if (instance == null){ instance = new Connections(); } return instance; } public void sendData(String data){ System.out.println(data); } public void sendData(String []data){ for (var val : data){ System.out.println(val); } } public String getData(){ return scanner.next(); } }
0
10
0
15907_2
import java.util.LinkedList; public class P641 { public static void main(String[] args) { } } class MyCircularDeque { private int size = 0; private LinkedList<Integer> list = new LinkedList(); //初始化大小 public MyCircularDeque(int k) { this.size = k; } public boolean insertFront(int value) { //首先查看大小是否核算 if (list.size() == size){ return false; } list.addFirst(value); return true; } public boolean insertLast(int value) { //首先查看大小是否核算 if (list.size() == size){ return false; } list.addLast(value); return true; } public boolean deleteFront() { //判断大小是否为0,如果为0直接返回false if (list.size() == 0){ return false; } list.removeFirst(); return true; } public boolean deleteLast() { //判断大小是否为0,如果为0直接返回false if (list.size() == 0){ return false; } list.removeLast(); return true; } public int getFront() { //判断大小是否为0,如果为0直接返回-1 if (list.size() == 0){ return -1; } return list.getFirst(); } public int getRear() { if (list.size() == 0){ return -1; } return list.getLast(); } public boolean isEmpty() { return list.isEmpty(); } public boolean isFull() { return list.size() == size; } } /** * Your MyCircularDeque object will be instantiated and called as such: * MyCircularDeque obj = new MyCircularDeque(k); * boolean param_1 = obj.insertFront(value); * boolean param_2 = obj.insertLast(value); * boolean param_3 = obj.deleteFront(); * boolean param_4 = obj.deleteLast(); * int param_5 = obj.getFront(); * int param_6 = obj.getRear(); * boolean param_7 = obj.isEmpty(); * boolean param_8 = obj.isFull(); */
DaZuiZui/leetcode
P641.java
529
//首先查看大小是否核算
line_comment
zh-cn
import java.util.LinkedList; public class P641 { public static void main(String[] args) { } } class MyCircularDeque { private int size = 0; private LinkedList<Integer> list = new LinkedList(); //初始化大小 public MyCircularDeque(int k) { this.size = k; } public boolean insertFront(int value) { //首先查看大小是否核算 if (list.size() == size){ return false; } list.addFirst(value); return true; } public boolean insertLast(int value) { //首先 <SUF> if (list.size() == size){ return false; } list.addLast(value); return true; } public boolean deleteFront() { //判断大小是否为0,如果为0直接返回false if (list.size() == 0){ return false; } list.removeFirst(); return true; } public boolean deleteLast() { //判断大小是否为0,如果为0直接返回false if (list.size() == 0){ return false; } list.removeLast(); return true; } public int getFront() { //判断大小是否为0,如果为0直接返回-1 if (list.size() == 0){ return -1; } return list.getFirst(); } public int getRear() { if (list.size() == 0){ return -1; } return list.getLast(); } public boolean isEmpty() { return list.isEmpty(); } public boolean isFull() { return list.size() == size; } } /** * Your MyCircularDeque object will be instantiated and called as such: * MyCircularDeque obj = new MyCircularDeque(k); * boolean param_1 = obj.insertFront(value); * boolean param_2 = obj.insertLast(value); * boolean param_3 = obj.deleteFront(); * boolean param_4 = obj.deleteLast(); * int param_5 = obj.getFront(); * int param_6 = obj.getRear(); * boolean param_7 = obj.isEmpty(); * boolean param_8 = obj.isFull(); */
1
12
1
22440_20
package frame.http; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; @Data public class TbGameRoom extends BaseModel implements Serializable { private static final long serialVersionUID = 2011789298643005448L; /** * 下注限红1 */ private BigDecimal bottomRed1 = BigDecimal.ZERO; /** * 下注限红2 */ private BigDecimal bottomRed2 = BigDecimal.ZERO; /** * 厅主id */ private Long siteId; /** * 游戏标识 */ private String gameId; /** * 游戏名称 */ private String gameName; /** * 游戏类型 */ private String gameType; /** * 房间状态 1:正常 2:关闭 */ private Integer roomStatus; private String createBy; private String createDate; private String updateBy; private String updateDate; /** * 房间标识 */ private String roomNumber; /** * 房间名称 */ private String roomName; /** * 房间类型 1:普通房间 2:密码房间 */ private Integer roomType; /** * 是否密码房间 1:是 2:不是 */ private Integer whetherPassword; /** * 房间密码 */ private String roomPassword; /** * 桌子数目 */ private Integer tableNum; /** * 房间人数 */ private Integer roomPersons; /** * 桌子人数 */ private Integer tablePersons; /** * 税收比例 */ private BigDecimal taxRatio; /** * 房间最低金额 */ private BigDecimal minMoney; /** * 收费设置 1,收取服务费 2,税收比例收费 */ private Integer chargeType; /** * 收费值 */ private BigDecimal chargeValue; /** * 游戏底分 */ private BigDecimal roomField; /** * 货币类型 */ private int moneyType; }
DaddyXjy/ChessGameServeFrame
frame/http/TbGameRoom.java
554
/** * 货币类型 */
block_comment
zh-cn
package frame.http; import lombok.Data; import java.io.Serializable; import java.math.BigDecimal; @Data public class TbGameRoom extends BaseModel implements Serializable { private static final long serialVersionUID = 2011789298643005448L; /** * 下注限红1 */ private BigDecimal bottomRed1 = BigDecimal.ZERO; /** * 下注限红2 */ private BigDecimal bottomRed2 = BigDecimal.ZERO; /** * 厅主id */ private Long siteId; /** * 游戏标识 */ private String gameId; /** * 游戏名称 */ private String gameName; /** * 游戏类型 */ private String gameType; /** * 房间状态 1:正常 2:关闭 */ private Integer roomStatus; private String createBy; private String createDate; private String updateBy; private String updateDate; /** * 房间标识 */ private String roomNumber; /** * 房间名称 */ private String roomName; /** * 房间类型 1:普通房间 2:密码房间 */ private Integer roomType; /** * 是否密码房间 1:是 2:不是 */ private Integer whetherPassword; /** * 房间密码 */ private String roomPassword; /** * 桌子数目 */ private Integer tableNum; /** * 房间人数 */ private Integer roomPersons; /** * 桌子人数 */ private Integer tablePersons; /** * 税收比例 */ private BigDecimal taxRatio; /** * 房间最低金额 */ private BigDecimal minMoney; /** * 收费设置 1,收取服务费 2,税收比例收费 */ private Integer chargeType; /** * 收费值 */ private BigDecimal chargeValue; /** * 游戏底分 */ private BigDecimal roomField; /** * 货币类 <SUF>*/ private int moneyType; }
0
17
0
49972_6
package com.daemon.pas.presenter.player; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.MediaPlayer; import android.support.v4.content.LocalBroadcastManager; import com.daemon.framework.dutils.DLog; import com.daemon.pas.common.AppRunCache; import java.io.IOException; import java.util.List; /** * Created by Daemon on 2015/12/25. */ public class MusicPlayer implements BaseMusicPlayer, MediaPlayer.OnPreparedListener { public static final int State_Play = 0; public static final int State_Pasue = 1; public static final int State_Stop = 2; private Intent intent_update; private MediaPlayer mediaPlayer; //播放的music index 初始状态 private int play_index = 0; //当前音乐状态 private int Music_State; private List<String> musicList; private String path; private LocalBroadcastManager mLocalBroadcastManager; private IntentFilter intentFilter; private MusicPlayBroadReceiver myReceiver; private boolean isDestroy=false; public MusicPlayer(Context context) { Music_State = State_Stop; mediaPlayer = new MediaPlayer(); musicList = AppRunCache.musicList; intentFilter = new IntentFilter(); intentFilter.addAction(IntentFilterUtils.Music_Pause); intentFilter.addAction(IntentFilterUtils.Music_Resume); intentFilter.addAction(IntentFilterUtils.Music_Next); intentFilter.addAction(IntentFilterUtils.Music_Previous); intentFilter.addAction(IntentFilterUtils.Music_Play_Pause_Onlcik); intentFilter.addAction(IntentFilterUtils.Progress); intentFilter.addAction(IntentFilterUtils.Music_Reset); mLocalBroadcastManager = LocalBroadcastManager.getInstance(context); myReceiver = new MusicPlayBroadReceiver(); mLocalBroadcastManager.registerReceiver(myReceiver, intentFilter); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { //自动播放结束后 下一首 先通知 DLog.e("setOnCompletionListener"); next(); } }); DLog.e("onCreate"); mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mediaPlayer) { DLog.e("setOnSeekCompleteListener "); if (Music_State == State_Play) { mediaPlayer.start(); } } }); intent_update = new Intent(IntentFilterUtils.Progress_Update); mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) { intent_update.putExtra(IntentFilterUtils.Progress_Update, mediaPlayer.getCurrentPosition()); //DLog.e("setOnBufferingUpdateListener " + mediaPlayer.getCurrentPosition() + " " + i); mLocalBroadcastManager.sendBroadcast(intent_update); } }); play(); } /** * 对外点击播放按钮提供的方法 */ public void actionPlay() { switch (Music_State) { case State_Play: pause(); break; case State_Pasue: resume(); break; case State_Stop: Music_State = State_Play; if(mediaPlayer.getCurrentPosition()!=0){ //说明是拖拽过的 mediaPlayer.start(); sendUIAnimatorPlay(); }else { play(); } break; } } @Override public void play() { if(musicList==null || musicList.size()==0){ return; } path = musicList.get(play_index); try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(this); } catch (IOException e) { e.printStackTrace(); } DLog.e("play " + play_index); } @Override public void pause() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); Music_State = State_Pasue; mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Pause)); } DLog.e("pause " + musicList.size() + " -> " + play_index); } @Override public void resume() { if (Music_State == State_Pasue) { mediaPlayer.start(); Music_State = State_Play; mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Resume)); } DLog.e("resume " + musicList.size() + " -> " + play_index); } @Override public void seekTo(int progress) { DLog.e("接受 " + progress); mediaPlayer.seekTo(progress * mediaPlayer.getDuration() / 100); } /** * 上一首 */ public void previous() { if (play_index == 0) { sendNoPrevious(); return; } else { play_index--; } Music_State=State_Play; play(); sendCurrentPosition(); DLog.e("previous " + musicList.size() + " -> " + play_index); } /** * 下一首 */ public void next() { Music_State=State_Play; if (play_index == musicList.size() - 1) { play_index = 0; } else { play_index++; } play(); sendCurrentPosition(); DLog.e("next " + musicList.size() + " -> " + play_index); } /** * 当前显示的数据 停止上一个动画 */ private void sendCurrentPosition() { Intent intent = new Intent(IntentFilterUtils.Position); intent.putExtra(IntentFilterUtils.Index, play_index); mLocalBroadcastManager.sendBroadcast(intent); } private void reset() { play_index = 0; musicList = AppRunCache.musicList; sendCurrentPosition(); play(); } @Override public void destory() { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } mLocalBroadcastManager.unregisterReceiver(myReceiver); } /** * 通知没有上一首了 */ private void sendNoPrevious() { Intent intent = new Intent(IntentFilterUtils.Music_Previous_NO); mLocalBroadcastManager.sendBroadcast(intent); } /** * 通知 ui 改变 动画开始 显示当前歌曲信息 */ private void sendUIAnimatorPlay() { //缓存完毕 发送通知 动画 做出改变 Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK); intent.putExtra(IntentFilterUtils.Index, play_index); intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration()); mLocalBroadcastManager.sendBroadcast(intent); } @Override public void onPrepared(MediaPlayer mp) { if (Music_State != State_Stop) { //只要缓存完毕 就开始放歌 不不管现在是暂停还是播放 只要下一首就继续播放 mediaPlayer.start(); sendUIAnimatorPlay(); Music_State = State_Play; DLog.e("onPrepared pay" + musicList.size() + " -> " + play_index); }else { //只要缓冲完了 就将真个音乐的size传送 sendMusicSize(); Music_State=State_Pasue; DLog.e("onPrepared stop" + musicList.size() + " -> " + play_index); } } private void sendMusicSize() { //有位置就播放 没有就显示大小 Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK); intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration()); mLocalBroadcastManager.sendBroadcast(intent); } class MusicPlayBroadReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case IntentFilterUtils.Music_Play_Pause_Onlcik: DLog.e("Music_Play_Pause_Onlcik"); actionPlay(); break; case IntentFilterUtils.Music_Next: DLog.e("Music_Next"); next(); break; case IntentFilterUtils.Music_Previous: DLog.e("Music_Previous"); previous(); break; case IntentFilterUtils.Music_Reset: reset(); break; case IntentFilterUtils.Progress: int progress = intent.getIntExtra(IntentFilterUtils.Progress, -1); seekTo(progress); break; } } } }
Daemon1993/Pas
app/src/main/java/com/daemon/pas/presenter/player/MusicPlayer.java
2,096
//说明是拖拽过的
line_comment
zh-cn
package com.daemon.pas.presenter.player; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.MediaPlayer; import android.support.v4.content.LocalBroadcastManager; import com.daemon.framework.dutils.DLog; import com.daemon.pas.common.AppRunCache; import java.io.IOException; import java.util.List; /** * Created by Daemon on 2015/12/25. */ public class MusicPlayer implements BaseMusicPlayer, MediaPlayer.OnPreparedListener { public static final int State_Play = 0; public static final int State_Pasue = 1; public static final int State_Stop = 2; private Intent intent_update; private MediaPlayer mediaPlayer; //播放的music index 初始状态 private int play_index = 0; //当前音乐状态 private int Music_State; private List<String> musicList; private String path; private LocalBroadcastManager mLocalBroadcastManager; private IntentFilter intentFilter; private MusicPlayBroadReceiver myReceiver; private boolean isDestroy=false; public MusicPlayer(Context context) { Music_State = State_Stop; mediaPlayer = new MediaPlayer(); musicList = AppRunCache.musicList; intentFilter = new IntentFilter(); intentFilter.addAction(IntentFilterUtils.Music_Pause); intentFilter.addAction(IntentFilterUtils.Music_Resume); intentFilter.addAction(IntentFilterUtils.Music_Next); intentFilter.addAction(IntentFilterUtils.Music_Previous); intentFilter.addAction(IntentFilterUtils.Music_Play_Pause_Onlcik); intentFilter.addAction(IntentFilterUtils.Progress); intentFilter.addAction(IntentFilterUtils.Music_Reset); mLocalBroadcastManager = LocalBroadcastManager.getInstance(context); myReceiver = new MusicPlayBroadReceiver(); mLocalBroadcastManager.registerReceiver(myReceiver, intentFilter); mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { //自动播放结束后 下一首 先通知 DLog.e("setOnCompletionListener"); next(); } }); DLog.e("onCreate"); mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() { @Override public void onSeekComplete(MediaPlayer mediaPlayer) { DLog.e("setOnSeekCompleteListener "); if (Music_State == State_Play) { mediaPlayer.start(); } } }); intent_update = new Intent(IntentFilterUtils.Progress_Update); mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) { intent_update.putExtra(IntentFilterUtils.Progress_Update, mediaPlayer.getCurrentPosition()); //DLog.e("setOnBufferingUpdateListener " + mediaPlayer.getCurrentPosition() + " " + i); mLocalBroadcastManager.sendBroadcast(intent_update); } }); play(); } /** * 对外点击播放按钮提供的方法 */ public void actionPlay() { switch (Music_State) { case State_Play: pause(); break; case State_Pasue: resume(); break; case State_Stop: Music_State = State_Play; if(mediaPlayer.getCurrentPosition()!=0){ //说明 <SUF> mediaPlayer.start(); sendUIAnimatorPlay(); }else { play(); } break; } } @Override public void play() { if(musicList==null || musicList.size()==0){ return; } path = musicList.get(play_index); try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.prepareAsync(); mediaPlayer.setOnPreparedListener(this); } catch (IOException e) { e.printStackTrace(); } DLog.e("play " + play_index); } @Override public void pause() { if (mediaPlayer != null && mediaPlayer.isPlaying()) { mediaPlayer.pause(); Music_State = State_Pasue; mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Pause)); } DLog.e("pause " + musicList.size() + " -> " + play_index); } @Override public void resume() { if (Music_State == State_Pasue) { mediaPlayer.start(); Music_State = State_Play; mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Resume)); } DLog.e("resume " + musicList.size() + " -> " + play_index); } @Override public void seekTo(int progress) { DLog.e("接受 " + progress); mediaPlayer.seekTo(progress * mediaPlayer.getDuration() / 100); } /** * 上一首 */ public void previous() { if (play_index == 0) { sendNoPrevious(); return; } else { play_index--; } Music_State=State_Play; play(); sendCurrentPosition(); DLog.e("previous " + musicList.size() + " -> " + play_index); } /** * 下一首 */ public void next() { Music_State=State_Play; if (play_index == musicList.size() - 1) { play_index = 0; } else { play_index++; } play(); sendCurrentPosition(); DLog.e("next " + musicList.size() + " -> " + play_index); } /** * 当前显示的数据 停止上一个动画 */ private void sendCurrentPosition() { Intent intent = new Intent(IntentFilterUtils.Position); intent.putExtra(IntentFilterUtils.Index, play_index); mLocalBroadcastManager.sendBroadcast(intent); } private void reset() { play_index = 0; musicList = AppRunCache.musicList; sendCurrentPosition(); play(); } @Override public void destory() { if (mediaPlayer != null) { mediaPlayer.stop(); mediaPlayer.release(); mediaPlayer = null; } mLocalBroadcastManager.unregisterReceiver(myReceiver); } /** * 通知没有上一首了 */ private void sendNoPrevious() { Intent intent = new Intent(IntentFilterUtils.Music_Previous_NO); mLocalBroadcastManager.sendBroadcast(intent); } /** * 通知 ui 改变 动画开始 显示当前歌曲信息 */ private void sendUIAnimatorPlay() { //缓存完毕 发送通知 动画 做出改变 Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK); intent.putExtra(IntentFilterUtils.Index, play_index); intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration()); mLocalBroadcastManager.sendBroadcast(intent); } @Override public void onPrepared(MediaPlayer mp) { if (Music_State != State_Stop) { //只要缓存完毕 就开始放歌 不不管现在是暂停还是播放 只要下一首就继续播放 mediaPlayer.start(); sendUIAnimatorPlay(); Music_State = State_Play; DLog.e("onPrepared pay" + musicList.size() + " -> " + play_index); }else { //只要缓冲完了 就将真个音乐的size传送 sendMusicSize(); Music_State=State_Pasue; DLog.e("onPrepared stop" + musicList.size() + " -> " + play_index); } } private void sendMusicSize() { //有位置就播放 没有就显示大小 Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK); intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration()); mLocalBroadcastManager.sendBroadcast(intent); } class MusicPlayBroadReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { switch (intent.getAction()) { case IntentFilterUtils.Music_Play_Pause_Onlcik: DLog.e("Music_Play_Pause_Onlcik"); actionPlay(); break; case IntentFilterUtils.Music_Next: DLog.e("Music_Next"); next(); break; case IntentFilterUtils.Music_Previous: DLog.e("Music_Previous"); previous(); break; case IntentFilterUtils.Music_Reset: reset(); break; case IntentFilterUtils.Progress: int progress = intent.getIntExtra(IntentFilterUtils.Progress, -1); seekTo(progress); break; } } } }
1
9
1
44720_0
package main.Array; public interface Array { //查找对付 public int find(String element); //插入 public void insert(String element); //删除 public void delete(String element); //列出所有元素 public void display(); }
Daemonxiao/DataStructures
src/main/Array/Array.java
60
//查找对付
line_comment
zh-cn
package main.Array; public interface Array { //查找 <SUF> public int find(String element); //插入 public void insert(String element); //删除 public void delete(String element); //列出所有元素 public void display(); }
1
6
1
21745_12
package utils; import Jama.Matrix; import Jama.SingularValueDecomposition; import java.util.*; public class LSA { private Matrix matrix; private int truncatedDimension = Integer.MAX_VALUE; public LSA(double[][] matrix) { this.matrix = Matrix.constructWithCopy(matrix); } public void setTruncatedDimension(int dimension){ this.truncatedDimension = dimension; } public Matrix lsa() { Matrix u = geU(); Matrix s = geS(); Matrix v = geV(); return transform(u, s , v); } /** * 打印矩阵 * * @param matrix */ public void printMatrix(Matrix matrix) { for (int i = 0; i < matrix.getRowDimension(); i++) { for (int j = 0; j < matrix.getColumnDimension(); j++) { System.out.printf("m(%d,%d) = %g\t", i, j, matrix.get(i, j)); } System.out.printf("\n"); } } /** * SVD分解,降维 */ public Matrix geV() { SingularValueDecomposition svd = matrix.svd(); // 注意,这里是v的转置 Matrix v = svd.getV().transpose(); return v; } public Matrix geU() { SingularValueDecomposition svd = matrix.svd(); Matrix u = svd.getU(); return u; } public Matrix geS() { SingularValueDecomposition svd = matrix.svd(); Matrix s = svd.getS(); return s; } /** * 计算相似度 * * @param v1 * @param v2 */ double cos(List<Double> v1, List<Double> v2, int dim) { // Cos(theta) = A(dot)B / |A||B| double a_dot_b = 0; for (int i = 0; i < dim; i++) { a_dot_b += v1.get(i) * v2.get(i); } double A = 0; for (int j = 0; j < dim; j++) { A += v1.get(j) * v1.get(j); } A = Math.sqrt(A); double B = 0; for (int k = 0; k < dim; k++) { B += v2.get(k) * v2.get(k); } B = Math.sqrt(B); return a_dot_b / (A * B); } public Matrix transform(Matrix u, Matrix s, Matrix v){ int notZeroLength = 0; for (int i = 0; i < s.getRowDimension(); i++){ if (s.get(i,i) >= 0){ notZeroLength++; // 统计>=0的特征值个数 } } Matrix newUMatrix = new Matrix(u.getRowDimension(), notZeroLength); Matrix newSMatrix = new Matrix(notZeroLength, notZeroLength); Matrix newVMatrix = new Matrix(notZeroLength, v.getColumnDimension()); if (truncatedDimension < Math.min(matrix.getRowDimension(), matrix.getColumnDimension())){ for (int i = 0; i < u.getRowDimension(); i++){ for (int j = 0; j < truncatedDimension; j++){ newUMatrix.set(i, j, u.get(i,j)); } } for (int i = 0; i < truncatedDimension; i++){ for (int j = 0; j < truncatedDimension; j++){ newSMatrix.set(i, j, s.get(i,j)); } } for (int i = 0; i < truncatedDimension; i++){ for (int j = 0; j < v.getColumnDimension(); j++){ newVMatrix.set(i, j, v.get(i, j)); } } return newUMatrix.times(newSMatrix).times(newVMatrix); } for (int i = 0; i < u.getRowDimension(); i++){ for (int j = 0; j < notZeroLength; j++){ newUMatrix.set(i, j, u.get(i,j)); } } for (int i = 0; i < notZeroLength; i++){ for (int j = 0; j < notZeroLength; j++){ newSMatrix.set(i, j, s.get(i,j)); } } for (int i = 0; i < notZeroLength; i++){ for (int j = 0; j < v.getColumnDimension(); j++){ newVMatrix.set(i, j, v.get(i, j)); } } return newUMatrix.times(newSMatrix).times(newVMatrix); } /** * 计算cos距离 * * @param matrix */ public Matrix cosDistance(Matrix matrix){ int length = matrix.getColumnDimension(); Matrix res = new Matrix(matrix.getRowDimension(), matrix.getRowDimension()); for (int i = 0; i < matrix.getRowDimension(); i++) { for (int j = 0; j < matrix.getRowDimension(); j++) { ArrayList<Double> vectorX = new ArrayList<>(); ArrayList<Double> vectorY = new ArrayList<>(); double[] x = matrix.getMatrix(i, i, 0, matrix.getColumnDimension() - 1).getArray()[0]; double[] y = matrix.getMatrix(j, j, 0, matrix.getColumnDimension() - 1).getArray()[0]; for (double d : x) { vectorX.add(d); } for (double d : y) { vectorY.add(d); } res.set(i, j, 1 - cos(vectorX, vectorY, length)); } } return res; } public static void main(String[] args) { // List<String> items = new ArrayList<>(); // String item1 = "皇马 的 球员 C罗 今天 退役"; // String item2 = "梅西 是 一位 年轻 有 天赋 的 足球运动员 皇马"; // String item3 = "中国 中国科学技术大学 在 今天 实现 了 用 机器学习 来 预测 地震"; // String item4 = "复旦大学 在 自然语言处理 和 知识图谱 领域 发表了 多篇 论文"; // String item5 = "中国 在 新冠病毒 复旦大学 疫情 中 做出了 重要 贡献 自然语言处理"; // // items.add(item1); // items.add(item2); // items.add(item3); // items.add(item4); // items.add(item5); int M = 100; int N = 20; double [][] m = new double[M][N]; for(int i = 0 ; i < M ; i ++ ) { m[i] = new double[N]; for(int j = 0 ; j < N ; j++) { m[i][j] = Math.random(); } } // LSA lsa = new LSA(m); // double[][] res = lsa.lsa(); // System.out.println(res.length); // System.out.println(res[0].length); // for (int i = 0; i < res.length; i++){ // for (int j = 0; j < res[0].length; j++){ // System.out.print(res[i][j]+" "); // } // System.out.println(); // } } }
DaiJianghai/KnowledgeGraphFusion
utils/LSA.java
1,889
// String item5 = "中国 在 新冠病毒 复旦大学 疫情 中 做出了 重要 贡献 自然语言处理";
line_comment
zh-cn
package utils; import Jama.Matrix; import Jama.SingularValueDecomposition; import java.util.*; public class LSA { private Matrix matrix; private int truncatedDimension = Integer.MAX_VALUE; public LSA(double[][] matrix) { this.matrix = Matrix.constructWithCopy(matrix); } public void setTruncatedDimension(int dimension){ this.truncatedDimension = dimension; } public Matrix lsa() { Matrix u = geU(); Matrix s = geS(); Matrix v = geV(); return transform(u, s , v); } /** * 打印矩阵 * * @param matrix */ public void printMatrix(Matrix matrix) { for (int i = 0; i < matrix.getRowDimension(); i++) { for (int j = 0; j < matrix.getColumnDimension(); j++) { System.out.printf("m(%d,%d) = %g\t", i, j, matrix.get(i, j)); } System.out.printf("\n"); } } /** * SVD分解,降维 */ public Matrix geV() { SingularValueDecomposition svd = matrix.svd(); // 注意,这里是v的转置 Matrix v = svd.getV().transpose(); return v; } public Matrix geU() { SingularValueDecomposition svd = matrix.svd(); Matrix u = svd.getU(); return u; } public Matrix geS() { SingularValueDecomposition svd = matrix.svd(); Matrix s = svd.getS(); return s; } /** * 计算相似度 * * @param v1 * @param v2 */ double cos(List<Double> v1, List<Double> v2, int dim) { // Cos(theta) = A(dot)B / |A||B| double a_dot_b = 0; for (int i = 0; i < dim; i++) { a_dot_b += v1.get(i) * v2.get(i); } double A = 0; for (int j = 0; j < dim; j++) { A += v1.get(j) * v1.get(j); } A = Math.sqrt(A); double B = 0; for (int k = 0; k < dim; k++) { B += v2.get(k) * v2.get(k); } B = Math.sqrt(B); return a_dot_b / (A * B); } public Matrix transform(Matrix u, Matrix s, Matrix v){ int notZeroLength = 0; for (int i = 0; i < s.getRowDimension(); i++){ if (s.get(i,i) >= 0){ notZeroLength++; // 统计>=0的特征值个数 } } Matrix newUMatrix = new Matrix(u.getRowDimension(), notZeroLength); Matrix newSMatrix = new Matrix(notZeroLength, notZeroLength); Matrix newVMatrix = new Matrix(notZeroLength, v.getColumnDimension()); if (truncatedDimension < Math.min(matrix.getRowDimension(), matrix.getColumnDimension())){ for (int i = 0; i < u.getRowDimension(); i++){ for (int j = 0; j < truncatedDimension; j++){ newUMatrix.set(i, j, u.get(i,j)); } } for (int i = 0; i < truncatedDimension; i++){ for (int j = 0; j < truncatedDimension; j++){ newSMatrix.set(i, j, s.get(i,j)); } } for (int i = 0; i < truncatedDimension; i++){ for (int j = 0; j < v.getColumnDimension(); j++){ newVMatrix.set(i, j, v.get(i, j)); } } return newUMatrix.times(newSMatrix).times(newVMatrix); } for (int i = 0; i < u.getRowDimension(); i++){ for (int j = 0; j < notZeroLength; j++){ newUMatrix.set(i, j, u.get(i,j)); } } for (int i = 0; i < notZeroLength; i++){ for (int j = 0; j < notZeroLength; j++){ newSMatrix.set(i, j, s.get(i,j)); } } for (int i = 0; i < notZeroLength; i++){ for (int j = 0; j < v.getColumnDimension(); j++){ newVMatrix.set(i, j, v.get(i, j)); } } return newUMatrix.times(newSMatrix).times(newVMatrix); } /** * 计算cos距离 * * @param matrix */ public Matrix cosDistance(Matrix matrix){ int length = matrix.getColumnDimension(); Matrix res = new Matrix(matrix.getRowDimension(), matrix.getRowDimension()); for (int i = 0; i < matrix.getRowDimension(); i++) { for (int j = 0; j < matrix.getRowDimension(); j++) { ArrayList<Double> vectorX = new ArrayList<>(); ArrayList<Double> vectorY = new ArrayList<>(); double[] x = matrix.getMatrix(i, i, 0, matrix.getColumnDimension() - 1).getArray()[0]; double[] y = matrix.getMatrix(j, j, 0, matrix.getColumnDimension() - 1).getArray()[0]; for (double d : x) { vectorX.add(d); } for (double d : y) { vectorY.add(d); } res.set(i, j, 1 - cos(vectorX, vectorY, length)); } } return res; } public static void main(String[] args) { // List<String> items = new ArrayList<>(); // String item1 = "皇马 的 球员 C罗 今天 退役"; // String item2 = "梅西 是 一位 年轻 有 天赋 的 足球运动员 皇马"; // String item3 = "中国 中国科学技术大学 在 今天 实现 了 用 机器学习 来 预测 地震"; // String item4 = "复旦大学 在 自然语言处理 和 知识图谱 领域 发表了 多篇 论文"; // St <SUF> // // items.add(item1); // items.add(item2); // items.add(item3); // items.add(item4); // items.add(item5); int M = 100; int N = 20; double [][] m = new double[M][N]; for(int i = 0 ; i < M ; i ++ ) { m[i] = new double[N]; for(int j = 0 ; j < N ; j++) { m[i][j] = Math.random(); } } // LSA lsa = new LSA(m); // double[][] res = lsa.lsa(); // System.out.println(res.length); // System.out.println(res[0].length); // for (int i = 0; i < res.length; i++){ // for (int j = 0; j < res[0].length; j++){ // System.out.print(res[i][j]+" "); // } // System.out.println(); // } } }
0
65
0
49387_3
package com.dai.entity; import java.util.Date; /** * 店铺 * @author 18491 * */ public class Shop { private Long shopId; private String shopName; private String shopDesc; //店铺地址 private String shopAddr; //店铺联系方式 private String phone; //店铺缩略图的地址 private String shopImg; private Integer priority; private Date createTime; private Date lastEditTime; //-1:不可用 0:审核中 1:可用 private Integer enableStatus; //超级管理员给店家的提醒 private String advice; //店铺的位置 private Area area; //店铺所属人 private PersonInfo owner; //店铺的类别 private ShopCategory shopCategory; public Long getShopId() { return shopId; } public void setShopId(Long shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public String getShopDesc() { return shopDesc; } public void setShopDesc(String shopDesc) { this.shopDesc = shopDesc; } public String getShopAddr() { return shopAddr; } public void setShopAddr(String shopAddr) { this.shopAddr = shopAddr; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getShopImg() { return shopImg; } public void setShopImg(String shopImg) { this.shopImg = shopImg; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastEditTime() { return lastEditTime; } public void setLastEditTime(Date lastEditTime) { this.lastEditTime = lastEditTime; } public Integer getEnableStatus() { return enableStatus; } public void setEnableStatus(Integer enableStatus) { this.enableStatus = enableStatus; } public String getAdvice() { return advice; } public void setAdvice(String advice) { this.advice = advice; } public Area getArea() { return area; } public void setArea(Area area) { this.area = area; } public PersonInfo getOwner() { return owner; } public void setOwner(PersonInfo owner) { this.owner = owner; } public ShopCategory getShopCategory() { return shopCategory; } public void setShopCategory(ShopCategory shopCategory) { this.shopCategory = shopCategory; } }
DaiOwen/DeskMate
src/main/java/com/dai/entity/Shop.java
819
//店铺缩略图的地址
line_comment
zh-cn
package com.dai.entity; import java.util.Date; /** * 店铺 * @author 18491 * */ public class Shop { private Long shopId; private String shopName; private String shopDesc; //店铺地址 private String shopAddr; //店铺联系方式 private String phone; //店铺 <SUF> private String shopImg; private Integer priority; private Date createTime; private Date lastEditTime; //-1:不可用 0:审核中 1:可用 private Integer enableStatus; //超级管理员给店家的提醒 private String advice; //店铺的位置 private Area area; //店铺所属人 private PersonInfo owner; //店铺的类别 private ShopCategory shopCategory; public Long getShopId() { return shopId; } public void setShopId(Long shopId) { this.shopId = shopId; } public String getShopName() { return shopName; } public void setShopName(String shopName) { this.shopName = shopName; } public String getShopDesc() { return shopDesc; } public void setShopDesc(String shopDesc) { this.shopDesc = shopDesc; } public String getShopAddr() { return shopAddr; } public void setShopAddr(String shopAddr) { this.shopAddr = shopAddr; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getShopImg() { return shopImg; } public void setShopImg(String shopImg) { this.shopImg = shopImg; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getLastEditTime() { return lastEditTime; } public void setLastEditTime(Date lastEditTime) { this.lastEditTime = lastEditTime; } public Integer getEnableStatus() { return enableStatus; } public void setEnableStatus(Integer enableStatus) { this.enableStatus = enableStatus; } public String getAdvice() { return advice; } public void setAdvice(String advice) { this.advice = advice; } public Area getArea() { return area; } public void setArea(Area area) { this.area = area; } public PersonInfo getOwner() { return owner; } public void setOwner(PersonInfo owner) { this.owner = owner; } public ShopCategory getShopCategory() { return shopCategory; } public void setShopCategory(ShopCategory shopCategory) { this.shopCategory = shopCategory; } }
1
10
1
16029_8
package cn.novelweb.video.pojo; /** * <p>权衡 视频质量 和 编码速度 的枚举值</p> * <p>ultrafast(终极快),superfast(超级快),veryfast(非常快),faster(很快),</p> * <p>fast(快),medium(中等),slow(慢),slower(很慢),veryslow(非常慢)</p> * <p>ultrafast(终极快)提供最少的压缩(低编码器CPU)和最大的视频流大小</p> * <p>veryslow(非常慢)提供最佳的压缩(高编码器CPU)的同时降低视频流的大小</p> * <p>2020-02-21 15:58</p> * * @author Dai Yuanchuan **/ public enum Preset { /** * 终极快 */ ultrafast, /** * 超级快 */ superfast, /** * 非常快 */ veryfast, /** * 很快 */ faster, /** * 快 */ fast, /** * 中等 */ medium, /** * 慢 */ slow, /** * 很慢 */ slower, /** * 非常慢 */ veryslow }
DaiYuanchuan/tool
tool-video/src/main/java/cn/novelweb/video/pojo/Preset.java
331
/** * 很慢 */
block_comment
zh-cn
package cn.novelweb.video.pojo; /** * <p>权衡 视频质量 和 编码速度 的枚举值</p> * <p>ultrafast(终极快),superfast(超级快),veryfast(非常快),faster(很快),</p> * <p>fast(快),medium(中等),slow(慢),slower(很慢),veryslow(非常慢)</p> * <p>ultrafast(终极快)提供最少的压缩(低编码器CPU)和最大的视频流大小</p> * <p>veryslow(非常慢)提供最佳的压缩(高编码器CPU)的同时降低视频流的大小</p> * <p>2020-02-21 15:58</p> * * @author Dai Yuanchuan **/ public enum Preset { /** * 终极快 */ ultrafast, /** * 超级快 */ superfast, /** * 非常快 */ veryfast, /** * 很快 */ faster, /** * 快 */ fast, /** * 中等 */ medium, /** * 慢 */ slow, /** * 很慢 <SUF>*/ slower, /** * 非常慢 */ veryslow }
0
21
0
17936_11
package com.dl.common.utils; import android.text.TextUtils; import java.util.regex.Pattern; /** * created by dalang at 2018/9/3 * * 检验工具类 */ public class CheckUtil { //-----------------------------------------------正则表达式------------------------------------------------------------// /** * 正则表达式:验证手机号 */ public static final String REGEX_MOBILE="[1][3456789]\\d{9}"; /** * 正则:手机号(精确) 移动号段: 134 135 136 137 138 139 147 148 150 151 152 157 158 159 172 178 182 183 184 187 188 198 联通号段: 130 131 132 145 146 155 156 166 171 175 176 185 186 电信号段: 133 149 153 173 174 177 180 181 189 199 虚拟运营商: 170 */ public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,9])|(15[0-3,5-9])|(166)|(17[0,3,5-8])|(18[0-9])|(19[8-9]))\\d{8}$"; /** * 正则表达式:验证身份证 */ public static final String REGEX_ID_CARD = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)"; /** * 正则:汉字 */ public static final String REGEX_ZH= "^[\\u4e00-\\u9fa5]+$"; /** * 匹配由数字、26个英文字母或者下划线组成的字符串 ^\w+$ */ public static final String REGEX_ENG_NUM_="^\\w+$"; /** * 匹配由数字和26个英文字母组成的字符串 ^[A-Za-z0-9]+$ */ public static final String REGEX_ENG_NUM="^[A-Za-z0-9]+"; /** * 匹配由26个英文字母组成的字符串 ^[A-Za-z]+$ */ public static final String REGEX_ENG="^[A-Za-z]+$"; /** * 匹配由纯数字 ^[0-9]+$ */ public static final String REGEX_NUM="^[0-9]+$"; /** * 过滤特殊字符串正则 * regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]"; */ public static final String STR_SPECIAL="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]"; //-----------------------------------------------常用的检验------------------------------------------------------------// /** * 验证手机号 * @param mobile * @return true表示无问题 */ public static boolean checkMobile(String mobile) { if (TextUtils.isEmpty(mobile)) { ToastUtil.warn("手机号不能为空"); return false; } if (!Pattern.matches(REGEX_MOBILE, mobile)) { ToastUtil.warn("请输入正确的手机号"); return false; } return true; } /** * 验证密码 * @param password * @return true表示无问题 */ public static boolean checkPassword(String password) { if (TextUtils.isEmpty(password)) { ToastUtil.warn("密码不能为空"); return false; } if (password.length()<6) { ToastUtil.warn("密码不能6位"); return false; } if (Pattern.matches(REGEX_NUM, password)) { ToastUtil.warn("密码不能为纯数字"); return false; } return true; } /** * 验证面 * @param password * @param password2 * @return true表示无问题 */ public static boolean checkPassword(String password,String password2) { if (TextUtils.isEmpty(password)) { ToastUtil.warn("密码不能为空"); return false; } if (password.length()<6) { ToastUtil.warn("密码不能小于6位"); return false; } if (Pattern.matches(REGEX_NUM, password)) { ToastUtil.warn("密码不能为纯数字"); return false; } if (!password.equals(password2)) { ToastUtil.warn("两次密码输入不一致"); return false; } return true; } /** * 验证身份证 * @param idCard * @return */ public static boolean checkIdCard(String idCard) { if (TextUtils.isEmpty(idCard)) { ToastUtil.warn("身份证号不能为空"); return false; } if (Pattern.matches(REGEX_ID_CARD, idCard)) { ToastUtil.warn("请输入正确的身份证号"); return false; } return true; } /** * 验证验证码 暂时只判空 根据需求做其他处理 * @param code * @return */ public static boolean checkCode(String code) { if (TextUtils.isEmpty(code)) { ToastUtil.warn("验证码不能为空"); return false; } return true; } /** * 验证车牌号 * 1.常规车牌号:仅允许以汉字开头,后面可录入六个字符,由大写英文字母和阿拉伯数字组成。如:粤B12345; 2.武警车牌:允许前两位为大写英文字母,后面可录入五个或六个字符,由大写英文字母和阿拉伯数字组成,其中第三位可录汉字也可录大写英文字母及阿拉伯数字,第三位也可空,如:WJ警00081、WJ京1234J、WJ1234X。 3.最后一个为汉字的车牌:允许以汉字开头,后面可录入六个字符,前五位字符,由大写英文字母和阿拉伯数字组成,而最后一个字符为汉字,汉字包括“挂”、“学”、“警”、“军”、“港”、“澳”。如:粤Z1234港。 4.新军车牌:以两位为大写英文字母开头,后面以5位阿拉伯数字组成。如:BA12345。 * @param carNumber * @return */ public static boolean isCarNumberNO(String carNumber) { String carnumRegex = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[警京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{0,1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$"; return carNumber.matches(carnumRegex); } /** * 判断是否为银行卡 * @param cardId * @return */ public static boolean checkBankCard(String cardId) { if (TextUtils.isEmpty(cardId)) { ToastUtil.warn("银行卡号不能为空"); return false; } char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1)); if(bit == 'N'){ ToastUtil.warn("请输入正确的银行卡号"); return false; } if (!(cardId.charAt(cardId.length() - 1) == bit)) { ToastUtil.warn("请输入正确的银行卡号"); return false; } return true; } /** * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位 * @param nonCheckCodeCardId * @return */ private static char getBankCardCheckCode(String nonCheckCodeCardId){ if(nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0 || !nonCheckCodeCardId.matches("\\d+")) { //如果传的不是数据返回N return 'N'; } char[] chs = nonCheckCodeCardId.trim().toCharArray(); int luhmSum = 0; for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) { int k = chs[i] - '0'; if(j % 2 == 0) { k *= 2; k = k / 10 + k % 10; } luhmSum += k; } //这边+'0',不是拼接,在Java和C#中是8+0的ASCII码得到8在ASCII中的编码值,然后通过(char)转成字符'8' return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0'); } }
Dalanger/MyBaseProject
common/src/main/java/com/dl/common/utils/CheckUtil.java
2,381
//-----------------------------------------------常用的检验------------------------------------------------------------//
line_comment
zh-cn
package com.dl.common.utils; import android.text.TextUtils; import java.util.regex.Pattern; /** * created by dalang at 2018/9/3 * * 检验工具类 */ public class CheckUtil { //-----------------------------------------------正则表达式------------------------------------------------------------// /** * 正则表达式:验证手机号 */ public static final String REGEX_MOBILE="[1][3456789]\\d{9}"; /** * 正则:手机号(精确) 移动号段: 134 135 136 137 138 139 147 148 150 151 152 157 158 159 172 178 182 183 184 187 188 198 联通号段: 130 131 132 145 146 155 156 166 171 175 176 185 186 电信号段: 133 149 153 173 174 177 180 181 189 199 虚拟运营商: 170 */ public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,9])|(15[0-3,5-9])|(166)|(17[0,3,5-8])|(18[0-9])|(19[8-9]))\\d{8}$"; /** * 正则表达式:验证身份证 */ public static final String REGEX_ID_CARD = "(^\\d{15}$)|(^\\d{17}([0-9]|X)$)"; /** * 正则:汉字 */ public static final String REGEX_ZH= "^[\\u4e00-\\u9fa5]+$"; /** * 匹配由数字、26个英文字母或者下划线组成的字符串 ^\w+$ */ public static final String REGEX_ENG_NUM_="^\\w+$"; /** * 匹配由数字和26个英文字母组成的字符串 ^[A-Za-z0-9]+$ */ public static final String REGEX_ENG_NUM="^[A-Za-z0-9]+"; /** * 匹配由26个英文字母组成的字符串 ^[A-Za-z]+$ */ public static final String REGEX_ENG="^[A-Za-z]+$"; /** * 匹配由纯数字 ^[0-9]+$ */ public static final String REGEX_NUM="^[0-9]+$"; /** * 过滤特殊字符串正则 * regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]"; */ public static final String STR_SPECIAL="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]"; //-- <SUF> /** * 验证手机号 * @param mobile * @return true表示无问题 */ public static boolean checkMobile(String mobile) { if (TextUtils.isEmpty(mobile)) { ToastUtil.warn("手机号不能为空"); return false; } if (!Pattern.matches(REGEX_MOBILE, mobile)) { ToastUtil.warn("请输入正确的手机号"); return false; } return true; } /** * 验证密码 * @param password * @return true表示无问题 */ public static boolean checkPassword(String password) { if (TextUtils.isEmpty(password)) { ToastUtil.warn("密码不能为空"); return false; } if (password.length()<6) { ToastUtil.warn("密码不能6位"); return false; } if (Pattern.matches(REGEX_NUM, password)) { ToastUtil.warn("密码不能为纯数字"); return false; } return true; } /** * 验证面 * @param password * @param password2 * @return true表示无问题 */ public static boolean checkPassword(String password,String password2) { if (TextUtils.isEmpty(password)) { ToastUtil.warn("密码不能为空"); return false; } if (password.length()<6) { ToastUtil.warn("密码不能小于6位"); return false; } if (Pattern.matches(REGEX_NUM, password)) { ToastUtil.warn("密码不能为纯数字"); return false; } if (!password.equals(password2)) { ToastUtil.warn("两次密码输入不一致"); return false; } return true; } /** * 验证身份证 * @param idCard * @return */ public static boolean checkIdCard(String idCard) { if (TextUtils.isEmpty(idCard)) { ToastUtil.warn("身份证号不能为空"); return false; } if (Pattern.matches(REGEX_ID_CARD, idCard)) { ToastUtil.warn("请输入正确的身份证号"); return false; } return true; } /** * 验证验证码 暂时只判空 根据需求做其他处理 * @param code * @return */ public static boolean checkCode(String code) { if (TextUtils.isEmpty(code)) { ToastUtil.warn("验证码不能为空"); return false; } return true; } /** * 验证车牌号 * 1.常规车牌号:仅允许以汉字开头,后面可录入六个字符,由大写英文字母和阿拉伯数字组成。如:粤B12345; 2.武警车牌:允许前两位为大写英文字母,后面可录入五个或六个字符,由大写英文字母和阿拉伯数字组成,其中第三位可录汉字也可录大写英文字母及阿拉伯数字,第三位也可空,如:WJ警00081、WJ京1234J、WJ1234X。 3.最后一个为汉字的车牌:允许以汉字开头,后面可录入六个字符,前五位字符,由大写英文字母和阿拉伯数字组成,而最后一个字符为汉字,汉字包括“挂”、“学”、“警”、“军”、“港”、“澳”。如:粤Z1234港。 4.新军车牌:以两位为大写英文字母开头,后面以5位阿拉伯数字组成。如:BA12345。 * @param carNumber * @return */ public static boolean isCarNumberNO(String carNumber) { String carnumRegex = "^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[警京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{0,1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$"; return carNumber.matches(carnumRegex); } /** * 判断是否为银行卡 * @param cardId * @return */ public static boolean checkBankCard(String cardId) { if (TextUtils.isEmpty(cardId)) { ToastUtil.warn("银行卡号不能为空"); return false; } char bit = getBankCardCheckCode(cardId.substring(0, cardId.length() - 1)); if(bit == 'N'){ ToastUtil.warn("请输入正确的银行卡号"); return false; } if (!(cardId.charAt(cardId.length() - 1) == bit)) { ToastUtil.warn("请输入正确的银行卡号"); return false; } return true; } /** * 从不含校验位的银行卡卡号采用 Luhm 校验算法获得校验位 * @param nonCheckCodeCardId * @return */ private static char getBankCardCheckCode(String nonCheckCodeCardId){ if(nonCheckCodeCardId == null || nonCheckCodeCardId.trim().length() == 0 || !nonCheckCodeCardId.matches("\\d+")) { //如果传的不是数据返回N return 'N'; } char[] chs = nonCheckCodeCardId.trim().toCharArray(); int luhmSum = 0; for(int i = chs.length - 1, j = 0; i >= 0; i--, j++) { int k = chs[i] - '0'; if(j % 2 == 0) { k *= 2; k = k / 10 + k % 10; } luhmSum += k; } //这边+'0',不是拼接,在Java和C#中是8+0的ASCII码得到8在ASCII中的编码值,然后通过(char)转成字符'8' return (luhmSum % 10 == 0) ? '0' : (char)((10 - luhmSum % 10) + '0'); } }
0
116
0
39416_2
package com.damon.chain.travel2; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * 功能:链管理者,链上所有节点都在此管理 * * @author Damon * @since 2018-12-23 21:54 */ @Slf4j public class HandlerChain { private List<Handler> handlerList = new ArrayList<>(); /** * 维护当前链上位置 */ private int pos; /** * 链的长度 */ private int handlerLength; public void addHandler(Handler handler) { handlerList.add(handler); handlerLength = handlerList.size(); } public void handle(String name, double wallet) { if (CollectionUtils.isEmpty(handlerList)) { log.error("有钱,但没提供服务,{}也估计就只能步行了。", name); return; } if (pos >= handlerLength) { log.error("身上钱不够,{}也估计就只能步行了。", name); reuse(); return; } Handler handler = handlerList.get(pos++); if (Objects.isNull(handler)) { log.error("假服务,{}也估计就只能步行了。", name); reuse(); return; } handler.handleRequest(name, wallet, this); } /** * 链重新使用 */ public void reuse() { pos = 0; } }
DamonChow/design_pattern
chain/src/main/java/com/damon/chain/travel2/HandlerChain.java
388
/** * 链的长度 */
block_comment
zh-cn
package com.damon.chain.travel2; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import java.util.ArrayList; import java.util.List; import java.util.Objects; /** * 功能:链管理者,链上所有节点都在此管理 * * @author Damon * @since 2018-12-23 21:54 */ @Slf4j public class HandlerChain { private List<Handler> handlerList = new ArrayList<>(); /** * 维护当前链上位置 */ private int pos; /** * 链的长 <SUF>*/ private int handlerLength; public void addHandler(Handler handler) { handlerList.add(handler); handlerLength = handlerList.size(); } public void handle(String name, double wallet) { if (CollectionUtils.isEmpty(handlerList)) { log.error("有钱,但没提供服务,{}也估计就只能步行了。", name); return; } if (pos >= handlerLength) { log.error("身上钱不够,{}也估计就只能步行了。", name); reuse(); return; } Handler handler = handlerList.get(pos++); if (Objects.isNull(handler)) { log.error("假服务,{}也估计就只能步行了。", name); reuse(); return; } handler.handleRequest(name, wallet, this); } /** * 链重新使用 */ public void reuse() { pos = 0; } }
1
23
1
54611_4
package com.sensor.entity; import com.sensor.Generate.*; import java.util.List; /** * Created by DanLongChen on 2018/11/26 * 网络节点类 **/ public class GANode extends Nodes { private int id; //唯一标示节点 private String data;//节点的数据 private Point point;//节点位置信息 private List<GANode> neibor;//邻居 private boolean state;//是否损坏 public int getId() { return id; } public void setId(int id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } public List<GANode> getNeibor() { return neibor; } public void setNeibor(List<GANode> neibor) { this.neibor = neibor; } public boolean isState() { return state; } public void setState(boolean state) { this.state = state; } }
DanLongChen/SensorSys
src/main/java/com/sensor/entity/GANode.java
292
//是否损坏
line_comment
zh-cn
package com.sensor.entity; import com.sensor.Generate.*; import java.util.List; /** * Created by DanLongChen on 2018/11/26 * 网络节点类 **/ public class GANode extends Nodes { private int id; //唯一标示节点 private String data;//节点的数据 private Point point;//节点位置信息 private List<GANode> neibor;//邻居 private boolean state;//是否 <SUF> public int getId() { return id; } public void setId(int id) { this.id = id; } public String getData() { return data; } public void setData(String data) { this.data = data; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } public List<GANode> getNeibor() { return neibor; } public void setNeibor(List<GANode> neibor) { this.neibor = neibor; } public boolean isState() { return state; } public void setState(boolean state) { this.state = state; } }
1
6
1
54579_12
package com.iv.demo.controller; import javax.annotation.Resource; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.iv.demo.model.ApiResource; import org.apache.commons.codec.binary.Base64; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; /*请求IdentityServer4 自省端点的拦截过滤器 * @author DanniKe */ //过滤器是Filter,拦截器是Interceptor //urlPattern 定义拦截的路径,不需要此过滤器的话,注释掉即可 @WebFilter(urlPatterns = "/*", filterName="tokenFilter") public class FilterController implements Filter { @Resource private ApiResource api; @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("Filter 初始化中,认证服务器自省端点版本"); } //认证部分 @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("开始进行过滤请求,由认证服务器自省端点验证token"); boolean authenticated = false; HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse rep = (HttpServletResponse) servletResponse; //--------------给自省端点发送请求------------------------------- //--------------准备请求信息---------------------------------------- //其实一个url请求就是一组组键对值,getHeader()方法获取的是头部的你想要的 //键名后面的值,由于请求里面token的keyname是这个,倒是要是要改这里也要改 //这里面header要是没有token这个就不行,会异常 boolean authorizationHeaderExist = req.getHeader("Authorization") != null; if (!authorizationHeaderExist) { rep.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } String token = cutToken(req.getHeader("Authorization")); //获取编码后的ApiSecret和ApiName,在application.propertiesz中 String apiNameSecret = "Basic " + ApiNameSecretbase64(); //倒是可以放到配置里面去,那里统一改 String introspectEndpoint = "http://localhost:5000/connect/introspect"; //-------------创造请求---------------------------------------------- //protected HttpClient client = new DefaultHttpClient();已过时 HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(introspectEndpoint); //添加请求头 post.setHeader("Authorization", apiNameSecret); //添加请求主体(body) List<NameValuePair> urlBodys = new ArrayList<NameValuePair>(); urlBodys.add(new BasicNameValuePair("token", token)); post.setEntity(new UrlEncodedFormEntity((urlBodys))); HttpResponse response = client.execute(post); System.out.println("\nSending 'POST' request to URL : " + introspectEndpoint); System.out.println("Post parameters : " + post.getEntity()); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); //读取返回reponse的content的信息,含有决定结果 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); //注意StringBuffer不是String StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } //调试用,打印得到的请求的content System.out.println(result.toString()); //-------------------------------决定authenticated结果--------------------------- JSONObject jo = new JSONObject(result.toString()); Boolean active = jo.getBoolean("active"); if (response.getStatusLine().getStatusCode() == 200&& active==true) { String role = jo.getString("role"); authenticated = true; } //--------------------------------处理authenticated结果,决定是否发出401----------- if (authenticated) { //调用该方法后,表示过滤器经过原来的url请求处理方法 filterChain.doFilter(servletRequest, servletResponse); } else { rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } } //返回Api名字和secret的编码,请求头的一部分 public String ApiNameSecretbase64() { String result = api.getapiName()+":"+api.getapiSecret(); byte[] data=Base64.encodeBase64(result.getBytes()); return new String(data); } //处理token字符串,去掉Bearer public String cutToken(String originToken) { String[] temp = originToken.split(" "); return temp[1]; } @Override public void destroy() { System.out.println("Filter销毁中,认证服务器自省端点版本"); } }
Danni-Ke/SpringBootDemo
src/main/java/com/iv/demo/controller/FilterController.java
1,224
//-------------创造请求----------------------------------------------
line_comment
zh-cn
package com.iv.demo.controller; import javax.annotation.Resource; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import com.iv.demo.model.ApiResource; import org.apache.commons.codec.binary.Base64; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; /*请求IdentityServer4 自省端点的拦截过滤器 * @author DanniKe */ //过滤器是Filter,拦截器是Interceptor //urlPattern 定义拦截的路径,不需要此过滤器的话,注释掉即可 @WebFilter(urlPatterns = "/*", filterName="tokenFilter") public class FilterController implements Filter { @Resource private ApiResource api; @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("Filter 初始化中,认证服务器自省端点版本"); } //认证部分 @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { System.out.println("开始进行过滤请求,由认证服务器自省端点验证token"); boolean authenticated = false; HttpServletRequest req = (HttpServletRequest) servletRequest; HttpServletResponse rep = (HttpServletResponse) servletResponse; //--------------给自省端点发送请求------------------------------- //--------------准备请求信息---------------------------------------- //其实一个url请求就是一组组键对值,getHeader()方法获取的是头部的你想要的 //键名后面的值,由于请求里面token的keyname是这个,倒是要是要改这里也要改 //这里面header要是没有token这个就不行,会异常 boolean authorizationHeaderExist = req.getHeader("Authorization") != null; if (!authorizationHeaderExist) { rep.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } String token = cutToken(req.getHeader("Authorization")); //获取编码后的ApiSecret和ApiName,在application.propertiesz中 String apiNameSecret = "Basic " + ApiNameSecretbase64(); //倒是可以放到配置里面去,那里统一改 String introspectEndpoint = "http://localhost:5000/connect/introspect"; //-- <SUF> //protected HttpClient client = new DefaultHttpClient();已过时 HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(introspectEndpoint); //添加请求头 post.setHeader("Authorization", apiNameSecret); //添加请求主体(body) List<NameValuePair> urlBodys = new ArrayList<NameValuePair>(); urlBodys.add(new BasicNameValuePair("token", token)); post.setEntity(new UrlEncodedFormEntity((urlBodys))); HttpResponse response = client.execute(post); System.out.println("\nSending 'POST' request to URL : " + introspectEndpoint); System.out.println("Post parameters : " + post.getEntity()); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); //读取返回reponse的content的信息,含有决定结果 BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); //注意StringBuffer不是String StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } //调试用,打印得到的请求的content System.out.println(result.toString()); //-------------------------------决定authenticated结果--------------------------- JSONObject jo = new JSONObject(result.toString()); Boolean active = jo.getBoolean("active"); if (response.getStatusLine().getStatusCode() == 200&& active==true) { String role = jo.getString("role"); authenticated = true; } //--------------------------------处理authenticated结果,决定是否发出401----------- if (authenticated) { //调用该方法后,表示过滤器经过原来的url请求处理方法 filterChain.doFilter(servletRequest, servletResponse); } else { rep.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return; } } //返回Api名字和secret的编码,请求头的一部分 public String ApiNameSecretbase64() { String result = api.getapiName()+":"+api.getapiSecret(); byte[] data=Base64.encodeBase64(result.getBytes()); return new String(data); } //处理token字符串,去掉Bearer public String cutToken(String originToken) { String[] temp = originToken.split(" "); return temp[1]; } @Override public void destroy() { System.out.println("Filter销毁中,认证服务器自省端点版本"); } }
0
65
0
36674_17
package com.real.simhotel.presenter; import com.real.simhotel.events.BaseStatus; import com.real.simhotel.events.EventCode; import com.real.simhotel.events.TrainStatus; import com.real.simhotel.events.StatusManager; import com.real.simhotel.presenter.base.BasePresenter; import com.real.simhotel.utils.log.KLog; import com.real.simhotel.view.adapter.DynamicListAdapter; import com.real.simhotel.view.adapter.DynamicListModel; import com.real.simhotel.view.adapter.DynamicListModelFactory; import com.real.simhotel.view.fragment.student.CeoNormalFragment; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.List; /** * Created by liudan on 2016/12/19. */ public class CeoNormalPresenter extends BasePresenter{ private CeoNormalFragment mView; private List<DynamicListModel> list; public static final int CEO_DECISION_HIRE = 1; public static final int CEO_DECISION_LOAN = 2; public CeoNormalPresenter(CeoNormalFragment view){ mView = view; } public DynamicListAdapter.NormalChooseInterface getChooseInterface() { return mChooseInterface; } @Override public void handleStatus(BaseStatus event) { switch (event.getStatus()){ case EventCode.GroupCode.GROUP_CEO_HIRE_ING: //开始 增加 雇员 信息 TODO 招聘会的时间 if (list == null){ list = new ArrayList<>(); } list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?", application.training.getCurrentCycle() + "", CEO_DECISION_HIRE)); //加载列表 mView.loadList(list); application.traingingStatusManager.consumeStatus(event); break; } } @Override public void destroy() { super.destroy(); EventBus.getDefault().unregister(this); } @Override public void requestData(Object... o) { super.requestData(o); // KLog.d("id = " + application.mHotel.getId()); // list = new ArrayList(); // if (application.group.getGroupStatus() == EventCode.GroupCode.GROUP_CEO_HIRE_ING){ // //增加一条招聘信息 // // list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?", // application.training.getCurrentCycle()+"", // CEO_DECISION_HIRE)); // // } // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 80 玩 ,支出 10 玩","2016年6月")); // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 90 玩 ,支出 30 玩","2016年6月")); // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 100 玩 ,支出 30 玩","2016年7月")); // list.add(DynamicListModelFactory.modelForCeoDecisionMessage("大哥你要破产了,贷款不?","2016年9月",2)); //加载列表 // mView.loadList(list); } /** * 监听list中的选项 */ private DynamicListAdapter.NormalChooseInterface mChooseInterface = new DynamicListAdapter.NormalChooseInterface() { @Override public void onChoose(DynamicListModel model, Boolean hasConfirm) { //修改状态 mView.showLoading(); int eventCode = 0; if ( (int)model.ext == CEO_DECISION_HIRE) { eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_REJECT; if (hasConfirm) eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_CONFIRM; }else if ((int)model.ext == CEO_DECISION_LOAN){ eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_REJECT; if (hasConfirm) eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_CONFIRM; } application.traingingStatusManager.changeGroupStatus( eventCode, new StatusManager.StatusChangeListener() { @Override public void OnChangedSuccess() { mView.disMissLoading(); if (hasConfirm){ model.butonChooseInfo = "已开始"; mView.showToast("已确认"); }else { model.butonChooseInfo = "已放弃"; mView.showToast("已放弃"); } model.hasChoose = true; mView.reload(); } @Override public void OnChangedFailed(String erro) { mView.disMissLoading(); mView.showToast("请求失败请稍后再试"); } }); } }; }
Danny1451/Simhotel
app/src/main/java/com/real/simhotel/presenter/CeoNormalPresenter.java
1,267
//修改状态
line_comment
zh-cn
package com.real.simhotel.presenter; import com.real.simhotel.events.BaseStatus; import com.real.simhotel.events.EventCode; import com.real.simhotel.events.TrainStatus; import com.real.simhotel.events.StatusManager; import com.real.simhotel.presenter.base.BasePresenter; import com.real.simhotel.utils.log.KLog; import com.real.simhotel.view.adapter.DynamicListAdapter; import com.real.simhotel.view.adapter.DynamicListModel; import com.real.simhotel.view.adapter.DynamicListModelFactory; import com.real.simhotel.view.fragment.student.CeoNormalFragment; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import java.util.ArrayList; import java.util.List; /** * Created by liudan on 2016/12/19. */ public class CeoNormalPresenter extends BasePresenter{ private CeoNormalFragment mView; private List<DynamicListModel> list; public static final int CEO_DECISION_HIRE = 1; public static final int CEO_DECISION_LOAN = 2; public CeoNormalPresenter(CeoNormalFragment view){ mView = view; } public DynamicListAdapter.NormalChooseInterface getChooseInterface() { return mChooseInterface; } @Override public void handleStatus(BaseStatus event) { switch (event.getStatus()){ case EventCode.GroupCode.GROUP_CEO_HIRE_ING: //开始 增加 雇员 信息 TODO 招聘会的时间 if (list == null){ list = new ArrayList<>(); } list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?", application.training.getCurrentCycle() + "", CEO_DECISION_HIRE)); //加载列表 mView.loadList(list); application.traingingStatusManager.consumeStatus(event); break; } } @Override public void destroy() { super.destroy(); EventBus.getDefault().unregister(this); } @Override public void requestData(Object... o) { super.requestData(o); // KLog.d("id = " + application.mHotel.getId()); // list = new ArrayList(); // if (application.group.getGroupStatus() == EventCode.GroupCode.GROUP_CEO_HIRE_ING){ // //增加一条招聘信息 // // list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?", // application.training.getCurrentCycle()+"", // CEO_DECISION_HIRE)); // // } // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 80 玩 ,支出 10 玩","2016年6月")); // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 90 玩 ,支出 30 玩","2016年6月")); // list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 100 玩 ,支出 30 玩","2016年7月")); // list.add(DynamicListModelFactory.modelForCeoDecisionMessage("大哥你要破产了,贷款不?","2016年9月",2)); //加载列表 // mView.loadList(list); } /** * 监听list中的选项 */ private DynamicListAdapter.NormalChooseInterface mChooseInterface = new DynamicListAdapter.NormalChooseInterface() { @Override public void onChoose(DynamicListModel model, Boolean hasConfirm) { //修改 <SUF> mView.showLoading(); int eventCode = 0; if ( (int)model.ext == CEO_DECISION_HIRE) { eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_REJECT; if (hasConfirm) eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_CONFIRM; }else if ((int)model.ext == CEO_DECISION_LOAN){ eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_REJECT; if (hasConfirm) eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_CONFIRM; } application.traingingStatusManager.changeGroupStatus( eventCode, new StatusManager.StatusChangeListener() { @Override public void OnChangedSuccess() { mView.disMissLoading(); if (hasConfirm){ model.butonChooseInfo = "已开始"; mView.showToast("已确认"); }else { model.butonChooseInfo = "已放弃"; mView.showToast("已放弃"); } model.hasChoose = true; mView.reload(); } @Override public void OnChangedFailed(String erro) { mView.disMissLoading(); mView.showToast("请求失败请稍后再试"); } }); } }; }
1
6
1
40713_1
package com.dl.officialsite.member; import com.dl.officialsite.common.privacy.PrivacyEncrypt; import com.dl.officialsite.common.privacy.PrivacyTypeEnum; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import java.io.Serializable; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString @EqualsAndHashCode(onlyExplicitlyIncluded = true) @EntityListeners(AuditingEntityListener.class) @Entity @DynamicUpdate @Table(name = "member", schema = "dl", uniqueConstraints = { @UniqueConstraint(name = "address", columnNames = {"address"}), @UniqueConstraint(name = "tweetId", columnNames = {"tweetId"}), @UniqueConstraint(name = "githubId", columnNames = {"githubId"}), @UniqueConstraint(name = "nickName", columnNames = {"nickName"})}) public class Member implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 42) @NotNull private String address; @Column(unique = true, length = 40) @NotNull @PrivacyEncrypt(type = PrivacyTypeEnum.EMAIL) private String email; @Column(unique = true, length = 20) @NotNull private String nickName; private int role; // 0开发者,1 设计师 2产品 3运营 4 测试 5 运维 6项目经理 7 研究员 8 投资人 9 市场 10 数据分析师 11 其他 @Column(unique = true, length = 38) private String githubId; @Column(length = 20) private String tweetId; @Column(unique = true, length = 64) private String tweetScreenName; @Column(length = 20) private String telegramId; @Column(length = 20) private String wechatId; private String avatar; private String techStack; //前端 ,后端 , 全栈, 运维,DBA, UI/UX, AI, 密码学,智能合约,数据分析, 共识算法,金融,数学, 网络安全, 英语, 其他 private String programing; // optional private String interests; //兴趣 private String city; private int shareCount; private int rewardCount; @CreatedDate @Column(updatable = false) private Long createTime; @LastModifiedDate @Column(updatable = false, nullable = false) private Long updateTime; //todo private Long workStatus; private int githubStatus; private int twitterStatus; //@PrivacyEncrypt(type= CUSTOMER) @JsonIgnore private String resume; /** * 1 forbidden 0 normal */ @Column(columnDefinition = "tinyint default 0") private Integer status = 0; }
Dapp-Learning-DAO/Official-website-backend
src/main/java/com/dl/officialsite/member/Member.java
857
//前端 ,后端 , 全栈, 运维,DBA, UI/UX, AI, 密码学,智能合约,数据分析, 共识算法,金融,数学, 网络安全, 英语, 其他
line_comment
zh-cn
package com.dl.officialsite.member; import com.dl.officialsite.common.privacy.PrivacyEncrypt; import com.dl.officialsite.common.privacy.PrivacyTypeEnum; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import org.hibernate.annotations.DynamicUpdate; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.annotation.LastModifiedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import javax.validation.constraints.NotNull; import java.io.Serializable; @Getter @Setter @AllArgsConstructor @NoArgsConstructor @ToString @EqualsAndHashCode(onlyExplicitlyIncluded = true) @EntityListeners(AuditingEntityListener.class) @Entity @DynamicUpdate @Table(name = "member", schema = "dl", uniqueConstraints = { @UniqueConstraint(name = "address", columnNames = {"address"}), @UniqueConstraint(name = "tweetId", columnNames = {"tweetId"}), @UniqueConstraint(name = "githubId", columnNames = {"githubId"}), @UniqueConstraint(name = "nickName", columnNames = {"nickName"})}) public class Member implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(length = 42) @NotNull private String address; @Column(unique = true, length = 40) @NotNull @PrivacyEncrypt(type = PrivacyTypeEnum.EMAIL) private String email; @Column(unique = true, length = 20) @NotNull private String nickName; private int role; // 0开发者,1 设计师 2产品 3运营 4 测试 5 运维 6项目经理 7 研究员 8 投资人 9 市场 10 数据分析师 11 其他 @Column(unique = true, length = 38) private String githubId; @Column(length = 20) private String tweetId; @Column(unique = true, length = 64) private String tweetScreenName; @Column(length = 20) private String telegramId; @Column(length = 20) private String wechatId; private String avatar; private String techStack; //前端 <SUF> private String programing; // optional private String interests; //兴趣 private String city; private int shareCount; private int rewardCount; @CreatedDate @Column(updatable = false) private Long createTime; @LastModifiedDate @Column(updatable = false, nullable = false) private Long updateTime; //todo private Long workStatus; private int githubStatus; private int twitterStatus; //@PrivacyEncrypt(type= CUSTOMER) @JsonIgnore private String resume; /** * 1 forbidden 0 normal */ @Column(columnDefinition = "tinyint default 0") private Integer status = 0; }
1
76
1
11241_7
package cn.binarywang.wx.miniapp.bean.analysis; import com.google.gson.annotations.SerializedName; import lombok.Data; import java.io.Serializable; /** * @author <a href="https://github.com/charmingoh">Charming</a> * @since 2018-04-28 */ @Data public class WxMaVisitPage implements Serializable { private static final long serialVersionUID = -7006334774516877372L; /** * 页面路径 */ @SerializedName(value = "pagePath", alternate = "page_path") private String pagePath; /** * 访问次数 */ @SerializedName(value = "pageVisitPv", alternate = "page_visit_pv") private Long pageVisitPv; /** * 访问人数 */ @SerializedName(value = "pageVisitUv", alternate = "page_visit_uv") private Long pageVisitUv; /** * 次均停留时长 */ @SerializedName(value = "pageStayTimePv", alternate = "page_staytime_pv") private Float pageStayTimePv; /** * 进入页次数 */ @SerializedName(value = "entryPagePv", alternate = "entrypage_pv") private Long entryPagePv; /** * 退出页次数 */ @SerializedName(value = "exitPagePv", alternate = "exitpage_pv") private Long exitPagePv; /** * 转发次数 */ @SerializedName(value = "pageSharePv", alternate = "page_share_pv") private Long pageSharePv; /** * 转发人数 */ @SerializedName(value = "pageShareUv", alternate = "page_share_uv") private Long pageShareUv; }
DarLiner/weixin-java-tools
weixin-java-miniapp/src/main/java/cn/binarywang/wx/miniapp/bean/analysis/WxMaVisitPage.java
431
/** * 转发次数 */
block_comment
zh-cn
package cn.binarywang.wx.miniapp.bean.analysis; import com.google.gson.annotations.SerializedName; import lombok.Data; import java.io.Serializable; /** * @author <a href="https://github.com/charmingoh">Charming</a> * @since 2018-04-28 */ @Data public class WxMaVisitPage implements Serializable { private static final long serialVersionUID = -7006334774516877372L; /** * 页面路径 */ @SerializedName(value = "pagePath", alternate = "page_path") private String pagePath; /** * 访问次数 */ @SerializedName(value = "pageVisitPv", alternate = "page_visit_pv") private Long pageVisitPv; /** * 访问人数 */ @SerializedName(value = "pageVisitUv", alternate = "page_visit_uv") private Long pageVisitUv; /** * 次均停留时长 */ @SerializedName(value = "pageStayTimePv", alternate = "page_staytime_pv") private Float pageStayTimePv; /** * 进入页次数 */ @SerializedName(value = "entryPagePv", alternate = "entrypage_pv") private Long entryPagePv; /** * 退出页次数 */ @SerializedName(value = "exitPagePv", alternate = "exitpage_pv") private Long exitPagePv; /** * 转发次 <SUF>*/ @SerializedName(value = "pageSharePv", alternate = "page_share_pv") private Long pageSharePv; /** * 转发人数 */ @SerializedName(value = "pageShareUv", alternate = "page_share_uv") private Long pageShareUv; }
0
19
0
31343_20
package com.dark.filter; /** * 作者:DarkGao * 首次开发:2015/3/10 * */ import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletContext; import javax.servlet.ServletInputStream; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlElement; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Date; import java.io.InputStream; import java.io.FileNotFoundException; import java.io.File; import java.io.FileOutputStream; import java.io.BufferedInputStream; import java.util.HashMap; import org.apache.commons.io.FileUtils; import com.dark.util.ArrayUtils; import com.dark.util.ByteUtils; import com.dark.util.GlobInfo; public class MultiForm implements Filter { //定义http协议中用到的一些关键字常量 private final static String SIGN_BOUNDARY = "boundary="; private final static String SIGN_FORMELEMENT = "name="; private final static String SIGN_FILENAME = "filename="; private final static String SIGN_MULTIDATA = "multipart/form-data"; private final static String SIGN_CONTENTDISPOS ="Content-Disposition:"; private final static String SIGN_CONTENTTYPE = "Content-Type:"; private final static String METHOD_POST="post"; private final static Long N_MAX_CONTENTLEN=1024*1024*1024L; //最大为1G接收请求内容 private final static Integer N_CHUNKBYTES=64*1024; //一次读取64K大小 //向后续页面传递的两个Request范围key public final static String REQUEST_KEY_FORMPARTLIST="FormPartList"; public final static String REQUEST_KEY_PROGERR="ProgErr"; private final static String APP_KEY_APPNAME = "DarkUploadApp"; private final static String DEF_SAVEPATH="uploadFile"; //定义xml配置filter时加载的属性 private final static String CONFIG_AUTODELPROG="autoDelProg"; private final static String CONFIG_MAXPKGBYTES="maxPkgBytes"; private final static String CONFIG_RECVEXTLIST="recvExtList"; private final static String CONFIG_REJECTEXTLIST="rejectExtList"; private final static String CONFIG_FILESAVEPATH="fileSavePath"; private final static String CONFIG_USEORIFILENAME="useOriFileName"; //HTTP MULTPART段分界线 private String boundary = ""; private FilterConfig config=null; //文件输出流对象,为了写文件时只打开一次文件 private FileOutputStream fos=null; //private FileOutputStream fosDebug=null; //配置文件参数,从.xml中读取 private ConfigParam configParam=null; private ProgressInfo.ProErrEnum progErr=ProgressInfo.ProErrEnum.PROERR_OK; /** * 进度信息类,描述了一次上传请求的进度信息 * 该对象会用来被客户端轮询请求以获得当前传输大文件过程中的进度信息 * @author DarkGao * */ @XmlRootElement public static class ProgressInfo{ //当前进度状态 public enum ProStateEnum{ PROSTATE_NULL, //无状态 PROSTATE_LOADING, //上传数据 PROSTATE_LOADED, //上传数据完毕 PROSTATE_PARSE, //数据分析中 PROSTATE_END; //全部完毕 } //上传进度错误 public enum ProErrEnum{ PROERR_OK, //无错误 PROEFF_CFGFILE, //配置文件读取错误 PROERR_PARAM, //参数错误 PROERR_REQ_SYS, //处理请求时的系统错误,比如取得当前请求包内容异常 PROERR_REQ_RULE, //请求包规则错误 PROERR_REQ_SIZE, //请求包过大 PROERR_IO_FILE; //保存文件错误,包括无法创建指定路径,指定文件,或无法打开指定文件 } //当前接收字节数 private long curBytes=-1l; //整个http请求的总共字节数 private long totalBytes=-1l; //请求发起起始时间 private Date startTime=new Date(); //当前进度时刻时间 private Date curTime=new Date(); //当前进度状态 private ProStateEnum proState=ProStateEnum.PROSTATE_NULL; @Override public String toString(){ String result=""; result=this.getClass()+":curBytes="+curBytes+";"+ "totalBytes="+totalBytes+";"+ "startTime="+startTime+";"+ "curTime="+curTime+";"+ "proState="+proState; return result; } //取得当前进度状态 @XmlElement public ProStateEnum getProState(){ return proState; } //取得当前接收字节数 @XmlElement public Long getCurBytes(){ return curBytes; } //取得本次HTTP包全部字节数 @XmlElement public Long getTotalBytes(){ return totalBytes; } //当前时刻已经花费的时间(秒数) @XmlElement public Long getElapseSecond(){ Long nReturn=0l; nReturn=(curTime.getTime()-startTime.getTime())/1000; return nReturn; } //当前上传速度(字节/秒) @XmlElement public long getTransRate(){ long nReturn=0l; //获得花费的时间(秒) long nSeconds=getElapseSecond(); //计算当前上传速度,字节/秒 if(nSeconds>0) nReturn=curBytes/nSeconds; return nReturn; } //当前进度百分比(0--100之间的数) @XmlElement public int getTransPercent(){ int nReturn=0; if(totalBytes>0) nReturn=(int)(curBytes*100/totalBytes); return nReturn; } //当前剩余秒数(小于零为未知时间) @XmlElement public int getRemainSecond(){ int nReturn=0; long nRate=getTransRate(); if(nRate>0) nReturn=(int)((totalBytes-curBytes)/nRate); return nReturn; } //根据progId取得在context中的进度对象 //注意,进度对象都被存储在context中的Map中(Application级别的内存共享区) @SuppressWarnings("unchecked") public static ProgressInfo getProgressInfo(ServletContext context,String progId){ if (progId == null) return null; progId = progId.trim(); ProgressInfo objInfo = null; if (progId.isEmpty()) return objInfo; objInfo = new ProgressInfo(); HashMap<String,ProgressInfo> progMap=(HashMap<String,ProgressInfo>) context.getAttribute(APP_KEY_APPNAME); if (progMap != null){ ProgressInfo objTemp= (ProgressInfo)progMap.get(progId); if (objTemp != null){ objInfo.curBytes = objTemp.curBytes; objInfo.curTime = objTemp.curTime; objInfo.proState = objTemp.proState; objInfo.startTime = objTemp.startTime; objInfo.totalBytes = objTemp.totalBytes; } } return objInfo; } //从context的map中删除指定progId的进度对象 @SuppressWarnings("unchecked") public static void delProgressInfo(ServletContext context,String progId){ progId = progId.trim(); if (progId.isEmpty()) return; //如果当前上下文中Application为空,那么创建ProgressInfo字典进入Application HashMap<String,ProgressInfo> progMap = (HashMap<String,ProgressInfo>)( context.getAttribute(APP_KEY_APPNAME)); if(progMap==null) return; //对全局context中对象修改需要进行线程锁控制 synchronized(progMap){ ProgressInfo objTemp= (ProgressInfo)progMap.get(progId); progMap.remove(objTemp); if(progMap.size()<=0) context.removeAttribute(APP_KEY_APPNAME); }// end synchronized } //将当前的ProgressInfo对象加入context(Application共享内存区) @SuppressWarnings("unchecked") private static void updateProgressInfo(ServletContext context, String progId,ProgressInfo objProgress){ progId = progId.trim(); if (progId.isEmpty()) return; //如果当前上下文中Application为空,那么创建ProgressInfo字典进入Application HashMap<String,ProgressInfo> progMap = (HashMap<String,ProgressInfo>)( context.getAttribute(APP_KEY_APPNAME)); //对全局context中对象修改需要进行线程锁控制 if (progMap == null) { progMap = new HashMap<String,ProgressInfo>(31); context.setAttribute(APP_KEY_APPNAME, progMap); } //由于针对Application操作是多线程并发,所以需要加同步锁控制 synchronized(progMap){ //从字典中寻找当前ID的ProgressInfo ProgressInfo objCur = (ProgressInfo)progMap.get(progId); //如果没找到则将当前ProgressInfo加入其中 if (objCur == null){ objCur = new ProgressInfo(); progMap.put(progId, objCur); } objCur.curBytes = objProgress.curBytes; objCur.curTime = objProgress.curTime; objCur.proState = objProgress.proState; objCur.startTime = objProgress.startTime; objCur.totalBytes = objProgress.totalBytes; } } }//End ProgressInfo /** * Http Form 表单数据结构 * @author DarkGao * */ public static class FormPart implements Cloneable{ public String name=""; public String value=""; public String fileName=""; public String fileExt=""; public String contentType=""; public String fileSavePath=""; public String newFileName=""; public String newFileSavePath=""; public boolean isValid=true; public FileErrEnum fileErr=FileErrEnum.FILEERR_OK; public enum FileErrEnum{ FILEERR_OK, //保存文件成功 FILEERR_FAIL_CREATE, //创建文件失败 FILEERR_FAIL_EXT //扩展名不符合要求 } @Override public String toString(){ String result=""; result=this.getClass()+":name="+name+";"+ "value="+value+";"+ "fileName="+fileName+";"+ "fileExt="+fileExt+";"+ "contentType="+contentType+";"+ "fileSavePath="+fileSavePath+";"+ "newFileName="+newFileName+";"+ "newFileSavePath="+newFileSavePath+";"+ "isValid="+isValid+";"+ "fileErr="+fileErr; return result; } //上传表单是否为文件类型 public Boolean isFileInput(){ return !contentType.isEmpty(); } //取得上传后保存文件的大小 public Long getFileSize(){ if(!newFileSavePath.isEmpty()){ return FileUtils.sizeOf(new File(newFileSavePath)); } return 0l; } //克隆 public Object clone(){ FormPart o=null; try{ o=(FormPart)super.clone(); }catch(CloneNotSupportedException e){ e.printStackTrace(); } return o; } }//End FormPart /** * xml中filter配置信息 * 这些配置信息主要用来限制接收文件条件,比如接收的文件大小限制,扩展名限制等 * @author DarkGao * */ private class ConfigParam{ //最大请求包尺寸 public int maxPkgBytes = 0; //保存文件路径 public String fileSavePath = ""; //只接收某些扩展名列表,用','分割,例如:'jpg,txt' public String recvExtList = ""; //拒绝某些扩展名列表,用','分割,例如:'ext,com,bat' public String rejectExtList = ""; //保存文件时是否使用原文件名保存 public boolean useOriFileName = true; //是否在本次请求结束后自动删除该进度信息 public boolean autoDelProg = true; public String toString(){ String result=""; result=this.getClass()+":maxPkgBytes="+maxPkgBytes+";"+ "fileSavePath="+fileSavePath+";"+ "recvExtList="+recvExtList+";"+ "rejectExtList="+rejectExtList+";"+ "useOriFileName="+useOriFileName+";"+ "autoDelProg="+autoDelProg+";"; return result; } }//End ConfigParam /** * 将不完整的文件件片段信息写进原文件内 * 这里的文件句柄已经在之前被开启(文件已经被创建) * @param buf * @param lastForm * @return */ private Boolean appendFileSect(byte[] buf,FormPart lastForm){ Boolean result=false; if(buf.length>0 && !lastForm.newFileSavePath.isEmpty()) { try{ //将本次接收的内存区写入文件 if(fos!=null) fos.write(buf); result=true; }catch(IOException e) { e.printStackTrace(); }//end try } return result; } /** * 从局部内存区中找到Boundary段信息 * 如果从本次接收的局部内存中找到了整体的表单信息,则存入表单信息结构中 * 这里分为几种情况 * 1.本次内存区中包含了1个或多个完整的表单信息。可能还会有剩余,即不完整的表单信息 * 2.本次内存区中只包含了不完整的表单信息,比如大文件中间的某段片段信息 * * @param buf * @param scanStart * @param boundary * @param lastForm * @param curForm * @return */ private int getBoundarySectFromBuf(byte[] buf,int scanStart,String boundary, FormPart lastForm,FormPart curForm){ curForm.isValid=true; int scanEnd=-1; byte[] scanKey=ByteUtils.getBytes(boundary); if(buf.length<=0 || scanKey.length<=0){ curForm.isValid=false; return scanEnd; } //在内存区中scanStart开始位置查找boundary key int start=ArrayUtils.indexOf(buf, scanKey, scanStart); //如果没找到boundary,但buf中的确有内容,则为上一个FormPart中文件的片段信息 if(start<0) { //这里需要进行写操作 if(lastForm==null || lastForm.newFileSavePath.isEmpty()) return scanEnd; scanEnd=appendFileSect(buf,lastForm)?buf.length:scanEnd; curForm.isValid=false; return scanEnd; } //如果找到了boundary但并不是起点位置则 else if((start-scanStart)!=2) { //则将boundary前面的部分写入上一个FormPart文件中 byte[] tempBuf=ArrayUtils.copyOfRange(buf, 0, start-2); if(lastForm==null || lastForm.newFileSavePath.isEmpty()) return scanEnd; appendFileSect(tempBuf,lastForm); try{ if(fos!=null) fos.close(); fos=null; }catch(IOException e){ e.printStackTrace(); } tempBuf=null; } //对当前的form结构进行初始化 curForm.name=""; curForm.value=""; curForm.fileName=""; curForm.fileExt=""; curForm.contentType=""; curForm.newFileSavePath=""; //如果找到指定第一个boundary,则查找下一行"Content-Disposition:" start=ArrayUtils.indexOf(buf, SIGN_CONTENTDISPOS.getBytes(),start); if(start<0){ curForm.isValid=false; return scanEnd; } //取得"Content-Disposition:"的一行 ArrayUtils.LineReturn line=ArrayUtils.getLine(buf, start);//ByteUtils.getString(byteLine); if(line.line.length()<=0){ curForm.isValid=false; return scanEnd; } //取得"name=" start=line.line.indexOf(SIGN_FORMELEMENT); if(start<0){ curForm.isValid=false; return scanEnd; } String formName=line.line.substring(start+SIGN_FORMELEMENT.length()); int end=formName.indexOf(";"); if(end>0) formName=formName.substring(0, end); //去掉formName的'\"' formName=formName.replace("\"", ""); //查找"filename=" start=line.line.indexOf(SIGN_FILENAME); //如果没找到filename=,则说明为form普通字段,否则为文件二进制字段 if(start<0){ //跳过一个"\r\n" //继续搜索下一个"\r\n" line=ArrayUtils.getLine(buf, line.endIndex); line=ArrayUtils.getLine(buf, line.endIndex); curForm.name=formName; curForm.value=line.line; scanEnd=line.endIndex; } //如果找到filename= else{ curForm.name=formName; curForm.value=""; //在内存区中找到下一个boundary key end=ArrayUtils.indexOf(buf, scanKey, line.endIndex); //如果找到第二个boundary则 if(end>0){ scanEnd=end-2; } else{ scanEnd=buf.length; } //截取filename= String fileName=line.line.substring(start+SIGN_FILENAME.length()); fileName=fileName.replace("\"",""); //**?转换中文编码问题 System.out.println("fileName="+fileName); String arr[]=fileName.split("\\."); if(arr.length>1){ curForm.fileName=arr[0]; curForm.fileExt=arr[1]; } //查找下一行 line=ArrayUtils.getLine(buf, line.endIndex); start=line.line.indexOf(SIGN_CONTENTTYPE); //找到Content-Type:内容 if(!line.line.isEmpty() && start>=0){ arr=line.line.split(":"); if(arr.length==2){ curForm.contentType=arr[1].trim(); } //找到下一空行 line=ArrayUtils.getLine(buf, line.endIndex); //此处为二进制信息开始地点,开始进行写文件操作 String newFileName=curForm.newFileName.isEmpty()?curForm.fileName:curForm.newFileName; if(!newFileName.isEmpty()){ String filePath=curForm.fileSavePath+newFileName; if(!curForm.fileExt.isEmpty()) filePath+="."+curForm.fileExt; curForm.newFileSavePath=filePath; byte[] tempBuf=ArrayUtils.copyOfRange(buf, line.endIndex, scanEnd); try{ //将本次接收的内存区写入文件 if(fos!=null) fos.close(); fos=FileUtils.openOutputStream(new File(filePath),false); fos.write(tempBuf); //fos.close(); }catch(IOException e) { e.printStackTrace(); fos=null; scanEnd=-1; }//end try tempBuf=null; } }//end if } return scanEnd; } /** * 从输入的流中分段读取用户请求,边接收边进行分段解析,通过累计后,最后形成表单列表 * * @param is * @param contentLen * @param boundary * @param inputList * @param progInfo * @param context * @param progId * @return */ private Boolean parseInputStream(InputStream is,Integer contentLen, String boundary,List<FormPart> inputList, ProgressInfo progInfo,ServletContext context,String progId) { Boolean result=false; if(is==null || contentLen<=0 || boundary==null || boundary.length()<=0) return result; //更新进度信息为正在上传状态 progInfo.curTime = new Date(); progInfo.proState = ProgressInfo.ProStateEnum.PROSTATE_LOADING; ProgressInfo.updateProgressInfo(context, progId, progInfo); //System.out.println(progInfo); try { //FileOutputStream fos=FileUtils.openOutputStream(new File("D:\\fileTemp2.dat"),true); //从输入流中循环读取客户发上来的请求 //循环读取字节流,一次读取64K数据 int totalLen=0; FormPart lastForm=new FormPart(); FormPart curForm=new FormPart(); curForm.fileSavePath=this.configParam.fileSavePath; //System.out.println("fileSavePath="+curForm.fileSavePath); while (totalLen<contentLen) { //创建最大读取缓冲区 byte[] bufTemp=new byte[N_CHUNKBYTES]; int remainLen=contentLen-totalLen; //每次最多读取N_CHUNKBYTES字节 int chunkSize=is.read(bufTemp,0,(remainLen>N_CHUNKBYTES)?N_CHUNKBYTES:remainLen); if(chunkSize<=0) break; //fosDebug.write(bufTemp); byte[] buf=ArrayUtils.copyOfRange(bufTemp, 0, chunkSize); bufTemp=null; totalLen+=chunkSize; //更新进度信息为当前传输过程中进度状态 progInfo.curTime = new Date(); progInfo.curBytes = totalLen; ProgressInfo.updateProgressInfo(context, progId, progInfo); //System.out.println(progInfo); //从当前接收的缓冲区中动态解析HTML multipart信息 //这里使用到循环,主要是为了处理本次接收的最大N_CHUNKBYTES字节数据中将包含多段FormPart信息 //如果包含多段FormPart,我们需要使用循环来分解并建立对象 int bufIndex=0; while(bufIndex<buf.length){ bufIndex=getBoundarySectFromBuf(buf,bufIndex,boundary,lastForm,curForm); if(bufIndex<0) break; lastForm=curForm; //判断本次Form Part信息是否完整,如果完整则填入结果列表 if(curForm.isValid){ FormPart tempForm=(FormPart)curForm.clone(); inputList.add(tempForm); } } if(bufIndex>=0){ result=true; } buf=null; } //fos.close(); } catch (FileNotFoundException e) { //更新进度信息 e.printStackTrace(); } catch (IOException e) { //更新进度信息 e.printStackTrace(); } //更新进度信息对象为结束状态 progInfo.proState = ProgressInfo.ProStateEnum.PROSTATE_END; ProgressInfo.updateProgressInfo(context, progId, progInfo); System.out.println(progInfo); return result; } /** * 获取本次上传对应的表单元素间的分隔符,注意该分隔符是随机生成的 * @param contentType * @return */ private String getBoundary(String contentType) { String tempStr = ""; if (contentType != null && contentType.startsWith(SIGN_MULTIDATA) && contentType.indexOf(SIGN_BOUNDARY) != -1) { //获取表单每个元素的分隔符 tempStr = contentType .substring( contentType.indexOf(SIGN_BOUNDARY) + SIGN_BOUNDARY.length()).trim(); } return tempStr; } /** * 获得xml文件中配置filter的配置信息 * @param config * @param configParam */ private void getConfigParam(FilterConfig config,ConfigParam configParam){ if(config==null || configParam==null) return; configParam.autoDelProg=Boolean.parseBoolean(config.getInitParameter(CONFIG_AUTODELPROG)); configParam.maxPkgBytes=Integer.parseInt(config.getInitParameter(CONFIG_MAXPKGBYTES)); configParam.recvExtList=config.getInitParameter(CONFIG_RECVEXTLIST); configParam.rejectExtList=config.getInitParameter(CONFIG_REJECTEXTLIST); configParam.fileSavePath=config.getInitParameter(CONFIG_FILESAVEPATH); configParam.useOriFileName=Boolean.parseBoolean(config.getInitParameter(CONFIG_USEORIFILENAME)); System.out.println(configParam); } /** * 检查所有请求表单项中的文件扩展名是否符合xml中配置选项 * @param listFormPart */ private void checkFileExt(List<FormPart> listFormPart){ //检查用户上传的文件扩展名 String[] recvExtArr=null; if(!configParam.recvExtList.isEmpty()) recvExtArr=configParam.recvExtList.split(","); String[] rejectExtArr=null; if(!configParam.rejectExtList.isEmpty()) rejectExtArr=configParam.rejectExtList.split(","); Boolean recvAll=true; //寻找"*" for(int i=0;i<recvExtArr.length;i++){ if(recvExtArr[i].equalsIgnoreCase("*")){ recvAll=false; break; } } for(int i=0;i<listFormPart.size();i++){ FormPart part=listFormPart.get(i); Boolean isDel=false; //如果接受所有扩展名,则需要检查rejectExtArr中内容 if(recvAll){ isDel=false; if(rejectExtArr!=null){ for(int j=0;j<rejectExtArr.length;j++){ if(part.fileExt.equalsIgnoreCase(rejectExtArr[j])){ isDel=true; break; } } } } //否则只检查recvExtArr内容 else if(recvExtArr.length>0){ isDel=true; if(recvExtArr!=null){ for(int j=0;j<recvExtArr.length;j++){ if(part.fileExt.equalsIgnoreCase(recvExtArr[j])){ isDel=false; break; } } } } if(isDel){ //删除该文件并标记该文件不符合要求 File file=new File(part.newFileSavePath); file.delete(); part.fileErr=FormPart.FileErrEnum.FILEERR_FAIL_EXT; } System.out.println(part); } } /** * 初始化Filter * 主要完成了加载xml文件中的filter配置信息 * 以及根据xml文件中的文件保存路径以及本app的系统目录创建最终的文件保存路径 */ @Override public void init(FilterConfig filterConfig) throws ServletException { this.config=filterConfig; this.configParam=new ConfigParam(); //加载来自XML的SAVEPATH //this.savePath=config.getInitParameter("savePath"); getConfigParam(this.config,this.configParam); System.out.println(configParam); String savePath=this.configParam.fileSavePath; if(savePath==null || savePath.isEmpty()) savePath=DEF_SAVEPATH; //取得系统当前目录 String appPath=GlobInfo.getAppPath(this); appPath=appPath.replace('/', '\\'); savePath=appPath+savePath; if(savePath.charAt(savePath.length()-1)!='\\' || savePath.charAt(savePath.length()-1)!='/') savePath+='\\'; this.configParam.fileSavePath=savePath; System.out.println("savePath="+this.configParam.fileSavePath); } /*fosDebug=FileUtils.openOutputStream(new File("D:\\MultiData.txt"),true); Enumeration<?> headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = (String)headerNames.nextElement(); // 同一个请求头名可能出现多次 Enumeration<?> values = request.getHeaders(headerName); while(values.hasMoreElements()) { //out.println(headerName + ":" + (String)values.nextElement() + "<br>"); String strLine=headerName + ":" + (String)values.nextElement()+"\r\n"; fosDebug.write(strLine.getBytes()); } } String strLine="\r\n\r\n"; fosDebug.write(strLine.getBytes());*/ /** * 过滤器主函数 * 该函数通过输入字节流调用相关的分析函数最终完成对本次http multipart form 的request请求 * 将文件表单项写到指定位置,将其他普通表单项形成数据结构供后续页面调用 * */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //主输入对象和主输出对象 HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; ServletContext context=this.config.getServletContext(); //首先分析HTTP header信息判断是否为混合型数据 String method=request.getMethod(); String contentType = request.getContentType(); int contentLen=request.getContentLength(); //System.out.println("content length="+contentLen); //判断 //1.取得请求内容类型如果不是POST, //2.如果请求内容不是"multipart/form-data", //3.content length必须>0 Boolean bIsMultiForm=( method.compareToIgnoreCase(METHOD_POST)==0 && contentType.startsWith(SIGN_MULTIDATA) && contentLen>0); if(bIsMultiForm){ //如果以上条件均成立 //取得boundary boundary = getBoundary(contentType); //我们为每次上传文件请求活动创建一个Progress Id,主要为了以后Client用此id向Server取得当前上传活动进度信息 String progId=GlobInfo.getQueryString(request,"progId"); System.out.println("progId="+progId); if(!progId.isEmpty() && !boundary.isEmpty()){ //检查最大接收尺寸 Boolean bParamCheck=true; Long maxBytes=(configParam.maxPkgBytes<=0)?N_MAX_CONTENTLEN:(configParam.maxPkgBytes*1024*1024); if(contentLen>maxBytes){ bParamCheck=false; } if(bParamCheck){ //创建进度信息 //并第一次更新进度信息为初始化状态 ProgressInfo progInfo = new ProgressInfo(); progInfo.startTime = new Date(); progInfo.curTime = new Date(); progInfo.proState = ProgressInfo.ProStateEnum.PROSTATE_NULL; progInfo.totalBytes = contentLen; progInfo.curBytes = 0; ProgressInfo.updateProgressInfo(context, progId, progInfo); System.out.println(progInfo); //取得输入流对象 ServletInputStream sis = request.getInputStream(); BufferedInputStream bis = new BufferedInputStream(sis); //建立一个FormPart空数组 List<FormPart> listFormPart=new ArrayList<FormPart>(); //分别传入 //输入流对象: 为了从流对象中按字节接收客户端request请求 //contentLen:接收的字节数ContentLength) //boundary: Multipart 分割线 //listFormPart:空的FormPart数组 //progInfo:进度信息对象 //progId:本次进度Id Boolean result=parseInputStream(bis,contentLen,boundary,listFormPart, progInfo,context,progId); //检查文件扩展名是否符合要求,否则删除并设置错误信息 checkFileExt(listFormPart); //如果分析过程出错误,则返回系统错误指令 if(!result) progErr=ProgressInfo.ProErrEnum.PROERR_REQ_SYS; //将本次分析包结果列表向后续页面传递 request.setAttribute(REQUEST_KEY_PROGERR, progErr); request.setAttribute(REQUEST_KEY_FORMPARTLIST, listFormPart); //从Application对象中,本次请求处理完毕你后删除当前进度信息 ProgressInfo.delProgressInfo(context, progId); }//end if bParamCheck } }//end if bIsMultiForm //fosDebug.close(); //交给后续filter链继续处理 filterChain.doFilter(request, response); } @Override public void destroy() { //System.out.println("MultiForm:destroy()"); } }
DarkGao/UploadBigFile
MultiForm.java
8,122
//参数错误
line_comment
zh-cn
package com.dark.filter; /** * 作者:DarkGao * 首次开发:2015/3/10 * */ import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletContext; import javax.servlet.ServletInputStream; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlElement; import java.io.IOException; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Date; import java.io.InputStream; import java.io.FileNotFoundException; import java.io.File; import java.io.FileOutputStream; import java.io.BufferedInputStream; import java.util.HashMap; import org.apache.commons.io.FileUtils; import com.dark.util.ArrayUtils; import com.dark.util.ByteUtils; import com.dark.util.GlobInfo; public class MultiForm implements Filter { //定义http协议中用到的一些关键字常量 private final static String SIGN_BOUNDARY = "boundary="; private final static String SIGN_FORMELEMENT = "name="; private final static String SIGN_FILENAME = "filename="; private final static String SIGN_MULTIDATA = "multipart/form-data"; private final static String SIGN_CONTENTDISPOS ="Content-Disposition:"; private final static String SIGN_CONTENTTYPE = "Content-Type:"; private final static String METHOD_POST="post"; private final static Long N_MAX_CONTENTLEN=1024*1024*1024L; //最大为1G接收请求内容 private final static Integer N_CHUNKBYTES=64*1024; //一次读取64K大小 //向后续页面传递的两个Request范围key public final static String REQUEST_KEY_FORMPARTLIST="FormPartList"; public final static String REQUEST_KEY_PROGERR="ProgErr"; private final static String APP_KEY_APPNAME = "DarkUploadApp"; private final static String DEF_SAVEPATH="uploadFile"; //定义xml配置filter时加载的属性 private final static String CONFIG_AUTODELPROG="autoDelProg"; private final static String CONFIG_MAXPKGBYTES="maxPkgBytes"; private final static String CONFIG_RECVEXTLIST="recvExtList"; private final static String CONFIG_REJECTEXTLIST="rejectExtList"; private final static String CONFIG_FILESAVEPATH="fileSavePath"; private final static String CONFIG_USEORIFILENAME="useOriFileName"; //HTTP MULTPART段分界线 private String boundary = ""; private FilterConfig config=null; //文件输出流对象,为了写文件时只打开一次文件 private FileOutputStream fos=null; //private FileOutputStream fosDebug=null; //配置文件参数,从.xml中读取 private ConfigParam configParam=null; private ProgressInfo.ProErrEnum progErr=ProgressInfo.ProErrEnum.PROERR_OK; /** * 进度信息类,描述了一次上传请求的进度信息 * 该对象会用来被客户端轮询请求以获得当前传输大文件过程中的进度信息 * @author DarkGao * */ @XmlRootElement public static class ProgressInfo{ //当前进度状态 public enum ProStateEnum{ PROSTATE_NULL, //无状态 PROSTATE_LOADING, //上传数据 PROSTATE_LOADED, //上传数据完毕 PROSTATE_PARSE, //数据分析中 PROSTATE_END; //全部完毕 } //上传进度错误 public enum ProErrEnum{ PROERR_OK, //无错误 PROEFF_CFGFILE, //配置文件读取错误 PROERR_PARAM, //参数 <SUF> PROERR_REQ_SYS, //处理请求时的系统错误,比如取得当前请求包内容异常 PROERR_REQ_RULE, //请求包规则错误 PROERR_REQ_SIZE, //请求包过大 PROERR_IO_FILE; //保存文件错误,包括无法创建指定路径,指定文件,或无法打开指定文件 } //当前接收字节数 private long curBytes=-1l; //整个http请求的总共字节数 private long totalBytes=-1l; //请求发起起始时间 private Date startTime=new Date(); //当前进度时刻时间 private Date curTime=new Date(); //当前进度状态 private ProStateEnum proState=ProStateEnum.PROSTATE_NULL; @Override public String toString(){ String result=""; result=this.getClass()+":curBytes="+curBytes+";"+ "totalBytes="+totalBytes+";"+ "startTime="+startTime+";"+ "curTime="+curTime+";"+ "proState="+proState; return result; } //取得当前进度状态 @XmlElement public ProStateEnum getProState(){ return proState; } //取得当前接收字节数 @XmlElement public Long getCurBytes(){ return curBytes; } //取得本次HTTP包全部字节数 @XmlElement public Long getTotalBytes(){ return totalBytes; } //当前时刻已经花费的时间(秒数) @XmlElement public Long getElapseSecond(){ Long nReturn=0l; nReturn=(curTime.getTime()-startTime.getTime())/1000; return nReturn; } //当前上传速度(字节/秒) @XmlElement public long getTransRate(){ long nReturn=0l; //获得花费的时间(秒) long nSeconds=getElapseSecond(); //计算当前上传速度,字节/秒 if(nSeconds>0) nReturn=curBytes/nSeconds; return nReturn; } //当前进度百分比(0--100之间的数) @XmlElement public int getTransPercent(){ int nReturn=0; if(totalBytes>0) nReturn=(int)(curBytes*100/totalBytes); return nReturn; } //当前剩余秒数(小于零为未知时间) @XmlElement public int getRemainSecond(){ int nReturn=0; long nRate=getTransRate(); if(nRate>0) nReturn=(int)((totalBytes-curBytes)/nRate); return nReturn; } //根据progId取得在context中的进度对象 //注意,进度对象都被存储在context中的Map中(Application级别的内存共享区) @SuppressWarnings("unchecked") public static ProgressInfo getProgressInfo(ServletContext context,String progId){ if (progId == null) return null; progId = progId.trim(); ProgressInfo objInfo = null; if (progId.isEmpty()) return objInfo; objInfo = new ProgressInfo(); HashMap<String,ProgressInfo> progMap=(HashMap<String,ProgressInfo>) context.getAttribute(APP_KEY_APPNAME); if (progMap != null){ ProgressInfo objTemp= (ProgressInfo)progMap.get(progId); if (objTemp != null){ objInfo.curBytes = objTemp.curBytes; objInfo.curTime = objTemp.curTime; objInfo.proState = objTemp.proState; objInfo.startTime = objTemp.startTime; objInfo.totalBytes = objTemp.totalBytes; } } return objInfo; } //从context的map中删除指定progId的进度对象 @SuppressWarnings("unchecked") public static void delProgressInfo(ServletContext context,String progId){ progId = progId.trim(); if (progId.isEmpty()) return; //如果当前上下文中Application为空,那么创建ProgressInfo字典进入Application HashMap<String,ProgressInfo> progMap = (HashMap<String,ProgressInfo>)( context.getAttribute(APP_KEY_APPNAME)); if(progMap==null) return; //对全局context中对象修改需要进行线程锁控制 synchronized(progMap){ ProgressInfo objTemp= (ProgressInfo)progMap.get(progId); progMap.remove(objTemp); if(progMap.size()<=0) context.removeAttribute(APP_KEY_APPNAME); }// end synchronized } //将当前的ProgressInfo对象加入context(Application共享内存区) @SuppressWarnings("unchecked") private static void updateProgressInfo(ServletContext context, String progId,ProgressInfo objProgress){ progId = progId.trim(); if (progId.isEmpty()) return; //如果当前上下文中Application为空,那么创建ProgressInfo字典进入Application HashMap<String,ProgressInfo> progMap = (HashMap<String,ProgressInfo>)( context.getAttribute(APP_KEY_APPNAME)); //对全局context中对象修改需要进行线程锁控制 if (progMap == null) { progMap = new HashMap<String,ProgressInfo>(31); context.setAttribute(APP_KEY_APPNAME, progMap); } //由于针对Application操作是多线程并发,所以需要加同步锁控制 synchronized(progMap){ //从字典中寻找当前ID的ProgressInfo ProgressInfo objCur = (ProgressInfo)progMap.get(progId); //如果没找到则将当前ProgressInfo加入其中 if (objCur == null){ objCur = new ProgressInfo(); progMap.put(progId, objCur); } objCur.curBytes = objProgress.curBytes; objCur.curTime = objProgress.curTime; objCur.proState = objProgress.proState; objCur.startTime = objProgress.startTime; objCur.totalBytes = objProgress.totalBytes; } } }//End ProgressInfo /** * Http Form 表单数据结构 * @author DarkGao * */ public static class FormPart implements Cloneable{ public String name=""; public String value=""; public String fileName=""; public String fileExt=""; public String contentType=""; public String fileSavePath=""; public String newFileName=""; public String newFileSavePath=""; public boolean isValid=true; public FileErrEnum fileErr=FileErrEnum.FILEERR_OK; public enum FileErrEnum{ FILEERR_OK, //保存文件成功 FILEERR_FAIL_CREATE, //创建文件失败 FILEERR_FAIL_EXT //扩展名不符合要求 } @Override public String toString(){ String result=""; result=this.getClass()+":name="+name+";"+ "value="+value+";"+ "fileName="+fileName+";"+ "fileExt="+fileExt+";"+ "contentType="+contentType+";"+ "fileSavePath="+fileSavePath+";"+ "newFileName="+newFileName+";"+ "newFileSavePath="+newFileSavePath+";"+ "isValid="+isValid+";"+ "fileErr="+fileErr; return result; } //上传表单是否为文件类型 public Boolean isFileInput(){ return !contentType.isEmpty(); } //取得上传后保存文件的大小 public Long getFileSize(){ if(!newFileSavePath.isEmpty()){ return FileUtils.sizeOf(new File(newFileSavePath)); } return 0l; } //克隆 public Object clone(){ FormPart o=null; try{ o=(FormPart)super.clone(); }catch(CloneNotSupportedException e){ e.printStackTrace(); } return o; } }//End FormPart /** * xml中filter配置信息 * 这些配置信息主要用来限制接收文件条件,比如接收的文件大小限制,扩展名限制等 * @author DarkGao * */ private class ConfigParam{ //最大请求包尺寸 public int maxPkgBytes = 0; //保存文件路径 public String fileSavePath = ""; //只接收某些扩展名列表,用','分割,例如:'jpg,txt' public String recvExtList = ""; //拒绝某些扩展名列表,用','分割,例如:'ext,com,bat' public String rejectExtList = ""; //保存文件时是否使用原文件名保存 public boolean useOriFileName = true; //是否在本次请求结束后自动删除该进度信息 public boolean autoDelProg = true; public String toString(){ String result=""; result=this.getClass()+":maxPkgBytes="+maxPkgBytes+";"+ "fileSavePath="+fileSavePath+";"+ "recvExtList="+recvExtList+";"+ "rejectExtList="+rejectExtList+";"+ "useOriFileName="+useOriFileName+";"+ "autoDelProg="+autoDelProg+";"; return result; } }//End ConfigParam /** * 将不完整的文件件片段信息写进原文件内 * 这里的文件句柄已经在之前被开启(文件已经被创建) * @param buf * @param lastForm * @return */ private Boolean appendFileSect(byte[] buf,FormPart lastForm){ Boolean result=false; if(buf.length>0 && !lastForm.newFileSavePath.isEmpty()) { try{ //将本次接收的内存区写入文件 if(fos!=null) fos.write(buf); result=true; }catch(IOException e) { e.printStackTrace(); }//end try } return result; } /** * 从局部内存区中找到Boundary段信息 * 如果从本次接收的局部内存中找到了整体的表单信息,则存入表单信息结构中 * 这里分为几种情况 * 1.本次内存区中包含了1个或多个完整的表单信息。可能还会有剩余,即不完整的表单信息 * 2.本次内存区中只包含了不完整的表单信息,比如大文件中间的某段片段信息 * * @param buf * @param scanStart * @param boundary * @param lastForm * @param curForm * @return */ private int getBoundarySectFromBuf(byte[] buf,int scanStart,String boundary, FormPart lastForm,FormPart curForm){ curForm.isValid=true; int scanEnd=-1; byte[] scanKey=ByteUtils.getBytes(boundary); if(buf.length<=0 || scanKey.length<=0){ curForm.isValid=false; return scanEnd; } //在内存区中scanStart开始位置查找boundary key int start=ArrayUtils.indexOf(buf, scanKey, scanStart); //如果没找到boundary,但buf中的确有内容,则为上一个FormPart中文件的片段信息 if(start<0) { //这里需要进行写操作 if(lastForm==null || lastForm.newFileSavePath.isEmpty()) return scanEnd; scanEnd=appendFileSect(buf,lastForm)?buf.length:scanEnd; curForm.isValid=false; return scanEnd; } //如果找到了boundary但并不是起点位置则 else if((start-scanStart)!=2) { //则将boundary前面的部分写入上一个FormPart文件中 byte[] tempBuf=ArrayUtils.copyOfRange(buf, 0, start-2); if(lastForm==null || lastForm.newFileSavePath.isEmpty()) return scanEnd; appendFileSect(tempBuf,lastForm); try{ if(fos!=null) fos.close(); fos=null; }catch(IOException e){ e.printStackTrace(); } tempBuf=null; } //对当前的form结构进行初始化 curForm.name=""; curForm.value=""; curForm.fileName=""; curForm.fileExt=""; curForm.contentType=""; curForm.newFileSavePath=""; //如果找到指定第一个boundary,则查找下一行"Content-Disposition:" start=ArrayUtils.indexOf(buf, SIGN_CONTENTDISPOS.getBytes(),start); if(start<0){ curForm.isValid=false; return scanEnd; } //取得"Content-Disposition:"的一行 ArrayUtils.LineReturn line=ArrayUtils.getLine(buf, start);//ByteUtils.getString(byteLine); if(line.line.length()<=0){ curForm.isValid=false; return scanEnd; } //取得"name=" start=line.line.indexOf(SIGN_FORMELEMENT); if(start<0){ curForm.isValid=false; return scanEnd; } String formName=line.line.substring(start+SIGN_FORMELEMENT.length()); int end=formName.indexOf(";"); if(end>0) formName=formName.substring(0, end); //去掉formName的'\"' formName=formName.replace("\"", ""); //查找"filename=" start=line.line.indexOf(SIGN_FILENAME); //如果没找到filename=,则说明为form普通字段,否则为文件二进制字段 if(start<0){ //跳过一个"\r\n" //继续搜索下一个"\r\n" line=ArrayUtils.getLine(buf, line.endIndex); line=ArrayUtils.getLine(buf, line.endIndex); curForm.name=formName; curForm.value=line.line; scanEnd=line.endIndex; } //如果找到filename= else{ curForm.name=formName; curForm.value=""; //在内存区中找到下一个boundary key end=ArrayUtils.indexOf(buf, scanKey, line.endIndex); //如果找到第二个boundary则 if(end>0){ scanEnd=end-2; } else{ scanEnd=buf.length; } //截取filename= String fileName=line.line.substring(start+SIGN_FILENAME.length()); fileName=fileName.replace("\"",""); //**?转换中文编码问题 System.out.println("fileName="+fileName); String arr[]=fileName.split("\\."); if(arr.length>1){ curForm.fileName=arr[0]; curForm.fileExt=arr[1]; } //查找下一行 line=ArrayUtils.getLine(buf, line.endIndex); start=line.line.indexOf(SIGN_CONTENTTYPE); //找到Content-Type:内容 if(!line.line.isEmpty() && start>=0){ arr=line.line.split(":"); if(arr.length==2){ curForm.contentType=arr[1].trim(); } //找到下一空行 line=ArrayUtils.getLine(buf, line.endIndex); //此处为二进制信息开始地点,开始进行写文件操作 String newFileName=curForm.newFileName.isEmpty()?curForm.fileName:curForm.newFileName; if(!newFileName.isEmpty()){ String filePath=curForm.fileSavePath+newFileName; if(!curForm.fileExt.isEmpty()) filePath+="."+curForm.fileExt; curForm.newFileSavePath=filePath; byte[] tempBuf=ArrayUtils.copyOfRange(buf, line.endIndex, scanEnd); try{ //将本次接收的内存区写入文件 if(fos!=null) fos.close(); fos=FileUtils.openOutputStream(new File(filePath),false); fos.write(tempBuf); //fos.close(); }catch(IOException e) { e.printStackTrace(); fos=null; scanEnd=-1; }//end try tempBuf=null; } }//end if } return scanEnd; } /** * 从输入的流中分段读取用户请求,边接收边进行分段解析,通过累计后,最后形成表单列表 * * @param is * @param contentLen * @param boundary * @param inputList * @param progInfo * @param context * @param progId * @return */ private Boolean parseInputStream(InputStream is,Integer contentLen, String boundary,List<FormPart> inputList, ProgressInfo progInfo,ServletContext context,String progId) { Boolean result=false; if(is==null || contentLen<=0 || boundary==null || boundary.length()<=0) return result; //更新进度信息为正在上传状态 progInfo.curTime = new Date(); progInfo.proState = ProgressInfo.ProStateEnum.PROSTATE_LOADING; ProgressInfo.updateProgressInfo(context, progId, progInfo); //System.out.println(progInfo); try { //FileOutputStream fos=FileUtils.openOutputStream(new File("D:\\fileTemp2.dat"),true); //从输入流中循环读取客户发上来的请求 //循环读取字节流,一次读取64K数据 int totalLen=0; FormPart lastForm=new FormPart(); FormPart curForm=new FormPart(); curForm.fileSavePath=this.configParam.fileSavePath; //System.out.println("fileSavePath="+curForm.fileSavePath); while (totalLen<contentLen) { //创建最大读取缓冲区 byte[] bufTemp=new byte[N_CHUNKBYTES]; int remainLen=contentLen-totalLen; //每次最多读取N_CHUNKBYTES字节 int chunkSize=is.read(bufTemp,0,(remainLen>N_CHUNKBYTES)?N_CHUNKBYTES:remainLen); if(chunkSize<=0) break; //fosDebug.write(bufTemp); byte[] buf=ArrayUtils.copyOfRange(bufTemp, 0, chunkSize); bufTemp=null; totalLen+=chunkSize; //更新进度信息为当前传输过程中进度状态 progInfo.curTime = new Date(); progInfo.curBytes = totalLen; ProgressInfo.updateProgressInfo(context, progId, progInfo); //System.out.println(progInfo); //从当前接收的缓冲区中动态解析HTML multipart信息 //这里使用到循环,主要是为了处理本次接收的最大N_CHUNKBYTES字节数据中将包含多段FormPart信息 //如果包含多段FormPart,我们需要使用循环来分解并建立对象 int bufIndex=0; while(bufIndex<buf.length){ bufIndex=getBoundarySectFromBuf(buf,bufIndex,boundary,lastForm,curForm); if(bufIndex<0) break; lastForm=curForm; //判断本次Form Part信息是否完整,如果完整则填入结果列表 if(curForm.isValid){ FormPart tempForm=(FormPart)curForm.clone(); inputList.add(tempForm); } } if(bufIndex>=0){ result=true; } buf=null; } //fos.close(); } catch (FileNotFoundException e) { //更新进度信息 e.printStackTrace(); } catch (IOException e) { //更新进度信息 e.printStackTrace(); } //更新进度信息对象为结束状态 progInfo.proState = ProgressInfo.ProStateEnum.PROSTATE_END; ProgressInfo.updateProgressInfo(context, progId, progInfo); System.out.println(progInfo); return result; } /** * 获取本次上传对应的表单元素间的分隔符,注意该分隔符是随机生成的 * @param contentType * @return */ private String getBoundary(String contentType) { String tempStr = ""; if (contentType != null && contentType.startsWith(SIGN_MULTIDATA) && contentType.indexOf(SIGN_BOUNDARY) != -1) { //获取表单每个元素的分隔符 tempStr = contentType .substring( contentType.indexOf(SIGN_BOUNDARY) + SIGN_BOUNDARY.length()).trim(); } return tempStr; } /** * 获得xml文件中配置filter的配置信息 * @param config * @param configParam */ private void getConfigParam(FilterConfig config,ConfigParam configParam){ if(config==null || configParam==null) return; configParam.autoDelProg=Boolean.parseBoolean(config.getInitParameter(CONFIG_AUTODELPROG)); configParam.maxPkgBytes=Integer.parseInt(config.getInitParameter(CONFIG_MAXPKGBYTES)); configParam.recvExtList=config.getInitParameter(CONFIG_RECVEXTLIST); configParam.rejectExtList=config.getInitParameter(CONFIG_REJECTEXTLIST); configParam.fileSavePath=config.getInitParameter(CONFIG_FILESAVEPATH); configParam.useOriFileName=Boolean.parseBoolean(config.getInitParameter(CONFIG_USEORIFILENAME)); System.out.println(configParam); } /** * 检查所有请求表单项中的文件扩展名是否符合xml中配置选项 * @param listFormPart */ private void checkFileExt(List<FormPart> listFormPart){ //检查用户上传的文件扩展名 String[] recvExtArr=null; if(!configParam.recvExtList.isEmpty()) recvExtArr=configParam.recvExtList.split(","); String[] rejectExtArr=null; if(!configParam.rejectExtList.isEmpty()) rejectExtArr=configParam.rejectExtList.split(","); Boolean recvAll=true; //寻找"*" for(int i=0;i<recvExtArr.length;i++){ if(recvExtArr[i].equalsIgnoreCase("*")){ recvAll=false; break; } } for(int i=0;i<listFormPart.size();i++){ FormPart part=listFormPart.get(i); Boolean isDel=false; //如果接受所有扩展名,则需要检查rejectExtArr中内容 if(recvAll){ isDel=false; if(rejectExtArr!=null){ for(int j=0;j<rejectExtArr.length;j++){ if(part.fileExt.equalsIgnoreCase(rejectExtArr[j])){ isDel=true; break; } } } } //否则只检查recvExtArr内容 else if(recvExtArr.length>0){ isDel=true; if(recvExtArr!=null){ for(int j=0;j<recvExtArr.length;j++){ if(part.fileExt.equalsIgnoreCase(recvExtArr[j])){ isDel=false; break; } } } } if(isDel){ //删除该文件并标记该文件不符合要求 File file=new File(part.newFileSavePath); file.delete(); part.fileErr=FormPart.FileErrEnum.FILEERR_FAIL_EXT; } System.out.println(part); } } /** * 初始化Filter * 主要完成了加载xml文件中的filter配置信息 * 以及根据xml文件中的文件保存路径以及本app的系统目录创建最终的文件保存路径 */ @Override public void init(FilterConfig filterConfig) throws ServletException { this.config=filterConfig; this.configParam=new ConfigParam(); //加载来自XML的SAVEPATH //this.savePath=config.getInitParameter("savePath"); getConfigParam(this.config,this.configParam); System.out.println(configParam); String savePath=this.configParam.fileSavePath; if(savePath==null || savePath.isEmpty()) savePath=DEF_SAVEPATH; //取得系统当前目录 String appPath=GlobInfo.getAppPath(this); appPath=appPath.replace('/', '\\'); savePath=appPath+savePath; if(savePath.charAt(savePath.length()-1)!='\\' || savePath.charAt(savePath.length()-1)!='/') savePath+='\\'; this.configParam.fileSavePath=savePath; System.out.println("savePath="+this.configParam.fileSavePath); } /*fosDebug=FileUtils.openOutputStream(new File("D:\\MultiData.txt"),true); Enumeration<?> headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String headerName = (String)headerNames.nextElement(); // 同一个请求头名可能出现多次 Enumeration<?> values = request.getHeaders(headerName); while(values.hasMoreElements()) { //out.println(headerName + ":" + (String)values.nextElement() + "<br>"); String strLine=headerName + ":" + (String)values.nextElement()+"\r\n"; fosDebug.write(strLine.getBytes()); } } String strLine="\r\n\r\n"; fosDebug.write(strLine.getBytes());*/ /** * 过滤器主函数 * 该函数通过输入字节流调用相关的分析函数最终完成对本次http multipart form 的request请求 * 将文件表单项写到指定位置,将其他普通表单项形成数据结构供后续页面调用 * */ @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //主输入对象和主输出对象 HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; ServletContext context=this.config.getServletContext(); //首先分析HTTP header信息判断是否为混合型数据 String method=request.getMethod(); String contentType = request.getContentType(); int contentLen=request.getContentLength(); //System.out.println("content length="+contentLen); //判断 //1.取得请求内容类型如果不是POST, //2.如果请求内容不是"multipart/form-data", //3.content length必须>0 Boolean bIsMultiForm=( method.compareToIgnoreCase(METHOD_POST)==0 && contentType.startsWith(SIGN_MULTIDATA) && contentLen>0); if(bIsMultiForm){ //如果以上条件均成立 //取得boundary boundary = getBoundary(contentType); //我们为每次上传文件请求活动创建一个Progress Id,主要为了以后Client用此id向Server取得当前上传活动进度信息 String progId=GlobInfo.getQueryString(request,"progId"); System.out.println("progId="+progId); if(!progId.isEmpty() && !boundary.isEmpty()){ //检查最大接收尺寸 Boolean bParamCheck=true; Long maxBytes=(configParam.maxPkgBytes<=0)?N_MAX_CONTENTLEN:(configParam.maxPkgBytes*1024*1024); if(contentLen>maxBytes){ bParamCheck=false; } if(bParamCheck){ //创建进度信息 //并第一次更新进度信息为初始化状态 ProgressInfo progInfo = new ProgressInfo(); progInfo.startTime = new Date(); progInfo.curTime = new Date(); progInfo.proState = ProgressInfo.ProStateEnum.PROSTATE_NULL; progInfo.totalBytes = contentLen; progInfo.curBytes = 0; ProgressInfo.updateProgressInfo(context, progId, progInfo); System.out.println(progInfo); //取得输入流对象 ServletInputStream sis = request.getInputStream(); BufferedInputStream bis = new BufferedInputStream(sis); //建立一个FormPart空数组 List<FormPart> listFormPart=new ArrayList<FormPart>(); //分别传入 //输入流对象: 为了从流对象中按字节接收客户端request请求 //contentLen:接收的字节数ContentLength) //boundary: Multipart 分割线 //listFormPart:空的FormPart数组 //progInfo:进度信息对象 //progId:本次进度Id Boolean result=parseInputStream(bis,contentLen,boundary,listFormPart, progInfo,context,progId); //检查文件扩展名是否符合要求,否则删除并设置错误信息 checkFileExt(listFormPart); //如果分析过程出错误,则返回系统错误指令 if(!result) progErr=ProgressInfo.ProErrEnum.PROERR_REQ_SYS; //将本次分析包结果列表向后续页面传递 request.setAttribute(REQUEST_KEY_PROGERR, progErr); request.setAttribute(REQUEST_KEY_FORMPARTLIST, listFormPart); //从Application对象中,本次请求处理完毕你后删除当前进度信息 ProgressInfo.delProgressInfo(context, progId); }//end if bParamCheck } }//end if bIsMultiForm //fosDebug.close(); //交给后续filter链继续处理 filterChain.doFilter(request, response); } @Override public void destroy() { //System.out.println("MultiForm:destroy()"); } }
0
6
0
17246_0
//超级素数:它本身,各位数字的和,各位数字的平方和,都是素数。 //求 100~10000 内的所有超级素数,及它们的平均数。 class SuperPrime { public static void main(String[] args) { System.out.println(args); //[ljava.lang.string;@139a55 “[”代表数组, “l”代表long , "@139a55"代表哈希值 System.out.println(args.length); //默认长度为0 for(int i = 0; i < args.length; i++) System.out.println(args[i]); } }
Dashark/hello-world
SuperPrime.java
180
//超级素数:它本身,各位数字的和,各位数字的平方和,都是素数。
line_comment
zh-cn
//超级 <SUF> //求 100~10000 内的所有超级素数,及它们的平均数。 class SuperPrime { public static void main(String[] args) { System.out.println(args); //[ljava.lang.string;@139a55 “[”代表数组, “l”代表long , "@139a55"代表哈希值 System.out.println(args.length); //默认长度为0 for(int i = 0; i < args.length; i++) System.out.println(args[i]); } }
0
32
0
61727_3
package com.dasinong.farmerclub.components.domain; import com.dasinong.farmerclub.ui.soil.domain.DataEntity; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by liuningning on 15/6/14. */ public class FieldEntity extends BaseResponse { public DataEntity latestReport; // field list // name:fieldID public Map<String, Long> fieldList; public CurrentFieldEntity currentField; public HomeDate date; public String soilHum; public static class HomeDate { public String lunar;// 大雪 public int day;// 周41(要是) public String date;// 10 } /** * cropName + stageName + SubStagName; 水稻分叶期8叶 */ public static class CurrentFieldEntity { public String startDate; // 当前的statgeID public int currentStageID; // 病害 public List<PetdiswsEntity> petdisws; // 作物名 public String cropName; // not show public int yield; // 任务清单 public List<TaskwsEntity> taskws; // not show userID public int userId; // not show location_id public int locationId; // not show public boolean active; // 结束时间 public String endDate; // 品种(id select substage) public int varietyId; // 自然(如果不是空,则是Banner的信息。如果是空,则加载Banner) public List<NatdiswsEntity> natdisws; // not show public int fieldId; // 当前田的名称 public String fieldName; public int dayToHarvest; // int只给 离收获boo还有多少天()(小于0不显示) // false public List<CurrentFieldEntity.Petdisspecws> petdisspecws; public List<SubStageEntity> stagelist; public static class PetdiswsEntity { /** * "rule": * "[发生规律](1)世代。江苏每年发生9~11代,安徽11代,浙江10~12代,福建中部约15代,广东中、南部15代以上。稻蓟马生活周期短,发生代数多,世代重叠,田间发生世代较难划分。(2)越冬。成虫在茭白、麦类、李氏禾、看麦娘等禾本科植物上越冬。翌年3~4月份,成虫先在杂草上活动繁殖,然后迁移到水稻秧田繁殖为害。(3)时期。主要在水稻生长前期为害。迁移代成虫于5月中旬前后在早稻本田,早播中稻秧田产卵繁殖为害,二代成虫于6月上中旬迁入迟栽早稻本田或单季中稻秧、本田和晚稻秧田产卵为害。江淮地区一般于4月中旬起虫口数量呈直线上升,5、6月份达最高虫口密度。(4)气候。7月中旬以后因受高温(平均气温28℃以上)影响和稻叶不适蓟马取食为害,虫口受到抑制,数量迅速下降。冬季气候温暖,有利于稻蓟马的越冬和提早繁殖。在6月初到7月上旬,凡阴雨日多、气温维持在22~23℃的天数长,稻蓟马就会大发生。(5)栽培。早稻穗期受害重于晚稻穗期,以盛花期侵入的虫数较多,次为初花期或谢花期,灌浆期最少。双晚秧田,尤其是双晚直播田因叶嫩多汁,易受蓟马集中为害。秧苗三叶期以后,本田自返青至分蘖期是稻蓟马的严重为害期。如稻后种植绿肥和油菜,将为稻蓟马提供充足的食源和越冬场所,小麦面积较大的地方,稻蓟马的为害就有加重的可能。" * , "sympton": * "[为害症状]成虫1、2代和若虫以口器磨破稻叶表皮,吸食汁液,被害叶上出现黄白色小斑点或微孔,叶尖枯黄卷缩,严重时可使成片秧苗发黄发红,状如火烧。稻苗严重受害时,影响稻株返青和分蘖生长受阻,稻苗坐兜。花器受害,影响受粉结实,有的造成空壳。" * , "form": * "[形态](1)成虫。体长1~1.3mm,雌虫略大于雄虫。初羽化时体色为褐色,1~2天后,为深褐色至黑色。头近正方形,触角鞭状7节,第6节至第7节与体同色,其余各节均黄褐色。复眼黑色,两复眼间有3个单眼,呈三角形排列。单眼前鬃长于单眼间鬃,单眼间鬃位于单眼三角形连线外缘。复眼后鬃4根。前胸背板发达,明显长于头部,或约于头长相等,后缘有鬃4根。前翅较后翅大,缨毛细长,有2条纵脉,上脉基鬃4+3根,端鬃3根,下脉鬃11~13根。雄成虫腹部3~7节腹板具腺域,雌成虫第8、9腹节有锯齿状产卵器。(2)卵。肾形,长约0.2mm,宽约0.1mm,初产白色透明,后变淡黄色,半透明,孵化前可透见红色眼点。(3)幼虫。共4龄。初孵时体长0.3~0.5mm,白色透明。触角直伸头前方,触角念珠状,第4节特别膨大。复眼红色,无单眼及翅芽。2龄若虫体长0.6~1.2mm,淡黄绿色,复眼褐色。3龄若虫又称前蛹,体长0.8~1.2mm,淡黄色,触角分向两边,单眼模糊,翅芽始现,复部显著膨大。4龄又称蛹,体长0.8~1.3mm,淡褐色,触角向后翻,在头部与前胸背面可见单眼3个,翅芽伸长达腹部5~7节。" * , "habbit": * "[习性](1)成虫。成虫白天多隐藏在纵卷的叶尖或心叶内,有的潜伏于叶鞘内,早晨、黄昏或阴天多在叶上活动,爬行迅速,受震动后常展翅飞去,有一定迁飞能力,能随气流扩散。雄成虫寿命短,只有几天;雌成虫寿命长,为害季节中多在20天以上。雌虫羽化后经过1~3天开始产卵,产卵期10~20天,一般在羽化后3~6天产卵最多,在适宜的温湿环境下,1头雌虫一生可产卵100粒左右;雌成虫可以进行孤雌生殖,孤雌生殖的产卵量与两性生殖相似。雌成虫有明显趋嫩绿秧苗产卵的习性,在秧田中,一般在2、3叶期以上的秧苗上产卵。雌虫产卵时把产卵器插入稻叶表皮下,散产于叶片表皮下的脉间组织内,对光可看到针孔大小边缘光滑的半透明卵粒。(2)幼虫。多在晚上7~9时孵出,3~5分钟离开壳体,活泼地在叶片上爬行,数分钟后即能取食,1、2龄若虫是取食为害的主要阶段,多聚集中叶耳、叶舌处,特别是在卷针状的心叶内隐匿取食;3龄若虫行动呆滞,取食变缓,此时多集中在叶尖部分,使秧叶自尖起纵卷变黄。因此,大量叶尖纵卷变黄,预兆着3、4龄若虫激增,成虫将盛发。" * , "pestName": "稻蓟马", "alias": "稻直鬃蓟马;俗称灰虫", "id": 3439 */ public boolean petDisStatus; public String petDisSpecName; public int id; public int fieldId; public int petDisId; public String description; public String type; } // 这个不是 public static class Petdisspecws { /** * "rule": * "[发生规律](1)世代。江苏每年发生9~11代,安徽11代,浙江10~12代,福建中部约15代,广东中、南部15代以上。稻蓟马生活周期短,发生代数多,世代重叠,田间发生世代较难划分。(2)越冬。成虫在茭白、麦类、李氏禾、看麦娘等禾本科植物上越冬。翌年3~4月份,成虫先在杂草上活动繁殖,然后迁移到水稻秧田繁殖为害。(3)时期。主要在水稻生长前期为害。迁移代成虫于5月中旬前后在早稻本田,早播中稻秧田产卵繁殖为害,二代成虫于6月上中旬迁入迟栽早稻本田或单季中稻秧、本田和晚稻秧田产卵为害。江淮地区一般于4月中旬起虫口数量呈直线上升,5、6月份达最高虫口密度。(4)气候。7月中旬以后因受高温(平均气温28℃以上)影响和稻叶不适蓟马取食为害,虫口受到抑制,数量迅速下降。冬季气候温暖,有利于稻蓟马的越冬和提早繁殖。在6月初到7月上旬,凡阴雨日多、气温维持在22~23℃的天数长,稻蓟马就会大发生。(5)栽培。早稻穗期受害重于晚稻穗期,以盛花期侵入的虫数较多,次为初花期或谢花期,灌浆期最少。双晚秧田,尤其是双晚直播田因叶嫩多汁,易受蓟马集中为害。秧苗三叶期以后,本田自返青至分蘖期是稻蓟马的严重为害期。如稻后种植绿肥和油菜,将为稻蓟马提供充足的食源和越冬场所,小麦面积较大的地方,稻蓟马的为害就有加重的可能。" * , "sympton": * "[为害症状]成虫1、2代和若虫以口器磨破稻叶表皮,吸食汁液,被害叶上出现黄白色小斑点或微孔,叶尖枯黄卷缩,严重时可使成片秧苗发黄发红,状如火烧。稻苗严重受害时,影响稻株返青和分蘖生长受阻,稻苗坐兜。花器受害,影响受粉结实,有的造成空壳。" * , "form": * "[形态](1)成虫。体长1~1.3mm,雌虫略大于雄虫。初羽化时体色为褐色,1~2天后,为深褐色至黑色。头近正方形,触角鞭状7节,第6节至第7节与体同色,其余各节均黄褐色。复眼黑色,两复眼间有3个单眼,呈三角形排列。单眼前鬃长于单眼间鬃,单眼间鬃位于单眼三角形连线外缘。复眼后鬃4根。前胸背板发达,明显长于头部,或约于头长相等,后缘有鬃4根。前翅较后翅大,缨毛细长,有2条纵脉,上脉基鬃4+3根,端鬃3根,下脉鬃11~13根。雄成虫腹部3~7节腹板具腺域,雌成虫第8、9腹节有锯齿状产卵器。(2)卵。肾形,长约0.2mm,宽约0.1mm,初产白色透明,后变淡黄色,半透明,孵化前可透见红色眼点。(3)幼虫。共4龄。初孵时体长0.3~0.5mm,白色透明。触角直伸头前方,触角念珠状,第4节特别膨大。复眼红色,无单眼及翅芽。2龄若虫体长0.6~1.2mm,淡黄绿色,复眼褐色。3龄若虫又称前蛹,体长0.8~1.2mm,淡黄色,触角分向两边,单眼模糊,翅芽始现,复部显著膨大。4龄又称蛹,体长0.8~1.3mm,淡褐色,触角向后翻,在头部与前胸背面可见单眼3个,翅芽伸长达腹部5~7节。" * , "habbit": * "[习性](1)成虫。成虫白天多隐藏在纵卷的叶尖或心叶内,有的潜伏于叶鞘内,早晨、黄昏或阴天多在叶上活动,爬行迅速,受震动后常展翅飞去,有一定迁飞能力,能随气流扩散。雄成虫寿命短,只有几天;雌成虫寿命长,为害季节中多在20天以上。雌虫羽化后经过1~3天开始产卵,产卵期10~20天,一般在羽化后3~6天产卵最多,在适宜的温湿环境下,1头雌虫一生可产卵100粒左右;雌成虫可以进行孤雌生殖,孤雌生殖的产卵量与两性生殖相似。雌成虫有明显趋嫩绿秧苗产卵的习性,在秧田中,一般在2、3叶期以上的秧苗上产卵。雌虫产卵时把产卵器插入稻叶表皮下,散产于叶片表皮下的脉间组织内,对光可看到针孔大小边缘光滑的半透明卵粒。(2)幼虫。多在晚上7~9时孵出,3~5分钟离开壳体,活泼地在叶片上爬行,数分钟后即能取食,1、2龄若虫是取食为害的主要阶段,多聚集中叶耳、叶舌处,特别是在卷针状的心叶内隐匿取食;3龄若虫行动呆滞,取食变缓,此时多集中在叶尖部分,使秧叶自尖起纵卷变黄。因此,大量叶尖纵卷变黄,预兆着3、4龄若虫激增,成虫将盛发。" * , "pestName": "稻蓟马", "alias": "稻直鬃蓟马;俗称灰虫", "id": 3439 */ public boolean petDisStatus; public String petDisSpecName; public int id; public int fieldId; public int petDisId; public String sympton; public String type; } public class TaskwsEntity implements Comparable<TaskwsEntity>{ public boolean taskStatus;// 状态 public int fieldId; public int taskSpecId; public int subStageId; public int taskId;// public String taskSpecName;// desc public String stageName; public String subStageName; @Override public int compareTo(TaskwsEntity another) { if (taskSpecId < another.taskSpecId) return -1; if (taskSpecId > another.taskSpecId) return 1; return 0; } } public class NatdiswsEntity { /** * natDisId : 10 natDisSpecId : 10 natDisStatus : false fieldId : 10 * natDisSpecName : 台风 */ public int natDisId; public int natDisSpecId; public boolean natDisStatus; public int fieldId; public String natDisSpecName; public String description; public boolean alerttype; } public static class SubStageEntity implements Comparable<SubStageEntity> { public String stageName; public int subStageId; public String subStageName; @Override public int compareTo(SubStageEntity another) { if (subStageId < another.subStageId) return -1; if (subStageId > another.subStageId) return 1; return 0; } } } public static final String TASK_TYPE_ALL = "all"; public static final String TASK_TYPE_NONE = "none"; // all | currentStage | none public static class Param { public String fieldId; public String task; public String lat; public String lon; } }
Dasinong/farmerClubAndroid
src/com/dasinong/farmerclub/components/domain/FieldEntity.java
5,099
// 周41(要是)
line_comment
zh-cn
package com.dasinong.farmerclub.components.domain; import com.dasinong.farmerclub.ui.soil.domain.DataEntity; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by liuningning on 15/6/14. */ public class FieldEntity extends BaseResponse { public DataEntity latestReport; // field list // name:fieldID public Map<String, Long> fieldList; public CurrentFieldEntity currentField; public HomeDate date; public String soilHum; public static class HomeDate { public String lunar;// 大雪 public int day;// 周4 <SUF> public String date;// 10 } /** * cropName + stageName + SubStagName; 水稻分叶期8叶 */ public static class CurrentFieldEntity { public String startDate; // 当前的statgeID public int currentStageID; // 病害 public List<PetdiswsEntity> petdisws; // 作物名 public String cropName; // not show public int yield; // 任务清单 public List<TaskwsEntity> taskws; // not show userID public int userId; // not show location_id public int locationId; // not show public boolean active; // 结束时间 public String endDate; // 品种(id select substage) public int varietyId; // 自然(如果不是空,则是Banner的信息。如果是空,则加载Banner) public List<NatdiswsEntity> natdisws; // not show public int fieldId; // 当前田的名称 public String fieldName; public int dayToHarvest; // int只给 离收获boo还有多少天()(小于0不显示) // false public List<CurrentFieldEntity.Petdisspecws> petdisspecws; public List<SubStageEntity> stagelist; public static class PetdiswsEntity { /** * "rule": * "[发生规律](1)世代。江苏每年发生9~11代,安徽11代,浙江10~12代,福建中部约15代,广东中、南部15代以上。稻蓟马生活周期短,发生代数多,世代重叠,田间发生世代较难划分。(2)越冬。成虫在茭白、麦类、李氏禾、看麦娘等禾本科植物上越冬。翌年3~4月份,成虫先在杂草上活动繁殖,然后迁移到水稻秧田繁殖为害。(3)时期。主要在水稻生长前期为害。迁移代成虫于5月中旬前后在早稻本田,早播中稻秧田产卵繁殖为害,二代成虫于6月上中旬迁入迟栽早稻本田或单季中稻秧、本田和晚稻秧田产卵为害。江淮地区一般于4月中旬起虫口数量呈直线上升,5、6月份达最高虫口密度。(4)气候。7月中旬以后因受高温(平均气温28℃以上)影响和稻叶不适蓟马取食为害,虫口受到抑制,数量迅速下降。冬季气候温暖,有利于稻蓟马的越冬和提早繁殖。在6月初到7月上旬,凡阴雨日多、气温维持在22~23℃的天数长,稻蓟马就会大发生。(5)栽培。早稻穗期受害重于晚稻穗期,以盛花期侵入的虫数较多,次为初花期或谢花期,灌浆期最少。双晚秧田,尤其是双晚直播田因叶嫩多汁,易受蓟马集中为害。秧苗三叶期以后,本田自返青至分蘖期是稻蓟马的严重为害期。如稻后种植绿肥和油菜,将为稻蓟马提供充足的食源和越冬场所,小麦面积较大的地方,稻蓟马的为害就有加重的可能。" * , "sympton": * "[为害症状]成虫1、2代和若虫以口器磨破稻叶表皮,吸食汁液,被害叶上出现黄白色小斑点或微孔,叶尖枯黄卷缩,严重时可使成片秧苗发黄发红,状如火烧。稻苗严重受害时,影响稻株返青和分蘖生长受阻,稻苗坐兜。花器受害,影响受粉结实,有的造成空壳。" * , "form": * "[形态](1)成虫。体长1~1.3mm,雌虫略大于雄虫。初羽化时体色为褐色,1~2天后,为深褐色至黑色。头近正方形,触角鞭状7节,第6节至第7节与体同色,其余各节均黄褐色。复眼黑色,两复眼间有3个单眼,呈三角形排列。单眼前鬃长于单眼间鬃,单眼间鬃位于单眼三角形连线外缘。复眼后鬃4根。前胸背板发达,明显长于头部,或约于头长相等,后缘有鬃4根。前翅较后翅大,缨毛细长,有2条纵脉,上脉基鬃4+3根,端鬃3根,下脉鬃11~13根。雄成虫腹部3~7节腹板具腺域,雌成虫第8、9腹节有锯齿状产卵器。(2)卵。肾形,长约0.2mm,宽约0.1mm,初产白色透明,后变淡黄色,半透明,孵化前可透见红色眼点。(3)幼虫。共4龄。初孵时体长0.3~0.5mm,白色透明。触角直伸头前方,触角念珠状,第4节特别膨大。复眼红色,无单眼及翅芽。2龄若虫体长0.6~1.2mm,淡黄绿色,复眼褐色。3龄若虫又称前蛹,体长0.8~1.2mm,淡黄色,触角分向两边,单眼模糊,翅芽始现,复部显著膨大。4龄又称蛹,体长0.8~1.3mm,淡褐色,触角向后翻,在头部与前胸背面可见单眼3个,翅芽伸长达腹部5~7节。" * , "habbit": * "[习性](1)成虫。成虫白天多隐藏在纵卷的叶尖或心叶内,有的潜伏于叶鞘内,早晨、黄昏或阴天多在叶上活动,爬行迅速,受震动后常展翅飞去,有一定迁飞能力,能随气流扩散。雄成虫寿命短,只有几天;雌成虫寿命长,为害季节中多在20天以上。雌虫羽化后经过1~3天开始产卵,产卵期10~20天,一般在羽化后3~6天产卵最多,在适宜的温湿环境下,1头雌虫一生可产卵100粒左右;雌成虫可以进行孤雌生殖,孤雌生殖的产卵量与两性生殖相似。雌成虫有明显趋嫩绿秧苗产卵的习性,在秧田中,一般在2、3叶期以上的秧苗上产卵。雌虫产卵时把产卵器插入稻叶表皮下,散产于叶片表皮下的脉间组织内,对光可看到针孔大小边缘光滑的半透明卵粒。(2)幼虫。多在晚上7~9时孵出,3~5分钟离开壳体,活泼地在叶片上爬行,数分钟后即能取食,1、2龄若虫是取食为害的主要阶段,多聚集中叶耳、叶舌处,特别是在卷针状的心叶内隐匿取食;3龄若虫行动呆滞,取食变缓,此时多集中在叶尖部分,使秧叶自尖起纵卷变黄。因此,大量叶尖纵卷变黄,预兆着3、4龄若虫激增,成虫将盛发。" * , "pestName": "稻蓟马", "alias": "稻直鬃蓟马;俗称灰虫", "id": 3439 */ public boolean petDisStatus; public String petDisSpecName; public int id; public int fieldId; public int petDisId; public String description; public String type; } // 这个不是 public static class Petdisspecws { /** * "rule": * "[发生规律](1)世代。江苏每年发生9~11代,安徽11代,浙江10~12代,福建中部约15代,广东中、南部15代以上。稻蓟马生活周期短,发生代数多,世代重叠,田间发生世代较难划分。(2)越冬。成虫在茭白、麦类、李氏禾、看麦娘等禾本科植物上越冬。翌年3~4月份,成虫先在杂草上活动繁殖,然后迁移到水稻秧田繁殖为害。(3)时期。主要在水稻生长前期为害。迁移代成虫于5月中旬前后在早稻本田,早播中稻秧田产卵繁殖为害,二代成虫于6月上中旬迁入迟栽早稻本田或单季中稻秧、本田和晚稻秧田产卵为害。江淮地区一般于4月中旬起虫口数量呈直线上升,5、6月份达最高虫口密度。(4)气候。7月中旬以后因受高温(平均气温28℃以上)影响和稻叶不适蓟马取食为害,虫口受到抑制,数量迅速下降。冬季气候温暖,有利于稻蓟马的越冬和提早繁殖。在6月初到7月上旬,凡阴雨日多、气温维持在22~23℃的天数长,稻蓟马就会大发生。(5)栽培。早稻穗期受害重于晚稻穗期,以盛花期侵入的虫数较多,次为初花期或谢花期,灌浆期最少。双晚秧田,尤其是双晚直播田因叶嫩多汁,易受蓟马集中为害。秧苗三叶期以后,本田自返青至分蘖期是稻蓟马的严重为害期。如稻后种植绿肥和油菜,将为稻蓟马提供充足的食源和越冬场所,小麦面积较大的地方,稻蓟马的为害就有加重的可能。" * , "sympton": * "[为害症状]成虫1、2代和若虫以口器磨破稻叶表皮,吸食汁液,被害叶上出现黄白色小斑点或微孔,叶尖枯黄卷缩,严重时可使成片秧苗发黄发红,状如火烧。稻苗严重受害时,影响稻株返青和分蘖生长受阻,稻苗坐兜。花器受害,影响受粉结实,有的造成空壳。" * , "form": * "[形态](1)成虫。体长1~1.3mm,雌虫略大于雄虫。初羽化时体色为褐色,1~2天后,为深褐色至黑色。头近正方形,触角鞭状7节,第6节至第7节与体同色,其余各节均黄褐色。复眼黑色,两复眼间有3个单眼,呈三角形排列。单眼前鬃长于单眼间鬃,单眼间鬃位于单眼三角形连线外缘。复眼后鬃4根。前胸背板发达,明显长于头部,或约于头长相等,后缘有鬃4根。前翅较后翅大,缨毛细长,有2条纵脉,上脉基鬃4+3根,端鬃3根,下脉鬃11~13根。雄成虫腹部3~7节腹板具腺域,雌成虫第8、9腹节有锯齿状产卵器。(2)卵。肾形,长约0.2mm,宽约0.1mm,初产白色透明,后变淡黄色,半透明,孵化前可透见红色眼点。(3)幼虫。共4龄。初孵时体长0.3~0.5mm,白色透明。触角直伸头前方,触角念珠状,第4节特别膨大。复眼红色,无单眼及翅芽。2龄若虫体长0.6~1.2mm,淡黄绿色,复眼褐色。3龄若虫又称前蛹,体长0.8~1.2mm,淡黄色,触角分向两边,单眼模糊,翅芽始现,复部显著膨大。4龄又称蛹,体长0.8~1.3mm,淡褐色,触角向后翻,在头部与前胸背面可见单眼3个,翅芽伸长达腹部5~7节。" * , "habbit": * "[习性](1)成虫。成虫白天多隐藏在纵卷的叶尖或心叶内,有的潜伏于叶鞘内,早晨、黄昏或阴天多在叶上活动,爬行迅速,受震动后常展翅飞去,有一定迁飞能力,能随气流扩散。雄成虫寿命短,只有几天;雌成虫寿命长,为害季节中多在20天以上。雌虫羽化后经过1~3天开始产卵,产卵期10~20天,一般在羽化后3~6天产卵最多,在适宜的温湿环境下,1头雌虫一生可产卵100粒左右;雌成虫可以进行孤雌生殖,孤雌生殖的产卵量与两性生殖相似。雌成虫有明显趋嫩绿秧苗产卵的习性,在秧田中,一般在2、3叶期以上的秧苗上产卵。雌虫产卵时把产卵器插入稻叶表皮下,散产于叶片表皮下的脉间组织内,对光可看到针孔大小边缘光滑的半透明卵粒。(2)幼虫。多在晚上7~9时孵出,3~5分钟离开壳体,活泼地在叶片上爬行,数分钟后即能取食,1、2龄若虫是取食为害的主要阶段,多聚集中叶耳、叶舌处,特别是在卷针状的心叶内隐匿取食;3龄若虫行动呆滞,取食变缓,此时多集中在叶尖部分,使秧叶自尖起纵卷变黄。因此,大量叶尖纵卷变黄,预兆着3、4龄若虫激增,成虫将盛发。" * , "pestName": "稻蓟马", "alias": "稻直鬃蓟马;俗称灰虫", "id": 3439 */ public boolean petDisStatus; public String petDisSpecName; public int id; public int fieldId; public int petDisId; public String sympton; public String type; } public class TaskwsEntity implements Comparable<TaskwsEntity>{ public boolean taskStatus;// 状态 public int fieldId; public int taskSpecId; public int subStageId; public int taskId;// public String taskSpecName;// desc public String stageName; public String subStageName; @Override public int compareTo(TaskwsEntity another) { if (taskSpecId < another.taskSpecId) return -1; if (taskSpecId > another.taskSpecId) return 1; return 0; } } public class NatdiswsEntity { /** * natDisId : 10 natDisSpecId : 10 natDisStatus : false fieldId : 10 * natDisSpecName : 台风 */ public int natDisId; public int natDisSpecId; public boolean natDisStatus; public int fieldId; public String natDisSpecName; public String description; public boolean alerttype; } public static class SubStageEntity implements Comparable<SubStageEntity> { public String stageName; public int subStageId; public String subStageName; @Override public int compareTo(SubStageEntity another) { if (subStageId < another.subStageId) return -1; if (subStageId > another.subStageId) return 1; return 0; } } } public static final String TASK_TYPE_ALL = "all"; public static final String TASK_TYPE_NONE = "none"; // all | currentStage | none public static class Param { public String fieldId; public String task; public String lat; public String lon; } }
0
10
0
12122_10
/* * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.dinky.function.util; import org.dinky.assertion.Asserts; import org.dinky.classloader.DinkyClassLoader; import org.dinky.config.Dialect; import org.dinky.context.FlinkUdfPathContextHolder; import org.dinky.data.enums.GatewayType; import org.dinky.data.exception.DinkyException; import org.dinky.data.model.FlinkUdfManifest; import org.dinky.data.model.SystemConfiguration; import org.dinky.executor.CustomTableEnvironment; import org.dinky.function.FunctionFactory; import org.dinky.function.compiler.CustomStringJavaCompiler; import org.dinky.function.compiler.CustomStringScalaCompiler; import org.dinky.function.constant.PathConstant; import org.dinky.function.data.model.UDF; import org.dinky.function.pool.UdfCodePool; import org.dinky.pool.ClassEntity; import org.dinky.pool.ClassPool; import org.dinky.utils.URLUtils; import org.apache.flink.client.python.PythonFunctionFactory; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.PipelineOptions; import org.apache.flink.python.PythonOptions; import org.apache.flink.table.api.ValidationException; import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.functions.UserDefinedFunction; import org.apache.flink.table.functions.UserDefinedFunctionHelper; import java.io.File; import java.io.InputStream; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarFile; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.resource.ResourceUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.ClassScanner; import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.JarClassLoader; import cn.hutool.core.lang.Opt; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.ClassLoaderUtil; import cn.hutool.core.util.ClassUtil; import cn.hutool.core.util.ReUtil; import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; import cn.hutool.crypto.digest.MD5; import cn.hutool.extra.template.TemplateConfig; import cn.hutool.extra.template.TemplateEngine; import cn.hutool.extra.template.engine.freemarker.FreemarkerEngine; import cn.hutool.json.JSONUtil; /** * UDFUtil * * @since 2021/12/27 23:25 */ public class UDFUtil { public static final String FUNCTION_SQL_REGEX = "^CREATE\\s+(?:(?:TEMPORARY|TEMPORARY\\s+SYSTEM)\\s+)?FUNCTION\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(\\S+)\\s+AS\\s+'(\\S+)'\\s*(?:LANGUAGE\\s+(?:JAVA|SCALA|PYTHON)\\s*)?(?:USING\\s+JAR\\s+'(\\S+)'\\s*(?:,\\s*JAR\\s+'(\\S+)'\\s*)*)?"; public static final Pattern PATTERN = Pattern.compile(FUNCTION_SQL_REGEX, Pattern.CASE_INSENSITIVE); public static final String SESSION = "SESSION"; public static final String YARN = "YARN"; public static final String APPLICATION = "APPLICATION"; /** * 网关类型 map 快速获取 session 与 application 等类型,为了减少判断 */ public static final Map<String, List<GatewayType>> GATEWAY_TYPE_MAP = MapUtil.builder( SESSION, Arrays.asList(GatewayType.YARN_SESSION, GatewayType.KUBERNETES_SESSION, GatewayType.STANDALONE)) .put(YARN, Arrays.asList(GatewayType.YARN_APPLICATION, GatewayType.YARN_PER_JOB)) .put(APPLICATION, Arrays.asList(GatewayType.YARN_APPLICATION, GatewayType.KUBERNETES_APPLICATION)) .build(); protected static final Logger log = LoggerFactory.getLogger(UDFUtil.class); /** * 存放 udf md5与版本对应的k,v值 */ protected static final Map<String, Integer> UDF_MD5_MAP = new HashMap<>(); public static final String PYTHON_UDF_ATTR = "(\\S+)\\s*=\\s*ud(?:f|tf|af|taf)"; public static final String PYTHON_UDF_DEF = "@ud(?:f|tf|af|taf).*\\n+def\\s+(.*)\\(.*\\):"; public static final String SCALA_UDF_CLASS = "class\\s+(\\w+)(\\s*\\(.*\\)){0,1}\\s+extends"; public static final String SCALA_UDF_PACKAGE = "package\\s+(.*);"; private static final TemplateEngine ENGINE = new FreemarkerEngine(new TemplateConfig()); /** * 模板解析 * * @param dialect 方言 * @param template 模板 * @param className 类名 * @return {@link String} */ public static String templateParse(String dialect, String template, String className) { List<String> split = StrUtil.split(className, "."); switch (Dialect.get(dialect)) { case JAVA: case SCALA: String clazz = CollUtil.getLast(split); String packageName = StrUtil.strip(className, clazz); Dict data = Dict.create() .set("className", clazz) .set("package", Asserts.isNullString(packageName) ? "" : StrUtil.strip(packageName, ".")); return ENGINE.getTemplate(template).render(data); case PYTHON: default: String clazzName = split.get(0); Dict data2 = Dict.create().set("className", clazzName).set("attr", split.size() > 1 ? split.get(1) : null); return ENGINE.getTemplate(template).render(data2); } } public static String[] initJavaUDF(List<UDF> udf, Integer missionId) { return FunctionFactory.initUDF( CollUtil.newArrayList( CollUtil.filterNew(udf, x -> x.getFunctionLanguage() != FunctionLanguage.PYTHON)), missionId, null) .getJarPaths(); } public static String[] initPythonUDF( List<UDF> udf, GatewayType gatewayType, Integer missionId, Configuration configuration) { return FunctionFactory.initUDF( CollUtil.newArrayList( CollUtil.filterNew(udf, x -> x.getFunctionLanguage() == FunctionLanguage.PYTHON)), missionId, configuration) .getPyPaths(); } public static String getPyFileName(String className) { Asserts.checkNullString(className, "类名不能为空"); return StrUtil.split(className, ".").get(0); } public static String getPyUDFAttr(String code) { return Opt.ofBlankAble(ReUtil.getGroup1(UDFUtil.PYTHON_UDF_ATTR, code)) .orElse(ReUtil.getGroup1(UDFUtil.PYTHON_UDF_DEF, code)); } public static String getScalaFullClassName(String code) { String packageName = ReUtil.getGroup1(UDFUtil.SCALA_UDF_PACKAGE, code); String clazz = ReUtil.getGroup1(UDFUtil.SCALA_UDF_CLASS, code); return String.join(".", Arrays.asList(packageName, clazz)); } @Deprecated public static Map<String, List<String>> buildJar(List<UDF> codeList) { List<String> successList = new ArrayList<>(); List<String> failedList = new ArrayList<>(); String tmpPath = PathConstant.UDF_PATH; String udfJarPath = PathConstant.UDF_JAR_TMP_PATH; // 删除jar缓存 FileUtil.del(udfJarPath); codeList.forEach(udf -> { if (udf.getFunctionLanguage() == FunctionLanguage.JAVA) { CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(udf.getCode()); boolean res = compiler.compilerToTmpPath(tmpPath); String className = compiler.getFullClassName(); if (res) { log.info("class compile successful:{}", className); log.info("compilerTakeTime:" + compiler.getCompilerTakeTime()); ClassPool.push(ClassEntity.build(className, udf.getCode())); successList.add(className); } else { log.warn("class compile failed:{}", className); log.warn(compiler.getCompilerMessage()); failedList.add(className); } } else if (udf.getFunctionLanguage() == FunctionLanguage.SCALA) { String className = udf.getClassName(); if (CustomStringScalaCompiler.getInterpreter().compileString(udf.getCode())) { log.info("scala class compile successful:{}", className); ClassPool.push(ClassEntity.build(className, udf.getCode())); successList.add(className); } else { log.warn("scala class compile failed:{}", className); failedList.add(className); } } }); String[] clazzs = successList.stream() .map(className -> StrUtil.replace(className, ".", "/") + ".class") .toArray(String[]::new); InputStream[] fileInputStreams = successList.stream() .map(className -> tmpPath + StrUtil.replace(className, ".", "/") + ".class") .map(FileUtil::getInputStream) .toArray(InputStream[]::new); // 编译好的文件打包jar try (ZipWriter zipWriter = new ZipWriter(FileUtil.file(udfJarPath), Charset.defaultCharset())) { zipWriter.add(clazzs, fileInputStreams); } String md5 = md5sum(udfJarPath); return MapUtil.builder("success", successList) .put("failed", failedList) .put("md5", Collections.singletonList(md5)) .build(); } /** * 得到udf版本和构建jar * * @param codeList 代码列表 * @return {@link String} */ @Deprecated public static String getUdfFileAndBuildJar(List<UDF> codeList) { // 1. 检查所有jar的版本,通常名字为 udf-${version}.jar;如 udf-1.jar,没有这个目录则跳过 FileUtil.mkdir(PathConstant.UDF_PATH); try { // 获取所有的udf jar的 md5 值,放入 map 里面 if (UDF_MD5_MAP.isEmpty()) { scanUDFMD5(); } // 2. 如果有匹配的,返回对应udf 版本,没有则构建jar,对应信息写入 jar String md5 = buildJar(codeList).get("md5").get(0); if (UDF_MD5_MAP.containsKey(md5)) { FileUtil.del(PathConstant.UDF_JAR_TMP_PATH); return StrUtil.format("udf-{}.jar", UDF_MD5_MAP.get(md5)); } // 3. 生成新版本jar Integer newVersion = UDF_MD5_MAP.values().size() > 0 ? CollUtil.max(UDF_MD5_MAP.values()) + 1 : 1; String jarName = StrUtil.format("udf-{}.jar", newVersion); String newName = PathConstant.UDF_PATH + jarName; FileUtil.rename(FileUtil.file(PathConstant.UDF_JAR_TMP_PATH), newName, true); UDF_MD5_MAP.put(md5, newVersion); return jarName; } catch (Exception e) { log.warn("builder jar failed! please check env. msg:{}", e.getMessage()); throw new RuntimeException(e); } } /** * 扫描udf包文件,写入md5到 UDF_MD5_MAP */ @Deprecated private static void scanUDFMD5() { List<String> fileList = FileUtil.listFileNames(PathConstant.UDF_PATH); fileList.stream() .filter(fileName -> ReUtil.isMatch(PathConstant.UDF_JAR_RULE, fileName)) .distinct() .forEach(fileName -> { Integer version = Convert.toInt(ReUtil.getGroup0(PathConstant.UDF_VERSION_RULE, fileName)); UDF_MD5_MAP.put(md5sum(PathConstant.UDF_PATH + fileName), version); }); } private static String md5sum(String filePath) { return MD5.create().digestHex(FileUtil.file(filePath)); } public static boolean isUdfStatement(Pattern pattern, String statement) { return !StrUtil.isBlank(statement) && CollUtil.isNotEmpty(ReUtil.findAll(pattern, statement, 0)); } public static UDF toUDF(String statement, DinkyClassLoader classLoader) { if (isUdfStatement(PATTERN, statement)) { List<String> groups = CollUtil.removeEmpty(ReUtil.getAllGroups(PATTERN, statement)); String udfName = groups.get(1); String className = groups.get(2); if (groups.size() > 3) { // if statement contains using jar, using these jars, not to lookup ClassLoaderUtil // pool return null; } FlinkUdfPathContextHolder udfPathContextHolder = classLoader.getUdfPathContextHolder(); if (ClassLoaderUtil.isPresent(className)) { // 获取已经加载在java的类,对应的包路径 try { udfPathContextHolder.addUdfPath(FileUtil.file(classLoader .loadClass(className) .getProtectionDomain() .getCodeSource() .getLocation() .getPath())); } catch (ClassNotFoundException e) { throw new DinkyException(e); } return null; } UDF udf = UdfCodePool.getUDF(className); if (udf != null) { return UDF.builder() .name(udfName) .className(className) .code(udf.getCode()) .functionLanguage(udf.getFunctionLanguage()) .build(); } String gitPackage = UdfCodePool.getGitPackage(className); if (StrUtil.isNotBlank(gitPackage) && FileUtil.exist(gitPackage)) { if ("jar".equals(FileUtil.getSuffix(gitPackage))) { udfPathContextHolder.addUdfPath(new File(gitPackage)); } else { udfPathContextHolder.addPyUdfPath(new File(gitPackage)); } } } return null; } // create FlinkUdfPathContextHolder from UdfCodePool public static FlinkUdfPathContextHolder createFlinkUdfPathContextHolder() { FlinkUdfPathContextHolder udfPathContextHolder = new FlinkUdfPathContextHolder(); UdfCodePool.getUdfCodePool().values().forEach(udf -> { if (udf.getFunctionLanguage() == FunctionLanguage.PYTHON) { udfPathContextHolder.addPyUdfPath(new File(udf.getCode())); } else { udfPathContextHolder.addUdfPath(new File(udf.getCode())); } }); UdfCodePool.getGitPool().values().forEach(gitPackage -> { if ("jar".equals(FileUtil.getSuffix(gitPackage))) { udfPathContextHolder.addUdfPath(URLUtils.toFile(gitPackage)); } else { udfPathContextHolder.addPyUdfPath(URLUtils.toFile(gitPackage)); } }); return udfPathContextHolder; } public static List<Class<?>> getUdfClassByJar(File jarPath) { Assert.notNull(jarPath); List<Class<?>> classList = new ArrayList<>(); try (JarClassLoader loader = new JarClassLoader()) { loader.addJar(jarPath); ClassScanner classScanner = new ClassScanner("", aClass -> ClassUtil.isAssignable(UserDefinedFunction.class, aClass)); classScanner.setClassLoader(loader); ReflectUtil.invoke(classScanner, "scanJar", new JarFile(jarPath)); Set<Class<? extends UserDefinedFunction>> classes = (Set<Class<? extends UserDefinedFunction>>) ReflectUtil.getFieldValue(classScanner, "classes"); for (Class<? extends UserDefinedFunction> aClass : classes) { try { UserDefinedFunctionHelper.validateClass(aClass); classList.add(aClass); } catch (Exception ex) { throw new DinkyException(); } } } catch (ValidationException e) { throw e; } catch (Exception e) { e.printStackTrace(); } return classList; } public static List<String> getPythonUdfList(String udfFile) { return getPythonUdfList(SystemConfiguration.getInstances().getPythonHome(), udfFile); } private static final String PYTHON_FUNC_FILE_MD5 = MD5.create().digestHex(ResourceUtil.readUtf8Str("getPyFuncList.py")); public static List<String> getPythonUdfList(String pythonPath, String udfFile) { File checkFile = new File(PathConstant.TMP_PATH, "getPyFuncList.py"); if (!checkFile.exists() || !MD5.create().digestHex(checkFile).equals(PYTHON_FUNC_FILE_MD5)) { FileUtil.writeUtf8String(ResourceUtil.readUtf8Str("getPyFuncList.py"), checkFile); } List<String> udfNameList = execPyAndGetUdfNameList(pythonPath, checkFile.getAbsolutePath(), udfFile); List<String> successUdfList = new ArrayList<>(); if (CollUtil.isEmpty(udfNameList)) { return new ArrayList<>(); } for (String udfName : udfNameList) { if (StrUtil.isBlank(udfName)) { continue; } Configuration configuration = new Configuration(); configuration.set(PythonOptions.PYTHON_FILES, udfFile); configuration.set(PythonOptions.PYTHON_CLIENT_EXECUTABLE, pythonPath); configuration.set(PythonOptions.PYTHON_EXECUTABLE, pythonPath); try { PythonFunctionFactory.getPythonFunction(udfName, configuration, null); successUdfList.add(udfName); } catch (Exception e) { log.error("", e); } } return successUdfList; } private static List<String> execPyAndGetUdfNameList(String pyPath, String pyFile, String checkPyFile) { try { // 运行Python3脚本的命令,换成自己的即可 String shell = StrUtil.join(" ", Arrays.asList(Opt.ofBlankAble(pyPath).orElse("python3"), pyFile, checkPyFile)); return StrUtil.split(StrUtil.trim(RuntimeUtil.execForStr(shell)), ","); } catch (Exception e) { throw new DinkyException(e); } } public static void addConfigurationClsAndJars( CustomTableEnvironment customTableEnvironment, List<URL> jarList, List<URL> classpaths) { customTableEnvironment.addConfiguration( PipelineOptions.CLASSPATHS, classpaths.stream().map(URL::toString).collect(Collectors.toList())); customTableEnvironment.addConfiguration( PipelineOptions.JARS, jarList.stream().map(URL::toString).collect(Collectors.toList())); } public static void writeManifest( Integer taskId, List<URL> jarPaths, FlinkUdfPathContextHolder udfPathContextHolder) { FlinkUdfManifest flinkUdfManifest = new FlinkUdfManifest(); flinkUdfManifest.setJars(jarPaths); flinkUdfManifest.setPythonFiles(udfPathContextHolder.getPyUdfFile().stream() .map(URLUtil::getURL) .collect(Collectors.toList())); FileUtil.writeUtf8String( JSONUtil.toJsonStr(flinkUdfManifest), PathConstant.getUdfPackagePath(taskId) + PathConstant.DEP_MANIFEST); } }
DataLinkDC/dinky
dinky-function/src/main/java/org/dinky/function/util/UDFUtil.java
5,130
// 2. 如果有匹配的,返回对应udf 版本,没有则构建jar,对应信息写入 jar
line_comment
zh-cn
/* * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.dinky.function.util; import org.dinky.assertion.Asserts; import org.dinky.classloader.DinkyClassLoader; import org.dinky.config.Dialect; import org.dinky.context.FlinkUdfPathContextHolder; import org.dinky.data.enums.GatewayType; import org.dinky.data.exception.DinkyException; import org.dinky.data.model.FlinkUdfManifest; import org.dinky.data.model.SystemConfiguration; import org.dinky.executor.CustomTableEnvironment; import org.dinky.function.FunctionFactory; import org.dinky.function.compiler.CustomStringJavaCompiler; import org.dinky.function.compiler.CustomStringScalaCompiler; import org.dinky.function.constant.PathConstant; import org.dinky.function.data.model.UDF; import org.dinky.function.pool.UdfCodePool; import org.dinky.pool.ClassEntity; import org.dinky.pool.ClassPool; import org.dinky.utils.URLUtils; import org.apache.flink.client.python.PythonFunctionFactory; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.PipelineOptions; import org.apache.flink.python.PythonOptions; import org.apache.flink.table.api.ValidationException; import org.apache.flink.table.catalog.FunctionLanguage; import org.apache.flink.table.functions.UserDefinedFunction; import org.apache.flink.table.functions.UserDefinedFunctionHelper; import java.io.File; import java.io.InputStream; import java.net.URL; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.jar.JarFile; import java.util.regex.Pattern; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.convert.Convert; import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.resource.ResourceUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.ClassScanner; import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.JarClassLoader; import cn.hutool.core.lang.Opt; import cn.hutool.core.map.MapUtil; import cn.hutool.core.util.ClassLoaderUtil; import cn.hutool.core.util.ClassUtil; import cn.hutool.core.util.ReUtil; import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.URLUtil; import cn.hutool.crypto.digest.MD5; import cn.hutool.extra.template.TemplateConfig; import cn.hutool.extra.template.TemplateEngine; import cn.hutool.extra.template.engine.freemarker.FreemarkerEngine; import cn.hutool.json.JSONUtil; /** * UDFUtil * * @since 2021/12/27 23:25 */ public class UDFUtil { public static final String FUNCTION_SQL_REGEX = "^CREATE\\s+(?:(?:TEMPORARY|TEMPORARY\\s+SYSTEM)\\s+)?FUNCTION\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?(\\S+)\\s+AS\\s+'(\\S+)'\\s*(?:LANGUAGE\\s+(?:JAVA|SCALA|PYTHON)\\s*)?(?:USING\\s+JAR\\s+'(\\S+)'\\s*(?:,\\s*JAR\\s+'(\\S+)'\\s*)*)?"; public static final Pattern PATTERN = Pattern.compile(FUNCTION_SQL_REGEX, Pattern.CASE_INSENSITIVE); public static final String SESSION = "SESSION"; public static final String YARN = "YARN"; public static final String APPLICATION = "APPLICATION"; /** * 网关类型 map 快速获取 session 与 application 等类型,为了减少判断 */ public static final Map<String, List<GatewayType>> GATEWAY_TYPE_MAP = MapUtil.builder( SESSION, Arrays.asList(GatewayType.YARN_SESSION, GatewayType.KUBERNETES_SESSION, GatewayType.STANDALONE)) .put(YARN, Arrays.asList(GatewayType.YARN_APPLICATION, GatewayType.YARN_PER_JOB)) .put(APPLICATION, Arrays.asList(GatewayType.YARN_APPLICATION, GatewayType.KUBERNETES_APPLICATION)) .build(); protected static final Logger log = LoggerFactory.getLogger(UDFUtil.class); /** * 存放 udf md5与版本对应的k,v值 */ protected static final Map<String, Integer> UDF_MD5_MAP = new HashMap<>(); public static final String PYTHON_UDF_ATTR = "(\\S+)\\s*=\\s*ud(?:f|tf|af|taf)"; public static final String PYTHON_UDF_DEF = "@ud(?:f|tf|af|taf).*\\n+def\\s+(.*)\\(.*\\):"; public static final String SCALA_UDF_CLASS = "class\\s+(\\w+)(\\s*\\(.*\\)){0,1}\\s+extends"; public static final String SCALA_UDF_PACKAGE = "package\\s+(.*);"; private static final TemplateEngine ENGINE = new FreemarkerEngine(new TemplateConfig()); /** * 模板解析 * * @param dialect 方言 * @param template 模板 * @param className 类名 * @return {@link String} */ public static String templateParse(String dialect, String template, String className) { List<String> split = StrUtil.split(className, "."); switch (Dialect.get(dialect)) { case JAVA: case SCALA: String clazz = CollUtil.getLast(split); String packageName = StrUtil.strip(className, clazz); Dict data = Dict.create() .set("className", clazz) .set("package", Asserts.isNullString(packageName) ? "" : StrUtil.strip(packageName, ".")); return ENGINE.getTemplate(template).render(data); case PYTHON: default: String clazzName = split.get(0); Dict data2 = Dict.create().set("className", clazzName).set("attr", split.size() > 1 ? split.get(1) : null); return ENGINE.getTemplate(template).render(data2); } } public static String[] initJavaUDF(List<UDF> udf, Integer missionId) { return FunctionFactory.initUDF( CollUtil.newArrayList( CollUtil.filterNew(udf, x -> x.getFunctionLanguage() != FunctionLanguage.PYTHON)), missionId, null) .getJarPaths(); } public static String[] initPythonUDF( List<UDF> udf, GatewayType gatewayType, Integer missionId, Configuration configuration) { return FunctionFactory.initUDF( CollUtil.newArrayList( CollUtil.filterNew(udf, x -> x.getFunctionLanguage() == FunctionLanguage.PYTHON)), missionId, configuration) .getPyPaths(); } public static String getPyFileName(String className) { Asserts.checkNullString(className, "类名不能为空"); return StrUtil.split(className, ".").get(0); } public static String getPyUDFAttr(String code) { return Opt.ofBlankAble(ReUtil.getGroup1(UDFUtil.PYTHON_UDF_ATTR, code)) .orElse(ReUtil.getGroup1(UDFUtil.PYTHON_UDF_DEF, code)); } public static String getScalaFullClassName(String code) { String packageName = ReUtil.getGroup1(UDFUtil.SCALA_UDF_PACKAGE, code); String clazz = ReUtil.getGroup1(UDFUtil.SCALA_UDF_CLASS, code); return String.join(".", Arrays.asList(packageName, clazz)); } @Deprecated public static Map<String, List<String>> buildJar(List<UDF> codeList) { List<String> successList = new ArrayList<>(); List<String> failedList = new ArrayList<>(); String tmpPath = PathConstant.UDF_PATH; String udfJarPath = PathConstant.UDF_JAR_TMP_PATH; // 删除jar缓存 FileUtil.del(udfJarPath); codeList.forEach(udf -> { if (udf.getFunctionLanguage() == FunctionLanguage.JAVA) { CustomStringJavaCompiler compiler = new CustomStringJavaCompiler(udf.getCode()); boolean res = compiler.compilerToTmpPath(tmpPath); String className = compiler.getFullClassName(); if (res) { log.info("class compile successful:{}", className); log.info("compilerTakeTime:" + compiler.getCompilerTakeTime()); ClassPool.push(ClassEntity.build(className, udf.getCode())); successList.add(className); } else { log.warn("class compile failed:{}", className); log.warn(compiler.getCompilerMessage()); failedList.add(className); } } else if (udf.getFunctionLanguage() == FunctionLanguage.SCALA) { String className = udf.getClassName(); if (CustomStringScalaCompiler.getInterpreter().compileString(udf.getCode())) { log.info("scala class compile successful:{}", className); ClassPool.push(ClassEntity.build(className, udf.getCode())); successList.add(className); } else { log.warn("scala class compile failed:{}", className); failedList.add(className); } } }); String[] clazzs = successList.stream() .map(className -> StrUtil.replace(className, ".", "/") + ".class") .toArray(String[]::new); InputStream[] fileInputStreams = successList.stream() .map(className -> tmpPath + StrUtil.replace(className, ".", "/") + ".class") .map(FileUtil::getInputStream) .toArray(InputStream[]::new); // 编译好的文件打包jar try (ZipWriter zipWriter = new ZipWriter(FileUtil.file(udfJarPath), Charset.defaultCharset())) { zipWriter.add(clazzs, fileInputStreams); } String md5 = md5sum(udfJarPath); return MapUtil.builder("success", successList) .put("failed", failedList) .put("md5", Collections.singletonList(md5)) .build(); } /** * 得到udf版本和构建jar * * @param codeList 代码列表 * @return {@link String} */ @Deprecated public static String getUdfFileAndBuildJar(List<UDF> codeList) { // 1. 检查所有jar的版本,通常名字为 udf-${version}.jar;如 udf-1.jar,没有这个目录则跳过 FileUtil.mkdir(PathConstant.UDF_PATH); try { // 获取所有的udf jar的 md5 值,放入 map 里面 if (UDF_MD5_MAP.isEmpty()) { scanUDFMD5(); } // 2. <SUF> String md5 = buildJar(codeList).get("md5").get(0); if (UDF_MD5_MAP.containsKey(md5)) { FileUtil.del(PathConstant.UDF_JAR_TMP_PATH); return StrUtil.format("udf-{}.jar", UDF_MD5_MAP.get(md5)); } // 3. 生成新版本jar Integer newVersion = UDF_MD5_MAP.values().size() > 0 ? CollUtil.max(UDF_MD5_MAP.values()) + 1 : 1; String jarName = StrUtil.format("udf-{}.jar", newVersion); String newName = PathConstant.UDF_PATH + jarName; FileUtil.rename(FileUtil.file(PathConstant.UDF_JAR_TMP_PATH), newName, true); UDF_MD5_MAP.put(md5, newVersion); return jarName; } catch (Exception e) { log.warn("builder jar failed! please check env. msg:{}", e.getMessage()); throw new RuntimeException(e); } } /** * 扫描udf包文件,写入md5到 UDF_MD5_MAP */ @Deprecated private static void scanUDFMD5() { List<String> fileList = FileUtil.listFileNames(PathConstant.UDF_PATH); fileList.stream() .filter(fileName -> ReUtil.isMatch(PathConstant.UDF_JAR_RULE, fileName)) .distinct() .forEach(fileName -> { Integer version = Convert.toInt(ReUtil.getGroup0(PathConstant.UDF_VERSION_RULE, fileName)); UDF_MD5_MAP.put(md5sum(PathConstant.UDF_PATH + fileName), version); }); } private static String md5sum(String filePath) { return MD5.create().digestHex(FileUtil.file(filePath)); } public static boolean isUdfStatement(Pattern pattern, String statement) { return !StrUtil.isBlank(statement) && CollUtil.isNotEmpty(ReUtil.findAll(pattern, statement, 0)); } public static UDF toUDF(String statement, DinkyClassLoader classLoader) { if (isUdfStatement(PATTERN, statement)) { List<String> groups = CollUtil.removeEmpty(ReUtil.getAllGroups(PATTERN, statement)); String udfName = groups.get(1); String className = groups.get(2); if (groups.size() > 3) { // if statement contains using jar, using these jars, not to lookup ClassLoaderUtil // pool return null; } FlinkUdfPathContextHolder udfPathContextHolder = classLoader.getUdfPathContextHolder(); if (ClassLoaderUtil.isPresent(className)) { // 获取已经加载在java的类,对应的包路径 try { udfPathContextHolder.addUdfPath(FileUtil.file(classLoader .loadClass(className) .getProtectionDomain() .getCodeSource() .getLocation() .getPath())); } catch (ClassNotFoundException e) { throw new DinkyException(e); } return null; } UDF udf = UdfCodePool.getUDF(className); if (udf != null) { return UDF.builder() .name(udfName) .className(className) .code(udf.getCode()) .functionLanguage(udf.getFunctionLanguage()) .build(); } String gitPackage = UdfCodePool.getGitPackage(className); if (StrUtil.isNotBlank(gitPackage) && FileUtil.exist(gitPackage)) { if ("jar".equals(FileUtil.getSuffix(gitPackage))) { udfPathContextHolder.addUdfPath(new File(gitPackage)); } else { udfPathContextHolder.addPyUdfPath(new File(gitPackage)); } } } return null; } // create FlinkUdfPathContextHolder from UdfCodePool public static FlinkUdfPathContextHolder createFlinkUdfPathContextHolder() { FlinkUdfPathContextHolder udfPathContextHolder = new FlinkUdfPathContextHolder(); UdfCodePool.getUdfCodePool().values().forEach(udf -> { if (udf.getFunctionLanguage() == FunctionLanguage.PYTHON) { udfPathContextHolder.addPyUdfPath(new File(udf.getCode())); } else { udfPathContextHolder.addUdfPath(new File(udf.getCode())); } }); UdfCodePool.getGitPool().values().forEach(gitPackage -> { if ("jar".equals(FileUtil.getSuffix(gitPackage))) { udfPathContextHolder.addUdfPath(URLUtils.toFile(gitPackage)); } else { udfPathContextHolder.addPyUdfPath(URLUtils.toFile(gitPackage)); } }); return udfPathContextHolder; } public static List<Class<?>> getUdfClassByJar(File jarPath) { Assert.notNull(jarPath); List<Class<?>> classList = new ArrayList<>(); try (JarClassLoader loader = new JarClassLoader()) { loader.addJar(jarPath); ClassScanner classScanner = new ClassScanner("", aClass -> ClassUtil.isAssignable(UserDefinedFunction.class, aClass)); classScanner.setClassLoader(loader); ReflectUtil.invoke(classScanner, "scanJar", new JarFile(jarPath)); Set<Class<? extends UserDefinedFunction>> classes = (Set<Class<? extends UserDefinedFunction>>) ReflectUtil.getFieldValue(classScanner, "classes"); for (Class<? extends UserDefinedFunction> aClass : classes) { try { UserDefinedFunctionHelper.validateClass(aClass); classList.add(aClass); } catch (Exception ex) { throw new DinkyException(); } } } catch (ValidationException e) { throw e; } catch (Exception e) { e.printStackTrace(); } return classList; } public static List<String> getPythonUdfList(String udfFile) { return getPythonUdfList(SystemConfiguration.getInstances().getPythonHome(), udfFile); } private static final String PYTHON_FUNC_FILE_MD5 = MD5.create().digestHex(ResourceUtil.readUtf8Str("getPyFuncList.py")); public static List<String> getPythonUdfList(String pythonPath, String udfFile) { File checkFile = new File(PathConstant.TMP_PATH, "getPyFuncList.py"); if (!checkFile.exists() || !MD5.create().digestHex(checkFile).equals(PYTHON_FUNC_FILE_MD5)) { FileUtil.writeUtf8String(ResourceUtil.readUtf8Str("getPyFuncList.py"), checkFile); } List<String> udfNameList = execPyAndGetUdfNameList(pythonPath, checkFile.getAbsolutePath(), udfFile); List<String> successUdfList = new ArrayList<>(); if (CollUtil.isEmpty(udfNameList)) { return new ArrayList<>(); } for (String udfName : udfNameList) { if (StrUtil.isBlank(udfName)) { continue; } Configuration configuration = new Configuration(); configuration.set(PythonOptions.PYTHON_FILES, udfFile); configuration.set(PythonOptions.PYTHON_CLIENT_EXECUTABLE, pythonPath); configuration.set(PythonOptions.PYTHON_EXECUTABLE, pythonPath); try { PythonFunctionFactory.getPythonFunction(udfName, configuration, null); successUdfList.add(udfName); } catch (Exception e) { log.error("", e); } } return successUdfList; } private static List<String> execPyAndGetUdfNameList(String pyPath, String pyFile, String checkPyFile) { try { // 运行Python3脚本的命令,换成自己的即可 String shell = StrUtil.join(" ", Arrays.asList(Opt.ofBlankAble(pyPath).orElse("python3"), pyFile, checkPyFile)); return StrUtil.split(StrUtil.trim(RuntimeUtil.execForStr(shell)), ","); } catch (Exception e) { throw new DinkyException(e); } } public static void addConfigurationClsAndJars( CustomTableEnvironment customTableEnvironment, List<URL> jarList, List<URL> classpaths) { customTableEnvironment.addConfiguration( PipelineOptions.CLASSPATHS, classpaths.stream().map(URL::toString).collect(Collectors.toList())); customTableEnvironment.addConfiguration( PipelineOptions.JARS, jarList.stream().map(URL::toString).collect(Collectors.toList())); } public static void writeManifest( Integer taskId, List<URL> jarPaths, FlinkUdfPathContextHolder udfPathContextHolder) { FlinkUdfManifest flinkUdfManifest = new FlinkUdfManifest(); flinkUdfManifest.setJars(jarPaths); flinkUdfManifest.setPythonFiles(udfPathContextHolder.getPyUdfFile().stream() .map(URLUtil::getURL) .collect(Collectors.toList())); FileUtil.writeUtf8String( JSONUtil.toJsonStr(flinkUdfManifest), PathConstant.getUdfPackagePath(taskId) + PathConstant.DEP_MANIFEST); } }
1
43
1
31252_1
package org.datasays.wes.demo.fetch; import okhttp3.Cache; import okhttp3.OkHttpClient; import org.datasays.util.JsonObjGetter; import org.datasays.util.WCfg; import org.datasays.util.WPage; import org.datasays.util.WPageIterator; import org.datasays.wes.EsBaseService; import org.datasays.wes.core.HttpException; import org.datasays.wes.core.JsonObj; import org.datasays.wes.core.RequestInfo; import org.datasays.wes.core.WHttpClient; import org.datasays.wes.toolkit.WGsonConvert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by watano on 2016/12/5. */ public class BaiduFetcher { private static Logger LOG = LoggerFactory.getLogger(BaiduFetcher.class); private final int FetchInterval = 1;//间隔时间,单位s public final String index = "fetchdata"; public final String type = "BaiduMap"; private WHttpClient baiduClient; private EsBaseService esHelper; public String appKey; public String appSecret; public BaiduFetcher(String appKey, String appSecret) { this.appKey = appKey; this.appSecret = appSecret; } public void init() { OkHttpClient.Builder cBuilder = new OkHttpClient.Builder(); cBuilder.cache(new Cache(new File("./build/baidu"), 10000)); baiduClient = new WHttpClient(cBuilder.build(), new WGsonConvert()); baiduClient.setLogFlag(false, false, true); esHelper = new EsBaseService(); esHelper.init(WCfg.getValue("ES.server"), null, null); } private RequestInfo create() { RequestInfo action = new RequestInfo("http://api.map.baidu.com/place/v2/"); action.addParams("ak", appKey); return action; } public JsonObjGetter searchPOIByRegion(WPage page, String query, String region) throws HttpException { RequestInfo action = create(); action.setUrl("search"); action.addParams("scope", 2); action.addParams("output", "json"); action.addParams("query", query); action.addParams("region", region); action.addParams("page_size", page.getSize()); if (page.getPageNo() > 0) { action.addParams("page_num", page.getPageNo()-1); } LOG.info(page.toText()); JsonObjGetter result = new JsonObjGetter(baiduClient.get(action, Object.class)); if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) { if (result.num("total") != null && result.num("total").intValue() > 0) { page.setTotal(result.num("total").intValue()); } } return result; } public void fetchALLPOIByRegion(String query, String region){ WPage page = new WPage(); WPageIterator<Object> pageIterator = new WPageIterator<Object>(page) { @Override public void doSearch() { try { JsonObjGetter result = searchPOIByRegion(getPage(), query, region); if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) { int total = 0; if (result.num("total") != null && result.num("total").intValue() > 0) { total = result.num("total").intValue(); } List<Object> items = new ArrayList<>(); if (result.list("results") != null) { items.addAll(result.list("results")); } update(items, total); Thread.sleep(FetchInterval*1000); } } catch (Exception e) { e.printStackTrace(); } } }; while (pageIterator.hasNext()) { Object item = pageIterator.next(); save(item); } } public void save(Object item) { try { esHelper.index(index, type, null, item); } catch (Exception e) { LOG.error(e.getMessage(), e); } } public static void main(String[] args) { JsonObj allIndustry = new JsonObj(); allIndustry.lstAdd("美食", "中餐厅", "外国餐厅", "小吃快餐店", "蛋糕甜品店", "咖啡厅", "茶座", "酒吧"); allIndustry.lstAdd("酒店", "星级酒店", "快捷酒店", "公寓式酒店"); allIndustry.lstAdd("购物", "购物中心", "超市", "便利店", "家居建材", "家电数码", "商铺", "集市"); allIndustry.lstAdd("生活服务", "通讯营业厅", "邮局", "物流公司", "售票处", "洗衣店", "图文快印店", "照相馆", "房产中介机构", "公用事业", "维修点", "家政服务", "殡葬服务", "彩票销售点", "宠物服务", "报刊亭", "公共厕所"); allIndustry.lstAdd("丽人", "美容", "美发", "美甲", "美体"); allIndustry.lstAdd("旅游景点", "公园", "动物园", "植物园", "游乐园", "博物馆", "水族馆", "海滨浴场", "文物古迹", "教堂", "风景区"); allIndustry.lstAdd("休闲娱乐", "度假村", "农家院", "电影院", "KTV", "剧院", "歌舞厅", "网吧", "游戏场所", "洗浴按摩", "休闲广场"); allIndustry.lstAdd("运动健身", "体育场馆", "极限运动场所", "健身中心"); allIndustry.lstAdd("教育培训", "高等院校", "中学", "小学", "幼儿园", "成人教育", "亲子教育", "特殊教育学校", "留学中介机构", "科研机构", "培训机构", "图书馆", "科技馆"); allIndustry.lstAdd("文化传媒", "新闻出版", "广播电视", "艺术团体", "美术馆", "展览馆", "文化宫"); allIndustry.lstAdd("医疗", "综合医院", "专科医院", "诊所", "药店", "体检机构", "疗养院", "急救中心", "疾控中心"); allIndustry.lstAdd("汽车服务", "汽车销售", "汽车维修", "汽车美容", "汽车配件", "汽车租赁", "汽车检测场"); allIndustry.lstAdd("交通设施", "飞机场", "火车站", "地铁站", "长途汽车站", "公交车站", "港口", "停车场", "加油加气站", "服务区", "收费站", "桥"); allIndustry.lstAdd("金融", "银行", "ATM", "信用社", "投资理财", "典当行"); allIndustry.lstAdd("房地产", "写字楼", "住宅区", "宿舍"); allIndustry.lstAdd("公司企业", "公司", "园区", "农林园艺", "厂矿"); allIndustry.lstAdd("政府机构", "中央机构", "各级政府", "行政单位", "公检法机构", "涉外机构", "党派团体", "福利机构", "政治教育机构"); BaiduFetcher fetcher = new BaiduFetcher(args[0], args[1]); fetcher.init(); String region = "玉溪"; for(String mainIndustry: new String[]{"美食", "酒店", "购物", "丽人", "休闲娱乐"}){ for(Object industry: (Object[]) allIndustry.get(mainIndustry)){ fetcher.fetchALLPOIByRegion(industry.toString(), region); } } } }
DataSays/wES
wES-demo/src/main/java/org/datasays/wes/demo/fetch/BaiduFetcher.java
2,281
//间隔时间,单位s
line_comment
zh-cn
package org.datasays.wes.demo.fetch; import okhttp3.Cache; import okhttp3.OkHttpClient; import org.datasays.util.JsonObjGetter; import org.datasays.util.WCfg; import org.datasays.util.WPage; import org.datasays.util.WPageIterator; import org.datasays.wes.EsBaseService; import org.datasays.wes.core.HttpException; import org.datasays.wes.core.JsonObj; import org.datasays.wes.core.RequestInfo; import org.datasays.wes.core.WHttpClient; import org.datasays.wes.toolkit.WGsonConvert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Created by watano on 2016/12/5. */ public class BaiduFetcher { private static Logger LOG = LoggerFactory.getLogger(BaiduFetcher.class); private final int FetchInterval = 1;//间隔 <SUF> public final String index = "fetchdata"; public final String type = "BaiduMap"; private WHttpClient baiduClient; private EsBaseService esHelper; public String appKey; public String appSecret; public BaiduFetcher(String appKey, String appSecret) { this.appKey = appKey; this.appSecret = appSecret; } public void init() { OkHttpClient.Builder cBuilder = new OkHttpClient.Builder(); cBuilder.cache(new Cache(new File("./build/baidu"), 10000)); baiduClient = new WHttpClient(cBuilder.build(), new WGsonConvert()); baiduClient.setLogFlag(false, false, true); esHelper = new EsBaseService(); esHelper.init(WCfg.getValue("ES.server"), null, null); } private RequestInfo create() { RequestInfo action = new RequestInfo("http://api.map.baidu.com/place/v2/"); action.addParams("ak", appKey); return action; } public JsonObjGetter searchPOIByRegion(WPage page, String query, String region) throws HttpException { RequestInfo action = create(); action.setUrl("search"); action.addParams("scope", 2); action.addParams("output", "json"); action.addParams("query", query); action.addParams("region", region); action.addParams("page_size", page.getSize()); if (page.getPageNo() > 0) { action.addParams("page_num", page.getPageNo()-1); } LOG.info(page.toText()); JsonObjGetter result = new JsonObjGetter(baiduClient.get(action, Object.class)); if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) { if (result.num("total") != null && result.num("total").intValue() > 0) { page.setTotal(result.num("total").intValue()); } } return result; } public void fetchALLPOIByRegion(String query, String region){ WPage page = new WPage(); WPageIterator<Object> pageIterator = new WPageIterator<Object>(page) { @Override public void doSearch() { try { JsonObjGetter result = searchPOIByRegion(getPage(), query, region); if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) { int total = 0; if (result.num("total") != null && result.num("total").intValue() > 0) { total = result.num("total").intValue(); } List<Object> items = new ArrayList<>(); if (result.list("results") != null) { items.addAll(result.list("results")); } update(items, total); Thread.sleep(FetchInterval*1000); } } catch (Exception e) { e.printStackTrace(); } } }; while (pageIterator.hasNext()) { Object item = pageIterator.next(); save(item); } } public void save(Object item) { try { esHelper.index(index, type, null, item); } catch (Exception e) { LOG.error(e.getMessage(), e); } } public static void main(String[] args) { JsonObj allIndustry = new JsonObj(); allIndustry.lstAdd("美食", "中餐厅", "外国餐厅", "小吃快餐店", "蛋糕甜品店", "咖啡厅", "茶座", "酒吧"); allIndustry.lstAdd("酒店", "星级酒店", "快捷酒店", "公寓式酒店"); allIndustry.lstAdd("购物", "购物中心", "超市", "便利店", "家居建材", "家电数码", "商铺", "集市"); allIndustry.lstAdd("生活服务", "通讯营业厅", "邮局", "物流公司", "售票处", "洗衣店", "图文快印店", "照相馆", "房产中介机构", "公用事业", "维修点", "家政服务", "殡葬服务", "彩票销售点", "宠物服务", "报刊亭", "公共厕所"); allIndustry.lstAdd("丽人", "美容", "美发", "美甲", "美体"); allIndustry.lstAdd("旅游景点", "公园", "动物园", "植物园", "游乐园", "博物馆", "水族馆", "海滨浴场", "文物古迹", "教堂", "风景区"); allIndustry.lstAdd("休闲娱乐", "度假村", "农家院", "电影院", "KTV", "剧院", "歌舞厅", "网吧", "游戏场所", "洗浴按摩", "休闲广场"); allIndustry.lstAdd("运动健身", "体育场馆", "极限运动场所", "健身中心"); allIndustry.lstAdd("教育培训", "高等院校", "中学", "小学", "幼儿园", "成人教育", "亲子教育", "特殊教育学校", "留学中介机构", "科研机构", "培训机构", "图书馆", "科技馆"); allIndustry.lstAdd("文化传媒", "新闻出版", "广播电视", "艺术团体", "美术馆", "展览馆", "文化宫"); allIndustry.lstAdd("医疗", "综合医院", "专科医院", "诊所", "药店", "体检机构", "疗养院", "急救中心", "疾控中心"); allIndustry.lstAdd("汽车服务", "汽车销售", "汽车维修", "汽车美容", "汽车配件", "汽车租赁", "汽车检测场"); allIndustry.lstAdd("交通设施", "飞机场", "火车站", "地铁站", "长途汽车站", "公交车站", "港口", "停车场", "加油加气站", "服务区", "收费站", "桥"); allIndustry.lstAdd("金融", "银行", "ATM", "信用社", "投资理财", "典当行"); allIndustry.lstAdd("房地产", "写字楼", "住宅区", "宿舍"); allIndustry.lstAdd("公司企业", "公司", "园区", "农林园艺", "厂矿"); allIndustry.lstAdd("政府机构", "中央机构", "各级政府", "行政单位", "公检法机构", "涉外机构", "党派团体", "福利机构", "政治教育机构"); BaiduFetcher fetcher = new BaiduFetcher(args[0], args[1]); fetcher.init(); String region = "玉溪"; for(String mainIndustry: new String[]{"美食", "酒店", "购物", "丽人", "休闲娱乐"}){ for(Object industry: (Object[]) allIndustry.get(mainIndustry)){ fetcher.fetchALLPOIByRegion(industry.toString(), region); } } } }
1
10
1
22451_0
import java.util.Date; public class UserInfo { private String userid; private String username; private String userpwd; private int userStatus;//默认为0,正常。1为注销 private Date userTime; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpwd() { return userpwd; } public void setUserpwd(String userpwd) { this.userpwd = userpwd; } public int getUserStatus() { return userStatus; } public void setUserStatus(int userStatus) { this.userStatus = userStatus; } public Date getUserTime() { return userTime; } public void setUserTime(Date userTime) { this.userTime = userTime; } }
DaturaH/demo-struts2-mybatis
src/UserInfo.java
257
//默认为0,正常。1为注销
line_comment
zh-cn
import java.util.Date; public class UserInfo { private String userid; private String username; private String userpwd; private int userStatus;//默认 <SUF> private Date userTime; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getUserpwd() { return userpwd; } public void setUserpwd(String userpwd) { this.userpwd = userpwd; } public int getUserStatus() { return userStatus; } public void setUserStatus(int userStatus) { this.userStatus = userStatus; } public Date getUserTime() { return userTime; } public void setUserTime(Date userTime) { this.userTime = userTime; } }
1
14
1
16868_1
package com.tingfm.utils; /** * Created by david on 15/11/26. */ public class Utils { /** * 15366->1.5万 * 1569->1569 */ public final static String convertWithTenthousand(int srcNum){ if(srcNum<10000){ return srcNum+""; }else{ int littleArea=(srcNum%10000)/1000; return srcNum/10000+"."+littleArea+"万"; } } public final static String formatTime(float srcNum){ int hour=(int)srcNum/60; int minute=(int)srcNum%60; if(minute>10){ return hour + ":" + minute; }else{ return hour + ":0" + minute; } } public final static String convertTimeDifferent(long pastTimeStamp){ long oneHourMills=60*60*1000; long oneDayMills=oneHourMills*24; long oneMonthMills=oneDayMills*30; long oneYearMills=365*oneDayMills; long different=System.currentTimeMillis()-pastTimeStamp; System.out.println(System.currentTimeMillis()+"differnt: "+different); if(different<oneHourMills){ return "刚刚"; }else if(different<oneDayMills){ return different/oneHourMills+"小时前"; }else if(different<oneMonthMills){ return different/oneDayMills+"天前"; }else if(different<oneYearMills){ return different/oneMonthMills+"个月前"; }else{ return different/oneYearMills+"年前"; } } }
Davidrou/DownLoadUtil
sample/src/main/java/com/tingfm/utils/Utils.java
431
/** * 15366->1.5万 * 1569->1569 */
block_comment
zh-cn
package com.tingfm.utils; /** * Created by david on 15/11/26. */ public class Utils { /** * 153 <SUF>*/ public final static String convertWithTenthousand(int srcNum){ if(srcNum<10000){ return srcNum+""; }else{ int littleArea=(srcNum%10000)/1000; return srcNum/10000+"."+littleArea+"万"; } } public final static String formatTime(float srcNum){ int hour=(int)srcNum/60; int minute=(int)srcNum%60; if(minute>10){ return hour + ":" + minute; }else{ return hour + ":0" + minute; } } public final static String convertTimeDifferent(long pastTimeStamp){ long oneHourMills=60*60*1000; long oneDayMills=oneHourMills*24; long oneMonthMills=oneDayMills*30; long oneYearMills=365*oneDayMills; long different=System.currentTimeMillis()-pastTimeStamp; System.out.println(System.currentTimeMillis()+"differnt: "+different); if(different<oneHourMills){ return "刚刚"; }else if(different<oneDayMills){ return different/oneHourMills+"小时前"; }else if(different<oneMonthMills){ return different/oneDayMills+"天前"; }else if(different<oneYearMills){ return different/oneMonthMills+"个月前"; }else{ return different/oneYearMills+"年前"; } } }
0
48
0
25049_63
package danxx.library.widget; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.Scroller; import android.widget.TextView; import danxx.library.R; /** * 万能的下拉刷新和上拉加载更多控件 * ------------------------------- * @Description: DXPullRefreshMoreView * @Author: Danxingxi * @CreateDate: 2016/8/5 10:12 */ public class DXPullRefreshMoreView extends LinearLayout implements IPullToRefreshMore { private static final String TAG = DXPullRefreshMoreView.class.getSimpleName(); /**最小移动距离,用于判断是否在下拉或者上拉,设置为0则touch事件的判断会过于频繁**/ private final static float MIN_MOVE_DISTANCE = 8.0f; private final static int SCROLL_DURATION = 400; enum RefreshStatus{ PULL_TO_REFRESH, // 从没刷新拖动到刷新 RELEASE_TO_REFRESH, // 本来就在刷新中,但还在拖动 REFRESHING, // 刷新中 NORMAL, // 当前无操作 } enum PullStatus{ PULL_UP_STATE, //下拉刷新 PULL_DOWN_STATE, //上拉加载更多 } /**header刷新情况的初始状态**/ private RefreshStatus headerRefreshStatus = RefreshStatus.NORMAL; /**footer刷新情况的初始状态**/ private RefreshStatus footerRefreshStatus = RefreshStatus.NORMAL; /**拖动方向的初始状态**/ private PullStatus pullStatus = PullStatus.PULL_DOWN_STATE; private Context mContext; /** pull to refresh View **/ private View headerView; /** pull to loadmore View **/ private View footerView; /** header view height **/ private int mHeaderViewHeight; /** footer view height **/ private int mFooterViewHeight; /*** header view image*/ private ImageView mHeaderImageView; /*** footer view image*/ private ImageView mFooterImageView; /*** header tip text*/ private TextView mHeaderTextView; /*** footer tip text*/ private TextView mFooterTextView; /*** header progress bar*/ private ProgressBar mHeaderProgressBar; /*** footer progress bar*/ private ProgressBar mFooterProgressBar; /*** 变为向下的箭头,改变箭头方向*/ private RotateAnimation mAnimation; /*** 变为向上的箭头*/ private RotateAnimation mReverseAnimation; /**记录手指滑动之前按下时的Y坐标**/ private int downY; /**回调监听器**/ private RefreshMoreLisenter refreshMoreLisenter; /**辅助滚动的scroller**/ private Scroller mScroller; /**Constructor & Init Method.**/ public DXPullRefreshMoreView(Context context) { this(context, null); } public DXPullRefreshMoreView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DXPullRefreshMoreView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } /** * init初始化 **/ @Override public void init(Context context, AttributeSet attrs, int defStyleAttr) { this.mContext = context; setOrientation(LinearLayout.VERTICAL); mScroller = new Scroller(mContext); mAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mAnimation.setInterpolator(new LinearInterpolator()); mAnimation.setDuration(250); mAnimation.setFillAfter(true); mReverseAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mReverseAnimation.setInterpolator(new LinearInterpolator()); mReverseAnimation.setDuration(200); mReverseAnimation.setFillAfter(true); /**在创建的时候就添加headerView,保证在LinearLayout的顶部**/ addHeaderRefreshView(); } @Override protected void onFinishInflate() { super.onFinishInflate(); /**在解析完所有的XML文件后添加footerView,保证在LinearLayout的最底部**/ addFooterRefreshView(); } /** * 添加刷新View **/ @Override public void addHeaderRefreshView() { headerView = LayoutInflater.from(mContext).inflate(R.layout.header_refresh_view, this, false); mHeaderImageView = (ImageView) headerView.findViewById(R.id.mHeaderImageView); mHeaderProgressBar = (ProgressBar) headerView.findViewById(R.id.mHeaderProgressBar); mHeaderTextView = (TextView) headerView.findViewById(R.id.mHeaderTextView); /**设置和测量headerView的大小**/ measureView(headerView); /**获取headerView的真实高度**/ mHeaderViewHeight = headerView.getMeasuredHeight(); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mHeaderViewHeight); /**设置topMargin的值为负的header View高度,即将其隐藏在最上方**/ params.topMargin = -(mHeaderViewHeight); addView(headerView, params); } /** * 添加加载更多View **/ @Override public void addFooterRefreshView() { footerView = LayoutInflater.from(mContext).inflate(R.layout.footer_refresh_view, this, false); mFooterImageView = (ImageView) footerView.findViewById(R.id.mFooterImageView); mFooterProgressBar = (ProgressBar) footerView.findViewById(R.id.mFooterProgressBar); mFooterTextView = (TextView) footerView.findViewById(R.id.mFooterTextView); measureView(footerView); mFooterViewHeight = footerView.getMeasuredHeight(); /**footerView不用设置bottomMatgin值,因为中间的ContentView的高度是MATCH_PARENT,会把footerView挤下来**/ LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mFooterViewHeight); addView(footerView, params); /**最后检测最后的子View数量是否符合要求**/ int count = getChildCount(); if (count < 3) { throw new IllegalArgumentException( "this layout must contain 3 child views!"); } } /** * 测量子控件大小 * * @param child **/ @Override public void measureView(View child) { ViewGroup.LayoutParams lp = child.getLayoutParams(); if(lp == null){ lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } /**用来计算一个合适子视图的宽度大小并返回最后的宽度值**/ int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, lp.width); int lpHeight = lp.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } /** * 事件分发拦截 * onInterceptTouchEvent()用于处理事件并改变事件的传递方向。 * 返回值为false时事件会传递给子控件的onInterceptTouchEvent(); * 返回值为true时事件会传递给当前控件的onTouchEvent(),而不在传递给子控件,这就是所谓的Intercept(截断)。 * * @param ev * @return -----------------------------示意图------------------------------------ * <p/> * ** -----------> rawY = M1, 手指按下ACTION_DOWN, downY = M1 * * 下拉距离pullY = (rawY - downY) = (M1 - M1) = 0 * * * * * * * * rawY = M2, 向下滑动ACTION_MOVE, downY * ** (downY不变是因为只会在第一次按下的时候才会记录downY的值) * * pullY = (rawY - downY) = (M2 - M1) * * * * * * * ** rawY = M3,向下滑动ACTION_MOVE, downY不变 * * pullY = (rawY - downY) = (M3 - M1) * * * * * V * -----------> rawY = M4,停止滑动ACTION_MOVE, downY不变 * pullY = (rawY - downY) = (M4 - M1) */ @Override public boolean onInterceptTouchEvent(MotionEvent ev) { Log.d("danxx" ,"onInterceptTouchEvent"); // return super.onInterceptTouchEvent(ev); /**每次手指按下时获取相对屏幕左上角的Y坐标值,一般都是负数**/ int rawY = (int) ev.getRawY(); switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: /**记录手指按下的时候相对于屏幕左上角的Y轴坐标**/ downY = rawY; break; case MotionEvent.ACTION_MOVE: /**pullY>0说明是下拉,pullY<0说明是上拉 */ int pullY = rawY - downY; /**滑动的距离满足下拉条件就返回true,就回去调用当前控件的onTouchEvent方法来处理事件**/ if ( Math.abs(pullY) > dp2px(MIN_MOVE_DISTANCE) && canScroll(pullY) ) { return true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: break; } return false; } /** * 处理手势事件 * onTouchEvent() 用于处理事件,返回值决定当前控件是否消费(consume)了这个事件 * @param ev * @return */ @Override public boolean onTouchEvent(MotionEvent ev) { // return super.onTouchEvent(event); /**每次手指按下时获取相对屏幕左上角的Y坐标值,一般都是负数**/ Log.d("danxx" ,"onTouchEvent22222"); int rawY = (int) ev.getRawY(); switch (ev.getAction()){ case MotionEvent.ACTION_DOWN: /**记录手指按下的时候相对于屏幕左上角的Y轴坐标**/ downY = rawY; break; case MotionEvent.ACTION_MOVE: Log.d("danxx" ,"ACTION_MOVE"); /**pullY>0说明是下拉,pullY<0说明是上拉 */ int pullY = rawY - downY; if(pullStatus == PullStatus.PULL_DOWN_STATE){ pullHeaderToRefresh(pullY); }else if(pullStatus == PullStatus.PULL_UP_STATE){ pullFooterToRefresh(pullY); } downY = rawY; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: /**手指滑动松开后判断是否符合刷新条件**/ int topMargin = getHeaderTopMargin(); if(pullStatus == PullStatus.PULL_DOWN_STATE){ if(topMargin > 0 ){ setHeaderRefreshing(); }else{ /**不满足刷新条件,隐藏header**/ setHeaderViewTopMargin(-mHeaderViewHeight); } }else if(pullStatus == PullStatus.PULL_UP_STATE){ if(Math.abs(topMargin) >= mHeaderViewHeight + mFooterViewHeight){ setFooterRefreshing(); }else{ setHeaderViewTopMargin(-mHeaderViewHeight); } } Log.d("danxx" ,"ACTION_UP_CANCEL"); break; } return false; } /** * 是否可以下拉或者上拉 * @param pullY 下拉的距离值, * pullY > 0 说明是下拉 * pullY < 0 说明是上拉 **/ @Override public boolean canScroll(int pullY) { Log.d("danxx" ,"canScroll"); if(headerRefreshStatus == RefreshStatus.REFRESHING || footerRefreshStatus == RefreshStatus.REFRESHING){ return false; } int childCount = getChildCount(); if(childCount>1){ View contentView = getChildAt(1); if(pullY > 0){ //下拉 if(contentView instanceof ScrollView){ Log.d("danxx" ,"ScrollView"); if(((ScrollView)contentView).getScrollY() == 0){ //scrollView滚动到顶部才可以下拉 mHeaderImageView.setVisibility(VISIBLE); mHeaderTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_DOWN_STATE; return true; }else{ return false; } }else if(contentView instanceof ListView){ int top = ((ListView) contentView).getChildAt(0).getTop(); int pad = ((ListView) contentView).getListPaddingTop(); if ((Math.abs(top - pad)) < 3 && ((ListView) contentView).getFirstVisiblePosition() == 0) { mHeaderImageView.setVisibility(VISIBLE); mHeaderTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_DOWN_STATE; return true; } else { return false; } }else if(contentView instanceof RecyclerView){ }else if(contentView instanceof LinearLayout){ mHeaderImageView.setVisibility(VISIBLE); mHeaderTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_DOWN_STATE; return true; } }else { //上拉 if(contentView instanceof ScrollView){ View child = ((ScrollView)contentView).getChildAt(0); if(child.getMeasuredHeight() <= getHeight() + ((ScrollView)contentView).getScrollY()){ mFooterImageView.setVisibility(VISIBLE); mFooterTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_UP_STATE; return true; }else{ return false; } }else if(contentView instanceof ListView){ View lastChild = ((ListView)contentView).getChildAt(((ListView)contentView).getChildCount() - 1); if(lastChild.getBottom() <= getHeight() && ((ListView)contentView).getLastVisiblePosition() == ((ListView)contentView).getCount() - 1){ mFooterImageView.setVisibility(VISIBLE); mFooterTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_UP_STATE; return true; }else{ return false; } }else if(contentView instanceof RecyclerView){ }else if(contentView instanceof LinearLayout){ mFooterImageView.setVisibility(VISIBLE); mFooterTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_UP_STATE; return true; } } } return canScroll(this); } /** * 子类重写此方法可以兼容其它的子控件来支持刷新和加载 * @param refreshMoreView * @return */ protected boolean canScroll(DXPullRefreshMoreView refreshMoreView){ return false; } /** * 下拉手指还在移动没有抬起来,此过程中需要改变箭头的方向 **/ @Override public void pullHeaderToRefresh(int pullY) { Log.d("danxx" ,"pullHeaderToRefresh"); int newTopMargin = changeHeaderViewTopMargin(pullY); // 当header view的topMargin>=0时,说明已经完全显示出来了,修改header view 的提示状态 if(newTopMargin >= 0 && headerRefreshStatus != RefreshStatus.RELEASE_TO_REFRESH){ mHeaderTextView.setText(R.string.pull_to_refresh_release_label); mHeaderImageView.clearAnimation(); mHeaderImageView.startAnimation(mAnimation); headerRefreshStatus = RefreshStatus.RELEASE_TO_REFRESH; } else if(newTopMargin < 0 && newTopMargin > - mHeaderViewHeight){ // 拖动时没有释放 mHeaderImageView.clearAnimation(); mHeaderImageView.startAnimation(mAnimation); mHeaderTextView.setText(R.string.pull_to_refresh_pull_label); headerRefreshStatus = RefreshStatus.PULL_TO_REFRESH; } } /** * 上拉手指还在移动没有抬起来,此过程中需要改变箭头的方向 * ooter 准备刷新,手指移动过程,还没有释放 移动footer view高度同样和移动header view * 高度是一样,都是通过修改header view的topmargin的值来达到 **/ @Override public void pullFooterToRefresh(int pullY) { mFooterImageView.setVisibility(VISIBLE); int newTopMargin = changeHeaderViewTopMargin(pullY); // 如果header view topMargin 的绝对值大于或等于header + footer 的高度 // 说明footer view 完全显示出来了,修改footer view 的提示状态 if (Math.abs(newTopMargin) >= (mHeaderViewHeight + mFooterViewHeight) && footerRefreshStatus != RefreshStatus.RELEASE_TO_REFRESH) { mFooterTextView .setText(R.string.pull_to_refresh_footer_release_label); mFooterImageView.clearAnimation(); mFooterImageView.startAnimation(mAnimation); footerRefreshStatus = RefreshStatus.RELEASE_TO_REFRESH; } else if (Math.abs(newTopMargin) < (mHeaderViewHeight + mFooterViewHeight)) { mFooterImageView.clearAnimation(); mFooterImageView.startAnimation(mAnimation); mFooterTextView.setText(R.string.pull_to_refresh_footer_pull_label); footerRefreshStatus = RefreshStatus.PULL_TO_REFRESH; } } /** * 在pullHeaderToRefresh动态改变HeaderView的TopMargin值 * * @param pullY **/ @Override public int changeHeaderViewTopMargin(int pullY) { Log.d("danxx", "changeHeaderViewTopMargin---pullY-->"+pullY); LayoutParams params = (LayoutParams) headerView.getLayoutParams(); /**对margin改变只是拉动距离的0.5倍,这样给人一种用力拉得感觉*/ float newTopMargin = params.topMargin + pullY*0.3f; /**对于在手指按下先下拉后又上拉的情况,避免在下拉刷新时出现footerView**/ if(pullStatus == PullStatus.PULL_DOWN_STATE && pullY<0 ){ if(newTopMargin < -mHeaderViewHeight){ newTopMargin = -mHeaderViewHeight; } } /**上拉又下拉屏蔽出现headerView**/ if(pullStatus == PullStatus.PULL_UP_STATE && pullY>0 ){ if(params.topMargin >= -mHeaderViewHeight - dp2px(4)){ return params.topMargin; } } params.topMargin = (int) newTopMargin; headerView.setLayoutParams(params); invalidate(); return params.topMargin; } /** * 在刷新中或者刷新完成后设置HeaderView的TopMargin值, * 上拉实现加载更多的动画也是设置setHeaderViewTopMargin的值, * 这样就会使整个ViewGroup往上升,这样就可以显示出FooterView了, * * @param margin */ @Override public void setHeaderViewTopMargin(int margin) { Log.d("danxx" ,"setHeaderViewTopMargin-->"+margin); LayoutParams params = (LayoutParams) headerView.getLayoutParams(); params.topMargin = margin; headerView.setLayoutParams(params); invalidate(); } /** * 设置开始下拉刷新 **/ @Override public void setHeaderRefreshing() { headerRefreshStatus = RefreshStatus.REFRESHING; // setHeaderViewTopMargin(0); mScroller.startScroll(0, mScroller.getStartY(), 0, 0, SCROLL_DURATION); invalidate(); mHeaderImageView.setVisibility(View.GONE); mHeaderImageView.clearAnimation(); mHeaderProgressBar.setVisibility(View.VISIBLE); mHeaderTextView.setText(R.string.pull_to_refresh_refreshing_label); if (refreshMoreLisenter != null) { refreshMoreLisenter.onRefresh(); } } /** * 下拉刷新完成,提供给别的类外调 **/ @Override public void onHeaderRefreshFinish() { // setHeaderViewTopMargin(-mHeaderViewHeight); mHeaderImageView.setVisibility(View.GONE); mHeaderProgressBar.setVisibility(View.GONE); mScroller.startScroll(0, getHeaderTopMargin(), 0, -mHeaderViewHeight, SCROLL_DURATION); invalidate(); // mHeaderUpdateTextView.setText(""); headerRefreshStatus = RefreshStatus.NORMAL; } /** * 设置开始上拉加载 **/ @Override public void setFooterRefreshing() { Log.d("danxx" ,"setFooterRefreshing"); footerRefreshStatus = RefreshStatus.REFRESHING; int top = mHeaderViewHeight + mFooterViewHeight; setHeaderViewTopMargin(-top); // mScroller.startScroll(0, getHeaderTopMargin(), 0, -top, SCROLL_DURATION); // invalidate(); mFooterImageView.setVisibility(View.GONE); mFooterImageView.clearAnimation(); if(mFooterProgressBar!=null) mFooterProgressBar.setVisibility(View.VISIBLE); mFooterTextView.setText(R.string.pull_to_refresh_footer_refreshing_label); if (refreshMoreLisenter != null) { refreshMoreLisenter.onLoadMore(); } } /** * 上拉加载完成,提供给别的类外调 **/ @Override public void onFootrRefreshFinish() { setHeaderViewTopMargin(-mHeaderViewHeight); // mScroller.startScroll(0, mScroller.getCurrY(), 0, -mHeaderViewHeight, SCROLL_DURATION); // invalidate(); mFooterTextView.setText(R.string.pull_to_refresh_footer_pull_label); if(mFooterProgressBar != null) mFooterProgressBar.setVisibility(View.GONE); // mHeaderUpdateTextView.setText(""); footerRefreshStatus = RefreshStatus.NORMAL; } /** * 获取当前header view 的topMargin **/ @Override public int getHeaderTopMargin() { LayoutParams params = (LayoutParams) headerView.getLayoutParams(); return params.topMargin; } /** * 设置刷新监听器 * * @param refreshListener **/ @Override public void setRefreshListener(RefreshMoreLisenter refreshListener) { this.refreshMoreLisenter = refreshListener; } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) {//scroll 动作还未结束 Log.i(TAG, "----->computeScroll()"); int i = this.mScroller.getCurrY(); LayoutParams lp = (LayoutParams) this.headerView .getLayoutParams(); int k = Math.max(i, -mHeaderViewHeight); // if(footerRefreshStatus == RefreshStatus.REFRESHING){ // lp.topMargin = -(mHeaderViewHeight+mFooterViewHeight); // }else{ lp.topMargin = k; // } this.headerView.setLayoutParams(lp); postInvalidate(); } super.computeScroll(); } protected int sp2px(float spValue) { final float fontScale = mContext.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } protected int dp2px(float dp) { final float scale = mContext.getResources().getDisplayMetrics().density; return (int) (dp * scale + 0.5f); } protected float dp2pxf(float dp) { final float scale = mContext.getResources().getDisplayMetrics().density; return (dp * scale + 0.5f); } }
Dawish/AndroidLearn
AppLibrary/src/main/java/danxx/library/widget/DXPullRefreshMoreView.java
5,678
/**对于在手指按下先下拉后又上拉的情况,避免在下拉刷新时出现footerView**/
block_comment
zh-cn
package danxx.library.widget; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.view.animation.RotateAnimation; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.ScrollView; import android.widget.Scroller; import android.widget.TextView; import danxx.library.R; /** * 万能的下拉刷新和上拉加载更多控件 * ------------------------------- * @Description: DXPullRefreshMoreView * @Author: Danxingxi * @CreateDate: 2016/8/5 10:12 */ public class DXPullRefreshMoreView extends LinearLayout implements IPullToRefreshMore { private static final String TAG = DXPullRefreshMoreView.class.getSimpleName(); /**最小移动距离,用于判断是否在下拉或者上拉,设置为0则touch事件的判断会过于频繁**/ private final static float MIN_MOVE_DISTANCE = 8.0f; private final static int SCROLL_DURATION = 400; enum RefreshStatus{ PULL_TO_REFRESH, // 从没刷新拖动到刷新 RELEASE_TO_REFRESH, // 本来就在刷新中,但还在拖动 REFRESHING, // 刷新中 NORMAL, // 当前无操作 } enum PullStatus{ PULL_UP_STATE, //下拉刷新 PULL_DOWN_STATE, //上拉加载更多 } /**header刷新情况的初始状态**/ private RefreshStatus headerRefreshStatus = RefreshStatus.NORMAL; /**footer刷新情况的初始状态**/ private RefreshStatus footerRefreshStatus = RefreshStatus.NORMAL; /**拖动方向的初始状态**/ private PullStatus pullStatus = PullStatus.PULL_DOWN_STATE; private Context mContext; /** pull to refresh View **/ private View headerView; /** pull to loadmore View **/ private View footerView; /** header view height **/ private int mHeaderViewHeight; /** footer view height **/ private int mFooterViewHeight; /*** header view image*/ private ImageView mHeaderImageView; /*** footer view image*/ private ImageView mFooterImageView; /*** header tip text*/ private TextView mHeaderTextView; /*** footer tip text*/ private TextView mFooterTextView; /*** header progress bar*/ private ProgressBar mHeaderProgressBar; /*** footer progress bar*/ private ProgressBar mFooterProgressBar; /*** 变为向下的箭头,改变箭头方向*/ private RotateAnimation mAnimation; /*** 变为向上的箭头*/ private RotateAnimation mReverseAnimation; /**记录手指滑动之前按下时的Y坐标**/ private int downY; /**回调监听器**/ private RefreshMoreLisenter refreshMoreLisenter; /**辅助滚动的scroller**/ private Scroller mScroller; /**Constructor & Init Method.**/ public DXPullRefreshMoreView(Context context) { this(context, null); } public DXPullRefreshMoreView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DXPullRefreshMoreView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr); } /** * init初始化 **/ @Override public void init(Context context, AttributeSet attrs, int defStyleAttr) { this.mContext = context; setOrientation(LinearLayout.VERTICAL); mScroller = new Scroller(mContext); mAnimation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mAnimation.setInterpolator(new LinearInterpolator()); mAnimation.setDuration(250); mAnimation.setFillAfter(true); mReverseAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f); mReverseAnimation.setInterpolator(new LinearInterpolator()); mReverseAnimation.setDuration(200); mReverseAnimation.setFillAfter(true); /**在创建的时候就添加headerView,保证在LinearLayout的顶部**/ addHeaderRefreshView(); } @Override protected void onFinishInflate() { super.onFinishInflate(); /**在解析完所有的XML文件后添加footerView,保证在LinearLayout的最底部**/ addFooterRefreshView(); } /** * 添加刷新View **/ @Override public void addHeaderRefreshView() { headerView = LayoutInflater.from(mContext).inflate(R.layout.header_refresh_view, this, false); mHeaderImageView = (ImageView) headerView.findViewById(R.id.mHeaderImageView); mHeaderProgressBar = (ProgressBar) headerView.findViewById(R.id.mHeaderProgressBar); mHeaderTextView = (TextView) headerView.findViewById(R.id.mHeaderTextView); /**设置和测量headerView的大小**/ measureView(headerView); /**获取headerView的真实高度**/ mHeaderViewHeight = headerView.getMeasuredHeight(); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mHeaderViewHeight); /**设置topMargin的值为负的header View高度,即将其隐藏在最上方**/ params.topMargin = -(mHeaderViewHeight); addView(headerView, params); } /** * 添加加载更多View **/ @Override public void addFooterRefreshView() { footerView = LayoutInflater.from(mContext).inflate(R.layout.footer_refresh_view, this, false); mFooterImageView = (ImageView) footerView.findViewById(R.id.mFooterImageView); mFooterProgressBar = (ProgressBar) footerView.findViewById(R.id.mFooterProgressBar); mFooterTextView = (TextView) footerView.findViewById(R.id.mFooterTextView); measureView(footerView); mFooterViewHeight = footerView.getMeasuredHeight(); /**footerView不用设置bottomMatgin值,因为中间的ContentView的高度是MATCH_PARENT,会把footerView挤下来**/ LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, mFooterViewHeight); addView(footerView, params); /**最后检测最后的子View数量是否符合要求**/ int count = getChildCount(); if (count < 3) { throw new IllegalArgumentException( "this layout must contain 3 child views!"); } } /** * 测量子控件大小 * * @param child **/ @Override public void measureView(View child) { ViewGroup.LayoutParams lp = child.getLayoutParams(); if(lp == null){ lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); } /**用来计算一个合适子视图的宽度大小并返回最后的宽度值**/ int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, lp.width); int lpHeight = lp.height; int childHeightSpec; if (lpHeight > 0) { childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY); } else { childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); } child.measure(childWidthSpec, childHeightSpec); } /** * 事件分发拦截 * onInterceptTouchEvent()用于处理事件并改变事件的传递方向。 * 返回值为false时事件会传递给子控件的onInterceptTouchEvent(); * 返回值为true时事件会传递给当前控件的onTouchEvent(),而不在传递给子控件,这就是所谓的Intercept(截断)。 * * @param ev * @return -----------------------------示意图------------------------------------ * <p/> * ** -----------> rawY = M1, 手指按下ACTION_DOWN, downY = M1 * * 下拉距离pullY = (rawY - downY) = (M1 - M1) = 0 * * * * * * * * rawY = M2, 向下滑动ACTION_MOVE, downY * ** (downY不变是因为只会在第一次按下的时候才会记录downY的值) * * pullY = (rawY - downY) = (M2 - M1) * * * * * * * ** rawY = M3,向下滑动ACTION_MOVE, downY不变 * * pullY = (rawY - downY) = (M3 - M1) * * * * * V * -----------> rawY = M4,停止滑动ACTION_MOVE, downY不变 * pullY = (rawY - downY) = (M4 - M1) */ @Override public boolean onInterceptTouchEvent(MotionEvent ev) { Log.d("danxx" ,"onInterceptTouchEvent"); // return super.onInterceptTouchEvent(ev); /**每次手指按下时获取相对屏幕左上角的Y坐标值,一般都是负数**/ int rawY = (int) ev.getRawY(); switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: /**记录手指按下的时候相对于屏幕左上角的Y轴坐标**/ downY = rawY; break; case MotionEvent.ACTION_MOVE: /**pullY>0说明是下拉,pullY<0说明是上拉 */ int pullY = rawY - downY; /**滑动的距离满足下拉条件就返回true,就回去调用当前控件的onTouchEvent方法来处理事件**/ if ( Math.abs(pullY) > dp2px(MIN_MOVE_DISTANCE) && canScroll(pullY) ) { return true; } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: break; } return false; } /** * 处理手势事件 * onTouchEvent() 用于处理事件,返回值决定当前控件是否消费(consume)了这个事件 * @param ev * @return */ @Override public boolean onTouchEvent(MotionEvent ev) { // return super.onTouchEvent(event); /**每次手指按下时获取相对屏幕左上角的Y坐标值,一般都是负数**/ Log.d("danxx" ,"onTouchEvent22222"); int rawY = (int) ev.getRawY(); switch (ev.getAction()){ case MotionEvent.ACTION_DOWN: /**记录手指按下的时候相对于屏幕左上角的Y轴坐标**/ downY = rawY; break; case MotionEvent.ACTION_MOVE: Log.d("danxx" ,"ACTION_MOVE"); /**pullY>0说明是下拉,pullY<0说明是上拉 */ int pullY = rawY - downY; if(pullStatus == PullStatus.PULL_DOWN_STATE){ pullHeaderToRefresh(pullY); }else if(pullStatus == PullStatus.PULL_UP_STATE){ pullFooterToRefresh(pullY); } downY = rawY; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: /**手指滑动松开后判断是否符合刷新条件**/ int topMargin = getHeaderTopMargin(); if(pullStatus == PullStatus.PULL_DOWN_STATE){ if(topMargin > 0 ){ setHeaderRefreshing(); }else{ /**不满足刷新条件,隐藏header**/ setHeaderViewTopMargin(-mHeaderViewHeight); } }else if(pullStatus == PullStatus.PULL_UP_STATE){ if(Math.abs(topMargin) >= mHeaderViewHeight + mFooterViewHeight){ setFooterRefreshing(); }else{ setHeaderViewTopMargin(-mHeaderViewHeight); } } Log.d("danxx" ,"ACTION_UP_CANCEL"); break; } return false; } /** * 是否可以下拉或者上拉 * @param pullY 下拉的距离值, * pullY > 0 说明是下拉 * pullY < 0 说明是上拉 **/ @Override public boolean canScroll(int pullY) { Log.d("danxx" ,"canScroll"); if(headerRefreshStatus == RefreshStatus.REFRESHING || footerRefreshStatus == RefreshStatus.REFRESHING){ return false; } int childCount = getChildCount(); if(childCount>1){ View contentView = getChildAt(1); if(pullY > 0){ //下拉 if(contentView instanceof ScrollView){ Log.d("danxx" ,"ScrollView"); if(((ScrollView)contentView).getScrollY() == 0){ //scrollView滚动到顶部才可以下拉 mHeaderImageView.setVisibility(VISIBLE); mHeaderTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_DOWN_STATE; return true; }else{ return false; } }else if(contentView instanceof ListView){ int top = ((ListView) contentView).getChildAt(0).getTop(); int pad = ((ListView) contentView).getListPaddingTop(); if ((Math.abs(top - pad)) < 3 && ((ListView) contentView).getFirstVisiblePosition() == 0) { mHeaderImageView.setVisibility(VISIBLE); mHeaderTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_DOWN_STATE; return true; } else { return false; } }else if(contentView instanceof RecyclerView){ }else if(contentView instanceof LinearLayout){ mHeaderImageView.setVisibility(VISIBLE); mHeaderTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_DOWN_STATE; return true; } }else { //上拉 if(contentView instanceof ScrollView){ View child = ((ScrollView)contentView).getChildAt(0); if(child.getMeasuredHeight() <= getHeight() + ((ScrollView)contentView).getScrollY()){ mFooterImageView.setVisibility(VISIBLE); mFooterTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_UP_STATE; return true; }else{ return false; } }else if(contentView instanceof ListView){ View lastChild = ((ListView)contentView).getChildAt(((ListView)contentView).getChildCount() - 1); if(lastChild.getBottom() <= getHeight() && ((ListView)contentView).getLastVisiblePosition() == ((ListView)contentView).getCount() - 1){ mFooterImageView.setVisibility(VISIBLE); mFooterTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_UP_STATE; return true; }else{ return false; } }else if(contentView instanceof RecyclerView){ }else if(contentView instanceof LinearLayout){ mFooterImageView.setVisibility(VISIBLE); mFooterTextView.setVisibility(VISIBLE); pullStatus = PullStatus.PULL_UP_STATE; return true; } } } return canScroll(this); } /** * 子类重写此方法可以兼容其它的子控件来支持刷新和加载 * @param refreshMoreView * @return */ protected boolean canScroll(DXPullRefreshMoreView refreshMoreView){ return false; } /** * 下拉手指还在移动没有抬起来,此过程中需要改变箭头的方向 **/ @Override public void pullHeaderToRefresh(int pullY) { Log.d("danxx" ,"pullHeaderToRefresh"); int newTopMargin = changeHeaderViewTopMargin(pullY); // 当header view的topMargin>=0时,说明已经完全显示出来了,修改header view 的提示状态 if(newTopMargin >= 0 && headerRefreshStatus != RefreshStatus.RELEASE_TO_REFRESH){ mHeaderTextView.setText(R.string.pull_to_refresh_release_label); mHeaderImageView.clearAnimation(); mHeaderImageView.startAnimation(mAnimation); headerRefreshStatus = RefreshStatus.RELEASE_TO_REFRESH; } else if(newTopMargin < 0 && newTopMargin > - mHeaderViewHeight){ // 拖动时没有释放 mHeaderImageView.clearAnimation(); mHeaderImageView.startAnimation(mAnimation); mHeaderTextView.setText(R.string.pull_to_refresh_pull_label); headerRefreshStatus = RefreshStatus.PULL_TO_REFRESH; } } /** * 上拉手指还在移动没有抬起来,此过程中需要改变箭头的方向 * ooter 准备刷新,手指移动过程,还没有释放 移动footer view高度同样和移动header view * 高度是一样,都是通过修改header view的topmargin的值来达到 **/ @Override public void pullFooterToRefresh(int pullY) { mFooterImageView.setVisibility(VISIBLE); int newTopMargin = changeHeaderViewTopMargin(pullY); // 如果header view topMargin 的绝对值大于或等于header + footer 的高度 // 说明footer view 完全显示出来了,修改footer view 的提示状态 if (Math.abs(newTopMargin) >= (mHeaderViewHeight + mFooterViewHeight) && footerRefreshStatus != RefreshStatus.RELEASE_TO_REFRESH) { mFooterTextView .setText(R.string.pull_to_refresh_footer_release_label); mFooterImageView.clearAnimation(); mFooterImageView.startAnimation(mAnimation); footerRefreshStatus = RefreshStatus.RELEASE_TO_REFRESH; } else if (Math.abs(newTopMargin) < (mHeaderViewHeight + mFooterViewHeight)) { mFooterImageView.clearAnimation(); mFooterImageView.startAnimation(mAnimation); mFooterTextView.setText(R.string.pull_to_refresh_footer_pull_label); footerRefreshStatus = RefreshStatus.PULL_TO_REFRESH; } } /** * 在pullHeaderToRefresh动态改变HeaderView的TopMargin值 * * @param pullY **/ @Override public int changeHeaderViewTopMargin(int pullY) { Log.d("danxx", "changeHeaderViewTopMargin---pullY-->"+pullY); LayoutParams params = (LayoutParams) headerView.getLayoutParams(); /**对margin改变只是拉动距离的0.5倍,这样给人一种用力拉得感觉*/ float newTopMargin = params.topMargin + pullY*0.3f; /**对于在 <SUF>*/ if(pullStatus == PullStatus.PULL_DOWN_STATE && pullY<0 ){ if(newTopMargin < -mHeaderViewHeight){ newTopMargin = -mHeaderViewHeight; } } /**上拉又下拉屏蔽出现headerView**/ if(pullStatus == PullStatus.PULL_UP_STATE && pullY>0 ){ if(params.topMargin >= -mHeaderViewHeight - dp2px(4)){ return params.topMargin; } } params.topMargin = (int) newTopMargin; headerView.setLayoutParams(params); invalidate(); return params.topMargin; } /** * 在刷新中或者刷新完成后设置HeaderView的TopMargin值, * 上拉实现加载更多的动画也是设置setHeaderViewTopMargin的值, * 这样就会使整个ViewGroup往上升,这样就可以显示出FooterView了, * * @param margin */ @Override public void setHeaderViewTopMargin(int margin) { Log.d("danxx" ,"setHeaderViewTopMargin-->"+margin); LayoutParams params = (LayoutParams) headerView.getLayoutParams(); params.topMargin = margin; headerView.setLayoutParams(params); invalidate(); } /** * 设置开始下拉刷新 **/ @Override public void setHeaderRefreshing() { headerRefreshStatus = RefreshStatus.REFRESHING; // setHeaderViewTopMargin(0); mScroller.startScroll(0, mScroller.getStartY(), 0, 0, SCROLL_DURATION); invalidate(); mHeaderImageView.setVisibility(View.GONE); mHeaderImageView.clearAnimation(); mHeaderProgressBar.setVisibility(View.VISIBLE); mHeaderTextView.setText(R.string.pull_to_refresh_refreshing_label); if (refreshMoreLisenter != null) { refreshMoreLisenter.onRefresh(); } } /** * 下拉刷新完成,提供给别的类外调 **/ @Override public void onHeaderRefreshFinish() { // setHeaderViewTopMargin(-mHeaderViewHeight); mHeaderImageView.setVisibility(View.GONE); mHeaderProgressBar.setVisibility(View.GONE); mScroller.startScroll(0, getHeaderTopMargin(), 0, -mHeaderViewHeight, SCROLL_DURATION); invalidate(); // mHeaderUpdateTextView.setText(""); headerRefreshStatus = RefreshStatus.NORMAL; } /** * 设置开始上拉加载 **/ @Override public void setFooterRefreshing() { Log.d("danxx" ,"setFooterRefreshing"); footerRefreshStatus = RefreshStatus.REFRESHING; int top = mHeaderViewHeight + mFooterViewHeight; setHeaderViewTopMargin(-top); // mScroller.startScroll(0, getHeaderTopMargin(), 0, -top, SCROLL_DURATION); // invalidate(); mFooterImageView.setVisibility(View.GONE); mFooterImageView.clearAnimation(); if(mFooterProgressBar!=null) mFooterProgressBar.setVisibility(View.VISIBLE); mFooterTextView.setText(R.string.pull_to_refresh_footer_refreshing_label); if (refreshMoreLisenter != null) { refreshMoreLisenter.onLoadMore(); } } /** * 上拉加载完成,提供给别的类外调 **/ @Override public void onFootrRefreshFinish() { setHeaderViewTopMargin(-mHeaderViewHeight); // mScroller.startScroll(0, mScroller.getCurrY(), 0, -mHeaderViewHeight, SCROLL_DURATION); // invalidate(); mFooterTextView.setText(R.string.pull_to_refresh_footer_pull_label); if(mFooterProgressBar != null) mFooterProgressBar.setVisibility(View.GONE); // mHeaderUpdateTextView.setText(""); footerRefreshStatus = RefreshStatus.NORMAL; } /** * 获取当前header view 的topMargin **/ @Override public int getHeaderTopMargin() { LayoutParams params = (LayoutParams) headerView.getLayoutParams(); return params.topMargin; } /** * 设置刷新监听器 * * @param refreshListener **/ @Override public void setRefreshListener(RefreshMoreLisenter refreshListener) { this.refreshMoreLisenter = refreshListener; } @Override public void computeScroll() { if (mScroller.computeScrollOffset()) {//scroll 动作还未结束 Log.i(TAG, "----->computeScroll()"); int i = this.mScroller.getCurrY(); LayoutParams lp = (LayoutParams) this.headerView .getLayoutParams(); int k = Math.max(i, -mHeaderViewHeight); // if(footerRefreshStatus == RefreshStatus.REFRESHING){ // lp.topMargin = -(mHeaderViewHeight+mFooterViewHeight); // }else{ lp.topMargin = k; // } this.headerView.setLayoutParams(lp); postInvalidate(); } super.computeScroll(); } protected int sp2px(float spValue) { final float fontScale = mContext.getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } protected int dp2px(float dp) { final float scale = mContext.getResources().getDisplayMetrics().density; return (int) (dp * scale + 0.5f); } protected float dp2pxf(float dp) { final float scale = mContext.getResources().getDisplayMetrics().density; return (dp * scale + 0.5f); } }
1
44
1
3203_5
package google.architecture.universal; import android.content.Context; import android.util.Log; import com.alibaba.android.arouter.facade.Postcard; import com.alibaba.android.arouter.facade.annotation.Interceptor; import com.alibaba.android.arouter.facade.callback.InterceptorCallback; import com.alibaba.android.arouter.facade.template.IInterceptor; import google.architecture.common.base.ARouterPath; /** * Created by danxx on 2017/11/27. * * 比较经典的应用就是在跳转过程中处理登陆事件,这样就不需要在目标页重复做登陆检查 * 拦截器会在跳转之前执行,多个拦截器会按优先级顺序依次执行 * * priority就是优先级 可以设置多个级别的拦截器都活一次执行 * 创建一个实现IInterceptor接口的类就是一个拦截器,不用做额外的配置了 */ @Interceptor(priority = 8, name = "测试用拦截器") public class RouterInterceptor implements IInterceptor { @Override public void process(Postcard postcard, InterceptorCallback callback) { if(postcard.getPath().contains(ARouterPath.GirlsListAty)){ Log.d("danxx", "拦截到向ActivityGirls跳转"); //自定义处理 }else { Log.d("danxx", "非拦截跳转执行path: "+postcard.getPath()); } callback.onContinue(postcard); // 处理完成,交还控制权 // callback.onInterrupt(new RuntimeException("我觉得有点异常")); // 觉得有问题,中断路由流程 // 以上两种至少需要调用其中一种,否则不会继续路由 } @Override public void init(Context context) { // 拦截器的初始化,会在sdk初始化的时候调用该方法,仅会调用一次 Log.d("danxx", "RouterInterceptor init"); } }
Dawish/GoogleArchitectureDemo
app_universal/src/main/java/google/architecture/universal/RouterInterceptor.java
474
// 拦截器的初始化,会在sdk初始化的时候调用该方法,仅会调用一次
line_comment
zh-cn
package google.architecture.universal; import android.content.Context; import android.util.Log; import com.alibaba.android.arouter.facade.Postcard; import com.alibaba.android.arouter.facade.annotation.Interceptor; import com.alibaba.android.arouter.facade.callback.InterceptorCallback; import com.alibaba.android.arouter.facade.template.IInterceptor; import google.architecture.common.base.ARouterPath; /** * Created by danxx on 2017/11/27. * * 比较经典的应用就是在跳转过程中处理登陆事件,这样就不需要在目标页重复做登陆检查 * 拦截器会在跳转之前执行,多个拦截器会按优先级顺序依次执行 * * priority就是优先级 可以设置多个级别的拦截器都活一次执行 * 创建一个实现IInterceptor接口的类就是一个拦截器,不用做额外的配置了 */ @Interceptor(priority = 8, name = "测试用拦截器") public class RouterInterceptor implements IInterceptor { @Override public void process(Postcard postcard, InterceptorCallback callback) { if(postcard.getPath().contains(ARouterPath.GirlsListAty)){ Log.d("danxx", "拦截到向ActivityGirls跳转"); //自定义处理 }else { Log.d("danxx", "非拦截跳转执行path: "+postcard.getPath()); } callback.onContinue(postcard); // 处理完成,交还控制权 // callback.onInterrupt(new RuntimeException("我觉得有点异常")); // 觉得有问题,中断路由流程 // 以上两种至少需要调用其中一种,否则不会继续路由 } @Override public void init(Context context) { // 拦截 <SUF> Log.d("danxx", "RouterInterceptor init"); } }
1
34
1
44559_6
package com.danxx.mdplayer.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; /** * * 类描述:网络链接类型判断 */ public class NetUtils { /** * 判断当前网络类型-1为未知网络0为没有网络连接1网络断开或关闭2为以太网3为WiFi4为2G5为3G6为4G */ public static int getNetworkType(Context context) { ConnectivityManager connectMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo(); if (networkInfo == null) { /** 没有任何网络 */ return 0; } if (!networkInfo.isConnected()) { /** 网络断开或关闭 */ return 1; } if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { /** 以太网网络 */ return 2; } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { /** wifi网络,当激活时,默认情况下,所有的数据流量将使用此连接 */ return 3; } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { /** 移动数据连接,不能与连接共存,如果wifi打开,则自动关闭 */ switch (networkInfo.getSubtype()) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: /** 2G网络 */ case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: /** 3G网络 */ case TelephonyManager.NETWORK_TYPE_LTE: /** 4G网络 */ return 4; } } /** 未知网络 */ return -1; } }
Dawish/MDPlayer
app/src/main/java/com/danxx/mdplayer/utils/NetUtils.java
646
/** 移动数据连接,不能与连接共存,如果wifi打开,则自动关闭 */
block_comment
zh-cn
package com.danxx.mdplayer.utils; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.telephony.TelephonyManager; /** * * 类描述:网络链接类型判断 */ public class NetUtils { /** * 判断当前网络类型-1为未知网络0为没有网络连接1网络断开或关闭2为以太网3为WiFi4为2G5为3G6为4G */ public static int getNetworkType(Context context) { ConnectivityManager connectMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo(); if (networkInfo == null) { /** 没有任何网络 */ return 0; } if (!networkInfo.isConnected()) { /** 网络断开或关闭 */ return 1; } if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) { /** 以太网网络 */ return 2; } else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { /** wifi网络,当激活时,默认情况下,所有的数据流量将使用此连接 */ return 3; } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { /** 移动数 <SUF>*/ switch (networkInfo.getSubtype()) { case TelephonyManager.NETWORK_TYPE_GPRS: case TelephonyManager.NETWORK_TYPE_EDGE: case TelephonyManager.NETWORK_TYPE_CDMA: case TelephonyManager.NETWORK_TYPE_1xRTT: case TelephonyManager.NETWORK_TYPE_IDEN: /** 2G网络 */ case TelephonyManager.NETWORK_TYPE_UMTS: case TelephonyManager.NETWORK_TYPE_EVDO_0: case TelephonyManager.NETWORK_TYPE_EVDO_A: case TelephonyManager.NETWORK_TYPE_HSDPA: case TelephonyManager.NETWORK_TYPE_HSUPA: case TelephonyManager.NETWORK_TYPE_HSPA: case TelephonyManager.NETWORK_TYPE_EVDO_B: case TelephonyManager.NETWORK_TYPE_EHRPD: case TelephonyManager.NETWORK_TYPE_HSPAP: /** 3G网络 */ case TelephonyManager.NETWORK_TYPE_LTE: /** 4G网络 */ return 4; } } /** 未知网络 */ return -1; } }
1
36
1
25646_1
import java.util.HashSet; /** * 最长没有重复数字的子串 * 滑动窗口法 */ public class Pro_003 { public int lengthOfLongestSubstring(String s) { int start = 0; int end = 0; int res = 0; HashSet<Character> set = new HashSet<>(); while (start < s.length() && end < s.length()) { if (set.contains(s.charAt(end))) { // 窗口前边后移 set.remove(s.charAt(start++)); } else { // 加入,并且后移 set.add(s.charAt(end++)); res = Math.max(res, end - start); } } return res; } }
DawnChau/leetcode
src/Pro_003.java
185
// 窗口前边后移
line_comment
zh-cn
import java.util.HashSet; /** * 最长没有重复数字的子串 * 滑动窗口法 */ public class Pro_003 { public int lengthOfLongestSubstring(String s) { int start = 0; int end = 0; int res = 0; HashSet<Character> set = new HashSet<>(); while (start < s.length() && end < s.length()) { if (set.contains(s.charAt(end))) { // 窗口 <SUF> set.remove(s.charAt(start++)); } else { // 加入,并且后移 set.add(s.charAt(end++)); res = Math.max(res, end - start); } } return res; } }
1
9
1
17958_1
package Top200; class NumSquares { public int numSquares(int n) { int[] dp = new int[n + 1]; for (int i = 0; i < n + 1; i++) { dp[i] = Integer.MAX_VALUE; } // base case dp[0] = 0; for (int i = 1; i <= n; i++) { for (int j = 1; i-j*j >= 0; j++) { // 这边等于号要注意,需要加上去,比如组成 4 的这个平方数个数只有 1 个。 dp[i] = Math.min(dp[i], dp[i - j*j] + 1); } } return dp[n]; } public static void main(String[] args) { NumSquares ns = new NumSquares(); System.out.println(ns.numSquares(4)); System.out.println(ns.numSquares(5)); System.out.println(ns.numSquares(6)); System.out.println(ns.numSquares(7)); System.out.println(ns.numSquares(12)); } }
DawnGuoDev/Algorithm
Top200/279-NumSquares.java
292
// 这边等于号要注意,需要加上去,比如组成 4 的这个平方数个数只有 1 个。
line_comment
zh-cn
package Top200; class NumSquares { public int numSquares(int n) { int[] dp = new int[n + 1]; for (int i = 0; i < n + 1; i++) { dp[i] = Integer.MAX_VALUE; } // base case dp[0] = 0; for (int i = 1; i <= n; i++) { for (int j = 1; i-j*j >= 0; j++) { // 这边 <SUF> dp[i] = Math.min(dp[i], dp[i - j*j] + 1); } } return dp[n]; } public static void main(String[] args) { NumSquares ns = new NumSquares(); System.out.println(ns.numSquares(4)); System.out.println(ns.numSquares(5)); System.out.println(ns.numSquares(6)); System.out.println(ns.numSquares(7)); System.out.println(ns.numSquares(12)); } }
1
40
1
57895_21
package com.benjaminwan.ocr; import com.benjaminwan.ocrlibrary.OcrEngine; import com.benjaminwan.ocrlibrary.OcrResult; public class Main { public static void main(String[] args) { String jniLibDir = System.getProperty("java.library.path"); System.out.println("java.library.path=" + jniLibDir); if (args.length < 6) { System.out.println("Usage: models/dir det/name cls/name rec/name keys/name image/path"); return; } //------- init models/dir image/path ------- String modelsDir = args[0]; String detName = args[1]; String clsName = args[2]; String recName = args[3]; String keysName = args[4]; String imagePath = args[5]; System.out.printf("modelsDir=%s, detName=%s, clsName=%s, recName=%s, keysName=%s, imagePath=%s", modelsDir, detName, clsName, recName, keysName, imagePath); //------- numThread ------- int numThread = 4; if (args.length > 6 && args[6] != null && args[6].length() > 0) { try { numThread = Integer.parseInt(args[6].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- padding ------- int padding = 50; if (args.length > 7 && args[7] != null && args[7].length() > 0) { try { padding = Integer.parseInt(args[7].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- maxSideLen ------- int maxSideLen = 1024; if (args.length > 8 && args[8] != null && args[8].length() > 0) { try { maxSideLen = Integer.parseInt(args[8].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- boxScoreThresh ------- float boxScoreThresh = 0.6f; if (args.length > 9 && args[9] != null && args[9].length() > 0) { try { boxScoreThresh = Float.parseFloat(args[9].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- boxThresh ------- float boxThresh = 0.3f; if (args.length > 10 && args[10] != null && args[10].length() > 0) { try { boxThresh = Float.parseFloat(args[10].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- unClipRatio ------- float unClipRatio = 2f; if (args.length > 11 && args[11] != null && args[11].length() > 0) { try { unClipRatio = Float.parseFloat(args[11].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- doAngle ------- int doAngleFlag = 1; if (args.length > 12 && args[12] != null && args[12].length() > 0) { try { doAngleFlag = Integer.parseInt(args[12].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } boolean doAngle = (doAngleFlag == 1); //------- mostAngle ------- int mostAngleFlag = 1; if (args.length > 13 && args[13] != null && args[13].length() > 0) { try { mostAngleFlag = Integer.parseInt(args[13].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } boolean mostAngle = (mostAngleFlag == 1); //------- get jni version ------- OcrEngine ocrEngine = new OcrEngine(); String version = ocrEngine.getVersion(); System.out.println("version=" + version); //------- setNumThread ------- ocrEngine.setNumThread(numThread); //------- init Logger ------- ocrEngine.initLogger( true, true, true ); ocrEngine.enableResultText(imagePath); //------- init Models ------- boolean initModelsRet = ocrEngine.initModels(modelsDir, detName, clsName, recName, keysName); if (!initModelsRet) { System.out.println("Error in models initialization, please check the models/keys path!"); return; } //------- set param ------- System.out.printf("padding(%d) boxScoreThresh(%f) boxThresh(%f) unClipRatio(%f) doAngle(%b) mostAngle(%b)", padding, boxScoreThresh, boxThresh, unClipRatio, doAngle, mostAngle); ocrEngine.setPadding(padding); //图像外接白框,用于提升识别率,文字框没有正确框住所有文字时,增加此值。 ocrEngine.setBoxScoreThresh(boxScoreThresh); //文字框置信度门限,文字框没有正确框住所有文字时,减小此值 ocrEngine.setBoxThresh(boxThresh); //请自行试验 ocrEngine.setUnClipRatio(unClipRatio); //单个文字框大小倍率,越大时单个文字框越大 ocrEngine.setDoAngle(doAngle); //启用(1)/禁用(0) 文字方向检测,只有图片倒置的情况下(旋转90~270度的图片),才需要启用文字方向检测 ocrEngine.setMostAngle(mostAngle); //启用(1)/禁用(0) 角度投票(整张图片以最大可能文字方向来识别),当禁用文字方向检测时,此项也不起作用 //------- start detect ------- OcrResult ocrResult = ocrEngine.detect(imagePath, maxSideLen); //按图像长边进行总体缩放,放大增加识别耗时但精度更高,缩小减小耗时但精度降低,maxSideLen=0代表不缩放 //使用native方法,可以让OcrEngine成为单例 //OcrResult ocrResult = ocrEngine.detect(imagePath, padding, maxSideLen, boxScoreThresh, boxThresh, unClipRatio, doAngle, mostAngle); //------- print result ------- System.out.println(ocrResult.toString()); return; } }
DayBreak-u/chineseocr_lite
jvm_projects/OcrLiteOnnxJvm/src/main/java/com/benjaminwan/ocr/Main.java
1,547
//按图像长边进行总体缩放,放大增加识别耗时但精度更高,缩小减小耗时但精度降低,maxSideLen=0代表不缩放
line_comment
zh-cn
package com.benjaminwan.ocr; import com.benjaminwan.ocrlibrary.OcrEngine; import com.benjaminwan.ocrlibrary.OcrResult; public class Main { public static void main(String[] args) { String jniLibDir = System.getProperty("java.library.path"); System.out.println("java.library.path=" + jniLibDir); if (args.length < 6) { System.out.println("Usage: models/dir det/name cls/name rec/name keys/name image/path"); return; } //------- init models/dir image/path ------- String modelsDir = args[0]; String detName = args[1]; String clsName = args[2]; String recName = args[3]; String keysName = args[4]; String imagePath = args[5]; System.out.printf("modelsDir=%s, detName=%s, clsName=%s, recName=%s, keysName=%s, imagePath=%s", modelsDir, detName, clsName, recName, keysName, imagePath); //------- numThread ------- int numThread = 4; if (args.length > 6 && args[6] != null && args[6].length() > 0) { try { numThread = Integer.parseInt(args[6].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- padding ------- int padding = 50; if (args.length > 7 && args[7] != null && args[7].length() > 0) { try { padding = Integer.parseInt(args[7].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- maxSideLen ------- int maxSideLen = 1024; if (args.length > 8 && args[8] != null && args[8].length() > 0) { try { maxSideLen = Integer.parseInt(args[8].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- boxScoreThresh ------- float boxScoreThresh = 0.6f; if (args.length > 9 && args[9] != null && args[9].length() > 0) { try { boxScoreThresh = Float.parseFloat(args[9].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- boxThresh ------- float boxThresh = 0.3f; if (args.length > 10 && args[10] != null && args[10].length() > 0) { try { boxThresh = Float.parseFloat(args[10].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- unClipRatio ------- float unClipRatio = 2f; if (args.length > 11 && args[11] != null && args[11].length() > 0) { try { unClipRatio = Float.parseFloat(args[11].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } //------- doAngle ------- int doAngleFlag = 1; if (args.length > 12 && args[12] != null && args[12].length() > 0) { try { doAngleFlag = Integer.parseInt(args[12].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } boolean doAngle = (doAngleFlag == 1); //------- mostAngle ------- int mostAngleFlag = 1; if (args.length > 13 && args[13] != null && args[13].length() > 0) { try { mostAngleFlag = Integer.parseInt(args[13].trim()); } catch (NumberFormatException e) { e.printStackTrace(); } } boolean mostAngle = (mostAngleFlag == 1); //------- get jni version ------- OcrEngine ocrEngine = new OcrEngine(); String version = ocrEngine.getVersion(); System.out.println("version=" + version); //------- setNumThread ------- ocrEngine.setNumThread(numThread); //------- init Logger ------- ocrEngine.initLogger( true, true, true ); ocrEngine.enableResultText(imagePath); //------- init Models ------- boolean initModelsRet = ocrEngine.initModels(modelsDir, detName, clsName, recName, keysName); if (!initModelsRet) { System.out.println("Error in models initialization, please check the models/keys path!"); return; } //------- set param ------- System.out.printf("padding(%d) boxScoreThresh(%f) boxThresh(%f) unClipRatio(%f) doAngle(%b) mostAngle(%b)", padding, boxScoreThresh, boxThresh, unClipRatio, doAngle, mostAngle); ocrEngine.setPadding(padding); //图像外接白框,用于提升识别率,文字框没有正确框住所有文字时,增加此值。 ocrEngine.setBoxScoreThresh(boxScoreThresh); //文字框置信度门限,文字框没有正确框住所有文字时,减小此值 ocrEngine.setBoxThresh(boxThresh); //请自行试验 ocrEngine.setUnClipRatio(unClipRatio); //单个文字框大小倍率,越大时单个文字框越大 ocrEngine.setDoAngle(doAngle); //启用(1)/禁用(0) 文字方向检测,只有图片倒置的情况下(旋转90~270度的图片),才需要启用文字方向检测 ocrEngine.setMostAngle(mostAngle); //启用(1)/禁用(0) 角度投票(整张图片以最大可能文字方向来识别),当禁用文字方向检测时,此项也不起作用 //------- start detect ------- OcrResult ocrResult = ocrEngine.detect(imagePath, maxSideLen); //按图 <SUF> //使用native方法,可以让OcrEngine成为单例 //OcrResult ocrResult = ocrEngine.detect(imagePath, padding, maxSideLen, boxScoreThresh, boxThresh, unClipRatio, doAngle, mostAngle); //------- print result ------- System.out.println(ocrResult.toString()); return; } }
0
57
0
38569_25
package blcs.lwb.lwbtool.utils.camera; import android.annotation.SuppressLint; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.Spanned; import android.text.TextWatcher; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import blcs.lwb.lwbtool.utils.MyUtils; import blcs.lwb.lwbtool.utils.RxTool.RxVibrateTool; /** * @author vondear * @date 2016/1/24 * RxTools的常用工具类 * <p> * For the brave souls who get this far: You are the chosen ones, * the valiant knights of programming who toil away, without rest, * fixing our most awful code. To you, true saviors, kings of men, * I say this: never gonna give you up, never gonna let you down, * never gonna run around and desert you. Never gonna make you cry, * never gonna say goodbye. Never gonna tell a lie and hurt you. * <p> * 致终于来到这里的勇敢的人: * 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。 * 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己, * 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。 */ public class RxTool { @SuppressLint("StaticFieldLeak") private static Context context; private static long lastClickTime; /** * 初始化工具类 * * @param context 上下文 */ public static void init(Context context) { RxTool.context = context.getApplicationContext(); RxCrashTool.init(context); } /** * 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context * <p> * 获取ApplicationContext * * @return ApplicationContext */ public static Context getContext() { if (context != null) { return context; } throw new NullPointerException("请先调用init()方法"); } //==============================================================================================延时任务封装 end //----------------------------------------------------------------------------------------------延时任务封装 start public static void delayToDo(long delayTime, final OnSimpleListener onSimpleListener) { new Handler().postDelayed(new Runnable() { @Override public void run() { //execute the task onSimpleListener.doSomething(); } }, delayTime); } /** * 倒计时 * * @param textView 控件 * @param waitTime 倒计时总时长 * @param interval 倒计时的间隔时间 * @param hint 倒计时完毕时显示的文字 */ public static void countDown(final TextView textView, long waitTime, long interval, final String hint) { textView.setEnabled(false); android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) { @SuppressLint("DefaultLocale") @Override public void onTick(long millisUntilFinished) { textView.setText(String.format("剩下 %d S", millisUntilFinished / 1000)); } @Override public void onFinish() { textView.setEnabled(true); textView.setText(hint); } }; timer.start(); } /** * 手动计算出listView的高度,但是不再具有滚动效果 * * @param listView */ public static void fixListViewHeight(ListView listView) { // 如果没有设置数据适配器,则ListView没有子项,返回。 ListAdapter listAdapter = listView.getAdapter(); int totalHeight = 0; if (listAdapter == null) { return; } for (int index = 0, len = listAdapter.getCount(); index < len; index++) { View listViewItem = listAdapter.getView(index, null, listView); // 计算子项View 的宽高 listViewItem.measure(0, 0); // 计算所有子项的高度 totalHeight += listViewItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); // listView.getDividerHeight()获取子项间分隔符的高度 // params.height设置ListView完全显示需要的高度 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } //---------------------------------------------MD5加密------------------------------------------- /** * 生成MD5加密32位字符串 * * @param MStr :需要加密的字符串 * @return */ public static String Md5(String MStr) { try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(MStr.getBytes()); return bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { return String.valueOf(MStr.hashCode()); } } // MD5内部算法---------------不能修改! private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } //============================================MD5加密============================================ /** * 根据资源名称获取资源 id * <p> * 不提倡使用这个方法获取资源,比其直接获取ID效率慢 * <p> * 例如 * getResources().getIdentifier("ic_launcher", "drawable", getPackageName()); * * @param context * @param name * @param defType * @return */ public final static int getResIdByName(Context context, String name, String defType) { return context.getResources().getIdentifier(name, defType, context.getPackageName()); } public static boolean isFastClick(int millisecond) { long curClickTime = System.currentTimeMillis(); long interval = (curClickTime - lastClickTime); if (0 < interval && interval < millisecond) { // 超过点击间隔后再将lastClickTime重置为当前点击时间 return true; } lastClickTime = curClickTime; return false; } /** * Edittext 首位小数点自动加零,最多两位小数 * * @param editText */ public static void setEdTwoDecimal(EditText editText) { setEdDecimal(editText, 2); } /** * 只允许数字和汉字 * @param editText */ public static void setEdType(final EditText editText) { editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String editable = editText.getText().toString(); String str = stringFilter(editable); if (!editable.equals(str)) { editText.setText(str); //设置新的光标所在位置 editText.setSelection(str.length()); } } @Override public void afterTextChanged(Editable s) { } }); } /** * // 只允许数字和汉字 * * @param str * @return * @throws PatternSyntaxException */ public static String stringFilter(String str) throws PatternSyntaxException { String regEx = "[^0-9\u4E00-\u9FA5]";//正则表达式 Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll("").trim(); } public static void setEdDecimal(EditText editText, int count) { if (count < 0) { count = 0; } count += 1; editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER); //设置字符过滤 final int finalCount = count; editText.setFilters(new InputFilter[]{new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (".".contentEquals(source) && dest.toString().length() == 0) { return "0."; } if (dest.toString().contains(".")) { int index = dest.toString().indexOf("."); int mlength = dest.toString().substring(index).length(); if (mlength == finalCount) { return ""; } } if (dest.toString().equals("0") && source.equals("0")) { return ""; } return null; } }}); } /** * @param editText 输入框控件 * @param number 位数 * 1 -> 1 * 2 -> 01 * 3 -> 001 * 4 -> 0001 * @param isStartForZero 是否从000开始 * true -> 从 000 开始 * false -> 从 001 开始 */ public static void setEditNumberAuto(final EditText editText, final int number, final boolean isStartForZero) { editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { setEditNumber(editText, number, isStartForZero); } } }); } /** * @param editText 输入框控件 * @param number 位数 * 1 -> 1 * 2 -> 01 * 3 -> 001 * 4 -> 0001 * @param isStartForZero 是否从000开始 * true -> 从 000 开始 * false -> 从 001 开始 */ public static void setEditNumber(EditText editText, int number, boolean isStartForZero) { StringBuilder s = new StringBuilder(editText.getText().toString()); StringBuilder temp = new StringBuilder(); int i; for (i = s.length(); i < number; ++i) { s.insert(0, "0"); } if (!isStartForZero) { for (i = 0; i < number; ++i) { temp.append("0"); } if (s.toString().equals(temp.toString())) { s = new StringBuilder(temp.substring(1) + "1"); } } editText.setText(s.toString()); } /** * 获取 * @return */ public static Handler getBackgroundHandler() { HandlerThread thread = new HandlerThread("background"); thread.start(); return new Handler(thread.getLooper()); } public static void initFastClickAndVibrate(Context mContext, OnDoListener onRxSimple) { if (RxTool.isFastClick(FAST_CLICK_TIME)) { MyUtils.toast(context,"请不要重复点击"); return; } else { RxVibrateTool.vibrateOnce(mContext, VIBRATE_TIME); onRxSimple.doSomething(); } } public final static int FAST_CLICK_TIME = 100; public final static int VIBRATE_TIME = 100; }
DayorNight/BLCS
LwbTool/src/main/java/blcs/lwb/lwbtool/utils/camera/RxTool.java
2,868
//设置字符过滤
line_comment
zh-cn
package blcs.lwb.lwbtool.utils.camera; import android.annotation.SuppressLint; import android.content.Context; import android.os.Handler; import android.os.HandlerThread; import android.text.Editable; import android.text.InputFilter; import android.text.InputType; import android.text.Spanned; import android.text.TextWatcher; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import blcs.lwb.lwbtool.utils.MyUtils; import blcs.lwb.lwbtool.utils.RxTool.RxVibrateTool; /** * @author vondear * @date 2016/1/24 * RxTools的常用工具类 * <p> * For the brave souls who get this far: You are the chosen ones, * the valiant knights of programming who toil away, without rest, * fixing our most awful code. To you, true saviors, kings of men, * I say this: never gonna give you up, never gonna let you down, * never gonna run around and desert you. Never gonna make you cry, * never gonna say goodbye. Never gonna tell a lie and hurt you. * <p> * 致终于来到这里的勇敢的人: * 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。 * 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己, * 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。 */ public class RxTool { @SuppressLint("StaticFieldLeak") private static Context context; private static long lastClickTime; /** * 初始化工具类 * * @param context 上下文 */ public static void init(Context context) { RxTool.context = context.getApplicationContext(); RxCrashTool.init(context); } /** * 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context * <p> * 获取ApplicationContext * * @return ApplicationContext */ public static Context getContext() { if (context != null) { return context; } throw new NullPointerException("请先调用init()方法"); } //==============================================================================================延时任务封装 end //----------------------------------------------------------------------------------------------延时任务封装 start public static void delayToDo(long delayTime, final OnSimpleListener onSimpleListener) { new Handler().postDelayed(new Runnable() { @Override public void run() { //execute the task onSimpleListener.doSomething(); } }, delayTime); } /** * 倒计时 * * @param textView 控件 * @param waitTime 倒计时总时长 * @param interval 倒计时的间隔时间 * @param hint 倒计时完毕时显示的文字 */ public static void countDown(final TextView textView, long waitTime, long interval, final String hint) { textView.setEnabled(false); android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) { @SuppressLint("DefaultLocale") @Override public void onTick(long millisUntilFinished) { textView.setText(String.format("剩下 %d S", millisUntilFinished / 1000)); } @Override public void onFinish() { textView.setEnabled(true); textView.setText(hint); } }; timer.start(); } /** * 手动计算出listView的高度,但是不再具有滚动效果 * * @param listView */ public static void fixListViewHeight(ListView listView) { // 如果没有设置数据适配器,则ListView没有子项,返回。 ListAdapter listAdapter = listView.getAdapter(); int totalHeight = 0; if (listAdapter == null) { return; } for (int index = 0, len = listAdapter.getCount(); index < len; index++) { View listViewItem = listAdapter.getView(index, null, listView); // 计算子项View 的宽高 listViewItem.measure(0, 0); // 计算所有子项的高度 totalHeight += listViewItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); // listView.getDividerHeight()获取子项间分隔符的高度 // params.height设置ListView完全显示需要的高度 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } //---------------------------------------------MD5加密------------------------------------------- /** * 生成MD5加密32位字符串 * * @param MStr :需要加密的字符串 * @return */ public static String Md5(String MStr) { try { final MessageDigest mDigest = MessageDigest.getInstance("MD5"); mDigest.update(MStr.getBytes()); return bytesToHexString(mDigest.digest()); } catch (NoSuchAlgorithmException e) { return String.valueOf(MStr.hashCode()); } } // MD5内部算法---------------不能修改! private static String bytesToHexString(byte[] bytes) { // http://stackoverflow.com/questions/332079 StringBuilder sb = new StringBuilder(); for (int i = 0; i < bytes.length; i++) { String hex = Integer.toHexString(0xFF & bytes[i]); if (hex.length() == 1) { sb.append('0'); } sb.append(hex); } return sb.toString(); } //============================================MD5加密============================================ /** * 根据资源名称获取资源 id * <p> * 不提倡使用这个方法获取资源,比其直接获取ID效率慢 * <p> * 例如 * getResources().getIdentifier("ic_launcher", "drawable", getPackageName()); * * @param context * @param name * @param defType * @return */ public final static int getResIdByName(Context context, String name, String defType) { return context.getResources().getIdentifier(name, defType, context.getPackageName()); } public static boolean isFastClick(int millisecond) { long curClickTime = System.currentTimeMillis(); long interval = (curClickTime - lastClickTime); if (0 < interval && interval < millisecond) { // 超过点击间隔后再将lastClickTime重置为当前点击时间 return true; } lastClickTime = curClickTime; return false; } /** * Edittext 首位小数点自动加零,最多两位小数 * * @param editText */ public static void setEdTwoDecimal(EditText editText) { setEdDecimal(editText, 2); } /** * 只允许数字和汉字 * @param editText */ public static void setEdType(final EditText editText) { editText.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { String editable = editText.getText().toString(); String str = stringFilter(editable); if (!editable.equals(str)) { editText.setText(str); //设置新的光标所在位置 editText.setSelection(str.length()); } } @Override public void afterTextChanged(Editable s) { } }); } /** * // 只允许数字和汉字 * * @param str * @return * @throws PatternSyntaxException */ public static String stringFilter(String str) throws PatternSyntaxException { String regEx = "[^0-9\u4E00-\u9FA5]";//正则表达式 Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(str); return m.replaceAll("").trim(); } public static void setEdDecimal(EditText editText, int count) { if (count < 0) { count = 0; } count += 1; editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER); //设置 <SUF> final int finalCount = count; editText.setFilters(new InputFilter[]{new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { if (".".contentEquals(source) && dest.toString().length() == 0) { return "0."; } if (dest.toString().contains(".")) { int index = dest.toString().indexOf("."); int mlength = dest.toString().substring(index).length(); if (mlength == finalCount) { return ""; } } if (dest.toString().equals("0") && source.equals("0")) { return ""; } return null; } }}); } /** * @param editText 输入框控件 * @param number 位数 * 1 -> 1 * 2 -> 01 * 3 -> 001 * 4 -> 0001 * @param isStartForZero 是否从000开始 * true -> 从 000 开始 * false -> 从 001 开始 */ public static void setEditNumberAuto(final EditText editText, final int number, final boolean isStartForZero) { editText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (!hasFocus) { setEditNumber(editText, number, isStartForZero); } } }); } /** * @param editText 输入框控件 * @param number 位数 * 1 -> 1 * 2 -> 01 * 3 -> 001 * 4 -> 0001 * @param isStartForZero 是否从000开始 * true -> 从 000 开始 * false -> 从 001 开始 */ public static void setEditNumber(EditText editText, int number, boolean isStartForZero) { StringBuilder s = new StringBuilder(editText.getText().toString()); StringBuilder temp = new StringBuilder(); int i; for (i = s.length(); i < number; ++i) { s.insert(0, "0"); } if (!isStartForZero) { for (i = 0; i < number; ++i) { temp.append("0"); } if (s.toString().equals(temp.toString())) { s = new StringBuilder(temp.substring(1) + "1"); } } editText.setText(s.toString()); } /** * 获取 * @return */ public static Handler getBackgroundHandler() { HandlerThread thread = new HandlerThread("background"); thread.start(); return new Handler(thread.getLooper()); } public static void initFastClickAndVibrate(Context mContext, OnDoListener onRxSimple) { if (RxTool.isFastClick(FAST_CLICK_TIME)) { MyUtils.toast(context,"请不要重复点击"); return; } else { RxVibrateTool.vibrateOnce(mContext, VIBRATE_TIME); onRxSimple.doSomething(); } } public final static int FAST_CLICK_TIME = 100; public final static int VIBRATE_TIME = 100; }
1
8
1
18997_2
public class Solution { // O(n * 2^n) time: // n为nums的length, subsets问题就是对于其中任意一个元素, 选或者不选入subset中 // 那么, 解的个数就是2^n // // 我们知道, subsets I的running time: // T(n) = n*2^(n-1) = θ(n*2^(n-1)) = O(n*2^n) // 但是我们知道在ret.contains()去重时, 每个解无论重复与否, 都有O(n)的时间, 所以 // 此题中, θ(n*2^(n-1))不再成立 // // contains()到底花了多少时间? // 我们知道list的大小是从1逐渐增加到2^m的, m为去重后解的个数, 那么其实就是 // 1 + 2 + 3 + ... + 2^m ~ 2^(m-1) + 2^(2m-1) // 这个时间是由重复元素个数决定的, 但我们可以用hashSet优化, 见subsetsWithDupOp // 那么最后running time还是O(n * 2^n) // O(n) space: // one n is the recursion stack // another n is the longest subset which is exactly the same as input // nums when used this in creating new linked list to store public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> ret = new LinkedList<List<Integer>>(); ret.add(new LinkedList<Integer>()); if(nums == null || nums.length == 0) return ret; Arrays.sort(nums); List<Integer> path = new LinkedList<Integer>(); doDFS(0, nums, path, ret); return ret; } private void doDFS(int start, int[] nums, List<Integer> path, List<List<Integer>> ret){ for(int i = start; i < nums.length; i++){ path.add(nums[i]); if(!ret.contains(path)){ ret.add(new LinkedList<Integer>(path)); doDFS(i + 1, nums, path, ret); } path.remove(path.size() - 1); } } // HashSet优化掉contains(), 实践证明可以省掉客观时间, 尤其是对于 // nums = {1, 1, ...... 1}这样的input public static List<List<Integer>> subsetsWithDupOp(int[] nums) { List<List<Integer>> ret = new LinkedList<List<Integer>>(); ret.add(new LinkedList<Integer>()); if(nums == null || nums.length == 0) return ret; Arrays.sort(nums); List<Integer> path = new LinkedList<Integer>(); HashSet<List<Integer>> set = new HashSet<List<Integer>>(); doDFS(0, nums, path, set); for(List<Integer> entry: set){ ret.add(entry); } return ret; } private static void doDFS(int start, int[] nums, List<Integer> path, HashSet<List<Integer>> set){ for(int i = start; i < nums.length; i++){ path.add(nums[i]); if(!set.contains(path)){ set.add(new LinkedList<Integer>(path)); doDFS(i + 1, nums, path, set); } path.remove(path.size() - 1); } } }
Deadbeef-ECE/Interview
Leetcode/All/090_Subsets_II.java
835
// 那么, 解的个数就是2^n
line_comment
zh-cn
public class Solution { // O(n * 2^n) time: // n为nums的length, subsets问题就是对于其中任意一个元素, 选或者不选入subset中 // 那么 <SUF> // // 我们知道, subsets I的running time: // T(n) = n*2^(n-1) = θ(n*2^(n-1)) = O(n*2^n) // 但是我们知道在ret.contains()去重时, 每个解无论重复与否, 都有O(n)的时间, 所以 // 此题中, θ(n*2^(n-1))不再成立 // // contains()到底花了多少时间? // 我们知道list的大小是从1逐渐增加到2^m的, m为去重后解的个数, 那么其实就是 // 1 + 2 + 3 + ... + 2^m ~ 2^(m-1) + 2^(2m-1) // 这个时间是由重复元素个数决定的, 但我们可以用hashSet优化, 见subsetsWithDupOp // 那么最后running time还是O(n * 2^n) // O(n) space: // one n is the recursion stack // another n is the longest subset which is exactly the same as input // nums when used this in creating new linked list to store public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> ret = new LinkedList<List<Integer>>(); ret.add(new LinkedList<Integer>()); if(nums == null || nums.length == 0) return ret; Arrays.sort(nums); List<Integer> path = new LinkedList<Integer>(); doDFS(0, nums, path, ret); return ret; } private void doDFS(int start, int[] nums, List<Integer> path, List<List<Integer>> ret){ for(int i = start; i < nums.length; i++){ path.add(nums[i]); if(!ret.contains(path)){ ret.add(new LinkedList<Integer>(path)); doDFS(i + 1, nums, path, ret); } path.remove(path.size() - 1); } } // HashSet优化掉contains(), 实践证明可以省掉客观时间, 尤其是对于 // nums = {1, 1, ...... 1}这样的input public static List<List<Integer>> subsetsWithDupOp(int[] nums) { List<List<Integer>> ret = new LinkedList<List<Integer>>(); ret.add(new LinkedList<Integer>()); if(nums == null || nums.length == 0) return ret; Arrays.sort(nums); List<Integer> path = new LinkedList<Integer>(); HashSet<List<Integer>> set = new HashSet<List<Integer>>(); doDFS(0, nums, path, set); for(List<Integer> entry: set){ ret.add(entry); } return ret; } private static void doDFS(int start, int[] nums, List<Integer> path, HashSet<List<Integer>> set){ for(int i = start; i < nums.length; i++){ path.add(nums[i]); if(!set.contains(path)){ set.add(new LinkedList<Integer>(path)); doDFS(i + 1, nums, path, set); } path.remove(path.size() - 1); } } }
1
16
1
56204_4
/*编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。 如果是有效的 IPv4 地址,返回 "IPv4" ; 如果是有效的 IPv6 地址,返回 "IPv6" ; 如果不是上述类型的 IP 地址,返回 "Neither" 。 IPv4 地址由十进制数和点来表示,每个地址包含 4 个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1; 同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。 IPv6 地址由 8 组 16 进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如,  2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。 然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。 同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。   :示例 1: 输入:IP = "172.16.254.1" 输出:"IPv4" 解释:有效的 IPv4 地址,返回 "IPv4" 示例 2: 输入:IP = "2001:0db8:85a3:0:08A2E:0370:7334" 输出:"IPv6" 解释:有效的 IPv6 地址,返回 "IPv6" 示例 3: 输入:IP = "256.256.256.256" 输出:"Neither" 解释:既不是 IPv4 地址,又不是 IPv6 地址 示例 4: 输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:" 输出:"Neither" 示例 5: 输入:IP = "1e1.4.5.6" 输出:"Neither"   提示: IP 仅由英文字母,数字,字符 '.' 和 ':' 组成。 */ public class Q468 { public static void main(String[] args) { System.out.print(validIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); } public static String validIPAddress(String IP) { String[] IP4Arr = IP.split("\\.",-1); // -1 表示尽可能用最多的次数 if(IP4Arr.length == 4){ return isIP4Arr(IP4Arr); } String[] IP6Arr = IP.split(":",-1); if(IP6Arr.length == 8){ return isIP6Arr(IP6Arr); } return "Neither"; } public static String isIP4Arr(String[] IP4Arr){ for(String ip : IP4Arr){ if(ip.length() > 3 || ip.length() <= 0){ return "Neither"; } for(int i = 0 ;i < ip.length();++i){ if(!Character.isDigit(ip.charAt(i))){ return "Neither"; } } int num = Integer.parseInt(ip); // String 转int --> Integer.parseInt() if(num > 255 || String.valueOf(num).length() != ip.length()){ // 判断是否是0开头, int转String --> String.valueOf() return "Neither"; } } return "IPv4"; } public static String isIP6Arr(String[] IP6Arr){ for(String ip : IP6Arr){ if(ip.length() > 4 || ip.length() <= 0){ return "Neither"; } for(int i = 0 ;i < ip.length();++i){ char c = ip.charAt(i); if(!Character.isDigit(c) && !( 'a' <= c && c <= 'f') && !('A' <= c && c <= 'F')){ // 判断字符串是否为数字 return "Neither"; } } } return "IPv6"; } }
DeadpanZiao/LEETCODE_comp
src/Q468.java
1,258
// 判断字符串是否为数字
line_comment
zh-cn
/*编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。 如果是有效的 IPv4 地址,返回 "IPv4" ; 如果是有效的 IPv6 地址,返回 "IPv6" ; 如果不是上述类型的 IP 地址,返回 "Neither" 。 IPv4 地址由十进制数和点来表示,每个地址包含 4 个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1; 同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。 IPv6 地址由 8 组 16 进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如,  2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。 然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。 同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。   :示例 1: 输入:IP = "172.16.254.1" 输出:"IPv4" 解释:有效的 IPv4 地址,返回 "IPv4" 示例 2: 输入:IP = "2001:0db8:85a3:0:08A2E:0370:7334" 输出:"IPv6" 解释:有效的 IPv6 地址,返回 "IPv6" 示例 3: 输入:IP = "256.256.256.256" 输出:"Neither" 解释:既不是 IPv4 地址,又不是 IPv6 地址 示例 4: 输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:" 输出:"Neither" 示例 5: 输入:IP = "1e1.4.5.6" 输出:"Neither"   提示: IP 仅由英文字母,数字,字符 '.' 和 ':' 组成。 */ public class Q468 { public static void main(String[] args) { System.out.print(validIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334")); } public static String validIPAddress(String IP) { String[] IP4Arr = IP.split("\\.",-1); // -1 表示尽可能用最多的次数 if(IP4Arr.length == 4){ return isIP4Arr(IP4Arr); } String[] IP6Arr = IP.split(":",-1); if(IP6Arr.length == 8){ return isIP6Arr(IP6Arr); } return "Neither"; } public static String isIP4Arr(String[] IP4Arr){ for(String ip : IP4Arr){ if(ip.length() > 3 || ip.length() <= 0){ return "Neither"; } for(int i = 0 ;i < ip.length();++i){ if(!Character.isDigit(ip.charAt(i))){ return "Neither"; } } int num = Integer.parseInt(ip); // String 转int --> Integer.parseInt() if(num > 255 || String.valueOf(num).length() != ip.length()){ // 判断是否是0开头, int转String --> String.valueOf() return "Neither"; } } return "IPv4"; } public static String isIP6Arr(String[] IP6Arr){ for(String ip : IP6Arr){ if(ip.length() > 4 || ip.length() <= 0){ return "Neither"; } for(int i = 0 ;i < ip.length();++i){ char c = ip.charAt(i); if(!Character.isDigit(c) && !( 'a' <= c && c <= 'f') && !('A' <= c && c <= 'F')){ // 判断 <SUF> return "Neither"; } } } return "IPv6"; } }
1
13
1
58790_0
package game.Object; import game.Engine.Base.BaseModel; import game.Engine.Enum.ObjectStatus; import game.Engine.GameObject; import game.Game; import game.Object.Model.Alpha; import game.Object.Model.ScoreIndicator; import java.util.concurrent.ThreadLocalRandom; @game.Engine.Annotation.GameObject public class Generator extends GameObject { private long lastTime = 0; private long interval = 1000; // 发射字母的时间间隔 private int maxAlphaCount = 8; private int currentAlphaCount = 0; @Override public void update() { if (status != ObjectStatus.ANIMATION) return; // 判断是否到达发射时间 if (System.currentTimeMillis() - lastTime < interval) return; // 判断是否达到最大限制 if (getAnimationAlphaCount() >= maxAlphaCount) return; ScoreIndicator scoreIndicator = ((ScoreIndicator) Game.getInstance().getModelManager().get("ScoreIndicator")); interval -= scoreIndicator.getScore() / 10; String rndAlpha = getRandomAlpha(); if (Game.getInstance().getModelManager().contains(rndAlpha)) { BaseModel alpha = Game.getInstance().getModelManager().get(rndAlpha); if (alpha.getStatus() != ObjectStatus.ANIMATION) alpha.start(); } else { Game.getInstance().getModelManager().register(new Alpha(rndAlpha), rndAlpha); } lastTime = System.currentTimeMillis(); } @Override public void start() { status = ObjectStatus.ANIMATION; } @Override public void stop() { status = ObjectStatus.STOP; } /** * 获取随机字母 * * @return */ private String getRandomAlpha() { int rnd = ThreadLocalRandom.current().nextInt(65, 90); return String.valueOf((char) rnd); } /** * 获取当前正在屏幕上运动的字母数量 * * @return 数量 */ private int getAnimationAlphaCount() { int result = 0; for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) { if (model instanceof Alpha) { if (model.getStatus() == ObjectStatus.ANIMATION) result++; } } return result; } /** * 重置字母生成器 */ public void reset() { lastTime = 0; interval = 1000; currentAlphaCount = 0; for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) { if (model instanceof Alpha) ((Alpha) model).stop(false); } } }
Deali-Axy/CrazyAlpha
src/main/java/game/Object/Generator.java
615
// 发射字母的时间间隔
line_comment
zh-cn
package game.Object; import game.Engine.Base.BaseModel; import game.Engine.Enum.ObjectStatus; import game.Engine.GameObject; import game.Game; import game.Object.Model.Alpha; import game.Object.Model.ScoreIndicator; import java.util.concurrent.ThreadLocalRandom; @game.Engine.Annotation.GameObject public class Generator extends GameObject { private long lastTime = 0; private long interval = 1000; // 发射 <SUF> private int maxAlphaCount = 8; private int currentAlphaCount = 0; @Override public void update() { if (status != ObjectStatus.ANIMATION) return; // 判断是否到达发射时间 if (System.currentTimeMillis() - lastTime < interval) return; // 判断是否达到最大限制 if (getAnimationAlphaCount() >= maxAlphaCount) return; ScoreIndicator scoreIndicator = ((ScoreIndicator) Game.getInstance().getModelManager().get("ScoreIndicator")); interval -= scoreIndicator.getScore() / 10; String rndAlpha = getRandomAlpha(); if (Game.getInstance().getModelManager().contains(rndAlpha)) { BaseModel alpha = Game.getInstance().getModelManager().get(rndAlpha); if (alpha.getStatus() != ObjectStatus.ANIMATION) alpha.start(); } else { Game.getInstance().getModelManager().register(new Alpha(rndAlpha), rndAlpha); } lastTime = System.currentTimeMillis(); } @Override public void start() { status = ObjectStatus.ANIMATION; } @Override public void stop() { status = ObjectStatus.STOP; } /** * 获取随机字母 * * @return */ private String getRandomAlpha() { int rnd = ThreadLocalRandom.current().nextInt(65, 90); return String.valueOf((char) rnd); } /** * 获取当前正在屏幕上运动的字母数量 * * @return 数量 */ private int getAnimationAlphaCount() { int result = 0; for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) { if (model instanceof Alpha) { if (model.getStatus() == ObjectStatus.ANIMATION) result++; } } return result; } /** * 重置字母生成器 */ public void reset() { lastTime = 0; interval = 1000; currentAlphaCount = 0; for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) { if (model instanceof Alpha) ((Alpha) model).stop(false); } } }
1
12
1
19954_0
package cn.deali.minimalpoem.task; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.support.v4.content.ContextCompat; import android.util.Log; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import cn.deali.minimalpoem.MainApp; import cn.deali.minimalpoem.R; import cn.deali.minimalpoem.utils.http.HttpRequestUtil; import cn.deali.minimalpoem.utils.http.tool.HttpRequestData; import cn.deali.minimalpoem.utils.http.tool.HttpResponseData; // 检查更新任务 public class CheckUpdateTask extends AsyncTask<Void, Integer, HttpResponseData> { private static final String TAG = "CheckUpdateTask"; private Context mContext; private boolean toast = false; /** * @param context Activity对象 * @param toast 是否显示 toast 提示最新版本 */ public CheckUpdateTask(Context context, boolean toast) { this.mContext = context; this.toast = toast; } @Override protected HttpResponseData doInBackground(Void... voids) { HttpRequestData request = new HttpRequestData(MainApp.getInstance().config.getHost() + "/qapp/get"); JSONObject json = new JSONObject(); try { json.put("id", MainApp.getInstance().config.getAppId()); } catch (JSONException ex) { Log.e(TAG, ex.getMessage()); this.cancel(true); } request.params = new StringBuffer(json.toString()); return HttpRequestUtil.postData(request); } @Override protected void onCancelled() { super.onCancelled(); Toast.makeText(mContext, "检查更新时发生错误!", Toast.LENGTH_SHORT).show(); } @Override protected void onPostExecute(HttpResponseData data) { super.onPostExecute(data); if (data.success) { try { JSONObject json = new JSONObject(data.content); if (json.getString("status").equals("ok")) { JSONObject app = json.getJSONObject("app"); if (app.getInt("version") > MainApp.getInstance().config.getVersionCode()) { showUpdateAlert(app); } else { if (toast) Toast.makeText(mContext, "你已经使用最新版本啦~", Toast.LENGTH_SHORT).show(); } } } catch (JSONException ex) { Log.e(TAG, ex.getMessage()); if (toast) Toast.makeText(mContext, "哦豁,完蛋,解析服务器数据失败~", Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Log.e(TAG, ex.getMessage()); if (toast) Toast.makeText(mContext, "糟糕,在检查更新的时候遇到奇奇怪怪的异常了~", Toast.LENGTH_SHORT).show(); } } } private void showUpdateAlert(JSONObject app) throws JSONException { final String download_link = app.getString("download_link"); final String detail_link = app.getString("detail_link"); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("发现新版本咯~"); builder.setMessage(String.format( "版本:%s\n更新说明:\n%s\n", app.getString("version_str"), app.getString("update_description"))); builder.setPositiveButton("下载", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri uri = Uri.parse(download_link); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setData(uri); mContext.startActivity(intent); } }); builder.setNeutralButton("了解详情", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri uri = Uri.parse(detail_link); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setData(uri); mContext.startActivity(intent); } }); AlertDialog dialog = builder.create(); // 适配夜间模式和白天模式 if (MainApp.getInstance().getNightMode()) dialog.setOnShowListener(dialogInterface -> { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.white)); dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.white)); }); else dialog.setOnShowListener(dialogInterface -> { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.black)); dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.black)); }); dialog.show(); } }
Deali-Axy/MinimalPoem
app/src/main/java/cn/deali/minimalpoem/task/CheckUpdateTask.java
1,177
// 检查更新任务
line_comment
zh-cn
package cn.deali.minimalpoem.task; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.support.v4.content.ContextCompat; import android.util.Log; import android.widget.Toast; import org.json.JSONException; import org.json.JSONObject; import cn.deali.minimalpoem.MainApp; import cn.deali.minimalpoem.R; import cn.deali.minimalpoem.utils.http.HttpRequestUtil; import cn.deali.minimalpoem.utils.http.tool.HttpRequestData; import cn.deali.minimalpoem.utils.http.tool.HttpResponseData; // 检查 <SUF> public class CheckUpdateTask extends AsyncTask<Void, Integer, HttpResponseData> { private static final String TAG = "CheckUpdateTask"; private Context mContext; private boolean toast = false; /** * @param context Activity对象 * @param toast 是否显示 toast 提示最新版本 */ public CheckUpdateTask(Context context, boolean toast) { this.mContext = context; this.toast = toast; } @Override protected HttpResponseData doInBackground(Void... voids) { HttpRequestData request = new HttpRequestData(MainApp.getInstance().config.getHost() + "/qapp/get"); JSONObject json = new JSONObject(); try { json.put("id", MainApp.getInstance().config.getAppId()); } catch (JSONException ex) { Log.e(TAG, ex.getMessage()); this.cancel(true); } request.params = new StringBuffer(json.toString()); return HttpRequestUtil.postData(request); } @Override protected void onCancelled() { super.onCancelled(); Toast.makeText(mContext, "检查更新时发生错误!", Toast.LENGTH_SHORT).show(); } @Override protected void onPostExecute(HttpResponseData data) { super.onPostExecute(data); if (data.success) { try { JSONObject json = new JSONObject(data.content); if (json.getString("status").equals("ok")) { JSONObject app = json.getJSONObject("app"); if (app.getInt("version") > MainApp.getInstance().config.getVersionCode()) { showUpdateAlert(app); } else { if (toast) Toast.makeText(mContext, "你已经使用最新版本啦~", Toast.LENGTH_SHORT).show(); } } } catch (JSONException ex) { Log.e(TAG, ex.getMessage()); if (toast) Toast.makeText(mContext, "哦豁,完蛋,解析服务器数据失败~", Toast.LENGTH_SHORT).show(); } catch (Exception ex) { Log.e(TAG, ex.getMessage()); if (toast) Toast.makeText(mContext, "糟糕,在检查更新的时候遇到奇奇怪怪的异常了~", Toast.LENGTH_SHORT).show(); } } } private void showUpdateAlert(JSONObject app) throws JSONException { final String download_link = app.getString("download_link"); final String detail_link = app.getString("detail_link"); AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setTitle("发现新版本咯~"); builder.setMessage(String.format( "版本:%s\n更新说明:\n%s\n", app.getString("version_str"), app.getString("update_description"))); builder.setPositiveButton("下载", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri uri = Uri.parse(download_link); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setData(uri); mContext.startActivity(intent); } }); builder.setNeutralButton("了解详情", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Uri uri = Uri.parse(detail_link); Intent intent = new Intent(); intent.setAction("android.intent.action.VIEW"); intent.setData(uri); mContext.startActivity(intent); } }); AlertDialog dialog = builder.create(); // 适配夜间模式和白天模式 if (MainApp.getInstance().getNightMode()) dialog.setOnShowListener(dialogInterface -> { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.white)); dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.white)); }); else dialog.setOnShowListener(dialogInterface -> { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.black)); dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.black)); }); dialog.show(); } }
1
9
1
25635_0
/* http://www.cnblogs.com/springfor/p/3889222.html 这道题是要考我知不知道格雷码么。。反正我自己单看找不出规律。。。 可以看到n位的格雷码由两部分构成,一部分是n-1位格雷码,再加上 1<<(n-1)和n-1位格雷码的逆序(整个格雷码逆序0132变成2310这种)的和。 1位格雷码有两个码字 (n+1)位格雷码中的前2^n个码字等于n位格雷码的码字,按顺序书写,加前缀0 (n+1)位格雷码中的后2^n个码字等于n位格雷码的码字,按逆序书写,加前缀1。 由于是二进制,在最高位加0跟原来的数本质没有改变,所以取得上一位算出的格雷码结果,再加上逆序添1的方法就是当前这位格雷码的结果了。 n = 0时,[0] n = 1时,[0,1] n = 2时,[00,01,11,10] n = 3时,[000,001,011,010,110,111,101,100] 当n=1时,0,1 当n=2时,原来的list 0,1不变,只是前面形式上加了个0变成00,01。然后加数是1<<1为10,依次:10+1=11 10+0=10。结果为:00 01 11 10 当n=3时,原来的list 00,01,11, 10(倒序为:10,11,01,00)。加数1<<2为100。倒序相加为:100+10=110, 100+11=111,100+01=101, 100+00= 100。 最终结果为000 001 011 010 110 111 101 100 **/ public ArrayList<Integer> grayCode(int n) { if(n==0) { ArrayList<Integer> result = new ArrayList<Integer>(); result.add(0); return result; } ArrayList<Integer> result = grayCode(n-1); int addNumber = 1 << (n-1); int originalsize=result.size(); for(int i=originalsize-1;i>=0;i--) { result.add(addNumber + result.get(i)); } return result; }
DeanWen/leetCodeInterview
LeetCode/089-GrayCode.java
722
/* http://www.cnblogs.com/springfor/p/3889222.html 这道题是要考我知不知道格雷码么。。反正我自己单看找不出规律。。。 可以看到n位的格雷码由两部分构成,一部分是n-1位格雷码,再加上 1<<(n-1)和n-1位格雷码的逆序(整个格雷码逆序0132变成2310这种)的和。 1位格雷码有两个码字 (n+1)位格雷码中的前2^n个码字等于n位格雷码的码字,按顺序书写,加前缀0 (n+1)位格雷码中的后2^n个码字等于n位格雷码的码字,按逆序书写,加前缀1。 由于是二进制,在最高位加0跟原来的数本质没有改变,所以取得上一位算出的格雷码结果,再加上逆序添1的方法就是当前这位格雷码的结果了。 n = 0时,[0] n = 1时,[0,1] n = 2时,[00,01,11,10] n = 3时,[000,001,011,010,110,111,101,100] 当n=1时,0,1 当n=2时,原来的list 0,1不变,只是前面形式上加了个0变成00,01。然后加数是1<<1为10,依次:10+1=11 10+0=10。结果为:00 01 11 10 当n=3时,原来的list 00,01,11, 10(倒序为:10,11,01,00)。加数1<<2为100。倒序相加为:100+10=110, 100+11=111,100+01=101, 100+00= 100。 最终结果为000 001 011 010 110 111 101 100 **/
block_comment
zh-cn
/* htt <SUF>*/ public ArrayList<Integer> grayCode(int n) { if(n==0) { ArrayList<Integer> result = new ArrayList<Integer>(); result.add(0); return result; } ArrayList<Integer> result = grayCode(n-1); int addNumber = 1 << (n-1); int originalsize=result.size(); for(int i=originalsize-1;i>=0;i--) { result.add(addNumber + result.get(i)); } return result; }
0
661
0
66588_1
package com.hanyi.thread.common.component; import com.hanyi.thread.domain.ScheduledTask; import lombok.RequiredArgsConstructor; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.config.CronTask; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * cron任务注册器 * * @author [email protected] * @since 2021-08-03 10:29 */ @Component @RequiredArgsConstructor public class CronTaskRegistrar { /** * 计划任务 */ private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16); /** * 任务调度器 */ private final TaskScheduler taskScheduler; /** * 添加cron任务 * * @param task 任务 * @param cronExpression cron表达式 */ public void addCronTask(Runnable task, String cronExpression) { this.addCronTask(new CronTask(task, cronExpression)); } /** * 添加cron任务 * * @param cronTask cron任务 */ public void addCronTask(CronTask cronTask) { if (cronTask != null) { Runnable task = cronTask.getRunnable(); this.removeCronTask(task); this.scheduledTasks.computeIfAbsent(task, k -> this.scheduledTasks.put(k, this.scheduleCronTask(cronTask))); } } /** * 删除cron任务 * * @param task 任务 */ public void removeCronTask(Runnable task) { ScheduledTask scheduledTask = this.scheduledTasks.remove(task); if (scheduledTask != null) { scheduledTask.cancel(); } } /** * 安排cron任务 * * @param cronTask cron任务 * @return {@link ScheduledTask} */ public ScheduledTask scheduleCronTask(CronTask cronTask) { ScheduledTask scheduledTask = new ScheduledTask(); scheduledTask.setFuture(this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger())); return scheduledTask; } /** * 摧毁 */ @PreDestroy public void destroy() { this.scheduledTasks.values().forEach(ScheduledTask::cancel); this.scheduledTasks.clear(); } }
Dearker/middleground
hanyi-dynamic-threadpool/src/main/java/com/hanyi/thread/common/component/CronTaskRegistrar.java
564
/** * 计划任务 */
block_comment
zh-cn
package com.hanyi.thread.common.component; import com.hanyi.thread.domain.ScheduledTask; import lombok.RequiredArgsConstructor; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.config.CronTask; import org.springframework.stereotype.Component; import javax.annotation.PreDestroy; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * cron任务注册器 * * @author [email protected] * @since 2021-08-03 10:29 */ @Component @RequiredArgsConstructor public class CronTaskRegistrar { /** * 计划任 <SUF>*/ private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16); /** * 任务调度器 */ private final TaskScheduler taskScheduler; /** * 添加cron任务 * * @param task 任务 * @param cronExpression cron表达式 */ public void addCronTask(Runnable task, String cronExpression) { this.addCronTask(new CronTask(task, cronExpression)); } /** * 添加cron任务 * * @param cronTask cron任务 */ public void addCronTask(CronTask cronTask) { if (cronTask != null) { Runnable task = cronTask.getRunnable(); this.removeCronTask(task); this.scheduledTasks.computeIfAbsent(task, k -> this.scheduledTasks.put(k, this.scheduleCronTask(cronTask))); } } /** * 删除cron任务 * * @param task 任务 */ public void removeCronTask(Runnable task) { ScheduledTask scheduledTask = this.scheduledTasks.remove(task); if (scheduledTask != null) { scheduledTask.cancel(); } } /** * 安排cron任务 * * @param cronTask cron任务 * @return {@link ScheduledTask} */ public ScheduledTask scheduleCronTask(CronTask cronTask) { ScheduledTask scheduledTask = new ScheduledTask(); scheduledTask.setFuture(this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger())); return scheduledTask; } /** * 摧毁 */ @PreDestroy public void destroy() { this.scheduledTasks.values().forEach(ScheduledTask::cancel); this.scheduledTasks.clear(); } }
1
23
1
40720_30
package com.debugTeam.entity; import com.debugTeam.dao.impl.IOHelper; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @Author: Cauchy-Ny * @Description: * @Data: Create in 20:51 2018/4/1 * @Modified By: */ public class Marker implements Serializable { private static final long serialVersionUID = -5809782578272943999L; private String phoneNum; //电话号码 private String userName; //用户名 private String password; //密码 private int empiricalValue; //经验值 private int credits; //积分,标记者初始有1000 //基本统计 private ArrayList<String> uploaderList; //接过的项目的上传者列表 private ArrayList<MarkerJob> jobList; //接受的标记项目列表,内含具体信息 private ArrayList<Integer> aveMarkTimeList; //平均标记时间 // private ArrayList<Double> scoreList; //评分列表 0-5分 private Map<String, Integer> hotMap; //标记热点图 private Map<String, Integer> creditsMap; //每天的积分值 private Map<String, Integer> empiricalValueMap; //每天的经验值 private int[] jobTypeNum; //三类标注的数量,依次为:整体标注、标框标注、轮廓标注 private int[] timeMarkNum; //每个小时段标注的图片数量统计 private int kickOutCount; //被踢出数 private Map<String, String> creditsHistory; //积分获取记录<date, credits-cause> //每日任务 private String lastLoginTime; //最后登录时间 private ArrayList<DailyMission> dailyMissionList; //每日任务列表 private ArrayList<Medal> medalList; //勋章墙 //兴趣 private int interestNum; //可能感兴趣标注数量 private int interestType; //可能感兴趣类型 private ArrayList<String> interestClassification; //可能感兴趣分类 public Marker(String phoneNum, String userName, String password) { this.phoneNum = phoneNum; this.userName = userName; this.password = password; this.empiricalValue = 0; this.credits = 1000; this.uploaderList = new ArrayList<>(); this.jobList = new ArrayList<>(); this.aveMarkTimeList = new ArrayList<>(); this.jobTypeNum = new int[3]; this.timeMarkNum = new int[24]; this.hotMap = new HashMap<>(); this.creditsMap = new HashMap<>(); this.empiricalValueMap = new HashMap<>(); this.lastLoginTime = ""; this.dailyMissionList = new ArrayList<>(); this.medalList = new ArrayList<>(); this.medalList.add(new Medal(1)); this.medalList.add(new Medal(2)); this.medalList.add(new Medal(3)); this.interestNum = 0; this.interestType = 0; this.interestClassification = new ArrayList<>(); this.kickOutCount = 0; this.creditsHistory = new HashMap<>(); } //获取五维数据 0-信誉度 1-勤劳 2-经验 3-积分 4-评分 均为100分制 public double[] getFiveDimension() { double[] result = new double[5]; //计算信誉 result[0] = 80 - kickOutCount > 0 ? 80 - kickOutCount : 0; //计算勤劳 double industriousScore = 0; for(String date : hotMap.keySet()) { industriousScore += hotMap.get(date); } if(hotMap.size() != 0) industriousScore = industriousScore/hotMap.size() + 50; if(industriousScore > 100) //懒得想好的平均标记张数map到100分区间 industriousScore = 100; result[1] = industriousScore==0 ? 70 : industriousScore; //计算经验 double empiricalValueScore = 0; for(String date : empiricalValueMap.keySet()) { empiricalValueScore += empiricalValueMap.get(date); } empiricalValueScore = empiricalValueScore/300 + 50; if(empiricalValueScore > 100) //懒得想... empiricalValueScore = 100; result[2] = empiricalValueScore; //计算积分 double creditsScore = 0; for(String date : creditsMap.keySet()) { creditsScore += creditsMap.get(date); } creditsScore = creditsScore/300 + 50; if(creditsScore > 100) //懒得想... creditsScore = 100; result[3] = creditsScore; //计算评分 result[4] = 80; for(MarkerJob job: jobList) { if(job.getScore() != 0) { result[4] = jobList.stream() .map(p -> p.getScore()) .reduce(Double::sum) .orElse(0.0) / jobList.size() * 20; break; } } return result; } public void increaseKickOutCount() { this.kickOutCount++; } //更新每日任务 public void initDailyMission() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(!date.equals(this.lastLoginTime)) { this.lastLoginTime = date; this.dailyMissionList = new DailyMissionFactory().updateDailyMission(); } } //添加新任务 public void chooseNewJob(String id, String uploaderPhoneNum) { //初始化项目 String file_separator = System.getProperty("file.separator"); Project project = (Project) IOHelper.readProject("data" + file_separator + "project" + file_separator + id + file_separator + id + ".ser"); MarkerJob mj = new MarkerJob(project.getId(), project.getPicList()); //添加任务类型统计 //顺带每日任务的记录 switch (project.getType()) { case 1: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 0) { dm.updateMissionState(); } } jobTypeNum[0]++; break; case 2: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 1) { dm.updateMissionState(); } } jobTypeNum[1]++; break; case 3: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 2) { dm.updateMissionState(); } } jobTypeNum[2]++; break; default: break; } //关联项入队维护 this.jobList.add(mj); this.uploaderList.add(uploaderPhoneNum); } //添加新任务 public void quitJob(String id, String uploaderPhoneNum) { //初始化项目 String file_separator = System.getProperty("file.separator"); Project project = (Project) IOHelper.readProject("data" + file_separator + "project" + file_separator + id + file_separator + id + ".ser"); MarkerJob mj = getJob(id); //删除任务类型统计 switch (project.getType()) { case 1: jobTypeNum[0]--; break; case 2: jobTypeNum[1]--; break; case 3: jobTypeNum[2]--; break; default: break; } //关联项出队维护 if(jobList.contains(mj)) this.jobList.remove(mj); if(uploaderList.contains(uploaderPhoneNum)) this.uploaderList.remove(uploaderPhoneNum); } //根据某个id获取job public MarkerJob getJob(String id) { MarkerJob result = null; for(MarkerJob mj : jobList) { if(mj.getId().equals(id)) result = mj; } return result; } //获取标记者承接的所有job列表 public ArrayList<String> getJobList() { ArrayList<String> result = new ArrayList<>(); for(MarkerJob mj : jobList) result.add(mj.getId()); return result; } public MarkerJob getMarkerJob(String id) { for(MarkerJob mj : jobList) { if (mj.getId().equals(id)) return mj; } return null; } //更新已标记未标记列表 public void updateList(String id, String picName) { for(MarkerJob mj : jobList) { if(mj.getId().equals(id)) mj.updateList(picName); } } //更新每天不同时段(24h)标记图片数统计 public void setTagTimeAnalyse() { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); //只有时分秒 String hourTime = sdf.format(new Date()).substring(0, 2); //只取小时数 int hour = Integer.parseInt(hourTime); timeMarkNum[hour]++; } //更新热点图 public void updateHotMap() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(hotMap.containsKey(date)) hotMap.put(date, hotMap.get(date) + 1); else hotMap.put(date, 1); } //更新积分图 public void updateCreditsMap(int credits) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(creditsMap.containsKey(date)) creditsMap.put(date, creditsMap.get(date) + credits); else creditsMap.put(date, credits); } //更新经验值图 public void updateEmpiricalValueMap(int empiricalValue) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(empiricalValueMap.containsKey(date)) empiricalValueMap.put(date, empiricalValueMap.get(date) + empiricalValue); else empiricalValueMap.put(date, empiricalValue); } //更新经验值和经验值记录表 public void setCredits(int credits, String cause) { this.credits += credits; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = df.format(new Date()); creditsHistory.put(date, credits + "!" + cause); } public ArrayList<Integer> getAveMarkTimeList() { return aveMarkTimeList; } public ArrayList<MarkerJob> getMarkerJobList() { return jobList;} //添加新的平均标记时间 public void addNewAveMarkTime(int aveMarkTime) { this.aveMarkTimeList.add(aveMarkTime); } public int getInterestNum() { return interestNum; } public void setInterestNum(int interestNum) { this.interestNum = interestNum; } public int getInterestType() { return interestType; } public void setInterestType(int interestType) { this.interestType = interestType; } public ArrayList<String> getInterestClassification() { return interestClassification; } public void setInterestClassification(ArrayList<String> interestClassification) { this.interestClassification = interestClassification; } public String getLastLoginTime() { return lastLoginTime; } public ArrayList<Medal> getMedalList() { return medalList; } public ArrayList<DailyMission> getDailyMissionList() { return dailyMissionList; } public int getEmpiricalValue() { return empiricalValue; } public int[] getJobTypeNum() { return jobTypeNum; } public ArrayList<String> getUploaderList() { return uploaderList; } public Map<String, Integer> getHotMap() { return hotMap; } public Map<String, String> getCreditsHistory() { return creditsHistory; } public Map<String, Integer> getCreditsMap() { return creditsMap; } public Map<String, Integer> getEmpiricalValueMap() { return empiricalValueMap; } public int[] getTimeMarkNum() { return timeMarkNum; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getCredits() { return credits; } public String getPhoneNum() { return phoneNum; } public String getPassword() { return password; } public void setEmpiricalValue(int empiricalValue) { this.empiricalValue += empiricalValue; } }
Debug-Team/PictureTag
src/main/java/com/debugTeam/entity/Marker.java
3,159
//计算积分
line_comment
zh-cn
package com.debugTeam.entity; import com.debugTeam.dao.impl.IOHelper; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * @Author: Cauchy-Ny * @Description: * @Data: Create in 20:51 2018/4/1 * @Modified By: */ public class Marker implements Serializable { private static final long serialVersionUID = -5809782578272943999L; private String phoneNum; //电话号码 private String userName; //用户名 private String password; //密码 private int empiricalValue; //经验值 private int credits; //积分,标记者初始有1000 //基本统计 private ArrayList<String> uploaderList; //接过的项目的上传者列表 private ArrayList<MarkerJob> jobList; //接受的标记项目列表,内含具体信息 private ArrayList<Integer> aveMarkTimeList; //平均标记时间 // private ArrayList<Double> scoreList; //评分列表 0-5分 private Map<String, Integer> hotMap; //标记热点图 private Map<String, Integer> creditsMap; //每天的积分值 private Map<String, Integer> empiricalValueMap; //每天的经验值 private int[] jobTypeNum; //三类标注的数量,依次为:整体标注、标框标注、轮廓标注 private int[] timeMarkNum; //每个小时段标注的图片数量统计 private int kickOutCount; //被踢出数 private Map<String, String> creditsHistory; //积分获取记录<date, credits-cause> //每日任务 private String lastLoginTime; //最后登录时间 private ArrayList<DailyMission> dailyMissionList; //每日任务列表 private ArrayList<Medal> medalList; //勋章墙 //兴趣 private int interestNum; //可能感兴趣标注数量 private int interestType; //可能感兴趣类型 private ArrayList<String> interestClassification; //可能感兴趣分类 public Marker(String phoneNum, String userName, String password) { this.phoneNum = phoneNum; this.userName = userName; this.password = password; this.empiricalValue = 0; this.credits = 1000; this.uploaderList = new ArrayList<>(); this.jobList = new ArrayList<>(); this.aveMarkTimeList = new ArrayList<>(); this.jobTypeNum = new int[3]; this.timeMarkNum = new int[24]; this.hotMap = new HashMap<>(); this.creditsMap = new HashMap<>(); this.empiricalValueMap = new HashMap<>(); this.lastLoginTime = ""; this.dailyMissionList = new ArrayList<>(); this.medalList = new ArrayList<>(); this.medalList.add(new Medal(1)); this.medalList.add(new Medal(2)); this.medalList.add(new Medal(3)); this.interestNum = 0; this.interestType = 0; this.interestClassification = new ArrayList<>(); this.kickOutCount = 0; this.creditsHistory = new HashMap<>(); } //获取五维数据 0-信誉度 1-勤劳 2-经验 3-积分 4-评分 均为100分制 public double[] getFiveDimension() { double[] result = new double[5]; //计算信誉 result[0] = 80 - kickOutCount > 0 ? 80 - kickOutCount : 0; //计算勤劳 double industriousScore = 0; for(String date : hotMap.keySet()) { industriousScore += hotMap.get(date); } if(hotMap.size() != 0) industriousScore = industriousScore/hotMap.size() + 50; if(industriousScore > 100) //懒得想好的平均标记张数map到100分区间 industriousScore = 100; result[1] = industriousScore==0 ? 70 : industriousScore; //计算经验 double empiricalValueScore = 0; for(String date : empiricalValueMap.keySet()) { empiricalValueScore += empiricalValueMap.get(date); } empiricalValueScore = empiricalValueScore/300 + 50; if(empiricalValueScore > 100) //懒得想... empiricalValueScore = 100; result[2] = empiricalValueScore; //计算 <SUF> double creditsScore = 0; for(String date : creditsMap.keySet()) { creditsScore += creditsMap.get(date); } creditsScore = creditsScore/300 + 50; if(creditsScore > 100) //懒得想... creditsScore = 100; result[3] = creditsScore; //计算评分 result[4] = 80; for(MarkerJob job: jobList) { if(job.getScore() != 0) { result[4] = jobList.stream() .map(p -> p.getScore()) .reduce(Double::sum) .orElse(0.0) / jobList.size() * 20; break; } } return result; } public void increaseKickOutCount() { this.kickOutCount++; } //更新每日任务 public void initDailyMission() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(!date.equals(this.lastLoginTime)) { this.lastLoginTime = date; this.dailyMissionList = new DailyMissionFactory().updateDailyMission(); } } //添加新任务 public void chooseNewJob(String id, String uploaderPhoneNum) { //初始化项目 String file_separator = System.getProperty("file.separator"); Project project = (Project) IOHelper.readProject("data" + file_separator + "project" + file_separator + id + file_separator + id + ".ser"); MarkerJob mj = new MarkerJob(project.getId(), project.getPicList()); //添加任务类型统计 //顺带每日任务的记录 switch (project.getType()) { case 1: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 0) { dm.updateMissionState(); } } jobTypeNum[0]++; break; case 2: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 1) { dm.updateMissionState(); } } jobTypeNum[1]++; break; case 3: for (DailyMission dm: dailyMissionList) { if(dm.getType() == 2) { dm.updateMissionState(); } } jobTypeNum[2]++; break; default: break; } //关联项入队维护 this.jobList.add(mj); this.uploaderList.add(uploaderPhoneNum); } //添加新任务 public void quitJob(String id, String uploaderPhoneNum) { //初始化项目 String file_separator = System.getProperty("file.separator"); Project project = (Project) IOHelper.readProject("data" + file_separator + "project" + file_separator + id + file_separator + id + ".ser"); MarkerJob mj = getJob(id); //删除任务类型统计 switch (project.getType()) { case 1: jobTypeNum[0]--; break; case 2: jobTypeNum[1]--; break; case 3: jobTypeNum[2]--; break; default: break; } //关联项出队维护 if(jobList.contains(mj)) this.jobList.remove(mj); if(uploaderList.contains(uploaderPhoneNum)) this.uploaderList.remove(uploaderPhoneNum); } //根据某个id获取job public MarkerJob getJob(String id) { MarkerJob result = null; for(MarkerJob mj : jobList) { if(mj.getId().equals(id)) result = mj; } return result; } //获取标记者承接的所有job列表 public ArrayList<String> getJobList() { ArrayList<String> result = new ArrayList<>(); for(MarkerJob mj : jobList) result.add(mj.getId()); return result; } public MarkerJob getMarkerJob(String id) { for(MarkerJob mj : jobList) { if (mj.getId().equals(id)) return mj; } return null; } //更新已标记未标记列表 public void updateList(String id, String picName) { for(MarkerJob mj : jobList) { if(mj.getId().equals(id)) mj.updateList(picName); } } //更新每天不同时段(24h)标记图片数统计 public void setTagTimeAnalyse() { SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); //只有时分秒 String hourTime = sdf.format(new Date()).substring(0, 2); //只取小时数 int hour = Integer.parseInt(hourTime); timeMarkNum[hour]++; } //更新热点图 public void updateHotMap() { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(hotMap.containsKey(date)) hotMap.put(date, hotMap.get(date) + 1); else hotMap.put(date, 1); } //更新积分图 public void updateCreditsMap(int credits) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(creditsMap.containsKey(date)) creditsMap.put(date, creditsMap.get(date) + credits); else creditsMap.put(date, credits); } //更新经验值图 public void updateEmpiricalValueMap(int empiricalValue) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String date = df.format(new Date()); if(empiricalValueMap.containsKey(date)) empiricalValueMap.put(date, empiricalValueMap.get(date) + empiricalValue); else empiricalValueMap.put(date, empiricalValue); } //更新经验值和经验值记录表 public void setCredits(int credits, String cause) { this.credits += credits; SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String date = df.format(new Date()); creditsHistory.put(date, credits + "!" + cause); } public ArrayList<Integer> getAveMarkTimeList() { return aveMarkTimeList; } public ArrayList<MarkerJob> getMarkerJobList() { return jobList;} //添加新的平均标记时间 public void addNewAveMarkTime(int aveMarkTime) { this.aveMarkTimeList.add(aveMarkTime); } public int getInterestNum() { return interestNum; } public void setInterestNum(int interestNum) { this.interestNum = interestNum; } public int getInterestType() { return interestType; } public void setInterestType(int interestType) { this.interestType = interestType; } public ArrayList<String> getInterestClassification() { return interestClassification; } public void setInterestClassification(ArrayList<String> interestClassification) { this.interestClassification = interestClassification; } public String getLastLoginTime() { return lastLoginTime; } public ArrayList<Medal> getMedalList() { return medalList; } public ArrayList<DailyMission> getDailyMissionList() { return dailyMissionList; } public int getEmpiricalValue() { return empiricalValue; } public int[] getJobTypeNum() { return jobTypeNum; } public ArrayList<String> getUploaderList() { return uploaderList; } public Map<String, Integer> getHotMap() { return hotMap; } public Map<String, String> getCreditsHistory() { return creditsHistory; } public Map<String, Integer> getCreditsMap() { return creditsMap; } public Map<String, Integer> getEmpiricalValueMap() { return empiricalValueMap; } public int[] getTimeMarkNum() { return timeMarkNum; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getCredits() { return credits; } public String getPhoneNum() { return phoneNum; } public String getPassword() { return password; } public void setEmpiricalValue(int empiricalValue) { this.empiricalValue += empiricalValue; } }
1
6
1
65520_1
package com.decrain.spark.mllib.dao; import com.google.gson.Gson; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.util.JSON; import org.apache.log4j.PropertyConfigurator; import com.decrain.spark.mllib.dto.data; /** * Created by Decrain on 2017/8/15. */ public class MongoDBConnect { public static void main(String args[]) { String log4jConfPath = "/Users/decrain/IdeaProjects/Classifier/log4j.properties"; PropertyConfigurator.configure(log4jConfPath); MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("TextClassifier"); DBCollection collection = db.getCollection("data"); DBCollection collection1 = db.getCollection("cur"); String[] temp = new String[100]; temp[0] = "自2008年首款 Andriod 系统推出以来,Google 一直提倡与App 开发者,设备制造商,及广大用户共享 Android 平台的预览版,并期望收到技术方面的反馈。今日, Google 发布首个 Android O 开发者预览版。 虽然作为早期预览版来说,很多新特性未正式加入其中,在稳定性与性能方面也需要更多改进,但这仅仅是一个开端在接下来的几个月中,Google 将发布开发者预览版的更新,更多详情将在今年 5 月的 Google I/O 大会上揭晓。同时,Google 也期待收到开发者关于新特性的反馈,也希望有更多开发者在这新的操作系统中对 App 进行测试。"; //temp = "晴朗的天空,我们常看到喷气式飞机在高空飞行时,机身后边会出现一条或数条长长的“白烟”。其实,这不是喷气式飞机喷出来的烟,而是飞机排出来的废气与周围环境空气混合后,水汽凝结而成的特殊云系,航空飞行界和航空气象学上称之为飞机尾迹"; temp[1] = "2017年7月19日,东风雪铁龙旗下全新紧凑型SUV天逸 C5 AIRCROSS在神龙汽车成都工厂正式下线,搜狐汽车抢先与东风雪铁龙的车总和饶总进行了产品设计方面的沟通"; temp[2] = "海军部队将在青岛至连云港以东海域组织大型军事活动。为确保安全,请各船舶特别注意:2017年7月27日0800至7月29日1800,不得进入下图所示临时禁航区,含91-95、101-105、111-115号、120-123号渔区,并听从外围警戒舰艇指挥,以策安全。——中国人民解放军91208部队"; temp[3] = "sdgfklasdngksdngosdgn"; temp[4] = "美联社说,美国与澳大利亚刚刚完成大型联合军事演习,双方派出36艘战舰、220架飞机及3.3万名士兵,期间遭到中国海军情报船监视。"; temp[5] = "据考试院介绍,在刚刚结束的本科二批次录取中,372所院校在京参加二批录取,计划招生14351人,实际录取15124人,较计划增加773人。其中文史类招生计划4435人,实际录取4525人,较计划增加了90人;理工类招生计划9916人,实际录取10599人,较计划增加了683人"; temp[6] = "按照全国考办的统一部署,2006年度全国会计专业技术资格考试定于5月20日、21日举行。准考证现已制作完毕,请县市区考生持身份证"; temp[7] = "《魔兽世界》一直是喜欢怀旧们的老铁心目中最值得回忆的游戏之一,而有一些外国技术宅也致力于通过私服的方式还原老版本的《魔兽世界》。这不,有一群外国粉丝进行了一个菲米丝计划(Felmyst project):一个打算让玩家重温“燃烧的远征”资料片的私服。该项目酝酿了四年之久,却在正式开服5小时之后,被暴雪无情关闭。"; temp[8] = "意甲本周末拉齐奥与帕尔马之战为收官阶段表现较为突出的两支球队之间的较量,两队在最"; temp[9] = "Can we make this quick? Roxanne Korrine and Andrew Barrett are having an incredibly horrendous public break- up on the quad. Again."; temp[10] = "半年後に銀行融資を受けたいのだが、今から何を準備すればいいのか?"; temp[11] = "代わりと言っては何ですが、???私が、いささか、ご指南いたしましょう。退職を契機に茶道を始めた。滞りのない、優雅な仕草でグラスに水を注ぎ込んだ体壊したらどうするんだ。アンバランスな食事は、万病の元だぞ。"; temp[12] = "本報訊 蘇崇琦、吳春輝報道:11月上旬,筆者在第20集團軍某團「戰神杯」千人百崗練兵比武場上看到:汽車連駕駛員李鵬在無千斤頂的情況下快速更換輪胎,用時不到5分鐘。教練班長沙仕萬和他所帶的徒弟謝家勝,包攬了瞄準手專業冠亞軍。該團團長王洪輝説,這是他們開展千人百崗大練兵帶來的可喜變化。"; temp[13] = "表示的測試總時長爲1180秒,總里程:11.007km,圖中有Part1和PArt2兩部分"; temp[14] = "買車時的售價雖然很重要,但之後養車的費用更是令許多人頭痛!養車成本主要可從擁車 3 年與 10 年兩個期間來看,大部分車款3年後都已過原廠保固,而 10 年則是一般車輛長期保養成本的分水嶺,也是民眾考慮換車的時候。美國《消費者報告 Consumer Reports》近日公布一項調查統計,比較平均保養成本。"; temp[15] = "美國相當具權威的《消費者報告 Consumer Reports》調查 32 家車廠,同時針對車主所提供的保養、維修費用進行統計,分別列出 3 年車與 10 年車的每年平均養車成本,數據顯示為 2014 年與 2007 年,其中部分品牌因為停產緣故,沒有 3 年養車成本數據,但仍可以比較 10 年養車成本。"; /* * 字符串读取 * */ data data = new data(); for (int i = 0; i < 15; i++) { data.setText(temp[i]); Gson gson = new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(data)); //插入数据库 collection.insert(dbObject); } /*、 * * txt文件存入mongodb数据库 * */ /* String[] dirNames = new File("/Users/decrain/IdeaProjects/Classifier/target/classes/data/ceshi").list(); //System.out.println("路径: "+CLASS_PATH); if(null==dirNames || dirNames.length==0){ new Exception("data is null").printStackTrace(); return; } //DBCollection collection1 = db.getCollection("cur"); DBCursor cur1 = collection1.find(); //获取cur数据库中的ID值 int t=0; while (cur1.hasNext()) { t = Integer.parseInt(cur1.next().get("cur").toString()); } for(String dirName:dirNames) { File f = null; f = new File("/Users/decrain/IdeaProjects/Classifier/target/classes/data/ceshi"+'/'+dirName); System.out.println(dirName); File[] files = f.listFiles(); // 得到f文件夹下面的所有文件。 List<File> list = new ArrayList<File>(); for (File file : files) { list.add(file); } data data = new data(); for (File file : files) { System.out.println("文件名字: " + file.getName()); String text = FileUtils.readFile(file.getAbsolutePath()); text = text.replaceAll("\t",""); text = text.replaceAll("\n",""); text = text.replaceAll("\r",""); text = text.replaceAll("\\u0000",""); data.setText(text.toString()); data.setID(t); t += 1; Gson gson = new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(data)); //插入数据库 collection.insert(dbObject); } }*/ /* * 字符串读取 * */ /*data data = new data(); for (int i = 0; i < 3; i++) { data.setText(temp[i]); Gson gson = new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(data)); //插入数据库 collection.insert(dbObject); }*/ /*DBCursor cur = collection1.find(); while (cur.hasNext()) { System.out.println(cur.next().get("cur"));*/ /*cur cur = new cur(); cur.setCur(0); Gson gson=new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(cur)); //插入数据库 collection1.insert(dbObject);*/ //db游标 /* DBCursor cur1 = collection1.find(); while (cur1.hasNext()){ DBCursor cur = collection.find(new BasicDBObject("_id", new BasicDBObject("$gte", cur1.next().get("cur")))); while (cur.hasNext()) { System.out.println(cur.next().get("text").toString()+'\n'); System.out.println(cur.next().get("_id")); Object t = cur.next().get("_id"); BasicDBObject doc = new BasicDBObject(); BasicDBObject res = new BasicDBObject(); res.put("cur",t); doc.put("$set",res); collection1.update(new BasicDBObject(),doc,false,true); } } */ //更新数据 /* BasicDBObject doc = new BasicDBObject(); BasicDBObject res = new BasicDBObject(); res.put("cur",t); doc.put("$set",res); collection1.update(new BasicDBObject(),doc,false,true);*/ // data.setText(); /* Gson gson=new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(data)); //插入数据库 collection.insert(dbObject); BasicDBObject document = new BasicDBObject(); document.put("id", 1001); document.put("msg", "hello world mongoDB in Java"); //将新建立的document保存到collection中去 collection.insert(document); // 创建要查询的document BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("id", 1001); // 使用collection的find方法查找document DBCursor cursor = collection.find(searchQuery); //循环输出结果 while (cursor.hasNext()) { System.out.println(cursor.next()); } System.out.println("Done");*/ } }
Decrain/classifier
src/main/java/com/decrain/spark/mllib/dao/MongoDBConnect.java
3,299
//temp = "晴朗的天空,我们常看到喷气式飞机在高空飞行时,机身后边会出现一条或数条长长的“白烟”。其实,这不是喷气式飞机喷出来的烟,而是飞机排出来的废气与周围环境空气混合后,水汽凝结而成的特殊云系,航空飞行界和航空气象学上称之为飞机尾迹";
line_comment
zh-cn
package com.decrain.spark.mllib.dao; import com.google.gson.Gson; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.mongodb.util.JSON; import org.apache.log4j.PropertyConfigurator; import com.decrain.spark.mllib.dto.data; /** * Created by Decrain on 2017/8/15. */ public class MongoDBConnect { public static void main(String args[]) { String log4jConfPath = "/Users/decrain/IdeaProjects/Classifier/log4j.properties"; PropertyConfigurator.configure(log4jConfPath); MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient.getDB("TextClassifier"); DBCollection collection = db.getCollection("data"); DBCollection collection1 = db.getCollection("cur"); String[] temp = new String[100]; temp[0] = "自2008年首款 Andriod 系统推出以来,Google 一直提倡与App 开发者,设备制造商,及广大用户共享 Android 平台的预览版,并期望收到技术方面的反馈。今日, Google 发布首个 Android O 开发者预览版。 虽然作为早期预览版来说,很多新特性未正式加入其中,在稳定性与性能方面也需要更多改进,但这仅仅是一个开端在接下来的几个月中,Google 将发布开发者预览版的更新,更多详情将在今年 5 月的 Google I/O 大会上揭晓。同时,Google 也期待收到开发者关于新特性的反馈,也希望有更多开发者在这新的操作系统中对 App 进行测试。"; //te <SUF> temp[1] = "2017年7月19日,东风雪铁龙旗下全新紧凑型SUV天逸 C5 AIRCROSS在神龙汽车成都工厂正式下线,搜狐汽车抢先与东风雪铁龙的车总和饶总进行了产品设计方面的沟通"; temp[2] = "海军部队将在青岛至连云港以东海域组织大型军事活动。为确保安全,请各船舶特别注意:2017年7月27日0800至7月29日1800,不得进入下图所示临时禁航区,含91-95、101-105、111-115号、120-123号渔区,并听从外围警戒舰艇指挥,以策安全。——中国人民解放军91208部队"; temp[3] = "sdgfklasdngksdngosdgn"; temp[4] = "美联社说,美国与澳大利亚刚刚完成大型联合军事演习,双方派出36艘战舰、220架飞机及3.3万名士兵,期间遭到中国海军情报船监视。"; temp[5] = "据考试院介绍,在刚刚结束的本科二批次录取中,372所院校在京参加二批录取,计划招生14351人,实际录取15124人,较计划增加773人。其中文史类招生计划4435人,实际录取4525人,较计划增加了90人;理工类招生计划9916人,实际录取10599人,较计划增加了683人"; temp[6] = "按照全国考办的统一部署,2006年度全国会计专业技术资格考试定于5月20日、21日举行。准考证现已制作完毕,请县市区考生持身份证"; temp[7] = "《魔兽世界》一直是喜欢怀旧们的老铁心目中最值得回忆的游戏之一,而有一些外国技术宅也致力于通过私服的方式还原老版本的《魔兽世界》。这不,有一群外国粉丝进行了一个菲米丝计划(Felmyst project):一个打算让玩家重温“燃烧的远征”资料片的私服。该项目酝酿了四年之久,却在正式开服5小时之后,被暴雪无情关闭。"; temp[8] = "意甲本周末拉齐奥与帕尔马之战为收官阶段表现较为突出的两支球队之间的较量,两队在最"; temp[9] = "Can we make this quick? Roxanne Korrine and Andrew Barrett are having an incredibly horrendous public break- up on the quad. Again."; temp[10] = "半年後に銀行融資を受けたいのだが、今から何を準備すればいいのか?"; temp[11] = "代わりと言っては何ですが、???私が、いささか、ご指南いたしましょう。退職を契機に茶道を始めた。滞りのない、優雅な仕草でグラスに水を注ぎ込んだ体壊したらどうするんだ。アンバランスな食事は、万病の元だぞ。"; temp[12] = "本報訊 蘇崇琦、吳春輝報道:11月上旬,筆者在第20集團軍某團「戰神杯」千人百崗練兵比武場上看到:汽車連駕駛員李鵬在無千斤頂的情況下快速更換輪胎,用時不到5分鐘。教練班長沙仕萬和他所帶的徒弟謝家勝,包攬了瞄準手專業冠亞軍。該團團長王洪輝説,這是他們開展千人百崗大練兵帶來的可喜變化。"; temp[13] = "表示的測試總時長爲1180秒,總里程:11.007km,圖中有Part1和PArt2兩部分"; temp[14] = "買車時的售價雖然很重要,但之後養車的費用更是令許多人頭痛!養車成本主要可從擁車 3 年與 10 年兩個期間來看,大部分車款3年後都已過原廠保固,而 10 年則是一般車輛長期保養成本的分水嶺,也是民眾考慮換車的時候。美國《消費者報告 Consumer Reports》近日公布一項調查統計,比較平均保養成本。"; temp[15] = "美國相當具權威的《消費者報告 Consumer Reports》調查 32 家車廠,同時針對車主所提供的保養、維修費用進行統計,分別列出 3 年車與 10 年車的每年平均養車成本,數據顯示為 2014 年與 2007 年,其中部分品牌因為停產緣故,沒有 3 年養車成本數據,但仍可以比較 10 年養車成本。"; /* * 字符串读取 * */ data data = new data(); for (int i = 0; i < 15; i++) { data.setText(temp[i]); Gson gson = new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(data)); //插入数据库 collection.insert(dbObject); } /*、 * * txt文件存入mongodb数据库 * */ /* String[] dirNames = new File("/Users/decrain/IdeaProjects/Classifier/target/classes/data/ceshi").list(); //System.out.println("路径: "+CLASS_PATH); if(null==dirNames || dirNames.length==0){ new Exception("data is null").printStackTrace(); return; } //DBCollection collection1 = db.getCollection("cur"); DBCursor cur1 = collection1.find(); //获取cur数据库中的ID值 int t=0; while (cur1.hasNext()) { t = Integer.parseInt(cur1.next().get("cur").toString()); } for(String dirName:dirNames) { File f = null; f = new File("/Users/decrain/IdeaProjects/Classifier/target/classes/data/ceshi"+'/'+dirName); System.out.println(dirName); File[] files = f.listFiles(); // 得到f文件夹下面的所有文件。 List<File> list = new ArrayList<File>(); for (File file : files) { list.add(file); } data data = new data(); for (File file : files) { System.out.println("文件名字: " + file.getName()); String text = FileUtils.readFile(file.getAbsolutePath()); text = text.replaceAll("\t",""); text = text.replaceAll("\n",""); text = text.replaceAll("\r",""); text = text.replaceAll("\\u0000",""); data.setText(text.toString()); data.setID(t); t += 1; Gson gson = new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(data)); //插入数据库 collection.insert(dbObject); } }*/ /* * 字符串读取 * */ /*data data = new data(); for (int i = 0; i < 3; i++) { data.setText(temp[i]); Gson gson = new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(data)); //插入数据库 collection.insert(dbObject); }*/ /*DBCursor cur = collection1.find(); while (cur.hasNext()) { System.out.println(cur.next().get("cur"));*/ /*cur cur = new cur(); cur.setCur(0); Gson gson=new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(cur)); //插入数据库 collection1.insert(dbObject);*/ //db游标 /* DBCursor cur1 = collection1.find(); while (cur1.hasNext()){ DBCursor cur = collection.find(new BasicDBObject("_id", new BasicDBObject("$gte", cur1.next().get("cur")))); while (cur.hasNext()) { System.out.println(cur.next().get("text").toString()+'\n'); System.out.println(cur.next().get("_id")); Object t = cur.next().get("_id"); BasicDBObject doc = new BasicDBObject(); BasicDBObject res = new BasicDBObject(); res.put("cur",t); doc.put("$set",res); collection1.update(new BasicDBObject(),doc,false,true); } } */ //更新数据 /* BasicDBObject doc = new BasicDBObject(); BasicDBObject res = new BasicDBObject(); res.put("cur",t); doc.put("$set",res); collection1.update(new BasicDBObject(),doc,false,true);*/ // data.setText(); /* Gson gson=new Gson(); //转换成json字符串,再转换成DBObject对象 DBObject dbObject = (DBObject) JSON.parse(gson.toJson(data)); //插入数据库 collection.insert(dbObject); BasicDBObject document = new BasicDBObject(); document.put("id", 1001); document.put("msg", "hello world mongoDB in Java"); //将新建立的document保存到collection中去 collection.insert(document); // 创建要查询的document BasicDBObject searchQuery = new BasicDBObject(); searchQuery.put("id", 1001); // 使用collection的find方法查找document DBCursor cursor = collection.find(searchQuery); //循环输出结果 while (cursor.hasNext()) { System.out.println(cursor.next()); } System.out.println("Done");*/ } }
0
124
0
24957_1
package com.mooctest; import io.appium.java_client.AndroidKeyCode; import io.appium.java_client.AppiumDriver; import org.openqa.selenium.remote.DesiredCapabilities; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; public class Main { /** * 所有和AppiumDriver相关的操作都必须写在该函数中 * * @param driver */ public void test(AppiumDriver driver) { driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); //设置尝试定位控件的最长时间为8s,也就是最多尝试8s /* * 余下的测试逻辑请按照题目要求进行编写 */ waitForActivity(driver, "MainActivity"); driver.findElementById("com.sankuai.meituan:id/city_button").click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } driver.findElementsByXPath("//android.widget.TextView[@text='南京']").get(1).click(); driver.findElementByXPath("//android.view.View[@content-desc='附近']").click(); driver.findElementByXPath("//android.view.View[@content-desc='发现']").click(); driver.findElementByXPath("//android.view.View[@content-desc='订单']").click(); driver.findElementByXPath("//android.view.View[@content-desc='我的']").click(); driver.findElementByXPath("//android.view.View[@content-desc='首页']").click(); driver.findElementByXPath("//android.view.View[@content-desc='美食']").click(); driver.findElementByXPath("//android.widget.TextView[@text='优惠团购']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='附近好券']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='预约订座']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='外卖']").click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='新店特惠']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='自助餐']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='火锅']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='江浙菜']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_list_map_menu_img").click(); driver.findElementById("com.sankuai.meituan:id/food_search_header_search").click(); driver.findElementByXPath("//android.widget.TextView[@text='新街口地区']").click(); driver.findElementById("com.sankuai.meituan:id/food_map_location_button").click(); driver.findElementById("com.sankuai.meituan:id/food_search_header_back").click(); driver.findElementById("com.sankuai.meituan:id/tv_search_text").click(); driver.findElementById("com.sankuai.meituan:id/search_edit").sendKeys("小龙虾"); driver.findElementById("com.sankuai.meituan:id/search").click(); driver.findElementById("com.sankuai.meituan:id/category").click(); driver.findElementByXPath("//android.widget.TextView[@text='美食']").click(); driver.findElementById("com.sankuai.meituan:id/category").click(); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.findElementByXPath("//android.widget.TextView[@text='海鲜']").click(); driver.findElementById("com.sankuai.meituan:id/area").click(); driver.findElementByXPath("//android.widget.TextView[@text='鼓楼区']").click(); driver.findElementByXPath("//android.widget.TextView[@text='新街口/金轮/五台山体育中心']").click(); driver.findElementById("com.sankuai.meituan:id/sort").click(); driver.findElementByXPath("//android.widget.TextView[@text='好评优先']").click(); driver.findElementById("com.sankuai.meituan:id/senior_filter").click(); driver.findElementByXPath("//android.widget.TextView[@text='5~10人餐']").click(); driver.findElementById("com.sankuai.meituan:id/bottom_confirm").click(); driver.findElementsById("com.sankuai.meituan:id/image").get(0).click(); driver.findElementById("com.sankuai.meituan:id/favor").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementById("com.sankuai.meituan:id/share_cancel").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementByXPath("//android.widget.TextView[@text='微信好友']"); //.click(); // driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='朋友圈']"); //.click(); // driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='复制']").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementByXPath("//android.widget.TextView[@text='更多']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_poi_top_image").click(); driver.findElementByXPath("//android.widget.ImageButton[@content-desc='转到上一层级']").click(); driver.findElementById("com.sankuai.meituan:id/food_poi_address_container").click(); driver.findElementById("com.sankuai.meituan:id/food_header_back").click(); driver.findElementById("com.sankuai.meituan:id/food_poi_taxi_img").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_poi_telephone_img").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='优惠信息']").click(); driver.findElementByXPath("//android.widget.TextView[@text='用户评论']").click(); driver.findElementByXPath("//android.widget.TextView[@text='商家信息']").click(); driver.quit(); } private void waitForActivity(AppiumDriver driver, String activity) { activity = "." + activity; while (!driver.currentActivity().contains(activity)) { System.out.println("- Waiting for " + activity); Thread.yield(); } System.out.println(">> Begin " + activity); } /** * AppiumDriver的初始化逻辑必须写在该函数中 * * @return */ public AppiumDriver initAppiumTest() { AppiumDriver driver = null; File classpathRoot = new File(System.getProperty("user.dir")); File appDir = new File(classpathRoot, "apk"); File app = new File(appDir, "Meituan.apk"); //设置自动化相关参数 DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("automationName", "UiAutomator2"); capabilities.setCapability("browserName", ""); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("deviceName", "Android Emulator"); //设置apk路径 capabilities.setCapability("app", app.getAbsolutePath()); capabilities.setCapability("appPackage", "com.sankuai.meituan"); capabilities.setCapability("appActivity", "com.meituan.android.pt.homepage.activity.Welcome"); //设置使用unicode键盘,支持输入中文和特殊字符 capabilities.setCapability("unicodeKeyboard", "true"); //设置用例执行完成后重置键盘 capabilities.setCapability("resetKeyboard", "true"); capabilities.setCapability("noSign", "true"); //初始化 try { driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return driver; } public void start() { test(initAppiumTest()); } public static void main(String[] args) { Main main = new Main(); main.start(); } }
DeepAQ/SoftwareTesting
Appium/Meituan/src/com/mooctest/Main.java
2,349
//设置尝试定位控件的最长时间为8s,也就是最多尝试8s
line_comment
zh-cn
package com.mooctest; import io.appium.java_client.AndroidKeyCode; import io.appium.java_client.AppiumDriver; import org.openqa.selenium.remote.DesiredCapabilities; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; public class Main { /** * 所有和AppiumDriver相关的操作都必须写在该函数中 * * @param driver */ public void test(AppiumDriver driver) { driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); //设置 <SUF> /* * 余下的测试逻辑请按照题目要求进行编写 */ waitForActivity(driver, "MainActivity"); driver.findElementById("com.sankuai.meituan:id/city_button").click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } driver.findElementsByXPath("//android.widget.TextView[@text='南京']").get(1).click(); driver.findElementByXPath("//android.view.View[@content-desc='附近']").click(); driver.findElementByXPath("//android.view.View[@content-desc='发现']").click(); driver.findElementByXPath("//android.view.View[@content-desc='订单']").click(); driver.findElementByXPath("//android.view.View[@content-desc='我的']").click(); driver.findElementByXPath("//android.view.View[@content-desc='首页']").click(); driver.findElementByXPath("//android.view.View[@content-desc='美食']").click(); driver.findElementByXPath("//android.widget.TextView[@text='优惠团购']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='附近好券']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='预约订座']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='外卖']").click(); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='新店特惠']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='自助餐']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='火锅']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='江浙菜']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_list_map_menu_img").click(); driver.findElementById("com.sankuai.meituan:id/food_search_header_search").click(); driver.findElementByXPath("//android.widget.TextView[@text='新街口地区']").click(); driver.findElementById("com.sankuai.meituan:id/food_map_location_button").click(); driver.findElementById("com.sankuai.meituan:id/food_search_header_back").click(); driver.findElementById("com.sankuai.meituan:id/tv_search_text").click(); driver.findElementById("com.sankuai.meituan:id/search_edit").sendKeys("小龙虾"); driver.findElementById("com.sankuai.meituan:id/search").click(); driver.findElementById("com.sankuai.meituan:id/category").click(); driver.findElementByXPath("//android.widget.TextView[@text='美食']").click(); driver.findElementById("com.sankuai.meituan:id/category").click(); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.swipe(800, 600, 800, 200, 500); driver.findElementByXPath("//android.widget.TextView[@text='海鲜']").click(); driver.findElementById("com.sankuai.meituan:id/area").click(); driver.findElementByXPath("//android.widget.TextView[@text='鼓楼区']").click(); driver.findElementByXPath("//android.widget.TextView[@text='新街口/金轮/五台山体育中心']").click(); driver.findElementById("com.sankuai.meituan:id/sort").click(); driver.findElementByXPath("//android.widget.TextView[@text='好评优先']").click(); driver.findElementById("com.sankuai.meituan:id/senior_filter").click(); driver.findElementByXPath("//android.widget.TextView[@text='5~10人餐']").click(); driver.findElementById("com.sankuai.meituan:id/bottom_confirm").click(); driver.findElementsById("com.sankuai.meituan:id/image").get(0).click(); driver.findElementById("com.sankuai.meituan:id/favor").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementById("com.sankuai.meituan:id/share_cancel").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementByXPath("//android.widget.TextView[@text='微信好友']"); //.click(); // driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='朋友圈']"); //.click(); // driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='复制']").click(); driver.findElementById("com.sankuai.meituan:id/share").click(); driver.findElementByXPath("//android.widget.TextView[@text='更多']").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_poi_top_image").click(); driver.findElementByXPath("//android.widget.ImageButton[@content-desc='转到上一层级']").click(); driver.findElementById("com.sankuai.meituan:id/food_poi_address_container").click(); driver.findElementById("com.sankuai.meituan:id/food_header_back").click(); driver.findElementById("com.sankuai.meituan:id/food_poi_taxi_img").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementById("com.sankuai.meituan:id/food_poi_telephone_img").click(); driver.sendKeyEvent(AndroidKeyCode.BACK); driver.findElementByXPath("//android.widget.TextView[@text='优惠信息']").click(); driver.findElementByXPath("//android.widget.TextView[@text='用户评论']").click(); driver.findElementByXPath("//android.widget.TextView[@text='商家信息']").click(); driver.quit(); } private void waitForActivity(AppiumDriver driver, String activity) { activity = "." + activity; while (!driver.currentActivity().contains(activity)) { System.out.println("- Waiting for " + activity); Thread.yield(); } System.out.println(">> Begin " + activity); } /** * AppiumDriver的初始化逻辑必须写在该函数中 * * @return */ public AppiumDriver initAppiumTest() { AppiumDriver driver = null; File classpathRoot = new File(System.getProperty("user.dir")); File appDir = new File(classpathRoot, "apk"); File app = new File(appDir, "Meituan.apk"); //设置自动化相关参数 DesiredCapabilities capabilities = new DesiredCapabilities(); capabilities.setCapability("automationName", "UiAutomator2"); capabilities.setCapability("browserName", ""); capabilities.setCapability("platformName", "Android"); capabilities.setCapability("deviceName", "Android Emulator"); //设置apk路径 capabilities.setCapability("app", app.getAbsolutePath()); capabilities.setCapability("appPackage", "com.sankuai.meituan"); capabilities.setCapability("appActivity", "com.meituan.android.pt.homepage.activity.Welcome"); //设置使用unicode键盘,支持输入中文和特殊字符 capabilities.setCapability("unicodeKeyboard", "true"); //设置用例执行完成后重置键盘 capabilities.setCapability("resetKeyboard", "true"); capabilities.setCapability("noSign", "true"); //初始化 try { driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return driver; } public void start() { test(initAppiumTest()); } public static void main(String[] args) { Main main = new Main(); main.start(); } }
1
28
1
34717_5
package info.hb.ccn.main; import info.hb.cnn.core.CNN; import info.hb.cnn.core.CNN.LayerBuilder; import info.hb.cnn.core.Layer; import info.hb.cnn.core.Layer.Size; import info.hb.cnn.data.DataSet; import info.hb.cnn.utils.ConcurentRunner; public class CNNMnist { private static final String MODEL_NAME = "mnist/model/model.cnn"; private static final String TRAIN_DATA = "mnist/train.format"; private static final String TEST_DATA = "mnist/test.format"; private static final String TEST_PREDICT = "mnist/test.predict"; public static void main(String[] args) { System.err.println("训练阶段:"); runTrain(); System.err.println("测试阶段:"); runTest(); ConcurentRunner.stop(); } public static void runTrain() { // 构建网络层次结构 LayerBuilder builder = new LayerBuilder(); builder.addLayer(Layer.buildInputLayer(new Size(28, 28))); // 输入层输出map大小为28×28 builder.addLayer(Layer.buildConvLayer(6, new Size(5, 5))); // 卷积层输出map大小为24×24,24=28+1-5 builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样层输出map大小为12×12,12=24/2 builder.addLayer(Layer.buildConvLayer(12, new Size(5, 5))); // 卷积层输出map大小为8×8,8=12+1-5 builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样层输出map大小为4×4,4=8/2 builder.addLayer(Layer.buildOutputLayer(10)); CNN cnn = new CNN(builder, 10); // 加载训练数据 DataSet dataset = DataSet.load(TRAIN_DATA, ",", 784); // 开始训练模型 cnn.train(dataset, 5); // 保存训练好的模型 cnn.saveModel(MODEL_NAME); dataset.clear(); } public static void runTest() { // 加载训练好的模型 CNN cnn = CNN.loadModel(MODEL_NAME); // 加载测试数据 DataSet testSet = DataSet.load(TEST_DATA, ",", -1); // 预测结果 cnn.predict(testSet, TEST_PREDICT); testSet.clear(); } }
DeepCompute/cnn
src/main/java/info/hb/ccn/main/CNNMnist.java
664
// 采样层输出map大小为4×4,4=8/2
line_comment
zh-cn
package info.hb.ccn.main; import info.hb.cnn.core.CNN; import info.hb.cnn.core.CNN.LayerBuilder; import info.hb.cnn.core.Layer; import info.hb.cnn.core.Layer.Size; import info.hb.cnn.data.DataSet; import info.hb.cnn.utils.ConcurentRunner; public class CNNMnist { private static final String MODEL_NAME = "mnist/model/model.cnn"; private static final String TRAIN_DATA = "mnist/train.format"; private static final String TEST_DATA = "mnist/test.format"; private static final String TEST_PREDICT = "mnist/test.predict"; public static void main(String[] args) { System.err.println("训练阶段:"); runTrain(); System.err.println("测试阶段:"); runTest(); ConcurentRunner.stop(); } public static void runTrain() { // 构建网络层次结构 LayerBuilder builder = new LayerBuilder(); builder.addLayer(Layer.buildInputLayer(new Size(28, 28))); // 输入层输出map大小为28×28 builder.addLayer(Layer.buildConvLayer(6, new Size(5, 5))); // 卷积层输出map大小为24×24,24=28+1-5 builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样层输出map大小为12×12,12=24/2 builder.addLayer(Layer.buildConvLayer(12, new Size(5, 5))); // 卷积层输出map大小为8×8,8=12+1-5 builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样 <SUF> builder.addLayer(Layer.buildOutputLayer(10)); CNN cnn = new CNN(builder, 10); // 加载训练数据 DataSet dataset = DataSet.load(TRAIN_DATA, ",", 784); // 开始训练模型 cnn.train(dataset, 5); // 保存训练好的模型 cnn.saveModel(MODEL_NAME); dataset.clear(); } public static void runTest() { // 加载训练好的模型 CNN cnn = CNN.loadModel(MODEL_NAME); // 加载测试数据 DataSet testSet = DataSet.load(TEST_DATA, ",", -1); // 预测结果 cnn.predict(testSet, TEST_PREDICT); testSet.clear(); } }
1
23
1
59249_1
package com.hspedu.homework.homework13; /* 写一个Teacher类,Teacher类有名称(name),性别(sex),年龄(age),工龄(work_age), 做合理封装,通过构造器在创建对象时将4个属性赋值 */ public class Teacher extends Person { //属性 private int work_age; //方法 public Teacher(String name, char gender, int age, int work_age) { super(name, gender, age); this.work_age = work_age; } public int getWork_age() { return work_age; } public void setWork_age(int work_age) { this.work_age = work_age; } //教师需要有教学的方法(teach),在方法里写上“我承诺,我会认真教学。 public void teach() { System.out.println(getName() + "承诺,我会认真教学 java..."); } /** * 老师爱玩象棋 */ @Override public String play() { return super.play() + "象棋"; } //输出信息方法 public void printInfo() { System.out.println("老师的信息:"); System.out.println(super.basicInfo()); System.out.println("工龄: " + work_age); teach(); System.out.println(play()); } @Override public String toString() { return "Teacher{" + "work_age=" + work_age + '}' + super.toString(); } }
DeepDarkBoy48/JavaStudy
newcode/chapter08/src/com/hspedu/homework/homework13/Teacher.java
384
//教师需要有教学的方法(teach),在方法里写上“我承诺,我会认真教学。
line_comment
zh-cn
package com.hspedu.homework.homework13; /* 写一个Teacher类,Teacher类有名称(name),性别(sex),年龄(age),工龄(work_age), 做合理封装,通过构造器在创建对象时将4个属性赋值 */ public class Teacher extends Person { //属性 private int work_age; //方法 public Teacher(String name, char gender, int age, int work_age) { super(name, gender, age); this.work_age = work_age; } public int getWork_age() { return work_age; } public void setWork_age(int work_age) { this.work_age = work_age; } //教师 <SUF> public void teach() { System.out.println(getName() + "承诺,我会认真教学 java..."); } /** * 老师爱玩象棋 */ @Override public String play() { return super.play() + "象棋"; } //输出信息方法 public void printInfo() { System.out.println("老师的信息:"); System.out.println(super.basicInfo()); System.out.println("工龄: " + work_age); teach(); System.out.println(play()); } @Override public String toString() { return "Teacher{" + "work_age=" + work_age + '}' + super.toString(); } }
0
38
0
58221_15
package bakacraft; import bakacraft.WeaponSkills.Random; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; public class CraftLimit extends BAKAPlugin implements Listener { public final static String CRAFT = Random.Colorilize("&2制造"); public final static String USE = Random.Colorilize("&3使用"); public final static String BREAK = Random.Colorilize("&c破坏"); public CraftLimit(JavaPlugin instance) { super(instance); getInstance().getServer().getPluginManager().registerEvents(this, instance); } @Override public void onDisable() { super.onDisable(); } //制造限制插件 //必须学习技能之后才有制造某件东西的权限 //限制下列工具: //木、石、铁、金、钻石 稿、斧、剑 //铲和锄不限制 //工作台、熔炉、打火机、剪刀、箱子 //合成除了原始合成之外,还需要旧的一件工具合成 //正常合成铁镐之后,会有无法使用标志 //需要使用一个石稿进行解锁 //熔炉需要打火机解锁才能使用。(消耗1点打火机耐久) //工作台、打火机、剪刀、箱子无需前置解锁即可使用() //挖掘限制: //木头可以手撸 //要挖石头必须木镐及以上 //要挖铁必须石镐及以上 //依次类推 //烧制相关矿石需要相关前置解锁 public boolean breakable(Material mat) { switch (mat) { case GOLD_ORE: case IRON_ORE: case DIAMOND_ORE: return true; default: return false; } } public boolean craftable(Material mat) { switch (mat) { case WOOD_AXE: case GOLD_AXE: case IRON_AXE: case STONE_AXE: case DIAMOND_AXE: case WOOD_PICKAXE: case GOLD_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: case DIAMOND_PICKAXE: case GOLD_SWORD: case STONE_SWORD: case IRON_SWORD: case WOOD_SWORD: case DIAMOND_SWORD: case WORKBENCH: case FURNACE: case SHEARS: case CHEST: return true; default: return false; } } public boolean usable(Material mat) { switch (mat) { case WOOD_AXE: case GOLD_AXE: case IRON_AXE: case STONE_AXE: case DIAMOND_AXE: case WOOD_PICKAXE: case GOLD_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: case DIAMOND_PICKAXE: case GOLD_SWORD: case STONE_SWORD: case IRON_SWORD: case WOOD_SWORD: case DIAMOND_SWORD: return true; default: return false; } } @EventHandler public void onPlayerCraft(CraftItemEvent e) { if (!craftable(e.getRecipe().getResult().getType())) return; if (e.getWhoClicked() instanceof Player) { Player p = (Player) e.getWhoClicked(); if (p.isOp()) return; if (!p.hasPermission(CRAFT + e.getCurrentItem().getItemMeta().getDisplayName())) { e.setCancelled(true); } else { List<String> lores = new ArrayList<>(); lores.add(Random.Colorilize("&e需要权限:")); lores.add(USE + e.getCurrentItem().getItemMeta().getDisplayName()); ItemMeta meta = e.getCurrentItem().getItemMeta(); meta.setLore(lores); e.getCurrentItem().setItemMeta(meta); } } } @EventHandler public void onPlayerFurnaceOpen(InventoryOpenEvent e) { if (e.getPlayer().isOp()) return; if (e.getInventory().getType() == InventoryType.FURNACE) { if (!e.getPlayer().getItemInHand().getType().equals(Material.FLINT_AND_STEEL)) { ((Player) e.getPlayer()).sendRawMessage("你需要一个打火石来点燃熔炉"); e.setCancelled(true); } } } @EventHandler public void onPlayerInteract(PlayerInteractEvent e) { if (e.getPlayer().isOp()) return; if (!usable(e.getPlayer().getItemInHand().getType())) return; if (e.getPlayer().hasPermission(CRAFT + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) { e.setCancelled(true); } } @EventHandler public void onPlayerBreak(BlockBreakEvent e) { if (e.getPlayer().isOp()) return; if (!breakable(e.getBlock().getType())) return; if (e.getPlayer().hasPermission(BREAK + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) { e.setCancelled(true); } } @EventHandler public void onPlayerSwitchHeld(PlayerItemHeldEvent e) { if (e.getPlayer().isOp()) return; ItemStack newItem = e.getPlayer().getInventory().getItem(e.getNewSlot()); if (newItem == null || !usable(newItem.getType())) return; if (e.getPlayer().hasPermission(USE + newItem.getItemMeta().getDisplayName())) { e.getPlayer().sendRawMessage("你需要解锁之后才能使用这件装备"); e.setCancelled(true); } } }
Deliay/BAKACraft
src/main/java/bakacraft/CraftLimit.java
1,568
//依次类推
line_comment
zh-cn
package bakacraft; import bakacraft.WeaponSkills.Random; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.inventory.CraftItemEvent; import org.bukkit.event.inventory.InventoryOpenEvent; import org.bukkit.event.inventory.InventoryType; import org.bukkit.event.player.PlayerInteractEvent; import org.bukkit.event.player.PlayerItemHeldEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.java.JavaPlugin; import java.util.ArrayList; import java.util.List; public class CraftLimit extends BAKAPlugin implements Listener { public final static String CRAFT = Random.Colorilize("&2制造"); public final static String USE = Random.Colorilize("&3使用"); public final static String BREAK = Random.Colorilize("&c破坏"); public CraftLimit(JavaPlugin instance) { super(instance); getInstance().getServer().getPluginManager().registerEvents(this, instance); } @Override public void onDisable() { super.onDisable(); } //制造限制插件 //必须学习技能之后才有制造某件东西的权限 //限制下列工具: //木、石、铁、金、钻石 稿、斧、剑 //铲和锄不限制 //工作台、熔炉、打火机、剪刀、箱子 //合成除了原始合成之外,还需要旧的一件工具合成 //正常合成铁镐之后,会有无法使用标志 //需要使用一个石稿进行解锁 //熔炉需要打火机解锁才能使用。(消耗1点打火机耐久) //工作台、打火机、剪刀、箱子无需前置解锁即可使用() //挖掘限制: //木头可以手撸 //要挖石头必须木镐及以上 //要挖铁必须石镐及以上 //依次 <SUF> //烧制相关矿石需要相关前置解锁 public boolean breakable(Material mat) { switch (mat) { case GOLD_ORE: case IRON_ORE: case DIAMOND_ORE: return true; default: return false; } } public boolean craftable(Material mat) { switch (mat) { case WOOD_AXE: case GOLD_AXE: case IRON_AXE: case STONE_AXE: case DIAMOND_AXE: case WOOD_PICKAXE: case GOLD_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: case DIAMOND_PICKAXE: case GOLD_SWORD: case STONE_SWORD: case IRON_SWORD: case WOOD_SWORD: case DIAMOND_SWORD: case WORKBENCH: case FURNACE: case SHEARS: case CHEST: return true; default: return false; } } public boolean usable(Material mat) { switch (mat) { case WOOD_AXE: case GOLD_AXE: case IRON_AXE: case STONE_AXE: case DIAMOND_AXE: case WOOD_PICKAXE: case GOLD_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: case DIAMOND_PICKAXE: case GOLD_SWORD: case STONE_SWORD: case IRON_SWORD: case WOOD_SWORD: case DIAMOND_SWORD: return true; default: return false; } } @EventHandler public void onPlayerCraft(CraftItemEvent e) { if (!craftable(e.getRecipe().getResult().getType())) return; if (e.getWhoClicked() instanceof Player) { Player p = (Player) e.getWhoClicked(); if (p.isOp()) return; if (!p.hasPermission(CRAFT + e.getCurrentItem().getItemMeta().getDisplayName())) { e.setCancelled(true); } else { List<String> lores = new ArrayList<>(); lores.add(Random.Colorilize("&e需要权限:")); lores.add(USE + e.getCurrentItem().getItemMeta().getDisplayName()); ItemMeta meta = e.getCurrentItem().getItemMeta(); meta.setLore(lores); e.getCurrentItem().setItemMeta(meta); } } } @EventHandler public void onPlayerFurnaceOpen(InventoryOpenEvent e) { if (e.getPlayer().isOp()) return; if (e.getInventory().getType() == InventoryType.FURNACE) { if (!e.getPlayer().getItemInHand().getType().equals(Material.FLINT_AND_STEEL)) { ((Player) e.getPlayer()).sendRawMessage("你需要一个打火石来点燃熔炉"); e.setCancelled(true); } } } @EventHandler public void onPlayerInteract(PlayerInteractEvent e) { if (e.getPlayer().isOp()) return; if (!usable(e.getPlayer().getItemInHand().getType())) return; if (e.getPlayer().hasPermission(CRAFT + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) { e.setCancelled(true); } } @EventHandler public void onPlayerBreak(BlockBreakEvent e) { if (e.getPlayer().isOp()) return; if (!breakable(e.getBlock().getType())) return; if (e.getPlayer().hasPermission(BREAK + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) { e.setCancelled(true); } } @EventHandler public void onPlayerSwitchHeld(PlayerItemHeldEvent e) { if (e.getPlayer().isOp()) return; ItemStack newItem = e.getPlayer().getInventory().getItem(e.getNewSlot()); if (newItem == null || !usable(newItem.getType())) return; if (e.getPlayer().hasPermission(USE + newItem.getItemMeta().getDisplayName())) { e.getPlayer().sendRawMessage("你需要解锁之后才能使用这件装备"); e.setCancelled(true); } } }
1
6
1
55286_3
package com.xd.demi.view; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; /** * Created by demi on 17/4/24. */ public class MyFlowLayout extends LinearLayout { private int verticalSpacing = 20; private int horizontalSpacing = 20; public MyFlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int widthUsed = paddingLeft + paddingRight; //已经占用的宽度 int heightUsed = paddingTop + paddingBottom; //已经占用的高度 int childMaxHeightOfThisLine = 0; //孩子中最高的那位,其实都一样高 int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childUsedWidth = 0; //某个孩子的宽度 int childUsedHeight = 0; //某个孩子的高度 measureChild(child, widthMeasureSpec, heightMeasureSpec); childUsedWidth += child.getMeasuredWidth(); childUsedHeight += child.getMeasuredHeight(); LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; childUsedWidth += marginLayoutParams.leftMargin + marginLayoutParams.rightMargin + horizontalSpacing; childUsedHeight += marginLayoutParams.topMargin + marginLayoutParams.bottomMargin; if (widthUsed + childUsedWidth < widthSpecSize) { widthUsed += childUsedWidth; if (childUsedHeight > childMaxHeightOfThisLine) { childMaxHeightOfThisLine = childUsedHeight; } } else { heightUsed += childMaxHeightOfThisLine + verticalSpacing; widthUsed = paddingLeft + paddingRight + childUsedWidth; childMaxHeightOfThisLine = childUsedHeight; } } } heightUsed += childMaxHeightOfThisLine; setMeasuredDimension(widthSpecSize, heightUsed); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int childStartLayoutX = paddingLeft; int childStartLayoutY = paddingTop; int widthUsed = paddingLeft + paddingRight; int childMaxHeight = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childNeededWidth, childNeedHeight; int left, top, right, bottom; int childMeasuredWidth = child.getMeasuredWidth(); int childMeasuredHeight = child.getMeasuredHeight(); LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; int childLeftMargin = marginLayoutParams.leftMargin; int childTopMargin = marginLayoutParams.topMargin; int childRightMargin = marginLayoutParams.rightMargin; int childBottomMargin = marginLayoutParams.bottomMargin; childNeededWidth = childLeftMargin + childRightMargin + childMeasuredWidth + horizontalSpacing; childNeedHeight = childTopMargin + childBottomMargin + childMeasuredHeight; if (widthUsed + childNeededWidth <= r - l) { if (childNeedHeight > childMaxHeight) { childMaxHeight = childNeedHeight; } left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; } else { childStartLayoutY += childMaxHeight + verticalSpacing; childStartLayoutX = paddingLeft; widthUsed = paddingLeft + paddingRight; left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; childMaxHeight = childNeedHeight; } child.layout(left, top, right, bottom); } } } }
Demidong/ClockView
app/src/main/java/com/xd/demi/view/MyFlowLayout.java
1,135
//孩子中最高的那位,其实都一样高
line_comment
zh-cn
package com.xd.demi.view; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; /** * Created by demi on 17/4/24. */ public class MyFlowLayout extends LinearLayout { private int verticalSpacing = 20; private int horizontalSpacing = 20; public MyFlowLayout(Context context, AttributeSet attrs) { super(context, attrs); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int widthUsed = paddingLeft + paddingRight; //已经占用的宽度 int heightUsed = paddingTop + paddingBottom; //已经占用的高度 int childMaxHeightOfThisLine = 0; //孩子 <SUF> int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childUsedWidth = 0; //某个孩子的宽度 int childUsedHeight = 0; //某个孩子的高度 measureChild(child, widthMeasureSpec, heightMeasureSpec); childUsedWidth += child.getMeasuredWidth(); childUsedHeight += child.getMeasuredHeight(); LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; childUsedWidth += marginLayoutParams.leftMargin + marginLayoutParams.rightMargin + horizontalSpacing; childUsedHeight += marginLayoutParams.topMargin + marginLayoutParams.bottomMargin; if (widthUsed + childUsedWidth < widthSpecSize) { widthUsed += childUsedWidth; if (childUsedHeight > childMaxHeightOfThisLine) { childMaxHeightOfThisLine = childUsedHeight; } } else { heightUsed += childMaxHeightOfThisLine + verticalSpacing; widthUsed = paddingLeft + paddingRight + childUsedWidth; childMaxHeightOfThisLine = childUsedHeight; } } } heightUsed += childMaxHeightOfThisLine; setMeasuredDimension(widthSpecSize, heightUsed); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int childStartLayoutX = paddingLeft; int childStartLayoutY = paddingTop; int widthUsed = paddingLeft + paddingRight; int childMaxHeight = 0; int childCount = getChildCount(); for (int i = 0; i < childCount; i++) { View child = getChildAt(i); if (child.getVisibility() != GONE) { int childNeededWidth, childNeedHeight; int left, top, right, bottom; int childMeasuredWidth = child.getMeasuredWidth(); int childMeasuredHeight = child.getMeasuredHeight(); LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams(); MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams; int childLeftMargin = marginLayoutParams.leftMargin; int childTopMargin = marginLayoutParams.topMargin; int childRightMargin = marginLayoutParams.rightMargin; int childBottomMargin = marginLayoutParams.bottomMargin; childNeededWidth = childLeftMargin + childRightMargin + childMeasuredWidth + horizontalSpacing; childNeedHeight = childTopMargin + childBottomMargin + childMeasuredHeight; if (widthUsed + childNeededWidth <= r - l) { if (childNeedHeight > childMaxHeight) { childMaxHeight = childNeedHeight; } left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; } else { childStartLayoutY += childMaxHeight + verticalSpacing; childStartLayoutX = paddingLeft; widthUsed = paddingLeft + paddingRight; left = childStartLayoutX + childLeftMargin; top = childStartLayoutY + childTopMargin; right = left + childMeasuredWidth; bottom = top + childMeasuredHeight; widthUsed += childNeededWidth; childStartLayoutX += childNeededWidth; childMaxHeight = childNeedHeight; } child.layout(left, top, right, bottom); } } } }
1
17
1
64372_3
package com.dxj.util; import lombok.extern.slf4j.Slf4j; /** * 原作者 zzxadi https://github.com/zzxadi/Snowflake-IdWorker * * @author Sinkiang */ @Slf4j public class SnowFlakeUtil { private final long id; /** * 机器标识位数 */ private final long workerIdBits = 10L; /** * 0,并发控制 */ private long sequence = 0L; private long lastTimestamp = -1L; private SnowFlakeUtil(long id) { // 机器ID最大值: 1023 long maxWorkerId = ~(-1L << this.workerIdBits); if (id > maxWorkerId || id < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } this.id = id; } public synchronized long nextId() { long timestamp = timeGen(); // 毫秒内自增位 long sequenceBits = 12L; if (this.lastTimestamp == timestamp) { //如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始 // 4095,111111111111,12位 long sequenceMask = ~(-1L << sequenceBits); this.sequence = this.sequence + 1 & sequenceMask; if (this.sequence == 0) { // 重新生成timestamp timestamp = this.tilNextMillis(this.lastTimestamp); } } else { this.sequence = 0; } if (timestamp < this.lastTimestamp) { log.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); return -1; } this.lastTimestamp = timestamp; // 22 long timestampLeftShift = sequenceBits + this.workerIdBits; // 时间起始标记点,作为基准,一般取系统的最近时间 long epoch = 1524291141010L; // 12 return timestamp - epoch << timestampLeftShift | this.id << sequenceBits | this.sequence; } private static SnowFlakeUtil flowIdWorker = new SnowFlakeUtil(1); public static SnowFlakeUtil getFlowIdInstance() { return flowIdWorker; } /** * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后 */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 获得系统当前毫秒数 */ private static long timeGen() { return System.currentTimeMillis(); } }
DengSinkiang/sk-admin
sk-common/src/main/java/com/dxj/util/SnowFlakeUtil.java
697
// 机器ID最大值: 1023
line_comment
zh-cn
package com.dxj.util; import lombok.extern.slf4j.Slf4j; /** * 原作者 zzxadi https://github.com/zzxadi/Snowflake-IdWorker * * @author Sinkiang */ @Slf4j public class SnowFlakeUtil { private final long id; /** * 机器标识位数 */ private final long workerIdBits = 10L; /** * 0,并发控制 */ private long sequence = 0L; private long lastTimestamp = -1L; private SnowFlakeUtil(long id) { // 机器 <SUF> long maxWorkerId = ~(-1L << this.workerIdBits); if (id > maxWorkerId || id < 0) { throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId)); } this.id = id; } public synchronized long nextId() { long timestamp = timeGen(); // 毫秒内自增位 long sequenceBits = 12L; if (this.lastTimestamp == timestamp) { //如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始 // 4095,111111111111,12位 long sequenceMask = ~(-1L << sequenceBits); this.sequence = this.sequence + 1 & sequenceMask; if (this.sequence == 0) { // 重新生成timestamp timestamp = this.tilNextMillis(this.lastTimestamp); } } else { this.sequence = 0; } if (timestamp < this.lastTimestamp) { log.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp))); return -1; } this.lastTimestamp = timestamp; // 22 long timestampLeftShift = sequenceBits + this.workerIdBits; // 时间起始标记点,作为基准,一般取系统的最近时间 long epoch = 1524291141010L; // 12 return timestamp - epoch << timestampLeftShift | this.id << sequenceBits | this.sequence; } private static SnowFlakeUtil flowIdWorker = new SnowFlakeUtil(1); public static SnowFlakeUtil getFlowIdInstance() { return flowIdWorker; } /** * 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后 */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } /** * 获得系统当前毫秒数 */ private static long timeGen() { return System.currentTimeMillis(); } }
1
16
1
23140_21
package com.uiatt.pcWeb; import java.io.File; import org.apache.log4j.Logger; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.testng.Reporter; import org.testng.annotations.Listeners; import com.uiatt.listener.Assertion; import com.uiatt.pcPage.RegPageElements; import com.uiatt.util.BaseTest; import com.uiatt.util.Dom4jXml; import com.uiatt.util.ReadWriteTxtFile; import com.uiatt.util.TakeMsgValidCode; import com.uiatt.util.Utils; /** * 提取2.0 PC 注册页面所有功能按钮元素 * author : Change * * */ @Log4j2 @Listeners({com.uiatt.listener.AssertionListener.class}) public class RegWebElements { // 注册用户名按钮 @FindBy(xpath = RegPageElements.REG_USERNAME) public static WebElement reg_username; // 注册密码 @FindBy(xpath = RegPageElements.REG_PWD) public static WebElement reg_pwd; // 确认密码 @FindBy(xpath = RegPageElements.REG_PWD_CONFIRM) public static WebElement reg_pwd_confirm; // 邮箱注册验证码输入框 @FindBy(xpath = RegPageElements.REG_EMAIL_VALIDCODE) public static WebElement reg_email_validcode; // 手机注册发送验证码按钮 @FindBy(xpath = RegPageElements.SEND_PHONE_VALIDCODE) public static WebElement send_phone_validcode; // 手机注册验证码输入框 @FindBy(xpath = RegPageElements.REG_PHONE_VALIDCODE) public static WebElement reg_phone_validcode; // 注册按钮 @FindBy(xpath = RegPageElements.REG_BTN) public static WebElement reg_btn; // 用户名错误提示信息 @FindBy(xpath = RegPageElements.REG_USERNAME_NOTICE) public static WebElement reg_username_notice; // 密码错误提示信息 @FindBy(xpath = RegPageElements.REG_PWD_NOTICE) public static WebElement reg_pwd_notice; // 再次输入密码错误提示信息 @FindBy(xpath = RegPageElements.REG_PWD_CONFIRM_NOTICE) public static WebElement reg_pwd_confirm_notice; // 邮箱验证码错误提示信息 @FindBy(xpath = RegPageElements.REG_EMAIL_VALIDCODE_NOTICE) public static WebElement reg_email_validcode_notice; // 短信验证码错误提示信息 @FindBy(xpath = RegPageElements.REG_PHONE_VALIDCODE_NOTICE) public static WebElement reg_phone_validcode_notice; public static WebDriver driver; public static String authLastName; public static String authFirstName; public static String authName; //初始化 public RegWebElements(WebDriver driver){ RegWebElements.driver = driver; authLastName=ReadWriteTxtFile.getLastName(); authFirstName=ReadWriteTxtFile.getFirstName(); //下面验证是否成功跳转微信关注公众号中间页时判断要用 authName=authLastName+authFirstName; BaseTest.logConf(); } //判断注册用户名输入框是否存在 public static boolean regUsnBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_USERNAME)); } //判断注册用户名错误提示信息是否存在 public static boolean regUsnNotiBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_USERNAME_NOTICE)); } //判断注册密码错误信息是否存在 public static boolean regPWDNotiBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_PWD_NOTICE)); } //判断注册再次输入密码错误信息是否存在 public static boolean regPWDConfNotiBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_PWD_CONFIRM_NOTICE)); } //判断注册图片验证码错误信息是否存在 public static boolean regEmValCoBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_EMAIL_VALIDCODE_NOTICE)); } //判断注册手机验证码错误提示信息是否存在 public static boolean regPhValCoBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_PHONE_VALIDCODE_NOTICE)); } //判断注册按钮是否存在 public static boolean regBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_BTN)); } /** * 注册邮箱账户 */ public static void regEmailFlow(String username, String password,String globalValicode) { LoginWebElements.regist_uiatt_btn.click(); Utils.sleep(5); logger.info("跳转并加载注册页面元素"); Reporter.log("跳转并加载注册页面元素"); //PageFactory.initElements(driver, RegWebElements.class); Utils.sleep(5); Assertion.assertEquals(true, RegWebElements.regUsnBtnIsExist(), "\"注册用户名\"输入框未找到,页面不符或元素改变,请检查!"); //因为此次只是功能流程的自动化脚本,先有行为逻辑才能触发相应校验,所以此处不对校验做全面的覆盖触发,只简单的考虑做一步行为,触发一个校验的判断;若今后有专门针对校验提示的全面覆盖脚本的需求,再说; logger.info("输入注册用户名:"+username); Reporter.log("输入注册用户名:"+username); reg_username.clear(); reg_username.sendKeys(username); reg_username.click(); logger.info("输入注册密码:"+password); Reporter.log("输入注册密码:"+password); reg_pwd.clear(); if(RegWebElements.regUsnNotiBtnIsExist() == true){ logger.error(reg_username_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_username_notice"); Assert.fail(reg_username_notice.getText()); } reg_pwd.sendKeys(password); reg_pwd.click(); logger.info("输入确认密码:"+password); Reporter.log("输入确认密码:"+password); reg_pwd_confirm.clear(); //ajax校验,错误提示在鼠标点击下一个输入框时才触发,元素才显示出来 if(RegWebElements.regPWDNotiBtnIsExist() == true){ logger.error(reg_pwd_notice.getText()); Reporter.log("[ERROR]"+reg_pwd_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_pwd_notice"); Assert.fail(reg_pwd_notice.getText()); } reg_pwd_confirm.sendKeys(password); reg_pwd_confirm.click(); logger.info("输入图片的万能验证码:"+globalValicode); Reporter.log("输入图片的万能验证码:"+globalValicode); //邮箱注册为图片验证码,此处以万能验证码处理,所以图片验证码的错误提示信息校验此处略过; reg_email_validcode.clear(); if(RegWebElements.regPWDConfNotiBtnIsExist() == true){ logger.error(reg_pwd_confirm_notice.getText()); Reporter.log("[ERROR]"+reg_pwd_confirm_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_pwd_confirm_notice"); Assert.fail(reg_pwd_confirm_notice.getText()); } reg_email_validcode.sendKeys(globalValicode); reg_email_validcode.click(); Assertion.assertEquals(true, RegWebElements.regBtnIsExist(), "\"注册\"按钮未找到,页面不符或元素改变,请检查!"); reg_btn.click(); //这个判断也许有点多余,只有在直接点击注册按钮,全部触发校验的时候才会生效 if(RegWebElements.regEmValCoBtnIsExist() == true && RegWebElements.regUsnNotiBtnIsExist() == true && RegWebElements.regPWDNotiBtnIsExist() == true && RegWebElements.regPWDConfNotiBtnIsExist() == true){ logger.error(reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_email_validcode_notice.getText()); Reporter.log("[ERROR]"+reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_email_validcode_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow"); Assert.fail(reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_email_validcode_notice.getText()); } Utils.sleep(2); } /** * 注册手机账户 */ public static void regPhoneFlow(String username, String password) { LoginWebElements.regist_uiatt_btn.click(); Utils.sleep(5); logger.info("跳转并加载注册页面元素"); Reporter.log("跳转并加载注册页面元素"); Utils.sleep(5); Assertion.assertEquals(true, RegWebElements.regUsnBtnIsExist(), "\"注册用户名\"输入框未找到,页面不符或元素改变,请检查!"); //因为此次只是功能流程的自动化脚本,先有行为逻辑才能触发相应校验,所以此处不对校验做全面的覆盖触发,只简单的考虑做一步行为,触发一个校验的判断;若今后有专门针对校验提示的全面覆盖脚本的需求,再说; logger.info("输入注册用户名:"+username); Reporter.log("输入注册用户名:"+username); reg_username.clear(); reg_username.sendKeys(username); reg_username.click(); logger.info("输入注册密码:"+password); Reporter.log("输入注册密码:"+password); reg_pwd.clear(); if(RegWebElements.regUsnNotiBtnIsExist() == true){ logger.error(reg_username_notice.getText()); Reporter.log("[ERROR]"+reg_username_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_username_notice"); Assert.fail(reg_username_notice.getText()); } reg_pwd.sendKeys(password); reg_pwd.click(); logger.info("输入确认密码:"+password); Reporter.log("输入确认密码:"+password); reg_pwd_confirm.clear(); //ajax校验,错误提示在鼠标点击下一个输入框时才触发,元素才显示出来 if(RegWebElements.regPWDNotiBtnIsExist() == true){ logger.error(reg_pwd_notice.getText()); Reporter.log("[ERROR]"+reg_pwd_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_pwd_notice"); Assert.fail(reg_pwd_notice.getText()); } reg_pwd_confirm.sendKeys(password); reg_pwd_confirm.click(); //点击发送短信验证码按钮 send_phone_validcode.click(); logger.info("已点击发送短信验证码按钮,等待响应返回值"); Reporter.log("已点击发送短信验证码按钮,等待响应返回值"); String mobileCheckCode = TakeMsgValidCode.takeMsgValidCode(username); logger.info("成功获取短信验证码:"+mobileCheckCode); Reporter.log("成功获取短信验证码:"+mobileCheckCode); reg_phone_validcode.clear(); if(RegWebElements.regPWDConfNotiBtnIsExist() == true){ logger.error(reg_pwd_confirm_notice.getText()); Reporter.log("[ERROR]"+reg_pwd_confirm_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_pwd_confirm_notice"); Assert.fail(reg_pwd_confirm_notice.getText()); } reg_phone_validcode.sendKeys(mobileCheckCode); reg_phone_validcode.click(); Assertion.assertEquals(true, RegWebElements.regBtnIsExist(), "\"注册\"按钮未找到,页面不符或元素改变,请检查!"); reg_btn.click(); if(RegWebElements.regPhValCoBtnIsExist() == true){ logger.error(reg_phone_validcode_notice.getText()); Reporter.log("[ERROR]"+reg_phone_validcode_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_phone_validcode_notice"); Assert.fail(reg_phone_validcode_notice.getText()); } //这个判断也许有点多余,只有在直接点击注册按钮,全部触发校验的时候才会生效 if(RegWebElements.regPhValCoBtnIsExist() == true && RegWebElements.regUsnNotiBtnIsExist() == true && RegWebElements.regPWDNotiBtnIsExist() == true && RegWebElements.regPWDConfNotiBtnIsExist() == true){ logger.error(reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_phone_validcode_notice.getText()); Reporter.log("[ERROR]"+reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_phone_validcode_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regPhoneFlow"); Assert.fail(reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_phone_validcode_notice.getText()); } Utils.sleep(2); } /** * 跳过认证 */ public static void skipAuth() { Utils.sleep(2); logger.info("开始跳转并加载医师认证页面元素"); Reporter.log("开始跳转并加载医师认证页面元素"); Utils.sleep(5); Assertion.assertEquals(true, DoctAuthWebElements.authSkipBtnIsExist(), "\"暂不认证\"按钮未找到,页面不符或元素改变,请检查!"); logger.info("暂不认证按钮元素确认存在并找到"); Reporter.log("暂不认证按钮元素确认存在并找到"); //点击暂不认证,跳转登录后的主页 DoctAuthWebElements.auth_skip_btn.click(); logger.info("点击暂不认证,跳转登录后的主页"); Reporter.log("点击暂不认证,跳转登录后的主页"); Utils.sleep(5); //通过判断“立即认证”按钮是否存在来验证是否跳转成功 Assertion.assertEquals(true, IndexWebElements.authNowBtnIsExist(), "\"立即认证\"按钮未找到,页面不符或元素改变,请检查!"); logger.info("立即认证按钮元素确认存在并找到,暂不认证注册用户登录成功"); Reporter.log("立即认证按钮元素确认存在并找到,暂不认证注册用户登录成功"); } /** * 完成认证,此处只对上传照片处做异常捕获与处理 */ public static void doneAuth() { logger.info("开始跳转并加载医师认证页面元素"); Reporter.log("开始跳转并加载医师认证页面元素"); Utils.sleep(3); Assertion.assertEquals(true, DoctAuthWebElements.lastNameBtnIsExist(), "\"姓\"输入框未找到,页面不符或元素改变,请检查!"); logger.info("开始进行认证信息的填写."); Reporter.log("开始进行认证信息的填写."); //姓 DoctAuthWebElements.auth_lastname.clear(); DoctAuthWebElements.auth_lastname.sendKeys(authLastName); DoctAuthWebElements.auth_lastname.click(); //名 DoctAuthWebElements.auth_firstname.clear(); DoctAuthWebElements.auth_firstname.sendKeys(authFirstName); DoctAuthWebElements.auth_firstname.click(); logger.info("doneAuth医师认证姓名检查:"+authName); Reporter.log("doneAuth医师认证姓名检查:"+authName); //勾选 医师学历证 DoctAuthWebElements.auth_educ_papers.click(); //证件号码 DoctAuthWebElements.auth_papers_number.clear(); DoctAuthWebElements.auth_papers_number.sendKeys(Dom4jXml.getValue("AUTH_PAPER_NUMBER")); DoctAuthWebElements.auth_papers_number.click(); Assertion.assertEquals(true, DoctAuthWebElements.authPhotoIsExist(), "\"上传照片\"按钮未找到,页面不符或元素未找到,请检查!"); //上传证件照片 String curPath = new File("").getAbsolutePath(); //所得结果为workspace所在路径 String filePath = curPath + Dom4jXml.getValue("AUTH_PHOTO_PATH"); logger.info("找到上传图片的按钮了吗?"+DoctAuthWebElements.authPhotoIsExist()); logger.info("找到上传图片的路径:"+filePath); logger.info("找到上传图片的定位路径:"+DoctAuthWebElements.auth_photo); Reporter.log("找到上传图片的按钮了吗?"+DoctAuthWebElements.authPhotoIsExist()); Reporter.log("找到上传图片的路径:"+filePath); Reporter.log("找到上传图片的定位路径:"+DoctAuthWebElements.auth_photo); DoctAuthWebElements.auth_photo.sendKeys(filePath); //医院 DoctAuthWebElements.auth_hospital.clear(); DoctAuthWebElements.auth_hospital.sendKeys(Dom4jXml.getValue("AUTH_HOSPITAL")); DoctAuthWebElements.auth_hospital.click(); //选择职称,先选择一个再取消一个 DoctAuthWebElements.auth_job.click(); DoctAuthWebElements.auth_resident_doct.click(); Utils.sleep(2); DoctAuthWebElements.selected_auth_resident_doct.click(); Utils.sleep(2); DoctAuthWebElements.auth_attend_doct.click(); DoctAuthWebElements.auth_lecturer.click(); DoctAuthWebElements.auth_master_tutor.click(); Utils.sleep(2); DoctAuthWebElements.auth_job_confirm.click(); //选择专业,先选择一个再取消一个 DoctAuthWebElements.auth_professional.click(); //此处只对上传照片处做异常捕获与处理 if(DoctAuthWebElements.authPhoNotiIsExist() == true){ logger.error(DoctAuthWebElements.auth_photo_noti.getText()); Reporter.log("[ERROR]"+DoctAuthWebElements.auth_photo_noti.getText()); //ScreenShotPC.screenShot("RegWebElements.doneAuth"); Assert.fail(DoctAuthWebElements.auth_photo_noti.getText()); } DoctAuthWebElements.auth_joint.click(); Utils.sleep(2); DoctAuthWebElements.selected_auth_join.click(); Utils.sleep(2); DoctAuthWebElements.auth_spine.click(); Utils.sleep(2); DoctAuthWebElements.auth_prof_confirm.click(); //提交认证 DoctAuthWebElements.auth_sub_btn.click(); logger.info("医师认证流程已完成!等待审核..."); Reporter.log("医师认证流程已完成!等待审核..."); } /** * 如果是从注册后直接到医师认证完成的微信关注页的跳过 */ public static void weixinMid(){ logger.info("开始跳转并加载微信关注公众号中间页面元素,此为专属从注册后直接到医师认证完成的微信关注页的跳过"); Reporter.log("开始跳转并加载微信关注公众号中间页面元素,此为专属从注册后直接到医师认证完成的微信关注页的跳过"); Utils.sleep(5); //logger.info("weixinMid医师认证姓名检查:"+authName); //通过判断 Assertion.assertEquals(true, WeiXinMiddleWebElements.assertGoToWeiXinMiddlePage(authName), "未跳转到微信关注公众号中间页,是否加载失败或认证流程未正常结束,请检查!"); logger.info("微信关注公众号中间页跳转成功!点击跳过,进入登录后的主页"); Reporter.log("微信关注公众号中间页跳转成功!点击跳过,进入登录后的主页"); Assertion.assertEquals(true, WeiXinMiddleWebElements.skipWXBtnIsExist(), "跳过按钮未找到,是否加载失败,请检查!"); WeiXinMiddleWebElements.skip_weixin_scan.click(); logger.info("点击跳过,进入登录后的主页"); Reporter.log("点击跳过,进入登录后的主页"); } /** * 如果是注册后跳过认证,但在操作文库、病例、话题等终端的详情页造成的权限提示后,从该入口进入的医师认证后跳转的微信关注页的跳过按钮,路径值竟然与从注册后直接到医师认证完成的微信关注页的跳过路径值不同,坑啊!!!切记! */ public static void weixinMidAccess(){ logger.info("开始跳转并加载微信关注公众号中间页面元素,此为专属注册后跳过认证,但在操作文库、病例、话题等终端的详情页造成的权限提示后,从该入口进入的医师认证后跳转的微信关注页的跳过按钮"); Reporter.log("开始跳转并加载微信关注公众号中间页面元素,此为专属注册后跳过认证,但在操作文库、病例、话题等终端的详情页造成的权限提示后,从该入口进入的医师认证后跳转的微信关注页的跳过按钮"); Utils.sleep(5); //logger.info("weixinMid医师认证姓名检查:"+authName); //通过判断 Assertion.assertEquals(true, WeiXinMiddleWebElements.assertGoToWeiXinMiddlePage(authName), "未跳转到微信关注公众号中间页,是否加载失败或认证流程未正常结束,请检查!"); logger.info("微信关注公众号中间页跳转成功!点击跳过,进入登录后的主页"); Reporter.log("微信关注公众号中间页跳转成功!点击跳过,进入登录后的主页"); Assertion.assertEquals(true, WeiXinMiddleWebElements.skipWXAccessBtnIsExist(), "跳过按钮未找到,是否加载失败,请检查!"); WeiXinMiddleWebElements.skip_weixin_scan_access.click(); logger.info("点击跳过,进入登录后的主页"); Reporter.log("点击跳过,进入登录后的主页"); } }
DeosChange/UIATT_WEB
UIATT_WEB/src/com/uiatt/pcWeb/RegWebElements.java
5,853
//判断注册按钮是否存在
line_comment
zh-cn
package com.uiatt.pcWeb; import java.io.File; import org.apache.log4j.Logger; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.testng.Reporter; import org.testng.annotations.Listeners; import com.uiatt.listener.Assertion; import com.uiatt.pcPage.RegPageElements; import com.uiatt.util.BaseTest; import com.uiatt.util.Dom4jXml; import com.uiatt.util.ReadWriteTxtFile; import com.uiatt.util.TakeMsgValidCode; import com.uiatt.util.Utils; /** * 提取2.0 PC 注册页面所有功能按钮元素 * author : Change * * */ @Log4j2 @Listeners({com.uiatt.listener.AssertionListener.class}) public class RegWebElements { // 注册用户名按钮 @FindBy(xpath = RegPageElements.REG_USERNAME) public static WebElement reg_username; // 注册密码 @FindBy(xpath = RegPageElements.REG_PWD) public static WebElement reg_pwd; // 确认密码 @FindBy(xpath = RegPageElements.REG_PWD_CONFIRM) public static WebElement reg_pwd_confirm; // 邮箱注册验证码输入框 @FindBy(xpath = RegPageElements.REG_EMAIL_VALIDCODE) public static WebElement reg_email_validcode; // 手机注册发送验证码按钮 @FindBy(xpath = RegPageElements.SEND_PHONE_VALIDCODE) public static WebElement send_phone_validcode; // 手机注册验证码输入框 @FindBy(xpath = RegPageElements.REG_PHONE_VALIDCODE) public static WebElement reg_phone_validcode; // 注册按钮 @FindBy(xpath = RegPageElements.REG_BTN) public static WebElement reg_btn; // 用户名错误提示信息 @FindBy(xpath = RegPageElements.REG_USERNAME_NOTICE) public static WebElement reg_username_notice; // 密码错误提示信息 @FindBy(xpath = RegPageElements.REG_PWD_NOTICE) public static WebElement reg_pwd_notice; // 再次输入密码错误提示信息 @FindBy(xpath = RegPageElements.REG_PWD_CONFIRM_NOTICE) public static WebElement reg_pwd_confirm_notice; // 邮箱验证码错误提示信息 @FindBy(xpath = RegPageElements.REG_EMAIL_VALIDCODE_NOTICE) public static WebElement reg_email_validcode_notice; // 短信验证码错误提示信息 @FindBy(xpath = RegPageElements.REG_PHONE_VALIDCODE_NOTICE) public static WebElement reg_phone_validcode_notice; public static WebDriver driver; public static String authLastName; public static String authFirstName; public static String authName; //初始化 public RegWebElements(WebDriver driver){ RegWebElements.driver = driver; authLastName=ReadWriteTxtFile.getLastName(); authFirstName=ReadWriteTxtFile.getFirstName(); //下面验证是否成功跳转微信关注公众号中间页时判断要用 authName=authLastName+authFirstName; BaseTest.logConf(); } //判断注册用户名输入框是否存在 public static boolean regUsnBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_USERNAME)); } //判断注册用户名错误提示信息是否存在 public static boolean regUsnNotiBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_USERNAME_NOTICE)); } //判断注册密码错误信息是否存在 public static boolean regPWDNotiBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_PWD_NOTICE)); } //判断注册再次输入密码错误信息是否存在 public static boolean regPWDConfNotiBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_PWD_CONFIRM_NOTICE)); } //判断注册图片验证码错误信息是否存在 public static boolean regEmValCoBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_EMAIL_VALIDCODE_NOTICE)); } //判断注册手机验证码错误提示信息是否存在 public static boolean regPhValCoBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_PHONE_VALIDCODE_NOTICE)); } //判断 <SUF> public static boolean regBtnIsExist() { return Utils.isElementExist(driver, By.xpath(RegPageElements.REG_BTN)); } /** * 注册邮箱账户 */ public static void regEmailFlow(String username, String password,String globalValicode) { LoginWebElements.regist_uiatt_btn.click(); Utils.sleep(5); logger.info("跳转并加载注册页面元素"); Reporter.log("跳转并加载注册页面元素"); //PageFactory.initElements(driver, RegWebElements.class); Utils.sleep(5); Assertion.assertEquals(true, RegWebElements.regUsnBtnIsExist(), "\"注册用户名\"输入框未找到,页面不符或元素改变,请检查!"); //因为此次只是功能流程的自动化脚本,先有行为逻辑才能触发相应校验,所以此处不对校验做全面的覆盖触发,只简单的考虑做一步行为,触发一个校验的判断;若今后有专门针对校验提示的全面覆盖脚本的需求,再说; logger.info("输入注册用户名:"+username); Reporter.log("输入注册用户名:"+username); reg_username.clear(); reg_username.sendKeys(username); reg_username.click(); logger.info("输入注册密码:"+password); Reporter.log("输入注册密码:"+password); reg_pwd.clear(); if(RegWebElements.regUsnNotiBtnIsExist() == true){ logger.error(reg_username_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_username_notice"); Assert.fail(reg_username_notice.getText()); } reg_pwd.sendKeys(password); reg_pwd.click(); logger.info("输入确认密码:"+password); Reporter.log("输入确认密码:"+password); reg_pwd_confirm.clear(); //ajax校验,错误提示在鼠标点击下一个输入框时才触发,元素才显示出来 if(RegWebElements.regPWDNotiBtnIsExist() == true){ logger.error(reg_pwd_notice.getText()); Reporter.log("[ERROR]"+reg_pwd_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_pwd_notice"); Assert.fail(reg_pwd_notice.getText()); } reg_pwd_confirm.sendKeys(password); reg_pwd_confirm.click(); logger.info("输入图片的万能验证码:"+globalValicode); Reporter.log("输入图片的万能验证码:"+globalValicode); //邮箱注册为图片验证码,此处以万能验证码处理,所以图片验证码的错误提示信息校验此处略过; reg_email_validcode.clear(); if(RegWebElements.regPWDConfNotiBtnIsExist() == true){ logger.error(reg_pwd_confirm_notice.getText()); Reporter.log("[ERROR]"+reg_pwd_confirm_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_pwd_confirm_notice"); Assert.fail(reg_pwd_confirm_notice.getText()); } reg_email_validcode.sendKeys(globalValicode); reg_email_validcode.click(); Assertion.assertEquals(true, RegWebElements.regBtnIsExist(), "\"注册\"按钮未找到,页面不符或元素改变,请检查!"); reg_btn.click(); //这个判断也许有点多余,只有在直接点击注册按钮,全部触发校验的时候才会生效 if(RegWebElements.regEmValCoBtnIsExist() == true && RegWebElements.regUsnNotiBtnIsExist() == true && RegWebElements.regPWDNotiBtnIsExist() == true && RegWebElements.regPWDConfNotiBtnIsExist() == true){ logger.error(reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_email_validcode_notice.getText()); Reporter.log("[ERROR]"+reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_email_validcode_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow"); Assert.fail(reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_email_validcode_notice.getText()); } Utils.sleep(2); } /** * 注册手机账户 */ public static void regPhoneFlow(String username, String password) { LoginWebElements.regist_uiatt_btn.click(); Utils.sleep(5); logger.info("跳转并加载注册页面元素"); Reporter.log("跳转并加载注册页面元素"); Utils.sleep(5); Assertion.assertEquals(true, RegWebElements.regUsnBtnIsExist(), "\"注册用户名\"输入框未找到,页面不符或元素改变,请检查!"); //因为此次只是功能流程的自动化脚本,先有行为逻辑才能触发相应校验,所以此处不对校验做全面的覆盖触发,只简单的考虑做一步行为,触发一个校验的判断;若今后有专门针对校验提示的全面覆盖脚本的需求,再说; logger.info("输入注册用户名:"+username); Reporter.log("输入注册用户名:"+username); reg_username.clear(); reg_username.sendKeys(username); reg_username.click(); logger.info("输入注册密码:"+password); Reporter.log("输入注册密码:"+password); reg_pwd.clear(); if(RegWebElements.regUsnNotiBtnIsExist() == true){ logger.error(reg_username_notice.getText()); Reporter.log("[ERROR]"+reg_username_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_username_notice"); Assert.fail(reg_username_notice.getText()); } reg_pwd.sendKeys(password); reg_pwd.click(); logger.info("输入确认密码:"+password); Reporter.log("输入确认密码:"+password); reg_pwd_confirm.clear(); //ajax校验,错误提示在鼠标点击下一个输入框时才触发,元素才显示出来 if(RegWebElements.regPWDNotiBtnIsExist() == true){ logger.error(reg_pwd_notice.getText()); Reporter.log("[ERROR]"+reg_pwd_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_pwd_notice"); Assert.fail(reg_pwd_notice.getText()); } reg_pwd_confirm.sendKeys(password); reg_pwd_confirm.click(); //点击发送短信验证码按钮 send_phone_validcode.click(); logger.info("已点击发送短信验证码按钮,等待响应返回值"); Reporter.log("已点击发送短信验证码按钮,等待响应返回值"); String mobileCheckCode = TakeMsgValidCode.takeMsgValidCode(username); logger.info("成功获取短信验证码:"+mobileCheckCode); Reporter.log("成功获取短信验证码:"+mobileCheckCode); reg_phone_validcode.clear(); if(RegWebElements.regPWDConfNotiBtnIsExist() == true){ logger.error(reg_pwd_confirm_notice.getText()); Reporter.log("[ERROR]"+reg_pwd_confirm_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_pwd_confirm_notice"); Assert.fail(reg_pwd_confirm_notice.getText()); } reg_phone_validcode.sendKeys(mobileCheckCode); reg_phone_validcode.click(); Assertion.assertEquals(true, RegWebElements.regBtnIsExist(), "\"注册\"按钮未找到,页面不符或元素改变,请检查!"); reg_btn.click(); if(RegWebElements.regPhValCoBtnIsExist() == true){ logger.error(reg_phone_validcode_notice.getText()); Reporter.log("[ERROR]"+reg_phone_validcode_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regEmailFlow.reg_phone_validcode_notice"); Assert.fail(reg_phone_validcode_notice.getText()); } //这个判断也许有点多余,只有在直接点击注册按钮,全部触发校验的时候才会生效 if(RegWebElements.regPhValCoBtnIsExist() == true && RegWebElements.regUsnNotiBtnIsExist() == true && RegWebElements.regPWDNotiBtnIsExist() == true && RegWebElements.regPWDConfNotiBtnIsExist() == true){ logger.error(reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_phone_validcode_notice.getText()); Reporter.log("[ERROR]"+reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_phone_validcode_notice.getText()); //ScreenShotPC.screenShot("RegWebElements.regPhoneFlow"); Assert.fail(reg_username_notice.getText()+"\n"+reg_pwd_notice.getText()+"\n"+reg_pwd_confirm_notice.getText()+"\n"+reg_phone_validcode_notice.getText()); } Utils.sleep(2); } /** * 跳过认证 */ public static void skipAuth() { Utils.sleep(2); logger.info("开始跳转并加载医师认证页面元素"); Reporter.log("开始跳转并加载医师认证页面元素"); Utils.sleep(5); Assertion.assertEquals(true, DoctAuthWebElements.authSkipBtnIsExist(), "\"暂不认证\"按钮未找到,页面不符或元素改变,请检查!"); logger.info("暂不认证按钮元素确认存在并找到"); Reporter.log("暂不认证按钮元素确认存在并找到"); //点击暂不认证,跳转登录后的主页 DoctAuthWebElements.auth_skip_btn.click(); logger.info("点击暂不认证,跳转登录后的主页"); Reporter.log("点击暂不认证,跳转登录后的主页"); Utils.sleep(5); //通过判断“立即认证”按钮是否存在来验证是否跳转成功 Assertion.assertEquals(true, IndexWebElements.authNowBtnIsExist(), "\"立即认证\"按钮未找到,页面不符或元素改变,请检查!"); logger.info("立即认证按钮元素确认存在并找到,暂不认证注册用户登录成功"); Reporter.log("立即认证按钮元素确认存在并找到,暂不认证注册用户登录成功"); } /** * 完成认证,此处只对上传照片处做异常捕获与处理 */ public static void doneAuth() { logger.info("开始跳转并加载医师认证页面元素"); Reporter.log("开始跳转并加载医师认证页面元素"); Utils.sleep(3); Assertion.assertEquals(true, DoctAuthWebElements.lastNameBtnIsExist(), "\"姓\"输入框未找到,页面不符或元素改变,请检查!"); logger.info("开始进行认证信息的填写."); Reporter.log("开始进行认证信息的填写."); //姓 DoctAuthWebElements.auth_lastname.clear(); DoctAuthWebElements.auth_lastname.sendKeys(authLastName); DoctAuthWebElements.auth_lastname.click(); //名 DoctAuthWebElements.auth_firstname.clear(); DoctAuthWebElements.auth_firstname.sendKeys(authFirstName); DoctAuthWebElements.auth_firstname.click(); logger.info("doneAuth医师认证姓名检查:"+authName); Reporter.log("doneAuth医师认证姓名检查:"+authName); //勾选 医师学历证 DoctAuthWebElements.auth_educ_papers.click(); //证件号码 DoctAuthWebElements.auth_papers_number.clear(); DoctAuthWebElements.auth_papers_number.sendKeys(Dom4jXml.getValue("AUTH_PAPER_NUMBER")); DoctAuthWebElements.auth_papers_number.click(); Assertion.assertEquals(true, DoctAuthWebElements.authPhotoIsExist(), "\"上传照片\"按钮未找到,页面不符或元素未找到,请检查!"); //上传证件照片 String curPath = new File("").getAbsolutePath(); //所得结果为workspace所在路径 String filePath = curPath + Dom4jXml.getValue("AUTH_PHOTO_PATH"); logger.info("找到上传图片的按钮了吗?"+DoctAuthWebElements.authPhotoIsExist()); logger.info("找到上传图片的路径:"+filePath); logger.info("找到上传图片的定位路径:"+DoctAuthWebElements.auth_photo); Reporter.log("找到上传图片的按钮了吗?"+DoctAuthWebElements.authPhotoIsExist()); Reporter.log("找到上传图片的路径:"+filePath); Reporter.log("找到上传图片的定位路径:"+DoctAuthWebElements.auth_photo); DoctAuthWebElements.auth_photo.sendKeys(filePath); //医院 DoctAuthWebElements.auth_hospital.clear(); DoctAuthWebElements.auth_hospital.sendKeys(Dom4jXml.getValue("AUTH_HOSPITAL")); DoctAuthWebElements.auth_hospital.click(); //选择职称,先选择一个再取消一个 DoctAuthWebElements.auth_job.click(); DoctAuthWebElements.auth_resident_doct.click(); Utils.sleep(2); DoctAuthWebElements.selected_auth_resident_doct.click(); Utils.sleep(2); DoctAuthWebElements.auth_attend_doct.click(); DoctAuthWebElements.auth_lecturer.click(); DoctAuthWebElements.auth_master_tutor.click(); Utils.sleep(2); DoctAuthWebElements.auth_job_confirm.click(); //选择专业,先选择一个再取消一个 DoctAuthWebElements.auth_professional.click(); //此处只对上传照片处做异常捕获与处理 if(DoctAuthWebElements.authPhoNotiIsExist() == true){ logger.error(DoctAuthWebElements.auth_photo_noti.getText()); Reporter.log("[ERROR]"+DoctAuthWebElements.auth_photo_noti.getText()); //ScreenShotPC.screenShot("RegWebElements.doneAuth"); Assert.fail(DoctAuthWebElements.auth_photo_noti.getText()); } DoctAuthWebElements.auth_joint.click(); Utils.sleep(2); DoctAuthWebElements.selected_auth_join.click(); Utils.sleep(2); DoctAuthWebElements.auth_spine.click(); Utils.sleep(2); DoctAuthWebElements.auth_prof_confirm.click(); //提交认证 DoctAuthWebElements.auth_sub_btn.click(); logger.info("医师认证流程已完成!等待审核..."); Reporter.log("医师认证流程已完成!等待审核..."); } /** * 如果是从注册后直接到医师认证完成的微信关注页的跳过 */ public static void weixinMid(){ logger.info("开始跳转并加载微信关注公众号中间页面元素,此为专属从注册后直接到医师认证完成的微信关注页的跳过"); Reporter.log("开始跳转并加载微信关注公众号中间页面元素,此为专属从注册后直接到医师认证完成的微信关注页的跳过"); Utils.sleep(5); //logger.info("weixinMid医师认证姓名检查:"+authName); //通过判断 Assertion.assertEquals(true, WeiXinMiddleWebElements.assertGoToWeiXinMiddlePage(authName), "未跳转到微信关注公众号中间页,是否加载失败或认证流程未正常结束,请检查!"); logger.info("微信关注公众号中间页跳转成功!点击跳过,进入登录后的主页"); Reporter.log("微信关注公众号中间页跳转成功!点击跳过,进入登录后的主页"); Assertion.assertEquals(true, WeiXinMiddleWebElements.skipWXBtnIsExist(), "跳过按钮未找到,是否加载失败,请检查!"); WeiXinMiddleWebElements.skip_weixin_scan.click(); logger.info("点击跳过,进入登录后的主页"); Reporter.log("点击跳过,进入登录后的主页"); } /** * 如果是注册后跳过认证,但在操作文库、病例、话题等终端的详情页造成的权限提示后,从该入口进入的医师认证后跳转的微信关注页的跳过按钮,路径值竟然与从注册后直接到医师认证完成的微信关注页的跳过路径值不同,坑啊!!!切记! */ public static void weixinMidAccess(){ logger.info("开始跳转并加载微信关注公众号中间页面元素,此为专属注册后跳过认证,但在操作文库、病例、话题等终端的详情页造成的权限提示后,从该入口进入的医师认证后跳转的微信关注页的跳过按钮"); Reporter.log("开始跳转并加载微信关注公众号中间页面元素,此为专属注册后跳过认证,但在操作文库、病例、话题等终端的详情页造成的权限提示后,从该入口进入的医师认证后跳转的微信关注页的跳过按钮"); Utils.sleep(5); //logger.info("weixinMid医师认证姓名检查:"+authName); //通过判断 Assertion.assertEquals(true, WeiXinMiddleWebElements.assertGoToWeiXinMiddlePage(authName), "未跳转到微信关注公众号中间页,是否加载失败或认证流程未正常结束,请检查!"); logger.info("微信关注公众号中间页跳转成功!点击跳过,进入登录后的主页"); Reporter.log("微信关注公众号中间页跳转成功!点击跳过,进入登录后的主页"); Assertion.assertEquals(true, WeiXinMiddleWebElements.skipWXAccessBtnIsExist(), "跳过按钮未找到,是否加载失败,请检查!"); WeiXinMiddleWebElements.skip_weixin_scan_access.click(); logger.info("点击跳过,进入登录后的主页"); Reporter.log("点击跳过,进入登录后的主页"); } }
1
13
1
20968_3
package com.hansn; import com.hansn.entity.Resume; public class PrototypeTest { public static void main(String[] args) { //原型A对象 Resume a = new Resume("闫猪头"); a.setPersonInfo("2.16", "男", "家里蹲大学"); a.setWorkExperience("2018.09.05", "搬砖工地"); //克隆B对象 Resume b = (Resume) a.clone(); //输出A和B对象 System.out.println("----------------A--------------"); a.display(); System.out.println("----------------B--------------"); b.display(); /* * 测试A==B? * 对任何的对象x,都有x.clone() !=x,即克隆对象与原对象不是同一个对象 */ System.out.println("A==B?"); System.out.println( a == b); /* * 对任何的对象x,都有x.clone().getClass()==x.getClass(),即克隆对象与原对象的类型一样。 */ System.out.println("A.getClass()==B.getClass()?"); System.out.println(a.getClass() == b.getClass()); } }
DespairYoke/java-advance
design-pattern/prototype/src/main/java/com/hansn/PrototypeTest.java
301
/* * 测试A==B? * 对任何的对象x,都有x.clone() !=x,即克隆对象与原对象不是同一个对象 */
block_comment
zh-cn
package com.hansn; import com.hansn.entity.Resume; public class PrototypeTest { public static void main(String[] args) { //原型A对象 Resume a = new Resume("闫猪头"); a.setPersonInfo("2.16", "男", "家里蹲大学"); a.setWorkExperience("2018.09.05", "搬砖工地"); //克隆B对象 Resume b = (Resume) a.clone(); //输出A和B对象 System.out.println("----------------A--------------"); a.display(); System.out.println("----------------B--------------"); b.display(); /* * 测试A <SUF>*/ System.out.println("A==B?"); System.out.println( a == b); /* * 对任何的对象x,都有x.clone().getClass()==x.getClass(),即克隆对象与原对象的类型一样。 */ System.out.println("A.getClass()==B.getClass()?"); System.out.println(a.getClass() == b.getClass()); } }
0
85
0
51482_14
/* * www.msxf.com Inc. * Copyright (c) 2017 All Rights Reserved */ package com.falcon.suitagent.util; // ,%%%%%%%%, // ,%%/\%%%%/\%% // ,%%%\c "" J/%%% // %. %%%%/ o o \%%% // `%%. %%%% _ |%%% // `%% `%%%%(__Y__)%%' // // ;%%%%`\-/%%%' // (( / `%%%%%%%' // \\ .' | // \\ / \ | | // \\/攻城狮保佑) | | // \ /_ | |__ // (___________))))))) `\/' /* * 修订记录: * [email protected] 2017-08-04 14:08 创建 */ /** * @author [email protected] */ public class HexUtil { private static boolean isCnSymbol(char ch) { if (0x3004 <= ch && ch <= 0x301C) return true; if (0x3020 <= ch && ch <= 0x303F) return true; return false; } private static boolean isEnSymbol(char ch){ if (ch == 0x40) return true; if (ch == 0x2D || ch == 0x2F) return true; if (0x23 <= ch && ch <= 0x26) return true; if (0x28 <= ch && ch <= 0x2B) return true; if (0x3C <= ch && ch <= 0x3E) return true; if (0x5B <= ch && ch <= 0x60) return true; if (0x7B <= ch && ch <= 0x7E) return true; return false; } private static boolean isPunctuation(char ch){ if(isCjkPunc(ch)) return true; if(isEnPunc(ch)) return true; if(0x2018 <= ch && ch <= 0x201F) return true; if(ch == 0xFF01 || ch == 0xFF02) return true; if(ch == 0xFF07 || ch == 0xFF0C) return true; if(ch == 0xFF1A || ch == 0xFF1B) return true; if(ch == 0xFF1F || ch == 0xFF61) return true; if(ch == 0xFF0E) return true; if(ch == 0xFF65) return true; return false; } private static boolean isEnPunc(char ch){ if (0x21 <= ch && ch <= 0x22) return true; if (ch == 0x27 || ch == 0x2C) return true; if (ch == 0x2E || ch == 0x3A) return true; if (ch == 0x3B || ch == 0x3F) return true; return false; } private static boolean isCjkPunc(char ch){ if (0x3001 <= ch && ch <= 0x3003) return true; if (0x301D <= ch && ch <= 0x301F) return true; return false; } private static boolean isSymbol(char ch) { if(isCnSymbol(ch)) return true; if(isEnSymbol(ch))return true; if(0x2010 <= ch && ch <= 0x2017) return true; if(0x2020 <= ch && ch <= 0x2027) return true; if(0x2B00 <= ch && ch <= 0x2BFF) return true; if(0xFF03 <= ch && ch <= 0xFF06) return true; if(0xFF08 <= ch && ch <= 0xFF0B) return true; if(ch == 0xFF0D || ch == 0xFF0F) return true; if(0xFF1C <= ch && ch <= 0xFF1E) return true; if(ch == 0xFF20 || ch == 0xFF65) return true; if(0xFF3B <= ch && ch <= 0xFF40) return true; if(0xFF5B <= ch && ch <= 0xFF60) return true; if(ch == 0xFF62 || ch == 0xFF63) return true; if(ch == 0x0020 || ch == 0x3000) return true; return false; } /** * 过滤字符串,返回可见字符形式(数字、字母、符号等) * @param str * @return */ public static String filter(String str){ StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") || isSymbol(c) || isPunctuation(c)){ sb.append(c); } } return sb.toString(); } /** * 过滤字符串,将不可见字符串替换为指定的字符串 * @param str * @param replace * @return */ public static String filter(String str,String replace){ StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") || isSymbol(c) || isPunctuation(c)){ sb.append(c); }else { sb.append(replace); } } return sb.toString(); } }
DevopsJK/SuitAgent
src/main/java/com/falcon/suitagent/util/HexUtil.java
1,432
/* * 修订记录: * [email protected] 2017-08-04 14:08 创建 */
block_comment
zh-cn
/* * www.msxf.com Inc. * Copyright (c) 2017 All Rights Reserved */ package com.falcon.suitagent.util; // ,%%%%%%%%, // ,%%/\%%%%/\%% // ,%%%\c "" J/%%% // %. %%%%/ o o \%%% // `%%. %%%% _ |%%% // `%% `%%%%(__Y__)%%' // // ;%%%%`\-/%%%' // (( / `%%%%%%%' // \\ .' | // \\ / \ | | // \\/攻城狮保佑) | | // \ /_ | |__ // (___________))))))) `\/' /* * 修订记 <SUF>*/ /** * @author [email protected] */ public class HexUtil { private static boolean isCnSymbol(char ch) { if (0x3004 <= ch && ch <= 0x301C) return true; if (0x3020 <= ch && ch <= 0x303F) return true; return false; } private static boolean isEnSymbol(char ch){ if (ch == 0x40) return true; if (ch == 0x2D || ch == 0x2F) return true; if (0x23 <= ch && ch <= 0x26) return true; if (0x28 <= ch && ch <= 0x2B) return true; if (0x3C <= ch && ch <= 0x3E) return true; if (0x5B <= ch && ch <= 0x60) return true; if (0x7B <= ch && ch <= 0x7E) return true; return false; } private static boolean isPunctuation(char ch){ if(isCjkPunc(ch)) return true; if(isEnPunc(ch)) return true; if(0x2018 <= ch && ch <= 0x201F) return true; if(ch == 0xFF01 || ch == 0xFF02) return true; if(ch == 0xFF07 || ch == 0xFF0C) return true; if(ch == 0xFF1A || ch == 0xFF1B) return true; if(ch == 0xFF1F || ch == 0xFF61) return true; if(ch == 0xFF0E) return true; if(ch == 0xFF65) return true; return false; } private static boolean isEnPunc(char ch){ if (0x21 <= ch && ch <= 0x22) return true; if (ch == 0x27 || ch == 0x2C) return true; if (ch == 0x2E || ch == 0x3A) return true; if (ch == 0x3B || ch == 0x3F) return true; return false; } private static boolean isCjkPunc(char ch){ if (0x3001 <= ch && ch <= 0x3003) return true; if (0x301D <= ch && ch <= 0x301F) return true; return false; } private static boolean isSymbol(char ch) { if(isCnSymbol(ch)) return true; if(isEnSymbol(ch))return true; if(0x2010 <= ch && ch <= 0x2017) return true; if(0x2020 <= ch && ch <= 0x2027) return true; if(0x2B00 <= ch && ch <= 0x2BFF) return true; if(0xFF03 <= ch && ch <= 0xFF06) return true; if(0xFF08 <= ch && ch <= 0xFF0B) return true; if(ch == 0xFF0D || ch == 0xFF0F) return true; if(0xFF1C <= ch && ch <= 0xFF1E) return true; if(ch == 0xFF20 || ch == 0xFF65) return true; if(0xFF3B <= ch && ch <= 0xFF40) return true; if(0xFF5B <= ch && ch <= 0xFF60) return true; if(ch == 0xFF62 || ch == 0xFF63) return true; if(ch == 0x0020 || ch == 0x3000) return true; return false; } /** * 过滤字符串,返回可见字符形式(数字、字母、符号等) * @param str * @return */ public static String filter(String str){ StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") || isSymbol(c) || isPunctuation(c)){ sb.append(c); } } return sb.toString(); } /** * 过滤字符串,将不可见字符串替换为指定的字符串 * @param str * @param replace * @return */ public static String filter(String str,String replace){ StringBuilder sb = new StringBuilder(); for (char c : str.toCharArray()) { if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") || isSymbol(c) || isPunctuation(c)){ sb.append(c); }else { sb.append(replace); } } return sb.toString(); } }
1
57
1
13819_1
/** * @author liuhuanhuan * @version 1.0 * @date 2022/2/21 22:33 * @describe Twitter推出的分布式唯一id算法 */ public class UUIDUtil { //因为二进制里第一个 bit 为如果是 1,那么都是负数,但是我们生成的 id 都是正数,所以第一个 bit 统一都是 0。 //机器ID 2进制5位 32位减掉1位 31个 private long workerId; //机房ID 2进制5位 32位减掉1位 31个 private long datacenterId; //代表一毫秒内生成的多个id的最新序号 12位 4096 -1 = 4095 个 private long sequence; //设置一个时间初始值 2^41 - 1 差不多可以用69年 private long twepoch = 1585644268888L; //5位的机器id private long workerIdBits = 5L; //5位的机房id;。‘ private long datacenterIdBits = 5L; //每毫秒内产生的id数 2 的 12次方 private long sequenceBits = 12L; // 这个是二进制运算,就是5 bit最多只能有31个数字,也就是说机器id最多只能是32以内 private long maxWorkerId = -1L ^ (-1L << workerIdBits); // 这个是一个意思,就是5 bit最多只能有31个数字,机房id最多只能是32以内 private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); private long workerIdShift = sequenceBits; private long datacenterIdShift = sequenceBits + workerIdBits; private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // -1L 二进制就是1111 1111 为什么? // -1 左移12位就是 1111 1111 0000 0000 0000 0000 // 异或 相同为0 ,不同为1 // 1111 1111 0000 0000 0000 0000 // ^ // 1111 1111 1111 1111 1111 1111 // 0000 0000 1111 1111 1111 1111 换算成10进制就是4095 private long sequenceMask = -1L ^ (-1L << sequenceBits); //记录产生时间毫秒数,判断是否是同1毫秒 private long lastTimestamp = -1L; public long getWorkerId(){ return workerId; } public long getDatacenterId() { return datacenterId; } public long getTimestamp() { return System.currentTimeMillis(); } public UUIDUtil() { } public UUIDUtil(long workerId, long datacenterId, long sequence) { // 检查机房id和机器id是否超过31 不能小于0 if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException( String.format("worker Id can't be greater than %d or less than 0",maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException( String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; this.sequence = sequence; } // 这个是核心方法,通过调用nextId()方法, // 让当前这台机器上的snowflake算法程序生成一个全局唯一的id public synchronized long nextId() { // 这儿就是获取当前时间戳,单位是毫秒 long timestamp = timeGen(); // 判断是否小于上次时间戳,如果小于的话,就抛出异常 if (timestamp < lastTimestamp) { System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp); throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } // 下面是说假设在同一个毫秒内,又发送了一个请求生成一个id // 这个时候就得把seqence序号给递增1,最多就是4096 if (timestamp == lastTimestamp) { // 这个意思是说一个毫秒内最多只能有4096个数字,无论你传递多少进来, //这个位运算保证始终就是在4096这个范围内,避免你自己传递个sequence超过了4096这个范围 sequence = (sequence + 1) & sequenceMask; //当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0; } // 这儿记录一下最近一次生成id的时间戳,单位是毫秒 lastTimestamp = timestamp; // 这儿就是最核心的二进制位运算操作,生成一个64bit的id // 先将当前时间戳左移,放到41 bit那儿;将机房id左移放到5 bit那儿;将机器id左移放到5 bit那儿;将序号放最后12 bit // 最后拼接起来成一个64 bit的二进制数字,转换成10进制就是个long型 return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; } /** * 当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID * @param lastTimestamp * @return */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } //获取当前时间戳 private long timeGen(){ return System.currentTimeMillis(); } /** * main 测试类 * @param args */ public static void main(String[] args) { // System.out.println(1&4596); // System.out.println(2&4596); // System.out.println(6&4596); // System.out.println(6&4596); // System.out.println(6&4596); // System.out.println(6&4596); UUIDUtil snowFlow = new UUIDUtil(1, 1, 1); for (int i = 0; i < 22; i++) { System.out.println(snowFlow.nextId()); // } } } }
Dexter-Huang/mycode
Algorithm/src/main/java/UUIDUtil.java
1,738
//因为二进制里第一个 bit 为如果是 1,那么都是负数,但是我们生成的 id 都是正数,所以第一个 bit 统一都是 0。
line_comment
zh-cn
/** * @author liuhuanhuan * @version 1.0 * @date 2022/2/21 22:33 * @describe Twitter推出的分布式唯一id算法 */ public class UUIDUtil { //因为 <SUF> //机器ID 2进制5位 32位减掉1位 31个 private long workerId; //机房ID 2进制5位 32位减掉1位 31个 private long datacenterId; //代表一毫秒内生成的多个id的最新序号 12位 4096 -1 = 4095 个 private long sequence; //设置一个时间初始值 2^41 - 1 差不多可以用69年 private long twepoch = 1585644268888L; //5位的机器id private long workerIdBits = 5L; //5位的机房id;。‘ private long datacenterIdBits = 5L; //每毫秒内产生的id数 2 的 12次方 private long sequenceBits = 12L; // 这个是二进制运算,就是5 bit最多只能有31个数字,也就是说机器id最多只能是32以内 private long maxWorkerId = -1L ^ (-1L << workerIdBits); // 这个是一个意思,就是5 bit最多只能有31个数字,机房id最多只能是32以内 private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits); private long workerIdShift = sequenceBits; private long datacenterIdShift = sequenceBits + workerIdBits; private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits; // -1L 二进制就是1111 1111 为什么? // -1 左移12位就是 1111 1111 0000 0000 0000 0000 // 异或 相同为0 ,不同为1 // 1111 1111 0000 0000 0000 0000 // ^ // 1111 1111 1111 1111 1111 1111 // 0000 0000 1111 1111 1111 1111 换算成10进制就是4095 private long sequenceMask = -1L ^ (-1L << sequenceBits); //记录产生时间毫秒数,判断是否是同1毫秒 private long lastTimestamp = -1L; public long getWorkerId(){ return workerId; } public long getDatacenterId() { return datacenterId; } public long getTimestamp() { return System.currentTimeMillis(); } public UUIDUtil() { } public UUIDUtil(long workerId, long datacenterId, long sequence) { // 检查机房id和机器id是否超过31 不能小于0 if (workerId > maxWorkerId || workerId < 0) { throw new IllegalArgumentException( String.format("worker Id can't be greater than %d or less than 0",maxWorkerId)); } if (datacenterId > maxDatacenterId || datacenterId < 0) { throw new IllegalArgumentException( String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId)); } this.workerId = workerId; this.datacenterId = datacenterId; this.sequence = sequence; } // 这个是核心方法,通过调用nextId()方法, // 让当前这台机器上的snowflake算法程序生成一个全局唯一的id public synchronized long nextId() { // 这儿就是获取当前时间戳,单位是毫秒 long timestamp = timeGen(); // 判断是否小于上次时间戳,如果小于的话,就抛出异常 if (timestamp < lastTimestamp) { System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp); throw new RuntimeException( String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); } // 下面是说假设在同一个毫秒内,又发送了一个请求生成一个id // 这个时候就得把seqence序号给递增1,最多就是4096 if (timestamp == lastTimestamp) { // 这个意思是说一个毫秒内最多只能有4096个数字,无论你传递多少进来, //这个位运算保证始终就是在4096这个范围内,避免你自己传递个sequence超过了4096这个范围 sequence = (sequence + 1) & sequenceMask; //当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID if (sequence == 0) { timestamp = tilNextMillis(lastTimestamp); } } else { sequence = 0; } // 这儿记录一下最近一次生成id的时间戳,单位是毫秒 lastTimestamp = timestamp; // 这儿就是最核心的二进制位运算操作,生成一个64bit的id // 先将当前时间戳左移,放到41 bit那儿;将机房id左移放到5 bit那儿;将机器id左移放到5 bit那儿;将序号放最后12 bit // 最后拼接起来成一个64 bit的二进制数字,转换成10进制就是个long型 return ((timestamp - twepoch) << timestampLeftShift) | (datacenterId << datacenterIdShift) | (workerId << workerIdShift) | sequence; } /** * 当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID * @param lastTimestamp * @return */ private long tilNextMillis(long lastTimestamp) { long timestamp = timeGen(); while (timestamp <= lastTimestamp) { timestamp = timeGen(); } return timestamp; } //获取当前时间戳 private long timeGen(){ return System.currentTimeMillis(); } /** * main 测试类 * @param args */ public static void main(String[] args) { // System.out.println(1&4596); // System.out.println(2&4596); // System.out.println(6&4596); // System.out.println(6&4596); // System.out.println(6&4596); // System.out.println(6&4596); UUIDUtil snowFlow = new UUIDUtil(1, 1, 1); for (int i = 0; i < 22; i++) { System.out.println(snowFlow.nextId()); // } } } }
1
63
1
34427_19
package util; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.UUID; import android.util.Log; public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * Android上传文件到服务端 * * @param file * 需要上传的文件 * @param RequestURL * 请求的rul * @return 返回响应的内容 */ public static String uploadFile(File file, String RequestURL) { String result = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); Log.e(TAG, "response code:" + res); // if(res==200) // { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); // } // else{ // Log.e(TAG, "request error"); // } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param url * Service net address * @param params * text content * @param files * pictures * @return String result of Service response * @throws IOException */ public static String post(String url, Map<String, String> params, Map<String, File> files) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(url); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(10 * 1000); // 缓存的最长时间 conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许输出 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // 首先组拼文本类型的参数 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream( conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // 发送文件数据 if (files != null) for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); Log.i("http", LINEND); } // 请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到响应码 int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sb2 = new StringBuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sb2.append((char) ch); } } outStream.close(); conn.disconnect(); return sb2.toString(); } }
DickyQie/android-picture-upload
src/util/UploadUtil.java
1,933
// 允许输出
line_comment
zh-cn
package util; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Map; import java.util.UUID; import android.util.Log; public class UploadUtil { private static final String TAG = "uploadFile"; private static final int TIME_OUT = 10 * 1000; // 超时时间 private static final String CHARSET = "utf-8"; // 设置编码 /** * Android上传文件到服务端 * * @param file * 需要上传的文件 * @param RequestURL * 请求的rul * @return 返回响应的内容 */ public static String uploadFile(File file, String RequestURL) { String result = null; String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成 String PREFIX = "--", LINE_END = "\r\n"; String CONTENT_TYPE = "multipart/form-data"; // 内容类型 try { URL url = new URL(RequestURL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(TIME_OUT); conn.setConnectTimeout(TIME_OUT); conn.setDoInput(true); // 允许输入流 conn.setDoOutput(true); // 允许输出流 conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); // 请求方式 conn.setRequestProperty("Charset", CHARSET); // 设置编码 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY); if (file != null) { /** * 当文件不为空,把文件包装并且上传 */ DataOutputStream dos = new DataOutputStream( conn.getOutputStream()); StringBuffer sb = new StringBuffer(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINE_END); /** * 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件 * filename是文件的名字,包含后缀名的 比如:abc.png */ sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getName() + "\"" + LINE_END); sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END); sb.append(LINE_END); dos.write(sb.toString().getBytes()); InputStream is = new FileInputStream(file); byte[] bytes = new byte[1024]; int len = 0; while ((len = is.read(bytes)) != -1) { dos.write(bytes, 0, len); } is.close(); dos.write(LINE_END.getBytes()); byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END) .getBytes(); dos.write(end_data); dos.flush(); /** * 获取响应码 200=成功 当响应成功,获取响应的流 */ int res = conn.getResponseCode(); Log.e(TAG, "response code:" + res); // if(res==200) // { Log.e(TAG, "request success"); InputStream input = conn.getInputStream(); StringBuffer sb1 = new StringBuffer(); int ss; while ((ss = input.read()) != -1) { sb1.append((char) ss); } result = sb1.toString(); Log.e(TAG, "result : " + result); // } // else{ // Log.e(TAG, "request error"); // } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } /** * 通过拼接的方式构造请求内容,实现参数传输以及文件传输 * * @param url * Service net address * @param params * text content * @param files * pictures * @return String result of Service response * @throws IOException */ public static String post(String url, Map<String, String> params, Map<String, File> files) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(url); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(10 * 1000); // 缓存的最长时间 conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许 <SUF> conn.setUseCaches(false); // 不允许使用缓存 conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); // 首先组拼文本类型的参数 StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : params.entrySet()) { sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND); sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND); sb.append("Content-Transfer-Encoding: 8bit" + LINEND); sb.append(LINEND); sb.append(entry.getValue()); sb.append(LINEND); } DataOutputStream outStream = new DataOutputStream( conn.getOutputStream()); outStream.write(sb.toString().getBytes()); // 发送文件数据 if (files != null) for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\"" + file.getValue().getName() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes()); InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); Log.i("http", LINEND); } // 请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到响应码 int res = conn.getResponseCode(); InputStream in = conn.getInputStream(); StringBuilder sb2 = new StringBuilder(); if (res == 200) { int ch; while ((ch = in.read()) != -1) { sb2.append((char) ch); } } outStream.close(); conn.disconnect(); return sb2.toString(); } }
1
7
1
28596_3
package com.zhangqie.videosummary.widget; import android.content.Context; import android.media.MediaPlayer; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; import java.io.IOException; /** * Created by zhangqie on 2019/8/29 * Describe: */ public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener { private SurfaceHolder holder; private MediaPlayer mediaPlayer; public MySurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); }//快进 public void setprogress(int progress) { int currentPosition = mediaPlayer.getCurrentPosition(); mediaPlayer.seekTo(currentPosition + progress); Toast.makeText(getContext(), "快进" + progress, Toast.LENGTH_SHORT).show(); } //暂停/播放方法 public void stopVideo() { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); } else { mediaPlayer.start(); } } //播放视频方法 public void playVideo(String path) { if (mediaPlayer == null) { mediaPlayer = new MediaPlayer();//设置surfaceview不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前 mediaPlayer.setOnCompletionListener(this); } try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.setDisplay(holder); mediaPlayer.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } private void init() { holder = this.getHolder(); //重写SurfaceHolder.Callback方法 holder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; } }//缓冲完成播放 @Override public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.start(); } }
DickyQie/android-video
app/src/main/java/com/zhangqie/videosummary/widget/MySurfaceView.java
537
//设置surfaceview不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前
line_comment
zh-cn
package com.zhangqie.videosummary.widget; import android.content.Context; import android.media.MediaPlayer; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.widget.Toast; import java.io.IOException; /** * Created by zhangqie on 2019/8/29 * Describe: */ public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener { private SurfaceHolder holder; private MediaPlayer mediaPlayer; public MySurfaceView(Context context, AttributeSet attrs) { super(context, attrs); init(); }//快进 public void setprogress(int progress) { int currentPosition = mediaPlayer.getCurrentPosition(); mediaPlayer.seekTo(currentPosition + progress); Toast.makeText(getContext(), "快进" + progress, Toast.LENGTH_SHORT).show(); } //暂停/播放方法 public void stopVideo() { if (mediaPlayer.isPlaying()) { mediaPlayer.pause(); } else { mediaPlayer.start(); } } //播放视频方法 public void playVideo(String path) { if (mediaPlayer == null) { mediaPlayer = new MediaPlayer();//设置 <SUF> mediaPlayer.setOnCompletionListener(this); } try { mediaPlayer.reset(); mediaPlayer.setDataSource(path); mediaPlayer.setDisplay(holder); mediaPlayer.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } private void init() { holder = this.getHolder(); //重写SurfaceHolder.Callback方法 holder.addCallback(this); } @Override public void surfaceCreated(SurfaceHolder surfaceHolder) { } @Override public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) { } @Override public void surfaceDestroyed(SurfaceHolder surfaceHolder) { if (mediaPlayer != null) { mediaPlayer.release(); mediaPlayer = null; } }//缓冲完成播放 @Override public void onCompletion(MediaPlayer mediaPlayer) { mediaPlayer.start(); } }
1
46
1
25988_6
package src; import java.sql.*; import java.util.ArrayList; public class Dao { //查询单个英雄 public Hero select(String name) throws SQLException, ClassNotFoundException { int i=0; String driverName = "com.mysql.jdbc.Driver"; //驱动程 序名 String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url="jdbc:mysql://localhost:3306/"+dbName+ "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Hero hero = null; Class.forName(driverName); Connection conn= DriverManager.getConnection(url,userName,userPwd); String sq1="select * from heros where name1=?"; PreparedStatement ps=conn.prepareStatement(sq1); ps.setString(1,name); ResultSet rs=ps.executeQuery(); while (rs.next()){ String name1=rs.getString("name1"); String name2=rs.getString("name2"); String back_stories=rs.getString("back_stories"); String q=rs.getString("q"); String w=rs.getString("w"); String e=rs.getString("e"); String r=rs.getString("r"); String pic=rs.getString("pic"); String music=rs.getString("music"); hero =new Hero(name1,name2,back_stories,q,w,e,r,pic,music); } try { throw new Exception("未查询到该英雄"); } catch (Exception e) { System.out.println("We got unexpected:" + e.getMessage()); } return hero; } // 查询所有英雄: public ArrayList selectAll() throws SQLException, ClassNotFoundException { ArrayList<Hero> heroes=new ArrayList<Hero>(); int i=0; String driverName = "com.mysql.jdbc.Driver"; //驱动程 序名 String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url="jdbc:mysql://localhost:3306/"+dbName+ "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Hero hero = null; Class.forName(driverName); Connection conn= DriverManager.getConnection(url,userName,userPwd); String sq1="select * from heros"; PreparedStatement ps=conn.prepareStatement(sq1); ResultSet rs=ps.executeQuery(); while (rs.next()){ String name1=rs.getString("name1"); String name2=rs.getString("name2"); String back_stories=rs.getString("back_stories"); String q=rs.getString("q"); String w=rs.getString("w"); String e=rs.getString("e"); String r=rs.getString("r"); String pic=rs.getString("pic"); String music=rs.getString("music"); hero =new Hero(name1,name2,back_stories,q,w,e,r,pic,music); heroes.add(hero); } return heroes; } //英雄插入: public int insert(String name1,String name2,String back_stories,String q,String w ,String e,String r,String pic,String music ) throws SQLException, ClassNotFoundException { int i = 0; String driverName = "com.mysql.jdbc.Driver"; //驱动程 序名 String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url = "jdbc:mysql://localhost:3306/" + dbName + "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Hero hero = null; Class.forName(driverName); Connection conn = DriverManager.getConnection(url, userName, userPwd); String sql="Insert INTO heros(name1,name2,back_stories,q,w,e,r,pic,music)"+"values(?,?,?,?,?,?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1,name1); ps.setString(2,name2); ps.setString(3,back_stories); ps.setString(4,q); ps.setString(5,w); ps.setString(6,e); ps.setString(7,r); ps.setString(8,pic); ps.setString(9,music); return ps.executeUpdate(); } //英雄删除 public int delete(String name) throws SQLException, ClassNotFoundException { int i=0; String driverName = "com.mysql.jdbc.Driver"; //驱动程序名 String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url="jdbc:mysql://localhost:3306/"+dbName+ "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Class.forName(driverName); Connection conn= DriverManager.getConnection(url,"root","12345678"); String sq1="DELETE from heros where name1=?"; PreparedStatement ps=conn.prepareStatement(sq1); ps.setString(1,name); i=ps.executeUpdate(); try { throw new NullPointerException("英雄名字输入不对!"); } catch (Exception e) { System.out.println("We got unexpected:" + e.getMessage()); } return i; } //英雄更新 public int update(String name1,String name2,String back_stories,String q,String w,String e,String r,String pic,String music) throws SQLException, ClassNotFoundException { int i=0; String driverName = "com.mysql.jdbc.Driver"; //驱动程序名 String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url="jdbc:mysql://localhost:3306/"+dbName+ "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Class.forName(driverName); Connection conn= DriverManager.getConnection(url,"root","12345678"); String sq1="update users set name1=?,name2=?,back_stories=?,q=?,w=?,e=?,r=?,pic=?,music=? where name1=?"; PreparedStatement ps=conn.prepareStatement(sq1); ps.setString(1,name1); ps.setString(2,name2); ps.setString(3,back_stories); ps.setString(4,q); ps.setString(5,w); ps.setString(6,e); ps.setString(7,r); ps.setString(8,pic); ps.setString(9,music); i=ps.executeUpdate(); try { throw new NullPointerException("更新信息输入有误"); } catch (Exception ex) { System.out.println("We got unexpected:" + ex.getMessage()); System.out.println("We got unexpected:" + ex.getLocalizedMessage()); } return i; } }
DietCokewithSugar/LOL-Web-Data-Bank
src/Dao.java
1,724
//驱动程 序名
line_comment
zh-cn
package src; import java.sql.*; import java.util.ArrayList; public class Dao { //查询单个英雄 public Hero select(String name) throws SQLException, ClassNotFoundException { int i=0; String driverName = "com.mysql.jdbc.Driver"; //驱动程 序名 String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url="jdbc:mysql://localhost:3306/"+dbName+ "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Hero hero = null; Class.forName(driverName); Connection conn= DriverManager.getConnection(url,userName,userPwd); String sq1="select * from heros where name1=?"; PreparedStatement ps=conn.prepareStatement(sq1); ps.setString(1,name); ResultSet rs=ps.executeQuery(); while (rs.next()){ String name1=rs.getString("name1"); String name2=rs.getString("name2"); String back_stories=rs.getString("back_stories"); String q=rs.getString("q"); String w=rs.getString("w"); String e=rs.getString("e"); String r=rs.getString("r"); String pic=rs.getString("pic"); String music=rs.getString("music"); hero =new Hero(name1,name2,back_stories,q,w,e,r,pic,music); } try { throw new Exception("未查询到该英雄"); } catch (Exception e) { System.out.println("We got unexpected:" + e.getMessage()); } return hero; } // 查询所有英雄: public ArrayList selectAll() throws SQLException, ClassNotFoundException { ArrayList<Hero> heroes=new ArrayList<Hero>(); int i=0; String driverName = "com.mysql.jdbc.Driver"; //驱动 <SUF> String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url="jdbc:mysql://localhost:3306/"+dbName+ "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Hero hero = null; Class.forName(driverName); Connection conn= DriverManager.getConnection(url,userName,userPwd); String sq1="select * from heros"; PreparedStatement ps=conn.prepareStatement(sq1); ResultSet rs=ps.executeQuery(); while (rs.next()){ String name1=rs.getString("name1"); String name2=rs.getString("name2"); String back_stories=rs.getString("back_stories"); String q=rs.getString("q"); String w=rs.getString("w"); String e=rs.getString("e"); String r=rs.getString("r"); String pic=rs.getString("pic"); String music=rs.getString("music"); hero =new Hero(name1,name2,back_stories,q,w,e,r,pic,music); heroes.add(hero); } return heroes; } //英雄插入: public int insert(String name1,String name2,String back_stories,String q,String w ,String e,String r,String pic,String music ) throws SQLException, ClassNotFoundException { int i = 0; String driverName = "com.mysql.jdbc.Driver"; //驱动程 序名 String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url = "jdbc:mysql://localhost:3306/" + dbName + "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Hero hero = null; Class.forName(driverName); Connection conn = DriverManager.getConnection(url, userName, userPwd); String sql="Insert INTO heros(name1,name2,back_stories,q,w,e,r,pic,music)"+"values(?,?,?,?,?,?,?,?,?)"; PreparedStatement ps = conn.prepareStatement(sql); ps.setString(1,name1); ps.setString(2,name2); ps.setString(3,back_stories); ps.setString(4,q); ps.setString(5,w); ps.setString(6,e); ps.setString(7,r); ps.setString(8,pic); ps.setString(9,music); return ps.executeUpdate(); } //英雄删除 public int delete(String name) throws SQLException, ClassNotFoundException { int i=0; String driverName = "com.mysql.jdbc.Driver"; //驱动程序名 String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url="jdbc:mysql://localhost:3306/"+dbName+ "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Class.forName(driverName); Connection conn= DriverManager.getConnection(url,"root","12345678"); String sq1="DELETE from heros where name1=?"; PreparedStatement ps=conn.prepareStatement(sq1); ps.setString(1,name); i=ps.executeUpdate(); try { throw new NullPointerException("英雄名字输入不对!"); } catch (Exception e) { System.out.println("We got unexpected:" + e.getMessage()); } return i; } //英雄更新 public int update(String name1,String name2,String back_stories,String q,String w,String e,String r,String pic,String music) throws SQLException, ClassNotFoundException { int i=0; String driverName = "com.mysql.jdbc.Driver"; //驱动程序名 String userName = "root"; //数据库用户名 String userPwd = "12345678"; //密码 String dbName = "testdb"; //数据库名 String url="jdbc:mysql://localhost:3306/"+dbName+ "?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true"; Class.forName(driverName); Connection conn= DriverManager.getConnection(url,"root","12345678"); String sq1="update users set name1=?,name2=?,back_stories=?,q=?,w=?,e=?,r=?,pic=?,music=? where name1=?"; PreparedStatement ps=conn.prepareStatement(sq1); ps.setString(1,name1); ps.setString(2,name2); ps.setString(3,back_stories); ps.setString(4,q); ps.setString(5,w); ps.setString(6,e); ps.setString(7,r); ps.setString(8,pic); ps.setString(9,music); i=ps.executeUpdate(); try { throw new NullPointerException("更新信息输入有误"); } catch (Exception ex) { System.out.println("We got unexpected:" + ex.getMessage()); System.out.println("We got unexpected:" + ex.getLocalizedMessage()); } return i; } }
0
8
0
30972_0
package MeaT; import JDBC.JDBCUtils; import blockchain.Block; import blockchain.Transaction; import dataset.DataProcessing; import functions.MeaTUtils; import graph.Edge; import graph.Node; import merkletree.Leaf; import merkletree.MerkleTree; import javax.xml.crypto.dsig.TransformService; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class CreateMeaT { public Random ran=new Random(); public ArrayList<Transaction> txs=new ArrayList<>(); public ArrayList<Block> blocks=new ArrayList<>(); public String[] types={"food","electronic","face","furniture"}; public ArrayList<Node> all_nodes=new ArrayList<>(); public void create_nodes(){ int i=0; for (i=0;i<15;i++) { String id=String.valueOf(i); String type=types[ran.nextInt(4)]; Node node=new Node(id,type); all_nodes.add(node); System.out.println(node.getNode_id()); } } public void create_txs_blocks(ArrayList<Node> nodes){ int block_id=1; String[] types={"Electronic","Food","Furniture"}; for (int i=0;i<5;i++) { String blockid=String.valueOf(block_id); Block b=new Block(blockid); for(int j=0;j<20;j++) { String tx_id_string=String.valueOf(j); String tx_id=tx_id_string; String tx_time_cost=String.valueOf(ran.nextDouble()*150); String tx_repu=String.valueOf(ran.nextDouble()*100); int firstNumber = ran.nextInt(15); // 生成0到3之间的随机数 int secondNumber; do { secondNumber = ran.nextInt(15); } while (secondNumber == firstNumber); Node node1=nodes.get(firstNumber); Node node2=nodes.get(secondNumber); String tx_timestamp=String.valueOf(block_id); int type=ran.nextInt(3); Transaction tx=new Transaction(tx_id,tx_timestamp,tx_time_cost,tx_repu,node1,node2,types[type]); tx.setBlock(b); txs.add(tx); System.out.println("TX:"+tx.getType()); b.getTxs().add(tx); } block_id+=1; blocks.add(b); System.out.println("Block:"+b.getId()); System.out.println("Amounts:"+b.getTxs().size()); } } public Block query_block(String id, ArrayList<Block> blocks) { for (Block block:blocks) { if (block.getId().equals(id)) { return block; } } return null; } public boolean exist_block(String id, ArrayList<Block> blocks) { for (Block block:blocks) { if (block.getId().equals(id)) { return true; } } return false; } public Node query_node(String id, ArrayList<Node> nodes) { for (Node node:nodes) { if (node.getNode_id().equals(id)) { return node; } } return null; } public static void main(String[] args) throws NoSuchAlgorithmException, SQLException { String file="./Dataset/100000.csv"; HashMap<Node,ArrayList<Transaction>> node_txs=new HashMap<>(); JDBCUtils jdbcUtils=new JDBCUtils(); DataProcessing dp=new DataProcessing(); CreateMeaT cmt=new CreateMeaT(); //将交易、节点、区块写入数据库并暂存至内存 node_txs=dp.test_dataset_to_txs(file); for(Node node:node_txs.keySet()) { dp.insert_transaction_database(node_txs.get(node)); cmt.all_nodes.add(node); cmt.txs.addAll(node_txs.get(node)); } // //miniminitest的操作,一个区块,将所有交易加到这个区块中 // cmt.blocks.add(cmt.txs.get(0).getBlock()); // for (Transaction tx: cmt.txs){ // cmt.blocks.get(0).getTxs().add(tx); // } //交易、节点存完了,直接读就可以 //将数据库中的交易和节点读出来 ResultSet rs = dp.select_transaction(); ResultSet rs2=dp.select_node(); ResultSet rs3=dp.select_block(); while(rs2.next()) { Node node=new Node(rs2.getString("node_id")); cmt.all_nodes.add(node); } while(rs3.next()) { Block block=new Block(rs3.getString("block_id")); cmt.blocks.add(block); } System.out.println("All blocks: "+cmt.blocks.size()); System.out.println("All nodes: "+cmt.all_nodes.size()); Node start_node=null; Node end_node = new Node(""); // 创建一个空的Node对象,用于重复使用 while (rs.next()) { Transaction tx=null; start_node = cmt.query_node(rs.getString("start_node"), cmt.all_nodes); // 重复使用end_node对象,而不是在每次迭代中创建新对象 end_node.setNode_id(rs.getString("end_node")); Block b=cmt.query_block(rs.getString("block"),cmt.blocks); // 重复使用tx对象,而不是在每次迭代中创建新对象 if (tx == null) { tx = new Transaction("", "", "", "", null, null, ""); } // 更新tx对象的属性 tx.setId(rs.getString("id")); tx.setTimestamp(rs.getString("timestamp")); tx.setTime_cost(rs.getString("time_cost")); tx.setReputation(rs.getString("reputation")); tx.setStart_node(start_node); tx.setEnd_node(end_node); tx.setType(rs.getString("type")); tx.setBlock(b); cmt.txs.add(tx); System.out.println("Pre tx: " + rs.getString("id")); b.getTxs().add(tx); } System.out.println("Total blocks: "+cmt.blocks.size()); //Merkle树的 int leafcount=0; for (Block block: cmt.blocks) { ArrayList<Transaction> transactions=block.getTxs(); ArrayList<Leaf> leaves=new ArrayList<>(); for(Transaction tx: transactions) { Leaf leaf=Leaf.tx_to_leaf(tx); leaf.setId(String.valueOf(leafcount)); leaves.add(leaf); leafcount+=1; } System.out.println("Block "+block.getId()+" has "+leaves.size()+" leaves"); MerkleTree mt=MerkleTree.create_Merkletree(leaves); } //开始创建整体的graphmerkle树架构 System.out.println("------------------------------ Stage 1----------------------------"); System.out.println("------------------------------Lower MGT----------------------------"); //首先,按照起始节点的不同,将交易过滤为edge并分类(在MeaTUtils类中) int gnlItemcount=0; //MerkleGraphTree的 for (Block block: cmt.blocks) { HashMap<Node,ArrayList<Edge>> all_transactions=new HashMap<>(); all_transactions=MeaTUtils.start_node_filter(block.getTxs()); System.out.println("This block has "+block.getTxs().size()+" transactions"); //之后,对不同的节点构建多个下层MGT树 GraphNodeLink gnl=new GraphNodeLink(); int mgtleafcount=0; for(Node node: all_transactions.keySet()) { System.out.println("Pre Node id: "+node.getNode_id()); GraphNodeLinkItem gnlItem=new GraphNodeLinkItem(); ArrayList<Edge> edges=all_transactions.get(node); ArrayList<GraphLeaf> leaves=new ArrayList<>(); for(Edge e: edges){ GraphLeaf graphLeaf=GraphLeaf.edge_to_leaf(e); graphLeaf.setId(String.valueOf(mgtleafcount)); leaves.add(graphLeaf); mgtleafcount+=1; } MerkleGraphTree lower_mgt=MerkleGraphTree.create_Merkletree(leaves); gnlItem.addMGTs(lower_mgt); gnlItem.setPre_node(node); gnlItem.setId(String.valueOf(gnlItemcount)); gnlItemcount+=1; //将gnlItem写入数据库 Connection gnlCoon= jdbcUtils.connect_database(); String gnlSql="insert into graphnodelink (start_node,mgtroot_hashvalue,gnlitem_id) value (?,?,?)"; PreparedStatement ps=gnlCoon.prepareStatement(gnlSql); ps.setString(1,gnlItem.getPre_node().getNode_id()); ps.setString(2,lower_mgt.getHash_value().toString()); ps.setString(3,String.valueOf(gnlItemcount)); ps.executeUpdate(); try { if (null != ps) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (null != gnlCoon) { gnlCoon.close(); } } catch (SQLException e) { e.printStackTrace(); } //GNL中加入item gnl.addLink(lower_mgt); } System.out.println("GNL also has been created. It has "+gnl.getItems().size()+" items now."); System.out.println("------------------------------ Stage 2- -----------------------"); System.out.println("------------------------------Upper MGT--------------------------"); //接着,构建上层的MGT树 MerkleGraphTree upper_mgt=gnl.create_upper_MGT(gnl,block); System.out.println("Now the upper MGT has been created, the root is "+block.getRoot()+", and the hash is "+block.getHashroot()); System.out.println("-------------------------------Stage 3---------------------------"); System.out.println("------------------------------PST Tree---------------------------"); //最后,构建PST树 PropertySemanticTrie pst=new PropertySemanticTrie(); String[] filter={"type","time_cost","reputation"}; pst.create_PST(block.getRoot(),cmt.txs, filter, 3); } } }
Dignity556/MerkleTree0111
src/MeaT/CreateMeaT.java
2,606
// 生成0到3之间的随机数
line_comment
zh-cn
package MeaT; import JDBC.JDBCUtils; import blockchain.Block; import blockchain.Transaction; import dataset.DataProcessing; import functions.MeaTUtils; import graph.Edge; import graph.Node; import merkletree.Leaf; import merkletree.MerkleTree; import javax.xml.crypto.dsig.TransformService; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; public class CreateMeaT { public Random ran=new Random(); public ArrayList<Transaction> txs=new ArrayList<>(); public ArrayList<Block> blocks=new ArrayList<>(); public String[] types={"food","electronic","face","furniture"}; public ArrayList<Node> all_nodes=new ArrayList<>(); public void create_nodes(){ int i=0; for (i=0;i<15;i++) { String id=String.valueOf(i); String type=types[ran.nextInt(4)]; Node node=new Node(id,type); all_nodes.add(node); System.out.println(node.getNode_id()); } } public void create_txs_blocks(ArrayList<Node> nodes){ int block_id=1; String[] types={"Electronic","Food","Furniture"}; for (int i=0;i<5;i++) { String blockid=String.valueOf(block_id); Block b=new Block(blockid); for(int j=0;j<20;j++) { String tx_id_string=String.valueOf(j); String tx_id=tx_id_string; String tx_time_cost=String.valueOf(ran.nextDouble()*150); String tx_repu=String.valueOf(ran.nextDouble()*100); int firstNumber = ran.nextInt(15); // 生成 <SUF> int secondNumber; do { secondNumber = ran.nextInt(15); } while (secondNumber == firstNumber); Node node1=nodes.get(firstNumber); Node node2=nodes.get(secondNumber); String tx_timestamp=String.valueOf(block_id); int type=ran.nextInt(3); Transaction tx=new Transaction(tx_id,tx_timestamp,tx_time_cost,tx_repu,node1,node2,types[type]); tx.setBlock(b); txs.add(tx); System.out.println("TX:"+tx.getType()); b.getTxs().add(tx); } block_id+=1; blocks.add(b); System.out.println("Block:"+b.getId()); System.out.println("Amounts:"+b.getTxs().size()); } } public Block query_block(String id, ArrayList<Block> blocks) { for (Block block:blocks) { if (block.getId().equals(id)) { return block; } } return null; } public boolean exist_block(String id, ArrayList<Block> blocks) { for (Block block:blocks) { if (block.getId().equals(id)) { return true; } } return false; } public Node query_node(String id, ArrayList<Node> nodes) { for (Node node:nodes) { if (node.getNode_id().equals(id)) { return node; } } return null; } public static void main(String[] args) throws NoSuchAlgorithmException, SQLException { String file="./Dataset/100000.csv"; HashMap<Node,ArrayList<Transaction>> node_txs=new HashMap<>(); JDBCUtils jdbcUtils=new JDBCUtils(); DataProcessing dp=new DataProcessing(); CreateMeaT cmt=new CreateMeaT(); //将交易、节点、区块写入数据库并暂存至内存 node_txs=dp.test_dataset_to_txs(file); for(Node node:node_txs.keySet()) { dp.insert_transaction_database(node_txs.get(node)); cmt.all_nodes.add(node); cmt.txs.addAll(node_txs.get(node)); } // //miniminitest的操作,一个区块,将所有交易加到这个区块中 // cmt.blocks.add(cmt.txs.get(0).getBlock()); // for (Transaction tx: cmt.txs){ // cmt.blocks.get(0).getTxs().add(tx); // } //交易、节点存完了,直接读就可以 //将数据库中的交易和节点读出来 ResultSet rs = dp.select_transaction(); ResultSet rs2=dp.select_node(); ResultSet rs3=dp.select_block(); while(rs2.next()) { Node node=new Node(rs2.getString("node_id")); cmt.all_nodes.add(node); } while(rs3.next()) { Block block=new Block(rs3.getString("block_id")); cmt.blocks.add(block); } System.out.println("All blocks: "+cmt.blocks.size()); System.out.println("All nodes: "+cmt.all_nodes.size()); Node start_node=null; Node end_node = new Node(""); // 创建一个空的Node对象,用于重复使用 while (rs.next()) { Transaction tx=null; start_node = cmt.query_node(rs.getString("start_node"), cmt.all_nodes); // 重复使用end_node对象,而不是在每次迭代中创建新对象 end_node.setNode_id(rs.getString("end_node")); Block b=cmt.query_block(rs.getString("block"),cmt.blocks); // 重复使用tx对象,而不是在每次迭代中创建新对象 if (tx == null) { tx = new Transaction("", "", "", "", null, null, ""); } // 更新tx对象的属性 tx.setId(rs.getString("id")); tx.setTimestamp(rs.getString("timestamp")); tx.setTime_cost(rs.getString("time_cost")); tx.setReputation(rs.getString("reputation")); tx.setStart_node(start_node); tx.setEnd_node(end_node); tx.setType(rs.getString("type")); tx.setBlock(b); cmt.txs.add(tx); System.out.println("Pre tx: " + rs.getString("id")); b.getTxs().add(tx); } System.out.println("Total blocks: "+cmt.blocks.size()); //Merkle树的 int leafcount=0; for (Block block: cmt.blocks) { ArrayList<Transaction> transactions=block.getTxs(); ArrayList<Leaf> leaves=new ArrayList<>(); for(Transaction tx: transactions) { Leaf leaf=Leaf.tx_to_leaf(tx); leaf.setId(String.valueOf(leafcount)); leaves.add(leaf); leafcount+=1; } System.out.println("Block "+block.getId()+" has "+leaves.size()+" leaves"); MerkleTree mt=MerkleTree.create_Merkletree(leaves); } //开始创建整体的graphmerkle树架构 System.out.println("------------------------------ Stage 1----------------------------"); System.out.println("------------------------------Lower MGT----------------------------"); //首先,按照起始节点的不同,将交易过滤为edge并分类(在MeaTUtils类中) int gnlItemcount=0; //MerkleGraphTree的 for (Block block: cmt.blocks) { HashMap<Node,ArrayList<Edge>> all_transactions=new HashMap<>(); all_transactions=MeaTUtils.start_node_filter(block.getTxs()); System.out.println("This block has "+block.getTxs().size()+" transactions"); //之后,对不同的节点构建多个下层MGT树 GraphNodeLink gnl=new GraphNodeLink(); int mgtleafcount=0; for(Node node: all_transactions.keySet()) { System.out.println("Pre Node id: "+node.getNode_id()); GraphNodeLinkItem gnlItem=new GraphNodeLinkItem(); ArrayList<Edge> edges=all_transactions.get(node); ArrayList<GraphLeaf> leaves=new ArrayList<>(); for(Edge e: edges){ GraphLeaf graphLeaf=GraphLeaf.edge_to_leaf(e); graphLeaf.setId(String.valueOf(mgtleafcount)); leaves.add(graphLeaf); mgtleafcount+=1; } MerkleGraphTree lower_mgt=MerkleGraphTree.create_Merkletree(leaves); gnlItem.addMGTs(lower_mgt); gnlItem.setPre_node(node); gnlItem.setId(String.valueOf(gnlItemcount)); gnlItemcount+=1; //将gnlItem写入数据库 Connection gnlCoon= jdbcUtils.connect_database(); String gnlSql="insert into graphnodelink (start_node,mgtroot_hashvalue,gnlitem_id) value (?,?,?)"; PreparedStatement ps=gnlCoon.prepareStatement(gnlSql); ps.setString(1,gnlItem.getPre_node().getNode_id()); ps.setString(2,lower_mgt.getHash_value().toString()); ps.setString(3,String.valueOf(gnlItemcount)); ps.executeUpdate(); try { if (null != ps) { ps.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (null != gnlCoon) { gnlCoon.close(); } } catch (SQLException e) { e.printStackTrace(); } //GNL中加入item gnl.addLink(lower_mgt); } System.out.println("GNL also has been created. It has "+gnl.getItems().size()+" items now."); System.out.println("------------------------------ Stage 2- -----------------------"); System.out.println("------------------------------Upper MGT--------------------------"); //接着,构建上层的MGT树 MerkleGraphTree upper_mgt=gnl.create_upper_MGT(gnl,block); System.out.println("Now the upper MGT has been created, the root is "+block.getRoot()+", and the hash is "+block.getHashroot()); System.out.println("-------------------------------Stage 3---------------------------"); System.out.println("------------------------------PST Tree---------------------------"); //最后,构建PST树 PropertySemanticTrie pst=new PropertySemanticTrie(); String[] filter={"type","time_cost","reputation"}; pst.create_PST(block.getRoot(),cmt.txs, filter, 3); } } }
1
14
1
47231_0
package com.uin.leetcode_100.dfs.leetcode_1254; /** * 1254. 统计封闭岛屿的数目 * 二维矩阵 grid由 0(土地)和 1(水)组成。岛是由最大的4个方向连通的 0组成的群,封闭岛是一个完全 * 由1包围(左、上、右、下)的岛。 * <p> * 请返回 封闭岛屿 的数目。 */ public class Main { public int closedIsland(int[][] grid) { int m = grid.length, n = grid[0].length; int count = 0; for (int i = 0; i < m; i++) { dfs(grid, i, 0, m, n); dfs(grid, i, n - 1, m, n); } for (int j = 0; j < n; j++) { dfs(grid, 0, j, m, n); dfs(grid, m - 1, j, m, n); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 0) { dfs(grid, i, j, m, n); count++; } } } return count; } private void dfs(int[][] grid, int i, int j, int m, int n) { if (i < 0 || i >= m || j < 0 || j >= n) return; if (grid[i][j] == 1) return; grid[i][j] = 1; dfs(grid, i + 1, j, m, n); dfs(grid, i - 1, j, m, n); dfs(grid, i, j + 1, m, n); dfs(grid, i, j - 1, m, n); } }
DingChuanV/Uin-LeetCode
src/main/java/com/uin/leetcode_100/dfs/leetcode_1254/Main.java
484
/** * 1254. 统计封闭岛屿的数目 * 二维矩阵 grid由 0(土地)和 1(水)组成。岛是由最大的4个方向连通的 0组成的群,封闭岛是一个完全 * 由1包围(左、上、右、下)的岛。 * <p> * 请返回 封闭岛屿 的数目。 */
block_comment
zh-cn
package com.uin.leetcode_100.dfs.leetcode_1254; /** * 125 <SUF>*/ public class Main { public int closedIsland(int[][] grid) { int m = grid.length, n = grid[0].length; int count = 0; for (int i = 0; i < m; i++) { dfs(grid, i, 0, m, n); dfs(grid, i, n - 1, m, n); } for (int j = 0; j < n; j++) { dfs(grid, 0, j, m, n); dfs(grid, m - 1, j, m, n); } for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (grid[i][j] == 0) { dfs(grid, i, j, m, n); count++; } } } return count; } private void dfs(int[][] grid, int i, int j, int m, int n) { if (i < 0 || i >= m || j < 0 || j >= n) return; if (grid[i][j] == 1) return; grid[i][j] = 1; dfs(grid, i + 1, j, m, n); dfs(grid, i - 1, j, m, n); dfs(grid, i, j + 1, m, n); dfs(grid, i, j - 1, m, n); } }
0
127
0
21688_2
package design20_备忘录模式.sample_2; //相当于Originator, public class Game { private int checkPoint = 1;//游戏第一关 private int lifeValue = 100;//刚开始血量满满 private String weapon = "匕首";//武器 //开始游戏 public void play(){ System.out.println("开始游戏:"+String.format("第%d关",checkPoint)+" fighting!! ︻$▅▆▇◤"); lifeValue -= 10; System.out.println("闯关成功"); checkPoint++; System.out.println("到达"+String.format("第%d关",checkPoint)); } //退出游戏 public void quit(){ System.out.println(". . . . . ."); System.out.println(this.toString()+"\n退出游戏"); } //创建备忘录 public Memoto createMemoto(){ Memoto memoto = new Memoto(); memoto.setCheckPoint(this.checkPoint); memoto.setLifeValue(lifeValue); memoto.setWeapon(weapon); return memoto; } //恢复游戏 public void restore(Memoto memoto){ this.checkPoint = memoto.getCheckPoint(); this.lifeValue = memoto.getLifeValue(); this.weapon = memoto.getWeapon(); System.out.println("恢复后的游戏状态:"+this.toString()); } @Override public String toString() { return "当前游戏关数:"+checkPoint+" 血量:"+lifeValue+" 武器:"+weapon; } }
DingMouRen/DesignPattern
src/design20_备忘录模式/sample_2/Game.java
387
//刚开始血量满满
line_comment
zh-cn
package design20_备忘录模式.sample_2; //相当于Originator, public class Game { private int checkPoint = 1;//游戏第一关 private int lifeValue = 100;//刚开 <SUF> private String weapon = "匕首";//武器 //开始游戏 public void play(){ System.out.println("开始游戏:"+String.format("第%d关",checkPoint)+" fighting!! ︻$▅▆▇◤"); lifeValue -= 10; System.out.println("闯关成功"); checkPoint++; System.out.println("到达"+String.format("第%d关",checkPoint)); } //退出游戏 public void quit(){ System.out.println(". . . . . ."); System.out.println(this.toString()+"\n退出游戏"); } //创建备忘录 public Memoto createMemoto(){ Memoto memoto = new Memoto(); memoto.setCheckPoint(this.checkPoint); memoto.setLifeValue(lifeValue); memoto.setWeapon(weapon); return memoto; } //恢复游戏 public void restore(Memoto memoto){ this.checkPoint = memoto.getCheckPoint(); this.lifeValue = memoto.getLifeValue(); this.weapon = memoto.getWeapon(); System.out.println("恢复后的游戏状态:"+this.toString()); } @Override public String toString() { return "当前游戏关数:"+checkPoint+" 血量:"+lifeValue+" 武器:"+weapon; } }
1
9
1
41455_7
package com.dingmouren.dingdingmap.util; import android.content.Context; import com.amap.api.maps.AMap; import com.amap.api.maps.CameraUpdateFactory; import com.amap.api.maps.model.LatLng; import com.amap.api.maps.model.MarkerOptions; import com.amap.api.maps.model.PolylineOptions; import com.amap.api.services.busline.BusStationItem; import com.amap.api.services.core.LatLonPoint; import com.amap.api.services.route.BusPath; import com.amap.api.services.route.BusStep; import com.amap.api.services.route.Doorway; import com.amap.api.services.route.RailwayStationItem; import com.amap.api.services.route.RouteBusLineItem; import com.amap.api.services.route.RouteBusWalkItem; import com.amap.api.services.route.RouteRailwayItem; import com.amap.api.services.route.TaxiItem; import com.amap.api.services.route.WalkStep; import java.util.ArrayList; import java.util.List; /** * 公交路线图层类。在高德地图API里,如果需要显示公交路线,可以用此类来创建公交路线图层。如不满足需求,也可以自己创建自定义的公交路线图层。 * @since V2.1.0 */ public class BusRouteOverlay extends RouteOverlay { private BusPath busPath; private LatLng latLng; /** * 通过此构造函数创建公交路线图层。 * @param context 当前activity。 * @param amap 地图对象。 * @param path 公交路径规划的一个路段。详见搜索服务模块的路径查询包(com.amap.api.services.route)中的类<strong> <a href="../../../../../../Search/com/amap/api/services/route/BusPath.html" title="com.amap.api.services.route中的类">BusPath</a></strong>。 * @param start 起点坐标。详见搜索服务模块的核心基础包(com.amap.api.services.core)中的类 <strong><a href="../../../../../../Search/com/amap/api/services/core/LatLonPoint.html" title="com.amap.api.services.core中的类">LatLonPoint</a></strong>。 * @param end 终点坐标。详见搜索服务模块的核心基础包(com.amap.api.services.core)中的类 <strong><a href="../../../../../../Search/com/amap/api/services/core/LatLonPoint.html" title="com.amap.api.services.core中的类">LatLonPoint</a></strong>。 * @since V2.1.0 */ public BusRouteOverlay(Context context, AMap amap, BusPath path, LatLonPoint start, LatLonPoint end) { super(context); this.busPath = path; startPoint = AMapUtil.convertToLatLng(start); endPoint = AMapUtil.convertToLatLng(end); mAMap = amap; } /** * 添加公交路线到地图上。 * @since V2.1.0 */ public void addToMap() { /** * 绘制节点和线<br> * 细节情况较多<br> * 两个step之间,用step和step1区分<br> * 1.一个step内可能有步行和公交,然后有可能他们之间连接有断开<br> * 2.step的公交和step1的步行,有可能连接有断开<br> * 3.step和step1之间是公交换乘,且没有步行,需要把step的终点和step1的起点连起来<br> * 4.公交最后一站和终点间有步行,加入步行线路,还会有一些步行marker<br> * 5.公交最后一站和终点间无步行,之间连起来<br> */ try { List<BusStep> busSteps = busPath.getSteps(); for (int i = 0; i < busSteps.size(); i++) { BusStep busStep = busSteps.get(i); if (i < busSteps.size() - 1) { BusStep busStep1 = busSteps.get(i + 1);// 取得当前下一个BusStep对象 // 假如步行和公交之间连接有断开,就把步行最后一个经纬度点和公交第一个经纬度点连接起来,避免断线问题 if (busStep.getWalk() != null && busStep.getBusLine() != null) { checkWalkToBusline(busStep); } // 假如公交和步行之间连接有断开,就把上一公交经纬度点和下一步行第一个经纬度点连接起来,避免断线问题 if (busStep.getBusLine() != null && busStep1.getWalk() != null && busStep1.getWalk().getSteps().size() > 0) { checkBusLineToNextWalk(busStep, busStep1); } // 假如两个公交换乘中间没有步行,就把上一公交经纬度点和下一步公交第一个经纬度点连接起来,避免断线问题 if (busStep.getBusLine() != null && busStep1.getWalk() == null && busStep1.getBusLine() != null) { checkBusEndToNextBusStart(busStep, busStep1); } // 和上面的很类似 if (busStep.getBusLine() != null && busStep1.getWalk() == null && busStep1.getBusLine() != null) { checkBusToNextBusNoWalk(busStep, busStep1); } if (busStep.getBusLine() != null && busStep1.getRailway() != null ) { checkBusLineToNextRailway(busStep, busStep1); } if (busStep1.getWalk() != null && busStep1.getWalk().getSteps().size() > 0 && busStep.getRailway() != null) { checkRailwayToNextWalk(busStep, busStep1); } if ( busStep1.getRailway() != null && busStep.getRailway() != null) { checkRailwayToNextRailway(busStep, busStep1); } if (busStep.getRailway() != null && busStep1.getTaxi() != null ){ checkRailwayToNextTaxi(busStep, busStep1); } } if (busStep.getWalk() != null && busStep.getWalk().getSteps().size() > 0) { addWalkSteps(busStep); } else { if (busStep.getBusLine() == null && busStep.getRailway() == null && busStep.getTaxi() == null) { addWalkPolyline(latLng, endPoint); } } if (busStep.getBusLine() != null) { RouteBusLineItem routeBusLineItem = busStep.getBusLine(); addBusLineSteps(routeBusLineItem); addBusStationMarkers(routeBusLineItem); if (i == busSteps.size() - 1) { addWalkPolyline(AMapUtil.convertToLatLng(getLastBuslinePoint(busStep)), endPoint); } } if (busStep.getRailway() != null) { addRailwayStep(busStep.getRailway()); addRailwayMarkers(busStep.getRailway()); if (i == busSteps.size() - 1) { addWalkPolyline(AMapUtil.convertToLatLng(busStep.getRailway().getArrivalstop().getLocation()), endPoint); } } if (busStep.getTaxi() != null) { addTaxiStep(busStep.getTaxi()); addTaxiMarkers(busStep.getTaxi()); } } addStartAndEndMarker(); } catch (Throwable e) { e.printStackTrace(); } } private void checkRailwayToNextTaxi(BusStep busStep, BusStep busStep1) { LatLonPoint railwayLastPoint = busStep.getRailway().getArrivalstop().getLocation(); LatLonPoint taxiFirstPoint = busStep1.getTaxi().getOrigin(); if (!railwayLastPoint.equals(taxiFirstPoint)) { addWalkPolyLineByLatLonPoints(railwayLastPoint, taxiFirstPoint); } } private void checkRailwayToNextRailway(BusStep busStep, BusStep busStep1) { LatLonPoint railwayLastPoint = busStep.getRailway().getArrivalstop().getLocation(); LatLonPoint railwayFirstPoint = busStep1.getRailway().getDeparturestop().getLocation(); if (!railwayLastPoint.equals(railwayFirstPoint)) { addWalkPolyLineByLatLonPoints(railwayLastPoint, railwayFirstPoint); } } private void checkBusLineToNextRailway(BusStep busStep, BusStep busStep1) { LatLonPoint busLastPoint = getLastBuslinePoint(busStep); LatLonPoint railwayFirstPoint = busStep1.getRailway().getDeparturestop().getLocation(); if (!busLastPoint.equals(railwayFirstPoint)) { addWalkPolyLineByLatLonPoints(busLastPoint, railwayFirstPoint); } } private void checkRailwayToNextWalk(BusStep busStep, BusStep busStep1) { LatLonPoint railwayLastPoint = busStep.getRailway().getArrivalstop().getLocation(); LatLonPoint walkFirstPoint = getFirstWalkPoint(busStep1); if (!railwayLastPoint.equals(walkFirstPoint)) { addWalkPolyLineByLatLonPoints(railwayLastPoint, walkFirstPoint); } } private void addRailwayStep(RouteRailwayItem railway) { List<LatLng> railwaylistpoint = new ArrayList<LatLng>(); List<RailwayStationItem> railwayStationItems = new ArrayList<RailwayStationItem>(); railwayStationItems.add(railway.getDeparturestop()); railwayStationItems.addAll(railway.getViastops()); railwayStationItems.add(railway.getArrivalstop()); for (int i = 0; i < railwayStationItems.size(); i++) { railwaylistpoint.add(AMapUtil.convertToLatLng(railwayStationItems.get(i).getLocation())); } addRailwayPolyline(railwaylistpoint); } private void addTaxiStep(TaxiItem taxi){ addPolyLine(new PolylineOptions().width(getRouteWidth()) .color(getBusColor()) .add(AMapUtil.convertToLatLng(taxi.getOrigin())) .add(AMapUtil.convertToLatLng(taxi.getDestination()))); } /** * @param busStep */ private void addWalkSteps(BusStep busStep) { RouteBusWalkItem routeBusWalkItem = busStep.getWalk(); List<WalkStep> walkSteps = routeBusWalkItem.getSteps(); for (int j = 0; j < walkSteps.size(); j++) { WalkStep walkStep = walkSteps.get(j); if (j == 0) { LatLng latLng = AMapUtil.convertToLatLng(walkStep .getPolyline().get(0)); String road = walkStep.getRoad();// 道路名字 String instruction = getWalkSnippet(walkSteps);// 步行导航信息 addWalkStationMarkers(latLng, road, instruction); } List<LatLng> listWalkPolyline = AMapUtil .convertArrList(walkStep.getPolyline()); this.latLng = listWalkPolyline.get(listWalkPolyline.size() - 1); addWalkPolyline(listWalkPolyline); // 假如步行前一段的终点和下的起点有断开,断画直线连接起来,避免断线问题 if (j < walkSteps.size() - 1) { LatLng lastLatLng = listWalkPolyline.get(listWalkPolyline .size() - 1); LatLng firstlatLatLng = AMapUtil .convertToLatLng(walkSteps.get(j + 1).getPolyline() .get(0)); if (!(lastLatLng.equals(firstlatLatLng))) { addWalkPolyline(lastLatLng, firstlatLatLng); } } } } /** * 添加一系列的bus PolyLine * * @param routeBusLineItem */ private void addBusLineSteps(RouteBusLineItem routeBusLineItem) { addBusLineSteps(routeBusLineItem.getPolyline()); } private void addBusLineSteps(List<LatLonPoint> listPoints) { if (listPoints.size() < 1) { return; } addPolyLine(new PolylineOptions().width(getRouteWidth()) .color(getBusColor()) .addAll(AMapUtil.convertArrList(listPoints))); } /** * @param latLng * marker * @param title * @param snippet */ private void addWalkStationMarkers(LatLng latLng, String title, String snippet) { addStationMarker(new MarkerOptions().position(latLng).title(title) .snippet(snippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getWalkBitmapDescriptor())); } /** * @param routeBusLineItem */ private void addBusStationMarkers(RouteBusLineItem routeBusLineItem) { BusStationItem startBusStation = routeBusLineItem .getDepartureBusStation(); LatLng position = AMapUtil.convertToLatLng(startBusStation .getLatLonPoint()); String title = routeBusLineItem.getBusLineName(); String snippet = getBusSnippet(routeBusLineItem); addStationMarker(new MarkerOptions().position(position).title(title) .snippet(snippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getBusBitmapDescriptor())); } private void addTaxiMarkers(TaxiItem taxiItem) { LatLng position = AMapUtil.convertToLatLng(taxiItem .getOrigin()); String title = taxiItem.getmSname()+"打车"; String snippet = "到终点"; addStationMarker(new MarkerOptions().position(position).title(title) .snippet(snippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getDriveBitmapDescriptor())); } private void addRailwayMarkers(RouteRailwayItem railway) { LatLng Departureposition = AMapUtil.convertToLatLng(railway .getDeparturestop().getLocation()); String Departuretitle = railway.getDeparturestop().getName()+"上车"; String Departuresnippet = railway.getName(); addStationMarker(new MarkerOptions().position(Departureposition).title(Departuretitle) .snippet(Departuresnippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getBusBitmapDescriptor())); LatLng Arrivalposition = AMapUtil.convertToLatLng(railway .getArrivalstop().getLocation()); String Arrivaltitle = railway.getArrivalstop().getName()+"下车"; String Arrivalsnippet = railway.getName(); addStationMarker(new MarkerOptions().position(Arrivalposition).title(Arrivaltitle) .snippet(Arrivalsnippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getBusBitmapDescriptor())); } /** * 如果换乘没有步行 检查bus最后一点和下一个step的bus起点是否一致 * * @param busStep * @param busStep1 */ private void checkBusToNextBusNoWalk(BusStep busStep, BusStep busStep1) { LatLng endbusLatLng = AMapUtil .convertToLatLng(getLastBuslinePoint(busStep)); LatLng startbusLatLng = AMapUtil .convertToLatLng(getFirstBuslinePoint(busStep1)); if (startbusLatLng.latitude - endbusLatLng.latitude > 0.0001 || startbusLatLng.longitude - endbusLatLng.longitude > 0.0001) { drawLineArrow(endbusLatLng, startbusLatLng);// 断线用带箭头的直线连? } } /** * * checkBusToNextBusNoWalk 和这个类似 * * @param busStep * @param busStep1 */ private void checkBusEndToNextBusStart(BusStep busStep, BusStep busStep1) { LatLonPoint busLastPoint = getLastBuslinePoint(busStep); LatLng endbusLatLng = AMapUtil.convertToLatLng(busLastPoint); LatLonPoint busFirstPoint = getFirstBuslinePoint(busStep1); LatLng startbusLatLng = AMapUtil.convertToLatLng(busFirstPoint); if (!endbusLatLng.equals(startbusLatLng)) { drawLineArrow(endbusLatLng, startbusLatLng);// } } /** * 检查bus最后一步和下一各step的步行起点是否一致 * * @param busStep * @param busStep1 */ private void checkBusLineToNextWalk(BusStep busStep, BusStep busStep1) { LatLonPoint busLastPoint = getLastBuslinePoint(busStep); LatLonPoint walkFirstPoint = getFirstWalkPoint(busStep1); if (!busLastPoint.equals(walkFirstPoint)) { addWalkPolyLineByLatLonPoints(busLastPoint, walkFirstPoint); } } /** * 检查 步行最后一点 和 bus的起点 是否一致 * * @param busStep */ private void checkWalkToBusline(BusStep busStep) { LatLonPoint walkLastPoint = getLastWalkPoint(busStep); LatLonPoint buslineFirstPoint = getFirstBuslinePoint(busStep); if (!walkLastPoint.equals(buslineFirstPoint)) { addWalkPolyLineByLatLonPoints(walkLastPoint, buslineFirstPoint); } } /** * @param busStep1 * @return */ private LatLonPoint getFirstWalkPoint(BusStep busStep1) { return busStep1.getWalk().getSteps().get(0).getPolyline().get(0); } /** * */ private void addWalkPolyLineByLatLonPoints(LatLonPoint pointFrom, LatLonPoint pointTo) { LatLng latLngFrom = AMapUtil.convertToLatLng(pointFrom); LatLng latLngTo = AMapUtil.convertToLatLng(pointTo); addWalkPolyline(latLngFrom, latLngTo); } /** * @param latLngFrom * @param latLngTo * @return */ private void addWalkPolyline(LatLng latLngFrom, LatLng latLngTo) { addPolyLine(new PolylineOptions().add(latLngFrom, latLngTo) .width(getRouteWidth()).color(getWalkColor()).setDottedLine(true)); } /** * @param listWalkPolyline */ private void addWalkPolyline(List<LatLng> listWalkPolyline) { addPolyLine(new PolylineOptions().addAll(listWalkPolyline) .color(getWalkColor()).width(getRouteWidth()).setDottedLine(true)); } private void addRailwayPolyline(List<LatLng> listPolyline) { addPolyLine(new PolylineOptions().addAll(listPolyline) .color(getDriveColor()).width(getRouteWidth())); } private String getWalkSnippet(List<WalkStep> walkSteps) { float disNum = 0; for (WalkStep step : walkSteps) { disNum += step.getDistance(); } return "\u6B65\u884C" + disNum + "\u7C73"; } public void drawLineArrow(LatLng latLngFrom, LatLng latLngTo) { addPolyLine(new PolylineOptions().add(latLngFrom, latLngTo).width(3) .color(getBusColor()).width(getRouteWidth()));// 绘制直线 } private String getBusSnippet(RouteBusLineItem routeBusLineItem) { return "(" + routeBusLineItem.getDepartureBusStation().getBusStationName() + "-->" + routeBusLineItem.getArrivalBusStation().getBusStationName() + ") \u7ECF\u8FC7" + (routeBusLineItem.getPassStationNum() + 1) + "\u7AD9"; } /** * @param busStep * @return */ private LatLonPoint getLastWalkPoint(BusStep busStep) { List<WalkStep> walkSteps = busStep.getWalk().getSteps(); WalkStep walkStep = walkSteps.get(walkSteps.size() - 1); List<LatLonPoint> lonPoints = walkStep.getPolyline(); return lonPoints.get(lonPoints.size() - 1); } private LatLonPoint getExitPoint(BusStep busStep) { Doorway doorway = busStep.getExit(); if (doorway == null) { return null; } return doorway.getLatLonPoint(); } private LatLonPoint getLastBuslinePoint(BusStep busStep) { List<LatLonPoint> lonPoints = busStep.getBusLine().getPolyline(); return lonPoints.get(lonPoints.size() - 1); } private LatLonPoint getEntrancePoint(BusStep busStep) { Doorway doorway = busStep.getEntrance(); if (doorway == null) { return null; } return doorway.getLatLonPoint(); } private LatLonPoint getFirstBuslinePoint(BusStep busStep) { return busStep.getBusLine().getPolyline().get(0); } }
DingMouRen/DingDingMap
app/src/main/java/com/dingmouren/dingdingmap/util/BusRouteOverlay.java
5,515
// 假如两个公交换乘中间没有步行,就把上一公交经纬度点和下一步公交第一个经纬度点连接起来,避免断线问题
line_comment
zh-cn
package com.dingmouren.dingdingmap.util; import android.content.Context; import com.amap.api.maps.AMap; import com.amap.api.maps.CameraUpdateFactory; import com.amap.api.maps.model.LatLng; import com.amap.api.maps.model.MarkerOptions; import com.amap.api.maps.model.PolylineOptions; import com.amap.api.services.busline.BusStationItem; import com.amap.api.services.core.LatLonPoint; import com.amap.api.services.route.BusPath; import com.amap.api.services.route.BusStep; import com.amap.api.services.route.Doorway; import com.amap.api.services.route.RailwayStationItem; import com.amap.api.services.route.RouteBusLineItem; import com.amap.api.services.route.RouteBusWalkItem; import com.amap.api.services.route.RouteRailwayItem; import com.amap.api.services.route.TaxiItem; import com.amap.api.services.route.WalkStep; import java.util.ArrayList; import java.util.List; /** * 公交路线图层类。在高德地图API里,如果需要显示公交路线,可以用此类来创建公交路线图层。如不满足需求,也可以自己创建自定义的公交路线图层。 * @since V2.1.0 */ public class BusRouteOverlay extends RouteOverlay { private BusPath busPath; private LatLng latLng; /** * 通过此构造函数创建公交路线图层。 * @param context 当前activity。 * @param amap 地图对象。 * @param path 公交路径规划的一个路段。详见搜索服务模块的路径查询包(com.amap.api.services.route)中的类<strong> <a href="../../../../../../Search/com/amap/api/services/route/BusPath.html" title="com.amap.api.services.route中的类">BusPath</a></strong>。 * @param start 起点坐标。详见搜索服务模块的核心基础包(com.amap.api.services.core)中的类 <strong><a href="../../../../../../Search/com/amap/api/services/core/LatLonPoint.html" title="com.amap.api.services.core中的类">LatLonPoint</a></strong>。 * @param end 终点坐标。详见搜索服务模块的核心基础包(com.amap.api.services.core)中的类 <strong><a href="../../../../../../Search/com/amap/api/services/core/LatLonPoint.html" title="com.amap.api.services.core中的类">LatLonPoint</a></strong>。 * @since V2.1.0 */ public BusRouteOverlay(Context context, AMap amap, BusPath path, LatLonPoint start, LatLonPoint end) { super(context); this.busPath = path; startPoint = AMapUtil.convertToLatLng(start); endPoint = AMapUtil.convertToLatLng(end); mAMap = amap; } /** * 添加公交路线到地图上。 * @since V2.1.0 */ public void addToMap() { /** * 绘制节点和线<br> * 细节情况较多<br> * 两个step之间,用step和step1区分<br> * 1.一个step内可能有步行和公交,然后有可能他们之间连接有断开<br> * 2.step的公交和step1的步行,有可能连接有断开<br> * 3.step和step1之间是公交换乘,且没有步行,需要把step的终点和step1的起点连起来<br> * 4.公交最后一站和终点间有步行,加入步行线路,还会有一些步行marker<br> * 5.公交最后一站和终点间无步行,之间连起来<br> */ try { List<BusStep> busSteps = busPath.getSteps(); for (int i = 0; i < busSteps.size(); i++) { BusStep busStep = busSteps.get(i); if (i < busSteps.size() - 1) { BusStep busStep1 = busSteps.get(i + 1);// 取得当前下一个BusStep对象 // 假如步行和公交之间连接有断开,就把步行最后一个经纬度点和公交第一个经纬度点连接起来,避免断线问题 if (busStep.getWalk() != null && busStep.getBusLine() != null) { checkWalkToBusline(busStep); } // 假如公交和步行之间连接有断开,就把上一公交经纬度点和下一步行第一个经纬度点连接起来,避免断线问题 if (busStep.getBusLine() != null && busStep1.getWalk() != null && busStep1.getWalk().getSteps().size() > 0) { checkBusLineToNextWalk(busStep, busStep1); } // 假如 <SUF> if (busStep.getBusLine() != null && busStep1.getWalk() == null && busStep1.getBusLine() != null) { checkBusEndToNextBusStart(busStep, busStep1); } // 和上面的很类似 if (busStep.getBusLine() != null && busStep1.getWalk() == null && busStep1.getBusLine() != null) { checkBusToNextBusNoWalk(busStep, busStep1); } if (busStep.getBusLine() != null && busStep1.getRailway() != null ) { checkBusLineToNextRailway(busStep, busStep1); } if (busStep1.getWalk() != null && busStep1.getWalk().getSteps().size() > 0 && busStep.getRailway() != null) { checkRailwayToNextWalk(busStep, busStep1); } if ( busStep1.getRailway() != null && busStep.getRailway() != null) { checkRailwayToNextRailway(busStep, busStep1); } if (busStep.getRailway() != null && busStep1.getTaxi() != null ){ checkRailwayToNextTaxi(busStep, busStep1); } } if (busStep.getWalk() != null && busStep.getWalk().getSteps().size() > 0) { addWalkSteps(busStep); } else { if (busStep.getBusLine() == null && busStep.getRailway() == null && busStep.getTaxi() == null) { addWalkPolyline(latLng, endPoint); } } if (busStep.getBusLine() != null) { RouteBusLineItem routeBusLineItem = busStep.getBusLine(); addBusLineSteps(routeBusLineItem); addBusStationMarkers(routeBusLineItem); if (i == busSteps.size() - 1) { addWalkPolyline(AMapUtil.convertToLatLng(getLastBuslinePoint(busStep)), endPoint); } } if (busStep.getRailway() != null) { addRailwayStep(busStep.getRailway()); addRailwayMarkers(busStep.getRailway()); if (i == busSteps.size() - 1) { addWalkPolyline(AMapUtil.convertToLatLng(busStep.getRailway().getArrivalstop().getLocation()), endPoint); } } if (busStep.getTaxi() != null) { addTaxiStep(busStep.getTaxi()); addTaxiMarkers(busStep.getTaxi()); } } addStartAndEndMarker(); } catch (Throwable e) { e.printStackTrace(); } } private void checkRailwayToNextTaxi(BusStep busStep, BusStep busStep1) { LatLonPoint railwayLastPoint = busStep.getRailway().getArrivalstop().getLocation(); LatLonPoint taxiFirstPoint = busStep1.getTaxi().getOrigin(); if (!railwayLastPoint.equals(taxiFirstPoint)) { addWalkPolyLineByLatLonPoints(railwayLastPoint, taxiFirstPoint); } } private void checkRailwayToNextRailway(BusStep busStep, BusStep busStep1) { LatLonPoint railwayLastPoint = busStep.getRailway().getArrivalstop().getLocation(); LatLonPoint railwayFirstPoint = busStep1.getRailway().getDeparturestop().getLocation(); if (!railwayLastPoint.equals(railwayFirstPoint)) { addWalkPolyLineByLatLonPoints(railwayLastPoint, railwayFirstPoint); } } private void checkBusLineToNextRailway(BusStep busStep, BusStep busStep1) { LatLonPoint busLastPoint = getLastBuslinePoint(busStep); LatLonPoint railwayFirstPoint = busStep1.getRailway().getDeparturestop().getLocation(); if (!busLastPoint.equals(railwayFirstPoint)) { addWalkPolyLineByLatLonPoints(busLastPoint, railwayFirstPoint); } } private void checkRailwayToNextWalk(BusStep busStep, BusStep busStep1) { LatLonPoint railwayLastPoint = busStep.getRailway().getArrivalstop().getLocation(); LatLonPoint walkFirstPoint = getFirstWalkPoint(busStep1); if (!railwayLastPoint.equals(walkFirstPoint)) { addWalkPolyLineByLatLonPoints(railwayLastPoint, walkFirstPoint); } } private void addRailwayStep(RouteRailwayItem railway) { List<LatLng> railwaylistpoint = new ArrayList<LatLng>(); List<RailwayStationItem> railwayStationItems = new ArrayList<RailwayStationItem>(); railwayStationItems.add(railway.getDeparturestop()); railwayStationItems.addAll(railway.getViastops()); railwayStationItems.add(railway.getArrivalstop()); for (int i = 0; i < railwayStationItems.size(); i++) { railwaylistpoint.add(AMapUtil.convertToLatLng(railwayStationItems.get(i).getLocation())); } addRailwayPolyline(railwaylistpoint); } private void addTaxiStep(TaxiItem taxi){ addPolyLine(new PolylineOptions().width(getRouteWidth()) .color(getBusColor()) .add(AMapUtil.convertToLatLng(taxi.getOrigin())) .add(AMapUtil.convertToLatLng(taxi.getDestination()))); } /** * @param busStep */ private void addWalkSteps(BusStep busStep) { RouteBusWalkItem routeBusWalkItem = busStep.getWalk(); List<WalkStep> walkSteps = routeBusWalkItem.getSteps(); for (int j = 0; j < walkSteps.size(); j++) { WalkStep walkStep = walkSteps.get(j); if (j == 0) { LatLng latLng = AMapUtil.convertToLatLng(walkStep .getPolyline().get(0)); String road = walkStep.getRoad();// 道路名字 String instruction = getWalkSnippet(walkSteps);// 步行导航信息 addWalkStationMarkers(latLng, road, instruction); } List<LatLng> listWalkPolyline = AMapUtil .convertArrList(walkStep.getPolyline()); this.latLng = listWalkPolyline.get(listWalkPolyline.size() - 1); addWalkPolyline(listWalkPolyline); // 假如步行前一段的终点和下的起点有断开,断画直线连接起来,避免断线问题 if (j < walkSteps.size() - 1) { LatLng lastLatLng = listWalkPolyline.get(listWalkPolyline .size() - 1); LatLng firstlatLatLng = AMapUtil .convertToLatLng(walkSteps.get(j + 1).getPolyline() .get(0)); if (!(lastLatLng.equals(firstlatLatLng))) { addWalkPolyline(lastLatLng, firstlatLatLng); } } } } /** * 添加一系列的bus PolyLine * * @param routeBusLineItem */ private void addBusLineSteps(RouteBusLineItem routeBusLineItem) { addBusLineSteps(routeBusLineItem.getPolyline()); } private void addBusLineSteps(List<LatLonPoint> listPoints) { if (listPoints.size() < 1) { return; } addPolyLine(new PolylineOptions().width(getRouteWidth()) .color(getBusColor()) .addAll(AMapUtil.convertArrList(listPoints))); } /** * @param latLng * marker * @param title * @param snippet */ private void addWalkStationMarkers(LatLng latLng, String title, String snippet) { addStationMarker(new MarkerOptions().position(latLng).title(title) .snippet(snippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getWalkBitmapDescriptor())); } /** * @param routeBusLineItem */ private void addBusStationMarkers(RouteBusLineItem routeBusLineItem) { BusStationItem startBusStation = routeBusLineItem .getDepartureBusStation(); LatLng position = AMapUtil.convertToLatLng(startBusStation .getLatLonPoint()); String title = routeBusLineItem.getBusLineName(); String snippet = getBusSnippet(routeBusLineItem); addStationMarker(new MarkerOptions().position(position).title(title) .snippet(snippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getBusBitmapDescriptor())); } private void addTaxiMarkers(TaxiItem taxiItem) { LatLng position = AMapUtil.convertToLatLng(taxiItem .getOrigin()); String title = taxiItem.getmSname()+"打车"; String snippet = "到终点"; addStationMarker(new MarkerOptions().position(position).title(title) .snippet(snippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getDriveBitmapDescriptor())); } private void addRailwayMarkers(RouteRailwayItem railway) { LatLng Departureposition = AMapUtil.convertToLatLng(railway .getDeparturestop().getLocation()); String Departuretitle = railway.getDeparturestop().getName()+"上车"; String Departuresnippet = railway.getName(); addStationMarker(new MarkerOptions().position(Departureposition).title(Departuretitle) .snippet(Departuresnippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getBusBitmapDescriptor())); LatLng Arrivalposition = AMapUtil.convertToLatLng(railway .getArrivalstop().getLocation()); String Arrivaltitle = railway.getArrivalstop().getName()+"下车"; String Arrivalsnippet = railway.getName(); addStationMarker(new MarkerOptions().position(Arrivalposition).title(Arrivaltitle) .snippet(Arrivalsnippet).anchor(0.5f, 0.5f).visible(nodeIconVisible) .icon(getBusBitmapDescriptor())); } /** * 如果换乘没有步行 检查bus最后一点和下一个step的bus起点是否一致 * * @param busStep * @param busStep1 */ private void checkBusToNextBusNoWalk(BusStep busStep, BusStep busStep1) { LatLng endbusLatLng = AMapUtil .convertToLatLng(getLastBuslinePoint(busStep)); LatLng startbusLatLng = AMapUtil .convertToLatLng(getFirstBuslinePoint(busStep1)); if (startbusLatLng.latitude - endbusLatLng.latitude > 0.0001 || startbusLatLng.longitude - endbusLatLng.longitude > 0.0001) { drawLineArrow(endbusLatLng, startbusLatLng);// 断线用带箭头的直线连? } } /** * * checkBusToNextBusNoWalk 和这个类似 * * @param busStep * @param busStep1 */ private void checkBusEndToNextBusStart(BusStep busStep, BusStep busStep1) { LatLonPoint busLastPoint = getLastBuslinePoint(busStep); LatLng endbusLatLng = AMapUtil.convertToLatLng(busLastPoint); LatLonPoint busFirstPoint = getFirstBuslinePoint(busStep1); LatLng startbusLatLng = AMapUtil.convertToLatLng(busFirstPoint); if (!endbusLatLng.equals(startbusLatLng)) { drawLineArrow(endbusLatLng, startbusLatLng);// } } /** * 检查bus最后一步和下一各step的步行起点是否一致 * * @param busStep * @param busStep1 */ private void checkBusLineToNextWalk(BusStep busStep, BusStep busStep1) { LatLonPoint busLastPoint = getLastBuslinePoint(busStep); LatLonPoint walkFirstPoint = getFirstWalkPoint(busStep1); if (!busLastPoint.equals(walkFirstPoint)) { addWalkPolyLineByLatLonPoints(busLastPoint, walkFirstPoint); } } /** * 检查 步行最后一点 和 bus的起点 是否一致 * * @param busStep */ private void checkWalkToBusline(BusStep busStep) { LatLonPoint walkLastPoint = getLastWalkPoint(busStep); LatLonPoint buslineFirstPoint = getFirstBuslinePoint(busStep); if (!walkLastPoint.equals(buslineFirstPoint)) { addWalkPolyLineByLatLonPoints(walkLastPoint, buslineFirstPoint); } } /** * @param busStep1 * @return */ private LatLonPoint getFirstWalkPoint(BusStep busStep1) { return busStep1.getWalk().getSteps().get(0).getPolyline().get(0); } /** * */ private void addWalkPolyLineByLatLonPoints(LatLonPoint pointFrom, LatLonPoint pointTo) { LatLng latLngFrom = AMapUtil.convertToLatLng(pointFrom); LatLng latLngTo = AMapUtil.convertToLatLng(pointTo); addWalkPolyline(latLngFrom, latLngTo); } /** * @param latLngFrom * @param latLngTo * @return */ private void addWalkPolyline(LatLng latLngFrom, LatLng latLngTo) { addPolyLine(new PolylineOptions().add(latLngFrom, latLngTo) .width(getRouteWidth()).color(getWalkColor()).setDottedLine(true)); } /** * @param listWalkPolyline */ private void addWalkPolyline(List<LatLng> listWalkPolyline) { addPolyLine(new PolylineOptions().addAll(listWalkPolyline) .color(getWalkColor()).width(getRouteWidth()).setDottedLine(true)); } private void addRailwayPolyline(List<LatLng> listPolyline) { addPolyLine(new PolylineOptions().addAll(listPolyline) .color(getDriveColor()).width(getRouteWidth())); } private String getWalkSnippet(List<WalkStep> walkSteps) { float disNum = 0; for (WalkStep step : walkSteps) { disNum += step.getDistance(); } return "\u6B65\u884C" + disNum + "\u7C73"; } public void drawLineArrow(LatLng latLngFrom, LatLng latLngTo) { addPolyLine(new PolylineOptions().add(latLngFrom, latLngTo).width(3) .color(getBusColor()).width(getRouteWidth()));// 绘制直线 } private String getBusSnippet(RouteBusLineItem routeBusLineItem) { return "(" + routeBusLineItem.getDepartureBusStation().getBusStationName() + "-->" + routeBusLineItem.getArrivalBusStation().getBusStationName() + ") \u7ECF\u8FC7" + (routeBusLineItem.getPassStationNum() + 1) + "\u7AD9"; } /** * @param busStep * @return */ private LatLonPoint getLastWalkPoint(BusStep busStep) { List<WalkStep> walkSteps = busStep.getWalk().getSteps(); WalkStep walkStep = walkSteps.get(walkSteps.size() - 1); List<LatLonPoint> lonPoints = walkStep.getPolyline(); return lonPoints.get(lonPoints.size() - 1); } private LatLonPoint getExitPoint(BusStep busStep) { Doorway doorway = busStep.getExit(); if (doorway == null) { return null; } return doorway.getLatLonPoint(); } private LatLonPoint getLastBuslinePoint(BusStep busStep) { List<LatLonPoint> lonPoints = busStep.getBusLine().getPolyline(); return lonPoints.get(lonPoints.size() - 1); } private LatLonPoint getEntrancePoint(BusStep busStep) { Doorway doorway = busStep.getEntrance(); if (doorway == null) { return null; } return doorway.getLatLonPoint(); } private LatLonPoint getFirstBuslinePoint(BusStep busStep) { return busStep.getBusLine().getPolyline().get(0); } }
1
52
1
2927_18
package com.dingmouren.example.layoutmanagergroup.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.ColorDrawable; import android.text.TextPaint; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.dingmouren.example.layoutmanagergroup.R; /** * Created by DELL on 2017/7/25. */ public class SmileView extends LinearLayout implements Animator.AnimatorListener { //分割线间距 private int dividerMargin = 20; private float count; private int defalutBottom = 70; private String defaultLike = "喜欢"; private String defalutDis = "无感"; private int defalutTextColor = Color.WHITE; private String defaluteShadow = "#7F484848"; private int defalutGravity = Gravity.CENTER_HORIZONTAL; private int defalutSize = dip2px(getContext(), 25); private int like = 20; private int disLike = 20; //点赞数,差评数 private float fLike, fDis; private ImageView imageLike; private ImageView imageDis; private TextView likeNum, disNum, likeText, disText; private LinearLayout likeBack, disBack, likeAll, disAll; private AnimationDrawable animLike, animDis; //笑脸帧动画 private ValueAnimator animatorBack; //背景拉伸动画 private int type = 0; //选择执行帧动画的笑脸 //0 笑脸 1 哭脸 private boolean isClose = false; //判断收起动画 public SmileView setDefalutBottom(int defalutBottom) { this.defalutBottom = defalutBottom; return this; } public void notifyChange() { init(); bindListener(); } public void setDefalutGravity(int defalutGravity) { this.defalutGravity = defalutGravity; } public void setDefalutDis(String defalutDis) { this.defalutDis = defalutDis; } public void setDefaultLike(String defaultLike) { this.defaultLike = defaultLike; } public SmileView setDividerMargin(int dividerMargin) { this.dividerMargin = dividerMargin; return this; } public void setDefalutSize(int defalutSize) { this.defalutSize = defalutSize; } public void setNum(int like, int dislike) { //设置百分比 count = like + dislike; fLike = like / count; fDis = dislike / count; this.like = (int) (fLike * 100); this.disLike = 100 - this.like; setLike(this.like); setDisLike(this.disLike); } public void setLike(int like) { likeNum.setText(like + ""); } public void setDisLike(int disLike) { disNum.setText(disLike + ""); } public SmileView(Context context) { this(context, null); } public SmileView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SmileView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); bindListener(); } private void init() { this.removeAllViews(); //初始化总布局 setOrientation(HORIZONTAL); setGravity(defalutGravity | Gravity.BOTTOM); setBackgroundColor(Color.TRANSPARENT); //开始透明 //设置百分比 float count = like + disLike; fLike = like / count; fDis = disLike / count; like = (int) (fLike * 100); disLike = (int) (fDis * 100); //初始化图片 imageLike = new ImageView(getContext()); //添加动画资源 获得帧动画 imageLike.setBackgroundResource(R.drawable.animation_like); animLike = (AnimationDrawable) imageLike.getBackground(); //初始化文字 likeNum = new TextView(getContext()); likeNum.setText(like + ""); likeNum.setTextColor(defalutTextColor); TextPaint likeNumPaint = likeNum.getPaint(); likeNumPaint.setFakeBoldText(true); likeNum.setTextSize(20f); likeText = new TextView(getContext()); likeText.setText(defaultLike); likeText.setTextColor(defalutTextColor); imageDis = new ImageView(getContext()); imageDis.setBackgroundResource(R.drawable.animation_dislike); animDis = (AnimationDrawable) imageDis.getBackground(); disNum = new TextView(getContext()); disNum.setText(disLike + ""); disNum.setTextColor(defalutTextColor); TextPaint disNumPaint = disNum.getPaint(); disNumPaint.setFakeBoldText(true); disNum.setTextSize(20f); disText = new TextView(getContext()); disText.setText(defalutDis); disText.setTextColor(defalutTextColor); //初始化布局 likeBack = new LinearLayout(getContext()); disBack = new LinearLayout(getContext()); LayoutParams params2 = new LayoutParams(defalutSize, defalutSize); likeBack.addView(imageLike, params2); disBack.addView(imageDis, params2); disBack.setBackgroundResource(R.drawable.white_background); likeBack.setBackgroundResource(R.drawable.white_background); //单列总布局 likeAll = new LinearLayout(getContext()); disAll = new LinearLayout(getContext()); likeAll.setOrientation(VERTICAL); disAll.setOrientation(VERTICAL); likeAll.setGravity(Gravity.CENTER_HORIZONTAL); disAll.setGravity(Gravity.CENTER_HORIZONTAL); likeAll.setBackgroundColor(Color.TRANSPARENT); disAll.setBackgroundColor(Color.TRANSPARENT); //添加文字图片放进一列 LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(0, 10, 0, 0); params.gravity = Gravity.CENTER; disAll.setGravity(Gravity.CENTER_HORIZONTAL); likeAll.setGravity(Gravity.RIGHT); disAll.addView(disNum, params); disAll.addView(disText, params); disAll.addView(disBack, params); likeAll.addView(likeNum, params); likeAll.addView(likeText, params); likeAll.addView(likeBack, params); //中间分隔线 ImageView imageView = new ImageView(getContext()); imageView.setBackground(new ColorDrawable(Color.GRAY)); LayoutParams params4 = new LayoutParams(3, 80); params4.setMargins(dividerMargin, 10, dividerMargin, defalutBottom + 20); params4.gravity = Gravity.BOTTOM; LayoutParams params3 = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params3.setMargins(30, 20, 30, defalutBottom); params3.gravity = Gravity.BOTTOM; addView(disAll, params3); addView(imageView, params4); addView(likeAll, params3); //隐藏文字 setVisibities(GONE); } // public void setVisibities(int v) { likeNum.setVisibility(v); disNum.setVisibility(v); likeText.setVisibility(v); disText.setVisibility(v); } //绑定监听 private void bindListener() { imageDis.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* type = 1; //设置动画对象 animBack(); //拉伸背景 setVisibities(VISIBLE); //隐藏文字 //切换背景色 setBackgroundColor(Color.TRANSPARENT); likeBack.setBackgroundResource(R.drawable.white_background); disBack.setBackgroundResource(R.drawable.yellow_background); //重置帧动画 imageLike.setBackground(null); imageLike.setBackgroundResource(R.drawable.animation_like); animLike = (AnimationDrawable) imageLike.getBackground();*/ disLikeAnimation(); } }); imageLike.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* type = 0; animBack(); setVisibities(VISIBLE); setBackgroundColor(Color.TRANSPARENT); disBack.setBackgroundResource(R.drawable.white_background); likeBack.setBackgroundResource(R.drawable.yellow_background); imageDis.setBackground(null); imageDis.setBackgroundResource(R.drawable.animation_dislike); animDis = (AnimationDrawable) imageDis.getBackground();*/ likeAnimation(); } }); } public void disLikeAnimation(){ type = 1; //设置动画对象 animBack(); //拉伸背景 setVisibities(VISIBLE); //隐藏文字 //切换背景色 setBackgroundColor(Color.parseColor(defaluteShadow)); likeBack.setBackgroundResource(R.drawable.white_background); disBack.setBackgroundResource(R.drawable.yellow_background); //重置帧动画 imageLike.setBackground(null); imageLike.setBackgroundResource(R.drawable.animation_like); animLike = (AnimationDrawable) imageLike.getBackground(); } public void likeAnimation(){ type = 0; animBack(); setVisibities(VISIBLE); setBackgroundColor(Color.parseColor(defaluteShadow)); disBack.setBackgroundResource(R.drawable.white_background); likeBack.setBackgroundResource(R.drawable.yellow_background); imageDis.setBackground(null); imageDis.setBackgroundResource(R.drawable.animation_dislike); animDis = (AnimationDrawable) imageDis.getBackground(); } //背景伸展动画 public void animBack() { //动画执行中不能点击 imageDis.setClickable(false); imageLike.setClickable(false); final int max = Math.max(like * 4, disLike * 4); animatorBack = ValueAnimator.ofInt(5, max); animatorBack.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int magrin = (int) animation.getAnimatedValue(); LayoutParams paramsLike = (LayoutParams) imageLike.getLayoutParams(); paramsLike.bottomMargin = magrin; if (magrin <= like * 4) { imageLike.setLayoutParams(paramsLike); } if (magrin <= disLike * 4) { imageDis.setLayoutParams(paramsLike); } } }); isClose = false; animatorBack.addListener(this); animatorBack.setDuration(500); animatorBack.start(); } //背景收回动画 public void setBackUp() { final int max = Math.max(like * 4, disLike * 4); animatorBack = ValueAnimator.ofInt(max, 5); animatorBack.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int magrin = (int) animation.getAnimatedValue(); LayoutParams paramsLike = (LayoutParams) imageLike.getLayoutParams(); paramsLike.bottomMargin = magrin; if (magrin <= like * 4) { imageLike.setLayoutParams(paramsLike); } if (magrin <= disLike * 4) { imageDis.setLayoutParams(paramsLike); } } }); animatorBack.addListener(this); animatorBack.setDuration(500); animatorBack.start(); } @Override public void onAnimationEnd(Animator animation) { //重置帧动画 animDis.stop(); animLike.stop(); //关闭时不执行帧动画 if (isClose) { //收回后可点击 imageDis.setClickable(true); imageLike.setClickable(true); //隐藏文字 setVisibities(GONE); //恢复透明 setBackgroundColor(Color.TRANSPARENT); return; } isClose = true; if (type == 0) { animLike.start(); objectY(imageLike); } else { animDis.start(); objectX(imageDis); } } public void objectY(View view) { ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", -10.0f, 0.0f, 10.0f, 0.0f, -10.0f, 0.0f, 10.0f, 0); animator.setRepeatMode(ObjectAnimator.RESTART); //animator.setRepeatCount(1); animator.setDuration(1500); animator.start(); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { setBackUp(); //执行回弹动画 } }); } public void objectX(View view) { ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationX", -10.0f, 0.0f, 10.0f, 0.0f, -10.0f, 0.0f, 10.0f, 0); animator.setRepeatMode(ObjectAnimator.RESTART); // animator.setRepeatCount(1); animator.setDuration(1500); animator.start(); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { setBackUp(); //执行回弹动画 } }); } @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } //dp转px public static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } //px转dp public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }
DingMouRen/LayoutManagerGroup
app/src/main/java/com/dingmouren/example/layoutmanagergroup/widget/SmileView.java
3,503
//隐藏文字
line_comment
zh-cn
package com.dingmouren.example.layoutmanagergroup.widget; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.animation.ObjectAnimator; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Color; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.ColorDrawable; import android.text.TextPaint; import android.util.AttributeSet; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.dingmouren.example.layoutmanagergroup.R; /** * Created by DELL on 2017/7/25. */ public class SmileView extends LinearLayout implements Animator.AnimatorListener { //分割线间距 private int dividerMargin = 20; private float count; private int defalutBottom = 70; private String defaultLike = "喜欢"; private String defalutDis = "无感"; private int defalutTextColor = Color.WHITE; private String defaluteShadow = "#7F484848"; private int defalutGravity = Gravity.CENTER_HORIZONTAL; private int defalutSize = dip2px(getContext(), 25); private int like = 20; private int disLike = 20; //点赞数,差评数 private float fLike, fDis; private ImageView imageLike; private ImageView imageDis; private TextView likeNum, disNum, likeText, disText; private LinearLayout likeBack, disBack, likeAll, disAll; private AnimationDrawable animLike, animDis; //笑脸帧动画 private ValueAnimator animatorBack; //背景拉伸动画 private int type = 0; //选择执行帧动画的笑脸 //0 笑脸 1 哭脸 private boolean isClose = false; //判断收起动画 public SmileView setDefalutBottom(int defalutBottom) { this.defalutBottom = defalutBottom; return this; } public void notifyChange() { init(); bindListener(); } public void setDefalutGravity(int defalutGravity) { this.defalutGravity = defalutGravity; } public void setDefalutDis(String defalutDis) { this.defalutDis = defalutDis; } public void setDefaultLike(String defaultLike) { this.defaultLike = defaultLike; } public SmileView setDividerMargin(int dividerMargin) { this.dividerMargin = dividerMargin; return this; } public void setDefalutSize(int defalutSize) { this.defalutSize = defalutSize; } public void setNum(int like, int dislike) { //设置百分比 count = like + dislike; fLike = like / count; fDis = dislike / count; this.like = (int) (fLike * 100); this.disLike = 100 - this.like; setLike(this.like); setDisLike(this.disLike); } public void setLike(int like) { likeNum.setText(like + ""); } public void setDisLike(int disLike) { disNum.setText(disLike + ""); } public SmileView(Context context) { this(context, null); } public SmileView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public SmileView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); bindListener(); } private void init() { this.removeAllViews(); //初始化总布局 setOrientation(HORIZONTAL); setGravity(defalutGravity | Gravity.BOTTOM); setBackgroundColor(Color.TRANSPARENT); //开始透明 //设置百分比 float count = like + disLike; fLike = like / count; fDis = disLike / count; like = (int) (fLike * 100); disLike = (int) (fDis * 100); //初始化图片 imageLike = new ImageView(getContext()); //添加动画资源 获得帧动画 imageLike.setBackgroundResource(R.drawable.animation_like); animLike = (AnimationDrawable) imageLike.getBackground(); //初始化文字 likeNum = new TextView(getContext()); likeNum.setText(like + ""); likeNum.setTextColor(defalutTextColor); TextPaint likeNumPaint = likeNum.getPaint(); likeNumPaint.setFakeBoldText(true); likeNum.setTextSize(20f); likeText = new TextView(getContext()); likeText.setText(defaultLike); likeText.setTextColor(defalutTextColor); imageDis = new ImageView(getContext()); imageDis.setBackgroundResource(R.drawable.animation_dislike); animDis = (AnimationDrawable) imageDis.getBackground(); disNum = new TextView(getContext()); disNum.setText(disLike + ""); disNum.setTextColor(defalutTextColor); TextPaint disNumPaint = disNum.getPaint(); disNumPaint.setFakeBoldText(true); disNum.setTextSize(20f); disText = new TextView(getContext()); disText.setText(defalutDis); disText.setTextColor(defalutTextColor); //初始化布局 likeBack = new LinearLayout(getContext()); disBack = new LinearLayout(getContext()); LayoutParams params2 = new LayoutParams(defalutSize, defalutSize); likeBack.addView(imageLike, params2); disBack.addView(imageDis, params2); disBack.setBackgroundResource(R.drawable.white_background); likeBack.setBackgroundResource(R.drawable.white_background); //单列总布局 likeAll = new LinearLayout(getContext()); disAll = new LinearLayout(getContext()); likeAll.setOrientation(VERTICAL); disAll.setOrientation(VERTICAL); likeAll.setGravity(Gravity.CENTER_HORIZONTAL); disAll.setGravity(Gravity.CENTER_HORIZONTAL); likeAll.setBackgroundColor(Color.TRANSPARENT); disAll.setBackgroundColor(Color.TRANSPARENT); //添加文字图片放进一列 LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params.setMargins(0, 10, 0, 0); params.gravity = Gravity.CENTER; disAll.setGravity(Gravity.CENTER_HORIZONTAL); likeAll.setGravity(Gravity.RIGHT); disAll.addView(disNum, params); disAll.addView(disText, params); disAll.addView(disBack, params); likeAll.addView(likeNum, params); likeAll.addView(likeText, params); likeAll.addView(likeBack, params); //中间分隔线 ImageView imageView = new ImageView(getContext()); imageView.setBackground(new ColorDrawable(Color.GRAY)); LayoutParams params4 = new LayoutParams(3, 80); params4.setMargins(dividerMargin, 10, dividerMargin, defalutBottom + 20); params4.gravity = Gravity.BOTTOM; LayoutParams params3 = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); params3.setMargins(30, 20, 30, defalutBottom); params3.gravity = Gravity.BOTTOM; addView(disAll, params3); addView(imageView, params4); addView(likeAll, params3); //隐藏 <SUF> setVisibities(GONE); } // public void setVisibities(int v) { likeNum.setVisibility(v); disNum.setVisibility(v); likeText.setVisibility(v); disText.setVisibility(v); } //绑定监听 private void bindListener() { imageDis.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* type = 1; //设置动画对象 animBack(); //拉伸背景 setVisibities(VISIBLE); //隐藏文字 //切换背景色 setBackgroundColor(Color.TRANSPARENT); likeBack.setBackgroundResource(R.drawable.white_background); disBack.setBackgroundResource(R.drawable.yellow_background); //重置帧动画 imageLike.setBackground(null); imageLike.setBackgroundResource(R.drawable.animation_like); animLike = (AnimationDrawable) imageLike.getBackground();*/ disLikeAnimation(); } }); imageLike.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /* type = 0; animBack(); setVisibities(VISIBLE); setBackgroundColor(Color.TRANSPARENT); disBack.setBackgroundResource(R.drawable.white_background); likeBack.setBackgroundResource(R.drawable.yellow_background); imageDis.setBackground(null); imageDis.setBackgroundResource(R.drawable.animation_dislike); animDis = (AnimationDrawable) imageDis.getBackground();*/ likeAnimation(); } }); } public void disLikeAnimation(){ type = 1; //设置动画对象 animBack(); //拉伸背景 setVisibities(VISIBLE); //隐藏文字 //切换背景色 setBackgroundColor(Color.parseColor(defaluteShadow)); likeBack.setBackgroundResource(R.drawable.white_background); disBack.setBackgroundResource(R.drawable.yellow_background); //重置帧动画 imageLike.setBackground(null); imageLike.setBackgroundResource(R.drawable.animation_like); animLike = (AnimationDrawable) imageLike.getBackground(); } public void likeAnimation(){ type = 0; animBack(); setVisibities(VISIBLE); setBackgroundColor(Color.parseColor(defaluteShadow)); disBack.setBackgroundResource(R.drawable.white_background); likeBack.setBackgroundResource(R.drawable.yellow_background); imageDis.setBackground(null); imageDis.setBackgroundResource(R.drawable.animation_dislike); animDis = (AnimationDrawable) imageDis.getBackground(); } //背景伸展动画 public void animBack() { //动画执行中不能点击 imageDis.setClickable(false); imageLike.setClickable(false); final int max = Math.max(like * 4, disLike * 4); animatorBack = ValueAnimator.ofInt(5, max); animatorBack.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int magrin = (int) animation.getAnimatedValue(); LayoutParams paramsLike = (LayoutParams) imageLike.getLayoutParams(); paramsLike.bottomMargin = magrin; if (magrin <= like * 4) { imageLike.setLayoutParams(paramsLike); } if (magrin <= disLike * 4) { imageDis.setLayoutParams(paramsLike); } } }); isClose = false; animatorBack.addListener(this); animatorBack.setDuration(500); animatorBack.start(); } //背景收回动画 public void setBackUp() { final int max = Math.max(like * 4, disLike * 4); animatorBack = ValueAnimator.ofInt(max, 5); animatorBack.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { int magrin = (int) animation.getAnimatedValue(); LayoutParams paramsLike = (LayoutParams) imageLike.getLayoutParams(); paramsLike.bottomMargin = magrin; if (magrin <= like * 4) { imageLike.setLayoutParams(paramsLike); } if (magrin <= disLike * 4) { imageDis.setLayoutParams(paramsLike); } } }); animatorBack.addListener(this); animatorBack.setDuration(500); animatorBack.start(); } @Override public void onAnimationEnd(Animator animation) { //重置帧动画 animDis.stop(); animLike.stop(); //关闭时不执行帧动画 if (isClose) { //收回后可点击 imageDis.setClickable(true); imageLike.setClickable(true); //隐藏文字 setVisibities(GONE); //恢复透明 setBackgroundColor(Color.TRANSPARENT); return; } isClose = true; if (type == 0) { animLike.start(); objectY(imageLike); } else { animDis.start(); objectX(imageDis); } } public void objectY(View view) { ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationY", -10.0f, 0.0f, 10.0f, 0.0f, -10.0f, 0.0f, 10.0f, 0); animator.setRepeatMode(ObjectAnimator.RESTART); //animator.setRepeatCount(1); animator.setDuration(1500); animator.start(); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { setBackUp(); //执行回弹动画 } }); } public void objectX(View view) { ObjectAnimator animator = ObjectAnimator.ofFloat(view, "translationX", -10.0f, 0.0f, 10.0f, 0.0f, -10.0f, 0.0f, 10.0f, 0); animator.setRepeatMode(ObjectAnimator.RESTART); // animator.setRepeatCount(1); animator.setDuration(1500); animator.start(); animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { setBackUp(); //执行回弹动画 } }); } @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } //dp转px public static int dip2px(Context context, float dipValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dipValue * scale + 0.5f); } //px转dp public static int px2dip(Context context, float pxValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } }
1
6
1
16437_1
package com.ding.xlibrary; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.hardware.Camera; import android.hardware.Sensor; import android.hardware.SensorManager; import android.location.LocationManager; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.ContactsContract; import android.telephony.TelephonyManager; import androidx.core.content.PermissionChecker; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import static android.content.Context.TELEPHONY_SERVICE; public class PermissionUtils { public static boolean selfPermissionGranted (Context context, String... permissions) { for (String permission : permissions) { if(PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED){ continue; } return false; } return true; } public static boolean permissionIsNormal(){ return !Build.MANUFACTURER.equals("vivo") && !Build.MANUFACTURER.equals("OPPO"); } public static boolean checkSelfPermissionsWhitNoNoramal(Context context, String... permissions){ for (String permission : permissions) { if(checkSelfPermission(context,permission)){ continue; } return false; } return true; } private static boolean checkSelfPermission(Context context,String permission) { // 对于非oppo和vivo手机,做正常的权限申请 if (permissionIsNormal()){ return selfPermissionGranted(context,permission); } // 对于国内部分机型做非正常权限申请 switch (permission){ case Manifest.permission.CAMERA: return checkCameraPermissions(context); case Manifest.permission.RECORD_AUDIO: return checkAudioPermission(context); case Manifest.permission.BODY_SENSORS: return checkSensorsPermission(context); case Manifest.permission.READ_CALENDAR: case Manifest.permission.WRITE_CALENDAR: return checkCalenderPermission(context,permission); case Manifest.permission.READ_CONTACTS: case Manifest.permission.WRITE_CONTACTS: case Manifest.permission.GET_ACCOUNTS: return checkContactsPermission(context,permission); case Manifest.permission.ACCESS_FINE_LOCATION: case Manifest.permission.ACCESS_COARSE_LOCATION: return checkLocationsPermission(context,permission); case Manifest.permission.READ_PHONE_STATE: case Manifest.permission.CALL_PHONE: case Manifest.permission.READ_CALL_LOG: case Manifest.permission.WRITE_CALL_LOG: case Manifest.permission.ADD_VOICEMAIL: case Manifest.permission.USE_SIP: case Manifest.permission.PROCESS_OUTGOING_CALLS: return checkReadPhoneStatePermission(context,permission); case Manifest.permission.SEND_SMS: case Manifest.permission.RECEIVE_SMS: case Manifest.permission.READ_SMS: case Manifest.permission.RECEIVE_WAP_PUSH: case Manifest.permission.RECEIVE_MMS: return checkSMSPermission(context,permission); case Manifest.permission.READ_EXTERNAL_STORAGE: case Manifest.permission.WRITE_EXTERNAL_STORAGE: return checkWritePermission(context,permission); default: return selfPermissionGranted(context,permission); } } /** * READ_PHONE_STATE * @return 是否有读取手机状态的权限 * 电话 READ_PHONE_STATE 危险 允许对电话状态进行只读访问,包括设备的电话号码,当前蜂窝网络信息,任何正在进行的呼叫的状态以及设备上注册的任何PhoneAccounts列表 * 电话 CALL_PHONE 危险 允许应用程序在不通过拨号器用户界面的情况下发起电话呼叫,以便用户确认呼叫 * 电话 READ_CALL_LOG 危险 允许应用程序读取用户的通话记录 * 电话 WRITE_CALL_LOG 危险 允许应用程序写入(但不读取)用户的呼叫日志数据 * 电话 ADD_VOICEMAIL 危险 允许应用程序将语音邮件添加到系统中 * 电话 USE_SIP 危险 允许应用程序使用SIP服务 * 电话 PROCESS_OUTGOING_CALLS 危险 允许应用程序查看拨出呼叫期间拨打的号码,并选择将呼叫重定向到其他号码或完全中止呼叫 * 耗时3ms左右 */ @SuppressLint({"HardwareIds", "MissingPermission"}) private static boolean checkReadPhoneStatePermission(Context context,String permission) { TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE); try { tm.getDeviceId(); return selfPermissionGranted(context,permission); }catch (Exception e){ return false; } } /** * 检查是否拥有读写权限 * WRITE_EXTERNAL_STORAGE * 耗时 1-12ms * @return */ private static boolean checkWritePermission(Context context,String permission) { File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "permission.ymt"); try { FileOutputStream outputStream = new FileOutputStream(file); outputStream.flush(); outputStream.close(); file.delete(); } catch (FileNotFoundException e) { return false; } catch (IOException e) { e.printStackTrace(); } return selfPermissionGranted(context,permission); } /** * 日历 READ_CALENDAR 危险 允许应用程序读取用户的日历数据 * 日历 WRITE_CALENDAR 危险 允许应用程序写入用户的日历数据 * 检查日历权限 * 耗时 30ms左右 * @return */ private static boolean checkCalenderPermission(Context context,String permission){ Cursor cursor = null; try{ String CALANDER_EVENT_URL = "content://com.android.calendar/events"; Uri uri = Uri.parse(CALANDER_EVENT_URL); cursor = context.getContentResolver().query(uri, null, null, null, null); }catch (Exception e){ return false; }finally { if (cursor != null) { cursor.close(); } } return selfPermissionGranted(context,permission); } /** * 检测相机权限,这个因为直接拿camera还不一定行,当前测试机型:oppo 魅族 小米 * * 相机 CAMERA 危险 使用摄像头做相关工作 * @return */ private static boolean checkCameraPermissions(Context context) { Camera mCamera = null; try { // 大众路线 过了基本就是有权限 mCamera = Camera.open(); Camera.Parameters mParameters = mCamera.getParameters(); mCamera.setParameters(mParameters); // 特殊路线,oppo和vivo得根据rom去反射mHasPermission if (permissionIsNormal()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Field fieldPassword; if(mCamera == null) mCamera = Camera.open(); //通过反射去拿相机是否获得了权限 fieldPassword = mCamera.getClass().getDeclaredField("mHasPermission"); fieldPassword.setAccessible(true); Boolean result = (Boolean) fieldPassword.get(mCamera); if (mCamera != null) { mCamera.release(); } mCamera = null; return result; } } } catch (Exception e) { e.printStackTrace(); }finally { if (mCamera != null) { mCamera.release(); } } return selfPermissionGranted(context,Manifest.permission.CAMERA); } /** * 联系人 READ_CONTACTS 危险 读取联系人 * 联系人 WRITE_CONTACTS 危险 写入联系人 * 联系人 GET_ACCOUNTS 危险 允许访问帐户服务中的帐户列表 * @return */ private static boolean checkContactsPermission(Context context,String permission){ Cursor cursor = null; try { cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); } catch (Exception e) { e.printStackTrace(); return false; } finally { if (cursor != null) { cursor.close(); } } return selfPermissionGranted(context,permission); } /** * * 位置 ACCESS_FINE_LOCATION 危险 允许应用访问精确位置 * 位置 ACCESS_COARSE_LOCATION 危险 允许应用访问大致位置 * @return */ private static boolean checkLocationsPermission(Context context,String permission){ try { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); // 无用操作 lm.getAllProviders(); }catch (Exception e){ return false; } return selfPermissionGranted(context,permission); } /** * * 麦克风 RECORD_AUDIO 危险 麦克风的使用 * @return */ private static boolean checkAudioPermission(Context context){ try { AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); // 无用操作 audioManager.getMode(); }catch (Exception e){ return false; } return selfPermissionGranted(context,Manifest.permission.RECORD_AUDIO); } /** * * 传感器 BODY_SENSORS 危险 允许应用程序访问来自传感器的数据 * @return */ private static boolean checkSensorsPermission(Context context){ try { SensorManager sorMgr = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); // 无用操作 sorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); }catch (Exception e){ return false; } return selfPermissionGranted(context,Manifest.permission.BODY_SENSORS); } /** * * 短信 SEND_SMS 危险 允许应用程序发送SMS消息 * 短信 RECEIVE_SMS 危险 允许应用程序接收SMS消息 * 短信 READ_SMS 危险 允许应用程序读取SMS消息 * 短信 RECEIVE_WAP_PUSH 危险 允许应用程序接收WAP推送消息 * 短信 RECEIVE_MMS 危险 允许应用程序监视传入的MMS消息(彩信) * * @return */ private static boolean checkSMSPermission(Context context,String permission){ Cursor cursor = null; try { Uri uri = Uri.parse("content://sms/failed"); String[] projection = new String[] { "_id", "address", "person", "body", "date", "type", }; cursor = context.getContentResolver().query(uri, projection, null, null, "date desc"); } catch (Exception e){ return false; } finally { if (cursor != null) { cursor.close(); } } return selfPermissionGranted(context,permission); } }
DingProg/ActivityResultPermission
xlibrary/src/main/java/com/ding/xlibrary/PermissionUtils.java
2,661
// 对于国内部分机型做非正常权限申请
line_comment
zh-cn
package com.ding.xlibrary; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.database.Cursor; import android.hardware.Camera; import android.hardware.Sensor; import android.hardware.SensorManager; import android.location.LocationManager; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.ContactsContract; import android.telephony.TelephonyManager; import androidx.core.content.PermissionChecker; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import static android.content.Context.TELEPHONY_SERVICE; public class PermissionUtils { public static boolean selfPermissionGranted (Context context, String... permissions) { for (String permission : permissions) { if(PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED){ continue; } return false; } return true; } public static boolean permissionIsNormal(){ return !Build.MANUFACTURER.equals("vivo") && !Build.MANUFACTURER.equals("OPPO"); } public static boolean checkSelfPermissionsWhitNoNoramal(Context context, String... permissions){ for (String permission : permissions) { if(checkSelfPermission(context,permission)){ continue; } return false; } return true; } private static boolean checkSelfPermission(Context context,String permission) { // 对于非oppo和vivo手机,做正常的权限申请 if (permissionIsNormal()){ return selfPermissionGranted(context,permission); } // 对于 <SUF> switch (permission){ case Manifest.permission.CAMERA: return checkCameraPermissions(context); case Manifest.permission.RECORD_AUDIO: return checkAudioPermission(context); case Manifest.permission.BODY_SENSORS: return checkSensorsPermission(context); case Manifest.permission.READ_CALENDAR: case Manifest.permission.WRITE_CALENDAR: return checkCalenderPermission(context,permission); case Manifest.permission.READ_CONTACTS: case Manifest.permission.WRITE_CONTACTS: case Manifest.permission.GET_ACCOUNTS: return checkContactsPermission(context,permission); case Manifest.permission.ACCESS_FINE_LOCATION: case Manifest.permission.ACCESS_COARSE_LOCATION: return checkLocationsPermission(context,permission); case Manifest.permission.READ_PHONE_STATE: case Manifest.permission.CALL_PHONE: case Manifest.permission.READ_CALL_LOG: case Manifest.permission.WRITE_CALL_LOG: case Manifest.permission.ADD_VOICEMAIL: case Manifest.permission.USE_SIP: case Manifest.permission.PROCESS_OUTGOING_CALLS: return checkReadPhoneStatePermission(context,permission); case Manifest.permission.SEND_SMS: case Manifest.permission.RECEIVE_SMS: case Manifest.permission.READ_SMS: case Manifest.permission.RECEIVE_WAP_PUSH: case Manifest.permission.RECEIVE_MMS: return checkSMSPermission(context,permission); case Manifest.permission.READ_EXTERNAL_STORAGE: case Manifest.permission.WRITE_EXTERNAL_STORAGE: return checkWritePermission(context,permission); default: return selfPermissionGranted(context,permission); } } /** * READ_PHONE_STATE * @return 是否有读取手机状态的权限 * 电话 READ_PHONE_STATE 危险 允许对电话状态进行只读访问,包括设备的电话号码,当前蜂窝网络信息,任何正在进行的呼叫的状态以及设备上注册的任何PhoneAccounts列表 * 电话 CALL_PHONE 危险 允许应用程序在不通过拨号器用户界面的情况下发起电话呼叫,以便用户确认呼叫 * 电话 READ_CALL_LOG 危险 允许应用程序读取用户的通话记录 * 电话 WRITE_CALL_LOG 危险 允许应用程序写入(但不读取)用户的呼叫日志数据 * 电话 ADD_VOICEMAIL 危险 允许应用程序将语音邮件添加到系统中 * 电话 USE_SIP 危险 允许应用程序使用SIP服务 * 电话 PROCESS_OUTGOING_CALLS 危险 允许应用程序查看拨出呼叫期间拨打的号码,并选择将呼叫重定向到其他号码或完全中止呼叫 * 耗时3ms左右 */ @SuppressLint({"HardwareIds", "MissingPermission"}) private static boolean checkReadPhoneStatePermission(Context context,String permission) { TelephonyManager tm = (TelephonyManager) context.getSystemService(TELEPHONY_SERVICE); try { tm.getDeviceId(); return selfPermissionGranted(context,permission); }catch (Exception e){ return false; } } /** * 检查是否拥有读写权限 * WRITE_EXTERNAL_STORAGE * 耗时 1-12ms * @return */ private static boolean checkWritePermission(Context context,String permission) { File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "permission.ymt"); try { FileOutputStream outputStream = new FileOutputStream(file); outputStream.flush(); outputStream.close(); file.delete(); } catch (FileNotFoundException e) { return false; } catch (IOException e) { e.printStackTrace(); } return selfPermissionGranted(context,permission); } /** * 日历 READ_CALENDAR 危险 允许应用程序读取用户的日历数据 * 日历 WRITE_CALENDAR 危险 允许应用程序写入用户的日历数据 * 检查日历权限 * 耗时 30ms左右 * @return */ private static boolean checkCalenderPermission(Context context,String permission){ Cursor cursor = null; try{ String CALANDER_EVENT_URL = "content://com.android.calendar/events"; Uri uri = Uri.parse(CALANDER_EVENT_URL); cursor = context.getContentResolver().query(uri, null, null, null, null); }catch (Exception e){ return false; }finally { if (cursor != null) { cursor.close(); } } return selfPermissionGranted(context,permission); } /** * 检测相机权限,这个因为直接拿camera还不一定行,当前测试机型:oppo 魅族 小米 * * 相机 CAMERA 危险 使用摄像头做相关工作 * @return */ private static boolean checkCameraPermissions(Context context) { Camera mCamera = null; try { // 大众路线 过了基本就是有权限 mCamera = Camera.open(); Camera.Parameters mParameters = mCamera.getParameters(); mCamera.setParameters(mParameters); // 特殊路线,oppo和vivo得根据rom去反射mHasPermission if (permissionIsNormal()) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { Field fieldPassword; if(mCamera == null) mCamera = Camera.open(); //通过反射去拿相机是否获得了权限 fieldPassword = mCamera.getClass().getDeclaredField("mHasPermission"); fieldPassword.setAccessible(true); Boolean result = (Boolean) fieldPassword.get(mCamera); if (mCamera != null) { mCamera.release(); } mCamera = null; return result; } } } catch (Exception e) { e.printStackTrace(); }finally { if (mCamera != null) { mCamera.release(); } } return selfPermissionGranted(context,Manifest.permission.CAMERA); } /** * 联系人 READ_CONTACTS 危险 读取联系人 * 联系人 WRITE_CONTACTS 危险 写入联系人 * 联系人 GET_ACCOUNTS 危险 允许访问帐户服务中的帐户列表 * @return */ private static boolean checkContactsPermission(Context context,String permission){ Cursor cursor = null; try { cursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null); } catch (Exception e) { e.printStackTrace(); return false; } finally { if (cursor != null) { cursor.close(); } } return selfPermissionGranted(context,permission); } /** * * 位置 ACCESS_FINE_LOCATION 危险 允许应用访问精确位置 * 位置 ACCESS_COARSE_LOCATION 危险 允许应用访问大致位置 * @return */ private static boolean checkLocationsPermission(Context context,String permission){ try { LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); // 无用操作 lm.getAllProviders(); }catch (Exception e){ return false; } return selfPermissionGranted(context,permission); } /** * * 麦克风 RECORD_AUDIO 危险 麦克风的使用 * @return */ private static boolean checkAudioPermission(Context context){ try { AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE); // 无用操作 audioManager.getMode(); }catch (Exception e){ return false; } return selfPermissionGranted(context,Manifest.permission.RECORD_AUDIO); } /** * * 传感器 BODY_SENSORS 危险 允许应用程序访问来自传感器的数据 * @return */ private static boolean checkSensorsPermission(Context context){ try { SensorManager sorMgr = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); // 无用操作 sorMgr.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); }catch (Exception e){ return false; } return selfPermissionGranted(context,Manifest.permission.BODY_SENSORS); } /** * * 短信 SEND_SMS 危险 允许应用程序发送SMS消息 * 短信 RECEIVE_SMS 危险 允许应用程序接收SMS消息 * 短信 READ_SMS 危险 允许应用程序读取SMS消息 * 短信 RECEIVE_WAP_PUSH 危险 允许应用程序接收WAP推送消息 * 短信 RECEIVE_MMS 危险 允许应用程序监视传入的MMS消息(彩信) * * @return */ private static boolean checkSMSPermission(Context context,String permission){ Cursor cursor = null; try { Uri uri = Uri.parse("content://sms/failed"); String[] projection = new String[] { "_id", "address", "person", "body", "date", "type", }; cursor = context.getContentResolver().query(uri, projection, null, null, "date desc"); } catch (Exception e){ return false; } finally { if (cursor != null) { cursor.close(); } } return selfPermissionGranted(context,permission); } }
0
19
0
15017_3
package com.ding.makeup.beauty; import android.graphics.Bitmap; import android.graphics.Point; import com.ding.makeup.utils.TimeAopUtils; /** * @author by dingdegao * time 2017/9/29 16:03 * function: 眼睛放大 */ public class MagnifyEyeUtils { /** * 眼睛放大算法 * @param bitmap 原来的bitmap * @param centerPoint 放大中心点 * @param radius 放大半径 * @param sizeLevel 放大力度 [0,4] * @return 放大眼睛后的图片 */ public static Bitmap magnifyEye(Bitmap bitmap, Point centerPoint, int radius, float sizeLevel) { TimeAopUtils.start(); Bitmap dstBitmap = bitmap.copy(Bitmap.Config.RGB_565, true); int left = centerPoint.x - radius < 0 ? 0 : centerPoint.x - radius; int top = centerPoint.y - radius < 0 ? 0 : centerPoint.y - radius; int right = centerPoint.x + radius > bitmap.getWidth() ? bitmap.getWidth() - 1 : centerPoint.x + radius; int bottom = centerPoint.y + radius > bitmap.getHeight() ? bitmap.getHeight() - 1 : centerPoint.y + radius; int powRadius = radius * radius; int offsetX, offsetY, powDistance, powOffsetX, powOffsetY; int disX, disY; //当为负数时,为缩小 float strength = (5 + sizeLevel * 2) / 10; for (int i = top; i <= bottom; i++) { offsetY = i - centerPoint.y; for (int j = left; j <= right; j++) { offsetX = j - centerPoint.x; powOffsetX = offsetX * offsetX; powOffsetY = offsetY * offsetY; powDistance = powOffsetX + powOffsetY; if (powDistance <= powRadius) { double distance = Math.sqrt(powDistance); double sinA = offsetX / distance; double cosA = offsetY / distance; double scaleFactor = distance / radius - 1; scaleFactor = (1 - scaleFactor * scaleFactor * (distance / radius) * strength); distance = distance * scaleFactor; disY = (int) (distance * cosA + centerPoint.y + 0.5); disY = checkY(disY, bitmap); disX = (int) (distance * sinA + centerPoint.x + 0.5); disX = checkX(disX, bitmap); //中心点不做处理 if (!(j == centerPoint.x && i == centerPoint.y)) { dstBitmap.setPixel(j, i, bitmap.getPixel(disX, disY)); } } } } TimeAopUtils.end("eye","magnifyEye"); return dstBitmap; } private static int checkY(int disY, Bitmap bitmap) { if (disY < 0) { disY = 0; } else if (disY >= bitmap.getHeight()) { disY = bitmap.getHeight() - 1; } return disY; } private static int checkX(int disX, Bitmap bitmap) { if (disX < 0) { disX = 0; } else if (disX >= bitmap.getWidth()) { disX = bitmap.getWidth() - 1; } return disX; } }
DingProg/Makeup
app/src/main/java/com/ding/makeup/beauty/MagnifyEyeUtils.java
853
//中心点不做处理
line_comment
zh-cn
package com.ding.makeup.beauty; import android.graphics.Bitmap; import android.graphics.Point; import com.ding.makeup.utils.TimeAopUtils; /** * @author by dingdegao * time 2017/9/29 16:03 * function: 眼睛放大 */ public class MagnifyEyeUtils { /** * 眼睛放大算法 * @param bitmap 原来的bitmap * @param centerPoint 放大中心点 * @param radius 放大半径 * @param sizeLevel 放大力度 [0,4] * @return 放大眼睛后的图片 */ public static Bitmap magnifyEye(Bitmap bitmap, Point centerPoint, int radius, float sizeLevel) { TimeAopUtils.start(); Bitmap dstBitmap = bitmap.copy(Bitmap.Config.RGB_565, true); int left = centerPoint.x - radius < 0 ? 0 : centerPoint.x - radius; int top = centerPoint.y - radius < 0 ? 0 : centerPoint.y - radius; int right = centerPoint.x + radius > bitmap.getWidth() ? bitmap.getWidth() - 1 : centerPoint.x + radius; int bottom = centerPoint.y + radius > bitmap.getHeight() ? bitmap.getHeight() - 1 : centerPoint.y + radius; int powRadius = radius * radius; int offsetX, offsetY, powDistance, powOffsetX, powOffsetY; int disX, disY; //当为负数时,为缩小 float strength = (5 + sizeLevel * 2) / 10; for (int i = top; i <= bottom; i++) { offsetY = i - centerPoint.y; for (int j = left; j <= right; j++) { offsetX = j - centerPoint.x; powOffsetX = offsetX * offsetX; powOffsetY = offsetY * offsetY; powDistance = powOffsetX + powOffsetY; if (powDistance <= powRadius) { double distance = Math.sqrt(powDistance); double sinA = offsetX / distance; double cosA = offsetY / distance; double scaleFactor = distance / radius - 1; scaleFactor = (1 - scaleFactor * scaleFactor * (distance / radius) * strength); distance = distance * scaleFactor; disY = (int) (distance * cosA + centerPoint.y + 0.5); disY = checkY(disY, bitmap); disX = (int) (distance * sinA + centerPoint.x + 0.5); disX = checkX(disX, bitmap); //中心 <SUF> if (!(j == centerPoint.x && i == centerPoint.y)) { dstBitmap.setPixel(j, i, bitmap.getPixel(disX, disY)); } } } } TimeAopUtils.end("eye","magnifyEye"); return dstBitmap; } private static int checkY(int disY, Bitmap bitmap) { if (disY < 0) { disY = 0; } else if (disY >= bitmap.getHeight()) { disY = bitmap.getHeight() - 1; } return disY; } private static int checkX(int disX, Bitmap bitmap) { if (disX < 0) { disX = 0; } else if (disX >= bitmap.getWidth()) { disX = bitmap.getWidth() - 1; } return disX; } }
1
9
1
36265_0
package com.parkingwang.keyboard.engine; import static com.parkingwang.keyboard.engine.NumberType.AVIATION; import static com.parkingwang.keyboard.engine.NumberType.CIVIL; import static com.parkingwang.keyboard.engine.NumberType.LING2012; import static com.parkingwang.keyboard.engine.NumberType.LING2018; import static com.parkingwang.keyboard.engine.NumberType.NEW_ENERGY; import static com.parkingwang.keyboard.engine.NumberType.PLA2012; import static com.parkingwang.keyboard.engine.NumberType.SHI2012; import static com.parkingwang.keyboard.engine.NumberType.WJ2012; /** * 禁用更多键的逻辑: * 1. 第1位,民用、新能源、新旧领事馆 * 2. 第3位,武警类型; * 3. 第7位,新能源、武警、军队、旧式2012大使馆、民航类型; * 4. 第8位; * */ public class MoreKeyTransformer extends LayoutMixer.AbstractTypedKeyTransformer { public MoreKeyTransformer() { super(KeyType.FUNC_MORE); } @Override protected KeyEntry transform(Context ctx, KeyEntry key) { if (0 == ctx.selectIndex && ctx.numberType.isAnyOf(CIVIL, NEW_ENERGY, LING2012, LING2018)) { return KeyEntry.newOfSetEnable(key, false); } else if (2 == ctx.selectIndex && WJ2012.equals(ctx.numberType)) { return KeyEntry.newOfSetEnable(key, false); } else if (6 == ctx.selectIndex && ctx.numberType.isAnyOf(NEW_ENERGY, WJ2012, PLA2012, SHI2012, AVIATION)) { return KeyEntry.newOfSetEnable(key, false); } else if (7 == ctx.selectIndex) { return KeyEntry.newOfSetEnable(key, false); } else { return key; } } }
DingXianSen/ProDemo
keyboard/src/main/java/com/parkingwang/keyboard/engine/MoreKeyTransformer.java
539
/** * 禁用更多键的逻辑: * 1. 第1位,民用、新能源、新旧领事馆 * 2. 第3位,武警类型; * 3. 第7位,新能源、武警、军队、旧式2012大使馆、民航类型; * 4. 第8位; * */
block_comment
zh-cn
package com.parkingwang.keyboard.engine; import static com.parkingwang.keyboard.engine.NumberType.AVIATION; import static com.parkingwang.keyboard.engine.NumberType.CIVIL; import static com.parkingwang.keyboard.engine.NumberType.LING2012; import static com.parkingwang.keyboard.engine.NumberType.LING2018; import static com.parkingwang.keyboard.engine.NumberType.NEW_ENERGY; import static com.parkingwang.keyboard.engine.NumberType.PLA2012; import static com.parkingwang.keyboard.engine.NumberType.SHI2012; import static com.parkingwang.keyboard.engine.NumberType.WJ2012; /** * 禁用更 <SUF>*/ public class MoreKeyTransformer extends LayoutMixer.AbstractTypedKeyTransformer { public MoreKeyTransformer() { super(KeyType.FUNC_MORE); } @Override protected KeyEntry transform(Context ctx, KeyEntry key) { if (0 == ctx.selectIndex && ctx.numberType.isAnyOf(CIVIL, NEW_ENERGY, LING2012, LING2018)) { return KeyEntry.newOfSetEnable(key, false); } else if (2 == ctx.selectIndex && WJ2012.equals(ctx.numberType)) { return KeyEntry.newOfSetEnable(key, false); } else if (6 == ctx.selectIndex && ctx.numberType.isAnyOf(NEW_ENERGY, WJ2012, PLA2012, SHI2012, AVIATION)) { return KeyEntry.newOfSetEnable(key, false); } else if (7 == ctx.selectIndex) { return KeyEntry.newOfSetEnable(key, false); } else { return key; } } }
1
109
1
8274_8
package com.mori.domain; import java.util.ArrayList; import java.util.List; public class Lesson { private String pk_LId;// 每门课都有那本书的ID +课程者TPhone 组合成ID 由课程建设者设定 Len 32 private String LName;//Len 20 private String LInfo;//Len 50 private String LIcon;//Len 100 private String fk_L_TPhone;//Len 11 private int LCount;//Len 255(数据库每个int 4字节 255=8字节 就32字节 没错) //考虑到有的课程课程号一样 老师不一样 所以老师在建设课程的时候输入的只是课程ID 而主键还是要老师PHONE+课程ID组合成唯一辨识 我了个去劳资又要改表又要 //从最里面改 = = ==== = = == = == = =所以就在逻辑上偷偷这样定义 自己手动添加PHONE 和ID组合再存入PK 在APP中JSON也有PK 不显示 隐藏起来 //点击课程显示章什么的再通过这个隐藏字段去FIND 显示详细章 节 private String fk_DId;//系ID private List<Section> sd=new ArrayList<Section>();//非字段 public List<Section> getSd() { return sd; } public void setSd(List<Section> sd) { this.sd = sd; } public String getFk_DId() { return fk_DId; } public void setFk_DId(String fk_DId) { this.fk_DId = fk_DId; } public int getLCount() { return LCount; } public void setLCount(int lCount) { LCount = lCount; } public String getFk_L_TPhone() { return fk_L_TPhone; } public void setFk_L_TPhone(String fk_L_TPhone) { this.fk_L_TPhone = fk_L_TPhone; } @Override public String toString() { return "Lesson [pk_LId=" + pk_LId + ", LName=" + LName + ", LInfo=" + LInfo + ", LIcon=" + LIcon + ", fk_L_TPhone=" + fk_L_TPhone + ", LCount=" + LCount + ", fk_DId=" + fk_DId + "]"; } public String getPk_LId() { return pk_LId; } public void setPk_LId(String pk_LId) { this.pk_LId = pk_LId; } public String getLName() { return LName; } public void setLName(String lName) { LName = lName; } public String getLInfo() { return LInfo; } public void setLInfo(String lInfo) { LInfo = lInfo; } public String getLIcon() { return LIcon; } public void setLIcon(String lIcon) { LIcon = lIcon; } }
DingYonghui/OnlineClass
web端源码/OnlineClass/src/com/mori/domain/Lesson.java
816
//点击课程显示章什么的再通过这个隐藏字段去FIND 显示详细章 节
line_comment
zh-cn
package com.mori.domain; import java.util.ArrayList; import java.util.List; public class Lesson { private String pk_LId;// 每门课都有那本书的ID +课程者TPhone 组合成ID 由课程建设者设定 Len 32 private String LName;//Len 20 private String LInfo;//Len 50 private String LIcon;//Len 100 private String fk_L_TPhone;//Len 11 private int LCount;//Len 255(数据库每个int 4字节 255=8字节 就32字节 没错) //考虑到有的课程课程号一样 老师不一样 所以老师在建设课程的时候输入的只是课程ID 而主键还是要老师PHONE+课程ID组合成唯一辨识 我了个去劳资又要改表又要 //从最里面改 = = ==== = = == = == = =所以就在逻辑上偷偷这样定义 自己手动添加PHONE 和ID组合再存入PK 在APP中JSON也有PK 不显示 隐藏起来 //点击 <SUF> private String fk_DId;//系ID private List<Section> sd=new ArrayList<Section>();//非字段 public List<Section> getSd() { return sd; } public void setSd(List<Section> sd) { this.sd = sd; } public String getFk_DId() { return fk_DId; } public void setFk_DId(String fk_DId) { this.fk_DId = fk_DId; } public int getLCount() { return LCount; } public void setLCount(int lCount) { LCount = lCount; } public String getFk_L_TPhone() { return fk_L_TPhone; } public void setFk_L_TPhone(String fk_L_TPhone) { this.fk_L_TPhone = fk_L_TPhone; } @Override public String toString() { return "Lesson [pk_LId=" + pk_LId + ", LName=" + LName + ", LInfo=" + LInfo + ", LIcon=" + LIcon + ", fk_L_TPhone=" + fk_L_TPhone + ", LCount=" + LCount + ", fk_DId=" + fk_DId + "]"; } public String getPk_LId() { return pk_LId; } public void setPk_LId(String pk_LId) { this.pk_LId = pk_LId; } public String getLName() { return LName; } public void setLName(String lName) { LName = lName; } public String getLInfo() { return LInfo; } public void setLInfo(String lInfo) { LInfo = lInfo; } public String getLIcon() { return LIcon; } public void setLIcon(String lIcon) { LIcon = lIcon; } }
1
34
1
30422_36
package cn.com.zhs.bitmapeditordemo; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; /** * Bitmap编辑封装工具类(你可能需要申请读写外部存储权限) * Created by ZhangHaoSong on 2017/03/25 0025. */ public class BitmapEditor { /** * 上下文 */ private Context context; /** * 基础的Bmp */ private Bitmap srcBmp; /** * 处理完毕的Bitmap */ private Bitmap resultBmp; /** * 输入的Bitmap的格式 */ private BitmapDataSource mSource; /** * 期望的Size */ private Size desireSize; /** * 期望的宽高比 */ private float desireRatio = 0; /** * 是否保持src的宽高比 */ private boolean keepSrcRatio = false; /** * 当遇到分辨率缩放时,缩放后的分辨率是大于给定分辨率还是小于给定分辨率 */ private boolean isLargerResolution; /** * 质量衰减间隔(缩放质量时每次缩减的质量间隔) */ private int qualityInterval = 10; /** * 设置处理后图片的大小限制(通过修改Bitmap的质量) */ private int bmpLimitedSize = -1; /** * 设置颜色格式 */ private int colorMode = 0; /** * 是否异步处理所有图像编辑 */ private boolean isAsync = true; /** * 处理监听器 */ private BitmapEditorListener mListener; /** * 颜色格式rgb565 */ public static final int COLOR_MODE_RGB565 = 1; /** * 颜色格式argb8888 */ public static final int COLOR_MODE_ARGB8888 = 2; /** * 构造函数 */ private BitmapEditor() { } /** * 初始化Editor */ public static BitmapEditor init() { return new BitmapEditor(); } /** * 给BitmapEditor赋予Bmp * * @param filePtah * @return */ public BitmapEditor from(String filePtah) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_FILE; mSource.file = new File(filePtah); return this; } /** * 图片资源来自文件 * * @param file * @return */ public BitmapEditor from(File file) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_FILE; mSource.file = file; return this; } /** * 图片资源来data * * @param bmpData * @return */ public BitmapEditor from(byte[] bmpData) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_DATA; mSource.data = bmpData; return this; } /** * 图片资源来Buffer * * @param bmpBuffer * @param offset * @param length * @return */ public BitmapEditor from(ByteBuffer bmpBuffer, int offset, int length) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_BUFFER; mSource.data = new byte[length]; bmpBuffer.get(mSource.data, offset, length); return this; } /** * 图片资源来Buffer * * @param bmpBuffer * @return */ public BitmapEditor from(ByteBuffer bmpBuffer) { return from(bmpBuffer, 0, bmpBuffer.remaining()); } /** * 图片资源来Bmp * * @param bmp * @return */ public BitmapEditor from(Bitmap bmp) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_BITMAP; mSource.bmp = bmp; return this; } /** * 图片资源来资源文件 * * @param resId * @return */ public BitmapEditor from(int resId, Context context) { this.context = context; mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_RES; mSource.resId = resId; return this; } /** * 设置监听 * * @param listener * @return */ public BitmapEditor listener(BitmapEditorListener listener) { mListener = listener; return this; } /** * 设置分辨率,直接将原有Bitmap进行缩放,不考虑给定的长宽比直接缩放 * * @param width 单位(px) * @param height 单位(px) * @return */ public BitmapEditor paserResolution(int width, int height) { desireSize = new Size(width, height); keepSrcRatio = false; return this; } /** * 保证给定长宽比的情况下,进行分辨率缩放 * * @param ratio width/height * @param isLargerResolution 设置缩放后的分辨率 是比需要设置的分辨率大还是小 * @return */ public BitmapEditor paserResolutionKeepRatio(int width, int height, float ratio, boolean isLargerResolution) { desireSize = new Size(width, height); this.desireRatio = ratio; this.isLargerResolution = isLargerResolution; keepSrcRatio = false; return this; } /** * 保证所给定长宽比的情况下,进行分辨率缩放 */ public BitmapEditor paserResolutionKeepRatio(int width, int height) { desireSize = new Size(width, height); keepSrcRatio = true; return this; } /** * 设置宽高比,一次来缩放 * * @param desireRatio 期望的宽/高 * @return */ public BitmapEditor setDesireRatio(float desireRatio) { this.desireRatio = desireRatio; return this; } /** * 设置按照长宽比缩放的时候大于Size还是小于Size * * @param isLargerResolution * @return */ public BitmapEditor setResolutionLarger(boolean isLargerResolution) { this.isLargerResolution = isLargerResolution; return this; } /** * 通过改变质量,来限制Bitmap的大小(只对Jpeg有效,因为PNG为无损,无法压缩) * * @param bmpSize 单位(kb) */ public BitmapEditor limitSize(int bmpSize) { this.bmpLimitedSize = bmpSize; Log.e("BitmapEditor", "bmpLimitedSize = " + bmpLimitedSize); return this; } /** * 设置Bitmap颜色格式(ARGB_8888,RGB_565) */ public BitmapEditor setColorMode(int colorMode) { this.colorMode = colorMode; return this; } /** * 设置是否为异步处理Bitmap */ public BitmapEditor async() { this.isAsync = true; return this; } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得 */ public void asBmp() { if (isAsync) { asBmpAsync(); } else { asBmpSync(); } } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) * * @param filePath 写入文件地址(如果文件不存在,将会创建文件) */ public void asFile(String filePath) { if (isAsync) { asFileAsync(filePath); } else { asFileSync(filePath); } } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asByteArray() { Thread t = new Thread() { @Override public void run() { asByteArraySync(); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asBmp(BitmapEditorListener listener) { if (isAsync) { asBmpAsync(); } else { asBmpSync(); } } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得 * * @param filePath 写入文件地址(如果文件不存在,将会创建文件) */ public void asFile(String filePath, BitmapEditorListener listener) { if (isAsync) { asFileAsync(filePath); } else { asFileSync(filePath); } } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asByteArray(BitmapEditorListener listener) { Thread t = new Thread() { @Override public void run() { asByteArraySync(); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asBmpAsync() { Thread t = new Thread() { @Override public void run() { asBmpSync(); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asFileAsync(String filePath) { final String file = filePath; Thread t = new Thread() { @Override public void run() { asFileSync(file); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asByteArrayAsync() { Thread t = new Thread() { @Override public void run() { asByteArraySync(); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回最终处理后的Bmp(同步处理/阻塞) */ public Bitmap asBmpSync() { try { long startPts = System.currentTimeMillis(); //判断条件 checkEditorReady(); if (mListener != null) { mListener.onEditorStart(); } //将不同数据源的图片数据获取成为srcBitmap,根据设置的颜色格式 srcBmp = getSrcBmpFromDataSource(colorMode); //处理分辨率缩放 resultBmp = setResolution(srcBmp, desireRatio, desireSize, isLargerResolution); //质量压缩处理 resultBmp = getBmpResultForBitmap(resultBmp, bmpLimitedSize); if (mListener != null) { mListener.onEditorEnd(resultBmp, System.currentTimeMillis() - startPts); } return resultBmp; } catch (Exception e) { if (mListener != null) { mListener.OnError(e); } } return resultBmp; } /** * 根据设置参数来开始处理Bitmap,返回最终处理结果写入File(同步处理/阻塞) */ public File asFileSync(String filePath) { try { long startPts = System.currentTimeMillis(); //判断条件 checkEditorReady(); if (mListener != null) { mListener.onEditorStart(); } //将不同数据源的图片数据获取成为srcBitmap,根据设置的颜色格式 srcBmp = getSrcBmpFromDataSource(colorMode); Log.e("BitmapEditor", "srcBmp length =" + srcBmp.getByteCount()); //处理分辨率缩放 resultBmp = setResolution(srcBmp, desireRatio, desireSize, isLargerResolution); Log.e("BitmapEditor", "resultBmp length =" + resultBmp.getByteCount()); //质量压缩处理 File file = getFileResultForBitmap(resultBmp, bmpLimitedSize, filePath); if (mListener != null) { mListener.onEditorEnd(file, System.currentTimeMillis() - startPts); } return file; } catch (Exception e) { if (mListener != null) { mListener.OnError(e); } } return null; } /** * 根据设置参数来开始处理Bitmap,返回最终处理结果生成数据(同步处理/阻塞) */ public byte[] asByteArraySync() { try { long startPts = System.currentTimeMillis(); //判断条件 checkEditorReady(); if (mListener != null) { mListener.onEditorStart(); } //将不同数据源的图片数据获取成为srcBitmap,根据设置的颜色格式 srcBmp = getSrcBmpFromDataSource(colorMode); //处理分辨率缩放 resultBmp = setResolution(srcBmp, desireRatio, desireSize, isLargerResolution); //质量压缩处理 byte[] data = getByteArrayResultForBitmap(resultBmp, bmpLimitedSize); if (mListener != null) { mListener.onEditorEnd(data, System.currentTimeMillis() - startPts); } return data; } catch (Exception e) { if (mListener != null) { mListener.OnError(e); } } return null; } /** * Bitmap处理过程监听 */ public interface BitmapEditorListener { /** * 处理开始 */ void onEditorStart(); /** * Bitmap 处理完毕 * * @param data 处理结果Bitmap * @param timeCost 处理所花时间 */ void onEditorEnd(Bitmap data, long timeCost); /** * Bitmap 处理完毕存储为文件 * * @param file 处理结果写入文件 * @param timeCost 处理所花时间 */ void onEditorEnd(File file, long timeCost); /** * Bitmap 处理完毕 * * @param data 处理结果Byte数组 * @param timeCost 处理所花时间 */ void onEditorEnd(byte[] data, long timeCost); /** * Bitmap 处理出错 * * @param e 错误异常 */ void OnError(Exception e); } /** * 长宽尺寸 */ public class Size { int width; int height; public Size(int width, int height) { this.width = width; this.height = height; } @Override public String toString() { return "Size{" + "width=" + width + ", height=" + height + '}'; } } /** * Bitmap数据源 */ private class BitmapDataSource { BitmapDataSourceMode mode; File file; byte[] data; Bitmap bmp; int resId; @Override public String toString() { return "BitmapDataSource{" + "mode=" + mode + ", file=" + file + ", data=" + Arrays.toString(data) + ", bmp=" + bmp + ", resId=" + resId + '}'; } } /** * bitmap 存储或者输出的数据源的格式 */ private enum BitmapDataSourceMode { FROM_FILE, FROM_DATA, FROM_BUFFER, FROM_BITMAP, FROM_RES } /** * 没有设置数据源异常 */ public class NoSourceException extends Exception { public NoSourceException() { super("you should set dataSource,for editor"); } } /** * 检测Editor的上下文以及Source是否设置 * * @throws NoSourceException */ private void checkEditorReady() throws NoSourceException { //暂时未想好怎么处理 if (mSource == null) { throw new NoSourceException(); } } /** * 获取Source Bmp,根据设定的颜色格式 */ private Bitmap getSrcBmpFromDataSource(int colorModel) { //根据颜色格式设置Bitmap option BitmapFactory.Options option = new BitmapFactory.Options(); if (colorModel == BitmapEditor.COLOR_MODE_ARGB8888) { option.inPreferredConfig = Bitmap.Config.ARGB_8888; } else if (colorModel == BitmapEditor.COLOR_MODE_RGB565) { option.inPreferredConfig = Bitmap.Config.RGB_565; } else { //未设置颜色格式 option = null; } Bitmap data = null; Log.e("BitmapEditor", "getSrcBmpFromDataSource option =" + option); //解析DataSource转化为Bmp switch (mSource.mode) { case FROM_FILE: if (option == null) data = BitmapFactory.decodeFile(mSource.file.getAbsolutePath()); else data = BitmapFactory.decodeFile(mSource.file.getAbsolutePath(), option); break; case FROM_DATA: if (option == null) data = BitmapFactory.decodeByteArray(mSource.data, 0, mSource.data.length); else data = BitmapFactory.decodeByteArray(mSource.data, 0, mSource.data.length, option); break; case FROM_BUFFER: if (option == null) data = BitmapFactory.decodeByteArray(mSource.data, 0, mSource.data.length); else data = BitmapFactory.decodeByteArray(mSource.data, 0, mSource.data.length, option); break; case FROM_BITMAP: data = mSource.bmp; break; case FROM_RES: if (option == null) data = BitmapFactory.decodeResource(context.getResources(), mSource.resId); else data = BitmapFactory.decodeResource(context.getResources(), mSource.resId, option); break; default: data = mSource.bmp; break; } return data; } /** * 根据设定的条件进行分辨率的缩放 * Resolution * * @param src 源图片 * @param ratio 设定的宽高比 * @param desireSize 设定的Size * @param isLargerSize 缩放大于/小于期望的Size * @return */ private Bitmap setResolution(Bitmap src, float ratio, Size desireSize, boolean isLargerSize) { //获取原始Size以及Ratio int srcWidth = src.getWidth(); int srcHeight = src.getHeight(); float srcRatio = srcWidth / srcHeight; //是否保持原有的宽高比 if (keepSrcRatio) { ratio = srcRatio; } Log.e("BitmapEditor", "getSrcBmpFromDataSource srcWidth =" + srcWidth); Log.e("BitmapEditor", "getSrcBmpFromDataSource srcHeight =" + srcHeight); //不需要做分辨率变换 if (desireSize == null && (ratio == 0 || ratio == srcRatio)) { //未设置期望Size且宽高比未设置或者与Src宽高比相等 return src; } if (desireSize.width == srcWidth && desireSize.height == srcHeight && ratio == srcRatio) { return src; } //计算输出Bitmap的分辨率 int destHeight; int destWidth; float destRatio; if (desireSize != null) { destWidth = desireSize.width; destHeight = desireSize.height; destRatio = destWidth / destHeight; } else { destWidth = srcWidth; destHeight = srcHeight; destRatio = srcRatio; } //调整分辨率 if (ratio > 0 && ratio != destRatio) { if (ratio > destRatio) { //期望的宽大于目标宽 if (isLargerSize) { //放大width destWidth = (int) (destHeight * ratio); } else { //缩小Height destHeight = (int) (destWidth / ratio); } } else { //期望的宽小于目标的宽 if (isLargerSize) { destHeight = (int) (destWidth / ratio); } else { destWidth = (int) (destHeight * ratio); } } } Log.e("BitmapEditor", "getSrcBmpFromDataSource destWidth =" + destWidth); Log.e("BitmapEditor", "getSrcBmpFromDataSource destHeight =" + destHeight); //根据调整后的分辨率进行缩放 return src.createScaledBitmap(src, destWidth, destHeight, false); } /** * 判定Size条件并返回Bmp */ private Bitmap getBmpResultForBitmap(Bitmap src, int size) { Log.e("BitmapEditor", "getBmpResultForBitmap size =" + size); if (size < 0) { return src; } else { return getBmpFromBOS(limitSize(src, size)); } } /** * 判定Size条件并返回File */ private File getFileResultForBitmap(Bitmap src, int size, String filePath) throws IOException { Log.e("BitmapEditor", "getFileResultForBitmap size =" + size); return getFileFromBOS(limitSize(src, size), filePath); } /** * 判定Size条件并返回Byte数组 */ private byte[] getByteArrayResultForBitmap(Bitmap src, int size) { Log.e("BitmapEditor", "getByteArrayResultForBitmap size =" + size); return getByteArrayFromBOS(limitSize(src, size)); } /** * 通过削减图片质量来缩减bmp的内存(获取压缩过的ByteBuffer) * * @param src * @param size */ private ByteArrayOutputStream limitSize(Bitmap src, int size) { //控制图片大小 int DEFAULT_POST_PHOTO_QUALITY = 100; ByteArrayOutputStream dataByte = new ByteArrayOutputStream(); src.compress(Bitmap.CompressFormat.JPEG, DEFAULT_POST_PHOTO_QUALITY, dataByte); //(质量压缩)(有效) if (size > 0) { Log.e("saveBmpAsFile", "dataByte length start=" + dataByte.toByteArray().length / 1024); while (dataByte.toByteArray().length > size) {//循环判断如果压缩后图片是否大于1000kb,大于继续压缩 Log.e("saveBmpAsFile", "dataByte length recycle=" + dataByte.toByteArray().length / 1024); if (DEFAULT_POST_PHOTO_QUALITY <= qualityInterval) { qualityInterval = (int) (Math.ceil(qualityInterval / 2)); } dataByte.reset();//重置dataByte即清空dataByte DEFAULT_POST_PHOTO_QUALITY = DEFAULT_POST_PHOTO_QUALITY - qualityInterval;//每次-qualityInterval质量 src.compress(Bitmap.CompressFormat.JPEG, DEFAULT_POST_PHOTO_QUALITY, dataByte);//这里压缩options%,把压缩后的数据存放到baos中 } } Log.e("saveBmpAsFile", "dataByte DEFAULT_POST_PHOTO_QUALITY=" + DEFAULT_POST_PHOTO_QUALITY); Log.e("saveBmpAsFile", "dataByte length end=" + dataByte.toByteArray().length / 1024); //生成ResultBmp return dataByte; } private Bitmap getBmpFromBOS(ByteArrayOutputStream bos) { return BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size()); } private byte[] getByteArrayFromBOS(ByteArrayOutputStream bos) { return bos.toByteArray(); } private File getFileFromBOS(ByteArrayOutputStream bos, String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file); //写入文件 bos.writeTo(fos); fos.close(); return file; } }
DiskyZhs/BitmapEdtior
BitmapEditor.java
5,662
/** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */
block_comment
zh-cn
package cn.com.zhs.bitmapeditordemo; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Log; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.util.Arrays; /** * Bitmap编辑封装工具类(你可能需要申请读写外部存储权限) * Created by ZhangHaoSong on 2017/03/25 0025. */ public class BitmapEditor { /** * 上下文 */ private Context context; /** * 基础的Bmp */ private Bitmap srcBmp; /** * 处理完毕的Bitmap */ private Bitmap resultBmp; /** * 输入的Bitmap的格式 */ private BitmapDataSource mSource; /** * 期望的Size */ private Size desireSize; /** * 期望的宽高比 */ private float desireRatio = 0; /** * 是否保持src的宽高比 */ private boolean keepSrcRatio = false; /** * 当遇到分辨率缩放时,缩放后的分辨率是大于给定分辨率还是小于给定分辨率 */ private boolean isLargerResolution; /** * 质量衰减间隔(缩放质量时每次缩减的质量间隔) */ private int qualityInterval = 10; /** * 设置处理后图片的大小限制(通过修改Bitmap的质量) */ private int bmpLimitedSize = -1; /** * 设置颜色格式 */ private int colorMode = 0; /** * 是否异步处理所有图像编辑 */ private boolean isAsync = true; /** * 处理监听器 */ private BitmapEditorListener mListener; /** * 颜色格式rgb565 */ public static final int COLOR_MODE_RGB565 = 1; /** * 颜色格式argb8888 */ public static final int COLOR_MODE_ARGB8888 = 2; /** * 构造函数 */ private BitmapEditor() { } /** * 初始化Editor */ public static BitmapEditor init() { return new BitmapEditor(); } /** * 给BitmapEditor赋予Bmp * * @param filePtah * @return */ public BitmapEditor from(String filePtah) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_FILE; mSource.file = new File(filePtah); return this; } /** * 图片资源来自文件 * * @param file * @return */ public BitmapEditor from(File file) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_FILE; mSource.file = file; return this; } /** * 图片资源来data * * @param bmpData * @return */ public BitmapEditor from(byte[] bmpData) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_DATA; mSource.data = bmpData; return this; } /** * 图片资源来Buffer * * @param bmpBuffer * @param offset * @param length * @return */ public BitmapEditor from(ByteBuffer bmpBuffer, int offset, int length) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_BUFFER; mSource.data = new byte[length]; bmpBuffer.get(mSource.data, offset, length); return this; } /** * 图片资源来Buffer * * @param bmpBuffer * @return */ public BitmapEditor from(ByteBuffer bmpBuffer) { return from(bmpBuffer, 0, bmpBuffer.remaining()); } /** * 图片资源来Bmp * * @param bmp * @return */ public BitmapEditor from(Bitmap bmp) { mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_BITMAP; mSource.bmp = bmp; return this; } /** * 图片资源来资源文件 * * @param resId * @return */ public BitmapEditor from(int resId, Context context) { this.context = context; mSource = new BitmapDataSource(); mSource.mode = BitmapDataSourceMode.FROM_RES; mSource.resId = resId; return this; } /** * 设置监听 * * @param listener * @return */ public BitmapEditor listener(BitmapEditorListener listener) { mListener = listener; return this; } /** * 设置分辨率,直接将原有Bitmap进行缩放,不考虑给定的长宽比直接缩放 * * @param width 单位(px) * @param height 单位(px) * @return */ public BitmapEditor paserResolution(int width, int height) { desireSize = new Size(width, height); keepSrcRatio = false; return this; } /** * 保证给定长宽比的情况下,进行分辨率缩放 * * @param ratio width/height * @param isLargerResolution 设置缩放后的分辨率 是比需要设置的分辨率大还是小 * @return */ public BitmapEditor paserResolutionKeepRatio(int width, int height, float ratio, boolean isLargerResolution) { desireSize = new Size(width, height); this.desireRatio = ratio; this.isLargerResolution = isLargerResolution; keepSrcRatio = false; return this; } /** * 保证所给定长宽比的情况下,进行分辨率缩放 */ public BitmapEditor paserResolutionKeepRatio(int width, int height) { desireSize = new Size(width, height); keepSrcRatio = true; return this; } /** * 设置宽高比,一次来缩放 * * @param desireRatio 期望的宽/高 * @return */ public BitmapEditor setDesireRatio(float desireRatio) { this.desireRatio = desireRatio; return this; } /** * 设置按照长宽比缩放的时候大于Size还是小于Size * * @param isLargerResolution * @return */ public BitmapEditor setResolutionLarger(boolean isLargerResolution) { this.isLargerResolution = isLargerResolution; return this; } /** * 通过改变质量,来限制Bitmap的大小(只对Jpeg有效,因为PNG为无损,无法压缩) * * @param bmpSize 单位(kb) */ public BitmapEditor limitSize(int bmpSize) { this.bmpLimitedSize = bmpSize; Log.e("BitmapEditor", "bmpLimitedSize = " + bmpLimitedSize); return this; } /** * 设置Bitmap颜色格式(ARGB_8888,RGB_565) */ public BitmapEditor setColorMode(int colorMode) { this.colorMode = colorMode; return this; } /** * 设置是否为异步处理Bitmap */ public BitmapEditor async() { this.isAsync = true; return this; } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得 */ public void asBmp() { if (isAsync) { asBmpAsync(); } else { asBmpSync(); } } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) * * @param filePath 写入文件地址(如果文件不存在,将会创建文件) */ public void asFile(String filePath) { if (isAsync) { asFileAsync(filePath); } else { asFileSync(filePath); } } /** * 根据设 <SUF>*/ public void asByteArray() { Thread t = new Thread() { @Override public void run() { asByteArraySync(); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asBmp(BitmapEditorListener listener) { if (isAsync) { asBmpAsync(); } else { asBmpSync(); } } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得 * * @param filePath 写入文件地址(如果文件不存在,将会创建文件) */ public void asFile(String filePath, BitmapEditorListener listener) { if (isAsync) { asFileAsync(filePath); } else { asFileSync(filePath); } } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asByteArray(BitmapEditorListener listener) { Thread t = new Thread() { @Override public void run() { asByteArraySync(); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asBmpAsync() { Thread t = new Thread() { @Override public void run() { asBmpSync(); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asFileAsync(String filePath) { final String file = filePath; Thread t = new Thread() { @Override public void run() { asFileSync(file); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回结果请设置回调,在回调中取得(异步处理/非阻塞) */ public void asByteArrayAsync() { Thread t = new Thread() { @Override public void run() { asByteArraySync(); } }; t.start(); } /** * 根据设置参数来开始处理Bitmap,返回最终处理后的Bmp(同步处理/阻塞) */ public Bitmap asBmpSync() { try { long startPts = System.currentTimeMillis(); //判断条件 checkEditorReady(); if (mListener != null) { mListener.onEditorStart(); } //将不同数据源的图片数据获取成为srcBitmap,根据设置的颜色格式 srcBmp = getSrcBmpFromDataSource(colorMode); //处理分辨率缩放 resultBmp = setResolution(srcBmp, desireRatio, desireSize, isLargerResolution); //质量压缩处理 resultBmp = getBmpResultForBitmap(resultBmp, bmpLimitedSize); if (mListener != null) { mListener.onEditorEnd(resultBmp, System.currentTimeMillis() - startPts); } return resultBmp; } catch (Exception e) { if (mListener != null) { mListener.OnError(e); } } return resultBmp; } /** * 根据设置参数来开始处理Bitmap,返回最终处理结果写入File(同步处理/阻塞) */ public File asFileSync(String filePath) { try { long startPts = System.currentTimeMillis(); //判断条件 checkEditorReady(); if (mListener != null) { mListener.onEditorStart(); } //将不同数据源的图片数据获取成为srcBitmap,根据设置的颜色格式 srcBmp = getSrcBmpFromDataSource(colorMode); Log.e("BitmapEditor", "srcBmp length =" + srcBmp.getByteCount()); //处理分辨率缩放 resultBmp = setResolution(srcBmp, desireRatio, desireSize, isLargerResolution); Log.e("BitmapEditor", "resultBmp length =" + resultBmp.getByteCount()); //质量压缩处理 File file = getFileResultForBitmap(resultBmp, bmpLimitedSize, filePath); if (mListener != null) { mListener.onEditorEnd(file, System.currentTimeMillis() - startPts); } return file; } catch (Exception e) { if (mListener != null) { mListener.OnError(e); } } return null; } /** * 根据设置参数来开始处理Bitmap,返回最终处理结果生成数据(同步处理/阻塞) */ public byte[] asByteArraySync() { try { long startPts = System.currentTimeMillis(); //判断条件 checkEditorReady(); if (mListener != null) { mListener.onEditorStart(); } //将不同数据源的图片数据获取成为srcBitmap,根据设置的颜色格式 srcBmp = getSrcBmpFromDataSource(colorMode); //处理分辨率缩放 resultBmp = setResolution(srcBmp, desireRatio, desireSize, isLargerResolution); //质量压缩处理 byte[] data = getByteArrayResultForBitmap(resultBmp, bmpLimitedSize); if (mListener != null) { mListener.onEditorEnd(data, System.currentTimeMillis() - startPts); } return data; } catch (Exception e) { if (mListener != null) { mListener.OnError(e); } } return null; } /** * Bitmap处理过程监听 */ public interface BitmapEditorListener { /** * 处理开始 */ void onEditorStart(); /** * Bitmap 处理完毕 * * @param data 处理结果Bitmap * @param timeCost 处理所花时间 */ void onEditorEnd(Bitmap data, long timeCost); /** * Bitmap 处理完毕存储为文件 * * @param file 处理结果写入文件 * @param timeCost 处理所花时间 */ void onEditorEnd(File file, long timeCost); /** * Bitmap 处理完毕 * * @param data 处理结果Byte数组 * @param timeCost 处理所花时间 */ void onEditorEnd(byte[] data, long timeCost); /** * Bitmap 处理出错 * * @param e 错误异常 */ void OnError(Exception e); } /** * 长宽尺寸 */ public class Size { int width; int height; public Size(int width, int height) { this.width = width; this.height = height; } @Override public String toString() { return "Size{" + "width=" + width + ", height=" + height + '}'; } } /** * Bitmap数据源 */ private class BitmapDataSource { BitmapDataSourceMode mode; File file; byte[] data; Bitmap bmp; int resId; @Override public String toString() { return "BitmapDataSource{" + "mode=" + mode + ", file=" + file + ", data=" + Arrays.toString(data) + ", bmp=" + bmp + ", resId=" + resId + '}'; } } /** * bitmap 存储或者输出的数据源的格式 */ private enum BitmapDataSourceMode { FROM_FILE, FROM_DATA, FROM_BUFFER, FROM_BITMAP, FROM_RES } /** * 没有设置数据源异常 */ public class NoSourceException extends Exception { public NoSourceException() { super("you should set dataSource,for editor"); } } /** * 检测Editor的上下文以及Source是否设置 * * @throws NoSourceException */ private void checkEditorReady() throws NoSourceException { //暂时未想好怎么处理 if (mSource == null) { throw new NoSourceException(); } } /** * 获取Source Bmp,根据设定的颜色格式 */ private Bitmap getSrcBmpFromDataSource(int colorModel) { //根据颜色格式设置Bitmap option BitmapFactory.Options option = new BitmapFactory.Options(); if (colorModel == BitmapEditor.COLOR_MODE_ARGB8888) { option.inPreferredConfig = Bitmap.Config.ARGB_8888; } else if (colorModel == BitmapEditor.COLOR_MODE_RGB565) { option.inPreferredConfig = Bitmap.Config.RGB_565; } else { //未设置颜色格式 option = null; } Bitmap data = null; Log.e("BitmapEditor", "getSrcBmpFromDataSource option =" + option); //解析DataSource转化为Bmp switch (mSource.mode) { case FROM_FILE: if (option == null) data = BitmapFactory.decodeFile(mSource.file.getAbsolutePath()); else data = BitmapFactory.decodeFile(mSource.file.getAbsolutePath(), option); break; case FROM_DATA: if (option == null) data = BitmapFactory.decodeByteArray(mSource.data, 0, mSource.data.length); else data = BitmapFactory.decodeByteArray(mSource.data, 0, mSource.data.length, option); break; case FROM_BUFFER: if (option == null) data = BitmapFactory.decodeByteArray(mSource.data, 0, mSource.data.length); else data = BitmapFactory.decodeByteArray(mSource.data, 0, mSource.data.length, option); break; case FROM_BITMAP: data = mSource.bmp; break; case FROM_RES: if (option == null) data = BitmapFactory.decodeResource(context.getResources(), mSource.resId); else data = BitmapFactory.decodeResource(context.getResources(), mSource.resId, option); break; default: data = mSource.bmp; break; } return data; } /** * 根据设定的条件进行分辨率的缩放 * Resolution * * @param src 源图片 * @param ratio 设定的宽高比 * @param desireSize 设定的Size * @param isLargerSize 缩放大于/小于期望的Size * @return */ private Bitmap setResolution(Bitmap src, float ratio, Size desireSize, boolean isLargerSize) { //获取原始Size以及Ratio int srcWidth = src.getWidth(); int srcHeight = src.getHeight(); float srcRatio = srcWidth / srcHeight; //是否保持原有的宽高比 if (keepSrcRatio) { ratio = srcRatio; } Log.e("BitmapEditor", "getSrcBmpFromDataSource srcWidth =" + srcWidth); Log.e("BitmapEditor", "getSrcBmpFromDataSource srcHeight =" + srcHeight); //不需要做分辨率变换 if (desireSize == null && (ratio == 0 || ratio == srcRatio)) { //未设置期望Size且宽高比未设置或者与Src宽高比相等 return src; } if (desireSize.width == srcWidth && desireSize.height == srcHeight && ratio == srcRatio) { return src; } //计算输出Bitmap的分辨率 int destHeight; int destWidth; float destRatio; if (desireSize != null) { destWidth = desireSize.width; destHeight = desireSize.height; destRatio = destWidth / destHeight; } else { destWidth = srcWidth; destHeight = srcHeight; destRatio = srcRatio; } //调整分辨率 if (ratio > 0 && ratio != destRatio) { if (ratio > destRatio) { //期望的宽大于目标宽 if (isLargerSize) { //放大width destWidth = (int) (destHeight * ratio); } else { //缩小Height destHeight = (int) (destWidth / ratio); } } else { //期望的宽小于目标的宽 if (isLargerSize) { destHeight = (int) (destWidth / ratio); } else { destWidth = (int) (destHeight * ratio); } } } Log.e("BitmapEditor", "getSrcBmpFromDataSource destWidth =" + destWidth); Log.e("BitmapEditor", "getSrcBmpFromDataSource destHeight =" + destHeight); //根据调整后的分辨率进行缩放 return src.createScaledBitmap(src, destWidth, destHeight, false); } /** * 判定Size条件并返回Bmp */ private Bitmap getBmpResultForBitmap(Bitmap src, int size) { Log.e("BitmapEditor", "getBmpResultForBitmap size =" + size); if (size < 0) { return src; } else { return getBmpFromBOS(limitSize(src, size)); } } /** * 判定Size条件并返回File */ private File getFileResultForBitmap(Bitmap src, int size, String filePath) throws IOException { Log.e("BitmapEditor", "getFileResultForBitmap size =" + size); return getFileFromBOS(limitSize(src, size), filePath); } /** * 判定Size条件并返回Byte数组 */ private byte[] getByteArrayResultForBitmap(Bitmap src, int size) { Log.e("BitmapEditor", "getByteArrayResultForBitmap size =" + size); return getByteArrayFromBOS(limitSize(src, size)); } /** * 通过削减图片质量来缩减bmp的内存(获取压缩过的ByteBuffer) * * @param src * @param size */ private ByteArrayOutputStream limitSize(Bitmap src, int size) { //控制图片大小 int DEFAULT_POST_PHOTO_QUALITY = 100; ByteArrayOutputStream dataByte = new ByteArrayOutputStream(); src.compress(Bitmap.CompressFormat.JPEG, DEFAULT_POST_PHOTO_QUALITY, dataByte); //(质量压缩)(有效) if (size > 0) { Log.e("saveBmpAsFile", "dataByte length start=" + dataByte.toByteArray().length / 1024); while (dataByte.toByteArray().length > size) {//循环判断如果压缩后图片是否大于1000kb,大于继续压缩 Log.e("saveBmpAsFile", "dataByte length recycle=" + dataByte.toByteArray().length / 1024); if (DEFAULT_POST_PHOTO_QUALITY <= qualityInterval) { qualityInterval = (int) (Math.ceil(qualityInterval / 2)); } dataByte.reset();//重置dataByte即清空dataByte DEFAULT_POST_PHOTO_QUALITY = DEFAULT_POST_PHOTO_QUALITY - qualityInterval;//每次-qualityInterval质量 src.compress(Bitmap.CompressFormat.JPEG, DEFAULT_POST_PHOTO_QUALITY, dataByte);//这里压缩options%,把压缩后的数据存放到baos中 } } Log.e("saveBmpAsFile", "dataByte DEFAULT_POST_PHOTO_QUALITY=" + DEFAULT_POST_PHOTO_QUALITY); Log.e("saveBmpAsFile", "dataByte length end=" + dataByte.toByteArray().length / 1024); //生成ResultBmp return dataByte; } private Bitmap getBmpFromBOS(ByteArrayOutputStream bos) { return BitmapFactory.decodeByteArray(bos.toByteArray(), 0, bos.size()); } private byte[] getByteArrayFromBOS(ByteArrayOutputStream bos) { return bos.toByteArray(); } private File getFileFromBOS(ByteArrayOutputStream bos, String filePath) throws IOException { File file = new File(filePath); if (!file.exists()) { file.createNewFile(); } FileOutputStream fos = new FileOutputStream(file); //写入文件 bos.writeTo(fos); fos.close(); return file; } }
0
63
0
33432_3
package com.example.administrator.httpdemo.Other; import android.widget.ListView; import com.example.administrator.httpdemo.Data.entity.CreateSongList; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/8/3. */ public class Constant { public static final int TYPE_LOCAL = 1; public static final int TYPE_NET = 2; public static final int TYPE_BMOB = 3; public static final int TYPE_CREATE = 4; public static final int TYPE_COLLECT = 5; public static final int TYPE_SONGLIST = 6; public static final int TYPE_TOPLIST = 7; public static final int TYPE_SHARE = 8; public static final String BASE_URL = "http://music.163.com/api/"; public static final String BASE_URL2 = "http://s.music.163.com/"; public static List<CreateSongList> sCreateSongLists = new ArrayList<>(); public static List<Long> getTopListIDFor1(){ List<Long> topListID = new ArrayList<>(); topListID.add((long) 19723756); topListID.add((long) 3779629); topListID.add((long) 2884035); topListID.add((long) 3778678); return topListID; } public static List<Long> getTopListIDFor2(){ List<Long> topListID = new ArrayList<>(); topListID.add((long) 71385702); topListID.add((long) 71384707); topListID.add((long) 10520166); topListID.add((long) 180106); topListID.add((long) 60198); topListID.add((long) 3812895); topListID.add((long) 27135204); topListID.add((long) 21845217); topListID.add((long) 11641012); topListID.add((long) 60131); topListID.add((long) 112463); topListID.add((long) 112504); topListID.add((long) 64016); topListID.add((long) 10169002); topListID.add((long) 1899724); return topListID; } //语种 风格 情感 场景 主题 public static List<String> getTagForTheme(){ List<String> tags = new ArrayList<>(); tags.add("经典"); tags.add("翻唱");tags.add("榜单");tags.add("现场"); tags.add("KTV");tags.add("DJ");tags.add("网络歌曲"); tags.add("器乐"); return tags; } public static List<String> getTagForPlace(){ List<String> tags = new ArrayList<>(); tags.add("运动");tags.add("驾驶"); tags.add("学习");tags.add("工作"); tags.add("清晨");tags.add("夜晚");tags.add("午后"); tags.add("游戏");tags.add("旅行");tags.add("散步"); tags.add("酒吧");tags.add("夜店"); tags.add("咖啡厅");tags.add("地铁"); tags.add("校园");tags.add("婚礼"); tags.add("约会");tags.add("休息"); return tags; } public static List<String> getTagForMood(){ List<String> tags = new ArrayList<>(); tags.add("快乐");tags.add("美好"); tags.add("安静");tags.add("伤感");tags.add("寂寞"); tags.add("思念");tags.add("孤独");tags.add("怀旧"); tags.add("悲伤");tags.add("感动");tags.add("治愈"); tags.add("放松");tags.add("清新");tags.add("浪漫"); tags.add("兴奋");tags.add("性感"); tags.add("励志"); return tags; } public static List<String> getTagForStyle(){ List<String> tags = new ArrayList<>(); tags.add("流行"); tags.add("摇滚");tags.add("民谣"); tags.add("电子");tags.add("影视原声"); tags.add("ACG");tags.add("轻音乐");tags.add("新世纪"); tags.add("爵士");tags.add("古典"); tags.add("乡村");tags.add("说唱");tags.add("世界音乐"); tags.add("古风");tags.add("儿歌"); tags.add("朋克");tags.add("布鲁斯"); tags.add("金属");tags.add("雷鬼");tags.add("英伦"); tags.add("民族");tags.add("后摇");tags.add("拉丁"); return tags; } public static List<String> getTagForLanguage(){ List<String> tags = new ArrayList<>(); tags.add("华语");tags.add("欧美");tags.add("粤语"); tags.add("日语");tags.add("韩语"); tags.add("纯音乐");tags.add("小语种"); return tags; } }
Django-go-go/EnjoyMusic
app/src/main/java/com/example/administrator/httpdemo/Other/Constant.java
1,413
//语种 风格 情感 场景 主题
line_comment
zh-cn
package com.example.administrator.httpdemo.Other; import android.widget.ListView; import com.example.administrator.httpdemo.Data.entity.CreateSongList; import java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/8/3. */ public class Constant { public static final int TYPE_LOCAL = 1; public static final int TYPE_NET = 2; public static final int TYPE_BMOB = 3; public static final int TYPE_CREATE = 4; public static final int TYPE_COLLECT = 5; public static final int TYPE_SONGLIST = 6; public static final int TYPE_TOPLIST = 7; public static final int TYPE_SHARE = 8; public static final String BASE_URL = "http://music.163.com/api/"; public static final String BASE_URL2 = "http://s.music.163.com/"; public static List<CreateSongList> sCreateSongLists = new ArrayList<>(); public static List<Long> getTopListIDFor1(){ List<Long> topListID = new ArrayList<>(); topListID.add((long) 19723756); topListID.add((long) 3779629); topListID.add((long) 2884035); topListID.add((long) 3778678); return topListID; } public static List<Long> getTopListIDFor2(){ List<Long> topListID = new ArrayList<>(); topListID.add((long) 71385702); topListID.add((long) 71384707); topListID.add((long) 10520166); topListID.add((long) 180106); topListID.add((long) 60198); topListID.add((long) 3812895); topListID.add((long) 27135204); topListID.add((long) 21845217); topListID.add((long) 11641012); topListID.add((long) 60131); topListID.add((long) 112463); topListID.add((long) 112504); topListID.add((long) 64016); topListID.add((long) 10169002); topListID.add((long) 1899724); return topListID; } //语种 <SUF> public static List<String> getTagForTheme(){ List<String> tags = new ArrayList<>(); tags.add("经典"); tags.add("翻唱");tags.add("榜单");tags.add("现场"); tags.add("KTV");tags.add("DJ");tags.add("网络歌曲"); tags.add("器乐"); return tags; } public static List<String> getTagForPlace(){ List<String> tags = new ArrayList<>(); tags.add("运动");tags.add("驾驶"); tags.add("学习");tags.add("工作"); tags.add("清晨");tags.add("夜晚");tags.add("午后"); tags.add("游戏");tags.add("旅行");tags.add("散步"); tags.add("酒吧");tags.add("夜店"); tags.add("咖啡厅");tags.add("地铁"); tags.add("校园");tags.add("婚礼"); tags.add("约会");tags.add("休息"); return tags; } public static List<String> getTagForMood(){ List<String> tags = new ArrayList<>(); tags.add("快乐");tags.add("美好"); tags.add("安静");tags.add("伤感");tags.add("寂寞"); tags.add("思念");tags.add("孤独");tags.add("怀旧"); tags.add("悲伤");tags.add("感动");tags.add("治愈"); tags.add("放松");tags.add("清新");tags.add("浪漫"); tags.add("兴奋");tags.add("性感"); tags.add("励志"); return tags; } public static List<String> getTagForStyle(){ List<String> tags = new ArrayList<>(); tags.add("流行"); tags.add("摇滚");tags.add("民谣"); tags.add("电子");tags.add("影视原声"); tags.add("ACG");tags.add("轻音乐");tags.add("新世纪"); tags.add("爵士");tags.add("古典"); tags.add("乡村");tags.add("说唱");tags.add("世界音乐"); tags.add("古风");tags.add("儿歌"); tags.add("朋克");tags.add("布鲁斯"); tags.add("金属");tags.add("雷鬼");tags.add("英伦"); tags.add("民族");tags.add("后摇");tags.add("拉丁"); return tags; } public static List<String> getTagForLanguage(){ List<String> tags = new ArrayList<>(); tags.add("华语");tags.add("欧美");tags.add("粤语"); tags.add("日语");tags.add("韩语"); tags.add("纯音乐");tags.add("小语种"); return tags; } }
0
16
0
50094_0
import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public interface Utility { static boolean isSpace(char c) { return c == ' '; } static boolean isNewLine(char c) { return c == '\n'; } static boolean isTab(char c) { return c == '\t'; } static long filesCompareByLine(Path path1, Path path2) throws IOException { try (BufferedReader bf1 = Files.newBufferedReader(path1); BufferedReader bf2 = Files.newBufferedReader(path2)) { // 用于标识两文件是否相同,-1是完全相同, // 否则是不同的行的行号,某种条件下也是较小文件的最大行号 long lineNumber = 1; String line1 = "", line2 = ""; while ((line1 = bf1.readLine()) != null) { line2 = bf2.readLine(); if (!line1.equals(line2)) { return lineNumber; } lineNumber++; } if (bf2.readLine() == null) { return -1; } else { return lineNumber; } } } }
Dludora/BUAA_Compiler
syntactic_analysis/src/Utility.java
282
// 用于标识两文件是否相同,-1是完全相同,
line_comment
zh-cn
import java.io.BufferedReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public interface Utility { static boolean isSpace(char c) { return c == ' '; } static boolean isNewLine(char c) { return c == '\n'; } static boolean isTab(char c) { return c == '\t'; } static long filesCompareByLine(Path path1, Path path2) throws IOException { try (BufferedReader bf1 = Files.newBufferedReader(path1); BufferedReader bf2 = Files.newBufferedReader(path2)) { // 用于 <SUF> // 否则是不同的行的行号,某种条件下也是较小文件的最大行号 long lineNumber = 1; String line1 = "", line2 = ""; while ((line1 = bf1.readLine()) != null) { line2 = bf2.readLine(); if (!line1.equals(line2)) { return lineNumber; } lineNumber++; } if (bf2.readLine() == null) { return -1; } else { return lineNumber; } } } }
1
23
1
18212_1
package cn.nuaa.dmrfcoder.androidexceldemo; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StrictMode; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.List; import cn.nuaa.dmrfcoder.androidexceldemo.Bean.DemoBean; import cn.nuaa.dmrfcoder.androidexceldemo.Utils.ExcelUtil; public class MainActivity extends Activity implements View.OnClickListener { private Button exportButton; private Button openButton; private TextView textView; private AlertDialog alertDialog; private AlertDialog mDialog; String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}; private int REQUEST_PERMISSION_CODE = 1000; private String filePath = "/sdcard/AndroidExcelDemo"; private void requestPermission() { if (Build.VERSION.SDK_INT > 23) { if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED) { //授予权限 Log.i("requestPermission:", "用户之前已经授予了权限!"); } else { //未获得权限 Log.i("requestPermission:", "未获得权限,现在申请!"); requestPermissions(permissions , REQUEST_PERMISSION_CODE); } } } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); requestPermission(); StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); builder.detectFileUriExposure(); exportButton = findViewById(R.id.export_button); exportButton.setOnClickListener(this); openButton = findViewById(R.id.open_button); openButton.setOnClickListener(this); textView = findViewById(R.id.textView); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.i("onPermissionsResult:", "权限" + permissions[0] + "申请成功"); // permission was granted, yay! Do the // contacts-related task you need to do. } else { Log.i("onPermissionsResult:", "用户拒绝了权限申请"); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("permission") .setMessage("点击允许才可以使用我们的app哦") .setPositiveButton("去允许", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { if (alertDialog != null && alertDialog.isShowing()) { alertDialog.dismiss(); } ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } }); alertDialog = builder.create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); // permission denied, boo! Disable the // functionality that depends on this permission. } } } private void showDialogTipUserRequestPermission() { ActivityCompat.requestPermissions(this, permissions, 321); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.export_button: exportExcel(this); break; case R.id.open_button: openDir(); default: break; } } private void openDir() { File file = new File(filePath); Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setDataAndType(Uri.fromFile(file), "file/*"); try { startActivity(intent); } catch (Exception e) { Toast.makeText(this, "没有正确打开文件管理器", Toast.LENGTH_SHORT).show(); } } private void exportExcel(Context context) { File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } String excelFileName = "/demo.xls"; String[] title = {"姓名", "年龄", "男孩"}; String sheetName = "demoSheetName"; List<DemoBean> demoBeanList = new ArrayList<>(); DemoBean demoBean1 = new DemoBean("张三", 10, true); DemoBean demoBean2 = new DemoBean("小红", 12, false); DemoBean demoBean3 = new DemoBean("李四", 18, true); DemoBean demoBean4 = new DemoBean("王香", 13, false); demoBeanList.add(demoBean1); demoBeanList.add(demoBean2); demoBeanList.add(demoBean3); demoBeanList.add(demoBean4); filePath = filePath + excelFileName; ExcelUtil.initExcel(filePath, sheetName, title); ExcelUtil.writeObjListToExcel(demoBeanList, filePath, context); textView.setText("excel已导出至:" + filePath); } }
DmrfCoder/AndroidExcelDemo
app/src/main/java/cn/nuaa/dmrfcoder/androidexceldemo/MainActivity.java
1,433
//未获得权限
line_comment
zh-cn
package cn.nuaa.dmrfcoder.androidexceldemo; import android.Manifest; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.StrictMode; import android.support.annotation.NonNull; import android.support.annotation.RequiresApi; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.util.ArrayList; import java.util.List; import cn.nuaa.dmrfcoder.androidexceldemo.Bean.DemoBean; import cn.nuaa.dmrfcoder.androidexceldemo.Utils.ExcelUtil; public class MainActivity extends Activity implements View.OnClickListener { private Button exportButton; private Button openButton; private TextView textView; private AlertDialog alertDialog; private AlertDialog mDialog; String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}; private int REQUEST_PERMISSION_CODE = 1000; private String filePath = "/sdcard/AndroidExcelDemo"; private void requestPermission() { if (Build.VERSION.SDK_INT > 23) { if (ContextCompat.checkSelfPermission(MainActivity.this, permissions[0]) == PackageManager.PERMISSION_GRANTED) { //授予权限 Log.i("requestPermission:", "用户之前已经授予了权限!"); } else { //未获 <SUF> Log.i("requestPermission:", "未获得权限,现在申请!"); requestPermissions(permissions , REQUEST_PERMISSION_CODE); } } } @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); requestPermission(); StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder(); StrictMode.setVmPolicy(builder.build()); builder.detectFileUriExposure(); exportButton = findViewById(R.id.export_button); exportButton.setOnClickListener(this); openButton = findViewById(R.id.open_button); openButton.setOnClickListener(this); textView = findViewById(R.id.textView); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_PERMISSION_CODE) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.i("onPermissionsResult:", "权限" + permissions[0] + "申请成功"); // permission was granted, yay! Do the // contacts-related task you need to do. } else { Log.i("onPermissionsResult:", "用户拒绝了权限申请"); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setTitle("permission") .setMessage("点击允许才可以使用我们的app哦") .setPositiveButton("去允许", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { if (alertDialog != null && alertDialog.isShowing()) { alertDialog.dismiss(); } ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); } }); alertDialog = builder.create(); alertDialog.setCanceledOnTouchOutside(false); alertDialog.show(); // permission denied, boo! Disable the // functionality that depends on this permission. } } } private void showDialogTipUserRequestPermission() { ActivityCompat.requestPermissions(this, permissions, 321); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.export_button: exportExcel(this); break; case R.id.open_button: openDir(); default: break; } } private void openDir() { File file = new File(filePath); Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("*/*"); intent.addCategory(Intent.CATEGORY_OPENABLE); intent.setDataAndType(Uri.fromFile(file), "file/*"); try { startActivity(intent); } catch (Exception e) { Toast.makeText(this, "没有正确打开文件管理器", Toast.LENGTH_SHORT).show(); } } private void exportExcel(Context context) { File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } String excelFileName = "/demo.xls"; String[] title = {"姓名", "年龄", "男孩"}; String sheetName = "demoSheetName"; List<DemoBean> demoBeanList = new ArrayList<>(); DemoBean demoBean1 = new DemoBean("张三", 10, true); DemoBean demoBean2 = new DemoBean("小红", 12, false); DemoBean demoBean3 = new DemoBean("李四", 18, true); DemoBean demoBean4 = new DemoBean("王香", 13, false); demoBeanList.add(demoBean1); demoBeanList.add(demoBean2); demoBeanList.add(demoBean3); demoBeanList.add(demoBean4); filePath = filePath + excelFileName; ExcelUtil.initExcel(filePath, sheetName, title); ExcelUtil.writeObjListToExcel(demoBeanList, filePath, context); textView.setText("excel已导出至:" + filePath); } }
1
7
1
56954_1
package View; import Configure.ViewConfigure; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * @author dmrfcoder * @date 2019-04-17 */ public class SwichButton extends JLabel { //0代表开始/绿色(停止中),1代表结束/红色(运行中) private int curState; private int D; interface StateChangeListener { void changeToRunning(); void changeToStop(); } private StateChangeListener stateChangeListener; public void setStateChangeListener(StateChangeListener stateChangeListener) { this.stateChangeListener = stateChangeListener; } public SwichButton(int D) { curState = 0; this.D = D; initListener(); } private void initListener() { addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (curState == 0) { curState = 1; stateChangeListener.changeToRunning(); } else { curState = 0; stateChangeListener.changeToStop(); } repaint(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); } @Override public void paint(Graphics g) { super.paint(g); if (curState == 0) { g.setColor(ViewConfigure.defaultTextColor); } else { g.setColor(Color.red); } g.fillOval((getWidth() - D) / 2, (getHeight() - D) / 2, D, D); String text = ""; g.setColor(Color.BLACK); if (curState == 0) { text = "开始"; } else { text = "结束"; } g.drawString(text, (getWidth() - 25) / 2, 5 + getHeight() / 2); } }
DmrfCoder/SimulationRouter
src/View/SwichButton.java
524
//0代表开始/绿色(停止中),1代表结束/红色(运行中)
line_comment
zh-cn
package View; import Configure.ViewConfigure; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * @author dmrfcoder * @date 2019-04-17 */ public class SwichButton extends JLabel { //0代 <SUF> private int curState; private int D; interface StateChangeListener { void changeToRunning(); void changeToStop(); } private StateChangeListener stateChangeListener; public void setStateChangeListener(StateChangeListener stateChangeListener) { this.stateChangeListener = stateChangeListener; } public SwichButton(int D) { curState = 0; this.D = D; initListener(); } private void initListener() { addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { if (curState == 0) { curState = 1; stateChangeListener.changeToRunning(); } else { curState = 0; stateChangeListener.changeToStop(); } repaint(); } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } }); } @Override public void paint(Graphics g) { super.paint(g); if (curState == 0) { g.setColor(ViewConfigure.defaultTextColor); } else { g.setColor(Color.red); } g.fillOval((getWidth() - D) / 2, (getHeight() - D) / 2, D, D); String text = ""; g.setColor(Color.BLACK); if (curState == 0) { text = "开始"; } else { text = "结束"; } g.drawString(text, (getWidth() - 25) / 2, 5 + getHeight() / 2); } }
1
29
1
56936_1
package game; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class GameFrame extends JFrame implements ActionListener{ static boolean judge = true; static String name; public GameFrame() { setSize(288, 512);//设置窗口大小(288,512); setLocationRelativeTo(null);//窗口位于电脑的正中间; setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按键 setResizable(false); setTitle("Flappy Bird终极豪华版"); init(); } public static void main(String[] args){ GameFrame frame = new GameFrame(); GamePanel panel = new GamePanel(); frame.add(panel);//添加到界面 frame.setVisible(true); } public void actionPerformed(ActionEvent e) {} void init() { JMenuBar menubar = new JMenuBar(); JMenu menu = new JMenu("菜单"); JMenu birdcolor = new JMenu("小鸟颜色"); JMenu bgcolor = new JMenu("背景主题"); JMenu column = new JMenu("柱子颜色"); menubar.add(menu); JMenuItem itembc1 = new JMenuItem("黄色"); JMenuItem itembc2 = new JMenuItem("蓝色"); JMenuItem itembc3 = new JMenuItem("红色"); menu.add(birdcolor); birdcolor.add(itembc1); birdcolor.add(itembc2); birdcolor.add(itembc3); JMenuItem itembg1 = new JMenuItem("白天"); JMenuItem itembg2 = new JMenuItem("黑夜"); menu.add(bgcolor); bgcolor.add(itembg1); bgcolor.add(itembg2); JMenuItem itemc1 = new JMenuItem("绿色"); JMenuItem itemc2 = new JMenuItem("橙色"); menu.add(column); column.add(itemc1); column.add(itemc2); setJMenuBar(menubar); itembc1.addActionListener(this); itembc2.addActionListener(this); itembc3.addActionListener(this); itembg1.addActionListener(this); itembg2.addActionListener(this); itemc1.addActionListener(this); itemc2.addActionListener(this); itembc1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 0; } }); itembc2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 1; } }); itembc3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 2; } }); itemc1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Column.j = 0; } }); itemc2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Column.j = 1; } }); itembg1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GamePanel.j = 1; } }); itembg2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GamePanel.j = 0; } }); } }
DmuFreeCoding/DMU-cs-course
Java/MrLeea/src/game/GameFrame.java
884
//窗口位于电脑的正中间;
line_comment
zh-cn
package game; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class GameFrame extends JFrame implements ActionListener{ static boolean judge = true; static String name; public GameFrame() { setSize(288, 512);//设置窗口大小(288,512); setLocationRelativeTo(null);//窗口 <SUF> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按键 setResizable(false); setTitle("Flappy Bird终极豪华版"); init(); } public static void main(String[] args){ GameFrame frame = new GameFrame(); GamePanel panel = new GamePanel(); frame.add(panel);//添加到界面 frame.setVisible(true); } public void actionPerformed(ActionEvent e) {} void init() { JMenuBar menubar = new JMenuBar(); JMenu menu = new JMenu("菜单"); JMenu birdcolor = new JMenu("小鸟颜色"); JMenu bgcolor = new JMenu("背景主题"); JMenu column = new JMenu("柱子颜色"); menubar.add(menu); JMenuItem itembc1 = new JMenuItem("黄色"); JMenuItem itembc2 = new JMenuItem("蓝色"); JMenuItem itembc3 = new JMenuItem("红色"); menu.add(birdcolor); birdcolor.add(itembc1); birdcolor.add(itembc2); birdcolor.add(itembc3); JMenuItem itembg1 = new JMenuItem("白天"); JMenuItem itembg2 = new JMenuItem("黑夜"); menu.add(bgcolor); bgcolor.add(itembg1); bgcolor.add(itembg2); JMenuItem itemc1 = new JMenuItem("绿色"); JMenuItem itemc2 = new JMenuItem("橙色"); menu.add(column); column.add(itemc1); column.add(itemc2); setJMenuBar(menubar); itembc1.addActionListener(this); itembc2.addActionListener(this); itembc3.addActionListener(this); itembg1.addActionListener(this); itembg2.addActionListener(this); itemc1.addActionListener(this); itemc2.addActionListener(this); itembc1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 0; } }); itembc2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 1; } }); itembc3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Bird.i = 2; } }); itemc1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Column.j = 0; } }); itemc2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Column.j = 1; } }); itembg1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GamePanel.j = 1; } }); itembg2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { GamePanel.j = 0; } }); } }
1
13
1
45653_7
package com.dnake.panel; import com.dnake.misc.SysTalk; import com.dnake.misc.sCaller; import com.dnake.misc.Sound; import com.dnake.v700.dmsg; import com.dnake.v700.dxml; import com.dnake.v700.sys; import android.annotation.SuppressLint; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.TextView; @SuppressLint({ "DefaultLocale", "SetJavaScriptEnabled", "NewApi" }) public class TalkLabel extends BaseLabel { public static Intent mIntent = null; public static TalkLabel mContext = null; public static int build = 0; public static int unit = 0; public static int id; public static int OUT = 0; public static int IN = 1; public static int mMode = 0; // 0:呼出, 1:呼入 private MediaPlayer mPlayer = null; private TextView mText; private long mAutoTs = 0; private long mEndTs = 0; private String mPstnDtmf = null; // 语音网关拨号DTMF @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.talk); this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility(); if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } mContext = this; mPeriod = 300; mText = (TextView) this.findViewById(R.id.prompt_text); if (mMode == OUT) { mText.setText(R.string.sCaller_call); } else if (mMode == IN) { mText.setText(R.string.sCaller_monitor); } } @Override public void onStart() { super.onStart(); mContext = this; this.onStart2(); } public void onStart2() { sCaller.refresh(); if (mMode == OUT) { String s; if (id == 0) { // 呼叫管理机,使用固定ID id = 10001; s = "10001"; } else { s = String.format("%d%02d%04d", build, unit, id); } sCaller.query(s); OnCompletionListener listener = new OnCompletionListener() { public void onCompletion(MediaPlayer p) { p.stop(); p.reset(); p.release(); mPlayer = null; } }; mPlayer = Sound.play(Sound.ringback, true, listener); } else { mAutoTs = System.currentTimeMillis(); } } @Override public void onStop() { super.onStop(); if (sCaller.running != sCaller.NONE) this.stop(true); mIntent = null; mAutoTs = 0; mContext = null; } @Override public void onTimer() { super.onTimer(); WakeTask.acquire(); int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility(); if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } if (mMode == OUT) {// 呼叫 if (sCaller.running == sCaller.QUERY) { if (sys.qResult.sip.url != null) { sCaller.start(sys.qResult.sip.url); sCaller.logger(sCaller.logger.CALL); sys.qResult.sip.url = null; } else if (sys.qResult.d600.ip != null) { System.out.println("ip: " + sys.qResult.d600.ip); sCaller.s600(sys.qResult.d600.host, sys.qResult.d600.ip); } else if (sCaller.timeout() >= sCaller.Time.QUERY) this.forward(); } else if (sCaller.running == sCaller.CALL) { if (sCaller.timeout() >= sCaller.Time.CALL || sys.qResult.result >= 400) this.forward(); } else if (sCaller.running == sCaller.RINGING) { // 有转呼25秒超时,其他按系统设置 int timeout = sys.panel.ringing * 1000; if (sCaller.timeout() >= timeout) { // 振铃超时 if (!this.forward()) { // 转呼失败 mText.setText(R.string.sCaller_no_answer); } } } else if (sCaller.running == sCaller.TALK) { if (sCaller.timeout() >= sys.talk.timeout * 1000) {// 对讲结束 mText.setText(R.string.sCaller_finish); this.stop(true); } if (mPstnDtmf != null && sCaller.timeout() > 1000) { char d = mPstnDtmf.charAt(0); mPstnDtmf = mPstnDtmf.substring(1); if (mPstnDtmf.length() <= 0) mPstnDtmf = null; dxml p = new dxml(); dmsg req = new dmsg(); p.setText("/params/dtmf", String.valueOf(d)); req.to("/talk/send_dtmf", p.toString()); } } } else if (mMode == IN) {// 监视 if (mAutoTs != 0 && Math.abs(System.currentTimeMillis() - mAutoTs) > 500) { mAutoTs = 0; sCaller.running = sCaller.TALK; dmsg req = new dmsg(); req.to("/talk/start", null); } if (sCaller.timeout() >= sCaller.Time.MONITOR) {// 监视超时 this.stop(true); if (!this.isFinishing()) this.finish(); } } if (mEndTs != 0) { if (Math.abs(System.currentTimeMillis() - mEndTs) >= 1000) { if (!this.isFinishing()) this.finish(); mEndTs = 0; } } else { if (sCaller.bStop) { // 挂断 this.stop(true); mText.setText(R.string.sCaller_finish); } } } @Override public void onKey(String key) { super.onKey(key); if (key.charAt(0) == '*' || key.charAt(0) == 'X') { if (!this.isFinishing()) { this.finish(); this.stop(true); } } } private Boolean forward() { mText.setText(R.string.sCaller_call_err); Sound.play(Sound.call_err, false); this.stop(true); return false; } public void play() { if (mPlayer != null) { Sound.stop(mPlayer); mPlayer = null; } mText.setText(R.string.sCaller_talk); sCaller.logger(sCaller.logger.ANSWER); } public void stop(Boolean mode) { if (mMode == OUT) { if (sCaller.running == sCaller.RINGING) sCaller.logger(sCaller.logger.FAILED); else if (sCaller.running == sCaller.TALK) sCaller.logger(sCaller.logger.END); } dmsg req = new dmsg(); req.to("/talk/stop", null); sCaller.reset(); if (mode) { if (mPlayer != null) { Sound.stop(mPlayer); mPlayer = null; } mEndTs = System.currentTimeMillis(); } else { mEndTs = 0; } } public static void start(int b, int u, int r) { build = b; unit = u; id = r; mMode = OUT; SysTalk.start(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) return true; return super.onKeyDown(keyCode, event); } }
DnakeFace/Face
ui/talk/src/com/dnake/panel/TalkLabel.java
2,408
// 对讲结束
line_comment
zh-cn
package com.dnake.panel; import com.dnake.misc.SysTalk; import com.dnake.misc.sCaller; import com.dnake.misc.Sound; import com.dnake.v700.dmsg; import com.dnake.v700.dxml; import com.dnake.v700.sys; import android.annotation.SuppressLint; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.widget.TextView; @SuppressLint({ "DefaultLocale", "SetJavaScriptEnabled", "NewApi" }) public class TalkLabel extends BaseLabel { public static Intent mIntent = null; public static TalkLabel mContext = null; public static int build = 0; public static int unit = 0; public static int id; public static int OUT = 0; public static int IN = 1; public static int mMode = 0; // 0:呼出, 1:呼入 private MediaPlayer mPlayer = null; private TextView mText; private long mAutoTs = 0; private long mEndTs = 0; private String mPstnDtmf = null; // 语音网关拨号DTMF @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.talk); this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility(); if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } mContext = this; mPeriod = 300; mText = (TextView) this.findViewById(R.id.prompt_text); if (mMode == OUT) { mText.setText(R.string.sCaller_call); } else if (mMode == IN) { mText.setText(R.string.sCaller_monitor); } } @Override public void onStart() { super.onStart(); mContext = this; this.onStart2(); } public void onStart2() { sCaller.refresh(); if (mMode == OUT) { String s; if (id == 0) { // 呼叫管理机,使用固定ID id = 10001; s = "10001"; } else { s = String.format("%d%02d%04d", build, unit, id); } sCaller.query(s); OnCompletionListener listener = new OnCompletionListener() { public void onCompletion(MediaPlayer p) { p.stop(); p.reset(); p.release(); mPlayer = null; } }; mPlayer = Sound.play(Sound.ringback, true, listener); } else { mAutoTs = System.currentTimeMillis(); } } @Override public void onStop() { super.onStop(); if (sCaller.running != sCaller.NONE) this.stop(true); mIntent = null; mAutoTs = 0; mContext = null; } @Override public void onTimer() { super.onTimer(); WakeTask.acquire(); int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility(); if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) { this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY); } if (mMode == OUT) {// 呼叫 if (sCaller.running == sCaller.QUERY) { if (sys.qResult.sip.url != null) { sCaller.start(sys.qResult.sip.url); sCaller.logger(sCaller.logger.CALL); sys.qResult.sip.url = null; } else if (sys.qResult.d600.ip != null) { System.out.println("ip: " + sys.qResult.d600.ip); sCaller.s600(sys.qResult.d600.host, sys.qResult.d600.ip); } else if (sCaller.timeout() >= sCaller.Time.QUERY) this.forward(); } else if (sCaller.running == sCaller.CALL) { if (sCaller.timeout() >= sCaller.Time.CALL || sys.qResult.result >= 400) this.forward(); } else if (sCaller.running == sCaller.RINGING) { // 有转呼25秒超时,其他按系统设置 int timeout = sys.panel.ringing * 1000; if (sCaller.timeout() >= timeout) { // 振铃超时 if (!this.forward()) { // 转呼失败 mText.setText(R.string.sCaller_no_answer); } } } else if (sCaller.running == sCaller.TALK) { if (sCaller.timeout() >= sys.talk.timeout * 1000) {// 对讲 <SUF> mText.setText(R.string.sCaller_finish); this.stop(true); } if (mPstnDtmf != null && sCaller.timeout() > 1000) { char d = mPstnDtmf.charAt(0); mPstnDtmf = mPstnDtmf.substring(1); if (mPstnDtmf.length() <= 0) mPstnDtmf = null; dxml p = new dxml(); dmsg req = new dmsg(); p.setText("/params/dtmf", String.valueOf(d)); req.to("/talk/send_dtmf", p.toString()); } } } else if (mMode == IN) {// 监视 if (mAutoTs != 0 && Math.abs(System.currentTimeMillis() - mAutoTs) > 500) { mAutoTs = 0; sCaller.running = sCaller.TALK; dmsg req = new dmsg(); req.to("/talk/start", null); } if (sCaller.timeout() >= sCaller.Time.MONITOR) {// 监视超时 this.stop(true); if (!this.isFinishing()) this.finish(); } } if (mEndTs != 0) { if (Math.abs(System.currentTimeMillis() - mEndTs) >= 1000) { if (!this.isFinishing()) this.finish(); mEndTs = 0; } } else { if (sCaller.bStop) { // 挂断 this.stop(true); mText.setText(R.string.sCaller_finish); } } } @Override public void onKey(String key) { super.onKey(key); if (key.charAt(0) == '*' || key.charAt(0) == 'X') { if (!this.isFinishing()) { this.finish(); this.stop(true); } } } private Boolean forward() { mText.setText(R.string.sCaller_call_err); Sound.play(Sound.call_err, false); this.stop(true); return false; } public void play() { if (mPlayer != null) { Sound.stop(mPlayer); mPlayer = null; } mText.setText(R.string.sCaller_talk); sCaller.logger(sCaller.logger.ANSWER); } public void stop(Boolean mode) { if (mMode == OUT) { if (sCaller.running == sCaller.RINGING) sCaller.logger(sCaller.logger.FAILED); else if (sCaller.running == sCaller.TALK) sCaller.logger(sCaller.logger.END); } dmsg req = new dmsg(); req.to("/talk/stop", null); sCaller.reset(); if (mode) { if (mPlayer != null) { Sound.stop(mPlayer); mPlayer = null; } mEndTs = System.currentTimeMillis(); } else { mEndTs = 0; } } public static void start(int b, int u, int r) { build = b; unit = u; id = r; mMode = OUT; SysTalk.start(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) return true; return super.onKeyDown(keyCode, event); } }
1
8
1
53010_2
package com.randian.win.model; import java.io.Serializable; import java.util.List; /** * Created by lily on 15-6-24. */ public class Coach implements Serializable { private int id; private int level;//等级 1:中级 2:高级 3:特级 4:专家 private int distance; private int order_num; private int comment_num; private int reputation_num; private float score; private float coach_price; private String sex; private String name; private String city; private String location; private String verified; private String created_at; private String updated_at; private String description; private String hours_class; private String available_areas; private String profile_image_url; private String positive_reputation; private String categoriesStr; private List<Sport> sports;//教练对应的课程列表 private List<Category> categories; //category的结构 [{"name":"瑜伽"},{"name":"健身"}] public class Category implements Serializable{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public List<Category> getCategoriesList() { return categories; } public void setCategoriesList(List<Category> categories) { this.categories = categories; } public String getCategories() { return categoriesStr; } public void setCategories(String categoriesStr) { this.categoriesStr = categoriesStr; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getOrder_num() { return order_num; } public void setOrder_num(int order_num) { this.order_num = order_num; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } public int getReputation_num() { return reputation_num; } public void setReputation_num(int reputation_num) { this.reputation_num = reputation_num; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPositive_reputation() { return positive_reputation; } public void setPositive_reputation(String positive_reputation) { this.positive_reputation = positive_reputation; } public String getProfile_image_url() { return profile_image_url; } public void setProfile_image_url(String profile_image_url) { this.profile_image_url = profile_image_url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVerified() { return verified; } public void setVerified(String verified) { this.verified = verified; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } public String getUpdated_at() { return updated_at; } public void setUpdated_at(String updated_at) { this.updated_at = updated_at; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getHours_class() { return hours_class; } public void setHours_class(String hours_class) { this.hours_class = hours_class; } public String getAvailable_areas() { return available_areas; } public void setAvailable_areas(String available_areas) { this.available_areas = available_areas; } public List<Sport> getSports() { return sports; } public void setSports(List<Sport> sports) { this.sports = sports; } public int getComment_num() { return comment_num; } public void setComment_num(int comment_num) { this.comment_num = comment_num; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public float getCoach_price() { return coach_price; } public void setCoach_price(float coach_price) { this.coach_price = coach_price; } }
DoTalkLily/AppKit
app/src/main/java/com/randian/win/model/Coach.java
1,205
//教练对应的课程列表
line_comment
zh-cn
package com.randian.win.model; import java.io.Serializable; import java.util.List; /** * Created by lily on 15-6-24. */ public class Coach implements Serializable { private int id; private int level;//等级 1:中级 2:高级 3:特级 4:专家 private int distance; private int order_num; private int comment_num; private int reputation_num; private float score; private float coach_price; private String sex; private String name; private String city; private String location; private String verified; private String created_at; private String updated_at; private String description; private String hours_class; private String available_areas; private String profile_image_url; private String positive_reputation; private String categoriesStr; private List<Sport> sports;//教练 <SUF> private List<Category> categories; //category的结构 [{"name":"瑜伽"},{"name":"健身"}] public class Category implements Serializable{ private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } public List<Category> getCategoriesList() { return categories; } public void setCategoriesList(List<Category> categories) { this.categories = categories; } public String getCategories() { return categoriesStr; } public void setCategories(String categoriesStr) { this.categoriesStr = categoriesStr; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getOrder_num() { return order_num; } public void setOrder_num(int order_num) { this.order_num = order_num; } public int getDistance() { return distance; } public void setDistance(int distance) { this.distance = distance; } public int getReputation_num() { return reputation_num; } public void setReputation_num(int reputation_num) { this.reputation_num = reputation_num; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getPositive_reputation() { return positive_reputation; } public void setPositive_reputation(String positive_reputation) { this.positive_reputation = positive_reputation; } public String getProfile_image_url() { return profile_image_url; } public void setProfile_image_url(String profile_image_url) { this.profile_image_url = profile_image_url; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getVerified() { return verified; } public void setVerified(String verified) { this.verified = verified; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getCreated_at() { return created_at; } public void setCreated_at(String created_at) { this.created_at = created_at; } public String getUpdated_at() { return updated_at; } public void setUpdated_at(String updated_at) { this.updated_at = updated_at; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getHours_class() { return hours_class; } public void setHours_class(String hours_class) { this.hours_class = hours_class; } public String getAvailable_areas() { return available_areas; } public void setAvailable_areas(String available_areas) { this.available_areas = available_areas; } public List<Sport> getSports() { return sports; } public void setSports(List<Sport> sports) { this.sports = sports; } public int getComment_num() { return comment_num; } public void setComment_num(int comment_num) { this.comment_num = comment_num; } public float getScore() { return score; } public void setScore(float score) { this.score = score; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public float getCoach_price() { return coach_price; } public void setCoach_price(float coach_price) { this.coach_price = coach_price; } }
1
11
1
11898_0
package xyz.doikki.dkplayer.widget.component; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import xyz.doikki.dkplayer.R; import xyz.doikki.videoplayer.controller.IControlComponent; import xyz.doikki.videoplayer.controller.ControlWrapper; import xyz.doikki.videoplayer.player.VideoView; import xyz.doikki.videoplayer.util.PlayerUtils; public class AdControlView extends FrameLayout implements IControlComponent, View.OnClickListener { protected TextView mAdTime, mAdDetail; protected ImageView mBack, mVolume, mFullScreen, mPlayButton; protected AdControlListener mListener; private ControlWrapper mControlWrapper; public AdControlView(@NonNull Context context) { super(context); } public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } { LayoutInflater.from(getContext()).inflate(R.layout.layout_ad_control_view, this, true); mAdTime = findViewById(R.id.ad_time); mAdDetail = findViewById(R.id.ad_detail); mAdDetail.setText("了解详情>"); mBack = findViewById(R.id.back); mBack.setVisibility(GONE); mVolume = findViewById(R.id.iv_volume); mFullScreen = findViewById(R.id.fullscreen); mPlayButton = findViewById(R.id.iv_play); mPlayButton.setOnClickListener(this); mAdTime.setOnClickListener(this); mAdDetail.setOnClickListener(this); mBack.setOnClickListener(this); mVolume.setOnClickListener(this); mFullScreen.setOnClickListener(this); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mListener != null) mListener.onAdClick(); } }); } @Override public void attach(@NonNull ControlWrapper controlWrapper) { mControlWrapper = controlWrapper; } @Override public View getView() { return this; } @Override public void onVisibilityChanged(boolean isVisible, Animation anim) { } @Override public void onPlayStateChanged(int playState) { switch (playState) { case VideoView.STATE_PLAYING: mControlWrapper.startProgress(); mPlayButton.setSelected(true); break; case VideoView.STATE_PAUSED: mPlayButton.setSelected(false); break; } } @Override public void onPlayerStateChanged(int playerState) { switch (playerState) { case VideoView.PLAYER_NORMAL: mBack.setVisibility(GONE); mFullScreen.setSelected(false); break; case VideoView.PLAYER_FULL_SCREEN: mBack.setVisibility(VISIBLE); mFullScreen.setSelected(true); break; } //暂未实现全面屏适配逻辑,需要你自己补全 } @Override public void setProgress(int duration, int position) { if (mAdTime != null) mAdTime.setText(String.format("%s | 跳过", (duration - position) / 1000)); } @Override public void onLockStateChanged(boolean isLocked) { } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.back | id == R.id.fullscreen) { toggleFullScreen(); } else if (id == R.id.iv_volume) { doMute(); } else if (id == R.id.ad_detail) { if (mListener != null) mListener.onAdClick(); } else if (id == R.id.ad_time) { if (mListener != null) mListener.onSkipAd(); } else if (id == R.id.iv_play) { mControlWrapper.togglePlay(); } } private void doMute() { mControlWrapper.setMute(!mControlWrapper.isMute()); mVolume.setImageResource(mControlWrapper.isMute() ? R.drawable.dkplayer_ic_action_volume_up : R.drawable.dkplayer_ic_action_volume_off); } /** * 横竖屏切换 */ private void toggleFullScreen() { Activity activity = PlayerUtils.scanForActivity(getContext()); mControlWrapper.toggleFullScreen(activity); } public void setListener(AdControlListener listener) { this.mListener = listener; } public interface AdControlListener { void onAdClick(); void onSkipAd(); } }
Doikki/DKVideoPlayer
dkplayer-sample/src/main/java/xyz/doikki/dkplayer/widget/component/AdControlView.java
1,178
//暂未实现全面屏适配逻辑,需要你自己补全
line_comment
zh-cn
package xyz.doikki.dkplayer.widget.component; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import xyz.doikki.dkplayer.R; import xyz.doikki.videoplayer.controller.IControlComponent; import xyz.doikki.videoplayer.controller.ControlWrapper; import xyz.doikki.videoplayer.player.VideoView; import xyz.doikki.videoplayer.util.PlayerUtils; public class AdControlView extends FrameLayout implements IControlComponent, View.OnClickListener { protected TextView mAdTime, mAdDetail; protected ImageView mBack, mVolume, mFullScreen, mPlayButton; protected AdControlListener mListener; private ControlWrapper mControlWrapper; public AdControlView(@NonNull Context context) { super(context); } public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } { LayoutInflater.from(getContext()).inflate(R.layout.layout_ad_control_view, this, true); mAdTime = findViewById(R.id.ad_time); mAdDetail = findViewById(R.id.ad_detail); mAdDetail.setText("了解详情>"); mBack = findViewById(R.id.back); mBack.setVisibility(GONE); mVolume = findViewById(R.id.iv_volume); mFullScreen = findViewById(R.id.fullscreen); mPlayButton = findViewById(R.id.iv_play); mPlayButton.setOnClickListener(this); mAdTime.setOnClickListener(this); mAdDetail.setOnClickListener(this); mBack.setOnClickListener(this); mVolume.setOnClickListener(this); mFullScreen.setOnClickListener(this); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (mListener != null) mListener.onAdClick(); } }); } @Override public void attach(@NonNull ControlWrapper controlWrapper) { mControlWrapper = controlWrapper; } @Override public View getView() { return this; } @Override public void onVisibilityChanged(boolean isVisible, Animation anim) { } @Override public void onPlayStateChanged(int playState) { switch (playState) { case VideoView.STATE_PLAYING: mControlWrapper.startProgress(); mPlayButton.setSelected(true); break; case VideoView.STATE_PAUSED: mPlayButton.setSelected(false); break; } } @Override public void onPlayerStateChanged(int playerState) { switch (playerState) { case VideoView.PLAYER_NORMAL: mBack.setVisibility(GONE); mFullScreen.setSelected(false); break; case VideoView.PLAYER_FULL_SCREEN: mBack.setVisibility(VISIBLE); mFullScreen.setSelected(true); break; } //暂未 <SUF> } @Override public void setProgress(int duration, int position) { if (mAdTime != null) mAdTime.setText(String.format("%s | 跳过", (duration - position) / 1000)); } @Override public void onLockStateChanged(boolean isLocked) { } @Override public void onClick(View v) { int id = v.getId(); if (id == R.id.back | id == R.id.fullscreen) { toggleFullScreen(); } else if (id == R.id.iv_volume) { doMute(); } else if (id == R.id.ad_detail) { if (mListener != null) mListener.onAdClick(); } else if (id == R.id.ad_time) { if (mListener != null) mListener.onSkipAd(); } else if (id == R.id.iv_play) { mControlWrapper.togglePlay(); } } private void doMute() { mControlWrapper.setMute(!mControlWrapper.isMute()); mVolume.setImageResource(mControlWrapper.isMute() ? R.drawable.dkplayer_ic_action_volume_up : R.drawable.dkplayer_ic_action_volume_off); } /** * 横竖屏切换 */ private void toggleFullScreen() { Activity activity = PlayerUtils.scanForActivity(getContext()); mControlWrapper.toggleFullScreen(activity); } public void setListener(AdControlListener listener) { this.mListener = listener; } public interface AdControlListener { void onAdClick(); void onSkipAd(); } }
1
21
1
20671_6
package com.baobaotao.web; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.management.RuntimeErrorException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.FileCopyUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.ValidationUtils; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.WebUtils; import com.baobaotao.UserService; import com.baobaotao.domain.Dept; import com.baobaotao.domain.User; @Controller @RequestMapping("/user") // @SessionAttributes(value={"user","user1","user2"},types={Dept.class}) public class UserController { @Autowired private UserService userService; @RequestMapping(method = RequestMethod.POST) public ModelAndView createUser(User user) { userService.createUser(user); ModelAndView mav = new ModelAndView(); mav.setViewName("user/createSuccess"); mav.addObject("user", user); return mav; } @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") public String register(@ModelAttribute("user") User user) { return "user/register"; } @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") public String test1(@RequestParam("userId") String userId) { // do sth return "user/test1"; } @RequestMapping(value = "/show", headers = "content-type=text/*") public String test2(@RequestParam("userId") String userId) { // do sth return "user/test2"; } // ①请求参数按名称匹配的方式绑定到方法入参中,方法返回对应的字符串代表逻辑视图名 @RequestMapping(value = "/handle1") public String handle1(@RequestParam("userName") String userName, @RequestParam("password") String password, @RequestParam("realName") String realName) { return "success"; } // ②将Cooke值及报文头属性绑定到入参中、方法返回ModelAndView @RequestMapping(value = "/handle2") public ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId, @RequestHeader("Accept-Language") String accpetLanguage) { ModelAndView mav = new ModelAndView(); mav.setViewName("success"); mav.addObject("user", new User()); return mav; } // ③请求参数按名称匹配的方式绑定到user的属性中、方法返回对应的字符串代表逻辑视图名 @RequestMapping(value = "/handle3") public String handle3(User user) { return "success"; } // ④直接将HTTP请求对象传递给处理方法、方法返回对应的字符串代表逻辑视图名 @RequestMapping(value = "/handle4") public String handle4(HttpServletRequest request) { return "success"; } @RequestMapping(value = "/handle11") public String handle11( @RequestParam(value = "userName", required = false) String userName, @RequestParam("age") int age) { return "success"; } @RequestMapping(value = "/handle12") public String handle12( @CookieValue(value = "sessionId", required = false) String sessionId, @RequestParam("age") int age) { return "success"; } @RequestMapping(value = "/handle13") public String handle13(@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive") long keepAlive) { return "success"; } @RequestMapping(value = "/handle14") public String handle14(User user) { return "success"; } @RequestMapping(value = "/handle21") public void handle21(HttpServletRequest request, HttpServletResponse response) { String userName = request.getParameter("userName"); response.addCookie(new Cookie("userName", userName)); } @RequestMapping(value = "/handle22") public ModelAndView handle22(HttpServletRequest request) { String userName = WebUtils.findParameterValue(request, "userName"); ModelAndView mav = new ModelAndView(); mav.setViewName("success"); mav.addObject("userName", userName); return mav; } @RequestMapping(value = "/handle23") public String handle23(HttpSession session) { session.setAttribute("sessionId", 1234); return "success"; } @RequestMapping(value = "/success") public String success() { return "success"; } @RequestMapping(value = "/fail") public String fail() { return "fail"; } @RequestMapping(value = "/handle24") public String handle24(HttpServletRequest request, @RequestParam("userName") String userName) { return "success"; } @RequestMapping(value = "/handle25") public String handle25(WebRequest request) { String userName = request.getParameter("userName"); return "success"; } @RequestMapping(value = "/handle31") public void handle31(OutputStream os) throws IOException { Resource res = new ClassPathResource("/image.jpg"); FileCopyUtils.copy(res.getInputStream(), os); } // @RequestMapping(value="/{userId}") // public ModelAndView showDetail(@PathVariable("userId") String userId){ // ModelAndView mav = new ModelAndView(); // mav.setViewName("user/showDetail"); // mav.addObject("user", userService.getUserById(userId)); // return mav; // } @RequestMapping(value = "/handle41") public String handle41(@RequestBody String body) { System.out.println(body); return "success"; } @ResponseBody @RequestMapping(value = "/handle42/{imageId}") public byte[] handle42(@PathVariable("imageId") String imageId) throws IOException { System.out.println("load image of " + imageId); Resource res = new ClassPathResource("/image.jpg"); byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream()); return fileData; } @RequestMapping(value = "/handle43") public String handle43(HttpEntity<String> requestEntity) { long contentLen = requestEntity.getHeaders().getContentLength(); System.out.println("user:" + requestEntity.getBody()); return "success"; } @RequestMapping(value = "/handle44/{imageId}") public ResponseEntity<byte[]> handle44( @PathVariable("imageId") String imageId) throws Throwable { Resource res = new ClassPathResource("/image.jpg"); byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream()); ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>( fileData, HttpStatus.OK); return responseEntity; } @RequestMapping(value = "/handle51") public ResponseEntity<User> handle51(HttpEntity<User> requestEntity) { User user = requestEntity.getBody(); user.setUserId("1000"); return new ResponseEntity<User>(user, HttpStatus.OK); } @RequestMapping(value = "/handle61") public String handle61(@ModelAttribute("user") User user) { user.setUserId("1000"); return "/user/createSuccess"; } @RequestMapping(value = "/handle62") public String handle62(@ModelAttribute("user") User user) { user.setUserName("tom"); return "/user/showUser"; } @RequestMapping(value = "/handle63") public String handle63(ModelMap modelMap) { User user = (User) modelMap.get("user"); user.setUserName("tom"); modelMap.addAttribute("testAttr", "value1"); return "/user/showUser"; } @ModelAttribute("user") public User getUser() { User user = new User(); user.setUserId("1001"); user.setUserName("<>"); return user; } @ModelAttribute("user1") public User getUser1() { User user = new User(); user.setUserId("1"); return user; } @ModelAttribute("user2") public User getUser2() { User user = new User(); user.setUserId("1"); return user; } @ModelAttribute("dept") public Dept getDept() { Dept dept = new Dept(); return dept; } @RequestMapping(value = "/handle71") public String handle71(@ModelAttribute("user") User user) { user.setUserName("John"); return "redirect:handle72.html"; } @RequestMapping(value = "/handle72") public String handle72(ModelMap modelMap, SessionStatus sessionStatus) { User user = (User) modelMap.get("user"); if (user != null) { user.setUserName("Jetty"); sessionStatus.setComplete(); } return "/user/showUser"; } @RequestMapping(value = "/handle81") public String handle81(@RequestParam("user") User user, ModelMap modelMap) { modelMap.put("user", user); return "/user/showUser"; } @RequestMapping(value = "/register2") public String register2(User user) { return "/user/register2"; } @RequestMapping(value = "/handle82") public String handle82(User user) { return "/user/showUser"; } @RequestMapping(value = "/register3") public String register3() { return "/user/register3"; } @RequestMapping(value = "/register4") public String register4() { return "/user/register4"; } @RequestMapping(value = "/handle91") public String handle91(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, ModelMap mm) { if (bindingResult.hasErrors()) { return "/user/register3"; } else { return "/user/showUser"; } } @RequestMapping(value = "/handle92") public String handle92(@ModelAttribute("user") User user, BindingResult bindingResult) { ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "userName", "required"); if ("aaaa".equalsIgnoreCase(user.getUserName())) { bindingResult.rejectValue("userName", "reserved"); } if (bindingResult.hasErrors()) { return "/user/register4"; } else { return "/user/showUser"; } } @RequestMapping(value = "/welcome") public String handle100() { return "/user/welcome"; } @RequestMapping(value = "/showUserList") public String showUserList(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "user/userList"; } @RequestMapping(value = "/showUserListByFtl") public String showUserListInFtl(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListFtl"; } @RequestMapping(value = "/showUserListByXls") public String showUserListInExcel(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListExcel"; } @RequestMapping(value = "/showUserListByPdf") public String showUserListInPdf(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListPdf"; } @RequestMapping(value = "/showUserListByXml") public String showUserListInXml(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListXml"; } @RequestMapping(value = "/showUserListByJson") public String showUserListInJson(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListJson"; } @RequestMapping(value = "/showUserListByJson1") public String showUserListInJson1(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆1"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListJson1"; } @RequestMapping(value = "/showUserListByI18n") public String showUserListInI18n(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆1"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListi18n"; } @RequestMapping(value = "/showUserListMix") public String showUserListMix(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆1"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListMix"; } @RequestMapping(value = "/uploadPage") public String updatePage() { return "uploadPage"; } @RequestMapping(value = "/upload") public String updateThumb(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws Exception{ if (!file.isEmpty()) { file.transferTo(new File("d:/temp/"+file.getOriginalFilename())); return "redirect:success.html"; }else{ return "redirect:fail.html"; } } @RequestMapping(value = "/throwException") public String throwException() { if(2>1){ throw new RuntimeException("ddd"); } return "success"; } @ExceptionHandler(RuntimeException.class) public String handleException(RuntimeException re, HttpServletRequest request) { return "forward:/error.jsp"; } @RequestMapping(value = "/notFound") public String notFound() { return "successdddd"; } @ResponseStatus(HttpStatus.NOT_FOUND) public String notFound(HttpServletRequest request) { return "forward:/error.jsp"; } @InitBinder public void initBinder(WebDataBinder binder) { // binder.registerCustomEditor(User.class, new UserEditor()); // binder.setValidator(new UserValidator()); } }
DoingLee/Reading--Spring-3.x-enterprise-application-development
chapter15/src/com/baobaotao/web/UserController.java
5,298
// ④直接将HTTP请求对象传递给处理方法、方法返回对应的字符串代表逻辑视图名
line_comment
zh-cn
package com.baobaotao.web; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.management.RuntimeErrorException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.FileSystemResource; import org.springframework.core.io.Resource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.FileCopyUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.ValidationUtils; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.CookieValue; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.support.SessionStatus; import org.springframework.web.context.request.WebRequest; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.util.WebUtils; import com.baobaotao.UserService; import com.baobaotao.domain.Dept; import com.baobaotao.domain.User; @Controller @RequestMapping("/user") // @SessionAttributes(value={"user","user1","user2"},types={Dept.class}) public class UserController { @Autowired private UserService userService; @RequestMapping(method = RequestMethod.POST) public ModelAndView createUser(User user) { userService.createUser(user); ModelAndView mav = new ModelAndView(); mav.setViewName("user/createSuccess"); mav.addObject("user", user); return mav; } @RequestMapping(value = "/register", method = RequestMethod.GET, params = "!myParam") public String register(@ModelAttribute("user") User user) { return "user/register"; } @RequestMapping(value = "/delete", method = RequestMethod.POST, params = "userId") public String test1(@RequestParam("userId") String userId) { // do sth return "user/test1"; } @RequestMapping(value = "/show", headers = "content-type=text/*") public String test2(@RequestParam("userId") String userId) { // do sth return "user/test2"; } // ①请求参数按名称匹配的方式绑定到方法入参中,方法返回对应的字符串代表逻辑视图名 @RequestMapping(value = "/handle1") public String handle1(@RequestParam("userName") String userName, @RequestParam("password") String password, @RequestParam("realName") String realName) { return "success"; } // ②将Cooke值及报文头属性绑定到入参中、方法返回ModelAndView @RequestMapping(value = "/handle2") public ModelAndView handle2(@CookieValue("JSESSIONID") String sessionId, @RequestHeader("Accept-Language") String accpetLanguage) { ModelAndView mav = new ModelAndView(); mav.setViewName("success"); mav.addObject("user", new User()); return mav; } // ③请求参数按名称匹配的方式绑定到user的属性中、方法返回对应的字符串代表逻辑视图名 @RequestMapping(value = "/handle3") public String handle3(User user) { return "success"; } // ④直 <SUF> @RequestMapping(value = "/handle4") public String handle4(HttpServletRequest request) { return "success"; } @RequestMapping(value = "/handle11") public String handle11( @RequestParam(value = "userName", required = false) String userName, @RequestParam("age") int age) { return "success"; } @RequestMapping(value = "/handle12") public String handle12( @CookieValue(value = "sessionId", required = false) String sessionId, @RequestParam("age") int age) { return "success"; } @RequestMapping(value = "/handle13") public String handle13(@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive") long keepAlive) { return "success"; } @RequestMapping(value = "/handle14") public String handle14(User user) { return "success"; } @RequestMapping(value = "/handle21") public void handle21(HttpServletRequest request, HttpServletResponse response) { String userName = request.getParameter("userName"); response.addCookie(new Cookie("userName", userName)); } @RequestMapping(value = "/handle22") public ModelAndView handle22(HttpServletRequest request) { String userName = WebUtils.findParameterValue(request, "userName"); ModelAndView mav = new ModelAndView(); mav.setViewName("success"); mav.addObject("userName", userName); return mav; } @RequestMapping(value = "/handle23") public String handle23(HttpSession session) { session.setAttribute("sessionId", 1234); return "success"; } @RequestMapping(value = "/success") public String success() { return "success"; } @RequestMapping(value = "/fail") public String fail() { return "fail"; } @RequestMapping(value = "/handle24") public String handle24(HttpServletRequest request, @RequestParam("userName") String userName) { return "success"; } @RequestMapping(value = "/handle25") public String handle25(WebRequest request) { String userName = request.getParameter("userName"); return "success"; } @RequestMapping(value = "/handle31") public void handle31(OutputStream os) throws IOException { Resource res = new ClassPathResource("/image.jpg"); FileCopyUtils.copy(res.getInputStream(), os); } // @RequestMapping(value="/{userId}") // public ModelAndView showDetail(@PathVariable("userId") String userId){ // ModelAndView mav = new ModelAndView(); // mav.setViewName("user/showDetail"); // mav.addObject("user", userService.getUserById(userId)); // return mav; // } @RequestMapping(value = "/handle41") public String handle41(@RequestBody String body) { System.out.println(body); return "success"; } @ResponseBody @RequestMapping(value = "/handle42/{imageId}") public byte[] handle42(@PathVariable("imageId") String imageId) throws IOException { System.out.println("load image of " + imageId); Resource res = new ClassPathResource("/image.jpg"); byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream()); return fileData; } @RequestMapping(value = "/handle43") public String handle43(HttpEntity<String> requestEntity) { long contentLen = requestEntity.getHeaders().getContentLength(); System.out.println("user:" + requestEntity.getBody()); return "success"; } @RequestMapping(value = "/handle44/{imageId}") public ResponseEntity<byte[]> handle44( @PathVariable("imageId") String imageId) throws Throwable { Resource res = new ClassPathResource("/image.jpg"); byte[] fileData = FileCopyUtils.copyToByteArray(res.getInputStream()); ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>( fileData, HttpStatus.OK); return responseEntity; } @RequestMapping(value = "/handle51") public ResponseEntity<User> handle51(HttpEntity<User> requestEntity) { User user = requestEntity.getBody(); user.setUserId("1000"); return new ResponseEntity<User>(user, HttpStatus.OK); } @RequestMapping(value = "/handle61") public String handle61(@ModelAttribute("user") User user) { user.setUserId("1000"); return "/user/createSuccess"; } @RequestMapping(value = "/handle62") public String handle62(@ModelAttribute("user") User user) { user.setUserName("tom"); return "/user/showUser"; } @RequestMapping(value = "/handle63") public String handle63(ModelMap modelMap) { User user = (User) modelMap.get("user"); user.setUserName("tom"); modelMap.addAttribute("testAttr", "value1"); return "/user/showUser"; } @ModelAttribute("user") public User getUser() { User user = new User(); user.setUserId("1001"); user.setUserName("<>"); return user; } @ModelAttribute("user1") public User getUser1() { User user = new User(); user.setUserId("1"); return user; } @ModelAttribute("user2") public User getUser2() { User user = new User(); user.setUserId("1"); return user; } @ModelAttribute("dept") public Dept getDept() { Dept dept = new Dept(); return dept; } @RequestMapping(value = "/handle71") public String handle71(@ModelAttribute("user") User user) { user.setUserName("John"); return "redirect:handle72.html"; } @RequestMapping(value = "/handle72") public String handle72(ModelMap modelMap, SessionStatus sessionStatus) { User user = (User) modelMap.get("user"); if (user != null) { user.setUserName("Jetty"); sessionStatus.setComplete(); } return "/user/showUser"; } @RequestMapping(value = "/handle81") public String handle81(@RequestParam("user") User user, ModelMap modelMap) { modelMap.put("user", user); return "/user/showUser"; } @RequestMapping(value = "/register2") public String register2(User user) { return "/user/register2"; } @RequestMapping(value = "/handle82") public String handle82(User user) { return "/user/showUser"; } @RequestMapping(value = "/register3") public String register3() { return "/user/register3"; } @RequestMapping(value = "/register4") public String register4() { return "/user/register4"; } @RequestMapping(value = "/handle91") public String handle91(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, ModelMap mm) { if (bindingResult.hasErrors()) { return "/user/register3"; } else { return "/user/showUser"; } } @RequestMapping(value = "/handle92") public String handle92(@ModelAttribute("user") User user, BindingResult bindingResult) { ValidationUtils.rejectIfEmptyOrWhitespace(bindingResult, "userName", "required"); if ("aaaa".equalsIgnoreCase(user.getUserName())) { bindingResult.rejectValue("userName", "reserved"); } if (bindingResult.hasErrors()) { return "/user/register4"; } else { return "/user/showUser"; } } @RequestMapping(value = "/welcome") public String handle100() { return "/user/welcome"; } @RequestMapping(value = "/showUserList") public String showUserList(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "user/userList"; } @RequestMapping(value = "/showUserListByFtl") public String showUserListInFtl(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListFtl"; } @RequestMapping(value = "/showUserListByXls") public String showUserListInExcel(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListExcel"; } @RequestMapping(value = "/showUserListByPdf") public String showUserListInPdf(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListPdf"; } @RequestMapping(value = "/showUserListByXml") public String showUserListInXml(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListXml"; } @RequestMapping(value = "/showUserListByJson") public String showUserListInJson(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListJson"; } @RequestMapping(value = "/showUserListByJson1") public String showUserListInJson1(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆1"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListJson1"; } @RequestMapping(value = "/showUserListByI18n") public String showUserListInI18n(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆1"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListi18n"; } @RequestMapping(value = "/showUserListMix") public String showUserListMix(ModelMap mm) { Calendar calendar = new GregorianCalendar(); List<User> userList = new ArrayList<User>(); User user1 = new User(); user1.setUserName("tom"); user1.setRealName("汤姆1"); calendar.set(1980, 1, 1); user1.setBirthday(calendar.getTime()); User user2 = new User(); user2.setUserName("john"); user2.setRealName("约翰"); user2.setBirthday(calendar.getTime()); userList.add(user1); userList.add(user2); mm.addAttribute("userList", userList); return "userListMix"; } @RequestMapping(value = "/uploadPage") public String updatePage() { return "uploadPage"; } @RequestMapping(value = "/upload") public String updateThumb(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) throws Exception{ if (!file.isEmpty()) { file.transferTo(new File("d:/temp/"+file.getOriginalFilename())); return "redirect:success.html"; }else{ return "redirect:fail.html"; } } @RequestMapping(value = "/throwException") public String throwException() { if(2>1){ throw new RuntimeException("ddd"); } return "success"; } @ExceptionHandler(RuntimeException.class) public String handleException(RuntimeException re, HttpServletRequest request) { return "forward:/error.jsp"; } @RequestMapping(value = "/notFound") public String notFound() { return "successdddd"; } @ResponseStatus(HttpStatus.NOT_FOUND) public String notFound(HttpServletRequest request) { return "forward:/error.jsp"; } @InitBinder public void initBinder(WebDataBinder binder) { // binder.registerCustomEditor(User.class, new UserEditor()); // binder.setValidator(new UserValidator()); } }
0
40
0
52982_0
import java.util.*; import java.lang.Math; class Point2D { int X, Y; public Point2D() { //无形参的构造方法,一定要有 } public Point2D(int x,int y) { this.X=x; this.Y=y; } public void offset(int a, int b)//2D平移方法 { this.X+=a; this.Y+=b; } public void printInfo() { System.out.println("X= "+this.X+"\nY= "+this.Y); } public void distance(Point2D p) { double DT=1; DT*=(this.X-p.X)*(this.X-p.X)+(this.Y-p.Y)*(this.Y-p.Y); System.out.println("2D 距离:"+Math.sqrt(DT)); } } class Point3D extends Point2D { int Z; public Point3D() { //无形参的构造方法,一定要有 } public Point3D(int x,int y,int z) { this.X=x; this.Y=y; this.Z=z; } Point3D(Point2D p,int z) { this.X=p.X; this.Y=p.Y; this.Z=z; } public void offset(int a, int b,int c)//3D平移方法 { this.X+=a; this.Y+=b; this.Z+=c; } public void printInfo() { System.out.println("X= "+this.X+"\nY= "+this.Y+"\nZ= "+this.Z); } public void distance(Point3D p) { double DT=1; DT*=(this.X-p.X)*(this.X-p.X)+(this.Y-p.Y)*(this.Y-p.Y)+(this.Z-p.Z)*(this.Z-p.Z); System.out.println("3D 距离:"+Math.sqrt(DT)); } } public class Alex { public static void main(String args[]) { System.out.print("*****录入信息*****\n"); Scanner cin = new Scanner(System.in); int x[]=new int[2]; int y[]=new int[2]; int z[]=new int[2]; for(int i=1;i<3;i++) { System.out.print("录入第 "+ i +" 个 2D 平面坐标\n 输入横坐标X:"); x[i-1]=cin.nextInt(); System.out.print(" 输入纵坐标Y:"); y[i-1]=cin.nextInt(); } Point2D _2Dp1=new Point2D(x[0],y[0]); Point2D _2Dp2=new Point2D(x[1],y[1]); _2Dp1.printInfo(); _2Dp2.printInfo(); System.out.println("现在将 2D 平面图,3D 化,请给出 竖坐标Z的值"); for(int i=1;i<3;i++) { System.out.print("录入第 "+ i +" 个 3D 平面坐标\n 输入竖坐标Z:"); z[i-1]=cin.nextInt(); } Point3D _3Dp1=new Point3D(_2Dp1,z[0]); Point3D _3Dp2=new Point3D(_2Dp2,z[1]); _3Dp1.printInfo(); _3Dp2.printInfo(); System.out.println("平移 2D 图形:"); for(int i=1;i<3;i++) { System.out.print("录入第 "+ i +" 个 2D 图形的平移量\n 输入横坐标X的平移量:"); x[i-1]=cin.nextInt(); System.out.print(" 输入纵坐标Y的平移量:"); y[i-1]=cin.nextInt(); } _2Dp1.offset(x[0], y[0]); _2Dp2.offset(x[1], y[1]); _2Dp1.printInfo(); _2Dp2.printInfo(); for(int i=1;i<3;i++) { System.out.print("录入第 "+ i +" 个 3D 图形的平移量\n 输入竖坐标Z的平移量:"); z[i-1]=cin.nextInt(); } _3Dp1.offset(x[0],y[0],z[0]); _3Dp2.offset(x[1],y[1],z[1]); _3Dp1.printInfo(); _3Dp2.printInfo(); _2Dp1.distance(_2Dp2); _3Dp1.distance(_3Dp2); } }
DolorHunter/hfut-exp-archived
Java_exp/exp2/Alex.java
1,216
//无形参的构造方法,一定要有
line_comment
zh-cn
import java.util.*; import java.lang.Math; class Point2D { int X, Y; public Point2D() { //无形 <SUF> } public Point2D(int x,int y) { this.X=x; this.Y=y; } public void offset(int a, int b)//2D平移方法 { this.X+=a; this.Y+=b; } public void printInfo() { System.out.println("X= "+this.X+"\nY= "+this.Y); } public void distance(Point2D p) { double DT=1; DT*=(this.X-p.X)*(this.X-p.X)+(this.Y-p.Y)*(this.Y-p.Y); System.out.println("2D 距离:"+Math.sqrt(DT)); } } class Point3D extends Point2D { int Z; public Point3D() { //无形参的构造方法,一定要有 } public Point3D(int x,int y,int z) { this.X=x; this.Y=y; this.Z=z; } Point3D(Point2D p,int z) { this.X=p.X; this.Y=p.Y; this.Z=z; } public void offset(int a, int b,int c)//3D平移方法 { this.X+=a; this.Y+=b; this.Z+=c; } public void printInfo() { System.out.println("X= "+this.X+"\nY= "+this.Y+"\nZ= "+this.Z); } public void distance(Point3D p) { double DT=1; DT*=(this.X-p.X)*(this.X-p.X)+(this.Y-p.Y)*(this.Y-p.Y)+(this.Z-p.Z)*(this.Z-p.Z); System.out.println("3D 距离:"+Math.sqrt(DT)); } } public class Alex { public static void main(String args[]) { System.out.print("*****录入信息*****\n"); Scanner cin = new Scanner(System.in); int x[]=new int[2]; int y[]=new int[2]; int z[]=new int[2]; for(int i=1;i<3;i++) { System.out.print("录入第 "+ i +" 个 2D 平面坐标\n 输入横坐标X:"); x[i-1]=cin.nextInt(); System.out.print(" 输入纵坐标Y:"); y[i-1]=cin.nextInt(); } Point2D _2Dp1=new Point2D(x[0],y[0]); Point2D _2Dp2=new Point2D(x[1],y[1]); _2Dp1.printInfo(); _2Dp2.printInfo(); System.out.println("现在将 2D 平面图,3D 化,请给出 竖坐标Z的值"); for(int i=1;i<3;i++) { System.out.print("录入第 "+ i +" 个 3D 平面坐标\n 输入竖坐标Z:"); z[i-1]=cin.nextInt(); } Point3D _3Dp1=new Point3D(_2Dp1,z[0]); Point3D _3Dp2=new Point3D(_2Dp2,z[1]); _3Dp1.printInfo(); _3Dp2.printInfo(); System.out.println("平移 2D 图形:"); for(int i=1;i<3;i++) { System.out.print("录入第 "+ i +" 个 2D 图形的平移量\n 输入横坐标X的平移量:"); x[i-1]=cin.nextInt(); System.out.print(" 输入纵坐标Y的平移量:"); y[i-1]=cin.nextInt(); } _2Dp1.offset(x[0], y[0]); _2Dp2.offset(x[1], y[1]); _2Dp1.printInfo(); _2Dp2.printInfo(); for(int i=1;i<3;i++) { System.out.print("录入第 "+ i +" 个 3D 图形的平移量\n 输入竖坐标Z的平移量:"); z[i-1]=cin.nextInt(); } _3Dp1.offset(x[0],y[0],z[0]); _3Dp2.offset(x[1],y[1],z[1]); _3Dp1.printInfo(); _3Dp2.printInfo(); _2Dp1.distance(_2Dp2); _3Dp1.distance(_3Dp2); } }
0
15
0