file_id
stringlengths
5
9
content
stringlengths
24
16.1k
repo
stringlengths
8
84
path
stringlengths
7
167
token_length
int64
18
3.48k
original_comment
stringlengths
5
2.57k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
11
16.1k
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
14
3.27k
comment-tokens-Qwen/Qwen2-7B
int64
2
1.74k
file-tokens-bigcode/starcoder2-7b
int64
18
3.48k
comment-tokens-bigcode/starcoder2-7b
int64
2
2.11k
file-tokens-google/codegemma-7b
int64
14
3.57k
comment-tokens-google/codegemma-7b
int64
2
1.75k
file-tokens-ibm-granite/granite-8b-code-base
int64
18
3.48k
comment-tokens-ibm-granite/granite-8b-code-base
int64
2
2.11k
file-tokens-meta-llama/CodeLlama-7b-hf
int64
31
3.93k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
2.71k
excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool
2 classes
excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool
2 classes
excluded-based-on-tokenizer-google/codegemma-7b
bool
2 classes
excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool
2 classes
excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool
2 classes
include-for-inference
bool
2 classes
52073_1
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Encrypt { /** * @author crazykay * @see "在异或运算中,对于两个变量 x,y 满足 (x^y^y)==x" */ // 加密数值(可随意设定) private static final int PASSWORD = 01234567; // 设置加密文件后缀(可随意设定) private static final String SUFFIX = ".enc"; // path指定加密文件路径 public void doEncrypt(String path) { FileInputStream in = null; FileOutputStream out = null; try { int tmp = 0; File inFile = new File(path); in = new FileInputStream(inFile); File outFile = new File(path + SUFFIX); out = new FileOutputStream(outFile); while ((tmp = in.read()) != -1) { // 加密处理 out.write(tmp ^ PASSWORD); } } catch (FileNotFoundException e) { System.err.println("文件不存在!!"); } catch (IOException e) { System.err.println("文件读取异常!!"); } finally { // finally块关闭流操作 try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { System.err.println("关闭流失败!!"); } } } // path指定解密文件路径 public void doDecrypt(String path) { int index = path.lastIndexOf(SUFFIX); if (index != path.length() - SUFFIX.length()) { System.err.println("文件类型不正确!!"); return; } FileInputStream in = null; FileOutputStream out = null; try { int tmp = 0; File inFile = new File(path); in = new FileInputStream(inFile); String name = path.substring(0, index); File outFile = new File(name); out = new FileOutputStream(outFile); while ((tmp = in.read()) != -1) { // 再次异或PASSWORD实现解密 out.write(tmp ^ PASSWORD); } } catch (FileNotFoundException e) { System.err.println("文件不存在!!"); } catch (IOException e) { System.err.println("文件读取异常!!"); } finally { // finally块关闭流操作 try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { System.err.println("关闭流失败!!"); } } } public static void main(String[] args) { Encrypt encrypt = new Encrypt(); // 第一个参数指定操作(加密/解密) // 第二个参数制定文件所在路径 if (args.length != 2) { System.err.println("参数设置不正确"); System.out.println(); System.out.println("java Encrypt [OPTION] [FILE PATH]"); System.out.println("\tencrypt\t-e\t加密\n\tdecrypt\t-d\t解密"); return; } switch (args[0]) { case "encrypt": encrypt.doEncrypt(args[1]); break; case "-e": encrypt.doEncrypt(args[1]); break; case "decrypt": encrypt.doDecrypt(args[1]); break; case "-d": encrypt.doDecrypt(args[1]); break; default: System.err.println("参数设置不正确"); System.out.println(); System.out.println("java Encrypt [OPTION] [FILE PATH]"); System.out.println("\tencrypt\t-e\t加密\n\tdecrypt\t-d\t解密"); break; } } }
crazykay/JavaSimplestEncrypt
src/Encrypt.java
1,035
// 加密数值(可随意设定)
line_comment
zh-cn
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class Encrypt { /** * @author crazykay * @see "在异或运算中,对于两个变量 x,y 满足 (x^y^y)==x" */ // 加密 <SUF> private static final int PASSWORD = 01234567; // 设置加密文件后缀(可随意设定) private static final String SUFFIX = ".enc"; // path指定加密文件路径 public void doEncrypt(String path) { FileInputStream in = null; FileOutputStream out = null; try { int tmp = 0; File inFile = new File(path); in = new FileInputStream(inFile); File outFile = new File(path + SUFFIX); out = new FileOutputStream(outFile); while ((tmp = in.read()) != -1) { // 加密处理 out.write(tmp ^ PASSWORD); } } catch (FileNotFoundException e) { System.err.println("文件不存在!!"); } catch (IOException e) { System.err.println("文件读取异常!!"); } finally { // finally块关闭流操作 try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { System.err.println("关闭流失败!!"); } } } // path指定解密文件路径 public void doDecrypt(String path) { int index = path.lastIndexOf(SUFFIX); if (index != path.length() - SUFFIX.length()) { System.err.println("文件类型不正确!!"); return; } FileInputStream in = null; FileOutputStream out = null; try { int tmp = 0; File inFile = new File(path); in = new FileInputStream(inFile); String name = path.substring(0, index); File outFile = new File(name); out = new FileOutputStream(outFile); while ((tmp = in.read()) != -1) { // 再次异或PASSWORD实现解密 out.write(tmp ^ PASSWORD); } } catch (FileNotFoundException e) { System.err.println("文件不存在!!"); } catch (IOException e) { System.err.println("文件读取异常!!"); } finally { // finally块关闭流操作 try { if (in != null) { in.close(); } if (out != null) { out.close(); } } catch (IOException e) { System.err.println("关闭流失败!!"); } } } public static void main(String[] args) { Encrypt encrypt = new Encrypt(); // 第一个参数指定操作(加密/解密) // 第二个参数制定文件所在路径 if (args.length != 2) { System.err.println("参数设置不正确"); System.out.println(); System.out.println("java Encrypt [OPTION] [FILE PATH]"); System.out.println("\tencrypt\t-e\t加密\n\tdecrypt\t-d\t解密"); return; } switch (args[0]) { case "encrypt": encrypt.doEncrypt(args[1]); break; case "-e": encrypt.doEncrypt(args[1]); break; case "decrypt": encrypt.doDecrypt(args[1]); break; case "-d": encrypt.doDecrypt(args[1]); break; default: System.err.println("参数设置不正确"); System.out.println(); System.out.println("java Encrypt [OPTION] [FILE PATH]"); System.out.println("\tencrypt\t-e\t加密\n\tdecrypt\t-d\t解密"); break; } } }
false
852
9
1,035
12
1,014
9
1,035
12
1,384
15
false
false
false
false
false
true
32352_15
package org.ninetripods.mq.study.customViewGroup.fiveRings; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import org.ninetripods.mq.study.util.DpUtil; /** * Created by MQ on 2016/12/16. */ public class CustomFiveRings extends ViewGroup { private Context mContext; private TextPaint mPaint; private int startX;//圆环起始X轴 private int startY;//圆环起始Y轴 private int mWidth;//ViewGroup的宽 private int mHeight;//ViewGroup的高 public CustomFiveRings(Context context) { this(context, null); } public CustomFiveRings(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomFiveRings(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setBackgroundColor(Color.TRANSPARENT); mContext = context; mPaint = new TextPaint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setTextSize(50); mPaint.setColor(Color.BLACK); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //触发所有子View的onMeasure函数去测量宽高 measureChildren(widthMeasureSpec, heightMeasureSpec); //MeasureSpec封装了父View传递给子View的布局要求 int wMode = MeasureSpec.getMode(widthMeasureSpec); int wSize = MeasureSpec.getSize(widthMeasureSpec); int hMode = MeasureSpec.getMode(heightMeasureSpec); int hSize = MeasureSpec.getSize(heightMeasureSpec); switch (wMode) { case MeasureSpec.EXACTLY: mWidth = wSize; break; case MeasureSpec.AT_MOST: //这里应该先计算所有子view的宽度,暂时先写死 mWidth = wSize; break; case MeasureSpec.UNSPECIFIED: break; } switch (hMode) { case MeasureSpec.EXACTLY: mHeight = hSize; break; case MeasureSpec.AT_MOST: //这里应该先计算所有子view的高度,暂时先写死 mHeight = hSize; // mHeight = getCircleHeight() / 2 * 3; break; case MeasureSpec.UNSPECIFIED: break; } setMeasuredDimension(mWidth, mHeight); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childNum = getChildCount(); startX = startY = 0; int gap = 10;//同一行圆圈之间的间隔 int screenWidth = DpUtil.getScreenSizeWidth(mContext); int firstTotalWidth = 0;//第一行子View的总宽度 int secondTotalWidth = 0;//第二行子View的总宽度 for (int i = 0; i < childNum; i++) { View childView = getChildAt(i); int childWidth = childView.getMeasuredWidth(); if (i <= 2) { //前三个总宽度 firstTotalWidth += childWidth; } else { //后两个总宽度 secondTotalWidth += childWidth; } } int leftFMargin = (screenWidth - firstTotalWidth - gap * 2) / 2; int leftSMargin = (screenWidth - secondTotalWidth - gap) / 2; for (int i = 0; i < childNum; i++) { View childView = getChildAt(i); int childWidth = childView.getMeasuredWidth(); int childHeight = childView.getMeasuredHeight(); if (i <= 2) { //排列前三个圆圈 if (i == 0) { childView.layout(leftFMargin + startX, startY, leftFMargin + startX + childWidth, startY + childHeight); startX += childWidth; } else { childView.layout(leftFMargin + startX + gap, startY, leftFMargin + startX + gap + childWidth, startY + childHeight); startX += (childWidth + gap); } if (i == 2) { startX = 0; startY += childHeight / 2; } } else { //排列后两个圆圈 if (i == 3) { childView.layout(leftSMargin + startX, startY, leftSMargin + startX + childWidth, startY + childHeight); startX += childWidth; } else { childView.layout(leftSMargin + startX + gap, startY, leftSMargin + startX + gap + childWidth, startY + childHeight); startX += (childWidth + gap); } } } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int screenWidth = DpUtil.getScreenSizeWidth(mContext); String upStr = "同一个世界,同一个梦想"; String downStr = "One World,One Dream"; canvas.drawText(upStr, (screenWidth - mPaint.measureText(upStr)) / 2, getCircleHeight() / 2 * 3 + 60, mPaint); canvas.drawText(downStr, (screenWidth - mPaint.measureText(downStr)) / 2, getCircleHeight() / 2 * 3 + 120, mPaint); } /** * 获得圆环高度 * * @return 圆环高度 */ private int getCircleHeight() { //5个圆环大小是一样的,这里就直接取第一个了 View childView = getChildAt(0); return childView.getMeasuredHeight(); } }
crazyqiang/AndroidStudy
app/src/main/java/org/ninetripods/mq/study/customViewGroup/fiveRings/CustomFiveRings.java
1,450
//排列前三个圆圈
line_comment
zh-cn
package org.ninetripods.mq.study.customViewGroup.fiveRings; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import org.ninetripods.mq.study.util.DpUtil; /** * Created by MQ on 2016/12/16. */ public class CustomFiveRings extends ViewGroup { private Context mContext; private TextPaint mPaint; private int startX;//圆环起始X轴 private int startY;//圆环起始Y轴 private int mWidth;//ViewGroup的宽 private int mHeight;//ViewGroup的高 public CustomFiveRings(Context context) { this(context, null); } public CustomFiveRings(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomFiveRings(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setBackgroundColor(Color.TRANSPARENT); mContext = context; mPaint = new TextPaint(); mPaint.setAntiAlias(true); mPaint.setDither(true); mPaint.setTextSize(50); mPaint.setColor(Color.BLACK); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //触发所有子View的onMeasure函数去测量宽高 measureChildren(widthMeasureSpec, heightMeasureSpec); //MeasureSpec封装了父View传递给子View的布局要求 int wMode = MeasureSpec.getMode(widthMeasureSpec); int wSize = MeasureSpec.getSize(widthMeasureSpec); int hMode = MeasureSpec.getMode(heightMeasureSpec); int hSize = MeasureSpec.getSize(heightMeasureSpec); switch (wMode) { case MeasureSpec.EXACTLY: mWidth = wSize; break; case MeasureSpec.AT_MOST: //这里应该先计算所有子view的宽度,暂时先写死 mWidth = wSize; break; case MeasureSpec.UNSPECIFIED: break; } switch (hMode) { case MeasureSpec.EXACTLY: mHeight = hSize; break; case MeasureSpec.AT_MOST: //这里应该先计算所有子view的高度,暂时先写死 mHeight = hSize; // mHeight = getCircleHeight() / 2 * 3; break; case MeasureSpec.UNSPECIFIED: break; } setMeasuredDimension(mWidth, mHeight); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { int childNum = getChildCount(); startX = startY = 0; int gap = 10;//同一行圆圈之间的间隔 int screenWidth = DpUtil.getScreenSizeWidth(mContext); int firstTotalWidth = 0;//第一行子View的总宽度 int secondTotalWidth = 0;//第二行子View的总宽度 for (int i = 0; i < childNum; i++) { View childView = getChildAt(i); int childWidth = childView.getMeasuredWidth(); if (i <= 2) { //前三个总宽度 firstTotalWidth += childWidth; } else { //后两个总宽度 secondTotalWidth += childWidth; } } int leftFMargin = (screenWidth - firstTotalWidth - gap * 2) / 2; int leftSMargin = (screenWidth - secondTotalWidth - gap) / 2; for (int i = 0; i < childNum; i++) { View childView = getChildAt(i); int childWidth = childView.getMeasuredWidth(); int childHeight = childView.getMeasuredHeight(); if (i <= 2) { //排列 <SUF> if (i == 0) { childView.layout(leftFMargin + startX, startY, leftFMargin + startX + childWidth, startY + childHeight); startX += childWidth; } else { childView.layout(leftFMargin + startX + gap, startY, leftFMargin + startX + gap + childWidth, startY + childHeight); startX += (childWidth + gap); } if (i == 2) { startX = 0; startY += childHeight / 2; } } else { //排列后两个圆圈 if (i == 3) { childView.layout(leftSMargin + startX, startY, leftSMargin + startX + childWidth, startY + childHeight); startX += childWidth; } else { childView.layout(leftSMargin + startX + gap, startY, leftSMargin + startX + gap + childWidth, startY + childHeight); startX += (childWidth + gap); } } } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int screenWidth = DpUtil.getScreenSizeWidth(mContext); String upStr = "同一个世界,同一个梦想"; String downStr = "One World,One Dream"; canvas.drawText(upStr, (screenWidth - mPaint.measureText(upStr)) / 2, getCircleHeight() / 2 * 3 + 60, mPaint); canvas.drawText(downStr, (screenWidth - mPaint.measureText(downStr)) / 2, getCircleHeight() / 2 * 3 + 120, mPaint); } /** * 获得圆环高度 * * @return 圆环高度 */ private int getCircleHeight() { //5个圆环大小是一样的,这里就直接取第一个了 View childView = getChildAt(0); return childView.getMeasuredHeight(); } }
false
1,309
6
1,455
8
1,485
6
1,450
8
1,799
14
false
false
false
false
false
true
6164_6
package data.lab.knowledgegraph.utils; /* * * Data Lab - graph database organization. * */ import com.alibaba.fastjson.JSONArray; /** * @author Yc-Ma * @PACKAGE_NAME: data.lab.knowledgegraph.utils.SearchSentenceProcess * @Description: TODO * @date 2020/5/1 19:06 */ public class SearchSentenceProcess { private String[] perLocEventThingOrgArr = new String[]{""}; // 问答举例: // 1、小明和吴良述有共同参与的组织吗? // 2、小明和吴良述有共同参与的事吗? // 3、小明都参与过哪些组织? // 4、小明都参与过哪些事? // 5、小明有哪些虚拟账号? // 问答举例: // 1、小明住哪里? // 2、小明家在哪里? // 3、小明的微信是什么? // 4、小明从哪儿毕业的? // 5、小明去过南湖路20号吗? // 6、小明和吴良述有一起去过的地方吗? // 7、小明和吴良述是什么关系? // 8、小明最近qq上线是什么时候? // 9、小明最近有啥异常行为吗? public String extractionCypher(String askString, JSONArray sysIds, String startTime, String stopTime) { String cypher = null; StringBuilder builder = new StringBuilder(); if (askString.indexOf("哪里") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:居住地]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:居住地]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:爆发地]-(m:事) where n.name=~'.*" + entityOne + ".*' and m.start_time>='" + startTime + "' and m.start_time<='" + stopTime + "' return p limit 50 union all "); builder.append("match p=(n:事)-[r:爆发地]-(m:地) where n.name=~'.*" + entityOne + ".*' and n.start_time>='" + startTime + "' and n.start_time<='" + stopTime + "' return p limit 50 union all "); builder.append("match p=(n:人)-[r:截获位置]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:截获位置]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r:身份证归属地]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:身份证归属地]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:隶属地]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("qq") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:QQ号]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1]-(k:物)-[r2:QQ号]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("微信") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:WeChat号]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:物)-[r:WeChat号]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("毕业") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:毕业]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:毕业]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("行为") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:参与事]-(m:事) where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.start_time>='" + startTime + "' and m.start_time<='" + stopTime + "' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:手机号]-(k:物)-[r2:换手机设备]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:手机号]-(k:物)-[r2:换手机卡]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:增加好友]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:删除好友]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:上线]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:下线]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("关系") != -1) { String entityOne = askString.substring(0, 2); String entityTwo = askString.substring(4, 6); for (int i = 0; i < perLocEventThingOrgArr.length; i++) { String label = perLocEventThingOrgArr[i]; builder.append("match (n:人),(m:人) "); builder.append("where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.name=~'.*" + entityTwo + ".*' and m.sys_id in " + sysIds + " "); builder.append("match (f:" + label + ") "); builder.append("match p1=(n)-[r1*1]-(f),p2=(m)-[r2*1]-(f) "); builder.append("return p1,p2 limit 200 union all "); } cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("去过") != -1) { String entityOne = askString.substring(0, 2); String entityTwo = askString.substring(5, 7); builder.append("match p=(n:人)-[*1]-(m:地) where n.name=~'.*" + entityOne + ".*' and m.name=~'.*" + entityTwo + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[*1]-(m:人) where n.name=~'.*" + entityOne + ".*' and m.name=~'.*" + entityTwo + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:截获位置]-(k:地)-[r2:截获位置]-(m:人) where n.name=~'.*" + entityOne + ".*' and m.name=~'.*" + entityTwo + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("上线") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:上线]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:WeChat号]-(k:物)-[r2:上线]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("共同参与") != -1 && askString.indexOf("组织") != -1) { String entityOne = askString.substring(0, 2); String entityTwo = askString.substring(4, 6); builder.append("match (n:人),(m:人) "); builder.append("where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.name=~'.*" + entityTwo + ".*' and m.sys_id in " + sysIds + " "); builder.append("match (f:组织) "); builder.append("match p1=(n)-[r1]-(f),p2=(m)-[r2]-(f) "); builder.append("return p1,p2 limit 200 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("共同参与") != -1 && askString.indexOf("事") != -1) { String entityOne = askString.substring(0, 2); String entityTwo = askString.substring(4, 6); builder.append("match (n:人),(m:人) "); builder.append("where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.name=~'.*" + entityTwo + ".*' and m.sys_id in " + sysIds + " "); builder.append("match (f:事) "); builder.append("where f.start_time>='" + startTime + "' and f.start_time<='" + stopTime + "' "); builder.append("match p1=(n)-[r1:参与事]-(f),p2=(m)-[r2:参与事]-(f) "); builder.append("return p1,p2 limit 200 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("参与过") != -1 && askString.indexOf("组织") != -1) { String entityOne = askString.substring(0, 2); cypher = "match p=(n:人)-[r]-(m:组织) where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " return p limit 100"; } else if (askString.indexOf("参与过") != -1 && askString.indexOf("事") != -1) { String entityOne = askString.substring(0, 2); cypher = "match p=(n:人)-[r:参与事]-(m:事) where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.start_time>='" + startTime + "' and m.start_time<='" + stopTime + "' return p limit 100"; } else if (askString.indexOf("哪些虚拟账号") != -1) { String entityOne = askString.substring(0, 2); cypher = "match p=(n:人)-[r]-(m:物) where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " return p limit 100"; } return cypher; } /** * @param * @return * @Description: TODO(Test main entrance) */ public static void main(String[] args) { SearchSentenceProcess process = new SearchSentenceProcess(); // process.extractionCypher(askString, sysIds, startTime, "小明最近有啥异常行为吗?"); } }
crazyyanchao/knowledge-graph
src/main/java/data/lab/knowledgegraph/utils/SearchSentenceProcess.java
3,483
// 4、小明都参与过哪些事?
line_comment
zh-cn
package data.lab.knowledgegraph.utils; /* * * Data Lab - graph database organization. * */ import com.alibaba.fastjson.JSONArray; /** * @author Yc-Ma * @PACKAGE_NAME: data.lab.knowledgegraph.utils.SearchSentenceProcess * @Description: TODO * @date 2020/5/1 19:06 */ public class SearchSentenceProcess { private String[] perLocEventThingOrgArr = new String[]{""}; // 问答举例: // 1、小明和吴良述有共同参与的组织吗? // 2、小明和吴良述有共同参与的事吗? // 3、小明都参与过哪些组织? // 4、 <SUF> // 5、小明有哪些虚拟账号? // 问答举例: // 1、小明住哪里? // 2、小明家在哪里? // 3、小明的微信是什么? // 4、小明从哪儿毕业的? // 5、小明去过南湖路20号吗? // 6、小明和吴良述有一起去过的地方吗? // 7、小明和吴良述是什么关系? // 8、小明最近qq上线是什么时候? // 9、小明最近有啥异常行为吗? public String extractionCypher(String askString, JSONArray sysIds, String startTime, String stopTime) { String cypher = null; StringBuilder builder = new StringBuilder(); if (askString.indexOf("哪里") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:居住地]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:居住地]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:爆发地]-(m:事) where n.name=~'.*" + entityOne + ".*' and m.start_time>='" + startTime + "' and m.start_time<='" + stopTime + "' return p limit 50 union all "); builder.append("match p=(n:事)-[r:爆发地]-(m:地) where n.name=~'.*" + entityOne + ".*' and n.start_time>='" + startTime + "' and n.start_time<='" + stopTime + "' return p limit 50 union all "); builder.append("match p=(n:人)-[r:截获位置]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:截获位置]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r:身份证归属地]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:身份证归属地]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:隶属地]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("qq") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:QQ号]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1]-(k:物)-[r2:QQ号]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("微信") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:WeChat号]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:物)-[r:WeChat号]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("毕业") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:毕业]-(m:地) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[r:毕业]-(m:人) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("行为") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r:参与事]-(m:事) where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.start_time>='" + startTime + "' and m.start_time<='" + stopTime + "' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:手机号]-(k:物)-[r2:换手机设备]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:手机号]-(k:物)-[r2:换手机卡]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:增加好友]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:删除好友]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:上线]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:下线]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("关系") != -1) { String entityOne = askString.substring(0, 2); String entityTwo = askString.substring(4, 6); for (int i = 0; i < perLocEventThingOrgArr.length; i++) { String label = perLocEventThingOrgArr[i]; builder.append("match (n:人),(m:人) "); builder.append("where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.name=~'.*" + entityTwo + ".*' and m.sys_id in " + sysIds + " "); builder.append("match (f:" + label + ") "); builder.append("match p1=(n)-[r1*1]-(f),p2=(m)-[r2*1]-(f) "); builder.append("return p1,p2 limit 200 union all "); } cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("去过") != -1) { String entityOne = askString.substring(0, 2); String entityTwo = askString.substring(5, 7); builder.append("match p=(n:人)-[*1]-(m:地) where n.name=~'.*" + entityOne + ".*' and m.name=~'.*" + entityTwo + ".*' return p limit 50 union all "); builder.append("match p=(n:地)-[*1]-(m:人) where n.name=~'.*" + entityOne + ".*' and m.name=~'.*" + entityTwo + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:截获位置]-(k:地)-[r2:截获位置]-(m:人) where n.name=~'.*" + entityOne + ".*' and m.name=~'.*" + entityTwo + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("上线") != -1) { String entityOne = askString.substring(0, 2); builder.append("match p=(n:人)-[r1:QQ号]-(k:物)-[r2:上线]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); builder.append("match p=(n:人)-[r1:WeChat号]-(k:物)-[r2:上线]-(m:物) where n.name=~'.*" + entityOne + ".*' return p limit 50 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("共同参与") != -1 && askString.indexOf("组织") != -1) { String entityOne = askString.substring(0, 2); String entityTwo = askString.substring(4, 6); builder.append("match (n:人),(m:人) "); builder.append("where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.name=~'.*" + entityTwo + ".*' and m.sys_id in " + sysIds + " "); builder.append("match (f:组织) "); builder.append("match p1=(n)-[r1]-(f),p2=(m)-[r2]-(f) "); builder.append("return p1,p2 limit 200 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("共同参与") != -1 && askString.indexOf("事") != -1) { String entityOne = askString.substring(0, 2); String entityTwo = askString.substring(4, 6); builder.append("match (n:人),(m:人) "); builder.append("where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.name=~'.*" + entityTwo + ".*' and m.sys_id in " + sysIds + " "); builder.append("match (f:事) "); builder.append("where f.start_time>='" + startTime + "' and f.start_time<='" + stopTime + "' "); builder.append("match p1=(n)-[r1:参与事]-(f),p2=(m)-[r2:参与事]-(f) "); builder.append("return p1,p2 limit 200 union all "); cypher = builder.toString().substring(0, builder.length() - 10); } else if (askString.indexOf("参与过") != -1 && askString.indexOf("组织") != -1) { String entityOne = askString.substring(0, 2); cypher = "match p=(n:人)-[r]-(m:组织) where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " return p limit 100"; } else if (askString.indexOf("参与过") != -1 && askString.indexOf("事") != -1) { String entityOne = askString.substring(0, 2); cypher = "match p=(n:人)-[r:参与事]-(m:事) where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " and m.start_time>='" + startTime + "' and m.start_time<='" + stopTime + "' return p limit 100"; } else if (askString.indexOf("哪些虚拟账号") != -1) { String entityOne = askString.substring(0, 2); cypher = "match p=(n:人)-[r]-(m:物) where n.name=~'.*" + entityOne + ".*' and n.sys_id in " + sysIds + " return p limit 100"; } return cypher; } /** * @param * @return * @Description: TODO(Test main entrance) */ public static void main(String[] args) { SearchSentenceProcess process = new SearchSentenceProcess(); // process.extractionCypher(askString, sysIds, startTime, "小明最近有啥异常行为吗?"); } }
false
3,168
12
3,482
14
3,571
12
3,483
14
3,842
16
false
false
false
false
false
true
56510_11
package com.example.windowshowdemo; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.example.windowshowdemo.model.EnjoyBean; import com.silencedut.router.Router; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author zxl on 2018/5/22. * discription:弹出的喜欢的Fragment */ public class ShowEnjoyDialogFragment extends DialogFragment{ private RecyclerView mRv; private TextView mTVSubmit; private TextView mTvFive; private Context mContext; private BaseQuickAdapter<EnjoyBean,BaseViewHolder> mBaseAdapter; private List<EnjoyBean> mEnjoyBeans = new ArrayList<>(); private static final String HOBBY_KEY_ENJOY = "hobby_key_enjoy"; private EnsureListener mEnsureListener; public interface EnsureListener{ void onEnsureData(List<EnjoyBean> mList); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置数据... _initData(); Bundle arguments = getArguments(); if (arguments != null) { List<EnjoyBean> enjoyBeans = (List<EnjoyBean>) arguments.getSerializable("list"); if (enjoyBeans.size() == 0){ return; } for (int i=0;i<mEnjoyBeans.size();i++){ int id = mEnjoyBeans.get(i).getId(); for (int j=0;j<enjoyBeans.size();j++){ if (enjoyBeans.get(j).getId() == id){ mEnjoyBeans.get(i).setSelected(true); break; } } } } } // 初始化数据 private void _initData() { mEnjoyBeans.add(new EnjoyBean(0,"聚会")); mEnjoyBeans.add(new EnjoyBean(1,"高科技")); mEnjoyBeans.add(new EnjoyBean(2,"运动健身")); mEnjoyBeans.add(new EnjoyBean(3,"购物狂")); mEnjoyBeans.add(new EnjoyBean(4,"理财")); mEnjoyBeans.add(new EnjoyBean(5,"影视")); mEnjoyBeans.add(new EnjoyBean(6,"音乐")); mEnjoyBeans.add(new EnjoyBean(7,"自驾")); mEnjoyBeans.add(new EnjoyBean(8,"读书")); mEnjoyBeans.add(new EnjoyBean(9,"画画")); mEnjoyBeans.add(new EnjoyBean(10,"DIY")); mEnjoyBeans.add(new EnjoyBean(11,"游戏")); mEnjoyBeans.add(new EnjoyBean(12,"涨知识")); mEnjoyBeans.add(new EnjoyBean(13,"旅游")); } public static void showFragment(Activity activity,List<EnjoyBean> enjoys,EnsureListener ensureListener){ ShowEnjoyDialogFragment enjoyDialogFragment = new ShowEnjoyDialogFragment(); enjoyDialogFragment.setEnsureListener(ensureListener); Bundle bundle = new Bundle(); bundle.putSerializable("list", (Serializable) enjoys); enjoyDialogFragment.setArguments(bundle); enjoyDialogFragment.show(activity.getFragmentManager(),"enjoy"); } private void setEnsureListener(EnsureListener ensureListener){ this.mEnsureListener = ensureListener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // 使用不带Theme的构造器, 获得的dialog边框距离屏幕仍有几毫米的缝隙。 Dialog dialog = new Dialog(getActivity(), R.style.MyDialog); mContext = getActivity(); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定 dialog.setContentView(R.layout.fragment_dialog_show_enjoy); dialog.setCanceledOnTouchOutside(true); // 外部点击取消 // 设置宽度为屏宽, 靠近屏幕底部。 final Window window = dialog.getWindow(); window.setWindowAnimations(R.style.AnimBottom); final WindowManager.LayoutParams lp = window.getAttributes(); lp.gravity = Gravity.BOTTOM; // 紧贴底部 lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平 lp.height = getActivity().getWindowManager().getDefaultDisplay().getHeight() * 2/ 3; window.setAttributes(lp); initView(dialog); // 窗口初始化后 请求网络数据 return dialog; } private void initView(Dialog dialog) { mRv = (RecyclerView)dialog.findViewById(R.id.rv); mTVSubmit = (TextView) dialog.findViewById(R.id.tvBtn); mTvFive =(TextView)dialog.findViewById(R.id.tvFive); setAdapter(); setListener(); } private void setListener() { mTVSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (selectNum() == 0){ Toast.makeText(mContext, "客官请至少选择一个兴趣", Toast.LENGTH_SHORT).show(); return; } List<EnjoyBean> mSelectList = new ArrayList<>(); for (int i=0;i<mEnjoyBeans.size();i++){ if (mEnjoyBeans.get(i).isSelected()){ mSelectList.add(mEnjoyBeans.get(i)); } } if (mEnsureListener != null){ mEnsureListener.onEnsureData(mSelectList); } // 关闭 dismiss(); } }); } private void setAdapter() { if (mBaseAdapter == null) { GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false); mRv.setLayoutManager(layoutManager); mRv.addItemDecoration (new GridSpacingItemDecoration(3, getResources().getDimensionPixelSize(R.dimen.common_dimension_10), true)); mBaseAdapter = new BaseQuickAdapter<EnjoyBean, BaseViewHolder>(R.layout.item_enjoy_text,mEnjoyBeans) { @Override protected void convert(BaseViewHolder helper, EnjoyBean item) { final TextView tvEnjoy = helper.getView(R.id.tvEnjoy); if (item.isSelected()){ tvEnjoy.setTextColor(ContextCompat.getColor(mContext,R.color.red0)); tvEnjoy.setBackground(ContextCompat.getDrawable(mContext,R.drawable.bg_enjoy_pink)); }else { tvEnjoy.setTextColor(ContextCompat.getColor(mContext,R.color.black)); tvEnjoy.setBackground(ContextCompat.getDrawable(mContext,R.drawable.bg_enjoy_normal)); } tvEnjoy.setText(item.getDescription()); } }; // 设置点击事件 mBaseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { if (selectNum() == 5){ Toast.makeText(mContext, "不超过5个", Toast.LENGTH_SHORT).show(); mTvFive.setVisibility(View.VISIBLE); }else { // 设置选中状态... mTvFive.setVisibility(View.GONE); mEnjoyBeans.get(position).setSelected(true); mBaseAdapter.notifyItemChanged(position); } } }); } if (selectNum() == 5){ mTvFive.setVisibility(View.VISIBLE); } mRv.setAdapter(mBaseAdapter); } private int selectNum(){ int selectSum = 0; for (int i=0;i<mEnjoyBeans.size();i++){ if (mEnjoyBeans.get(i).isSelected()){ selectSum ++; } } return selectSum; } }
crazyzhangxl/WindowShowDemo
app/src/main/java/com/example/windowshowdemo/ShowEnjoyDialogFragment.java
2,040
// 设置选中状态...
line_comment
zh-cn
package com.example.windowshowdemo; import android.app.Activity; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.chad.library.adapter.base.BaseQuickAdapter; import com.chad.library.adapter.base.BaseViewHolder; import com.example.windowshowdemo.model.EnjoyBean; import com.silencedut.router.Router; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * @author zxl on 2018/5/22. * discription:弹出的喜欢的Fragment */ public class ShowEnjoyDialogFragment extends DialogFragment{ private RecyclerView mRv; private TextView mTVSubmit; private TextView mTvFive; private Context mContext; private BaseQuickAdapter<EnjoyBean,BaseViewHolder> mBaseAdapter; private List<EnjoyBean> mEnjoyBeans = new ArrayList<>(); private static final String HOBBY_KEY_ENJOY = "hobby_key_enjoy"; private EnsureListener mEnsureListener; public interface EnsureListener{ void onEnsureData(List<EnjoyBean> mList); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 设置数据... _initData(); Bundle arguments = getArguments(); if (arguments != null) { List<EnjoyBean> enjoyBeans = (List<EnjoyBean>) arguments.getSerializable("list"); if (enjoyBeans.size() == 0){ return; } for (int i=0;i<mEnjoyBeans.size();i++){ int id = mEnjoyBeans.get(i).getId(); for (int j=0;j<enjoyBeans.size();j++){ if (enjoyBeans.get(j).getId() == id){ mEnjoyBeans.get(i).setSelected(true); break; } } } } } // 初始化数据 private void _initData() { mEnjoyBeans.add(new EnjoyBean(0,"聚会")); mEnjoyBeans.add(new EnjoyBean(1,"高科技")); mEnjoyBeans.add(new EnjoyBean(2,"运动健身")); mEnjoyBeans.add(new EnjoyBean(3,"购物狂")); mEnjoyBeans.add(new EnjoyBean(4,"理财")); mEnjoyBeans.add(new EnjoyBean(5,"影视")); mEnjoyBeans.add(new EnjoyBean(6,"音乐")); mEnjoyBeans.add(new EnjoyBean(7,"自驾")); mEnjoyBeans.add(new EnjoyBean(8,"读书")); mEnjoyBeans.add(new EnjoyBean(9,"画画")); mEnjoyBeans.add(new EnjoyBean(10,"DIY")); mEnjoyBeans.add(new EnjoyBean(11,"游戏")); mEnjoyBeans.add(new EnjoyBean(12,"涨知识")); mEnjoyBeans.add(new EnjoyBean(13,"旅游")); } public static void showFragment(Activity activity,List<EnjoyBean> enjoys,EnsureListener ensureListener){ ShowEnjoyDialogFragment enjoyDialogFragment = new ShowEnjoyDialogFragment(); enjoyDialogFragment.setEnsureListener(ensureListener); Bundle bundle = new Bundle(); bundle.putSerializable("list", (Serializable) enjoys); enjoyDialogFragment.setArguments(bundle); enjoyDialogFragment.show(activity.getFragmentManager(),"enjoy"); } private void setEnsureListener(EnsureListener ensureListener){ this.mEnsureListener = ensureListener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // 使用不带Theme的构造器, 获得的dialog边框距离屏幕仍有几毫米的缝隙。 Dialog dialog = new Dialog(getActivity(), R.style.MyDialog); mContext = getActivity(); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置Content前设定 dialog.setContentView(R.layout.fragment_dialog_show_enjoy); dialog.setCanceledOnTouchOutside(true); // 外部点击取消 // 设置宽度为屏宽, 靠近屏幕底部。 final Window window = dialog.getWindow(); window.setWindowAnimations(R.style.AnimBottom); final WindowManager.LayoutParams lp = window.getAttributes(); lp.gravity = Gravity.BOTTOM; // 紧贴底部 lp.width = WindowManager.LayoutParams.MATCH_PARENT; // 宽度持平 lp.height = getActivity().getWindowManager().getDefaultDisplay().getHeight() * 2/ 3; window.setAttributes(lp); initView(dialog); // 窗口初始化后 请求网络数据 return dialog; } private void initView(Dialog dialog) { mRv = (RecyclerView)dialog.findViewById(R.id.rv); mTVSubmit = (TextView) dialog.findViewById(R.id.tvBtn); mTvFive =(TextView)dialog.findViewById(R.id.tvFive); setAdapter(); setListener(); } private void setListener() { mTVSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (selectNum() == 0){ Toast.makeText(mContext, "客官请至少选择一个兴趣", Toast.LENGTH_SHORT).show(); return; } List<EnjoyBean> mSelectList = new ArrayList<>(); for (int i=0;i<mEnjoyBeans.size();i++){ if (mEnjoyBeans.get(i).isSelected()){ mSelectList.add(mEnjoyBeans.get(i)); } } if (mEnsureListener != null){ mEnsureListener.onEnsureData(mSelectList); } // 关闭 dismiss(); } }); } private void setAdapter() { if (mBaseAdapter == null) { GridLayoutManager layoutManager = new GridLayoutManager(getActivity(), 3, GridLayoutManager.VERTICAL, false); mRv.setLayoutManager(layoutManager); mRv.addItemDecoration (new GridSpacingItemDecoration(3, getResources().getDimensionPixelSize(R.dimen.common_dimension_10), true)); mBaseAdapter = new BaseQuickAdapter<EnjoyBean, BaseViewHolder>(R.layout.item_enjoy_text,mEnjoyBeans) { @Override protected void convert(BaseViewHolder helper, EnjoyBean item) { final TextView tvEnjoy = helper.getView(R.id.tvEnjoy); if (item.isSelected()){ tvEnjoy.setTextColor(ContextCompat.getColor(mContext,R.color.red0)); tvEnjoy.setBackground(ContextCompat.getDrawable(mContext,R.drawable.bg_enjoy_pink)); }else { tvEnjoy.setTextColor(ContextCompat.getColor(mContext,R.color.black)); tvEnjoy.setBackground(ContextCompat.getDrawable(mContext,R.drawable.bg_enjoy_normal)); } tvEnjoy.setText(item.getDescription()); } }; // 设置点击事件 mBaseAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() { @Override public void onItemClick(BaseQuickAdapter adapter, View view, int position) { if (selectNum() == 5){ Toast.makeText(mContext, "不超过5个", Toast.LENGTH_SHORT).show(); mTvFive.setVisibility(View.VISIBLE); }else { // 设置 <SUF> mTvFive.setVisibility(View.GONE); mEnjoyBeans.get(position).setSelected(true); mBaseAdapter.notifyItemChanged(position); } } }); } if (selectNum() == 5){ mTvFive.setVisibility(View.VISIBLE); } mRv.setAdapter(mBaseAdapter); } private int selectNum(){ int selectSum = 0; for (int i=0;i<mEnjoyBeans.size();i++){ if (mEnjoyBeans.get(i).isSelected()){ selectSum ++; } } return selectSum; } }
false
1,647
6
2,040
6
2,052
5
2,040
6
2,602
9
false
false
false
false
false
true
23404_2
/* * version 0.1 2015-3-11 */ package po; import java.awt.Image; public class PlayerPO { String name; String number; //球衣号码 String position; //位置 String height; String weight; String birth; //生日(月日,年) String age; String exp; //球龄 String school; //毕业院校 Image actionImage; //全身照 Image portaitImage; //球员头像 public void setName(String name) { this.name = name; } public void setNumber(String number) { this.number = number; } public void setPosition(String position) { this.position = position; } public void setHeight(String height) { this.height = height; } public void setWeight(String weight) { this.weight = weight; } public void setBirth(String birth) { this.birth = birth; } public void setAge(String age) { this.age = age; } public void setExp(String exp) { this.exp = exp; } public void setSchool(String school) { this.school = school; } public void setActionImage(Image actionImage) { this.actionImage = actionImage; } public void setPortaitImage(Image portaitImage) { this.portaitImage = portaitImage; } public String getName() { return name; } public String getNumber() { return number; } public String getPosition() { return position; } public String getHeight() { return height; } public String getWeight() { return weight; } public String getBirth() { return birth; } public String getAge() { return age; } public String getExp() { return exp; } public String getSchool() { return school; } public Image getActionImage() { return actionImage; } public Image getPortaitImage() { return portaitImage; } }
cristph/NBA_SE-III
NBA/src/main/java/po/PlayerPO.java
571
//生日(月日,年)
line_comment
zh-cn
/* * version 0.1 2015-3-11 */ package po; import java.awt.Image; public class PlayerPO { String name; String number; //球衣号码 String position; //位置 String height; String weight; String birth; //生日 <SUF> String age; String exp; //球龄 String school; //毕业院校 Image actionImage; //全身照 Image portaitImage; //球员头像 public void setName(String name) { this.name = name; } public void setNumber(String number) { this.number = number; } public void setPosition(String position) { this.position = position; } public void setHeight(String height) { this.height = height; } public void setWeight(String weight) { this.weight = weight; } public void setBirth(String birth) { this.birth = birth; } public void setAge(String age) { this.age = age; } public void setExp(String exp) { this.exp = exp; } public void setSchool(String school) { this.school = school; } public void setActionImage(Image actionImage) { this.actionImage = actionImage; } public void setPortaitImage(Image portaitImage) { this.portaitImage = portaitImage; } public String getName() { return name; } public String getNumber() { return number; } public String getPosition() { return position; } public String getHeight() { return height; } public String getWeight() { return weight; } public String getBirth() { return birth; } public String getAge() { return age; } public String getExp() { return exp; } public String getSchool() { return school; } public Image getActionImage() { return actionImage; } public Image getPortaitImage() { return portaitImage; } }
false
429
8
571
9
568
8
571
9
626
9
false
false
false
false
false
true
54498_7
package com.zbkj.common.vo; import lombok.Data; /** * 文件信息 * +---------------------------------------------------------------------- * | CRMEB [ CRMEB赋能开发者,助力企业发展 ] * +---------------------------------------------------------------------- * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved. * +---------------------------------------------------------------------- * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权 * +---------------------------------------------------------------------- * | Author: CRMEB Team <admin@crmeb.com> * +---------------------------------------------------------------------- */ @Data public class CloudVo { //域名空间 private String domain; //accessKey private String accessKey; //secretKey private String secretKey; //bucketName private String bucketName; // //webPath web访问的url地址,云服务会自动创建相对应的文件夹 // private String webPath; // // //服务器存储的文件绝对路径 // private String filePath; // // //图片id // private Integer id; //节点 private String region; }
crmeb/crmeb_java
crmeb/crmeb-common/src/main/java/com/zbkj/common/vo/CloudVo.java
257
// //服务器存储的文件绝对路径
line_comment
zh-cn
package com.zbkj.common.vo; import lombok.Data; /** * 文件信息 * +---------------------------------------------------------------------- * | CRMEB [ CRMEB赋能开发者,助力企业发展 ] * +---------------------------------------------------------------------- * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved. * +---------------------------------------------------------------------- * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权 * +---------------------------------------------------------------------- * | Author: CRMEB Team <admin@crmeb.com> * +---------------------------------------------------------------------- */ @Data public class CloudVo { //域名空间 private String domain; //accessKey private String accessKey; //secretKey private String secretKey; //bucketName private String bucketName; // //webPath web访问的url地址,云服务会自动创建相对应的文件夹 // private String webPath; // // //服务 <SUF> // private String filePath; // // //图片id // private Integer id; //节点 private String region; }
false
230
9
257
9
282
8
257
9
358
21
false
false
false
false
false
true
3810_2
package com.crossoverjie.actual; /** * Function:两个线程交替执行打印 1~100 * 等待通知机制版 * * @author crossoverJie * Date: 07/03/2018 13:19 * @since JDK 1.8 */ public class TwoThreadWaitNotifySimple { private boolean flag = false; public static void main(String[] args) { TwoThreadWaitNotifySimple twoThread = new TwoThreadWaitNotifySimple(); Thread t1 = new Thread(new OuNum(twoThread)); t1.setName("t1"); Thread t2 = new Thread(new JiNum(twoThread)); t2.setName("t2"); t1.start(); t2.start(); } /** * 偶数线程 */ public static class OuNum implements Runnable { private TwoThreadWaitNotifySimple number; public OuNum(TwoThreadWaitNotifySimple number) { this.number = number; } @Override public void run() { for (int i = 0; i < 11; i++) { synchronized (TwoThreadWaitNotifySimple.class) { if (number.flag) { if (i % 2 == 0) { System.out.println(Thread.currentThread().getName() + "+-+偶数" + i); number.flag = false; TwoThreadWaitNotifySimple.class.notify(); } } else { try { TwoThreadWaitNotifySimple.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } /** * 奇数线程 */ public static class JiNum implements Runnable { private TwoThreadWaitNotifySimple number; public JiNum(TwoThreadWaitNotifySimple number) { this.number = number; } @Override public void run() { for (int i = 0; i < 11; i++) { synchronized (TwoThreadWaitNotifySimple.class) { if (!number.flag) { if (i % 2 == 1) { System.out.println(Thread.currentThread().getName() + "+-+奇数" + i); number.flag = true; TwoThreadWaitNotifySimple.class.notify(); } } else { try { TwoThreadWaitNotifySimple.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } }
crossoverJie/JCSprout
src/main/java/com/crossoverjie/actual/TwoThreadWaitNotifySimple.java
582
/** * 奇数线程 */
block_comment
zh-cn
package com.crossoverjie.actual; /** * Function:两个线程交替执行打印 1~100 * 等待通知机制版 * * @author crossoverJie * Date: 07/03/2018 13:19 * @since JDK 1.8 */ public class TwoThreadWaitNotifySimple { private boolean flag = false; public static void main(String[] args) { TwoThreadWaitNotifySimple twoThread = new TwoThreadWaitNotifySimple(); Thread t1 = new Thread(new OuNum(twoThread)); t1.setName("t1"); Thread t2 = new Thread(new JiNum(twoThread)); t2.setName("t2"); t1.start(); t2.start(); } /** * 偶数线程 */ public static class OuNum implements Runnable { private TwoThreadWaitNotifySimple number; public OuNum(TwoThreadWaitNotifySimple number) { this.number = number; } @Override public void run() { for (int i = 0; i < 11; i++) { synchronized (TwoThreadWaitNotifySimple.class) { if (number.flag) { if (i % 2 == 0) { System.out.println(Thread.currentThread().getName() + "+-+偶数" + i); number.flag = false; TwoThreadWaitNotifySimple.class.notify(); } } else { try { TwoThreadWaitNotifySimple.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } /** * 奇数线 <SUF>*/ public static class JiNum implements Runnable { private TwoThreadWaitNotifySimple number; public JiNum(TwoThreadWaitNotifySimple number) { this.number = number; } @Override public void run() { for (int i = 0; i < 11; i++) { synchronized (TwoThreadWaitNotifySimple.class) { if (!number.flag) { if (i % 2 == 1) { System.out.println(Thread.currentThread().getName() + "+-+奇数" + i); number.flag = true; TwoThreadWaitNotifySimple.class.notify(); } } else { try { TwoThreadWaitNotifySimple.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } }
false
542
12
582
9
638
10
582
9
739
12
false
false
false
false
false
true
13410_5
package com.crossoverjie.cim.client.scanner; import com.crossoverjie.cim.client.config.AppConfiguration; import com.crossoverjie.cim.client.service.EchoService; import com.crossoverjie.cim.client.service.MsgHandle; import com.crossoverjie.cim.client.service.MsgLogger; import com.crossoverjie.cim.client.util.SpringBeanFactory; import com.vdurmont.emoji.EmojiParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Scanner; /** * Function: * * @author crossoverJie * Date: 2018/12/21 16:44 * @since JDK 1.8 */ public class Scan implements Runnable { private final static Logger LOGGER = LoggerFactory.getLogger(Scan.class); /** * 系统参数 */ private AppConfiguration configuration; private MsgHandle msgHandle ; private MsgLogger msgLogger ; private EchoService echoService ; public Scan() { this.configuration = SpringBeanFactory.getBean(AppConfiguration.class); this.msgHandle = SpringBeanFactory.getBean(MsgHandle.class) ; this.msgLogger = SpringBeanFactory.getBean(MsgLogger.class) ; this.echoService = SpringBeanFactory.getBean(EchoService.class) ; } @Override public void run() { Scanner sc = new Scanner(System.in); while (true) { String msg = sc.nextLine(); //检查消息 if (msgHandle.checkMsg(msg)) { continue; } //系统内置命令 if (msgHandle.innerCommand(msg)){ continue; } //真正的发送消息 msgHandle.sendMsg(msg) ; //写入聊天记录 msgLogger.log(msg) ; echoService.echo(EmojiParser.parseToUnicode(msg)); } } }
crossoverJie/cim
cim-client/src/main/java/com/crossoverjie/cim/client/scanner/Scan.java
467
//写入聊天记录
line_comment
zh-cn
package com.crossoverjie.cim.client.scanner; import com.crossoverjie.cim.client.config.AppConfiguration; import com.crossoverjie.cim.client.service.EchoService; import com.crossoverjie.cim.client.service.MsgHandle; import com.crossoverjie.cim.client.service.MsgLogger; import com.crossoverjie.cim.client.util.SpringBeanFactory; import com.vdurmont.emoji.EmojiParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Scanner; /** * Function: * * @author crossoverJie * Date: 2018/12/21 16:44 * @since JDK 1.8 */ public class Scan implements Runnable { private final static Logger LOGGER = LoggerFactory.getLogger(Scan.class); /** * 系统参数 */ private AppConfiguration configuration; private MsgHandle msgHandle ; private MsgLogger msgLogger ; private EchoService echoService ; public Scan() { this.configuration = SpringBeanFactory.getBean(AppConfiguration.class); this.msgHandle = SpringBeanFactory.getBean(MsgHandle.class) ; this.msgLogger = SpringBeanFactory.getBean(MsgLogger.class) ; this.echoService = SpringBeanFactory.getBean(EchoService.class) ; } @Override public void run() { Scanner sc = new Scanner(System.in); while (true) { String msg = sc.nextLine(); //检查消息 if (msgHandle.checkMsg(msg)) { continue; } //系统内置命令 if (msgHandle.innerCommand(msg)){ continue; } //真正的发送消息 msgHandle.sendMsg(msg) ; //写入 <SUF> msgLogger.log(msg) ; echoService.echo(EmojiParser.parseToUnicode(msg)); } } }
false
383
5
467
6
471
4
467
6
566
9
false
false
false
false
false
true
61420_3
package com.jzy.game.ai.nav.node; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.jzy.game.ai.nav.NavMeshData; import com.jzy.game.engine.math.Vector3; /** * navmesh寻路三角形网格数据 <br> * 依次三个顶点确定一个三角形 * * @author CruiseDing * */ public class NodeData extends NavMeshData { private static final Logger LOGGER = LoggerFactory.getLogger(NodeData.class); private static final long serialVersionUID = 1L; /** 阻挡顶点序号 */ private int[] blockTriangles; /** 阻挡坐标 */ private Vector3[] blockVertices; /** * 数据检测,客户端的顶点坐标和三角形数据有可能是重复的 * <br> * TODO 小三角形合并成大三角形或多边形;判断顶点是否在寻路层中,寻路层中的顶点不能作为路径点;两点所连线段是否穿过阻挡区,不穿过,直接获取坐标点 */ public void check(int scale) { super.check(scale); amendmentSameVector(blockTriangles, blockVertices); scaleVector(blockVertices, scale); } public int[] getBlockTriangles() { return blockTriangles; } public void setBlockTriangles(int[] blockTriangles) { this.blockTriangles = blockTriangles; } public Vector3[] getBlockVertices() { return blockVertices; } public void setBlockVertices(Vector3[] blockVertices) { this.blockVertices = blockVertices; } @Override public String toString() { return JSON.toJSONString(this); } }
cruiseding/game-server
game-ai/src/main/java/com/jzy/game/ai/nav/node/NodeData.java
488
/** * 数据检测,客户端的顶点坐标和三角形数据有可能是重复的 * <br> * TODO 小三角形合并成大三角形或多边形;判断顶点是否在寻路层中,寻路层中的顶点不能作为路径点;两点所连线段是否穿过阻挡区,不穿过,直接获取坐标点 */
block_comment
zh-cn
package com.jzy.game.ai.nav.node; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.fastjson.JSON; import com.jzy.game.ai.nav.NavMeshData; import com.jzy.game.engine.math.Vector3; /** * navmesh寻路三角形网格数据 <br> * 依次三个顶点确定一个三角形 * * @author CruiseDing * */ public class NodeData extends NavMeshData { private static final Logger LOGGER = LoggerFactory.getLogger(NodeData.class); private static final long serialVersionUID = 1L; /** 阻挡顶点序号 */ private int[] blockTriangles; /** 阻挡坐标 */ private Vector3[] blockVertices; /** * 数据检 <SUF>*/ public void check(int scale) { super.check(scale); amendmentSameVector(blockTriangles, blockVertices); scaleVector(blockVertices, scale); } public int[] getBlockTriangles() { return blockTriangles; } public void setBlockTriangles(int[] blockTriangles) { this.blockTriangles = blockTriangles; } public Vector3[] getBlockVertices() { return blockVertices; } public void setBlockVertices(Vector3[] blockVertices) { this.blockVertices = blockVertices; } @Override public String toString() { return JSON.toJSONString(this); } }
false
367
81
481
93
464
86
481
93
609
145
false
false
false
false
false
true
58917_3
package com.angelocyj.bodypart.region; /** * Created by angelo on 2015/2/28. */ public enum Region { HEAD ("头部", 1, LayoutSide.LEFT, 47, 38, 0), EYE ("眼部", 2, LayoutSide.LEFT, 49, 80, 0, 1), FACE ("面部", 5, LayoutSide.LEFT, 39, 121, 0, 2), THROAT ("咽喉", 6, LayoutSide.LEFT, 0, 199, 0, 3), EAR ("耳朵", 3, LayoutSide.RIGHT, 68, 82, 0), NOSEMOUTH ("口鼻", 4, LayoutSide.RIGHT, 0, 135, 0, 1), NECK ("脖子", 7, LayoutSide.RIGHT, 33, 192, 0, 2), SKIN ("皮肤", 17, LayoutSide.RIGHT, 0, 0, 0, 1), ARM("手臂", 10, LayoutSide.RIGHT, 170, 465, 335), HAND("手", 9, LayoutSide.LEFT, 245, 695, 545), SHOULDER("肩", 8, LayoutSide.LEFT, 120, 250, 338), CHEST("胸部", 11, LayoutSide.RIGHT, 59, 364, 125), ABDOMEN("腹部", 13, LayoutSide.LEFT, 0, 581, 415), WAIST("腰", 12, LayoutSide.LEFT, 112, 600, 415, 1), PELVIC("盆腔\n下体", 14, LayoutSide.RIGHT, 0, 687, 405), LEG("大腿", 15, LayoutSide.LEFT, 83, 877, 1026), FOOT("足", 16, LayoutSide.RIGHT, 56, 1313, 890), //1026 BACKNECK ("脖子", 7, LayoutSide.LEFT, 0, 168, 0, 1), BACKSHOULDER("肩", 8, LayoutSide.LEFT, 120, 250, 168), BACKHAND("手", 9, LayoutSide.LEFT, 245, 695, 168, 1), BACKARM("手臂", 10, LayoutSide.RIGHT, 170, 465, 168, 1), BACKBACK("背", 18, LayoutSide.RIGHT, 0, 420, 168), BACKWAIST("腰", 12, LayoutSide.LEFT, 120, 610, 538), BACKPELVIC("盆腔\n下体", 14, LayoutSide.LEFT, 0, 656, 538, 1), BACKHIP("臀部", 19, LayoutSide.RIGHT, 54, 666, 538), BACKANUSRECTUM("肛门\n直肠", 20, LayoutSide.RIGHT, 0, 703, 538, 1), BACKFOOT("足", 16, LayoutSide.LEFT, 56, 1313, 1026), BACKLEG("大腿", 15, LayoutSide.RIGHT, 83, 877, 890),//1026 OTHER("其他", 21, LayoutSide.RIGHT, 0, 0, 0), ALLDISEASE("全部症状", -1, LayoutSide.RIGHT, 0, 0, 0); private final String name; private final int value; private final int layoutSide; private final int offsetSX, offsetSY; //路径起始坐标点 private final int offsetDY; //部位中心点基准纵坐标 private int startX, startY; private final int offSetNum; //部位之间纵坐标偏移数 private int destinationY; // = offsetDY + RegionParam.OFFSET_Y * offsetNum Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY){ this(name, value, layoutSide, offsetSX, offsetSY, offsetDY, 0, 0, 0, 0); } Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY, final int offSetNum){ this(name, value, layoutSide, offsetSX, offsetSY, offsetDY, 0, 0, offSetNum, 0); } Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY, int startX, int startY, int offSetNum, int destinationY) { this.name = name; this.value = value; this.layoutSide = layoutSide; this.offsetSX = offsetSX; this.offsetSY = offsetSY; this.offsetDY = offsetDY; this.startX = startX; this.startY = startY; this.offSetNum = offSetNum; this.destinationY = destinationY; } @Override public String toString() { return this.name; } public static String getName(int value) { for (Region c : Region.values()) { if (c.getValue() == value) { return c.name; } } return null; } public String getName() { return name; } public int getValue() { return value; } public int getLayoutSide() { return layoutSide; } public int getOffsetSX() { return offsetSX; } public int getOffsetSY() { return offsetSY; } public int getOffsetDY() { return offsetDY; } public int getStartX() { return startX; } public void setStartX(int startX) { this.startX = startX; } public int getStartY() { return startY; } public void setStartY(int startY) { this.startY = startY; } public int getOffSetNum() { return offSetNum; } public int getDestinationY() { return destinationY; } public void setDestinationY(int destinationY) { this.destinationY = destinationY; } public static class LayoutSide { public final static int LEFT = 0; public final static int RIGHT = 1; } }
crystalchi/android-body-part-master
app/src/main/java/com/angelocyj/bodypart/region/Region.java
1,677
//路径起始坐标点
line_comment
zh-cn
package com.angelocyj.bodypart.region; /** * Created by angelo on 2015/2/28. */ public enum Region { HEAD ("头部", 1, LayoutSide.LEFT, 47, 38, 0), EYE ("眼部", 2, LayoutSide.LEFT, 49, 80, 0, 1), FACE ("面部", 5, LayoutSide.LEFT, 39, 121, 0, 2), THROAT ("咽喉", 6, LayoutSide.LEFT, 0, 199, 0, 3), EAR ("耳朵", 3, LayoutSide.RIGHT, 68, 82, 0), NOSEMOUTH ("口鼻", 4, LayoutSide.RIGHT, 0, 135, 0, 1), NECK ("脖子", 7, LayoutSide.RIGHT, 33, 192, 0, 2), SKIN ("皮肤", 17, LayoutSide.RIGHT, 0, 0, 0, 1), ARM("手臂", 10, LayoutSide.RIGHT, 170, 465, 335), HAND("手", 9, LayoutSide.LEFT, 245, 695, 545), SHOULDER("肩", 8, LayoutSide.LEFT, 120, 250, 338), CHEST("胸部", 11, LayoutSide.RIGHT, 59, 364, 125), ABDOMEN("腹部", 13, LayoutSide.LEFT, 0, 581, 415), WAIST("腰", 12, LayoutSide.LEFT, 112, 600, 415, 1), PELVIC("盆腔\n下体", 14, LayoutSide.RIGHT, 0, 687, 405), LEG("大腿", 15, LayoutSide.LEFT, 83, 877, 1026), FOOT("足", 16, LayoutSide.RIGHT, 56, 1313, 890), //1026 BACKNECK ("脖子", 7, LayoutSide.LEFT, 0, 168, 0, 1), BACKSHOULDER("肩", 8, LayoutSide.LEFT, 120, 250, 168), BACKHAND("手", 9, LayoutSide.LEFT, 245, 695, 168, 1), BACKARM("手臂", 10, LayoutSide.RIGHT, 170, 465, 168, 1), BACKBACK("背", 18, LayoutSide.RIGHT, 0, 420, 168), BACKWAIST("腰", 12, LayoutSide.LEFT, 120, 610, 538), BACKPELVIC("盆腔\n下体", 14, LayoutSide.LEFT, 0, 656, 538, 1), BACKHIP("臀部", 19, LayoutSide.RIGHT, 54, 666, 538), BACKANUSRECTUM("肛门\n直肠", 20, LayoutSide.RIGHT, 0, 703, 538, 1), BACKFOOT("足", 16, LayoutSide.LEFT, 56, 1313, 1026), BACKLEG("大腿", 15, LayoutSide.RIGHT, 83, 877, 890),//1026 OTHER("其他", 21, LayoutSide.RIGHT, 0, 0, 0), ALLDISEASE("全部症状", -1, LayoutSide.RIGHT, 0, 0, 0); private final String name; private final int value; private final int layoutSide; private final int offsetSX, offsetSY; //路径 <SUF> private final int offsetDY; //部位中心点基准纵坐标 private int startX, startY; private final int offSetNum; //部位之间纵坐标偏移数 private int destinationY; // = offsetDY + RegionParam.OFFSET_Y * offsetNum Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY){ this(name, value, layoutSide, offsetSX, offsetSY, offsetDY, 0, 0, 0, 0); } Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY, final int offSetNum){ this(name, value, layoutSide, offsetSX, offsetSY, offsetDY, 0, 0, offSetNum, 0); } Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY, int startX, int startY, int offSetNum, int destinationY) { this.name = name; this.value = value; this.layoutSide = layoutSide; this.offsetSX = offsetSX; this.offsetSY = offsetSY; this.offsetDY = offsetDY; this.startX = startX; this.startY = startY; this.offSetNum = offSetNum; this.destinationY = destinationY; } @Override public String toString() { return this.name; } public static String getName(int value) { for (Region c : Region.values()) { if (c.getValue() == value) { return c.name; } } return null; } public String getName() { return name; } public int getValue() { return value; } public int getLayoutSide() { return layoutSide; } public int getOffsetSX() { return offsetSX; } public int getOffsetSY() { return offsetSY; } public int getOffsetDY() { return offsetDY; } public int getStartX() { return startX; } public void setStartX(int startX) { this.startX = startX; } public int getStartY() { return startY; } public void setStartY(int startY) { this.startY = startY; } public int getOffSetNum() { return offSetNum; } public int getDestinationY() { return destinationY; } public void setDestinationY(int destinationY) { this.destinationY = destinationY; } public static class LayoutSide { public final static int LEFT = 0; public final static int RIGHT = 1; } }
false
1,554
6
1,677
6
1,710
5
1,677
6
1,942
12
false
false
false
false
false
true
47244_7
/** * 请勿将俱乐部专享资源复制给其他人,保护知识产权即是保护我们所在的行业,进而保护我们自己的利益 * 即便是公司的同事,也请尊重 JFinal 作者的努力与付出,不要复制给同事 * * 如果你尚未加入俱乐部,请立即删除该项目,或者现在加入俱乐部:http://jfinal.com/club * * 俱乐部将提供 jfinal-club 项目文档与设计资源、专用 QQ 群,以及作者在俱乐部定期的分享与答疑, * 价值远比仅仅拥有 jfinal club 项目源代码要大得多 * * JFinal 俱乐部是五年以来首次寻求外部资源的尝试,以便于有资源创建更加 * 高品质的产品与服务,为大家带来更大的价值,所以请大家多多支持,不要将 * 首次的尝试扼杀在了摇篮之中 */ package com.cser.play.common.kit; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; /** * @author res * IpKit 获取 ip 地址的工具类 */ public class IpKit { public static String getRealIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } public static String getRealIpV2(HttpServletRequest request) { String accessIP = request.getHeader("x-forwarded-for"); if (null == accessIP){ return request.getRemoteAddr(); } return accessIP; } /** * 获取本机 ip * @return 本机IP */ public static String getLocalIp() throws SocketException { // 本地IP,如果没有配置外网IP则返回 String localip = null; // 外网IP String netip = null; Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; // 是否找到外网IP boolean finded = false; while (netInterfaces.hasMoreElements() && !finded) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> address = ni.getInetAddresses(); while (address.hasMoreElements()) { ip = address.nextElement(); // 外网IP if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { netip = ip.getHostAddress(); finded = true; break; // 内网IP } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { localip = ip.getHostAddress(); } } } if (netip != null && !"".equals(netip)) { return netip; } else { return localip; } } }
cser700/play-together
src/main/java/com/cser/play/common/kit/IpKit.java
901
// 内网IP
line_comment
zh-cn
/** * 请勿将俱乐部专享资源复制给其他人,保护知识产权即是保护我们所在的行业,进而保护我们自己的利益 * 即便是公司的同事,也请尊重 JFinal 作者的努力与付出,不要复制给同事 * * 如果你尚未加入俱乐部,请立即删除该项目,或者现在加入俱乐部:http://jfinal.com/club * * 俱乐部将提供 jfinal-club 项目文档与设计资源、专用 QQ 群,以及作者在俱乐部定期的分享与答疑, * 价值远比仅仅拥有 jfinal club 项目源代码要大得多 * * JFinal 俱乐部是五年以来首次寻求外部资源的尝试,以便于有资源创建更加 * 高品质的产品与服务,为大家带来更大的价值,所以请大家多多支持,不要将 * 首次的尝试扼杀在了摇篮之中 */ package com.cser.play.common.kit; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; /** * @author res * IpKit 获取 ip 地址的工具类 */ public class IpKit { public static String getRealIp(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } public static String getRealIpV2(HttpServletRequest request) { String accessIP = request.getHeader("x-forwarded-for"); if (null == accessIP){ return request.getRemoteAddr(); } return accessIP; } /** * 获取本机 ip * @return 本机IP */ public static String getLocalIp() throws SocketException { // 本地IP,如果没有配置外网IP则返回 String localip = null; // 外网IP String netip = null; Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; // 是否找到外网IP boolean finded = false; while (netInterfaces.hasMoreElements() && !finded) { NetworkInterface ni = netInterfaces.nextElement(); Enumeration<InetAddress> address = ni.getInetAddresses(); while (address.hasMoreElements()) { ip = address.nextElement(); // 外网IP if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { netip = ip.getHostAddress(); finded = true; break; // 内网 <SUF> } else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) { localip = ip.getHostAddress(); } } } if (netip != null && !"".equals(netip)) { return netip; } else { return localip; } } }
false
750
5
901
5
842
4
901
5
1,210
5
false
false
false
false
false
true
66378_9
package com.michelin.java; /* * 算法的考察: 陣列的複製、反轉、查找(線性查找、二分法查找) */ public class ArrayTest2 { public static void main(String[] args) { String[] arr = new String[] {"JJ", "DD", "MM", "BB", "GG", "AA"}; // 陣列的複製(區別於陣列變量的賦值: arr1 = arr) String[] arr1 = new String[arr.length]; for(int i = 0; i < arr1.length; i++) { arr1[i] = arr[i]; } // 陣列的反轉 // 方法一: // for(int i = 0; i < (arr.length / 2); i++) { // String temp = arr[i]; // arr[i] = arr[arr.length - i -1]; // arr[arr.length - i -1] = temp; // } // 方法二: for(int i = 0, j = arr.length - 1; i < j; i++, j--) { String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // 遍歷 for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + "\t"); } System.out.println(); // 查找 (或搜索) // 線性查找(linear search): String[] arr2 = new String[] {"JJ", "DD", "MM", "BB", "GG", "AA"}; String desc = "BB"; boolean isFlag = true; for(int i = 0; i < arr2.length; i++) { if(desc.equals(arr[i])) { System.out.println("找到了指定的元素,位置為: " + i); isFlag = false; break; } } if(isFlag) { System.out.println("很遺憾,沒有找到喔!"); } // 二分法查找(binary search)(熟悉): // 前提: 所有查找的陣列必須有序 int[] arr3 = new int[] {-98, -34, 2, 34, 54, 66, 79, 105, 210, 333}; int desc1 = -98; int head = 0; // 初始首索引 int end = arr3.length - 1; // 初始的末索引 boolean isFlag1 = true; while(head <= end) { int middle = (head + end) / 2; if(desc1 == arr3[middle]) { System.out.println("找到了指定的元素,位置為: " + middle); isFlag1 = false; break; }else if(arr3[middle] > desc1) { end = middle - 1; }else { // arr3[middle] < desc1 head = middle + 1; } } if(isFlag1) { System.out.println("很遺憾,沒有找到啦!"); } } }
csiemichelin/Java-Tutorial
code/day07/src/com/michelin/java/ArrayTest2.java
859
// 查找 (或搜索)
line_comment
zh-cn
package com.michelin.java; /* * 算法的考察: 陣列的複製、反轉、查找(線性查找、二分法查找) */ public class ArrayTest2 { public static void main(String[] args) { String[] arr = new String[] {"JJ", "DD", "MM", "BB", "GG", "AA"}; // 陣列的複製(區別於陣列變量的賦值: arr1 = arr) String[] arr1 = new String[arr.length]; for(int i = 0; i < arr1.length; i++) { arr1[i] = arr[i]; } // 陣列的反轉 // 方法一: // for(int i = 0; i < (arr.length / 2); i++) { // String temp = arr[i]; // arr[i] = arr[arr.length - i -1]; // arr[arr.length - i -1] = temp; // } // 方法二: for(int i = 0, j = arr.length - 1; i < j; i++, j--) { String temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // 遍歷 for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + "\t"); } System.out.println(); // 查找 <SUF> // 線性查找(linear search): String[] arr2 = new String[] {"JJ", "DD", "MM", "BB", "GG", "AA"}; String desc = "BB"; boolean isFlag = true; for(int i = 0; i < arr2.length; i++) { if(desc.equals(arr[i])) { System.out.println("找到了指定的元素,位置為: " + i); isFlag = false; break; } } if(isFlag) { System.out.println("很遺憾,沒有找到喔!"); } // 二分法查找(binary search)(熟悉): // 前提: 所有查找的陣列必須有序 int[] arr3 = new int[] {-98, -34, 2, 34, 54, 66, 79, 105, 210, 333}; int desc1 = -98; int head = 0; // 初始首索引 int end = arr3.length - 1; // 初始的末索引 boolean isFlag1 = true; while(head <= end) { int middle = (head + end) / 2; if(desc1 == arr3[middle]) { System.out.println("找到了指定的元素,位置為: " + middle); isFlag1 = false; break; }else if(arr3[middle] > desc1) { end = middle - 1; }else { // arr3[middle] < desc1 head = middle + 1; } } if(isFlag1) { System.out.println("很遺憾,沒有找到啦!"); } } }
false
736
7
859
7
820
7
859
7
1,064
13
false
false
false
false
false
true
62954_15
package Greedy; import java.util.ArrayList; import java.util.List; public class Greed { // 1.先将任务按照时间惩罚递减顺序进行排序, // 2.然后用贪心的思想,尽量把惩罚重的任务先放入待完成队列中。 public class Task{ public int id; public int d;//截止时间 public int w;//惩罚 } public void init_array(int n, Task[] tasks){ //生成随机数据 for(int i=0;i<n;i++){ tasks[i] = new Task(); // tasks[i].id = i; // tasks[i].d = (int)(Math.random() * (n-1))+1; // tasks[i].w = (int)(Math.random() * 30); } tasks[0].id = 1;tasks[0].d = 4;tasks[0].w = 10; tasks[1].id = 2;tasks[1].d = 2;tasks[1].w = 20; tasks[2].id = 3;tasks[2].d = 4;tasks[2].w = 30; tasks[3].id = 4;tasks[3].d = 3;tasks[3].w = 40; tasks[4].id = 5;tasks[4].d = 1;tasks[4].w = 50; tasks[5].id = 6;tasks[5].d = 4;tasks[5].w = 60; tasks[6].id = 7;tasks[6].d = 6;tasks[6].w = 70; // tasks[0].id = 1;tasks[0].d = 4;tasks[0].w = 70; // tasks[1].id = 2;tasks[1].d = 2;tasks[1].w = 60; // tasks[2].id = 3;tasks[2].d = 4;tasks[2].w = 50; // tasks[3].id = 4;tasks[3].d = 3;tasks[3].w = 40; // tasks[4].id = 5;tasks[4].d = 1;tasks[4].w = 30; // tasks[5].id = 6;tasks[5].d = 4;tasks[5].w = 20; // tasks[6].id = 7;tasks[6].d = 6;tasks[6].w = 10; } public void sort_des(int n, Task[] tasks){ for(int i = 0; i < n-1; i++){ for(int j = i+1; j < n; j++){ if( tasks[i].w < tasks[j].w ){ Task temp = new Task(); temp = tasks[i]; tasks[i] = tasks[j]; tasks[j] = temp; } } } } public void sort_asc(int n, Task[] tasks){ for(int i = 0; i < n-1; i++){ for(int j = i+1; j < n; j++){ if( tasks[i].d > tasks[j].d ){ Task temp = new Task(); temp = tasks[i]; tasks[i] = tasks[j]; tasks[j] = temp; } } } } public void run(int n, Task[] tasks, List<Task> a,List<Task> b){ int j = 0; for(int i=0;i<n;i++){ a.add(tasks[i]); if(N(i+1, a) == false){ b.add(tasks[i]); a.remove(j); }else{ j++; } } } public boolean N(int t, List<Task> a) { int length = a.size(); int total = 0; for(int i = 1; i <= t; i++ ){ total = 0; for(int j=0; j < length; j++){ if( a.get(j).d <= i){ total++; } } if( total > i){ return false; } } return true; } public void Print(int n, Task[] tasks){ for(int i=0;i<n;i++){ System.out.println("id:" + tasks[i].id +" d:"+ tasks[i].d +" w:"+ tasks[i].w ); } } public void Print(List<Task> tasks){ for(int i=0;i<tasks.size(); i++){ System.out.println("id:" + tasks.get(i).id +" d:"+ tasks.get(i).d +" w:"+ tasks.get(i).w ); } } public int result( Task[] tasks, List<Task> a, List<Task> b){ for(int i = 0; i < a.size(); i++){ tasks[i] = a.get(i); } sort_asc(a.size(), tasks); int punish = 0; for(int i = a.size(); i < a.size()+b.size(); i++){ tasks[i] = b.get(i-a.size()); punish += tasks[i].w; } return punish; } public static void main(String[] args){ //初始化数据 int n = 7; Task[] tasks = new Task[n]; List<Task> a = new ArrayList<Task>(); List<Task> b = new ArrayList<Task>(); Greed greed = new Greed(); greed.init_array(n,tasks); //按照惩罚降序排列 greed.sort_des(n,tasks); //贪心选择 greed.run(n,tasks,a,b); //输出初始全部任务 greed.Print(n,tasks); //输出提前任务 greed.Print(a); System.out.println("---"); //输出迟到任务 greed.Print(b); System.out.println("---"); //整合结果 System.out.println("punish:" + greed.result(tasks, a, b)); //输出最优调度序列 greed.Print(n,tasks); } }
csxiaoyaojianxian/JavaStudy
02-java数据结构算法/src/Greedy/Greed.java
1,662
//按照惩罚降序排列
line_comment
zh-cn
package Greedy; import java.util.ArrayList; import java.util.List; public class Greed { // 1.先将任务按照时间惩罚递减顺序进行排序, // 2.然后用贪心的思想,尽量把惩罚重的任务先放入待完成队列中。 public class Task{ public int id; public int d;//截止时间 public int w;//惩罚 } public void init_array(int n, Task[] tasks){ //生成随机数据 for(int i=0;i<n;i++){ tasks[i] = new Task(); // tasks[i].id = i; // tasks[i].d = (int)(Math.random() * (n-1))+1; // tasks[i].w = (int)(Math.random() * 30); } tasks[0].id = 1;tasks[0].d = 4;tasks[0].w = 10; tasks[1].id = 2;tasks[1].d = 2;tasks[1].w = 20; tasks[2].id = 3;tasks[2].d = 4;tasks[2].w = 30; tasks[3].id = 4;tasks[3].d = 3;tasks[3].w = 40; tasks[4].id = 5;tasks[4].d = 1;tasks[4].w = 50; tasks[5].id = 6;tasks[5].d = 4;tasks[5].w = 60; tasks[6].id = 7;tasks[6].d = 6;tasks[6].w = 70; // tasks[0].id = 1;tasks[0].d = 4;tasks[0].w = 70; // tasks[1].id = 2;tasks[1].d = 2;tasks[1].w = 60; // tasks[2].id = 3;tasks[2].d = 4;tasks[2].w = 50; // tasks[3].id = 4;tasks[3].d = 3;tasks[3].w = 40; // tasks[4].id = 5;tasks[4].d = 1;tasks[4].w = 30; // tasks[5].id = 6;tasks[5].d = 4;tasks[5].w = 20; // tasks[6].id = 7;tasks[6].d = 6;tasks[6].w = 10; } public void sort_des(int n, Task[] tasks){ for(int i = 0; i < n-1; i++){ for(int j = i+1; j < n; j++){ if( tasks[i].w < tasks[j].w ){ Task temp = new Task(); temp = tasks[i]; tasks[i] = tasks[j]; tasks[j] = temp; } } } } public void sort_asc(int n, Task[] tasks){ for(int i = 0; i < n-1; i++){ for(int j = i+1; j < n; j++){ if( tasks[i].d > tasks[j].d ){ Task temp = new Task(); temp = tasks[i]; tasks[i] = tasks[j]; tasks[j] = temp; } } } } public void run(int n, Task[] tasks, List<Task> a,List<Task> b){ int j = 0; for(int i=0;i<n;i++){ a.add(tasks[i]); if(N(i+1, a) == false){ b.add(tasks[i]); a.remove(j); }else{ j++; } } } public boolean N(int t, List<Task> a) { int length = a.size(); int total = 0; for(int i = 1; i <= t; i++ ){ total = 0; for(int j=0; j < length; j++){ if( a.get(j).d <= i){ total++; } } if( total > i){ return false; } } return true; } public void Print(int n, Task[] tasks){ for(int i=0;i<n;i++){ System.out.println("id:" + tasks[i].id +" d:"+ tasks[i].d +" w:"+ tasks[i].w ); } } public void Print(List<Task> tasks){ for(int i=0;i<tasks.size(); i++){ System.out.println("id:" + tasks.get(i).id +" d:"+ tasks.get(i).d +" w:"+ tasks.get(i).w ); } } public int result( Task[] tasks, List<Task> a, List<Task> b){ for(int i = 0; i < a.size(); i++){ tasks[i] = a.get(i); } sort_asc(a.size(), tasks); int punish = 0; for(int i = a.size(); i < a.size()+b.size(); i++){ tasks[i] = b.get(i-a.size()); punish += tasks[i].w; } return punish; } public static void main(String[] args){ //初始化数据 int n = 7; Task[] tasks = new Task[n]; List<Task> a = new ArrayList<Task>(); List<Task> b = new ArrayList<Task>(); Greed greed = new Greed(); greed.init_array(n,tasks); //按照 <SUF> greed.sort_des(n,tasks); //贪心选择 greed.run(n,tasks,a,b); //输出初始全部任务 greed.Print(n,tasks); //输出提前任务 greed.Print(a); System.out.println("---"); //输出迟到任务 greed.Print(b); System.out.println("---"); //整合结果 System.out.println("punish:" + greed.result(tasks, a, b)); //输出最优调度序列 greed.Print(n,tasks); } }
false
1,403
6
1,662
10
1,624
6
1,662
10
1,930
19
false
false
false
false
false
true
66287_2
package OIO; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 传统socket服务端 * */ public class OioServer { @SuppressWarnings("resource") public static void main(String[] args) throws Exception { ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); //创建socket服务,监听10101端口 ServerSocket server=new ServerSocket(10101); System.out.println("服务器启动!"); while(true){ //获取一个套接字(阻塞) final Socket socket = server.accept(); System.out.println("来个一个新客户端!"); newCachedThreadPool.execute(new Runnable() { @Override public void run() { //业务处理 handler(socket); } }); } } /** * 读取数据 * @param socket * @throws Exception */ public static void handler(Socket socket){ try { byte[] bytes = new byte[1024]; InputStream inputStream = socket.getInputStream(); while(true){ //读取数据(阻塞) int read = inputStream.read(bytes); if(read != -1){ System.out.println(new String(bytes, 0, read)); }else{ break; } } } catch (Exception e) { e.printStackTrace(); }finally{ try { System.out.println("socket关闭"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
csy512889371/learndemo
netty/IOServer/src/OIO/OioServer.java
437
//获取一个套接字(阻塞)
line_comment
zh-cn
package OIO; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 传统socket服务端 * */ public class OioServer { @SuppressWarnings("resource") public static void main(String[] args) throws Exception { ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); //创建socket服务,监听10101端口 ServerSocket server=new ServerSocket(10101); System.out.println("服务器启动!"); while(true){ //获取 <SUF> final Socket socket = server.accept(); System.out.println("来个一个新客户端!"); newCachedThreadPool.execute(new Runnable() { @Override public void run() { //业务处理 handler(socket); } }); } } /** * 读取数据 * @param socket * @throws Exception */ public static void handler(Socket socket){ try { byte[] bytes = new byte[1024]; InputStream inputStream = socket.getInputStream(); while(true){ //读取数据(阻塞) int read = inputStream.read(bytes); if(read != -1){ System.out.println(new String(bytes, 0, read)); }else{ break; } } } catch (Exception e) { e.printStackTrace(); }finally{ try { System.out.println("socket关闭"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
false
364
10
437
10
439
9
437
10
630
18
false
false
false
false
false
true
56544_1
package logistic; import java.util.List; import java.util.Map; public class LogisticModel { private double[] sts=null;//参数Θ private double a=0.1;//学习速率 private List<Map<String,Object>> list=null; public LogisticModel(List<Map<String,Object>> list){ this.list=list; Map<String,Object> map=list.get(0); double[] x=(double[])map.get("x"); sts=new double[x.length]; } public LogisticModel(){ } public double function(double[] xs){//函数模型 double re=0f; for(int i=0;i<xs.length;i++){ re+=xs[i]*sts[i]; } return 1/(Math.pow(Math.E, -re)+1);//logistic函数 } /** * @author Administrator * @Description 使用梯度下降算法进行函数参数更新(学习) * @date 2018年7月16日 下午2:28:09 */ public void update(){//模型参数的更新 double[] stss=new double[sts.length];//新的模型参数,此处单独用数组来装而不是直接对该参数赋值,是为了不影响下一个参数的学习,保证每个参数对应的都是同一个函数 int len=list.size(); for(int i=0;i<stss.length;i++){//遍历每一个参数 double sum=0f; for(Map<String,Object> map:list){ double[] xs=(double[])map.get("x"); double y=(double)map.get("y"); sum+=(function(xs)-y)*xs[i]; } //System.out.println("js---:"+a*(1.0f/len)*sum); stss[i]=sts[i]-a*(1.0f/len)*sum;//更新该参数 } sts=stss;//统一更新参数 } public double dj(){//代价函数 double sum=0f; for(Map<String,Object> map:list){ double[] xs=(double[])map.get("x"); double y=(double)map.get("y"); sum+=y*Math.log(function(xs))+(1-y)*Math.log(1-function(xs)); } return -(1.0f/list.size())*sum; } public void go(){ int sum=0;//参数迭代次数 int count=0; while(true){ double oldDj=dj();//迭代前损失 sum++; if(sum>=10000){//迭代次数不超过10000 break; } update();//迭代 double newDj=dj();//迭代后损失 if(Math.abs(newDj-oldDj)<0.00001){//两次误差 count++; if(count>10){//如果损失小于0.00001连续10次,则认为已经拟合 break; } }else{count=0;} } // for(int j=0;j<sts.length;j++){ // System.out.println("st"+j+":"+sts[j]+" "); // } System.out.println("dj:"+dj()+" sum:"+sum); } public double[] getSts() { return sts; } public void setSts(double[] sts) { this.sts = sts; } public List<Map<String, Object>> getList() { return list; } public void setList(List<Map<String, Object>> list) { this.list = list; } }
ctripcorp/C-OCR
Recognition/main/java/logistic/LogisticModel.java
962
//学习速率
line_comment
zh-cn
package logistic; import java.util.List; import java.util.Map; public class LogisticModel { private double[] sts=null;//参数Θ private double a=0.1;//学习 <SUF> private List<Map<String,Object>> list=null; public LogisticModel(List<Map<String,Object>> list){ this.list=list; Map<String,Object> map=list.get(0); double[] x=(double[])map.get("x"); sts=new double[x.length]; } public LogisticModel(){ } public double function(double[] xs){//函数模型 double re=0f; for(int i=0;i<xs.length;i++){ re+=xs[i]*sts[i]; } return 1/(Math.pow(Math.E, -re)+1);//logistic函数 } /** * @author Administrator * @Description 使用梯度下降算法进行函数参数更新(学习) * @date 2018年7月16日 下午2:28:09 */ public void update(){//模型参数的更新 double[] stss=new double[sts.length];//新的模型参数,此处单独用数组来装而不是直接对该参数赋值,是为了不影响下一个参数的学习,保证每个参数对应的都是同一个函数 int len=list.size(); for(int i=0;i<stss.length;i++){//遍历每一个参数 double sum=0f; for(Map<String,Object> map:list){ double[] xs=(double[])map.get("x"); double y=(double)map.get("y"); sum+=(function(xs)-y)*xs[i]; } //System.out.println("js---:"+a*(1.0f/len)*sum); stss[i]=sts[i]-a*(1.0f/len)*sum;//更新该参数 } sts=stss;//统一更新参数 } public double dj(){//代价函数 double sum=0f; for(Map<String,Object> map:list){ double[] xs=(double[])map.get("x"); double y=(double)map.get("y"); sum+=y*Math.log(function(xs))+(1-y)*Math.log(1-function(xs)); } return -(1.0f/list.size())*sum; } public void go(){ int sum=0;//参数迭代次数 int count=0; while(true){ double oldDj=dj();//迭代前损失 sum++; if(sum>=10000){//迭代次数不超过10000 break; } update();//迭代 double newDj=dj();//迭代后损失 if(Math.abs(newDj-oldDj)<0.00001){//两次误差 count++; if(count>10){//如果损失小于0.00001连续10次,则认为已经拟合 break; } }else{count=0;} } // for(int j=0;j<sts.length;j++){ // System.out.println("st"+j+":"+sts[j]+" "); // } System.out.println("dj:"+dj()+" sum:"+sum); } public double[] getSts() { return sts; } public void setSts(double[] sts) { this.sts = sts; } public List<Map<String, Object>> getList() { return list; } public void setList(List<Map<String, Object>> list) { this.list = list; } }
false
761
4
959
5
922
5
958
5
1,192
10
false
false
false
false
false
true
58325_3
package com.angelocyj.bodypart.region; /** * Created by angelo on 2015/2/28. */ public enum Region { HEAD ("头部", 1, LayoutSide.LEFT, 47, 38, 0), EYE ("眼部", 2, LayoutSide.LEFT, 49, 80, 0, 1), FACE ("面部", 5, LayoutSide.LEFT, 39, 121, 0, 2), THROAT ("咽喉", 6, LayoutSide.LEFT, 0, 199, 0, 3), EAR ("耳朵", 3, LayoutSide.RIGHT, 68, 82, 0), NOSEMOUTH ("口鼻", 4, LayoutSide.RIGHT, 0, 135, 0, 1), NECK ("脖子", 7, LayoutSide.RIGHT, 33, 192, 0, 2), SKIN ("皮肤", 17, LayoutSide.RIGHT, 0, 0, 0, 1), ARM("手臂", 10, LayoutSide.RIGHT, 170, 465, 335), HAND("手", 9, LayoutSide.LEFT, 245, 695, 545), SHOULDER("肩", 8, LayoutSide.LEFT, 120, 250, 338), CHEST("胸部", 11, LayoutSide.RIGHT, 59, 364, 125), ABDOMEN("腹部", 13, LayoutSide.LEFT, 0, 581, 415), WAIST("腰", 12, LayoutSide.LEFT, 112, 600, 415, 1), PELVIC("盆腔\n下体", 14, LayoutSide.RIGHT, 0, 687, 405), LEG("大腿", 15, LayoutSide.LEFT, 83, 877, 1026), FOOT("足", 16, LayoutSide.RIGHT, 56, 1313, 890), //1026 BACKNECK ("脖子", 7, LayoutSide.LEFT, 0, 168, 0, 1), BACKSHOULDER("肩", 8, LayoutSide.LEFT, 120, 250, 168), BACKHAND("手", 9, LayoutSide.LEFT, 245, 695, 168, 1), BACKARM("手臂", 10, LayoutSide.RIGHT, 170, 465, 168, 1), BACKBACK("背", 18, LayoutSide.RIGHT, 0, 420, 168), BACKWAIST("腰", 12, LayoutSide.LEFT, 120, 610, 538), BACKPELVIC("盆腔\n下体", 14, LayoutSide.LEFT, 0, 656, 538, 1), BACKHIP("臀部", 19, LayoutSide.RIGHT, 54, 666, 538), BACKANUSRECTUM("肛门\n直肠", 20, LayoutSide.RIGHT, 0, 703, 538, 1), BACKFOOT("足", 16, LayoutSide.LEFT, 56, 1313, 1026), BACKLEG("大腿", 15, LayoutSide.RIGHT, 83, 877, 890),//1026 OTHER("其他", 21, LayoutSide.RIGHT, 0, 0, 0), ALLDISEASE("全部症状", -1, LayoutSide.RIGHT, 0, 0, 0); private final String name; private final int value; private final int layoutSide; private final int offsetSX, offsetSY; //路径起始坐标点 private final int offsetDY; //部位中心点基准纵坐标 private int startX, startY; private final int offSetNum; //部位之间纵坐标偏移数 private int destinationY; // = offsetDY + RegionParam.OFFSET_Y * offsetNum Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY){ this(name, value, layoutSide, offsetSX, offsetSY, offsetDY, 0, 0, 0, 0); } Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY, final int offSetNum){ this(name, value, layoutSide, offsetSX, offsetSY, offsetDY, 0, 0, offSetNum, 0); } Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY, int startX, int startY, int offSetNum, int destinationY) { this.name = name; this.value = value; this.layoutSide = layoutSide; this.offsetSX = offsetSX; this.offsetSY = offsetSY; this.offsetDY = offsetDY; this.startX = startX; this.startY = startY; this.offSetNum = offSetNum; this.destinationY = destinationY; } @Override public String toString() { return this.name; } public static String getName(int value) { for (Region c : Region.values()) { if (c.getValue() == value) { return c.name; } } return null; } public String getName() { return name; } public int getValue() { return value; } public int getLayoutSide() { return layoutSide; } public int getOffsetSX() { return offsetSX; } public int getOffsetSY() { return offsetSY; } public int getOffsetDY() { return offsetDY; } public int getStartX() { return startX; } public void setStartX(int startX) { this.startX = startX; } public int getStartY() { return startY; } public void setStartY(int startY) { this.startY = startY; } public int getOffSetNum() { return offSetNum; } public int getDestinationY() { return destinationY; } public void setDestinationY(int destinationY) { this.destinationY = destinationY; } public static class LayoutSide { public final static int LEFT = 0; public final static int RIGHT = 1; } }
cu2mr/android-body-part
app/src/main/java/com/angelocyj/bodypart/region/Region.java
1,679
//路径起始坐标点
line_comment
zh-cn
package com.angelocyj.bodypart.region; /** * Created by angelo on 2015/2/28. */ public enum Region { HEAD ("头部", 1, LayoutSide.LEFT, 47, 38, 0), EYE ("眼部", 2, LayoutSide.LEFT, 49, 80, 0, 1), FACE ("面部", 5, LayoutSide.LEFT, 39, 121, 0, 2), THROAT ("咽喉", 6, LayoutSide.LEFT, 0, 199, 0, 3), EAR ("耳朵", 3, LayoutSide.RIGHT, 68, 82, 0), NOSEMOUTH ("口鼻", 4, LayoutSide.RIGHT, 0, 135, 0, 1), NECK ("脖子", 7, LayoutSide.RIGHT, 33, 192, 0, 2), SKIN ("皮肤", 17, LayoutSide.RIGHT, 0, 0, 0, 1), ARM("手臂", 10, LayoutSide.RIGHT, 170, 465, 335), HAND("手", 9, LayoutSide.LEFT, 245, 695, 545), SHOULDER("肩", 8, LayoutSide.LEFT, 120, 250, 338), CHEST("胸部", 11, LayoutSide.RIGHT, 59, 364, 125), ABDOMEN("腹部", 13, LayoutSide.LEFT, 0, 581, 415), WAIST("腰", 12, LayoutSide.LEFT, 112, 600, 415, 1), PELVIC("盆腔\n下体", 14, LayoutSide.RIGHT, 0, 687, 405), LEG("大腿", 15, LayoutSide.LEFT, 83, 877, 1026), FOOT("足", 16, LayoutSide.RIGHT, 56, 1313, 890), //1026 BACKNECK ("脖子", 7, LayoutSide.LEFT, 0, 168, 0, 1), BACKSHOULDER("肩", 8, LayoutSide.LEFT, 120, 250, 168), BACKHAND("手", 9, LayoutSide.LEFT, 245, 695, 168, 1), BACKARM("手臂", 10, LayoutSide.RIGHT, 170, 465, 168, 1), BACKBACK("背", 18, LayoutSide.RIGHT, 0, 420, 168), BACKWAIST("腰", 12, LayoutSide.LEFT, 120, 610, 538), BACKPELVIC("盆腔\n下体", 14, LayoutSide.LEFT, 0, 656, 538, 1), BACKHIP("臀部", 19, LayoutSide.RIGHT, 54, 666, 538), BACKANUSRECTUM("肛门\n直肠", 20, LayoutSide.RIGHT, 0, 703, 538, 1), BACKFOOT("足", 16, LayoutSide.LEFT, 56, 1313, 1026), BACKLEG("大腿", 15, LayoutSide.RIGHT, 83, 877, 890),//1026 OTHER("其他", 21, LayoutSide.RIGHT, 0, 0, 0), ALLDISEASE("全部症状", -1, LayoutSide.RIGHT, 0, 0, 0); private final String name; private final int value; private final int layoutSide; private final int offsetSX, offsetSY; //路径 <SUF> private final int offsetDY; //部位中心点基准纵坐标 private int startX, startY; private final int offSetNum; //部位之间纵坐标偏移数 private int destinationY; // = offsetDY + RegionParam.OFFSET_Y * offsetNum Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY){ this(name, value, layoutSide, offsetSX, offsetSY, offsetDY, 0, 0, 0, 0); } Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY, final int offSetNum){ this(name, value, layoutSide, offsetSX, offsetSY, offsetDY, 0, 0, offSetNum, 0); } Region(final String name, final int value, final int layoutSide, final int offsetSX, final int offsetSY, final int offsetDY, int startX, int startY, int offSetNum, int destinationY) { this.name = name; this.value = value; this.layoutSide = layoutSide; this.offsetSX = offsetSX; this.offsetSY = offsetSY; this.offsetDY = offsetDY; this.startX = startX; this.startY = startY; this.offSetNum = offSetNum; this.destinationY = destinationY; } @Override public String toString() { return this.name; } public static String getName(int value) { for (Region c : Region.values()) { if (c.getValue() == value) { return c.name; } } return null; } public String getName() { return name; } public int getValue() { return value; } public int getLayoutSide() { return layoutSide; } public int getOffsetSX() { return offsetSX; } public int getOffsetSY() { return offsetSY; } public int getOffsetDY() { return offsetDY; } public int getStartX() { return startX; } public void setStartX(int startX) { this.startX = startX; } public int getStartY() { return startY; } public void setStartY(int startY) { this.startY = startY; } public int getOffSetNum() { return offSetNum; } public int getDestinationY() { return destinationY; } public void setDestinationY(int destinationY) { this.destinationY = destinationY; } public static class LayoutSide { public final static int LEFT = 0; public final static int RIGHT = 1; } }
false
1,554
7
1,677
7
1,710
6
1,677
7
1,942
13
false
false
false
false
false
true
20659_4
package ppoly; /** * Main是master主人类 */ public class Main { private String name; public Main(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } /*使用多态机制,统一管理主人喂食物问题*/ public void feed(Animal animal,Food food) { //直接用父类来管理 System.out.println("主人 " + name + "给" + animal.getName()+"吃"+food.getName()); } //主任给小狗喂食物 bone public void feed(Dog dog,Bone bone) { System.out.println("主人 " + name + "给" + dog.getName()+"吃"+bone.getName()); } /*主任给小猫喂黄花鱼*/ public void feed(Cat cat,Fish fish) { /*构成方法的重载*/ System.out.println("主人 " + name + "给" + cat.getName()+"吃"+fish.getName()); } }
cubxxw/awesome-cs-course
java/code/Java_charater/src/main/java/ppoly/Main.java
264
/*主任给小猫喂黄花鱼*/
block_comment
zh-cn
package ppoly; /** * Main是master主人类 */ public class Main { private String name; public Main(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } /*使用多态机制,统一管理主人喂食物问题*/ public void feed(Animal animal,Food food) { //直接用父类来管理 System.out.println("主人 " + name + "给" + animal.getName()+"吃"+food.getName()); } //主任给小狗喂食物 bone public void feed(Dog dog,Bone bone) { System.out.println("主人 " + name + "给" + dog.getName()+"吃"+bone.getName()); } /*主任给 <SUF>*/ public void feed(Cat cat,Fish fish) { /*构成方法的重载*/ System.out.println("主人 " + name + "给" + cat.getName()+"吃"+fish.getName()); } }
false
228
10
264
13
272
10
264
13
331
17
false
false
false
false
false
true
22438_1
/* 逻辑运算符 & 逻辑与 | 逻辑或 ! 逻辑非 ^ 逻辑异或 && 短路与 || 运行:javac -encoding utf-8 LogicTest.java && java LogicTest * */ class LogicTest { public static void main(String[] agrs) { boolean a = true; boolean b = false; System.out.println("a: " + a); System.out.println("b: " + b); System.out.println("a & b => " + (a & b)); System.out.println("a | b => " + (a | b)); System.out.println("!a => " + (!a)); System.out.println("a ^ b => " + (a ^ b)); System.out.println("a && b => " + (a && b)); System.out.println("a || b => " + (a || b)); System.out.println("############\n\n"); // & 与 &&区别: /* &:无论左边为true还是false,右边都会进行运算 &&:当左边为false时,右边不再进行运算,还可规避右边的错误 只有当左边为false时,&与&&才有区别,其他情况两都一样 建议使用 && * */ boolean c = false; int i27 = 10; if (c & (i27++) > 0) { System.out.println("结果为true"); } else { System.out.println("结果为false"); } System.out.println("i27: " + i27); // 11 int i35 = 10; if (c && (i35++) > 0) { System.out.println("结果为true"); } else { System.out.println("结果为false"); } System.out.println("i35: " + i35); // 10 /* if (c & 10 / 0 == 0) { // javac能正常编译,java运行时报错:Exception in thread "main" java.lang.ArithmeticException: / by zero System.out.println("情况1:。。。"); } else { System.out.println("情况2:。。。"); } */ if (c && 10 / 0 == 0) { // 正常 System.out.println("情况1:。。。"); } else { System.out.println("情况2:。。。"); } System.out.println("###\n\n"); // |与||区别 /* |:无论左边为true或false,右边都会进行运行 ||:左边为true时,右边不再进行运算,是|的智能版 推荐使用|| * */ c = true; int i67 = 10; if (c | (i67++) > 0) { System.out.println("情况1:。。。"); } else { System.out.println("情况2:。。。"); } System.out.println("i67: " + i67); // 11 i67 = 10; if (c || (i67++) > 0) { System.out.println("情况1:。。。"); } else { System.out.println("情况2:。。。"); } System.out.println("i67: " + i67); // 10 int x = 1; int y = 1; if (x++ == 2) { // 这里后加,先计算,这时候1 != 2 System.out.println("case 1: "+ x); } else { System.out.println("case 2:" + x); } } }
cucker0/java
day02/LogicTest.java
907
// & 与 &&区别:
line_comment
zh-cn
/* 逻辑运算符 & 逻辑与 | 逻辑或 ! 逻辑非 ^ 逻辑异或 && 短路与 || 运行:javac -encoding utf-8 LogicTest.java && java LogicTest * */ class LogicTest { public static void main(String[] agrs) { boolean a = true; boolean b = false; System.out.println("a: " + a); System.out.println("b: " + b); System.out.println("a & b => " + (a & b)); System.out.println("a | b => " + (a | b)); System.out.println("!a => " + (!a)); System.out.println("a ^ b => " + (a ^ b)); System.out.println("a && b => " + (a && b)); System.out.println("a || b => " + (a || b)); System.out.println("############\n\n"); // & <SUF> /* &:无论左边为true还是false,右边都会进行运算 &&:当左边为false时,右边不再进行运算,还可规避右边的错误 只有当左边为false时,&与&&才有区别,其他情况两都一样 建议使用 && * */ boolean c = false; int i27 = 10; if (c & (i27++) > 0) { System.out.println("结果为true"); } else { System.out.println("结果为false"); } System.out.println("i27: " + i27); // 11 int i35 = 10; if (c && (i35++) > 0) { System.out.println("结果为true"); } else { System.out.println("结果为false"); } System.out.println("i35: " + i35); // 10 /* if (c & 10 / 0 == 0) { // javac能正常编译,java运行时报错:Exception in thread "main" java.lang.ArithmeticException: / by zero System.out.println("情况1:。。。"); } else { System.out.println("情况2:。。。"); } */ if (c && 10 / 0 == 0) { // 正常 System.out.println("情况1:。。。"); } else { System.out.println("情况2:。。。"); } System.out.println("###\n\n"); // |与||区别 /* |:无论左边为true或false,右边都会进行运行 ||:左边为true时,右边不再进行运算,是|的智能版 推荐使用|| * */ c = true; int i67 = 10; if (c | (i67++) > 0) { System.out.println("情况1:。。。"); } else { System.out.println("情况2:。。。"); } System.out.println("i67: " + i67); // 11 i67 = 10; if (c || (i67++) > 0) { System.out.println("情况1:。。。"); } else { System.out.println("情况2:。。。"); } System.out.println("i67: " + i67); // 10 int x = 1; int y = 1; if (x++ == 2) { // 这里后加,先计算,这时候1 != 2 System.out.println("case 1: "+ x); } else { System.out.println("case 2:" + x); } } }
false
831
7
907
8
946
6
907
8
1,117
10
false
false
false
false
false
true
58128_1
package com.jk.config.cache; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; /** * @author cuiP * Created by JK on 2017/3/13. */ @Configuration @EnableCaching//标注启动缓存. public class EhCacheConfig { /** * ehcache 主要的管理器 * @param ehCacheManagerFactoryBean * @return */ @Bean public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean ehCacheManagerFactoryBean){ return new EhCacheCacheManager(ehCacheManagerFactoryBean.getObject()); } /* * 据shared与否的设置, * Spring分别通过CacheManager.create() * 或new CacheManager()方式来创建一个ehcache基地. * * 也说是说通过这个来设置cache的基地是这里的Spring独用,还是跟别的(如hibernate的Ehcache共享) * */ @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){ EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean (); cacheManagerFactoryBean.setConfigLocation (new ClassPathResource("ehcache-shiro.xml")); cacheManagerFactoryBean.setShared(true); return cacheManagerFactoryBean; } }
cuipengcx/good
src/main/java/com/jk/config/cache/EhCacheConfig.java
357
//标注启动缓存.
line_comment
zh-cn
package com.jk.config.cache; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.ehcache.EhCacheCacheManager; import org.springframework.cache.ehcache.EhCacheManagerFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.ClassPathResource; /** * @author cuiP * Created by JK on 2017/3/13. */ @Configuration @EnableCaching//标注 <SUF> public class EhCacheConfig { /** * ehcache 主要的管理器 * @param ehCacheManagerFactoryBean * @return */ @Bean public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean ehCacheManagerFactoryBean){ return new EhCacheCacheManager(ehCacheManagerFactoryBean.getObject()); } /* * 据shared与否的设置, * Spring分别通过CacheManager.create() * 或new CacheManager()方式来创建一个ehcache基地. * * 也说是说通过这个来设置cache的基地是这里的Spring独用,还是跟别的(如hibernate的Ehcache共享) * */ @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){ EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean (); cacheManagerFactoryBean.setConfigLocation (new ClassPathResource("ehcache-shiro.xml")); cacheManagerFactoryBean.setShared(true); return cacheManagerFactoryBean; } }
false
329
6
357
6
353
6
357
6
446
12
false
false
false
false
false
true
66345_1
package com.txxia.game.fivechess.game; import java.util.Deque; import java.util.LinkedList; import android.os.Handler; import android.os.Message; /** * 处理游戏逻辑 * @author cuiqing */ public class Game { public static final int SCALE_SMALL = 11; public static final int SCALE_MEDIUM = 15; public static final int SCALE_LARGE = 19; // 自己 Player me; // 对手 Player challenger; private int mMode = 0; // 默认黑子先出 private int mActive = 1; int mGameWidth = 0; int mGameHeight = 0; int[][] mGameMap = null; Deque<Coordinate> mActions ; public static final int BLACK = 1; public static final int WHITE = 2; private Handler mNotify; public Game(Handler h, Player me, Player challenger){ this(h, me, challenger, SCALE_MEDIUM, SCALE_MEDIUM); } public Game(Handler h, Player me, Player challenger, int width, int height){ mNotify = h; this.me = me; this.challenger = challenger; mGameWidth = width; mGameHeight = height; mGameMap = new int[mGameWidth][mGameHeight]; mActions = new LinkedList<Coordinate>(); } public void setMode(int mode){ this.mMode = mode; } public int getMode(){ return mMode; } /** * 悔棋一子 * @return 是否可以悔棋 */ public boolean rollback(){ Coordinate c = mActions.pollLast(); if (c != null){ mGameMap[c.x][c.y] = 0; changeActive(); return true; } return false; } /** * 游戏宽度 * @return 棋盘的列数 */ public int getWidth(){ return mGameWidth; } /** * 游戏高度 * @return 棋盘横数 */ public int getHeight(){ return mGameHeight; } /** * 落子 * @param x 横向下标 * @param y 纵向下标 * @return 当前位置是否可以下子 */ public boolean addChess(int x, int y){ if (mMode == GameConstants.MODE_FIGHT){ if(mGameMap[x][y] == 0){ int type ; if (mActive == BLACK){ mGameMap[x][y] = BLACK; type = Game.BLACK; } else { mGameMap[x][y] = WHITE; type = Game.WHITE; } if(!isGameEnd(x, y, type)){ changeActive(); sendAddChess(x, y); mActions.add(new Coordinate(x, y)); } return true; } } else if(mMode == GameConstants.MODE_NET) { if(mActive == me.type && mGameMap[x][y] == 0){ mGameMap[x][y] = me.type; mActive = challenger.type; if(!isGameEnd(x, y, me.type)){ mActions.add(new Coordinate(x, y)); } sendAddChess(x, y); return true; } } else if(mMode == GameConstants.MODE_SINGLE){ if(mActive == me.type && mGameMap[x][y] == 0){ mGameMap[x][y] = me.type; mActive = challenger.type; if(!isGameEnd(x, y, me.type)){ sendAddChess(x, y); mActions.add(new Coordinate(x, y)); } return true; } } return false; } /** * 落子 * @param x 横向下标 * @param y 纵向下标 * @param player 游戏选手 */ public void addChess(int x, int y, Player player){ if(mGameMap[x][y] == 0){ mGameMap[x][y] = player.type; mActions.add(new Coordinate(x, y)); boolean isEnd = isGameEnd(x, y, player.type); mActive = me.type; if(!isEnd){ mNotify.sendEmptyMessage(GameConstants.ACTIVE_CHANGE); } } } /** * 落子 * @param c 下子位置 * @param player 游戏选手 */ public void addChess(Coordinate c, Player player){ addChess(c.x, c.y, player); } public static int getFighter(int type){ if (type == BLACK){ return WHITE; } else { return BLACK; } } /** * 返回当前落子方 * @return mActive */ public int getActive(){ return mActive; } /** * 获取棋盘 * @return 棋盘数据 */ public int[][] getChessMap(){ return mGameMap; } /** * 获取棋盘历史 * @return mActions */ public Deque<Coordinate> getActions(){ return mActions; } /** * 重置游戏 */ public void reset(){ mGameMap = new int[mGameWidth][mGameHeight]; mActive = BLACK; mActions.clear(); } /** * 不需要更新落子方,谁输谁先手 */ public void resetNet(){ mGameMap = new int[mGameWidth][mGameHeight]; mActions.clear(); } private void changeActive(){ if(mActive == BLACK){ mActive = WHITE; } else { mActive = BLACK; } } private void sendAddChess(int x, int y){ Message msg = new Message(); msg.what = GameConstants.ADD_CHESS; msg.arg1 = x; msg.arg2 = y; mNotify.sendMessage(msg); } // 判断是否五子连珠 private boolean isGameEnd(int x, int y, int type){ int leftX = x-4 > 0? x-4 : 0; int rightX = x+4 < mGameWidth-1 ? x+4: mGameWidth-1; int topY = y-4 > 0? y-4 : 0; int bottomY = y + 4< mGameHeight-1 ? y+4: mGameHeight-1; int horizontal = 1; // 横向向左 for (int i = x - 1; i >= leftX ; --i){ if (mGameMap[i][y] != type){ break; } ++horizontal; } // 横向向右 for (int i = x + 1; i <= rightX ; ++i){ if (mGameMap[i][y] != type){ break; } ++horizontal; } if (horizontal>=5) { sendGameResult(type); return true; } int vertical = 1; // 纵向向上 for (int j = y - 1; j >= topY ; --j){ if (mGameMap[x][j] != type){ break; } ++vertical; } // 纵向向下 for (int j = y + 1; j <= bottomY ; ++j){ if (mGameMap[x][j] != type){ break; } ++vertical; } if (vertical >= 5) { sendGameResult(type); return true; } int leftOblique = 1; // 左斜向上 for (int i = x + 1,j = y - 1; i <= rightX && j >= topY ; ++i, --j){ if (mGameMap[i][j] != type){ break; } ++leftOblique; } // 左斜向下 for (int i = x - 1,j = y + 1; i >= leftX && j <= bottomY ; --i, ++j){ if (mGameMap[i][j] != type){ break; } ++leftOblique; } if (leftOblique >= 5) { sendGameResult(type); return true; } int rightOblique = 1; // 右斜向上 for (int i = x - 1,j = y - 1; i >= leftX && j >= topY ; --i, --j){ if (mGameMap[i][j] != type){ break; } ++rightOblique; } // 右斜向下 for (int i = x + 1,j = y + 1; i <= rightX && j <= bottomY ; ++i, ++j){ if (mGameMap[i][j] != type){ break; } ++rightOblique; } if (rightOblique >= 5) { sendGameResult(type); return true; } return false; } private void sendGameResult(int player){ Message msg = Message.obtain(); msg.what = GameConstants.GAME_OVER; msg.arg1 = player; mNotify.sendMessage(msg); } }
cuiqingandroid/FiveChess
app/src/main/java/com/txxia/game/fivechess/game/Game.java
2,236
// 默认黑子先出
line_comment
zh-cn
package com.txxia.game.fivechess.game; import java.util.Deque; import java.util.LinkedList; import android.os.Handler; import android.os.Message; /** * 处理游戏逻辑 * @author cuiqing */ public class Game { public static final int SCALE_SMALL = 11; public static final int SCALE_MEDIUM = 15; public static final int SCALE_LARGE = 19; // 自己 Player me; // 对手 Player challenger; private int mMode = 0; // 默认 <SUF> private int mActive = 1; int mGameWidth = 0; int mGameHeight = 0; int[][] mGameMap = null; Deque<Coordinate> mActions ; public static final int BLACK = 1; public static final int WHITE = 2; private Handler mNotify; public Game(Handler h, Player me, Player challenger){ this(h, me, challenger, SCALE_MEDIUM, SCALE_MEDIUM); } public Game(Handler h, Player me, Player challenger, int width, int height){ mNotify = h; this.me = me; this.challenger = challenger; mGameWidth = width; mGameHeight = height; mGameMap = new int[mGameWidth][mGameHeight]; mActions = new LinkedList<Coordinate>(); } public void setMode(int mode){ this.mMode = mode; } public int getMode(){ return mMode; } /** * 悔棋一子 * @return 是否可以悔棋 */ public boolean rollback(){ Coordinate c = mActions.pollLast(); if (c != null){ mGameMap[c.x][c.y] = 0; changeActive(); return true; } return false; } /** * 游戏宽度 * @return 棋盘的列数 */ public int getWidth(){ return mGameWidth; } /** * 游戏高度 * @return 棋盘横数 */ public int getHeight(){ return mGameHeight; } /** * 落子 * @param x 横向下标 * @param y 纵向下标 * @return 当前位置是否可以下子 */ public boolean addChess(int x, int y){ if (mMode == GameConstants.MODE_FIGHT){ if(mGameMap[x][y] == 0){ int type ; if (mActive == BLACK){ mGameMap[x][y] = BLACK; type = Game.BLACK; } else { mGameMap[x][y] = WHITE; type = Game.WHITE; } if(!isGameEnd(x, y, type)){ changeActive(); sendAddChess(x, y); mActions.add(new Coordinate(x, y)); } return true; } } else if(mMode == GameConstants.MODE_NET) { if(mActive == me.type && mGameMap[x][y] == 0){ mGameMap[x][y] = me.type; mActive = challenger.type; if(!isGameEnd(x, y, me.type)){ mActions.add(new Coordinate(x, y)); } sendAddChess(x, y); return true; } } else if(mMode == GameConstants.MODE_SINGLE){ if(mActive == me.type && mGameMap[x][y] == 0){ mGameMap[x][y] = me.type; mActive = challenger.type; if(!isGameEnd(x, y, me.type)){ sendAddChess(x, y); mActions.add(new Coordinate(x, y)); } return true; } } return false; } /** * 落子 * @param x 横向下标 * @param y 纵向下标 * @param player 游戏选手 */ public void addChess(int x, int y, Player player){ if(mGameMap[x][y] == 0){ mGameMap[x][y] = player.type; mActions.add(new Coordinate(x, y)); boolean isEnd = isGameEnd(x, y, player.type); mActive = me.type; if(!isEnd){ mNotify.sendEmptyMessage(GameConstants.ACTIVE_CHANGE); } } } /** * 落子 * @param c 下子位置 * @param player 游戏选手 */ public void addChess(Coordinate c, Player player){ addChess(c.x, c.y, player); } public static int getFighter(int type){ if (type == BLACK){ return WHITE; } else { return BLACK; } } /** * 返回当前落子方 * @return mActive */ public int getActive(){ return mActive; } /** * 获取棋盘 * @return 棋盘数据 */ public int[][] getChessMap(){ return mGameMap; } /** * 获取棋盘历史 * @return mActions */ public Deque<Coordinate> getActions(){ return mActions; } /** * 重置游戏 */ public void reset(){ mGameMap = new int[mGameWidth][mGameHeight]; mActive = BLACK; mActions.clear(); } /** * 不需要更新落子方,谁输谁先手 */ public void resetNet(){ mGameMap = new int[mGameWidth][mGameHeight]; mActions.clear(); } private void changeActive(){ if(mActive == BLACK){ mActive = WHITE; } else { mActive = BLACK; } } private void sendAddChess(int x, int y){ Message msg = new Message(); msg.what = GameConstants.ADD_CHESS; msg.arg1 = x; msg.arg2 = y; mNotify.sendMessage(msg); } // 判断是否五子连珠 private boolean isGameEnd(int x, int y, int type){ int leftX = x-4 > 0? x-4 : 0; int rightX = x+4 < mGameWidth-1 ? x+4: mGameWidth-1; int topY = y-4 > 0? y-4 : 0; int bottomY = y + 4< mGameHeight-1 ? y+4: mGameHeight-1; int horizontal = 1; // 横向向左 for (int i = x - 1; i >= leftX ; --i){ if (mGameMap[i][y] != type){ break; } ++horizontal; } // 横向向右 for (int i = x + 1; i <= rightX ; ++i){ if (mGameMap[i][y] != type){ break; } ++horizontal; } if (horizontal>=5) { sendGameResult(type); return true; } int vertical = 1; // 纵向向上 for (int j = y - 1; j >= topY ; --j){ if (mGameMap[x][j] != type){ break; } ++vertical; } // 纵向向下 for (int j = y + 1; j <= bottomY ; ++j){ if (mGameMap[x][j] != type){ break; } ++vertical; } if (vertical >= 5) { sendGameResult(type); return true; } int leftOblique = 1; // 左斜向上 for (int i = x + 1,j = y - 1; i <= rightX && j >= topY ; ++i, --j){ if (mGameMap[i][j] != type){ break; } ++leftOblique; } // 左斜向下 for (int i = x - 1,j = y + 1; i >= leftX && j <= bottomY ; --i, ++j){ if (mGameMap[i][j] != type){ break; } ++leftOblique; } if (leftOblique >= 5) { sendGameResult(type); return true; } int rightOblique = 1; // 右斜向上 for (int i = x - 1,j = y - 1; i >= leftX && j >= topY ; --i, --j){ if (mGameMap[i][j] != type){ break; } ++rightOblique; } // 右斜向下 for (int i = x + 1,j = y + 1; i <= rightX && j <= bottomY ; ++i, ++j){ if (mGameMap[i][j] != type){ break; } ++rightOblique; } if (rightOblique >= 5) { sendGameResult(type); return true; } return false; } private void sendGameResult(int player){ Message msg = Message.obtain(); msg.what = GameConstants.GAME_OVER; msg.arg1 = player; mNotify.sendMessage(msg); } }
false
2,134
6
2,236
6
2,492
6
2,236
6
2,789
10
false
false
false
false
false
true
59398_1
package com.tzq.commons.enums; public enum AgeTypeEunm { // 0 成人/1 儿童/2 婴儿 ADT(0, "成人","ADT"), CHD(1, "儿童","CHD"), INF(2, "婴儿","INF"),; /** * 枚举编码 */ private int code; /** * 枚举描述 */ private String desc; private String remark; public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } /** * 私有构造函数 */ AgeTypeEunm(int code, String desc,String remark) { this.code = code; this.desc = desc; this.remark = remark; } /** * 获取枚举类型 * * @param code 枚举码 * @return */ public static AgeTypeEunm getEnumByCode(int code) { if (code < 0 || code > 2) { return null; } for (AgeTypeEunm e : AgeTypeEunm.values()) { if (code == e.getCode()) { return e; } } return null; } /** * 获取枚举编码 * * @return */ public int getCode() { return code; } /** * 获取枚举描述 * * @return */ public String getDesc() { return desc; } }
cuittzq/FlightIntegration
commons/src/main/java/com/tzq/commons/enums/AgeTypeEunm.java
363
/** * 枚举编码 */
block_comment
zh-cn
package com.tzq.commons.enums; public enum AgeTypeEunm { // 0 成人/1 儿童/2 婴儿 ADT(0, "成人","ADT"), CHD(1, "儿童","CHD"), INF(2, "婴儿","INF"),; /** * 枚举编 <SUF>*/ private int code; /** * 枚举描述 */ private String desc; private String remark; public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } /** * 私有构造函数 */ AgeTypeEunm(int code, String desc,String remark) { this.code = code; this.desc = desc; this.remark = remark; } /** * 获取枚举类型 * * @param code 枚举码 * @return */ public static AgeTypeEunm getEnumByCode(int code) { if (code < 0 || code > 2) { return null; } for (AgeTypeEunm e : AgeTypeEunm.values()) { if (code == e.getCode()) { return e; } } return null; } /** * 获取枚举编码 * * @return */ public int getCode() { return code; } /** * 获取枚举描述 * * @return */ public String getDesc() { return desc; } }
false
353
10
363
9
396
10
363
9
498
16
false
false
false
false
false
true
24661_0
package com.cwj.we.module.ljxj; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.atech.glcamera.interfaces.FileCallback; import com.atech.glcamera.utils.FileUtils; import com.atech.glcamera.utils.FilterFactory; import com.atech.glcamera.views.GLCameraView; import com.cwj.we.R; import com.cwj.we.utils.OneClickThree; import com.cwj.we.utils.ToastUtil; import com.gyf.immersionbar.ImmersionBar; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; /** * 滤镜相机 */ public class OpenCameraActivity extends AppCompatActivity implements View.OnClickListener { ImageView imgSwitch; ImageView imgFilter; ImageView imgCapter; GLCameraView mCameraView; RecyclerView rv; private ImageView iv; private boolean mRecordingEnabled = false; // controls button state private int mode = 1; //1.capture 2.record private List<FilterFactory.FilterType> filters = new ArrayList<>(); private List<FilterInfo> infos = new ArrayList<>(); private boolean isShowing = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_open_camera); ImmersionBar.with(this) .init(); imgCapter = findViewById(R.id.img_capture); imgSwitch = findViewById(R.id.img_switch); imgFilter = findViewById(R.id.img_filter); mCameraView = findViewById(R.id.glcamera); rv = findViewById(R.id.rv); iv = findViewById(R.id.iv); imgSwitch.setOnClickListener(this); imgFilter.setOnClickListener(this); imgCapter.setOnClickListener(this); iv.setOnClickListener(this); initFilters(); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); FilterAdapter adapter = new FilterAdapter(this, infos); rv.setAdapter(adapter); rv.setLayoutManager(linearLayoutManager); adapter.setFilterSeletedListener(pos -> mCameraView.updateFilter(filters.get(pos))); mCameraView.setOnClickListener(v -> { if (isShowing) { rv.setVisibility(View.INVISIBLE); isShowing = false; } }); mCameraView.enableBeauty(true); } private void initFilters() { filters.add(FilterFactory.FilterType.Original); filters.add(FilterFactory.FilterType.Sunrise); filters.add(FilterFactory.FilterType.Sunset); filters.add(FilterFactory.FilterType.BlackWhite); filters.add(FilterFactory.FilterType.WhiteCat); filters.add(FilterFactory.FilterType.BlackCat); filters.add(FilterFactory.FilterType.Beauty); filters.add(FilterFactory.FilterType.Healthy); filters.add(FilterFactory.FilterType.Sakura); filters.add(FilterFactory.FilterType.Romance); filters.add(FilterFactory.FilterType.Latte); filters.add(FilterFactory.FilterType.Warm); filters.add(FilterFactory.FilterType.Calm); filters.add(FilterFactory.FilterType.Cool); filters.add(FilterFactory.FilterType.Brooklyn); filters.add(FilterFactory.FilterType.Amaro); filters.add(FilterFactory.FilterType.Antique); filters.add(FilterFactory.FilterType.Brannan); infos.add(new FilterInfo(R.drawable.filter_thumb_original, "原图")); infos.add(new FilterInfo(R.drawable.filter_thumb_sunrise, "日出")); infos.add(new FilterInfo(R.drawable.filter_thumb_sunset, "日落")); infos.add(new FilterInfo(R.drawable.filter_thumb_1977, "黑白")); infos.add(new FilterInfo(R.drawable.filter_thumb_whitecat, "白猫")); infos.add(new FilterInfo(R.drawable.filter_thumb_blackcat, "黑猫")); infos.add(new FilterInfo(R.drawable.filter_thumb_beauty, "美白")); infos.add(new FilterInfo(R.drawable.filter_thumb_healthy, "健康")); infos.add(new FilterInfo(R.drawable.filter_thumb_sakura, "樱花")); infos.add(new FilterInfo(R.drawable.filter_thumb_romance, "浪漫")); infos.add(new FilterInfo(R.drawable.filter_thumb_latte, "拿铁")); infos.add(new FilterInfo(R.drawable.filter_thumb_warm, "温暖")); infos.add(new FilterInfo(R.drawable.filter_thumb_calm, "安静")); infos.add(new FilterInfo(R.drawable.filter_thumb_cool, "寒冷")); infos.add(new FilterInfo(R.drawable.filter_thumb_brooklyn, "纽约")); infos.add(new FilterInfo(R.drawable.filter_thumb_amoro, "Amaro")); infos.add(new FilterInfo(R.drawable.filter_thumb_antique, "复古")); infos.add(new FilterInfo(R.drawable.filter_thumb_brannan, "Brannan")); //set your own output file here // mCameraView.setOuputMP4File(); //set record finish listener mCameraView.setrecordFinishedListnener(new FileCallback() { @Override public void onData(File file) { //update the gallery sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file))); } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv://相册 if (!OneClickThree.isFastClick()) { startActivity(new Intent(this, PhotoListActivity.class)); } break; case R.id.img_switch: mCameraView.switchCamera(); break; case R.id.img_filter: if (isShowing) { rv.setVisibility(View.INVISIBLE); } else { rv.setVisibility(View.VISIBLE); } isShowing = !isShowing; break; case R.id.img_capture: if (mode == 1) { onCapture(); } else { onRecord(); } break; } } private void onCapture() { mCameraView.takePicture(bitmap -> { File file = FileUtils.createImageFile(); //重新写入文件 try { // 写入文件 FileOutputStream fos; fos = new FileOutputStream(file); //默认jpg bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); bitmap.recycle(); sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file))); ToastUtil.showTextToast(OpenCameraActivity.this, "已保存"); } catch (Exception e) { e.printStackTrace(); } }); } @Override protected void onStop() { super.onStop(); mRecordingEnabled = false; mCameraView.changeRecordingState(mRecordingEnabled); } private void onRecord() { mRecordingEnabled = !mRecordingEnabled; mCameraView.changeRecordingState(mRecordingEnabled); if (mRecordingEnabled) { ToastUtil.showTextToast(OpenCameraActivity.this, "开始"); } else { ToastUtil.showTextToast(OpenCameraActivity.this, "完成"); } } }
cuiwenju2017/We
app/src/main/java/com/cwj/we/module/ljxj/OpenCameraActivity.java
1,913
/** * 滤镜相机 */
block_comment
zh-cn
package com.cwj.we.module.ljxj; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.atech.glcamera.interfaces.FileCallback; import com.atech.glcamera.utils.FileUtils; import com.atech.glcamera.utils.FilterFactory; import com.atech.glcamera.views.GLCameraView; import com.cwj.we.R; import com.cwj.we.utils.OneClickThree; import com.cwj.we.utils.ToastUtil; import com.gyf.immersionbar.ImmersionBar; import java.io.File; import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; /** * 滤镜相 <SUF>*/ public class OpenCameraActivity extends AppCompatActivity implements View.OnClickListener { ImageView imgSwitch; ImageView imgFilter; ImageView imgCapter; GLCameraView mCameraView; RecyclerView rv; private ImageView iv; private boolean mRecordingEnabled = false; // controls button state private int mode = 1; //1.capture 2.record private List<FilterFactory.FilterType> filters = new ArrayList<>(); private List<FilterInfo> infos = new ArrayList<>(); private boolean isShowing = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_open_camera); ImmersionBar.with(this) .init(); imgCapter = findViewById(R.id.img_capture); imgSwitch = findViewById(R.id.img_switch); imgFilter = findViewById(R.id.img_filter); mCameraView = findViewById(R.id.glcamera); rv = findViewById(R.id.rv); iv = findViewById(R.id.iv); imgSwitch.setOnClickListener(this); imgFilter.setOnClickListener(this); imgCapter.setOnClickListener(this); iv.setOnClickListener(this); initFilters(); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); FilterAdapter adapter = new FilterAdapter(this, infos); rv.setAdapter(adapter); rv.setLayoutManager(linearLayoutManager); adapter.setFilterSeletedListener(pos -> mCameraView.updateFilter(filters.get(pos))); mCameraView.setOnClickListener(v -> { if (isShowing) { rv.setVisibility(View.INVISIBLE); isShowing = false; } }); mCameraView.enableBeauty(true); } private void initFilters() { filters.add(FilterFactory.FilterType.Original); filters.add(FilterFactory.FilterType.Sunrise); filters.add(FilterFactory.FilterType.Sunset); filters.add(FilterFactory.FilterType.BlackWhite); filters.add(FilterFactory.FilterType.WhiteCat); filters.add(FilterFactory.FilterType.BlackCat); filters.add(FilterFactory.FilterType.Beauty); filters.add(FilterFactory.FilterType.Healthy); filters.add(FilterFactory.FilterType.Sakura); filters.add(FilterFactory.FilterType.Romance); filters.add(FilterFactory.FilterType.Latte); filters.add(FilterFactory.FilterType.Warm); filters.add(FilterFactory.FilterType.Calm); filters.add(FilterFactory.FilterType.Cool); filters.add(FilterFactory.FilterType.Brooklyn); filters.add(FilterFactory.FilterType.Amaro); filters.add(FilterFactory.FilterType.Antique); filters.add(FilterFactory.FilterType.Brannan); infos.add(new FilterInfo(R.drawable.filter_thumb_original, "原图")); infos.add(new FilterInfo(R.drawable.filter_thumb_sunrise, "日出")); infos.add(new FilterInfo(R.drawable.filter_thumb_sunset, "日落")); infos.add(new FilterInfo(R.drawable.filter_thumb_1977, "黑白")); infos.add(new FilterInfo(R.drawable.filter_thumb_whitecat, "白猫")); infos.add(new FilterInfo(R.drawable.filter_thumb_blackcat, "黑猫")); infos.add(new FilterInfo(R.drawable.filter_thumb_beauty, "美白")); infos.add(new FilterInfo(R.drawable.filter_thumb_healthy, "健康")); infos.add(new FilterInfo(R.drawable.filter_thumb_sakura, "樱花")); infos.add(new FilterInfo(R.drawable.filter_thumb_romance, "浪漫")); infos.add(new FilterInfo(R.drawable.filter_thumb_latte, "拿铁")); infos.add(new FilterInfo(R.drawable.filter_thumb_warm, "温暖")); infos.add(new FilterInfo(R.drawable.filter_thumb_calm, "安静")); infos.add(new FilterInfo(R.drawable.filter_thumb_cool, "寒冷")); infos.add(new FilterInfo(R.drawable.filter_thumb_brooklyn, "纽约")); infos.add(new FilterInfo(R.drawable.filter_thumb_amoro, "Amaro")); infos.add(new FilterInfo(R.drawable.filter_thumb_antique, "复古")); infos.add(new FilterInfo(R.drawable.filter_thumb_brannan, "Brannan")); //set your own output file here // mCameraView.setOuputMP4File(); //set record finish listener mCameraView.setrecordFinishedListnener(new FileCallback() { @Override public void onData(File file) { //update the gallery sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file))); } }); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.iv://相册 if (!OneClickThree.isFastClick()) { startActivity(new Intent(this, PhotoListActivity.class)); } break; case R.id.img_switch: mCameraView.switchCamera(); break; case R.id.img_filter: if (isShowing) { rv.setVisibility(View.INVISIBLE); } else { rv.setVisibility(View.VISIBLE); } isShowing = !isShowing; break; case R.id.img_capture: if (mode == 1) { onCapture(); } else { onRecord(); } break; } } private void onCapture() { mCameraView.takePicture(bitmap -> { File file = FileUtils.createImageFile(); //重新写入文件 try { // 写入文件 FileOutputStream fos; fos = new FileOutputStream(file); //默认jpg bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); bitmap.recycle(); sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file))); ToastUtil.showTextToast(OpenCameraActivity.this, "已保存"); } catch (Exception e) { e.printStackTrace(); } }); } @Override protected void onStop() { super.onStop(); mRecordingEnabled = false; mCameraView.changeRecordingState(mRecordingEnabled); } private void onRecord() { mRecordingEnabled = !mRecordingEnabled; mCameraView.changeRecordingState(mRecordingEnabled); if (mRecordingEnabled) { ToastUtil.showTextToast(OpenCameraActivity.this, "开始"); } else { ToastUtil.showTextToast(OpenCameraActivity.this, "完成"); } } }
false
1,498
9
1,913
11
1,994
9
1,913
11
2,290
14
false
false
false
false
false
true
28855_2
package com.cunyu; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created with IntelliJ IDEA. * * @author : 村雨 * @version : 1.0 * @project : Java 实战 * @package : com.cunyu * @className : MainApp * @createTime : 2021/8/1 7:22 * @email : 747731461@qq.com * @公众号 : 村雨遥 * @website : https://cunyu1943.github.io * @description : */ public class MainApp { static List<Bill> billList = new ArrayList<>(); static { billList.add(new Bill(1, "购物", "支付宝", "支出", 13000, "2021-08-01", "Macbook Pro 13")); billList.add(new Bill(2, "工资", "银行卡", "收入", 15000, "2021-08-01", "8 月份工资")); } public static void main(String[] args) { // 创建输入器 Scanner scanner = new Scanner(System.in); Bill bill = new Bill(); // 标志位,是否退出系统 boolean flag = true; while (flag) { System.out.println("----------欢迎使用记账系统--------"); System.out.println("----------【1】添加账务----------"); System.out.println("----------【2】删除账务----------"); System.out.println("----------【3】修改账务----------"); System.out.println("----------【4】查询账务----------"); System.out.println("----------【0】退出-------------"); System.out.println("请输入功能序号【0-4】"); String choice = scanner.next(); switch (choice) { case "1": System.out.println("添加账务"); System.out.println("请输入 id"); int id = scanner.nextInt(); bill.setId(id); System.out.println("请输入账务类别"); String category = scanner.next(); bill.setCategory(category); System.out.println("请输入账户"); String account = scanner.next(); bill.setAccount(category); System.out.println("请输入类型(收入/支出)"); String type = scanner.next(); bill.setType(type); System.out.println("请输入金额"); double amount = scanner.nextDouble(); bill.setAmount(amount); System.out.println("请输入时间"); String time = scanner.next(); bill.setTime(time); System.out.println("请输入备注"); String description = scanner.nextLine(); bill.setDesc(description); break; case "2": System.out.println("删除账务"); break; case "3": System.out.println("修改账务>>"); break; case "4": System.out.println("查询账务 >>"); System.out.println("1. 查询所有\t\t 2. 按时间区间\t\t 3. 按类型(收入/支出)"); System.out.println("输入你的选择"); int option = scanner.nextInt(); switch (option) { case 1: System.out.println(">> 所有账务"); System.out.println("ID\t\t类别\t\t\t账户\t\t类型\t\t金额\t\t\t时间\t\t\t\t备注"); bill.queryAll(billList); break; case 2: System.out.println(">> 按时间区间账务"); System.out.println("ID\t\t类别\t\t\t账户\t\t类型\t\t金额\t\t\t时间\t\t\t\t备注"); System.out.println("请输入开始时间(格式:2011-01-01)"); String startTime = scanner.next(); System.out.println("请输入结束时间(格式:2011-01-01)"); String endTime = scanner.next(); bill.queryByTime(billList, startTime, endTime); break; case 3: System.out.println(">> 按类型"); System.out.println("请输入查询类型(收入/支出)"); type = scanner.next(); System.out.println("ID\t\t类别\t\t\t账户\t\t类型\t\t金额\t\t\t时间\t\t\t\t备注"); bill.queryByType(billList, type); } break; case "0": flag = false; break; default: System.out.println("请重新输入"); break; } } System.out.println("退出系统,期待下次见面 ~"); } }
cunyu1943/java-in-actions
TallyBook/src/com/cunyu/MainApp.java
1,200
// 标志位,是否退出系统
line_comment
zh-cn
package com.cunyu; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /** * Created with IntelliJ IDEA. * * @author : 村雨 * @version : 1.0 * @project : Java 实战 * @package : com.cunyu * @className : MainApp * @createTime : 2021/8/1 7:22 * @email : 747731461@qq.com * @公众号 : 村雨遥 * @website : https://cunyu1943.github.io * @description : */ public class MainApp { static List<Bill> billList = new ArrayList<>(); static { billList.add(new Bill(1, "购物", "支付宝", "支出", 13000, "2021-08-01", "Macbook Pro 13")); billList.add(new Bill(2, "工资", "银行卡", "收入", 15000, "2021-08-01", "8 月份工资")); } public static void main(String[] args) { // 创建输入器 Scanner scanner = new Scanner(System.in); Bill bill = new Bill(); // 标志 <SUF> boolean flag = true; while (flag) { System.out.println("----------欢迎使用记账系统--------"); System.out.println("----------【1】添加账务----------"); System.out.println("----------【2】删除账务----------"); System.out.println("----------【3】修改账务----------"); System.out.println("----------【4】查询账务----------"); System.out.println("----------【0】退出-------------"); System.out.println("请输入功能序号【0-4】"); String choice = scanner.next(); switch (choice) { case "1": System.out.println("添加账务"); System.out.println("请输入 id"); int id = scanner.nextInt(); bill.setId(id); System.out.println("请输入账务类别"); String category = scanner.next(); bill.setCategory(category); System.out.println("请输入账户"); String account = scanner.next(); bill.setAccount(category); System.out.println("请输入类型(收入/支出)"); String type = scanner.next(); bill.setType(type); System.out.println("请输入金额"); double amount = scanner.nextDouble(); bill.setAmount(amount); System.out.println("请输入时间"); String time = scanner.next(); bill.setTime(time); System.out.println("请输入备注"); String description = scanner.nextLine(); bill.setDesc(description); break; case "2": System.out.println("删除账务"); break; case "3": System.out.println("修改账务>>"); break; case "4": System.out.println("查询账务 >>"); System.out.println("1. 查询所有\t\t 2. 按时间区间\t\t 3. 按类型(收入/支出)"); System.out.println("输入你的选择"); int option = scanner.nextInt(); switch (option) { case 1: System.out.println(">> 所有账务"); System.out.println("ID\t\t类别\t\t\t账户\t\t类型\t\t金额\t\t\t时间\t\t\t\t备注"); bill.queryAll(billList); break; case 2: System.out.println(">> 按时间区间账务"); System.out.println("ID\t\t类别\t\t\t账户\t\t类型\t\t金额\t\t\t时间\t\t\t\t备注"); System.out.println("请输入开始时间(格式:2011-01-01)"); String startTime = scanner.next(); System.out.println("请输入结束时间(格式:2011-01-01)"); String endTime = scanner.next(); bill.queryByTime(billList, startTime, endTime); break; case 3: System.out.println(">> 按类型"); System.out.println("请输入查询类型(收入/支出)"); type = scanner.next(); System.out.println("ID\t\t类别\t\t\t账户\t\t类型\t\t金额\t\t\t时间\t\t\t\t备注"); bill.queryByType(billList, type); } break; case "0": flag = false; break; default: System.out.println("请重新输入"); break; } } System.out.println("退出系统,期待下次见面 ~"); } }
false
994
9
1,200
9
1,233
7
1,200
9
1,570
14
false
false
false
false
false
true
50109_0
import java.lang.String; import java.util.Objects; public class HashCodeDemo { static class T { Integer a; String b; long c; public int hashCode() { /// 某种对 a, b, c 的哈希计算 return Objects.hash(a, b, c); } public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof T) || other == null) { return false; } boolean flag = true; T another = (T) other; flag = (this.a != null && this.a.equals(another.a)) || another.a == null; flag = (this.b != null && this.b.equals(another.b)) || another.b == null; return flag && this.hashCode() == another.hashCode() && c == another.c; } } static class T2 { Integer a; String b; long c; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; T2 t = (T2) o; return c == t.c && Objects.equals(a, t.a) && Objects.equals(b, t.b); } @Override public int hashCode() { return Objects.hash(a, b, c); } } public static void main(String[] args) { } }
cupid5trick/algo-training
interview/meituan/0319/HashCodeDemo.java
355
/// 某种对 a, b, c 的哈希计算
line_comment
zh-cn
import java.lang.String; import java.util.Objects; public class HashCodeDemo { static class T { Integer a; String b; long c; public int hashCode() { /// 某种 <SUF> return Objects.hash(a, b, c); } public boolean equals(Object other) { if (this == other) { return true; } if (!(other instanceof T) || other == null) { return false; } boolean flag = true; T another = (T) other; flag = (this.a != null && this.a.equals(another.a)) || another.a == null; flag = (this.b != null && this.b.equals(another.b)) || another.b == null; return flag && this.hashCode() == another.hashCode() && c == another.c; } } static class T2 { Integer a; String b; long c; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; T2 t = (T2) o; return c == t.c && Objects.equals(a, t.a) && Objects.equals(b, t.b); } @Override public int hashCode() { return Objects.hash(a, b, c); } } public static void main(String[] args) { } }
false
322
15
355
15
398
13
355
15
429
20
false
false
false
false
false
true
44215_19
class Solution { // 递归版本 // public int climbStairs(int n) { // if (n <= 2) { // return n; // } // return climbStairs(n-1) + climbStairs(n-2); // } // 记忆搜索递归版本 // public int climbStairs(int n) { // // 记忆 // int[] memo = new int[n+1]; // return climbStairs(n, memo); // } // private int climbStairs(int n, int[] memo) { // if (n == 0) { // return 1; // } // if (n == 1) { // return 1; // } // if (memo[n] != 0) { // return memo[n]; // } // int s = climbStairs(n-1, memo) + climbStairs(n-2, memo); // memo[n] = s; // return s; // } // 动态规划版本 // public int climbStairs(int n) { // if (n <= 2) return n; // int[] dp = new int[n + 1]; // dp[1] = 1; // dp[2] = 2; // for (int i = 3; i < dp.length; i++) { // dp[i] = dp[i-1] + dp[i-2]; // } // return dp[n]; // } // 循环版本 public int climbStairs(int n) { if (n <= 2) return n; int a = 1; int b = 2; for (int i = 3; i <= n; i++) { int tmp = a; a = b; b = tmp + b; } return b; } }
cuzz1/leetcode-lintcode
leetcode-cn/Solution0070.java
478
// 动态规划版本
line_comment
zh-cn
class Solution { // 递归版本 // public int climbStairs(int n) { // if (n <= 2) { // return n; // } // return climbStairs(n-1) + climbStairs(n-2); // } // 记忆搜索递归版本 // public int climbStairs(int n) { // // 记忆 // int[] memo = new int[n+1]; // return climbStairs(n, memo); // } // private int climbStairs(int n, int[] memo) { // if (n == 0) { // return 1; // } // if (n == 1) { // return 1; // } // if (memo[n] != 0) { // return memo[n]; // } // int s = climbStairs(n-1, memo) + climbStairs(n-2, memo); // memo[n] = s; // return s; // } // 动态 <SUF> // public int climbStairs(int n) { // if (n <= 2) return n; // int[] dp = new int[n + 1]; // dp[1] = 1; // dp[2] = 2; // for (int i = 3; i < dp.length; i++) { // dp[i] = dp[i-1] + dp[i-2]; // } // return dp[n]; // } // 循环版本 public int climbStairs(int n) { if (n <= 2) return n; int a = 1; int b = 2; for (int i = 3; i <= n; i++) { int tmp = a; a = b; b = tmp + b; } return b; } }
false
450
6
478
6
500
4
478
6
578
12
false
false
false
false
false
true
58660_3
package com.dingtalk.api.request; import com.taobao.api.internal.util.RequestCheckUtils; import java.util.Map; import java.util.List; import com.taobao.api.ApiRuleException; import com.taobao.api.BaseTaobaoRequest; import com.dingtalk.api.DingTalkConstants; import com.taobao.api.Constants; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.internal.util.TaobaoUtils; import com.dingtalk.api.response.OapiEduGuardianCreateResponse; /** * TOP DingTalk-API: dingtalk.oapi.edu.guardian.create request * * @author top auto create * @since 1.0, 2020.12.11 */ public class OapiEduGuardianCreateRequest extends BaseTaobaoRequest<OapiEduGuardianCreateResponse> { /** * 业务id */ private String bizId; /** * 班级id */ private Long classId; /** * 手机号码 */ private String mobile; /** * 钉钉企业管理员 */ private String operator; /** * 关系code;关系枚举如下: F:爸爸 M:妈妈 GF:爷爷 GM:奶奶 GFA:外公 GMA:外婆 U:叔叔 A:阿姨 B:哥哥 S:姐姐 O:其他 */ private String relation; /** * 学生id */ private String stuId; public void setBizId(String bizId) { this.bizId = bizId; } public String getBizId() { return this.bizId; } public void setClassId(Long classId) { this.classId = classId; } public Long getClassId() { return this.classId; } public void setMobile(String mobile) { this.mobile = mobile; } public String getMobile() { return this.mobile; } public void setOperator(String operator) { this.operator = operator; } public String getOperator() { return this.operator; } public void setRelation(String relation) { this.relation = relation; } public String getRelation() { return this.relation; } public void setStuId(String stuId) { this.stuId = stuId; } public String getStuId() { return this.stuId; } public String getApiMethodName() { return "dingtalk.oapi.edu.guardian.create"; } private String topResponseType = Constants.RESPONSE_TYPE_DINGTALK_OAPI; public String getTopResponseType() { return this.topResponseType; } public void setTopResponseType(String topResponseType) { this.topResponseType = topResponseType; } public String getTopApiCallType() { return DingTalkConstants.CALL_TYPE_OAPI; } private String topHttpMethod = DingTalkConstants.HTTP_METHOD_POST; public String getTopHttpMethod() { return this.topHttpMethod; } public void setTopHttpMethod(String topHttpMethod) { this.topHttpMethod = topHttpMethod; } public void setHttpMethod(String httpMethod) { this.setTopHttpMethod(httpMethod); } public Map<String, String> getTextParams() { TaobaoHashMap txtParams = new TaobaoHashMap(); txtParams.put("biz_id", this.bizId); txtParams.put("class_id", this.classId); txtParams.put("mobile", this.mobile); txtParams.put("operator", this.operator); txtParams.put("relation", this.relation); txtParams.put("stu_id", this.stuId); if(this.udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public Class<OapiEduGuardianCreateResponse> getResponseClass() { return OapiEduGuardianCreateResponse.class; } public void check() throws ApiRuleException { RequestCheckUtils.checkNotEmpty(classId, "classId"); RequestCheckUtils.checkNotEmpty(mobile, "mobile"); RequestCheckUtils.checkNotEmpty(operator, "operator"); RequestCheckUtils.checkNotEmpty(relation, "relation"); RequestCheckUtils.checkNotEmpty(stuId, "stuId"); } }
cvdnn/ZtoneNetwork
sdk-hook/src/main/java/com/dingtalk/api/request/OapiEduGuardianCreateRequest.java
1,172
/** * 手机号码 */
block_comment
zh-cn
package com.dingtalk.api.request; import com.taobao.api.internal.util.RequestCheckUtils; import java.util.Map; import java.util.List; import com.taobao.api.ApiRuleException; import com.taobao.api.BaseTaobaoRequest; import com.dingtalk.api.DingTalkConstants; import com.taobao.api.Constants; import com.taobao.api.internal.util.TaobaoHashMap; import com.taobao.api.internal.util.TaobaoUtils; import com.dingtalk.api.response.OapiEduGuardianCreateResponse; /** * TOP DingTalk-API: dingtalk.oapi.edu.guardian.create request * * @author top auto create * @since 1.0, 2020.12.11 */ public class OapiEduGuardianCreateRequest extends BaseTaobaoRequest<OapiEduGuardianCreateResponse> { /** * 业务id */ private String bizId; /** * 班级id */ private Long classId; /** * 手机号 <SUF>*/ private String mobile; /** * 钉钉企业管理员 */ private String operator; /** * 关系code;关系枚举如下: F:爸爸 M:妈妈 GF:爷爷 GM:奶奶 GFA:外公 GMA:外婆 U:叔叔 A:阿姨 B:哥哥 S:姐姐 O:其他 */ private String relation; /** * 学生id */ private String stuId; public void setBizId(String bizId) { this.bizId = bizId; } public String getBizId() { return this.bizId; } public void setClassId(Long classId) { this.classId = classId; } public Long getClassId() { return this.classId; } public void setMobile(String mobile) { this.mobile = mobile; } public String getMobile() { return this.mobile; } public void setOperator(String operator) { this.operator = operator; } public String getOperator() { return this.operator; } public void setRelation(String relation) { this.relation = relation; } public String getRelation() { return this.relation; } public void setStuId(String stuId) { this.stuId = stuId; } public String getStuId() { return this.stuId; } public String getApiMethodName() { return "dingtalk.oapi.edu.guardian.create"; } private String topResponseType = Constants.RESPONSE_TYPE_DINGTALK_OAPI; public String getTopResponseType() { return this.topResponseType; } public void setTopResponseType(String topResponseType) { this.topResponseType = topResponseType; } public String getTopApiCallType() { return DingTalkConstants.CALL_TYPE_OAPI; } private String topHttpMethod = DingTalkConstants.HTTP_METHOD_POST; public String getTopHttpMethod() { return this.topHttpMethod; } public void setTopHttpMethod(String topHttpMethod) { this.topHttpMethod = topHttpMethod; } public void setHttpMethod(String httpMethod) { this.setTopHttpMethod(httpMethod); } public Map<String, String> getTextParams() { TaobaoHashMap txtParams = new TaobaoHashMap(); txtParams.put("biz_id", this.bizId); txtParams.put("class_id", this.classId); txtParams.put("mobile", this.mobile); txtParams.put("operator", this.operator); txtParams.put("relation", this.relation); txtParams.put("stu_id", this.stuId); if(this.udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public Class<OapiEduGuardianCreateResponse> getResponseClass() { return OapiEduGuardianCreateResponse.class; } public void check() throws ApiRuleException { RequestCheckUtils.checkNotEmpty(classId, "classId"); RequestCheckUtils.checkNotEmpty(mobile, "mobile"); RequestCheckUtils.checkNotEmpty(operator, "operator"); RequestCheckUtils.checkNotEmpty(relation, "relation"); RequestCheckUtils.checkNotEmpty(stuId, "stuId"); } }
false
933
11
1,172
10
1,131
10
1,172
10
1,381
13
false
false
false
false
false
true
40757_9
package appname.example.com.testtablayout; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private TabLayout tabLayout; private ViewPager vp; // String[] des = {"尊享赔", "利息低", "高通过率", "优先申请", "优先申请", "优先申请", "优先申请"}; String[] des = {"尊享赔","利息低", "高通过率", "优先申请"}; private ArrayList<String> datas = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout = findViewById(R.id.tablayout); vp = findViewById(R.id.viewpager); inittab(); } private void inittab() { // init1(); final MenuViewPagerForFragment1 mvf = new MenuViewPagerForFragment1(getSupportFragmentManager(), des); Afragment afragment = Afragment.newInstance(datas,1); Afragment afragment1 = Afragment.newInstance(datas,2); Afragment afragment2 = Afragment.newInstance(datas,3); Afragment afragment3 = Afragment.newInstance(datas,4); mvf.add(afragment); mvf.add(afragment1); mvf.add(afragment2); mvf.add(afragment3); // new PassRateSvipFragment() //提前预加载也能够防止被销毁,但是开始可能就很卡(因为预加载很卡,然后不调用这个方法就行,然后在fragmentpageradapter中重写destroyItem(方法为空即可)) // vp.setOffscreenPageLimit(3); vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { LogUtil.e("onPageScrolled"); } @Override public void onPageSelected(int i) { LogUtil.e("onPageSelected---->"+i); } @Override public void onPageScrollStateChanged(int i) { LogUtil.e("onPageScrollStateChanged"); } }); vp.setAdapter(mvf); //可惜,和tablayout结合的viewpager不需要framelayout?2017. //tablayout的作用是绑定viewpager。 tabLayout.setupWithViewPager(vp); //下面这个是设置指示器的颜色,就是滑动时候的指示器。4.10 //tablayout.setSelectedTabIndicatorColor(Color.BLUE); //这个是选中颜色和未选中颜色 4.11 // binding.tablayout.setTabTextColors(Color.GRAY,getActivity().getResources().getColor(R.color.tab_layout_text_color)); tabLayout.setSelectedTabIndicatorHeight(10); //这个就是修改整个tablayout整个背景颜色的方法。4.10 //tablayout.setBackground(new ColorDrawable(Color.RED)); // todo 下面这两个是指定切换到某个 item vp.setCurrentItem(1); tabLayout.getTabAt(1).select(); } }
cvvbbo/TablayoutViewpagerFragment
app/src/main/java/appname/example/com/testtablayout/MainActivity.java
779
//这个是选中颜色和未选中颜色 4.11
line_comment
zh-cn
package appname.example.com.testtablayout; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { private TabLayout tabLayout; private ViewPager vp; // String[] des = {"尊享赔", "利息低", "高通过率", "优先申请", "优先申请", "优先申请", "优先申请"}; String[] des = {"尊享赔","利息低", "高通过率", "优先申请"}; private ArrayList<String> datas = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tabLayout = findViewById(R.id.tablayout); vp = findViewById(R.id.viewpager); inittab(); } private void inittab() { // init1(); final MenuViewPagerForFragment1 mvf = new MenuViewPagerForFragment1(getSupportFragmentManager(), des); Afragment afragment = Afragment.newInstance(datas,1); Afragment afragment1 = Afragment.newInstance(datas,2); Afragment afragment2 = Afragment.newInstance(datas,3); Afragment afragment3 = Afragment.newInstance(datas,4); mvf.add(afragment); mvf.add(afragment1); mvf.add(afragment2); mvf.add(afragment3); // new PassRateSvipFragment() //提前预加载也能够防止被销毁,但是开始可能就很卡(因为预加载很卡,然后不调用这个方法就行,然后在fragmentpageradapter中重写destroyItem(方法为空即可)) // vp.setOffscreenPageLimit(3); vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { LogUtil.e("onPageScrolled"); } @Override public void onPageSelected(int i) { LogUtil.e("onPageSelected---->"+i); } @Override public void onPageScrollStateChanged(int i) { LogUtil.e("onPageScrollStateChanged"); } }); vp.setAdapter(mvf); //可惜,和tablayout结合的viewpager不需要framelayout?2017. //tablayout的作用是绑定viewpager。 tabLayout.setupWithViewPager(vp); //下面这个是设置指示器的颜色,就是滑动时候的指示器。4.10 //tablayout.setSelectedTabIndicatorColor(Color.BLUE); //这个 <SUF> // binding.tablayout.setTabTextColors(Color.GRAY,getActivity().getResources().getColor(R.color.tab_layout_text_color)); tabLayout.setSelectedTabIndicatorHeight(10); //这个就是修改整个tablayout整个背景颜色的方法。4.10 //tablayout.setBackground(new ColorDrawable(Color.RED)); // todo 下面这两个是指定切换到某个 item vp.setCurrentItem(1); tabLayout.getTabAt(1).select(); } }
false
671
16
779
16
795
14
779
16
1,042
23
false
false
false
false
false
true
65923_3
package com.module.market; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.hibernate.hql.ast.SqlASTFactory; import org.json.JSONObject; import org.omg.CORBA.INTERNAL; import org.springframework.context.annotation.Scope; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import com.core.BaseAction; import com.core.dao.UtilDAO; import com.model.Customer; import com.model.Market; import com.model.Market; @Component @Scope("prototype") public class MarketAction extends BaseAction{ /** * */ private static final long serialVersionUID = 3861279572611224546L; private Market market; private List<Market> list; @Resource private UtilDAO utilDAO; @Resource private JdbcTemplate jdbcTemplate; private String resultObj; private int totalPage; private int currentPage; private int itemPrePage=10; private int id; private String clientName; private String opponentName; private String byPage; private int totalItem; private int start; public String insert() { market.setClientId("" + getSessionBranch().getId()); market.setClientName(getSessionBranch().getArea()+"/"+getSessionBranch().getTrueName()); String info=""; if (market.getId()!=0) { info="市场 "+market.getProductName()+" 更新成功"; }else { info="市场 "+market.getProductName()+" 录入成功"; } utilDAO.saveOrUpdate(market); writeJSON(info); System.out.println(resultObj); return SUCCESS; } public String delete(){ Market c=(Market) utilDAO.findListByProperty("Market", "id", id, "").get(0); String name=c.getProductName(); utilDAO.delete(c); JSONObject joCode=new JSONObject(); try { joCode.put("resultcode", "200"); joCode.put("name", name); joCode.put("id", id); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } resultObj=joCode.toString(); return SUCCESS; } public void writeJSON(String info){ JSONObject joCode=new JSONObject(); try { joCode.put("resultcode", "200"); joCode.put("info", info); joCode.put("id", market.getId()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } resultObj=joCode.toString(); } public String show(){ if(currentPage==0) currentPage=1; start=(currentPage-1)*itemPrePage; getPrar(); if (getSessionBranch().getType()==3) { type3(); } if (getSessionBranch().getType()==2) { type2(); } if (getSessionBranch().getType()==1) { type1(); } if (totalItem%itemPrePage==0) { totalPage=totalItem/itemPrePage; }else { totalPage=totalItem/itemPrePage+1; } return SUCCESS; } /** * 获取参数 */ public void getPrar(){ if (byPage==null) { //搜索框查询 if (StringUtils.isNotEmpty(clientName) ) { getSession().put("clientName",clientName); }else { getSession().put("clientName", ""); } if (StringUtils.isNotEmpty(opponentName) ) { getSession().put("opponentName",opponentName); }else { getSession().put("opponentName", ""); } }else { // 下一页查询 opponentName=(String) getSession().get("opponentName"); clientName=(String)getSession().get("clientName"); } // System.out.println(clientName+" sss"); } /* * 总公司 */ public void type3(){ String sqlCount="select count(*) from Market,opponent where opponentId=opponent.id "; String sql="select Market.*,opponent.name opponentName from Market,opponent where " + " market.opponentid =opponent.id "; if (StringUtils.isNotEmpty(opponentName)) { sqlCount+=" and opponent.name='"+opponentName+"'"; sql+=" and opponent.name='"+opponentName+"'"; } if (StringUtils.isNotEmpty(clientName)&& !clientName.equals("全部")) { sqlCount+=" and Market.clientName = '"+clientName+"'"; sql+=" and Market.clientName = '"+clientName+"'"; } sql+=" order by Market.clientid,market.id desc limit "+start+","+itemPrePage ; totalItem=jdbcTemplate.queryForInt(sqlCount); list=jdbcTemplate.query(sql, new BeanPropertyRowMapper<Market>(Market.class)); System.out.println(sql+" ppp "+ sqlCount); } /* * 分公司 */ public void type2(){ String sqlCount="select count(*) from Market,user,opponent where Market.clientId=user.id " + " and user.branchId="+getSessionBranch().getBranchId()+" and market.opponentid=opponent.id "; String sql="select Market.*,opponent.name opponentName from Market,user,opponent where Market.clientId=user.id and " + " user.branchId="+getSessionBranch().getBranchId()+" and market.opponentid =opponent.id "; if (StringUtils.isNotEmpty(opponentName)) { sqlCount+=" and opponent.name='"+opponentName+"'"; sql+=" and opponent.name='"+opponentName+"'"; } if (StringUtils.isNotEmpty(clientName)&& !clientName.equals("全部")) { sqlCount+=" and market.clientName='"+clientName+"'"; sql+=" and market.clientName='"+clientName+"'"; } sql+=" order by Market.clientid,market.id desc limit "+start+","+itemPrePage+" "; totalItem=jdbcTemplate.queryForInt(sqlCount); list=jdbcTemplate.query(sql, new BeanPropertyRowMapper<Market>(Market.class)); System.out.println(sql+" ppp"+ sqlCount); } /* * 业务员 */ public void type1(){ String sqlCount="select count(*) from Market,user,opponent where Market.clientId=user.id " + "and market.opponentid=opponent.id and user.id="+getSessionBranch().getId(); String sql="select Market.*,opponent.name opponentName from Market,user,opponent where " + " Market.clientId=user.id and user.id="+getSessionBranch().getId() + " and market.opponentId=opponent.id "; if (StringUtils.isNotEmpty(opponentName)) { sqlCount+=" and opponent.name='"+opponentName+"'"; sql+=" and opponent.name='"+opponentName+"'"; } sql+="order by Market.clientid,id desc limit "+start+","+itemPrePage; totalItem=jdbcTemplate.queryForInt(sqlCount); list=jdbcTemplate.query(sql, new BeanPropertyRowMapper<Market>(Market.class)); // System.out.println(sql+" sql"); } public String getMarketByPage(){ if(currentPage==0) currentPage=1; int start=(currentPage-1)*itemPrePage; if (currentPage==-1) { start=0; itemPrePage=1000; } String sql="SELECT "+ " market.*,opponent.`name` opponentName "+ " FROM"+ " market,opponent "+ " WHERE market.opponentId=opponent.id and "+ " market.clientId="+getSessionBranch().getId()+" order by id desc limit "+start+","+itemPrePage; List<Map<String, Object>> list=jdbcTemplate.queryForList(sql); net.sf.json.JSONObject joCode=new net.sf.json.JSONObject(); net.sf.json.JSONArray jsonArray=new net.sf.json.JSONArray(); sql="select count(*) from market where clientId="+getSessionBranch().getId()+" limit "+start+","+itemPrePage; int totalItem=jdbcTemplate.queryForInt(sql); if (totalItem%itemPrePage==0) { totalPage=totalItem/itemPrePage; }else { totalPage=(totalItem/itemPrePage)+1; } joCode.put("totalPage", totalPage); joCode.put("currentPage", currentPage); joCode.put("totalItems", totalItem); net.sf.json.JSONObject joResult=new net.sf.json.JSONObject(); for (Map<String, Object> m:list) { joResult=net.sf.json.JSONObject.fromObject(m); jsonArray.add(joResult); } joCode.put("result", jsonArray); resultObj=joCode.toString(); System.out.println(resultObj+" *********"); return SUCCESS; } public String getById(){ market=(Market) utilDAO.findListByProperty("Market","id",id,"").get(0); return SUCCESS; } public Market getMarket() { return market; } public void setMarket(Market market) { this.market = market; } public UtilDAO getUtilDAO() { return utilDAO; } public void setUtilDAO(UtilDAO utilDAO) { this.utilDAO = utilDAO; } public String getResultObj() { return resultObj; } public void setResultObj(String resultObj) { this.resultObj = resultObj; } public List<Market> getList() { return list; } public void setList(List<Market> list) { this.list = list; } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getItemPrePage() { return itemPrePage; } public void setItemPrePage(int itemPrePage) { this.itemPrePage = itemPrePage; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName; } public String getOpponentName() { return opponentName; } public void setOpponentName(String marketName) { this.opponentName = marketName; } public String getByPage() { return byPage; } public void setByPage(String byPage) { this.byPage = byPage; } public int getTotalItem() { return totalItem; } public void setTotalItem(int totalItem) { this.totalItem = totalItem; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } }
cxyxd/BJAdmin
src/com/module/market/MarketAction.java
3,021
//搜索框查询
line_comment
zh-cn
package com.module.market; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang.StringUtils; import org.hibernate.hql.ast.SqlASTFactory; import org.json.JSONObject; import org.omg.CORBA.INTERNAL; import org.springframework.context.annotation.Scope; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Component; import com.core.BaseAction; import com.core.dao.UtilDAO; import com.model.Customer; import com.model.Market; import com.model.Market; @Component @Scope("prototype") public class MarketAction extends BaseAction{ /** * */ private static final long serialVersionUID = 3861279572611224546L; private Market market; private List<Market> list; @Resource private UtilDAO utilDAO; @Resource private JdbcTemplate jdbcTemplate; private String resultObj; private int totalPage; private int currentPage; private int itemPrePage=10; private int id; private String clientName; private String opponentName; private String byPage; private int totalItem; private int start; public String insert() { market.setClientId("" + getSessionBranch().getId()); market.setClientName(getSessionBranch().getArea()+"/"+getSessionBranch().getTrueName()); String info=""; if (market.getId()!=0) { info="市场 "+market.getProductName()+" 更新成功"; }else { info="市场 "+market.getProductName()+" 录入成功"; } utilDAO.saveOrUpdate(market); writeJSON(info); System.out.println(resultObj); return SUCCESS; } public String delete(){ Market c=(Market) utilDAO.findListByProperty("Market", "id", id, "").get(0); String name=c.getProductName(); utilDAO.delete(c); JSONObject joCode=new JSONObject(); try { joCode.put("resultcode", "200"); joCode.put("name", name); joCode.put("id", id); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } resultObj=joCode.toString(); return SUCCESS; } public void writeJSON(String info){ JSONObject joCode=new JSONObject(); try { joCode.put("resultcode", "200"); joCode.put("info", info); joCode.put("id", market.getId()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } resultObj=joCode.toString(); } public String show(){ if(currentPage==0) currentPage=1; start=(currentPage-1)*itemPrePage; getPrar(); if (getSessionBranch().getType()==3) { type3(); } if (getSessionBranch().getType()==2) { type2(); } if (getSessionBranch().getType()==1) { type1(); } if (totalItem%itemPrePage==0) { totalPage=totalItem/itemPrePage; }else { totalPage=totalItem/itemPrePage+1; } return SUCCESS; } /** * 获取参数 */ public void getPrar(){ if (byPage==null) { //搜索 <SUF> if (StringUtils.isNotEmpty(clientName) ) { getSession().put("clientName",clientName); }else { getSession().put("clientName", ""); } if (StringUtils.isNotEmpty(opponentName) ) { getSession().put("opponentName",opponentName); }else { getSession().put("opponentName", ""); } }else { // 下一页查询 opponentName=(String) getSession().get("opponentName"); clientName=(String)getSession().get("clientName"); } // System.out.println(clientName+" sss"); } /* * 总公司 */ public void type3(){ String sqlCount="select count(*) from Market,opponent where opponentId=opponent.id "; String sql="select Market.*,opponent.name opponentName from Market,opponent where " + " market.opponentid =opponent.id "; if (StringUtils.isNotEmpty(opponentName)) { sqlCount+=" and opponent.name='"+opponentName+"'"; sql+=" and opponent.name='"+opponentName+"'"; } if (StringUtils.isNotEmpty(clientName)&& !clientName.equals("全部")) { sqlCount+=" and Market.clientName = '"+clientName+"'"; sql+=" and Market.clientName = '"+clientName+"'"; } sql+=" order by Market.clientid,market.id desc limit "+start+","+itemPrePage ; totalItem=jdbcTemplate.queryForInt(sqlCount); list=jdbcTemplate.query(sql, new BeanPropertyRowMapper<Market>(Market.class)); System.out.println(sql+" ppp "+ sqlCount); } /* * 分公司 */ public void type2(){ String sqlCount="select count(*) from Market,user,opponent where Market.clientId=user.id " + " and user.branchId="+getSessionBranch().getBranchId()+" and market.opponentid=opponent.id "; String sql="select Market.*,opponent.name opponentName from Market,user,opponent where Market.clientId=user.id and " + " user.branchId="+getSessionBranch().getBranchId()+" and market.opponentid =opponent.id "; if (StringUtils.isNotEmpty(opponentName)) { sqlCount+=" and opponent.name='"+opponentName+"'"; sql+=" and opponent.name='"+opponentName+"'"; } if (StringUtils.isNotEmpty(clientName)&& !clientName.equals("全部")) { sqlCount+=" and market.clientName='"+clientName+"'"; sql+=" and market.clientName='"+clientName+"'"; } sql+=" order by Market.clientid,market.id desc limit "+start+","+itemPrePage+" "; totalItem=jdbcTemplate.queryForInt(sqlCount); list=jdbcTemplate.query(sql, new BeanPropertyRowMapper<Market>(Market.class)); System.out.println(sql+" ppp"+ sqlCount); } /* * 业务员 */ public void type1(){ String sqlCount="select count(*) from Market,user,opponent where Market.clientId=user.id " + "and market.opponentid=opponent.id and user.id="+getSessionBranch().getId(); String sql="select Market.*,opponent.name opponentName from Market,user,opponent where " + " Market.clientId=user.id and user.id="+getSessionBranch().getId() + " and market.opponentId=opponent.id "; if (StringUtils.isNotEmpty(opponentName)) { sqlCount+=" and opponent.name='"+opponentName+"'"; sql+=" and opponent.name='"+opponentName+"'"; } sql+="order by Market.clientid,id desc limit "+start+","+itemPrePage; totalItem=jdbcTemplate.queryForInt(sqlCount); list=jdbcTemplate.query(sql, new BeanPropertyRowMapper<Market>(Market.class)); // System.out.println(sql+" sql"); } public String getMarketByPage(){ if(currentPage==0) currentPage=1; int start=(currentPage-1)*itemPrePage; if (currentPage==-1) { start=0; itemPrePage=1000; } String sql="SELECT "+ " market.*,opponent.`name` opponentName "+ " FROM"+ " market,opponent "+ " WHERE market.opponentId=opponent.id and "+ " market.clientId="+getSessionBranch().getId()+" order by id desc limit "+start+","+itemPrePage; List<Map<String, Object>> list=jdbcTemplate.queryForList(sql); net.sf.json.JSONObject joCode=new net.sf.json.JSONObject(); net.sf.json.JSONArray jsonArray=new net.sf.json.JSONArray(); sql="select count(*) from market where clientId="+getSessionBranch().getId()+" limit "+start+","+itemPrePage; int totalItem=jdbcTemplate.queryForInt(sql); if (totalItem%itemPrePage==0) { totalPage=totalItem/itemPrePage; }else { totalPage=(totalItem/itemPrePage)+1; } joCode.put("totalPage", totalPage); joCode.put("currentPage", currentPage); joCode.put("totalItems", totalItem); net.sf.json.JSONObject joResult=new net.sf.json.JSONObject(); for (Map<String, Object> m:list) { joResult=net.sf.json.JSONObject.fromObject(m); jsonArray.add(joResult); } joCode.put("result", jsonArray); resultObj=joCode.toString(); System.out.println(resultObj+" *********"); return SUCCESS; } public String getById(){ market=(Market) utilDAO.findListByProperty("Market","id",id,"").get(0); return SUCCESS; } public Market getMarket() { return market; } public void setMarket(Market market) { this.market = market; } public UtilDAO getUtilDAO() { return utilDAO; } public void setUtilDAO(UtilDAO utilDAO) { this.utilDAO = utilDAO; } public String getResultObj() { return resultObj; } public void setResultObj(String resultObj) { this.resultObj = resultObj; } public List<Market> getList() { return list; } public void setList(List<Market> list) { this.list = list; } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getItemPrePage() { return itemPrePage; } public void setItemPrePage(int itemPrePage) { this.itemPrePage = itemPrePage; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getClientName() { return clientName; } public void setClientName(String clientName) { this.clientName = clientName; } public String getOpponentName() { return opponentName; } public void setOpponentName(String marketName) { this.opponentName = marketName; } public String getByPage() { return byPage; } public void setByPage(String byPage) { this.byPage = byPage; } public int getTotalItem() { return totalItem; } public void setTotalItem(int totalItem) { this.totalItem = totalItem; } public int getStart() { return start; } public void setStart(int start) { this.start = start; } }
false
2,475
5
2,997
5
3,037
5
2,997
5
3,807
13
false
false
false
false
false
true
48845_0
/************************************************************ * Email: support@lansongtech.com * PlayObject.java * <p/> * <p/> * 这个程序仅仅是演示版本,仅是功能上的呈现,不保证性能和适用性。如正好满足您的项目,我们深感荣幸。 * 我们有更专业稳定强大的发行版本,期待和您进一步的合作。 ************************************************************/ package com.LanSoSdk.Play; import android.os.Handler; import android.os.Looper; abstract class PlayObject<T extends PlayEvent> { private PlayEvent.Listener<T> mEventListener = null; private Handler mHandler = null; private int mNativeRefCount = 1; /** * Returns true if native object is released */ public synchronized boolean isReleased() { return mNativeRefCount == 0; } /** * Increment internal ref count of the native object. * * @return true if media is retained */ public synchronized final boolean retain() { if (mNativeRefCount > 0) { mNativeRefCount++; return true; } else return false; } /** * Release the native object if ref count is 1. * <p/> * After this call, native calls are not possible anymore. * You can still call others methods to retrieve cached values. * For example: if you parse, then release a media, you'll still be able to retrieve all Metas or Tracks infos. */ public final void release() { int refCount = -1; synchronized (this) { if (mNativeRefCount == 0) return; if (mNativeRefCount > 0) { refCount = --mNativeRefCount; } // clear event list if (refCount == 0) setEventListener(null); } if (refCount == 0) { nativeDetachEvents(); synchronized (this) { onReleaseNative(); } } } /** * Called when native object is released (refcount is 0). * <p/> * This is where you must release native resources. */ protected abstract void onReleaseNative(); //========================================================================================================= /** * Set an event listener. * Events are sent via the android main thread. * * @param listener see {@link PlayEvent.Listener} */ protected synchronized void setEventListener(PlayEvent.Listener<T> listener) { if (mHandler != null) mHandler.removeCallbacksAndMessages(null); mEventListener = listener; if (mEventListener != null && mHandler == null) mHandler = new Handler(Looper.getMainLooper()); } /** * Called when libplay send events. * * @param eventType event type * @param arg1 first argument * @param arg2 second argument * @return Event that will be dispatched to listeners */ protected abstract T onEventNative(int eventType, long arg1, float arg2); /* JNI */ @SuppressWarnings("unused") /* Used from JNI */ private long mInstance = 0; private synchronized void dispatchEventFromNative(int eventType, long arg1, float arg2) { if (isReleased()) return; final T event = onEventNative(eventType, arg1, arg2); class EventRunnable implements Runnable { private final PlayEvent.Listener<T> listener; private final T event; private EventRunnable(PlayEvent.Listener<T> listener, T event) { this.listener = listener; this.event = event; } @Override public void run() { listener.onEvent(event); } } if (event != null && mEventListener != null && mHandler != null) mHandler.post(new EventRunnable(mEventListener, event)); } private native void nativeDetachEvents(); }
cybernhl/LanSoSdkVLCPlay
lansovlcplayer/src/main/java/com/LanSoSdk/Play/PlayObject.java
882
/************************************************************ * Email: support@lansongtech.com * PlayObject.java * <p/> * <p/> * 这个程序仅仅是演示版本,仅是功能上的呈现,不保证性能和适用性。如正好满足您的项目,我们深感荣幸。 * 我们有更专业稳定强大的发行版本,期待和您进一步的合作。 ************************************************************/
block_comment
zh-cn
/************************************************************ * Ema <SUF>*/ package com.LanSoSdk.Play; import android.os.Handler; import android.os.Looper; abstract class PlayObject<T extends PlayEvent> { private PlayEvent.Listener<T> mEventListener = null; private Handler mHandler = null; private int mNativeRefCount = 1; /** * Returns true if native object is released */ public synchronized boolean isReleased() { return mNativeRefCount == 0; } /** * Increment internal ref count of the native object. * * @return true if media is retained */ public synchronized final boolean retain() { if (mNativeRefCount > 0) { mNativeRefCount++; return true; } else return false; } /** * Release the native object if ref count is 1. * <p/> * After this call, native calls are not possible anymore. * You can still call others methods to retrieve cached values. * For example: if you parse, then release a media, you'll still be able to retrieve all Metas or Tracks infos. */ public final void release() { int refCount = -1; synchronized (this) { if (mNativeRefCount == 0) return; if (mNativeRefCount > 0) { refCount = --mNativeRefCount; } // clear event list if (refCount == 0) setEventListener(null); } if (refCount == 0) { nativeDetachEvents(); synchronized (this) { onReleaseNative(); } } } /** * Called when native object is released (refcount is 0). * <p/> * This is where you must release native resources. */ protected abstract void onReleaseNative(); //========================================================================================================= /** * Set an event listener. * Events are sent via the android main thread. * * @param listener see {@link PlayEvent.Listener} */ protected synchronized void setEventListener(PlayEvent.Listener<T> listener) { if (mHandler != null) mHandler.removeCallbacksAndMessages(null); mEventListener = listener; if (mEventListener != null && mHandler == null) mHandler = new Handler(Looper.getMainLooper()); } /** * Called when libplay send events. * * @param eventType event type * @param arg1 first argument * @param arg2 second argument * @return Event that will be dispatched to listeners */ protected abstract T onEventNative(int eventType, long arg1, float arg2); /* JNI */ @SuppressWarnings("unused") /* Used from JNI */ private long mInstance = 0; private synchronized void dispatchEventFromNative(int eventType, long arg1, float arg2) { if (isReleased()) return; final T event = onEventNative(eventType, arg1, arg2); class EventRunnable implements Runnable { private final PlayEvent.Listener<T> listener; private final T event; private EventRunnable(PlayEvent.Listener<T> listener, T event) { this.listener = listener; this.event = event; } @Override public void run() { listener.onEvent(event); } } if (event != null && mEventListener != null && mHandler != null) mHandler.post(new EventRunnable(mEventListener, event)); } private native void nativeDetachEvents(); }
false
823
81
882
104
968
90
882
104
1,099
155
false
false
false
false
false
true
3405_0
package com.cyh.sy.common.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * * @描述:任务调度管理类 * @作者:cyh * @版本:V1.0 * @创建时间::2016-11-21 下午10:54:10 * */ @Component public class TaskManager { @Scheduled(cron = "0 0/10 * * * ?") public void task1(){ System.out.println("我每10分钟都要执行一次,不管是刮风还是下雨"); } @Scheduled(cron = "0 0 2 * * ?") public void task2(){ System.out.println("我每天凌晨两点执行"); } @Scheduled(cron = "0 0 0 1 1 3") public void task3(){ System.err.println("如果现在是2016年的话,我会在未来的3年后也就是2019年一月一日凌晨0点钟执行,且只一次,假如错过了那么我将永远失去执行的机会"); } @Scheduled(cron = "0 0 0 1 1 3/4") public void task4(){ System.err.println("如果现在是2016年的话,我会在未来的3年后也就是2019年一月一日凌晨0点钟执行,假如错过了我会等待一年然后再执行一次"); } }
cyhjason/codes
SSM-Demo/src/main/java/com/cyh/sy/common/task/TaskManager.java
402
/** * * @描述:任务调度管理类 * @作者:cyh * @版本:V1.0 * @创建时间::2016-11-21 下午10:54:10 * */
block_comment
zh-cn
package com.cyh.sy.common.task; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; /** * * @描述 <SUF>*/ @Component public class TaskManager { @Scheduled(cron = "0 0/10 * * * ?") public void task1(){ System.out.println("我每10分钟都要执行一次,不管是刮风还是下雨"); } @Scheduled(cron = "0 0 2 * * ?") public void task2(){ System.out.println("我每天凌晨两点执行"); } @Scheduled(cron = "0 0 0 1 1 3") public void task3(){ System.err.println("如果现在是2016年的话,我会在未来的3年后也就是2019年一月一日凌晨0点钟执行,且只一次,假如错过了那么我将永远失去执行的机会"); } @Scheduled(cron = "0 0 0 1 1 3/4") public void task4(){ System.err.println("如果现在是2016年的话,我会在未来的3年后也就是2019年一月一日凌晨0点钟执行,假如错过了我会等待一年然后再执行一次"); } }
false
316
56
402
59
372
58
402
59
510
75
false
false
false
false
false
true
32807_4
package vo; import dataenum.UserIdentity; /** * 用户值对象 * @author cylong * @version Oct 26, 2014 1:59:25 PM */ /** * 添加name和phone属性 * @author cylong * @version 2014年12月1日 下午11:07:07 */ public class UserVO extends ValueObject { /** 用户名 */ public String username; /** 真实姓名 */ public String name; /** 用户密码 */ public String password; /** 用户电话 */ public String phone; /** 用户身份 */ public UserIdentity iden; public UserVO(String ID, String username, String name, String password, String phone, UserIdentity iden) { this.ID = ID; this.username = username; this.name = name; this.password = password; this.phone = phone; this.iden = iden; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "[用户ID=" + this.ID + ", " + "用户名=" + this.username + ", 姓名=" + this.name + ", 电话=" + this.phone + ", 身份=" + this.iden.value + "]"; } }
cylong1016/NJULily
src/main/java/vo/UserVO.java
337
/** 用户密码 */
block_comment
zh-cn
package vo; import dataenum.UserIdentity; /** * 用户值对象 * @author cylong * @version Oct 26, 2014 1:59:25 PM */ /** * 添加name和phone属性 * @author cylong * @version 2014年12月1日 下午11:07:07 */ public class UserVO extends ValueObject { /** 用户名 */ public String username; /** 真实姓名 */ public String name; /** 用户密 <SUF>*/ public String password; /** 用户电话 */ public String phone; /** 用户身份 */ public UserIdentity iden; public UserVO(String ID, String username, String name, String password, String phone, UserIdentity iden) { this.ID = ID; this.username = username; this.name = name; this.password = password; this.phone = phone; this.iden = iden; } /** * @see java.lang.Object#toString() */ @Override public String toString() { return "[用户ID=" + this.ID + ", " + "用户名=" + this.username + ", 姓名=" + this.name + ", 电话=" + this.phone + ", 身份=" + this.iden.value + "]"; } }
false
283
4
337
4
329
4
337
4
387
7
false
false
false
false
false
true
38221_9
package cn.czfshine.wechat.msg; import cn.czfshine.wechat.msg.xmlmsg.*; import java.io.Serializable; /** * @author:czfshine * @date:2018/2/20 22:02 */ public enum MSGTYPE implements Serializable { /**主要消息类型**/ TYPE_MSG(1,TextMessage.class,"文本"), TYPE_SPEAK(34,AudioMessage.class,"语音"), TYPE_WX_VIDEO (62,VideoMessage.class,"视频") , TYPE_VIDEO_FILE (43,VideoMessage.class,"视频文件"), TYPE_IMG (3,ImageMessage.class,"图片"), TYPE_EMOJI (47,EmojiMessage.class,"表情"), /**提示类**/ TYPE_YUYIN(64,PromptMessage.class,"微信语音聊天"), TYPE_VOIP (50,PromptMessage.class), TYPE_SYSTEM (10000,PromptMessage.class), /**富文本,基于xml**/ TYPE_BUSINESSCARD(42,BusinessCardMessage.class,"名片"), TYPE_LOCATION(48, LocationMessage.class,"位置"), TYPE_LINK (49, XmlLinkMessage.class,"链接") , TYPE_REDENVELOPE (436207665,RedEnvelopeMessage.class,"红包"), TYPE_LOCATION_SHARING (1879048186,XmlMessage.class,"位置共享"), TYPE_LOCATION_SHARING_D( -1879048186,XmlMessage.class,"位置共享"), TYPE_SPORT(-1879048185, SportMessage.class,"微信运动"),//微信运动日提示 TYPE_SPOERINTERACTION(-1879048183, SportInteractionMessage.class,"微信运动赞"),//微信运动赞 TYPE_GROUP_MONEY(503316529,XmlMessage.class,"群收款"),//群收款 TYPE_TRANSFER(419430449, TransferMessage.class,"转帐"),//转账 TYPE_SHEAR(268435505,AppShareMessage.class,"应用分享"),//别的应用的分享 TYPE_APP_MSG (16777265,NotionMessage.class,"应用消息"), TYPE_APP_NOTION(318767153,NotionMessage.class,"公众号提醒"),//公众号应用消息 TYPE_GROUP(10002,XmlMessage.class,"群通知"),//群相关的系统通知 TYPE_APP(570425393,GroupMessage.class,"邀请"), TYPE_JUAN(452984881,XmlMessage.class), TYPE_CLOUD(35,XmlMessage.class), /**链接**/ TYPE_MP_TUIWEN(285212721,LinkMessage.class),//公众号推文 /*未处理*/ //TODO TYPE_CUSTOM_EMOJI (1048625, CustomEmojiMessage.class), TYPE_UNKNOW(-1,UnknownMessage.class); public final int id; private String typename=""; public Class getClazz() { return clazz; } private Class clazz; MSGTYPE(int typeid, Class cl){ id=typeid; clazz=cl; } MSGTYPE(int typeid, Class cl ,String typename){ id=typeid; clazz=cl; this.typename=typename; } public static MSGTYPE getType(int typeid) throws UnknowMassageTypeException { for(MSGTYPE t:MSGTYPE.values()){ if(t.id==typeid){ return t; } } return TYPE_UNKNOW; } @Override public String toString() { if(!"".equals(typename)) { return typename; } return "无名类型"+id; } }
czfshine/wechattool
src/main/java/cn/czfshine/wechat/msg/MSGTYPE.java
961
//群相关的系统通知
line_comment
zh-cn
package cn.czfshine.wechat.msg; import cn.czfshine.wechat.msg.xmlmsg.*; import java.io.Serializable; /** * @author:czfshine * @date:2018/2/20 22:02 */ public enum MSGTYPE implements Serializable { /**主要消息类型**/ TYPE_MSG(1,TextMessage.class,"文本"), TYPE_SPEAK(34,AudioMessage.class,"语音"), TYPE_WX_VIDEO (62,VideoMessage.class,"视频") , TYPE_VIDEO_FILE (43,VideoMessage.class,"视频文件"), TYPE_IMG (3,ImageMessage.class,"图片"), TYPE_EMOJI (47,EmojiMessage.class,"表情"), /**提示类**/ TYPE_YUYIN(64,PromptMessage.class,"微信语音聊天"), TYPE_VOIP (50,PromptMessage.class), TYPE_SYSTEM (10000,PromptMessage.class), /**富文本,基于xml**/ TYPE_BUSINESSCARD(42,BusinessCardMessage.class,"名片"), TYPE_LOCATION(48, LocationMessage.class,"位置"), TYPE_LINK (49, XmlLinkMessage.class,"链接") , TYPE_REDENVELOPE (436207665,RedEnvelopeMessage.class,"红包"), TYPE_LOCATION_SHARING (1879048186,XmlMessage.class,"位置共享"), TYPE_LOCATION_SHARING_D( -1879048186,XmlMessage.class,"位置共享"), TYPE_SPORT(-1879048185, SportMessage.class,"微信运动"),//微信运动日提示 TYPE_SPOERINTERACTION(-1879048183, SportInteractionMessage.class,"微信运动赞"),//微信运动赞 TYPE_GROUP_MONEY(503316529,XmlMessage.class,"群收款"),//群收款 TYPE_TRANSFER(419430449, TransferMessage.class,"转帐"),//转账 TYPE_SHEAR(268435505,AppShareMessage.class,"应用分享"),//别的应用的分享 TYPE_APP_MSG (16777265,NotionMessage.class,"应用消息"), TYPE_APP_NOTION(318767153,NotionMessage.class,"公众号提醒"),//公众号应用消息 TYPE_GROUP(10002,XmlMessage.class,"群通知"),//群相 <SUF> TYPE_APP(570425393,GroupMessage.class,"邀请"), TYPE_JUAN(452984881,XmlMessage.class), TYPE_CLOUD(35,XmlMessage.class), /**链接**/ TYPE_MP_TUIWEN(285212721,LinkMessage.class),//公众号推文 /*未处理*/ //TODO TYPE_CUSTOM_EMOJI (1048625, CustomEmojiMessage.class), TYPE_UNKNOW(-1,UnknownMessage.class); public final int id; private String typename=""; public Class getClazz() { return clazz; } private Class clazz; MSGTYPE(int typeid, Class cl){ id=typeid; clazz=cl; } MSGTYPE(int typeid, Class cl ,String typename){ id=typeid; clazz=cl; this.typename=typename; } public static MSGTYPE getType(int typeid) throws UnknowMassageTypeException { for(MSGTYPE t:MSGTYPE.values()){ if(t.id==typeid){ return t; } } return TYPE_UNKNOW; } @Override public String toString() { if(!"".equals(typename)) { return typename; } return "无名类型"+id; } }
false
836
5
961
6
976
5
961
6
1,217
9
false
false
false
false
false
true
38735_4
package io.zhijian.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; /** * 获取IP工具类 * @author Hao * @create 2017-03-29 */ public class IPUtils { private static Logger logger = LoggerFactory.getLogger(PropertyReader.class); private static String LOCAL_IP_STAR_STR = "192.168."; static { String ip = null; String hostName = null; try { hostName = InetAddress.getLocalHost().getHostName(); InetAddress ipAddr[] = InetAddress.getAllByName(hostName); for (int i = 0; i < ipAddr.length; i++) { ip = ipAddr[i].getHostAddress(); if (ip.startsWith(LOCAL_IP_STAR_STR)) { break; } } if (ip == null) { ip = ipAddr[0].getHostAddress(); } } catch (UnknownHostException e) { logger.error("IpHelper error."); e.printStackTrace(); } LOCAL_IP = ip; HOST_NAME = hostName; } /** * 系统的本地IP地址 */ public static final String LOCAL_IP; /** * 系统的本地服务器名 */ public static final String HOST_NAME; /** * <p> * 获取客户端的IP地址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的。 * 但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了,如果通过了多级反向代理的话, * X-Forwarded-For的值并不止一个,而是一串IP值, 究竟哪个才是真正的用户端的真实IP呢? * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。 * 例如:X-Forwarded-For:192.168.1.110, 192.168.1.120, * 192.168.1.130, 192.168.1.100 用户真实IP为: 192.168.1.110 * </p> * * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); if (ip.equals("127.0.0.1")) { /** 根据网卡取本机配置的IP */ InetAddress inet = null; try { inet = InetAddress.getLocalHost(); ip = inet.getHostAddress(); } catch (UnknownHostException e) { logger.error("IpHelper error." + e.toString()); } } } /** * 对于通过多个代理的情况, 第一个IP为客户端真实IP,多个IP按照','分割 "***.***.***.***".length() = * 15 */ if (ip != null && ip.length() > 15) { if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } return ip; } }
daaao/app
app-utils/src/main/java/io/zhijian/utils/IPUtils.java
987
/** 根据网卡取本机配置的IP */
block_comment
zh-cn
package io.zhijian.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; /** * 获取IP工具类 * @author Hao * @create 2017-03-29 */ public class IPUtils { private static Logger logger = LoggerFactory.getLogger(PropertyReader.class); private static String LOCAL_IP_STAR_STR = "192.168."; static { String ip = null; String hostName = null; try { hostName = InetAddress.getLocalHost().getHostName(); InetAddress ipAddr[] = InetAddress.getAllByName(hostName); for (int i = 0; i < ipAddr.length; i++) { ip = ipAddr[i].getHostAddress(); if (ip.startsWith(LOCAL_IP_STAR_STR)) { break; } } if (ip == null) { ip = ipAddr[0].getHostAddress(); } } catch (UnknownHostException e) { logger.error("IpHelper error."); e.printStackTrace(); } LOCAL_IP = ip; HOST_NAME = hostName; } /** * 系统的本地IP地址 */ public static final String LOCAL_IP; /** * 系统的本地服务器名 */ public static final String HOST_NAME; /** * <p> * 获取客户端的IP地址的方法是:request.getRemoteAddr(),这种方法在大部分情况下都是有效的。 * 但是在通过了Apache,Squid等反向代理软件就不能获取到客户端的真实IP地址了,如果通过了多级反向代理的话, * X-Forwarded-For的值并不止一个,而是一串IP值, 究竟哪个才是真正的用户端的真实IP呢? * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。 * 例如:X-Forwarded-For:192.168.1.110, 192.168.1.120, * 192.168.1.130, 192.168.1.100 用户真实IP为: 192.168.1.110 * </p> * * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); if (ip.equals("127.0.0.1")) { /** 根据网 <SUF>*/ InetAddress inet = null; try { inet = InetAddress.getLocalHost(); ip = inet.getHostAddress(); } catch (UnknownHostException e) { logger.error("IpHelper error." + e.toString()); } } } /** * 对于通过多个代理的情况, 第一个IP为客户端真实IP,多个IP按照','分割 "***.***.***.***".length() = * 15 */ if (ip != null && ip.length() > 15) { if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } return ip; } }
false
894
13
987
11
1,037
11
987
11
1,258
16
false
false
false
false
false
true
39287_1
package string_02; public class StringMethodDemo02 { public static void main(String[] args) { //String subString(int beginIndex, int endIndex) // 截取字符串 的指定范围[]() String str = "又香又大新疆羊肉串哦"; System.out.println(str.substring(4, 9)); System.out.println(str.substring(4)); //替换功能 String replace() String str2 = "你个垃圾,0杀0助攻20死...垃圾死了"; System.out.println(str2.replaceAll("垃圾", "**")); } }
dada007007/JavaLearing
day09_code/src/string_02/StringMethodDemo02.java
163
// 截取字符串 的指定范围[]()
line_comment
zh-cn
package string_02; public class StringMethodDemo02 { public static void main(String[] args) { //String subString(int beginIndex, int endIndex) // 截取 <SUF> String str = "又香又大新疆羊肉串哦"; System.out.println(str.substring(4, 9)); System.out.println(str.substring(4)); //替换功能 String replace() String str2 = "你个垃圾,0杀0助攻20死...垃圾死了"; System.out.println(str2.replaceAll("垃圾", "**")); } }
false
126
11
162
12
154
11
162
12
207
22
false
false
false
false
false
true
23802_2
/** * 报时的钟 */ public class Clock { // 日期格式化 private final java.text.SimpleDateFormat clockDateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 状态检查 */ public void checkState() { java.util.Date d = nowDate(); long a = d.getTime(); try{Thread.sleep(500);}catch(Exception e){e.printStackTrace();} // throw new IllegalStateException("STATE ERROR!"); } public void doSomeTimeComsumingOperation(){ try{Thread.sleep(2000);}catch(Exception e){e.printStackTrace();} } /** * 获取当前时间 * * @return 当前时间 */ public java.util.Date nowDate() { return new java.util.Date(); } private void doSomeFastOperation(){ String s = ""; for(int i=0;i<10000;i++){ s += i; } new String(s); } /** * 报告时间 * * @return 报告时间 */ public String report(java.util.Date now) { checkState(); try{ Thread.sleep(400); }catch(Exception e){ e.printStackTrace(); } doSomeTimeComsumingOperation(); doSomeFastOperation(); String n = clockDateFormat.format(now); System.out.println("report: " + n); return n; } /** * 循环播报时间 */ final void loopReport() throws InterruptedException { while (true) { try { System.out.println(report(nowDate())); } catch (Throwable cause) { cause.printStackTrace(); } Thread.sleep(2000); } } public static void main(String... args) throws InterruptedException { new Clock().loopReport(); } }
dadiyang/jvm-sandbox-in-action
bin/demo/Clock.java
440
/** * 状态检查 */
block_comment
zh-cn
/** * 报时的钟 */ public class Clock { // 日期格式化 private final java.text.SimpleDateFormat clockDateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); /** * 状态检 <SUF>*/ public void checkState() { java.util.Date d = nowDate(); long a = d.getTime(); try{Thread.sleep(500);}catch(Exception e){e.printStackTrace();} // throw new IllegalStateException("STATE ERROR!"); } public void doSomeTimeComsumingOperation(){ try{Thread.sleep(2000);}catch(Exception e){e.printStackTrace();} } /** * 获取当前时间 * * @return 当前时间 */ public java.util.Date nowDate() { return new java.util.Date(); } private void doSomeFastOperation(){ String s = ""; for(int i=0;i<10000;i++){ s += i; } new String(s); } /** * 报告时间 * * @return 报告时间 */ public String report(java.util.Date now) { checkState(); try{ Thread.sleep(400); }catch(Exception e){ e.printStackTrace(); } doSomeTimeComsumingOperation(); doSomeFastOperation(); String n = clockDateFormat.format(now); System.out.println("report: " + n); return n; } /** * 循环播报时间 */ final void loopReport() throws InterruptedException { while (true) { try { System.out.println(report(nowDate())); } catch (Throwable cause) { cause.printStackTrace(); } Thread.sleep(2000); } } public static void main(String... args) throws InterruptedException { new Clock().loopReport(); } }
false
402
9
440
8
500
9
440
8
566
14
false
false
false
false
false
true
60169_6
package net.dreamlu.model; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import net.dreamlu.config.Consts; import com.jfinal.ext.plugin.db.DbModel; import com.jfinal.kit.StrKit; /** * 网站相关的链接 广告,友情链接 * @author L.cm * email: 596392912@qq.com * site: http://www.dreamlu.net * @date 2013-5-30 下午3:28:32 */ public class Links extends DbModel<Links> { private static final long serialVersionUID = -1561161846934854254L; public static final Links dao = new Links(); public static final String TABLE_NAME = "links"; public static final String ID = "id"; // id public static final String TYPE = "type"; // 分类 默认:0 友情链接 广告:1 其他待定 public static final String TITLE = "title"; // 链接说明 public static final String URL = "url"; // 链接url public static final String IMG = "img"; // 链接图片 public static final String ORDERS = "orders"; // 排序id public static final String DEL_STATUS = "del_status"; // 是否删除 默认:0 删除:1 public static final String CREATE_TIME = "create_time"; // 添加时间 public static final String UPDATE_TIME = "update_time"; // 更新时间 public static final int DEL_N = 0; // 未删 public static final int DEL_Y = 1; // 已删 // 统一保存 public boolean saveLinks() { this.set(Links.DEL_STATUS, Links.DEL_N); this.set(Links.CREATE_TIME, new Date()); this.set(Links.UPDATE_TIME, new Date()); return this.save(); } // 统一保存 public boolean updateLinks() { this.set(Links.UPDATE_TIME, new Date()); return this.update(); } /** * 从缓存查找连接 */ public List<Links> findListByType(int type, Integer status) { final List<Object> parameters = new ArrayList<Object>(); StringBuilder sql = new StringBuilder("SELECT l.* FROM links l WHERE 1 = 1 AND l.type =? "); parameters.add(type); if ( null != status ) { sql.append(" AND l.del_status = ? "); parameters.add(status.intValue()); } sql.append(" ORDER BY l.orders, l.id ASC"); return dao.findByCache(Consts.CACHE_TIME_MAX, sql.toString(), parameters.toArray()); } /** * 链接管理 */ public Map<String, Object> pageDataTables(int pageNum, int pageSize, String sEcho, String search) { final List<Object> parameters = new ArrayList<Object>(); String select = "SELECT l.*"; StringBuilder sqlExceptSelect = new StringBuilder(" FROM links AS l"); if (StrKit.notBlank(search)) { sqlExceptSelect.append(" AND l.title like ?"); parameters.add("%" + search + "%"); } sqlExceptSelect.append(" ORDER BY l.id DESC"); return dao.paginateDataTables(pageNum, pageSize, select, sqlExceptSelect.toString(), sEcho, parameters.toArray()); } }
daelan-zhou/JFinalBlog
src/net/dreamlu/model/Links.java
825
// 是否删除 默认:0 删除:1
line_comment
zh-cn
package net.dreamlu.model; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import net.dreamlu.config.Consts; import com.jfinal.ext.plugin.db.DbModel; import com.jfinal.kit.StrKit; /** * 网站相关的链接 广告,友情链接 * @author L.cm * email: 596392912@qq.com * site: http://www.dreamlu.net * @date 2013-5-30 下午3:28:32 */ public class Links extends DbModel<Links> { private static final long serialVersionUID = -1561161846934854254L; public static final Links dao = new Links(); public static final String TABLE_NAME = "links"; public static final String ID = "id"; // id public static final String TYPE = "type"; // 分类 默认:0 友情链接 广告:1 其他待定 public static final String TITLE = "title"; // 链接说明 public static final String URL = "url"; // 链接url public static final String IMG = "img"; // 链接图片 public static final String ORDERS = "orders"; // 排序id public static final String DEL_STATUS = "del_status"; // 是否 <SUF> public static final String CREATE_TIME = "create_time"; // 添加时间 public static final String UPDATE_TIME = "update_time"; // 更新时间 public static final int DEL_N = 0; // 未删 public static final int DEL_Y = 1; // 已删 // 统一保存 public boolean saveLinks() { this.set(Links.DEL_STATUS, Links.DEL_N); this.set(Links.CREATE_TIME, new Date()); this.set(Links.UPDATE_TIME, new Date()); return this.save(); } // 统一保存 public boolean updateLinks() { this.set(Links.UPDATE_TIME, new Date()); return this.update(); } /** * 从缓存查找连接 */ public List<Links> findListByType(int type, Integer status) { final List<Object> parameters = new ArrayList<Object>(); StringBuilder sql = new StringBuilder("SELECT l.* FROM links l WHERE 1 = 1 AND l.type =? "); parameters.add(type); if ( null != status ) { sql.append(" AND l.del_status = ? "); parameters.add(status.intValue()); } sql.append(" ORDER BY l.orders, l.id ASC"); return dao.findByCache(Consts.CACHE_TIME_MAX, sql.toString(), parameters.toArray()); } /** * 链接管理 */ public Map<String, Object> pageDataTables(int pageNum, int pageSize, String sEcho, String search) { final List<Object> parameters = new ArrayList<Object>(); String select = "SELECT l.*"; StringBuilder sqlExceptSelect = new StringBuilder(" FROM links AS l"); if (StrKit.notBlank(search)) { sqlExceptSelect.append(" AND l.title like ?"); parameters.add("%" + search + "%"); } sqlExceptSelect.append(" ORDER BY l.id DESC"); return dao.paginateDataTables(pageNum, pageSize, select, sqlExceptSelect.toString(), sEcho, parameters.toArray()); } }
false
763
11
825
11
871
11
825
11
1,009
17
false
false
false
false
false
true
49769_40
package com.zoomlion.hjsrm.pub.common; import java.io.Serializable; public class InspectGlobal extends Globals implements Serializable { private static final long serialVersionUID = 4544582373536964718L; /** **************稽查类型 欠费稽查:6010 查户稽查:6020 违章稽查:6030************** */ /** * 欠费稽查 */ public static final String PLANTYPE_ARREARS = "6010"; /** * 查户稽查 */ public static final String PLANTYPE_PATROL = "6020"; /** * 违章稽查 */ public static final String PLANTYPE_ILLEGAL = "6030"; /** *****************稽查计划表 状态 1 未派工 2 已完成 3 执行中 4 已取消****** */ /** * 未派工 */ public static final String PLANSTATE_NOTWORK = "1"; // /** * 已完成 */ public static final String PLANSTATE_FINISHED = "2"; // /** * 执行中 */ public static final String PLANSTATE_INPROGRESS = "3"; // /** * 已取消 */ public static final String PLANSTATE_CANCELED = "4"; // /** *****************稽查计划明细 状态 1 有效 0 无效****** */ /** * 有效 */ public static final String PLANTASKSTATE_VALID = "1"; // /** * 无效 */ public static final String PLANTASKSTATE_INVALID = "0"; // /** * 已录入 */ public static final String PLANTASKSTATE_SAVED = "2";// /** * 已转黑名单(欠费) */ public static final String PLANTASKSTATE_BLACKED = "3";// /** * 已传单 */ public static final String PLANTASKSTATE_TURNED = "4";// /** * *****************违章用户 状态 0 : 未入计划(待计划制定) 1 : 已入计划(在途中) 2 : 已稽查完毕****** */ /** * 未入计划 */ public static final String ILLEGALUSERSTATE_PREPARE = "0"; // /** * 已入计划 */ public static final String ILLEGALUSERSTATE_WORKING = "1"; // /** * 已稽查完毕 */ public static final String ILLEGALUSERSTATE_FINISHED = "2";// /** ******************稽查结果******************************** */ /** * 用户缴费 */ public static final String INSPECTRESAULT_PAYED = "0"; // /** * 承诺缴费 */ public static final String INSPECTRESULT_WILLPAY = "1";// /** * 拒绝缴费 */ public static final String INSPECTRESULT_NOPAY = "2";// /** * 无表 */ public static final String INSPECTRESULT_NOMETER = "3";// /** * 协议缴费 */ public static final String INSPECTRESULT_PACTPAY = "4";// /** * 后期无人 */ public static final String INSPECTRESULT_NOMAN = "5";// /** * 表坏 */ public static final String INSPECTRESULT_BADMETER = "6";// /** * 空房 */ public static final String INSPECTRESULT_VACANTROOM = "7";// /** * 拆房 */ public static final String INSPECTRESULT_TAKEROOM = "8";// /** * 部队 */ public static final String INSPECTRESULT_ARMY = "9";// /** * 其他 */ public static final String INSPECTRESULT_OTHER = "A";// /** ************************见表情况**************************正常、违章表具、表坏、表锈、超期表、乱码、空房户、代签、未进户、无铅封、漏气、其他***** */ /** * 正常 */ public static final String CHKRLTTYPE_NORMAL = "0";// /** * 违章表具 */ public static final String CHKRLTTYPE_BREAK = "1";// /** * 表坏 */ public static final String CHKRLTTYPE_DESTROY = "2";// /** * 表锈 */ public static final String CHKRLTTYPE_RUST = "3";// /** * 超期表 */ public static final String CHKRLTTYPE_PASSTIME = "4";// /** * 乱码 */ public static final String CHKRLTTYPE_MESSYCODE = "5";// /** * 空房户 */ public static final String CHKRLTTYPE_VACANTROOM = "6";// /** * 代签 */ public static final String CHKRLTTYPE_ALLOGRAPH = "7";// /** * 未进户 */ public static final String CHKRLTTYPE_UNHOUSEIN = "8";// /** * 无铅封 */ public static final String CHKRLTTYPE_UNSEALING = "9";// /** * 漏气 */ public static final String CHKRLTTYPE_LEAKAGE = "A";// /** * 其他 */ public static final String CHKRLTTYPE_OTHER = "B";// /** *****************违章稽查 稽查结果: 0未违章 1已整改 2未整改****** */ /** * 0未违章 */ public static final String ILLEGALCHECKRESULT_NORECORD = "0";// /** * 1已整改 */ public static final String ILLEGALCHECKRESULT_CORRECTED = "1";// /** * 2未整改 */ public static final String ILLEGALCHECKRESULT_UNCORRECTED = "2";// /** *****************安检稽查 稽查状态: 1已稽查****** */ /** * 1已稽查 */ public static final String CHECKRECORD_STATE = "1";// }
dafu71/keensen
com.zoomlion.hjsrm.pub/src/com/zoomlion/hjsrm/pub/common/InspectGlobal.java
1,610
/** * 未进户 */
block_comment
zh-cn
package com.zoomlion.hjsrm.pub.common; import java.io.Serializable; public class InspectGlobal extends Globals implements Serializable { private static final long serialVersionUID = 4544582373536964718L; /** **************稽查类型 欠费稽查:6010 查户稽查:6020 违章稽查:6030************** */ /** * 欠费稽查 */ public static final String PLANTYPE_ARREARS = "6010"; /** * 查户稽查 */ public static final String PLANTYPE_PATROL = "6020"; /** * 违章稽查 */ public static final String PLANTYPE_ILLEGAL = "6030"; /** *****************稽查计划表 状态 1 未派工 2 已完成 3 执行中 4 已取消****** */ /** * 未派工 */ public static final String PLANSTATE_NOTWORK = "1"; // /** * 已完成 */ public static final String PLANSTATE_FINISHED = "2"; // /** * 执行中 */ public static final String PLANSTATE_INPROGRESS = "3"; // /** * 已取消 */ public static final String PLANSTATE_CANCELED = "4"; // /** *****************稽查计划明细 状态 1 有效 0 无效****** */ /** * 有效 */ public static final String PLANTASKSTATE_VALID = "1"; // /** * 无效 */ public static final String PLANTASKSTATE_INVALID = "0"; // /** * 已录入 */ public static final String PLANTASKSTATE_SAVED = "2";// /** * 已转黑名单(欠费) */ public static final String PLANTASKSTATE_BLACKED = "3";// /** * 已传单 */ public static final String PLANTASKSTATE_TURNED = "4";// /** * *****************违章用户 状态 0 : 未入计划(待计划制定) 1 : 已入计划(在途中) 2 : 已稽查完毕****** */ /** * 未入计划 */ public static final String ILLEGALUSERSTATE_PREPARE = "0"; // /** * 已入计划 */ public static final String ILLEGALUSERSTATE_WORKING = "1"; // /** * 已稽查完毕 */ public static final String ILLEGALUSERSTATE_FINISHED = "2";// /** ******************稽查结果******************************** */ /** * 用户缴费 */ public static final String INSPECTRESAULT_PAYED = "0"; // /** * 承诺缴费 */ public static final String INSPECTRESULT_WILLPAY = "1";// /** * 拒绝缴费 */ public static final String INSPECTRESULT_NOPAY = "2";// /** * 无表 */ public static final String INSPECTRESULT_NOMETER = "3";// /** * 协议缴费 */ public static final String INSPECTRESULT_PACTPAY = "4";// /** * 后期无人 */ public static final String INSPECTRESULT_NOMAN = "5";// /** * 表坏 */ public static final String INSPECTRESULT_BADMETER = "6";// /** * 空房 */ public static final String INSPECTRESULT_VACANTROOM = "7";// /** * 拆房 */ public static final String INSPECTRESULT_TAKEROOM = "8";// /** * 部队 */ public static final String INSPECTRESULT_ARMY = "9";// /** * 其他 */ public static final String INSPECTRESULT_OTHER = "A";// /** ************************见表情况**************************正常、违章表具、表坏、表锈、超期表、乱码、空房户、代签、未进户、无铅封、漏气、其他***** */ /** * 正常 */ public static final String CHKRLTTYPE_NORMAL = "0";// /** * 违章表具 */ public static final String CHKRLTTYPE_BREAK = "1";// /** * 表坏 */ public static final String CHKRLTTYPE_DESTROY = "2";// /** * 表锈 */ public static final String CHKRLTTYPE_RUST = "3";// /** * 超期表 */ public static final String CHKRLTTYPE_PASSTIME = "4";// /** * 乱码 */ public static final String CHKRLTTYPE_MESSYCODE = "5";// /** * 空房户 */ public static final String CHKRLTTYPE_VACANTROOM = "6";// /** * 代签 */ public static final String CHKRLTTYPE_ALLOGRAPH = "7";// /** * 未进户 <SUF>*/ public static final String CHKRLTTYPE_UNHOUSEIN = "8";// /** * 无铅封 */ public static final String CHKRLTTYPE_UNSEALING = "9";// /** * 漏气 */ public static final String CHKRLTTYPE_LEAKAGE = "A";// /** * 其他 */ public static final String CHKRLTTYPE_OTHER = "B";// /** *****************违章稽查 稽查结果: 0未违章 1已整改 2未整改****** */ /** * 0未违章 */ public static final String ILLEGALCHECKRESULT_NORECORD = "0";// /** * 1已整改 */ public static final String ILLEGALCHECKRESULT_CORRECTED = "1";// /** * 2未整改 */ public static final String ILLEGALCHECKRESULT_UNCORRECTED = "2";// /** *****************安检稽查 稽查状态: 1已稽查****** */ /** * 1已稽查 */ public static final String CHECKRECORD_STATE = "1";// }
false
1,396
10
1,610
9
1,582
10
1,610
9
2,070
11
false
false
false
false
false
true
58692_25
package com.mallcai.fulfillment.common.utils; import java.util.List; /** * @author wangtao * @description: TODO * @title: RedisKeyGenerator * @date 2019-06-11 16:48 */ public class RedisKeyGenerator { /** * 生成用户充值券key */ public static String generateRechargePointsKey(Integer userId) { return "rechargePoints:user_id:" + userId; } /** * 订单回滚开关key */ public static String orderRollbackSwitchKey() { return "orderRollback:batchRollback:switch"; } /** * 订单回滚异常数据 */ public static String orderExceptionKey() { return "orderRollback:exception:key"; } /** * 订单迁移批量开关key */ public static String orderTransferBatchSwitchKey() { return "orderTransfer:batchTransfer:switch"; } /** * 订单迁移每日开关key */ public static String orderTransferDaySwitchKey() { return "orderTransfer:dayTransfer:switch"; } /** * 订单删除批量开关key */ public static String orderDeleteBatchSwitchKey() { return "orderTransfer:batchDelete:switch"; } /** * 订单删除每日开关key */ public static String orderDeleteDaySwitchKey() { return "orderTransfer:dayDelete:switch"; } /** * 每日增量订单迁移任务分布式锁key */ public static String orderTransferDayTaskLockKey() { return "orderTransfer:dayTask:lock"; } /** * 每日增量订单迁移任务执行结果key */ public static String orderTransferDayTaskResultKey() { return "orderTransfer:dayTask:result"; } /** * 历史库复原主库开关 */ public static String recoverOrderMainSwitchKey() { return "order:recovery:switch"; } /** * 批量生成订单索引开关key */ public static String generateOrderIndexSwitchKey() { return "orderIndex:batch:switch"; } /** * 每日充值券迁移增量分布式锁 */ public static String rechargePointDayTaskLockKey() { return "rechargePoint_dayTask_lock"; } /** * 充值券迁移批量执行开关锁 */ public static String rechargePointSwitchKey() { return "rechargePoint:batch:switch"; } /** * 取货订单并发锁 */ public static String deliveredOrderLockKey() { return "lock:delivered:order:"; } /** * 发票申请锁 */ public static String invoiceApplyLockKey() { return "lock:invoice:apply:"; } /** * 全局发票控制开关 */ public static String invoiceApplySwitchKey() { return "invoice:apply:switch"; } /** * 商家商品销售额 */ public static String merchantProductSalesAmountKey(List<Long> productIds, String day) { StringBuffer key = new StringBuffer("merchant:" + day + ":"); productIds.forEach(productId -> { key.append(productId.toString() + ":"); }); return key.toString(); } /** * 余额充值记录迁移-批量开关key */ public static String depositLogTransferBatchSwitchKey() { return "depositLogTransfer:batchTransfer:switch"; } /** * 余额充值记录迁移-每日开关key */ public static String depositLogTransferDaySwitchKey() { return "depositLogTransfer:dayTransfer:switch"; } /** * 余额充值记录删除-批量开关key */ public static String depositLogDeleteBatchSwitchKey() { return "depositLogTransfer:batchDelete:switch"; } /** * 余额充值记录删除-每日开关key */ public static String depositLogDeleteDaySwitchKey() { return "depositLogTransfer:dayDelete:switch"; } /** * 余额充值记录每日增量迁移任务-分布式锁key */ public static String depositLogTransferDayTaskLockKey() { return "depositLogTransfer:dayTask:lock"; } /** * 余额充值记录每日增量迁移任务-执行结果key */ public static String depositLogTransferDayTaskResultKey() { return "depositLogTransfer:dayTask:result"; } /** * 评价回访记录迁移-批量开关key */ public static String evaluateFeedbackTransferBatchSwitchKey() { return "evaluateFeedbackTransfer:batchTransfer:switch"; } /** * 异常结算数据处理key */ public static String orderPickUpLockKey() { return "order:pickUp:lock"; } /** * 异常结算数据处理key */ public static String orderPickUpSwitchKey() { return "order:pickUp:switch:key"; } /** * 线上取菜入口控制开关 */ public static String onlinePickUpSwitchKey() { return "orderOnline:pickup:switch"; } /** * mongo订单迁移批量开关key */ public static String mongoOrderTransferBatchSwitchKey() { return "mongoOrderTransfer:batchTransfer:switch"; } /** * mongo订单迁移每日开关key */ public static String mongoOrderTransferDaySwitchKey() { return "mongoOrderTransfer:dayTransfer:switch"; } /** * mongo订单删除批量开关key */ public static String mongoOrderDeleteBatchSwitchKey() { return "mongoOrderTransfer:batchDelete:switch"; } /** * mongo订单删除每日开关key */ public static String mongoOrderDeleteDaySwitchKey() { return "mongoOrderTransfer:dayDelete:switch"; } /** * mongo每日增量订单迁移任务分布式锁key */ public static String mongoOrderTransferDayTaskLockKey() { return "mongoOrderTransfer:dayTask:lock"; } /** * mongo每日增量订单迁移任务执行结果key */ public static String mongoOrderTransferDayTaskResultKey() { return "mongoOrderTransfer:dayTask:result"; } /** * mongo订单恢复批量开关key */ public static String mongoOrderRecoverBatchSwitchKey() { return "mongoOrderTransfer:batchRecover:switch"; } /** * 开票数据同步索引开关key */ public static String invoiceSyncDataSwitchKey() { return "invoice:syncData:switch"; } /** * 消息订单消息控制开关 */ public static String sendOrderMsgSwitch() { return "sendMsg:order:switch"; } }
dailuobo-code/fulfillment-center
fulfillment-dp-master/fulfillment-dp-common/src/main/java/com/mallcai/fulfillment/common/utils/RedisKeyGenerator.java
1,592
/** * 异常结算数据处理key */
block_comment
zh-cn
package com.mallcai.fulfillment.common.utils; import java.util.List; /** * @author wangtao * @description: TODO * @title: RedisKeyGenerator * @date 2019-06-11 16:48 */ public class RedisKeyGenerator { /** * 生成用户充值券key */ public static String generateRechargePointsKey(Integer userId) { return "rechargePoints:user_id:" + userId; } /** * 订单回滚开关key */ public static String orderRollbackSwitchKey() { return "orderRollback:batchRollback:switch"; } /** * 订单回滚异常数据 */ public static String orderExceptionKey() { return "orderRollback:exception:key"; } /** * 订单迁移批量开关key */ public static String orderTransferBatchSwitchKey() { return "orderTransfer:batchTransfer:switch"; } /** * 订单迁移每日开关key */ public static String orderTransferDaySwitchKey() { return "orderTransfer:dayTransfer:switch"; } /** * 订单删除批量开关key */ public static String orderDeleteBatchSwitchKey() { return "orderTransfer:batchDelete:switch"; } /** * 订单删除每日开关key */ public static String orderDeleteDaySwitchKey() { return "orderTransfer:dayDelete:switch"; } /** * 每日增量订单迁移任务分布式锁key */ public static String orderTransferDayTaskLockKey() { return "orderTransfer:dayTask:lock"; } /** * 每日增量订单迁移任务执行结果key */ public static String orderTransferDayTaskResultKey() { return "orderTransfer:dayTask:result"; } /** * 历史库复原主库开关 */ public static String recoverOrderMainSwitchKey() { return "order:recovery:switch"; } /** * 批量生成订单索引开关key */ public static String generateOrderIndexSwitchKey() { return "orderIndex:batch:switch"; } /** * 每日充值券迁移增量分布式锁 */ public static String rechargePointDayTaskLockKey() { return "rechargePoint_dayTask_lock"; } /** * 充值券迁移批量执行开关锁 */ public static String rechargePointSwitchKey() { return "rechargePoint:batch:switch"; } /** * 取货订单并发锁 */ public static String deliveredOrderLockKey() { return "lock:delivered:order:"; } /** * 发票申请锁 */ public static String invoiceApplyLockKey() { return "lock:invoice:apply:"; } /** * 全局发票控制开关 */ public static String invoiceApplySwitchKey() { return "invoice:apply:switch"; } /** * 商家商品销售额 */ public static String merchantProductSalesAmountKey(List<Long> productIds, String day) { StringBuffer key = new StringBuffer("merchant:" + day + ":"); productIds.forEach(productId -> { key.append(productId.toString() + ":"); }); return key.toString(); } /** * 余额充值记录迁移-批量开关key */ public static String depositLogTransferBatchSwitchKey() { return "depositLogTransfer:batchTransfer:switch"; } /** * 余额充值记录迁移-每日开关key */ public static String depositLogTransferDaySwitchKey() { return "depositLogTransfer:dayTransfer:switch"; } /** * 余额充值记录删除-批量开关key */ public static String depositLogDeleteBatchSwitchKey() { return "depositLogTransfer:batchDelete:switch"; } /** * 余额充值记录删除-每日开关key */ public static String depositLogDeleteDaySwitchKey() { return "depositLogTransfer:dayDelete:switch"; } /** * 余额充值记录每日增量迁移任务-分布式锁key */ public static String depositLogTransferDayTaskLockKey() { return "depositLogTransfer:dayTask:lock"; } /** * 余额充值记录每日增量迁移任务-执行结果key */ public static String depositLogTransferDayTaskResultKey() { return "depositLogTransfer:dayTask:result"; } /** * 评价回访记录迁移-批量开关key */ public static String evaluateFeedbackTransferBatchSwitchKey() { return "evaluateFeedbackTransfer:batchTransfer:switch"; } /** * 异常结 <SUF>*/ public static String orderPickUpLockKey() { return "order:pickUp:lock"; } /** * 异常结算数据处理key */ public static String orderPickUpSwitchKey() { return "order:pickUp:switch:key"; } /** * 线上取菜入口控制开关 */ public static String onlinePickUpSwitchKey() { return "orderOnline:pickup:switch"; } /** * mongo订单迁移批量开关key */ public static String mongoOrderTransferBatchSwitchKey() { return "mongoOrderTransfer:batchTransfer:switch"; } /** * mongo订单迁移每日开关key */ public static String mongoOrderTransferDaySwitchKey() { return "mongoOrderTransfer:dayTransfer:switch"; } /** * mongo订单删除批量开关key */ public static String mongoOrderDeleteBatchSwitchKey() { return "mongoOrderTransfer:batchDelete:switch"; } /** * mongo订单删除每日开关key */ public static String mongoOrderDeleteDaySwitchKey() { return "mongoOrderTransfer:dayDelete:switch"; } /** * mongo每日增量订单迁移任务分布式锁key */ public static String mongoOrderTransferDayTaskLockKey() { return "mongoOrderTransfer:dayTask:lock"; } /** * mongo每日增量订单迁移任务执行结果key */ public static String mongoOrderTransferDayTaskResultKey() { return "mongoOrderTransfer:dayTask:result"; } /** * mongo订单恢复批量开关key */ public static String mongoOrderRecoverBatchSwitchKey() { return "mongoOrderTransfer:batchRecover:switch"; } /** * 开票数据同步索引开关key */ public static String invoiceSyncDataSwitchKey() { return "invoice:syncData:switch"; } /** * 消息订单消息控制开关 */ public static String sendOrderMsgSwitch() { return "sendMsg:order:switch"; } }
false
1,514
13
1,592
12
1,698
13
1,592
12
2,232
19
false
false
false
false
false
true
35245_25
/** * @author 王佳栋 * 此类主要负责游戏逻辑处理 */ public class MineField { private Mine[][] mineField; private int rows;//行 private int columns;//列 private int mines;//地雷数目 private int minesFound =0;//发现地雷的数目 private int minesRemaining;//剩余地雷数目 private int emptiesRemaining;//剩余可点击格数 //游戏中返回的三种状态 enum gameState{ WIN, LOSE, CONTINUE } /** * @param rows 行 * @param columns 列 * @param mines 需要埋的雷数目 */ public MineField(int rows, int columns, int mines){ //传参 this.rows=rows; this.columns=columns; this.mines=mines; minesRemaining=mines;//初始化剩余地雷数目 emptiesRemaining=rows*columns-mines;//初始化非雷格剩余数目 mineField =new Mine[rows][columns];//申请内存空间存放雷池 init();//初始化函数 //TODO: to populate after first-click //populate();//布雷函数 } /** * 为mineField数组中的每一个元素所占的位置“埋”一个默认状态的“雷” */ private void init(){ for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { mineField[i][j]=new Mine(); } } } /** * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * 对外公开的函数 递归 埋会“爆炸”的雷 mineCount默认为0 */ public void populate(int x,int y){ populate(0,x,y); } /** * @param mineCount 已经埋下的雷的数目 * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * 私有类,确保mineCount参数的安全性 */ private void populate(int mineCount,int x,int y){ int currentCount =mineCount;//局部变量currentCount负责在该函数内部记录已经埋下的雷的数目 double mineChance=(double) mines/(double)(rows*columns);//概率 for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { Mine thisMine= mineField[i][j]; //TODO: skip first-click button if((!thisMine.hasMine())&&(i!=x&&j!=y)){//如果没有雷 if(Math.random()<mineChance){//如果随机出来的数小于概率,就埋雷,已埋雷数+1 thisMine.setMine(); currentCount++; if(currentCount==mines){//如果数目达到要求,布雷结束 return; } } } } } /* for (Mine[] minesRow: mineField) { for (Mine thisMine:minesRow){ if(!thisMine.hasMine()){ if(Math.random()<mineChance){ thisMine.setMine(); currentCount++; if(currentCount==mines){ return; } } } } } */ if(currentCount<mines){//如果数目还没达到要求,递归继续埋雷 populate(currentCount,x,y); } } public int getMinesRemaining(){ return minesRemaining; } public int getMinesFound(){ return minesFound; } /** * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * @param left 判断是鼠标左键点击还是非左键点击 * @return 游戏应该处于的状态 * 根据Mine的内容对鼠标点击后应该产生什么结果做出反应,需要有优先级 */ public gameState resolveClick(int x, int y ,boolean left){ //TODO: deal with these shit!!! for(int i = 0 ; i < rows ; i++){ for (int j = 0; j < columns; j++){ if(i == x && j == y){ Mine thisMine = mineField[i][j]; if(left){//如果是左键点击 if(thisMine.getFlagState()==Mine.flagState.MINE){//优先判断flag return gameState.CONTINUE; } if(thisMine.isCleared()){//防止被翻开的数字被再次点击后还递归操作,节省资源 return gameState.CONTINUE; } if(thisMine.hasMine()){ return gameState.LOSE; } else{ return cascade(i,j);//是0的话,瀑布 } } else{//如果是非左键,统一当做右键处理 Mine.flagState state = thisMine.setFlagState(); if(state == Mine.flagState.MINE){ minesFound++; minesRemaining--; } else if(state==Mine.flagState.SUSPECT){ minesFound--; minesRemaining++; } } } } } return gameState.CONTINUE;//其他情况对游戏无影响 } /** * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * @return 游戏应该处于的状态 * 瀑布,如果点到0,调用这个函数,对周围未作标记的区域进行递归操作 */ // private gameState cascade(int x, int y){ if( x<0 || y<0 || x>rows || y>columns ){//若点到无关区,对游戏无影响 return gameState.CONTINUE; } Mine thisMine=mineField[x][y]; if (thisMine.getFlagState()==Mine.flagState.MINE){ return gameState.CONTINUE; } //如果这块地方没做标记,做上标记 if(!thisMine.isCleared()){ thisMine.clear(); emptiesRemaining--; if(emptiesRemaining==0) {//如果只剩下有雷区,则游戏以玩家获胜结束 return gameState.WIN; } } //??? if(countAdjacentMines(x,y)>0){/*递归结束条件:如果周围有雷,则这块地方应该是一个数字, 游戏继续,瀑布结束 */ return gameState.CONTINUE; } else {//判断周围8个空格 for (int i = x-1 ; i <= x+1 ; i++) { for (int j = y-1; j <= y+1 ; j++) { if(i<0||j<0||i>=rows||j>=columns){ continue; } else if(!mineField[i][j].isCleared()){//如果未标记,瀑布之 cascade(i,j); } } } } return gameState.CONTINUE; } /** * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * @return 附近存在的雷的数目 * 清点附近雷的数目 */ public int countAdjacentMines(int x,int y){ int count = 0; for(int i = x-1 ; i <= x+1 ; i++){//遍历周围8格 for (int j = y-1; j <= y+1 ; j++) { if(i == x && j == y){ continue; } else if(i<0||j<0||i>=rows||j>=columns){ continue; } else if(mineField[i][j].hasMine()){//周围每有一个雷,count++ count++; } } } return count; } public Mine.flagState getMineFlag(int x,int y){ return mineField[x][y].getFlagState(); } public boolean getMineCleared(int x, int y){ return mineField[x][y].isCleared(); } public boolean isMine(int x,int y){ return mineField[x][y].hasMine(); } }
dakehero/MineSweeper
src/MineField.java
2,019
//如果是左键点击
line_comment
zh-cn
/** * @author 王佳栋 * 此类主要负责游戏逻辑处理 */ public class MineField { private Mine[][] mineField; private int rows;//行 private int columns;//列 private int mines;//地雷数目 private int minesFound =0;//发现地雷的数目 private int minesRemaining;//剩余地雷数目 private int emptiesRemaining;//剩余可点击格数 //游戏中返回的三种状态 enum gameState{ WIN, LOSE, CONTINUE } /** * @param rows 行 * @param columns 列 * @param mines 需要埋的雷数目 */ public MineField(int rows, int columns, int mines){ //传参 this.rows=rows; this.columns=columns; this.mines=mines; minesRemaining=mines;//初始化剩余地雷数目 emptiesRemaining=rows*columns-mines;//初始化非雷格剩余数目 mineField =new Mine[rows][columns];//申请内存空间存放雷池 init();//初始化函数 //TODO: to populate after first-click //populate();//布雷函数 } /** * 为mineField数组中的每一个元素所占的位置“埋”一个默认状态的“雷” */ private void init(){ for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { mineField[i][j]=new Mine(); } } } /** * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * 对外公开的函数 递归 埋会“爆炸”的雷 mineCount默认为0 */ public void populate(int x,int y){ populate(0,x,y); } /** * @param mineCount 已经埋下的雷的数目 * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * 私有类,确保mineCount参数的安全性 */ private void populate(int mineCount,int x,int y){ int currentCount =mineCount;//局部变量currentCount负责在该函数内部记录已经埋下的雷的数目 double mineChance=(double) mines/(double)(rows*columns);//概率 for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { Mine thisMine= mineField[i][j]; //TODO: skip first-click button if((!thisMine.hasMine())&&(i!=x&&j!=y)){//如果没有雷 if(Math.random()<mineChance){//如果随机出来的数小于概率,就埋雷,已埋雷数+1 thisMine.setMine(); currentCount++; if(currentCount==mines){//如果数目达到要求,布雷结束 return; } } } } } /* for (Mine[] minesRow: mineField) { for (Mine thisMine:minesRow){ if(!thisMine.hasMine()){ if(Math.random()<mineChance){ thisMine.setMine(); currentCount++; if(currentCount==mines){ return; } } } } } */ if(currentCount<mines){//如果数目还没达到要求,递归继续埋雷 populate(currentCount,x,y); } } public int getMinesRemaining(){ return minesRemaining; } public int getMinesFound(){ return minesFound; } /** * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * @param left 判断是鼠标左键点击还是非左键点击 * @return 游戏应该处于的状态 * 根据Mine的内容对鼠标点击后应该产生什么结果做出反应,需要有优先级 */ public gameState resolveClick(int x, int y ,boolean left){ //TODO: deal with these shit!!! for(int i = 0 ; i < rows ; i++){ for (int j = 0; j < columns; j++){ if(i == x && j == y){ Mine thisMine = mineField[i][j]; if(left){//如果 <SUF> if(thisMine.getFlagState()==Mine.flagState.MINE){//优先判断flag return gameState.CONTINUE; } if(thisMine.isCleared()){//防止被翻开的数字被再次点击后还递归操作,节省资源 return gameState.CONTINUE; } if(thisMine.hasMine()){ return gameState.LOSE; } else{ return cascade(i,j);//是0的话,瀑布 } } else{//如果是非左键,统一当做右键处理 Mine.flagState state = thisMine.setFlagState(); if(state == Mine.flagState.MINE){ minesFound++; minesRemaining--; } else if(state==Mine.flagState.SUSPECT){ minesFound--; minesRemaining++; } } } } } return gameState.CONTINUE;//其他情况对游戏无影响 } /** * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * @return 游戏应该处于的状态 * 瀑布,如果点到0,调用这个函数,对周围未作标记的区域进行递归操作 */ // private gameState cascade(int x, int y){ if( x<0 || y<0 || x>rows || y>columns ){//若点到无关区,对游戏无影响 return gameState.CONTINUE; } Mine thisMine=mineField[x][y]; if (thisMine.getFlagState()==Mine.flagState.MINE){ return gameState.CONTINUE; } //如果这块地方没做标记,做上标记 if(!thisMine.isCleared()){ thisMine.clear(); emptiesRemaining--; if(emptiesRemaining==0) {//如果只剩下有雷区,则游戏以玩家获胜结束 return gameState.WIN; } } //??? if(countAdjacentMines(x,y)>0){/*递归结束条件:如果周围有雷,则这块地方应该是一个数字, 游戏继续,瀑布结束 */ return gameState.CONTINUE; } else {//判断周围8个空格 for (int i = x-1 ; i <= x+1 ; i++) { for (int j = y-1; j <= y+1 ; j++) { if(i<0||j<0||i>=rows||j>=columns){ continue; } else if(!mineField[i][j].isCleared()){//如果未标记,瀑布之 cascade(i,j); } } } } return gameState.CONTINUE; } /** * @param x 鼠标点击点的X坐标 * @param y 鼠标点击点的Y坐标 * @return 附近存在的雷的数目 * 清点附近雷的数目 */ public int countAdjacentMines(int x,int y){ int count = 0; for(int i = x-1 ; i <= x+1 ; i++){//遍历周围8格 for (int j = y-1; j <= y+1 ; j++) { if(i == x && j == y){ continue; } else if(i<0||j<0||i>=rows||j>=columns){ continue; } else if(mineField[i][j].hasMine()){//周围每有一个雷,count++ count++; } } } return count; } public Mine.flagState getMineFlag(int x,int y){ return mineField[x][y].getFlagState(); } public boolean getMineCleared(int x, int y){ return mineField[x][y].isCleared(); } public boolean isMine(int x,int y){ return mineField[x][y].hasMine(); } }
false
1,830
5
2,019
6
2,007
5
2,019
6
2,763
10
false
false
false
false
false
true
28557_7
// We are using 7 and -8 because the 32 bit INT_MAX and INT_MIN last digit is 7 & -8 respectively; // so if the rev is already equal to INT_MAX/10 and pop is >= 7 (or less than -8) then it'll be overflow. //这是一道简单题,但是依然有两个知识点需要掌握。 //首先,要记住INT_MIN=-2^31,对它去绝对值的话是会溢出整形的。所以对一个任意整形取绝对值的时候一定要考虑它是否可能是INT_MIN。 //其次,如果快速判断一个数字在进位的过程中是否溢出?比如说如何判断x*10 > INT_MAX?其实交换一下位置,用if (x > INT_MAX/10)就巧妙地规避溢出报错的问题 //看做一个stack, 123, 先Pop出1,->2,->3 class Solution { public int reverse(int x) { int rev = 0; while (x != 0) { int pop = x % 10; x /= 10; if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0; if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0; rev = rev * 10 + pop; } return rev; } } // wrong, 极限情况 Integer.MAX_VALUE 超出32位1534236469, return 0, temp=rev⋅10+pop can cause overflow. class Solution { public int reverse(int x) { int y = 0; int z = 0; while (x/10 != 0) { y = x%10; //注意顺序,先做y, 否则x会先被处理 x = x/10; z = z*10 + y*10; } z = z + x%10; return z; } }
dalianmao22233/leetcode-googlePrepare
007. Reverse Integer.java
525
//注意顺序,先做y, 否则x会先被处理
line_comment
zh-cn
// We are using 7 and -8 because the 32 bit INT_MAX and INT_MIN last digit is 7 & -8 respectively; // so if the rev is already equal to INT_MAX/10 and pop is >= 7 (or less than -8) then it'll be overflow. //这是一道简单题,但是依然有两个知识点需要掌握。 //首先,要记住INT_MIN=-2^31,对它去绝对值的话是会溢出整形的。所以对一个任意整形取绝对值的时候一定要考虑它是否可能是INT_MIN。 //其次,如果快速判断一个数字在进位的过程中是否溢出?比如说如何判断x*10 > INT_MAX?其实交换一下位置,用if (x > INT_MAX/10)就巧妙地规避溢出报错的问题 //看做一个stack, 123, 先Pop出1,->2,->3 class Solution { public int reverse(int x) { int rev = 0; while (x != 0) { int pop = x % 10; x /= 10; if (rev > Integer.MAX_VALUE/10 || (rev == Integer.MAX_VALUE / 10 && pop > 7)) return 0; if (rev < Integer.MIN_VALUE/10 || (rev == Integer.MIN_VALUE / 10 && pop < -8)) return 0; rev = rev * 10 + pop; } return rev; } } // wrong, 极限情况 Integer.MAX_VALUE 超出32位1534236469, return 0, temp=rev⋅10+pop can cause overflow. class Solution { public int reverse(int x) { int y = 0; int z = 0; while (x/10 != 0) { y = x%10; //注意 <SUF> x = x/10; z = z*10 + y*10; } z = z + x%10; return z; } }
false
471
16
525
15
517
15
525
15
641
23
false
false
false
false
false
true
40722_2
package creational.builder; public class Person { // 姓名(必填) private String name; // 性别(必填) private int sex; // 年龄(必填) private Integer age; // 兴趣(非必填) private String interest; // 头像(非必填) private String face; // 地址(非必填) private String address; public Person(PersonBuilder personBuilder) { this.name = personBuilder.name; this.sex = personBuilder.sex; this.age = personBuilder.age; this.interest = personBuilder.interest; this.face = personBuilder.face; this.address = personBuilder.address; } public static class PersonBuilder { // 姓名(必填) private String name; // 性别(必填) private int sex; // 年龄(必填) private Integer age; // 兴趣(非必填) private String interest; // 头像(非必填) private String face; // 地址(非必填) private String address; public PersonBuilder() { } public PersonBuilder setInterest(String interest) { this.interest = interest; return this; } public PersonBuilder setFace(String face) { this.face = face; return this; } public PersonBuilder setAddress(String address) { this.address = address; return this; } public PersonBuilder setName(String name) { this.name = name; return this; } public PersonBuilder setSex(int sex) { this.sex = sex; return this; } public PersonBuilder setAge(Integer age) { this.age = age; return this; } public Person build() { return new Person(this); } } public String getInterest() { return interest; } public String getFace() { return face; } public String getAddress() { return address; } public String getName() { return name; } public int getSex() { return sex; } public Integer getAge() { return age; } }
danbomingzhi11/design_patterns
src/main/java/creational/builder/Person.java
513
// 年龄(必填)
line_comment
zh-cn
package creational.builder; public class Person { // 姓名(必填) private String name; // 性别(必填) private int sex; // 年龄 <SUF> private Integer age; // 兴趣(非必填) private String interest; // 头像(非必填) private String face; // 地址(非必填) private String address; public Person(PersonBuilder personBuilder) { this.name = personBuilder.name; this.sex = personBuilder.sex; this.age = personBuilder.age; this.interest = personBuilder.interest; this.face = personBuilder.face; this.address = personBuilder.address; } public static class PersonBuilder { // 姓名(必填) private String name; // 性别(必填) private int sex; // 年龄(必填) private Integer age; // 兴趣(非必填) private String interest; // 头像(非必填) private String face; // 地址(非必填) private String address; public PersonBuilder() { } public PersonBuilder setInterest(String interest) { this.interest = interest; return this; } public PersonBuilder setFace(String face) { this.face = face; return this; } public PersonBuilder setAddress(String address) { this.address = address; return this; } public PersonBuilder setName(String name) { this.name = name; return this; } public PersonBuilder setSex(int sex) { this.sex = sex; return this; } public PersonBuilder setAge(Integer age) { this.age = age; return this; } public Person build() { return new Person(this); } } public String getInterest() { return interest; } public String getFace() { return face; } public String getAddress() { return address; } public String getName() { return name; } public int getSex() { return sex; } public Integer getAge() { return age; } }
false
484
8
513
8
576
7
513
8
660
12
false
false
false
false
false
true
12381_4
package com.dangdang.config.service; import java.util.Set; /** * 配置组参数 * * @author <a href="mailto:wangyuxuan@dangdang.com">Yuxuan Wang</a> * */ public abstract class ConfigProfile { /** * 节点下属性的加载模式 * * @author <a href="mailto:wangyuxuan@dangdang.com">Yuxuan Wang</a> * */ public static enum KeyLoadingMode { /** * 加载所有属性 */ ALL, /** * 包含某些属性 */ INCLUDE, /** * 排除某些属性 */ EXCLUDE; } /** * 项目配置版本 */ protected final String version; private KeyLoadingMode keyLoadingMode = KeyLoadingMode.ALL; /** * 需要包含或排除的key,由{@code KeyLoadingMode}决定 */ private Set<String> keysSpecified; public ConfigProfile(String version) { super(); this.version = version; } public final String getVersion() { return version; } public ConfigProfile.KeyLoadingMode getKeyLoadingMode() { return keyLoadingMode; } public void setKeyLoadingMode(ConfigProfile.KeyLoadingMode keyLoadingMode) { this.keyLoadingMode = keyLoadingMode; } public Set<String> getKeysSpecified() { return keysSpecified; } public void setKeysSpecified(Set<String> keysSpecified) { this.keysSpecified = keysSpecified; } }
dangdangdotcom/config-toolkit
config-toolkit/src/main/java/com/dangdang/config/service/ConfigProfile.java
401
/** * 排除某些属性 */
block_comment
zh-cn
package com.dangdang.config.service; import java.util.Set; /** * 配置组参数 * * @author <a href="mailto:wangyuxuan@dangdang.com">Yuxuan Wang</a> * */ public abstract class ConfigProfile { /** * 节点下属性的加载模式 * * @author <a href="mailto:wangyuxuan@dangdang.com">Yuxuan Wang</a> * */ public static enum KeyLoadingMode { /** * 加载所有属性 */ ALL, /** * 包含某些属性 */ INCLUDE, /** * 排除某 <SUF>*/ EXCLUDE; } /** * 项目配置版本 */ protected final String version; private KeyLoadingMode keyLoadingMode = KeyLoadingMode.ALL; /** * 需要包含或排除的key,由{@code KeyLoadingMode}决定 */ private Set<String> keysSpecified; public ConfigProfile(String version) { super(); this.version = version; } public final String getVersion() { return version; } public ConfigProfile.KeyLoadingMode getKeyLoadingMode() { return keyLoadingMode; } public void setKeyLoadingMode(ConfigProfile.KeyLoadingMode keyLoadingMode) { this.keyLoadingMode = keyLoadingMode; } public Set<String> getKeysSpecified() { return keysSpecified; } public void setKeysSpecified(Set<String> keysSpecified) { this.keysSpecified = keysSpecified; } }
false
351
11
401
11
404
11
401
11
500
20
false
false
false
false
false
true
21122_1
package seven; import java.util.Arrays; /** * Created by Administrator on 2018/3/19. +--+--+--+ | | | | +--+--+--+--+ | | | | | +--+--+--+--+ | | | | +--+--+--+ 填入0~9的数字。要求:连续的两个数字不能相邻。 (左右、上下、对角都算相邻) 一共有多少种可能的填数方案? 想法:先全排,然后判断是否为对应想要的数据 */ public class Project_6 { private static int[] arr = {0,1,2,3,4,5,6,7,8,9 } ; private static boolean[] flag = new boolean[11]; private static int[] result = new int[11]; private static int count = 0; public static void main(String[] args) { dfs(1); System.out.println(count); } private static void dfs(int step) { if(step>arr.length){ if(check(result)){ System.out.println(Arrays.toString(result)); count++; } return ; } for(int i = 0;i<arr.length;i++){ if(!flag[arr[i]]){ flag[arr[i]] = true; result[step] = arr[i]; dfs(step + 1); flag[arr[i]] = false; } } } // 判断数据是否成立 private static boolean check(int[] a) { if ((a[1]==a[2]+1||a[1]==a[2]-1)|| (a[1]==a[6]+1||a[1]==a[6]-1)|| (a[1]==a[5]+1||a[1]==a[5]-1)|| (a[1]==a[4]+1||a[1]==a[4]-1)) { return false; }else if ((a[2]==a[5]+1||a[2]==a[5]-1)|| (a[2]==a[3]+1||a[2]==a[3]-1)|| (a[2]==a[7]+1||a[2]==a[7]-1)|| (a[2]==a[6]+1||a[2]==a[6]-1)) { return false; }else if ((a[3]==a[6]+1||a[3]==a[6]-1)|| (a[3]==a[7]+1||a[3]==a[7]-1)) { return false; }else if ((a[4]==a[5]+1||a[4]==a[5]-1)|| (a[4]==a[8]+1||a[4]==a[8]-1)|| (a[4]==a[9]+1||a[4]==a[9]-1)) { return false; }else if ((a[6]==a[7]+1||a[6]==a[7]-1)|| (a[6]==a[10]+1||a[6]==a[10]-1)|| (a[6]==a[9]+1||a[6]==a[9]-1)) { return false; }else if (a[7]==a[10]+1||a[7]==a[10]-1) { return false; }else if (a[8]==a[9]+1||a[8]==a[9]-1) { return false; }else if (a[9]==a[10]+1||a[9]==a[10]-1) { return false; }else if ((a[5]==a[6]+1||a[5]==a[6]-1)|| (a[5]==a[10]+1||a[5]==a[10]-1)|| (a[5]==a[9]+1||a[5]==a[9]-1)|| (a[5]==a[8]+1||a[5]==a[8]-1)) { return false; } return true; } }
danqiusheng/algorithm_practice
src/seven/Project_6.java
995
// 判断数据是否成立
line_comment
zh-cn
package seven; import java.util.Arrays; /** * Created by Administrator on 2018/3/19. +--+--+--+ | | | | +--+--+--+--+ | | | | | +--+--+--+--+ | | | | +--+--+--+ 填入0~9的数字。要求:连续的两个数字不能相邻。 (左右、上下、对角都算相邻) 一共有多少种可能的填数方案? 想法:先全排,然后判断是否为对应想要的数据 */ public class Project_6 { private static int[] arr = {0,1,2,3,4,5,6,7,8,9 } ; private static boolean[] flag = new boolean[11]; private static int[] result = new int[11]; private static int count = 0; public static void main(String[] args) { dfs(1); System.out.println(count); } private static void dfs(int step) { if(step>arr.length){ if(check(result)){ System.out.println(Arrays.toString(result)); count++; } return ; } for(int i = 0;i<arr.length;i++){ if(!flag[arr[i]]){ flag[arr[i]] = true; result[step] = arr[i]; dfs(step + 1); flag[arr[i]] = false; } } } // 判断 <SUF> private static boolean check(int[] a) { if ((a[1]==a[2]+1||a[1]==a[2]-1)|| (a[1]==a[6]+1||a[1]==a[6]-1)|| (a[1]==a[5]+1||a[1]==a[5]-1)|| (a[1]==a[4]+1||a[1]==a[4]-1)) { return false; }else if ((a[2]==a[5]+1||a[2]==a[5]-1)|| (a[2]==a[3]+1||a[2]==a[3]-1)|| (a[2]==a[7]+1||a[2]==a[7]-1)|| (a[2]==a[6]+1||a[2]==a[6]-1)) { return false; }else if ((a[3]==a[6]+1||a[3]==a[6]-1)|| (a[3]==a[7]+1||a[3]==a[7]-1)) { return false; }else if ((a[4]==a[5]+1||a[4]==a[5]-1)|| (a[4]==a[8]+1||a[4]==a[8]-1)|| (a[4]==a[9]+1||a[4]==a[9]-1)) { return false; }else if ((a[6]==a[7]+1||a[6]==a[7]-1)|| (a[6]==a[10]+1||a[6]==a[10]-1)|| (a[6]==a[9]+1||a[6]==a[9]-1)) { return false; }else if (a[7]==a[10]+1||a[7]==a[10]-1) { return false; }else if (a[8]==a[9]+1||a[8]==a[9]-1) { return false; }else if (a[9]==a[10]+1||a[9]==a[10]-1) { return false; }else if ((a[5]==a[6]+1||a[5]==a[6]-1)|| (a[5]==a[10]+1||a[5]==a[10]-1)|| (a[5]==a[9]+1||a[5]==a[9]-1)|| (a[5]==a[8]+1||a[5]==a[8]-1)) { return false; } return true; } }
false
949
6
995
6
1,037
5
995
6
1,172
10
false
false
false
false
false
true
17401_4
public class Page<T> { private List<T> data;//分页数据 private long count;//总记录数 private int preSize =10;//分页大小 private int offset = 0;//偏移量 private int currNum = 0;//当前页 public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public int getPreSize() { return preSize; } public void setPreSize(int preSize) { this.preSize = preSize; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getCurrNum() { return currNum; } public void setCurrNum(int currNum) { this.currNum = currNum; } }
dardarlin/jdbcTemplateDao
page.java
273
//当前页
line_comment
zh-cn
public class Page<T> { private List<T> data;//分页数据 private long count;//总记录数 private int preSize =10;//分页大小 private int offset = 0;//偏移量 private int currNum = 0;//当前 <SUF> public List<T> getData() { return data; } public void setData(List<T> data) { this.data = data; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public int getPreSize() { return preSize; } public void setPreSize(int preSize) { this.preSize = preSize; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } public int getCurrNum() { return currNum; } public void setCurrNum(int currNum) { this.currNum = currNum; } }
false
214
3
273
3
274
3
273
3
305
4
false
false
false
false
false
true
8941_5
package openeyes.dr.openeyes.networks; import openeyes.dr.openeyes.view.activity.StatementActivity; /** * Created by darryrzhong on 2018/6/7. * 网络请求地址API */ public interface API { //每日精选 public static final String DAILY="http://baobab.wandoujia.com/api/v2/feed?num=2&udid=26868b32e808498db32fd51fb422d00175e179df&vc=83"; //发现更多 public static final String FIND_MORE="http://baobab.wandoujia.com/api/v2/categories?udid=26868b32e808498db32fd51fb422d00175e179df&vc=83"; //热门排行 public static final String HOT_STRATEGY="http://baobab.wandoujia.com/api/v3/ranklist?num=10&strategy=%s&udid=26868b32e808498db32fd51fb422d00175e179df&vc=83"; //发现更多详情接口 public static final String FIND_DETAIL="http://baobab.kaiyanapp.com/api/v4/discovery/category"; //默认头像地址 public static final String USER_ICON="https://upload-images.jianshu.io/upload_images/5549640-bc72cbbac2138c94.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"; //关键字搜索接口 //http://baobab.kaiyanapp.com/api/v1/search?num=10&query=小姐姐 public static final String KEYWORD_SEARCH="http://baobab.kaiyanapp.com/api/v1/search?start=1&num=10&query="; //public static final String FIND_DETAIL="http://baobab.wandoujia.com/api/v3/videos?categoryName=%s&strategy=%s&udid=26868b32e808498db32fd51fb422d00175e179df&vc=83"; //http://baobab.wandoujia.com/api/v3/ranklist?num=10&strategy=monthly&udid=26868b32e808498db32fd51fb422d00175e179df&vc=83 //热映电影接口 public static final String HOT_VIDEO="https://api.douban.com/v2/movie/in_theaters?apikey=0b2bdeda43b5688921839c8ecb20399b&city=%E5%8C%97%E4%BA%AC&start=0&count=100&client=&udid="; //电影介绍接口,id来自热映电影中对于id; public static final String VIDEO = "http://api.douban.com/v2/movie/subject/"; public static final String VIDEO_ID ="?apikey=0b2bdeda43b5688921839c8ecb20399b&city=%E5%8C%97%E4%BA%AC&client=&udid="; //天气接口 public static final String WEATHER = "https://free-api.heweather.com/s6/weather/now?location=wuxi&key=746d5b65bae249439419ecb319a8663e"; }
darryrzhong/OpenEyes
app/src/main/java/openeyes/dr/openeyes/networks/API.java
971
//热门排行
line_comment
zh-cn
package openeyes.dr.openeyes.networks; import openeyes.dr.openeyes.view.activity.StatementActivity; /** * Created by darryrzhong on 2018/6/7. * 网络请求地址API */ public interface API { //每日精选 public static final String DAILY="http://baobab.wandoujia.com/api/v2/feed?num=2&udid=26868b32e808498db32fd51fb422d00175e179df&vc=83"; //发现更多 public static final String FIND_MORE="http://baobab.wandoujia.com/api/v2/categories?udid=26868b32e808498db32fd51fb422d00175e179df&vc=83"; //热门 <SUF> public static final String HOT_STRATEGY="http://baobab.wandoujia.com/api/v3/ranklist?num=10&strategy=%s&udid=26868b32e808498db32fd51fb422d00175e179df&vc=83"; //发现更多详情接口 public static final String FIND_DETAIL="http://baobab.kaiyanapp.com/api/v4/discovery/category"; //默认头像地址 public static final String USER_ICON="https://upload-images.jianshu.io/upload_images/5549640-bc72cbbac2138c94.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240"; //关键字搜索接口 //http://baobab.kaiyanapp.com/api/v1/search?num=10&query=小姐姐 public static final String KEYWORD_SEARCH="http://baobab.kaiyanapp.com/api/v1/search?start=1&num=10&query="; //public static final String FIND_DETAIL="http://baobab.wandoujia.com/api/v3/videos?categoryName=%s&strategy=%s&udid=26868b32e808498db32fd51fb422d00175e179df&vc=83"; //http://baobab.wandoujia.com/api/v3/ranklist?num=10&strategy=monthly&udid=26868b32e808498db32fd51fb422d00175e179df&vc=83 //热映电影接口 public static final String HOT_VIDEO="https://api.douban.com/v2/movie/in_theaters?apikey=0b2bdeda43b5688921839c8ecb20399b&city=%E5%8C%97%E4%BA%AC&start=0&count=100&client=&udid="; //电影介绍接口,id来自热映电影中对于id; public static final String VIDEO = "http://api.douban.com/v2/movie/subject/"; public static final String VIDEO_ID ="?apikey=0b2bdeda43b5688921839c8ecb20399b&city=%E5%8C%97%E4%BA%AC&client=&udid="; //天气接口 public static final String WEATHER = "https://free-api.heweather.com/s6/weather/now?location=wuxi&key=746d5b65bae249439419ecb319a8663e"; }
false
874
3
971
5
939
3
971
5
1,080
9
false
false
false
false
false
true
64377_2
package ys.drvier; import com.google.inject.ImplementedBy; import ys.component.InfraredDetector; import ys.drvier.impl.InfraredDetectorDriverImpl; import java.util.function.Consumer; /** * Created by yesheng on 2016/9/24. */ @ImplementedBy(InfraredDetectorDriverImpl.class) public interface InfraredDetectorDriver { // 创建实例 InfraredDetector create(int dataChannel); // 摧毁实例 void destroy(InfraredDetector infraredDetector); // 监听是否有人到来 void listen(InfraredDetector infraredDetector, final Consumer<Boolean> bodyNearHandler); }
dasheng523/pi
src/main/java/ys/drvier/InfraredDetectorDriver.java
173
// 摧毁实例
line_comment
zh-cn
package ys.drvier; import com.google.inject.ImplementedBy; import ys.component.InfraredDetector; import ys.drvier.impl.InfraredDetectorDriverImpl; import java.util.function.Consumer; /** * Created by yesheng on 2016/9/24. */ @ImplementedBy(InfraredDetectorDriverImpl.class) public interface InfraredDetectorDriver { // 创建实例 InfraredDetector create(int dataChannel); // 摧毁 <SUF> void destroy(InfraredDetector infraredDetector); // 监听是否有人到来 void listen(InfraredDetector infraredDetector, final Consumer<Boolean> bodyNearHandler); }
false
134
6
173
7
153
5
173
7
214
10
false
false
false
false
false
true
9931_1
/* * Copyright 2018-present datagear.tech * * This file is part of DataGear. * * DataGear is free software: you can redistribute it and/or modify it under the terms of * the GNU Lesser General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * DataGear is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with DataGear. * If not, see <https://www.gnu.org/licenses/>. */ package org.datagear.web.util; import java.util.List; /** * 消息通道。 * <p> * 支持向指定名称的通道发送消息、读取消息。 * </p> * * @author datagear@163.com * */ public interface MessageChannel { /** * 发送消息至指定通道末尾。 * * @param name * 消息通道名称 * @param messages */ public void push(String name, Object... messages); /** * 从指定通道开头读取一条消息并删除它。 * * @param <T> * @param name * 消息通道名称 * @return 消息对象,返回{@code null}表示无消息 */ public <T> T poll(String name); /** * 从指定通道开头读取最多指定数量的消息并删除它们。 * * @param <T> * @param name * 消息通道名称 * @param count * 最多数量,{@code -1}表示所有消息 * @return 消息对象列表,返回空列表表示无消息 */ public <T> List<T> poll(String name, int count); }
datageartech/datagear
datagear-web/src/main/java/org/datagear/web/util/MessageChannel.java
497
/** * 消息通道。 * <p> * 支持向指定名称的通道发送消息、读取消息。 * </p> * * @author datagear@163.com * */
block_comment
zh-cn
/* * Copyright 2018-present datagear.tech * * This file is part of DataGear. * * DataGear is free software: you can redistribute it and/or modify it under the terms of * the GNU Lesser General Public License as published by the Free Software Foundation, * either version 3 of the License, or (at your option) any later version. * * DataGear is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with DataGear. * If not, see <https://www.gnu.org/licenses/>. */ package org.datagear.web.util; import java.util.List; /** * 消息通 <SUF>*/ public interface MessageChannel { /** * 发送消息至指定通道末尾。 * * @param name * 消息通道名称 * @param messages */ public void push(String name, Object... messages); /** * 从指定通道开头读取一条消息并删除它。 * * @param <T> * @param name * 消息通道名称 * @return 消息对象,返回{@code null}表示无消息 */ public <T> T poll(String name); /** * 从指定通道开头读取最多指定数量的消息并删除它们。 * * @param <T> * @param name * 消息通道名称 * @param count * 最多数量,{@code -1}表示所有消息 * @return 消息对象列表,返回空列表表示无消息 */ public <T> List<T> poll(String name, int count); }
false
446
47
497
54
488
50
497
54
612
64
false
false
false
false
false
true
64470_2
package com.base.model; import java.sql.Timestamp; import java.util.Date; /** * 角色表 * * 项目名称:base_spring_framework 类名称:Role 类描述: 创建人:huangx 创建时间:2015年1月27日 下午6:42:22 * 修改人:huangx 修改时间:2015年1月27日 下午6:42:22 修改备注: * * 就四个角色 1\最高 2、财务 3、教务 4、前台 * @version 1.0 * */ public class Role { private Integer id; private String roleName;// 角色名称 private Integer state;// 状态,0=冻结,1=正常 private Date insertTime;// 插入时间 private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public Date getInsertTime() { return insertTime; } public void setInsertTime(Date insertTime) { this.insertTime = insertTime; } }
datasheetA/cms_security_spring
src/com/base/model/Role.java
412
// 状态,0=冻结,1=正常
line_comment
zh-cn
package com.base.model; import java.sql.Timestamp; import java.util.Date; /** * 角色表 * * 项目名称:base_spring_framework 类名称:Role 类描述: 创建人:huangx 创建时间:2015年1月27日 下午6:42:22 * 修改人:huangx 修改时间:2015年1月27日 下午6:42:22 修改备注: * * 就四个角色 1\最高 2、财务 3、教务 4、前台 * @version 1.0 * */ public class Role { private Integer id; private String roleName;// 角色名称 private Integer state;// 状态 <SUF> private Date insertTime;// 插入时间 private String description; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public Integer getState() { return state; } public void setState(Integer state) { this.state = state; } public Date getInsertTime() { return insertTime; } public void setInsertTime(Date insertTime) { this.insertTime = insertTime; } }
false
328
11
412
13
393
11
412
13
488
16
false
false
false
false
false
true
30755_5
/** * Copyright (c) 2015 The JobX Project * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.jobxhub.server.service; import com.google.common.collect.Lists; import com.jcraft.jsch.*; import com.jobxhub.common.Constants; import com.jobxhub.common.util.CommonUtils; import com.jobxhub.common.util.IOUtils; import com.jobxhub.server.domain.TerminalBean; import com.jobxhub.server.dao.TerminalDao; import com.jobxhub.server.support.JobXTools; import com.jobxhub.server.support.SshUserInfo; import com.jobxhub.server.support.TerminalClient; import com.jobxhub.server.tag.PageBean; import com.jobxhub.server.dto.Terminal; import com.jobxhub.server.dto.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.crypto.BadPaddingException; import javax.servlet.http.HttpSession; import java.io.*; import java.util.*; import static com.jobxhub.common.util.CommonUtils.notEmpty; /** * @author <a href="mailto:benjobs@qq.com">benjobs@qq.com</a> * @name:CommonUtil * @version: 1.0.0 * @company: com.jobxhub * @description: webconsole核心类 * @date: 2016-05-25 10:03<br/><br/> * <p> * <b style="color:RED"></b><br/><br/> * 你快乐吗?<br/> * 风轻轻的问我<br/> * 曾经快乐过<br/> * 那时的湖面<br/> * 她踏着轻舟泛过<br/><br/> * <p> * 你忧伤吗?<br/> * 雨悄悄的问我<br/> * 一直忧伤着<br/> * 此时的四季<br/> * 全是她的柳絮飘落<br/><br/> * <p> * 你心痛吗?<br/> * 泪偷偷的问我<br/> * 心痛如刀割<br/> * 收到记忆的包裹<br/> * 都是她冰清玉洁还不曾雕琢<br/><br/> * <p> * <hr style="color:RED"/> */ @Service public class TerminalService { private static Logger logger = LoggerFactory.getLogger(TerminalService.class); @Autowired private TerminalDao terminalDao; public boolean exists(String userName, String host) throws Exception { Map<String, Object> map = new HashMap<String, Object>(0); map.put("user_name", userName); map.put("host", host); int count = terminalDao.getCount(map); return count > 0; } public boolean merge(Terminal terminal) throws Exception { try { TerminalBean terminalBean = TerminalBean.transfer.apply(terminal); if (terminalBean.getId() == null) { terminalDao.save(terminalBean); terminal.setId(terminalBean.getId()); } else { terminalDao.update(terminalBean); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } public Terminal.AuthStatus auth(Terminal terminal) { JSch jSch = new JSch(); Session session = null; try { session = jSch.getSession(terminal.getUserName(), terminal.getHost(), terminal.getPort()); Constants.SshType sshType = Constants.SshType.getByType(terminal.getSshType()); switch (sshType) { case SSHKEY: //需要读取用户上传的sshKey if (terminal.getSshKeyFile() != null) { //将keyfile读取到数据库 terminal.setPrivateKey(terminal.getSshKeyFile().getBytes()); } if (notEmpty(terminal.getPrivateKey())) { File keyFile = new File(terminal.getPrivateKeyPath()); if (keyFile.exists()) { keyFile.delete(); } //将数据库中的私钥写到用户的机器上 IOUtils.writeFile(keyFile, new ByteArrayInputStream(terminal.getPrivateKey())); if (notEmpty(terminal.getPhrase())) { //设置带口令的密钥 jSch.addIdentity(terminal.getPrivateKeyPath(), terminal.getPhrase()); } else { //设置不带口令的密钥 jSch.addIdentity(terminal.getPrivateKeyPath()); } UserInfo userInfo = new SshUserInfo(); session.setUserInfo(userInfo); } break; case ACCOUNT: session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password"); session.setPassword(terminal.getPassword()); break; } session.setConfig("StrictHostKeyChecking", "no"); session.connect(TerminalClient.SESSION_TIMEOUT); return Terminal.AuthStatus.SUCCESS; } catch (Exception e) { if (e.getMessage().toLowerCase().contains("userauth fail")) { return Terminal.AuthStatus.PUBLIC_KEY_FAIL; } else if (e.getMessage().toLowerCase().contains("auth fail") || e.getMessage().toLowerCase().contains("auth cancel")) { return Terminal.AuthStatus.AUTH_FAIL; } else if (e.getMessage().toLowerCase().contains("unknownhostexception")) { if (logger.isInfoEnabled()) { logger.info("[JobX]:error: DNS Lookup Failed "); } return Terminal.AuthStatus.HOST_FAIL; } else if (e instanceof BadPaddingException) {//RSA解码错误..密码错误... return Terminal.AuthStatus.AUTH_FAIL; } else { return Terminal.AuthStatus.GENERIC_FAIL; } } finally { if (session != null) { session.disconnect(); } } } public void getPageBean(PageBean pageBean, Long userId) { pageBean.verifyOrderBy("name", "name", "host", "port", "ssh_type", "login_time"); pageBean.put("user_id", userId); List<TerminalBean> beanList = terminalDao.getByPageBean(pageBean); if (CommonUtils.notEmpty(beanList)) { int count = terminalDao.getCount(pageBean.getFilter()); pageBean.setResult(beanList); pageBean.setTotalCount(count); } } public Terminal getById(Long id) { TerminalBean terminalBean = terminalDao.getById(id); return Terminal.transfer.apply(terminalBean); } public String delete(HttpSession session, Long id) { Terminal term = getById(id); if (term == null) { return "error"; } User user = JobXTools.getUser(session); if (!JobXTools.isPermission(session) && !user.getUserId().equals(term.getUserId())) { return "error"; } terminalDao.delete(id); return "true"; } public void login(Long id) { Date date = new Date(); terminalDao.updateLoginTime(id,date); } public List<Terminal> getByUser(Long userId) { List<TerminalBean> list = terminalDao.getByUser(userId); return Lists.transform(list, Terminal.transfer); } public void theme(Terminal terminal, String theme) throws Exception { if (terminal != null) { terminalDao.updateTheme(terminal.getId(), theme); } } }
datavane/jobx
jobx-server/src/main/java/com/jobxhub/server/service/TerminalService.java
2,007
//设置带口令的密钥
line_comment
zh-cn
/** * Copyright (c) 2015 The JobX Project * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.jobxhub.server.service; import com.google.common.collect.Lists; import com.jcraft.jsch.*; import com.jobxhub.common.Constants; import com.jobxhub.common.util.CommonUtils; import com.jobxhub.common.util.IOUtils; import com.jobxhub.server.domain.TerminalBean; import com.jobxhub.server.dao.TerminalDao; import com.jobxhub.server.support.JobXTools; import com.jobxhub.server.support.SshUserInfo; import com.jobxhub.server.support.TerminalClient; import com.jobxhub.server.tag.PageBean; import com.jobxhub.server.dto.Terminal; import com.jobxhub.server.dto.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import javax.crypto.BadPaddingException; import javax.servlet.http.HttpSession; import java.io.*; import java.util.*; import static com.jobxhub.common.util.CommonUtils.notEmpty; /** * @author <a href="mailto:benjobs@qq.com">benjobs@qq.com</a> * @name:CommonUtil * @version: 1.0.0 * @company: com.jobxhub * @description: webconsole核心类 * @date: 2016-05-25 10:03<br/><br/> * <p> * <b style="color:RED"></b><br/><br/> * 你快乐吗?<br/> * 风轻轻的问我<br/> * 曾经快乐过<br/> * 那时的湖面<br/> * 她踏着轻舟泛过<br/><br/> * <p> * 你忧伤吗?<br/> * 雨悄悄的问我<br/> * 一直忧伤着<br/> * 此时的四季<br/> * 全是她的柳絮飘落<br/><br/> * <p> * 你心痛吗?<br/> * 泪偷偷的问我<br/> * 心痛如刀割<br/> * 收到记忆的包裹<br/> * 都是她冰清玉洁还不曾雕琢<br/><br/> * <p> * <hr style="color:RED"/> */ @Service public class TerminalService { private static Logger logger = LoggerFactory.getLogger(TerminalService.class); @Autowired private TerminalDao terminalDao; public boolean exists(String userName, String host) throws Exception { Map<String, Object> map = new HashMap<String, Object>(0); map.put("user_name", userName); map.put("host", host); int count = terminalDao.getCount(map); return count > 0; } public boolean merge(Terminal terminal) throws Exception { try { TerminalBean terminalBean = TerminalBean.transfer.apply(terminal); if (terminalBean.getId() == null) { terminalDao.save(terminalBean); terminal.setId(terminalBean.getId()); } else { terminalDao.update(terminalBean); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } public Terminal.AuthStatus auth(Terminal terminal) { JSch jSch = new JSch(); Session session = null; try { session = jSch.getSession(terminal.getUserName(), terminal.getHost(), terminal.getPort()); Constants.SshType sshType = Constants.SshType.getByType(terminal.getSshType()); switch (sshType) { case SSHKEY: //需要读取用户上传的sshKey if (terminal.getSshKeyFile() != null) { //将keyfile读取到数据库 terminal.setPrivateKey(terminal.getSshKeyFile().getBytes()); } if (notEmpty(terminal.getPrivateKey())) { File keyFile = new File(terminal.getPrivateKeyPath()); if (keyFile.exists()) { keyFile.delete(); } //将数据库中的私钥写到用户的机器上 IOUtils.writeFile(keyFile, new ByteArrayInputStream(terminal.getPrivateKey())); if (notEmpty(terminal.getPhrase())) { //设置 <SUF> jSch.addIdentity(terminal.getPrivateKeyPath(), terminal.getPhrase()); } else { //设置不带口令的密钥 jSch.addIdentity(terminal.getPrivateKeyPath()); } UserInfo userInfo = new SshUserInfo(); session.setUserInfo(userInfo); } break; case ACCOUNT: session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password"); session.setPassword(terminal.getPassword()); break; } session.setConfig("StrictHostKeyChecking", "no"); session.connect(TerminalClient.SESSION_TIMEOUT); return Terminal.AuthStatus.SUCCESS; } catch (Exception e) { if (e.getMessage().toLowerCase().contains("userauth fail")) { return Terminal.AuthStatus.PUBLIC_KEY_FAIL; } else if (e.getMessage().toLowerCase().contains("auth fail") || e.getMessage().toLowerCase().contains("auth cancel")) { return Terminal.AuthStatus.AUTH_FAIL; } else if (e.getMessage().toLowerCase().contains("unknownhostexception")) { if (logger.isInfoEnabled()) { logger.info("[JobX]:error: DNS Lookup Failed "); } return Terminal.AuthStatus.HOST_FAIL; } else if (e instanceof BadPaddingException) {//RSA解码错误..密码错误... return Terminal.AuthStatus.AUTH_FAIL; } else { return Terminal.AuthStatus.GENERIC_FAIL; } } finally { if (session != null) { session.disconnect(); } } } public void getPageBean(PageBean pageBean, Long userId) { pageBean.verifyOrderBy("name", "name", "host", "port", "ssh_type", "login_time"); pageBean.put("user_id", userId); List<TerminalBean> beanList = terminalDao.getByPageBean(pageBean); if (CommonUtils.notEmpty(beanList)) { int count = terminalDao.getCount(pageBean.getFilter()); pageBean.setResult(beanList); pageBean.setTotalCount(count); } } public Terminal getById(Long id) { TerminalBean terminalBean = terminalDao.getById(id); return Terminal.transfer.apply(terminalBean); } public String delete(HttpSession session, Long id) { Terminal term = getById(id); if (term == null) { return "error"; } User user = JobXTools.getUser(session); if (!JobXTools.isPermission(session) && !user.getUserId().equals(term.getUserId())) { return "error"; } terminalDao.delete(id); return "true"; } public void login(Long id) { Date date = new Date(); terminalDao.updateLoginTime(id,date); } public List<Terminal> getByUser(Long userId) { List<TerminalBean> list = terminalDao.getByUser(userId); return Lists.transform(list, Terminal.transfer); } public void theme(Terminal terminal, String theme) throws Exception { if (terminal != null) { terminalDao.updateTheme(terminal.getId(), theme); } } }
false
1,707
8
2,006
8
2,058
7
2,007
8
2,486
13
false
false
false
false
false
true
10347_6
package com.qlangtech.tis.sql.parser; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.qlangtech.tis.datax.DataXJobSubmit; import com.qlangtech.tis.datax.IDataXBatchPost; import com.qlangtech.tis.datax.IDataxProcessor; import com.qlangtech.tis.datax.IDataxReader; import com.qlangtech.tis.datax.IDataxWriter; import com.qlangtech.tis.datax.impl.DataXCfgGenerator; import com.qlangtech.tis.exec.IExecChainContext; import com.qlangtech.tis.fullbuild.indexbuild.IRemoteTaskPostTrigger; import com.qlangtech.tis.fullbuild.indexbuild.IRemoteTaskPreviousTrigger; import com.qlangtech.tis.fullbuild.indexbuild.IRemoteTaskTrigger; import com.qlangtech.tis.fullbuild.indexbuild.RemoteTaskTriggers; import com.qlangtech.tis.fullbuild.taskflow.TaskAndMilestone; import com.qlangtech.tis.plugin.ds.ISelectedTab; import com.qlangtech.tis.powerjob.IDAGSessionSpec; import com.qlangtech.tis.powerjob.SelectedTabTriggers; import com.tis.hadoop.rpc.RpcServiceReference; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; /** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author: 百岁(baisui@qlangtech.com) * @create: 2023-02-14 10:08 **/ public class DAGSessionSpec implements IDAGSessionSpec { Map<String, DAGSessionSpec> dptNodes = Maps.newHashMap(); private static final String KEY_ROOT = "root"; private final String id; List<DAGSessionSpec> attains = Lists.newArrayList(); boolean milestone = false; private final Map<String /** taskid*/, TaskAndMilestone> taskMap; public Set<String> getDptNodeNames() { return this.dptNodes.keySet(); } /** * 触发一个逻辑表相关子任务 * * @param execChainContext * @param appSource * @param submit * @param statusRpc * @param entry * @return */ public static SelectedTabTriggers buildTaskTriggers(IExecChainContext execChainContext, IDataxProcessor appSource , DataXJobSubmit submit , RpcServiceReference statusRpc // , ISelectedTab entry, String dumpTaskId, IDAGSessionSpec dagSessionSpec) { SelectedTabTriggers tabTriggers = new SelectedTabTriggers(entry, appSource); RemoteTaskTriggers triggers = Objects.requireNonNull(execChainContext.getTskTriggers(), "triggers can not be null"); if (org.apache.commons.lang3.StringUtils.isEmpty(dumpTaskId)) { throw new IllegalArgumentException("param dumpTaskId can not be null"); } // RemoteTaskTriggers triggers = new RemoteTaskTriggers(); IRemoteTaskTrigger jobTrigger = null; IDataxWriter writer = appSource.getWriter(null, true); DataXCfgGenerator.GenerateCfgs cfgFileNames = appSource.getDataxCfgFileNames(null); if (CollectionUtils.isEmpty(cfgFileNames.getDataXCfgFiles())) { throw new IllegalStateException("dataX cfgFileNames can not be empty"); } IDAGSessionSpec postSpec = null; IDAGSessionSpec dumpSpec = dagSessionSpec.getDpt(dumpTaskId).setMilestone(); IRemoteTaskPreviousTrigger preExec = null; if (writer instanceof IDataXBatchPost) { IDataXBatchPost batchPostTask = (IDataXBatchPost) writer; IRemoteTaskPostTrigger postTaskTrigger = batchPostTask.createPostTask(execChainContext, entry, cfgFileNames); if (postTaskTrigger != null) { postSpec = dumpSpec.getDpt(postTaskTrigger.getTaskName()); triggers.addJoinPhaseTask(postTaskTrigger); tabTriggers.setPostTrigger(postTaskTrigger); } // Objects.requireNonNull(postTaskTrigger, "postTaskTrigger can not be null"); preExec = batchPostTask.createPreExecuteTask(execChainContext, entry); if (preExec != null) { dagSessionSpec.getDpt(preExec.getTaskName()); triggers.addDumpPhaseTask(preExec); tabTriggers.setPreTrigger(preExec); } } List<DataXCfgGenerator.DBDataXChildTask> dataXCfgsOfTab = cfgFileNames.getDataXTaskDependencies(entry.getName()); final DataXJobSubmit.IDataXJobContext dataXJobContext = submit.createJobContext(execChainContext); Objects.requireNonNull(dataXJobContext, "dataXJobContext can not be null"); List<IRemoteTaskTrigger> splitTabTriggers = Lists.newArrayList(); for (DataXCfgGenerator.DBDataXChildTask fileName : dataXCfgsOfTab) { jobTrigger = createDataXJob(dataXJobContext, submit , statusRpc, appSource , new DataXJobSubmit.TableDataXEntity(fileName, entry)); IDAGSessionSpec childDumpSpec = getDumpSpec(postSpec, dumpSpec) .getDpt(Objects.requireNonNull(jobTrigger, "jobTrigger can not be null").getTaskName()); if (preExec != null) { childDumpSpec.getDpt(preExec.getTaskName()); } triggers.addDumpPhaseTask(jobTrigger); splitTabTriggers.add(jobTrigger); } tabTriggers.setSplitTabTriggers(splitTabTriggers); return tabTriggers; } public static Pair<DAGSessionSpec, List<ISelectedTab>> createDAGSessionSpec(IExecChainContext execChainContext , RpcServiceReference statusRpc, IDataxProcessor appSource, DataXJobSubmit submit) { IDataxReader reader = appSource.getReader(null); DAGSessionSpec sessionSpec = new DAGSessionSpec(); List<ISelectedTab> selectedTabs = reader.getSelectedTabs(); for (ISelectedTab entry : selectedTabs) { buildTaskTriggers(execChainContext, appSource, submit, statusRpc, entry, entry.getName(), sessionSpec); } return Pair.of(sessionSpec, selectedTabs); } protected static IRemoteTaskTrigger createDataXJob( DataXJobSubmit.IDataXJobContext execChainContext , DataXJobSubmit submit , RpcServiceReference statusRpc , IDataxProcessor appSource, DataXJobSubmit.TableDataXEntity fileName ) { if (submit.getType() == DataXJobSubmit.InstanceType.DISTRIBUTE) { // TODO: 先注释掉 ,看起来没有这段代码 也能正常执行的 2023/11/09 // IncrStatusUmbilicalProtocolImpl statCollect = IncrStatusUmbilicalProtocolImpl.getInstance(); // // 将指标纬度统计向注册到内存中,下一步可提供给DataX终止功能使用 // statCollect.getAppSubExecNodeMetrixStatus(execChainContext.getTaskContext().getIndexName(), fileName.getFileName()); } return submit.createDataXJob( execChainContext, statusRpc, appSource, fileName); } private static IDAGSessionSpec getDumpSpec(IDAGSessionSpec postSpec, IDAGSessionSpec dumpSpec) { if (postSpec != null) { return postSpec; } if (dumpSpec != null) { return dumpSpec; } throw new IllegalStateException("neither postSpec nor dumpSpec can be null"); } public Map<String, TaskAndMilestone> getTaskMap() { return taskMap; } public IDAGSessionSpec setMilestone() { this.milestone = true; this.taskMap.put(this.id, TaskAndMilestone.createMilestone(this.id)); return this; } public DAGSessionSpec(String id, Map<String, TaskAndMilestone> taskMap) { this.id = id; this.taskMap = taskMap; } public DAGSessionSpec() { this(KEY_ROOT, Maps.newHashMap()); } public StringBuffer buildSpec() { return buildSpec(Sets.newHashSet(), (dpt) -> { }); } public StringBuffer buildSpec(Consumer<Pair<String, String>> dptConsumer) { return buildSpec(Sets.newHashSet(), dptConsumer); } private StringBuffer buildSpec(Set<String> collected, Consumer<Pair<String, String>> dependency) { StringBuffer specs = new StringBuffer(); for (DAGSessionSpec spec : dptNodes.values()) { specs.append(spec.buildSpec(collected, dependency)).append(" "); } if (StringUtils.equals(this.id, KEY_ROOT)) { return specs; } if (!this.milestone && collected.add(this.id)) { specs.append(dptNodes.values().stream().map((n) -> { dependency.accept(Pair.of(n.id, DAGSessionSpec.this.id)); return n.id; }).collect(Collectors.joining(","))).append("->").append(this.id); if (CollectionUtils.isNotEmpty(this.attains)) { specs.append("->").append(this.attains.stream().map((a) -> { dependency.accept(Pair.of(DAGSessionSpec.this.id, a.id)); return a.id; }).collect(Collectors.joining(","))); } } return specs; } public IDAGSessionSpec getDpt(String id) { DAGSessionSpec spec = null; if ((spec = dptNodes.get(id)) == null) { spec = this.addDpt(id); if (this.milestone) { spec.attains.add(this); } return spec; } else { return spec; } } private DAGSessionSpec addDpt(String id) { DAGSessionSpec spec = new DAGSessionSpec(id, this.taskMap); this.dptNodes.put(id, spec); return spec; } public DAGSessionSpec addDpt(DAGSessionSpec spec) { dptNodes.put(spec.id, spec); return this; } public void put(String taskName, TaskAndMilestone taskAndMilestone) { this.taskMap.put(taskName, taskAndMilestone); } }
datavane/tis
tis-sql-parser/src/main/java/com/qlangtech/tis/sql/parser/DAGSessionSpec.java
2,689
// TODO: 先注释掉 ,看起来没有这段代码 也能正常执行的 2023/11/09
line_comment
zh-cn
package com.qlangtech.tis.sql.parser; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.qlangtech.tis.datax.DataXJobSubmit; import com.qlangtech.tis.datax.IDataXBatchPost; import com.qlangtech.tis.datax.IDataxProcessor; import com.qlangtech.tis.datax.IDataxReader; import com.qlangtech.tis.datax.IDataxWriter; import com.qlangtech.tis.datax.impl.DataXCfgGenerator; import com.qlangtech.tis.exec.IExecChainContext; import com.qlangtech.tis.fullbuild.indexbuild.IRemoteTaskPostTrigger; import com.qlangtech.tis.fullbuild.indexbuild.IRemoteTaskPreviousTrigger; import com.qlangtech.tis.fullbuild.indexbuild.IRemoteTaskTrigger; import com.qlangtech.tis.fullbuild.indexbuild.RemoteTaskTriggers; import com.qlangtech.tis.fullbuild.taskflow.TaskAndMilestone; import com.qlangtech.tis.plugin.ds.ISelectedTab; import com.qlangtech.tis.powerjob.IDAGSessionSpec; import com.qlangtech.tis.powerjob.SelectedTabTriggers; import com.tis.hadoop.rpc.RpcServiceReference; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.tuple.Pair; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Consumer; import java.util.stream.Collectors; /** * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @author: 百岁(baisui@qlangtech.com) * @create: 2023-02-14 10:08 **/ public class DAGSessionSpec implements IDAGSessionSpec { Map<String, DAGSessionSpec> dptNodes = Maps.newHashMap(); private static final String KEY_ROOT = "root"; private final String id; List<DAGSessionSpec> attains = Lists.newArrayList(); boolean milestone = false; private final Map<String /** taskid*/, TaskAndMilestone> taskMap; public Set<String> getDptNodeNames() { return this.dptNodes.keySet(); } /** * 触发一个逻辑表相关子任务 * * @param execChainContext * @param appSource * @param submit * @param statusRpc * @param entry * @return */ public static SelectedTabTriggers buildTaskTriggers(IExecChainContext execChainContext, IDataxProcessor appSource , DataXJobSubmit submit , RpcServiceReference statusRpc // , ISelectedTab entry, String dumpTaskId, IDAGSessionSpec dagSessionSpec) { SelectedTabTriggers tabTriggers = new SelectedTabTriggers(entry, appSource); RemoteTaskTriggers triggers = Objects.requireNonNull(execChainContext.getTskTriggers(), "triggers can not be null"); if (org.apache.commons.lang3.StringUtils.isEmpty(dumpTaskId)) { throw new IllegalArgumentException("param dumpTaskId can not be null"); } // RemoteTaskTriggers triggers = new RemoteTaskTriggers(); IRemoteTaskTrigger jobTrigger = null; IDataxWriter writer = appSource.getWriter(null, true); DataXCfgGenerator.GenerateCfgs cfgFileNames = appSource.getDataxCfgFileNames(null); if (CollectionUtils.isEmpty(cfgFileNames.getDataXCfgFiles())) { throw new IllegalStateException("dataX cfgFileNames can not be empty"); } IDAGSessionSpec postSpec = null; IDAGSessionSpec dumpSpec = dagSessionSpec.getDpt(dumpTaskId).setMilestone(); IRemoteTaskPreviousTrigger preExec = null; if (writer instanceof IDataXBatchPost) { IDataXBatchPost batchPostTask = (IDataXBatchPost) writer; IRemoteTaskPostTrigger postTaskTrigger = batchPostTask.createPostTask(execChainContext, entry, cfgFileNames); if (postTaskTrigger != null) { postSpec = dumpSpec.getDpt(postTaskTrigger.getTaskName()); triggers.addJoinPhaseTask(postTaskTrigger); tabTriggers.setPostTrigger(postTaskTrigger); } // Objects.requireNonNull(postTaskTrigger, "postTaskTrigger can not be null"); preExec = batchPostTask.createPreExecuteTask(execChainContext, entry); if (preExec != null) { dagSessionSpec.getDpt(preExec.getTaskName()); triggers.addDumpPhaseTask(preExec); tabTriggers.setPreTrigger(preExec); } } List<DataXCfgGenerator.DBDataXChildTask> dataXCfgsOfTab = cfgFileNames.getDataXTaskDependencies(entry.getName()); final DataXJobSubmit.IDataXJobContext dataXJobContext = submit.createJobContext(execChainContext); Objects.requireNonNull(dataXJobContext, "dataXJobContext can not be null"); List<IRemoteTaskTrigger> splitTabTriggers = Lists.newArrayList(); for (DataXCfgGenerator.DBDataXChildTask fileName : dataXCfgsOfTab) { jobTrigger = createDataXJob(dataXJobContext, submit , statusRpc, appSource , new DataXJobSubmit.TableDataXEntity(fileName, entry)); IDAGSessionSpec childDumpSpec = getDumpSpec(postSpec, dumpSpec) .getDpt(Objects.requireNonNull(jobTrigger, "jobTrigger can not be null").getTaskName()); if (preExec != null) { childDumpSpec.getDpt(preExec.getTaskName()); } triggers.addDumpPhaseTask(jobTrigger); splitTabTriggers.add(jobTrigger); } tabTriggers.setSplitTabTriggers(splitTabTriggers); return tabTriggers; } public static Pair<DAGSessionSpec, List<ISelectedTab>> createDAGSessionSpec(IExecChainContext execChainContext , RpcServiceReference statusRpc, IDataxProcessor appSource, DataXJobSubmit submit) { IDataxReader reader = appSource.getReader(null); DAGSessionSpec sessionSpec = new DAGSessionSpec(); List<ISelectedTab> selectedTabs = reader.getSelectedTabs(); for (ISelectedTab entry : selectedTabs) { buildTaskTriggers(execChainContext, appSource, submit, statusRpc, entry, entry.getName(), sessionSpec); } return Pair.of(sessionSpec, selectedTabs); } protected static IRemoteTaskTrigger createDataXJob( DataXJobSubmit.IDataXJobContext execChainContext , DataXJobSubmit submit , RpcServiceReference statusRpc , IDataxProcessor appSource, DataXJobSubmit.TableDataXEntity fileName ) { if (submit.getType() == DataXJobSubmit.InstanceType.DISTRIBUTE) { // TO <SUF> // IncrStatusUmbilicalProtocolImpl statCollect = IncrStatusUmbilicalProtocolImpl.getInstance(); // // 将指标纬度统计向注册到内存中,下一步可提供给DataX终止功能使用 // statCollect.getAppSubExecNodeMetrixStatus(execChainContext.getTaskContext().getIndexName(), fileName.getFileName()); } return submit.createDataXJob( execChainContext, statusRpc, appSource, fileName); } private static IDAGSessionSpec getDumpSpec(IDAGSessionSpec postSpec, IDAGSessionSpec dumpSpec) { if (postSpec != null) { return postSpec; } if (dumpSpec != null) { return dumpSpec; } throw new IllegalStateException("neither postSpec nor dumpSpec can be null"); } public Map<String, TaskAndMilestone> getTaskMap() { return taskMap; } public IDAGSessionSpec setMilestone() { this.milestone = true; this.taskMap.put(this.id, TaskAndMilestone.createMilestone(this.id)); return this; } public DAGSessionSpec(String id, Map<String, TaskAndMilestone> taskMap) { this.id = id; this.taskMap = taskMap; } public DAGSessionSpec() { this(KEY_ROOT, Maps.newHashMap()); } public StringBuffer buildSpec() { return buildSpec(Sets.newHashSet(), (dpt) -> { }); } public StringBuffer buildSpec(Consumer<Pair<String, String>> dptConsumer) { return buildSpec(Sets.newHashSet(), dptConsumer); } private StringBuffer buildSpec(Set<String> collected, Consumer<Pair<String, String>> dependency) { StringBuffer specs = new StringBuffer(); for (DAGSessionSpec spec : dptNodes.values()) { specs.append(spec.buildSpec(collected, dependency)).append(" "); } if (StringUtils.equals(this.id, KEY_ROOT)) { return specs; } if (!this.milestone && collected.add(this.id)) { specs.append(dptNodes.values().stream().map((n) -> { dependency.accept(Pair.of(n.id, DAGSessionSpec.this.id)); return n.id; }).collect(Collectors.joining(","))).append("->").append(this.id); if (CollectionUtils.isNotEmpty(this.attains)) { specs.append("->").append(this.attains.stream().map((a) -> { dependency.accept(Pair.of(DAGSessionSpec.this.id, a.id)); return a.id; }).collect(Collectors.joining(","))); } } return specs; } public IDAGSessionSpec getDpt(String id) { DAGSessionSpec spec = null; if ((spec = dptNodes.get(id)) == null) { spec = this.addDpt(id); if (this.milestone) { spec.attains.add(this); } return spec; } else { return spec; } } private DAGSessionSpec addDpt(String id) { DAGSessionSpec spec = new DAGSessionSpec(id, this.taskMap); this.dptNodes.put(id, spec); return spec; } public DAGSessionSpec addDpt(DAGSessionSpec spec) { dptNodes.put(spec.id, spec); return this; } public void put(String taskName, TaskAndMilestone taskAndMilestone) { this.taskMap.put(taskName, taskAndMilestone); } }
false
2,420
29
2,689
31
2,823
27
2,689
31
3,169
44
false
false
false
false
false
true
45164_20
// Generated by github.com/davyxu/tabtoy // DO NOT EDIT!! // Version: package main; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Table { public enum ActorType { None(0), // Pharah(1), // 法鸡 Junkrat(2), // 狂鼠 Genji(3), // 源氏 Mercy(4), // 天使 ; ActorType(int v) { this.ActorType = v; } public int getActorType() { return ActorType; } private final int ActorType; public static ActorType fromInt( int v ){ switch (v){ case 0: return None; case 1: return Pharah; case 2: return Junkrat; case 3: return Genji; case 4: return Mercy; default: return null; } } } public class ExampleData { public int ID = 0; // 任务ID; public int ID2 = 0; // 任务ID2; public String Name = ""; // 名称; public float Rate = 0; // 比例; public double Accuracy = 0; // 精度; public ActorType Type = ActorType.None; // 类型; public int[] Skill = new int[]{}; // 技能列表; public int Buff = 0; // 增益; public String[] TagList = new String[]{}; // 标记; public int[] Multi = new int[]{}; // 多列; } public class ExtendData { public float Additive = 0; // 附加; public int Index2 = 0; // 索引2; } public class ExampleKV { public String ServerIP = ""; // 服务器IP; public int ServerPort = 0; // 服务器端口; public int[] GroupID = new int[]{}; // 分组; } public List<ExampleData> ExampleData = new ArrayList<>(); // table: ExampleData public List<ExtendData> ExtendData = new ArrayList<>(); // table: ExtendData public List<ExampleKV> ExampleKV = new ArrayList<>(); // table: ExampleKV // Indices public Map<Integer, ExampleData> ExampleDataByID = new HashMap<Integer, ExampleData>(); // table: ExampleData public Map<Integer, ExampleData> ExampleDataByID2 = new HashMap<Integer, ExampleData>(); // table: ExampleData public Map<Integer, ExtendData> ExtendDataByIndex2 = new HashMap<Integer, ExtendData>(); // table: ExtendData // table: ExampleKV public ExampleKV GetKeyValue_ExampleKV() { return ExampleKV.get(0); } public interface TableEvent{ void OnPreProcess( ); void OnPostProcess( ); } // Handlers private List<TableEvent> eventHandlers = new ArrayList<TableEvent>(); // 注册加载后回调 public void RegisterEventHandler(TableEvent ev ){ eventHandlers.add(ev); } // 清除索引和数据, 在处理前调用OnPostProcess, 可能抛出异常 public void ResetData() { for( TableEvent ev : eventHandlers){ ev.OnPreProcess(); } ExampleData.clear(); ExtendData.clear(); ExampleKV.clear(); ExampleDataByID.clear(); ExampleDataByID2.clear(); ExtendDataByIndex2.clear(); } // 构建索引, 需要捕获OnPostProcess可能抛出的异常 public void BuildData() { for( ExampleData v:ExampleData ) { ExampleDataByID.put(v.ID, v); } for( ExampleData v:ExampleData ) { ExampleDataByID2.put(v.ID2, v); } for( ExtendData v:ExtendData ) { ExtendDataByIndex2.put(v.Index2, v); } for( TableEvent ev : eventHandlers){ ev.OnPostProcess(); } } }
davyxu/tabtoy
v3/example/java/src/main/java/main/Table.java
1,053
// 服务器端口;
line_comment
zh-cn
// Generated by github.com/davyxu/tabtoy // DO NOT EDIT!! // Version: package main; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Table { public enum ActorType { None(0), // Pharah(1), // 法鸡 Junkrat(2), // 狂鼠 Genji(3), // 源氏 Mercy(4), // 天使 ; ActorType(int v) { this.ActorType = v; } public int getActorType() { return ActorType; } private final int ActorType; public static ActorType fromInt( int v ){ switch (v){ case 0: return None; case 1: return Pharah; case 2: return Junkrat; case 3: return Genji; case 4: return Mercy; default: return null; } } } public class ExampleData { public int ID = 0; // 任务ID; public int ID2 = 0; // 任务ID2; public String Name = ""; // 名称; public float Rate = 0; // 比例; public double Accuracy = 0; // 精度; public ActorType Type = ActorType.None; // 类型; public int[] Skill = new int[]{}; // 技能列表; public int Buff = 0; // 增益; public String[] TagList = new String[]{}; // 标记; public int[] Multi = new int[]{}; // 多列; } public class ExtendData { public float Additive = 0; // 附加; public int Index2 = 0; // 索引2; } public class ExampleKV { public String ServerIP = ""; // 服务器IP; public int ServerPort = 0; // 服务 <SUF> public int[] GroupID = new int[]{}; // 分组; } public List<ExampleData> ExampleData = new ArrayList<>(); // table: ExampleData public List<ExtendData> ExtendData = new ArrayList<>(); // table: ExtendData public List<ExampleKV> ExampleKV = new ArrayList<>(); // table: ExampleKV // Indices public Map<Integer, ExampleData> ExampleDataByID = new HashMap<Integer, ExampleData>(); // table: ExampleData public Map<Integer, ExampleData> ExampleDataByID2 = new HashMap<Integer, ExampleData>(); // table: ExampleData public Map<Integer, ExtendData> ExtendDataByIndex2 = new HashMap<Integer, ExtendData>(); // table: ExtendData // table: ExampleKV public ExampleKV GetKeyValue_ExampleKV() { return ExampleKV.get(0); } public interface TableEvent{ void OnPreProcess( ); void OnPostProcess( ); } // Handlers private List<TableEvent> eventHandlers = new ArrayList<TableEvent>(); // 注册加载后回调 public void RegisterEventHandler(TableEvent ev ){ eventHandlers.add(ev); } // 清除索引和数据, 在处理前调用OnPostProcess, 可能抛出异常 public void ResetData() { for( TableEvent ev : eventHandlers){ ev.OnPreProcess(); } ExampleData.clear(); ExtendData.clear(); ExampleKV.clear(); ExampleDataByID.clear(); ExampleDataByID2.clear(); ExtendDataByIndex2.clear(); } // 构建索引, 需要捕获OnPostProcess可能抛出的异常 public void BuildData() { for( ExampleData v:ExampleData ) { ExampleDataByID.put(v.ID, v); } for( ExampleData v:ExampleData ) { ExampleDataByID2.put(v.ID2, v); } for( ExtendData v:ExtendData ) { ExtendDataByIndex2.put(v.Index2, v); } for( TableEvent ev : eventHandlers){ ev.OnPostProcess(); } } }
false
967
7
1,053
6
1,096
7
1,053
6
1,347
12
false
false
false
false
false
true
10847_11
package com.vm.shadowsocks.tunnel; import android.annotation.SuppressLint; import com.vm.shadowsocks.core.LocalVpnService; import com.vm.shadowsocks.core.ProxyConfig; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; public abstract class Tunnel { final static ByteBuffer GL_BUFFER = ByteBuffer.allocate(20000); public static long SessionCount; protected abstract void onConnected(ByteBuffer buffer) throws Exception; protected abstract boolean isTunnelEstablished(); protected abstract void beforeSend(ByteBuffer buffer) throws Exception; protected abstract void afterReceived(ByteBuffer buffer) throws Exception; protected abstract void onDispose(); private SocketChannel m_InnerChannel; private ByteBuffer m_SendRemainBuffer; private Selector m_Selector; private Tunnel m_BrotherTunnel; private boolean m_Disposed; private InetSocketAddress m_ServerEP; protected InetSocketAddress m_DestAddress; public Tunnel(SocketChannel innerChannel, Selector selector) { this.m_InnerChannel = innerChannel; this.m_Selector = selector; SessionCount++; } public Tunnel(InetSocketAddress serverAddress, Selector selector) throws IOException { SocketChannel innerChannel = SocketChannel.open(); innerChannel.configureBlocking(false); this.m_InnerChannel = innerChannel; this.m_Selector = selector; this.m_ServerEP = serverAddress; SessionCount++; } public void setBrotherTunnel(Tunnel brotherTunnel) { m_BrotherTunnel = brotherTunnel; } public void connect(InetSocketAddress destAddress) throws Exception { if (LocalVpnService.Instance.protect(m_InnerChannel.socket())) {//保护socket不走vpn m_DestAddress = destAddress; m_InnerChannel.register(m_Selector, SelectionKey.OP_CONNECT, this);//注册连接事件 m_InnerChannel.connect(m_ServerEP);//连接目标 } else { throw new Exception("VPN protect socket failed."); } } protected void beginReceive() throws Exception { if (m_InnerChannel.isBlocking()) { m_InnerChannel.configureBlocking(false); } m_InnerChannel.register(m_Selector, SelectionKey.OP_READ, this);//注册读事件 } protected boolean write(ByteBuffer buffer, boolean copyRemainData) throws Exception { int bytesSent; while (buffer.hasRemaining()) { bytesSent = m_InnerChannel.write(buffer); if (bytesSent == 0) { break;//不能再发送了,终止循环 } } if (buffer.hasRemaining()) {//数据没有发送完毕 if (copyRemainData) {//拷贝剩余数据,然后侦听写入事件,待可写入时写入。 //拷贝剩余数据 if (m_SendRemainBuffer == null) { m_SendRemainBuffer = ByteBuffer.allocate(buffer.capacity()); } m_SendRemainBuffer.clear(); m_SendRemainBuffer.put(buffer); m_SendRemainBuffer.flip(); m_InnerChannel.register(m_Selector, SelectionKey.OP_WRITE, this);//注册写事件 } return false; } else {//发送完毕了 return true; } } protected void onTunnelEstablished() throws Exception { this.beginReceive();//开始接收数据 m_BrotherTunnel.beginReceive();//兄弟也开始收数据吧 } @SuppressLint("DefaultLocale") public void onConnectable() { try { if (m_InnerChannel.finishConnect()) {//连接成功 onConnected(GL_BUFFER);//通知子类TCP已连接,子类可以根据协议实现握手等。 } else {//连接失败 LocalVpnService.Instance.writeLog("Error: connect to %s failed.", m_ServerEP); this.dispose(); } } catch (Exception e) { LocalVpnService.Instance.writeLog("Error: connect to %s failed: %s", m_ServerEP, e); this.dispose(); } } public void onReadable(SelectionKey key) { try { ByteBuffer buffer = GL_BUFFER; buffer.clear(); int bytesRead = m_InnerChannel.read(buffer); if (bytesRead > 0) { buffer.flip(); afterReceived(buffer);//先让子类处理,例如解密数据。 if (isTunnelEstablished() && buffer.hasRemaining()) {//将读到的数据,转发给兄弟。 m_BrotherTunnel.beforeSend(buffer);//发送之前,先让子类处理,例如做加密等。 if (!m_BrotherTunnel.write(buffer, true)) { key.cancel();//兄弟吃不消,就取消读取事件。 if (ProxyConfig.IS_DEBUG) System.out.printf("%s can not read more.\n", m_ServerEP); } } } else if (bytesRead < 0) { this.dispose();//连接已关闭,释放资源。 } } catch (Exception e) { e.printStackTrace(); this.dispose(); } } public void onWritable(SelectionKey key) { try { this.beforeSend(m_SendRemainBuffer);//发送之前,先让子类处理,例如做加密等。 if (this.write(m_SendRemainBuffer, false)) {//如果剩余数据已经发送完毕 key.cancel();//取消写事件。 if (isTunnelEstablished()) { m_BrotherTunnel.beginReceive();//这边数据发送完毕,通知兄弟可以收数据了。 } else { this.beginReceive();//开始接收代理服务器响应数据 } } } catch (Exception e) { this.dispose(); } } public void dispose() { disposeInternal(true); } void disposeInternal(boolean disposeBrother) { if (m_Disposed) { return; } else { try { m_InnerChannel.close(); } catch (Exception e) { } if (m_BrotherTunnel != null && disposeBrother) { m_BrotherTunnel.disposeInternal(false);//把兄弟的资源也释放了。 } m_InnerChannel = null; m_SendRemainBuffer = null; m_Selector = null; m_BrotherTunnel = null; m_Disposed = true; SessionCount--; onDispose(); } } }
dawei101/shadowsocks-android-java
app/src/main/java/com/vm/shadowsocks/tunnel/Tunnel.java
1,514
//兄弟也开始收数据吧
line_comment
zh-cn
package com.vm.shadowsocks.tunnel; import android.annotation.SuppressLint; import com.vm.shadowsocks.core.LocalVpnService; import com.vm.shadowsocks.core.ProxyConfig; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; public abstract class Tunnel { final static ByteBuffer GL_BUFFER = ByteBuffer.allocate(20000); public static long SessionCount; protected abstract void onConnected(ByteBuffer buffer) throws Exception; protected abstract boolean isTunnelEstablished(); protected abstract void beforeSend(ByteBuffer buffer) throws Exception; protected abstract void afterReceived(ByteBuffer buffer) throws Exception; protected abstract void onDispose(); private SocketChannel m_InnerChannel; private ByteBuffer m_SendRemainBuffer; private Selector m_Selector; private Tunnel m_BrotherTunnel; private boolean m_Disposed; private InetSocketAddress m_ServerEP; protected InetSocketAddress m_DestAddress; public Tunnel(SocketChannel innerChannel, Selector selector) { this.m_InnerChannel = innerChannel; this.m_Selector = selector; SessionCount++; } public Tunnel(InetSocketAddress serverAddress, Selector selector) throws IOException { SocketChannel innerChannel = SocketChannel.open(); innerChannel.configureBlocking(false); this.m_InnerChannel = innerChannel; this.m_Selector = selector; this.m_ServerEP = serverAddress; SessionCount++; } public void setBrotherTunnel(Tunnel brotherTunnel) { m_BrotherTunnel = brotherTunnel; } public void connect(InetSocketAddress destAddress) throws Exception { if (LocalVpnService.Instance.protect(m_InnerChannel.socket())) {//保护socket不走vpn m_DestAddress = destAddress; m_InnerChannel.register(m_Selector, SelectionKey.OP_CONNECT, this);//注册连接事件 m_InnerChannel.connect(m_ServerEP);//连接目标 } else { throw new Exception("VPN protect socket failed."); } } protected void beginReceive() throws Exception { if (m_InnerChannel.isBlocking()) { m_InnerChannel.configureBlocking(false); } m_InnerChannel.register(m_Selector, SelectionKey.OP_READ, this);//注册读事件 } protected boolean write(ByteBuffer buffer, boolean copyRemainData) throws Exception { int bytesSent; while (buffer.hasRemaining()) { bytesSent = m_InnerChannel.write(buffer); if (bytesSent == 0) { break;//不能再发送了,终止循环 } } if (buffer.hasRemaining()) {//数据没有发送完毕 if (copyRemainData) {//拷贝剩余数据,然后侦听写入事件,待可写入时写入。 //拷贝剩余数据 if (m_SendRemainBuffer == null) { m_SendRemainBuffer = ByteBuffer.allocate(buffer.capacity()); } m_SendRemainBuffer.clear(); m_SendRemainBuffer.put(buffer); m_SendRemainBuffer.flip(); m_InnerChannel.register(m_Selector, SelectionKey.OP_WRITE, this);//注册写事件 } return false; } else {//发送完毕了 return true; } } protected void onTunnelEstablished() throws Exception { this.beginReceive();//开始接收数据 m_BrotherTunnel.beginReceive();//兄弟 <SUF> } @SuppressLint("DefaultLocale") public void onConnectable() { try { if (m_InnerChannel.finishConnect()) {//连接成功 onConnected(GL_BUFFER);//通知子类TCP已连接,子类可以根据协议实现握手等。 } else {//连接失败 LocalVpnService.Instance.writeLog("Error: connect to %s failed.", m_ServerEP); this.dispose(); } } catch (Exception e) { LocalVpnService.Instance.writeLog("Error: connect to %s failed: %s", m_ServerEP, e); this.dispose(); } } public void onReadable(SelectionKey key) { try { ByteBuffer buffer = GL_BUFFER; buffer.clear(); int bytesRead = m_InnerChannel.read(buffer); if (bytesRead > 0) { buffer.flip(); afterReceived(buffer);//先让子类处理,例如解密数据。 if (isTunnelEstablished() && buffer.hasRemaining()) {//将读到的数据,转发给兄弟。 m_BrotherTunnel.beforeSend(buffer);//发送之前,先让子类处理,例如做加密等。 if (!m_BrotherTunnel.write(buffer, true)) { key.cancel();//兄弟吃不消,就取消读取事件。 if (ProxyConfig.IS_DEBUG) System.out.printf("%s can not read more.\n", m_ServerEP); } } } else if (bytesRead < 0) { this.dispose();//连接已关闭,释放资源。 } } catch (Exception e) { e.printStackTrace(); this.dispose(); } } public void onWritable(SelectionKey key) { try { this.beforeSend(m_SendRemainBuffer);//发送之前,先让子类处理,例如做加密等。 if (this.write(m_SendRemainBuffer, false)) {//如果剩余数据已经发送完毕 key.cancel();//取消写事件。 if (isTunnelEstablished()) { m_BrotherTunnel.beginReceive();//这边数据发送完毕,通知兄弟可以收数据了。 } else { this.beginReceive();//开始接收代理服务器响应数据 } } } catch (Exception e) { this.dispose(); } } public void dispose() { disposeInternal(true); } void disposeInternal(boolean disposeBrother) { if (m_Disposed) { return; } else { try { m_InnerChannel.close(); } catch (Exception e) { } if (m_BrotherTunnel != null && disposeBrother) { m_BrotherTunnel.disposeInternal(false);//把兄弟的资源也释放了。 } m_InnerChannel = null; m_SendRemainBuffer = null; m_Selector = null; m_BrotherTunnel = null; m_Disposed = true; SessionCount--; onDispose(); } } }
false
1,375
6
1,514
10
1,595
7
1,514
10
2,002
16
false
false
false
false
false
true
13803_41
//package com.daxue.idservice.service; // //import lombok.extern.slf4j.Slf4j; //import org.junit.Test; //import org.springframework.stereotype.Service; // ///** // * @author daxue0929 // * @date 2021/05/23 // **/ //@Slf4j //@Service //public class GenerateIdService { // // //因为二进制第一个 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 // private long sequence; // // //设置一个时间初始值 2^41-1 差不多可以用69年 // private long twepoct = 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; // // private long sequenceMask = -1L ^ (-1L << sequenceBits); // // //记录产生时间毫秒数,判断是否是同一秒 // private long lastTimestamp = -1L; // // public long getWorkerId(){ // return workerId; // } // // public long getDatacenterId() { // return datacenterId; // } // // public long getTimestamp() { // return System.currentTimeMillis(); // } // // public GenerateIdService generateId(long workerId, long datacenterId, long sequence) throws IllegalAccessException { // //检查机房id和机器id是否大于31, 不能小于0 // if (workerId > maxWorkerId || workerId < 0) { // throw new IllegalAccessException(String.format("worker Id 不能超过%d,并且不能小于0", maxWorkerId)); // } // // //检查机房id // if (datacenterId > maxDatacenterId || datacenterId < 0) { // throw new IllegalAccessException(String.format("datacenterId 不能超过%d,并且不能小于0", maxDatacenterId)); // } // // this.workerId = workerId; // this.datacenterId = datacenterId; // this.sequence = sequence; // // return this; // } // // public synchronized long nextId() throws IllegalAccessException { // // 这就是获取的当前时间戳,单位毫秒 // long timestamp = timeGen(); // if (timestamp < lastTimestamp) { // System.err.printf("Clock is moving backwards, Rejecting requests until %d", lastTimestamp); // throw new IllegalAccessException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); // } // // //下面是说假设在同一毫秒内,又发送了一个请求生成一个id // //这个时候就把sequence序号给递增1, 最多就是4096 // // if (lastTimestamp == timestamp) { // // // 这个意思说说一个毫秒只能有4096个数字,无论你传递多少进来 // // 这个位运算保证始终在4096这个范围内,避免你自己传递个sequence超过了4096这个范围 // sequence = (sequence + 1) & sequenceMask; // // if (sequence == 0) { // timestamp = tilNextMillis(lastTimestamp); // } // }else { // sequence = 0; // } // // // 这里记录一下最近一次生成id的时间戳,单位事毫秒 // lastTimestamp = timestamp; // // //这儿就是最核心的二进制位运算操作,生成一个64bit的id // //先将当前时间戳左移,房贷41bit 那儿, 将机房id左移5bit那儿,将机器id放到5bit那儿,将序号放最后12bit // //最后拼接成一个64 bit的二进制数,转换成10进制就是个long型 // // return (timestamp - twepoct) << timestampLeftShift | // (datacenterId << datacenterIdShift) | // (workerId << workerIdShift) | sequence; // } // // private long tilNextMillis(long lastTimestamp) { // long timestamp = timeGen(); // while (timestamp <= lastTimestamp) { // timestamp = timeGen(); // } // return timestamp; // } // // private long timeGen(){ // return System.currentTimeMillis(); // } // // // ..todo 这两个关键方法还是有问题的,需要修改一下. // @Test // public void test() throws IllegalAccessException { // System.out.println(1 & 4596); // System.out.println(2 & 4596); // System.out.println(3 & 4596); // System.out.println(4 & 4596); // System.out.println(5 & 4596); // System.out.println(6 & 4596); // generateId(1, 1, 1); // for (int i = 0; i < 22; i++) { // long l = nextId(); // System.out.println(l); // } // // } // //}
daxue0929/Spring-Cloud-Microservice-Development
id-service/src/main/java/com/daxue/idservice/service/GenerateIdService.java
1,677
// //检查机房id和机器id是否大于31, 不能小于0
line_comment
zh-cn
//package com.daxue.idservice.service; // //import lombok.extern.slf4j.Slf4j; //import org.junit.Test; //import org.springframework.stereotype.Service; // ///** // * @author daxue0929 // * @date 2021/05/23 // **/ //@Slf4j //@Service //public class GenerateIdService { // // //因为二进制第一个 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 // private long sequence; // // //设置一个时间初始值 2^41-1 差不多可以用69年 // private long twepoct = 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; // // private long sequenceMask = -1L ^ (-1L << sequenceBits); // // //记录产生时间毫秒数,判断是否是同一秒 // private long lastTimestamp = -1L; // // public long getWorkerId(){ // return workerId; // } // // public long getDatacenterId() { // return datacenterId; // } // // public long getTimestamp() { // return System.currentTimeMillis(); // } // // public GenerateIdService generateId(long workerId, long datacenterId, long sequence) throws IllegalAccessException { // //检查 <SUF> // if (workerId > maxWorkerId || workerId < 0) { // throw new IllegalAccessException(String.format("worker Id 不能超过%d,并且不能小于0", maxWorkerId)); // } // // //检查机房id // if (datacenterId > maxDatacenterId || datacenterId < 0) { // throw new IllegalAccessException(String.format("datacenterId 不能超过%d,并且不能小于0", maxDatacenterId)); // } // // this.workerId = workerId; // this.datacenterId = datacenterId; // this.sequence = sequence; // // return this; // } // // public synchronized long nextId() throws IllegalAccessException { // // 这就是获取的当前时间戳,单位毫秒 // long timestamp = timeGen(); // if (timestamp < lastTimestamp) { // System.err.printf("Clock is moving backwards, Rejecting requests until %d", lastTimestamp); // throw new IllegalAccessException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp)); // } // // //下面是说假设在同一毫秒内,又发送了一个请求生成一个id // //这个时候就把sequence序号给递增1, 最多就是4096 // // if (lastTimestamp == timestamp) { // // // 这个意思说说一个毫秒只能有4096个数字,无论你传递多少进来 // // 这个位运算保证始终在4096这个范围内,避免你自己传递个sequence超过了4096这个范围 // sequence = (sequence + 1) & sequenceMask; // // if (sequence == 0) { // timestamp = tilNextMillis(lastTimestamp); // } // }else { // sequence = 0; // } // // // 这里记录一下最近一次生成id的时间戳,单位事毫秒 // lastTimestamp = timestamp; // // //这儿就是最核心的二进制位运算操作,生成一个64bit的id // //先将当前时间戳左移,房贷41bit 那儿, 将机房id左移5bit那儿,将机器id放到5bit那儿,将序号放最后12bit // //最后拼接成一个64 bit的二进制数,转换成10进制就是个long型 // // return (timestamp - twepoct) << timestampLeftShift | // (datacenterId << datacenterIdShift) | // (workerId << workerIdShift) | sequence; // } // // private long tilNextMillis(long lastTimestamp) { // long timestamp = timeGen(); // while (timestamp <= lastTimestamp) { // timestamp = timeGen(); // } // return timestamp; // } // // private long timeGen(){ // return System.currentTimeMillis(); // } // // // ..todo 这两个关键方法还是有问题的,需要修改一下. // @Test // public void test() throws IllegalAccessException { // System.out.println(1 & 4596); // System.out.println(2 & 4596); // System.out.println(3 & 4596); // System.out.println(4 & 4596); // System.out.println(5 & 4596); // System.out.println(6 & 4596); // generateId(1, 1, 1); // for (int i = 0; i < 22; i++) { // long l = nextId(); // System.out.println(l); // } // // } // //}
false
1,471
19
1,677
20
1,612
18
1,677
20
1,963
27
false
false
false
false
false
true
17152_2
package yang.yu.tdd.bank; //被测对象 public class Account { //内部状态:账户是否被冻结 private boolean locked = false; //内部状态:当前余额 private int balance = 0; //外部依赖(协作者):记录每一笔收支 private Transactions transactions; //用于注入外部协作者的方法 public void setTransactions(Transactions transactions) { this.transactions = transactions; } public boolean isLocked() { return locked; } public int getBalance() { return balance; } //存款工作单元 public void deposit(int amount) { //失败路径1:账户被冻结时不允许存款 if (locked) { throw new AccountLockedException(); } //失败路径2:存款金额不是正数时不允许存款 if (amount <= 0) { throw new InvalidAmountException(); } //成功(快乐)路径 balance += amount; //存款成功后改变内部状态 transactions.add(this, TransactionType.DEBIT, amount); //存款成功后调用外部协作者 } //取款工作单元 public void withdraw(int amount) { //失败路径1:账户被冻结时不允许取款 if (locked) { throw new AccountLockedException(); } //失败路径2:取款金额不是正数时不允许取款 if (amount <= 0) { throw new InvalidAmountException(); } //失败路径3:取款金额超过余额时不允许取款 if (amount > balance) { throw new BalanceInsufficientException(); } //成功(快乐)路径 balance -= amount; //取款成功后改变内部状态 transactions.add(this, TransactionType.CREDIT, amount); //取款成功后调用外部协作者 } //冻结工作单元 public void lock() { locked = true; } //解冻工作单元 public void unlock() { locked = false; } }
dayatang/tdd-and-toolset
src/main/java/yang/yu/tdd/bank/Account.java
464
//内部状态:当前余额
line_comment
zh-cn
package yang.yu.tdd.bank; //被测对象 public class Account { //内部状态:账户是否被冻结 private boolean locked = false; //内部 <SUF> private int balance = 0; //外部依赖(协作者):记录每一笔收支 private Transactions transactions; //用于注入外部协作者的方法 public void setTransactions(Transactions transactions) { this.transactions = transactions; } public boolean isLocked() { return locked; } public int getBalance() { return balance; } //存款工作单元 public void deposit(int amount) { //失败路径1:账户被冻结时不允许存款 if (locked) { throw new AccountLockedException(); } //失败路径2:存款金额不是正数时不允许存款 if (amount <= 0) { throw new InvalidAmountException(); } //成功(快乐)路径 balance += amount; //存款成功后改变内部状态 transactions.add(this, TransactionType.DEBIT, amount); //存款成功后调用外部协作者 } //取款工作单元 public void withdraw(int amount) { //失败路径1:账户被冻结时不允许取款 if (locked) { throw new AccountLockedException(); } //失败路径2:取款金额不是正数时不允许取款 if (amount <= 0) { throw new InvalidAmountException(); } //失败路径3:取款金额超过余额时不允许取款 if (amount > balance) { throw new BalanceInsufficientException(); } //成功(快乐)路径 balance -= amount; //取款成功后改变内部状态 transactions.add(this, TransactionType.CREDIT, amount); //取款成功后调用外部协作者 } //冻结工作单元 public void lock() { locked = true; } //解冻工作单元 public void unlock() { locked = false; } }
false
444
6
464
7
494
6
464
7
720
14
false
false
false
false
false
true
60802_16
/* * AP(r) Computer Science GridWorld Case Study: * Copyright(c) 2005-2006 Cay S. Horstmann (http://horstmann.com) * * This code is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Chris Nevison * @author Barbara Cloud Wells * @author Cay Horstmann */ import info.gridworld.actor.*; import info.gridworld.grid.Grid; import info.gridworld.grid.Location; import java.awt.Color; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * A <code>CrabCritter</code> looks at a limited set of neighbors when it eats and moves. * <br /> * This class is not tested on the AP CS A and AB exams. */ public class AdvancedCritter extends Critter { private static final int MAXAGE = 100; private static final int HEALTH = 5; private static final double RATE1 = 14.0/30.0; private static final double RATE2 = 1.0/30.0; private static final int MALE = 0; private static final int FEMALE = 1; private static final int GAY = 2; private static final int LES = 3; private int age = 0; /** * Generation indicates the generation of NewJumper */ private int generation; /** * gender: 0=male, 1=female; 2=male&gay, 3=female&les */ private int gender; /** * 性别对应不同的颜色 */ private final Color[] genderColor = {Color.BLACK, Color.WHITE, Color.BLUE, Color.RED}; public AdvancedCritter(int gender, int generation) { this.gender = gender; this.generation = generation; setColor(genderColor[gender]); } public void act() { if (getGrid() == null) { return; } age++; // 判断age是否超过最大,是则死亡 if (age > MAXAGE) { removeSelfFromGrid(); return; } if ((gender == 0 || gender == 1) && canBear()) { bear(); return; } super.act(); } public void processActors(ArrayList<Actor> actors) { for (Actor a : actors) { // 吃到花的延年益寿,少5岁 if (a instanceof Flower) { a.removeSelfFromGrid(); age = age - HEALTH; } } } // 移动的时候改变方向 public void makeMove(Location loc) { setDirection(getLocation().getDirectionToward(loc)); super.makeMove(loc); } // 判断是否可以生孩子 private boolean canBear() { Location loc = getLocation(); int direction = getDirection(); Grid<Actor> gr = getGrid(); // 判断下一个位置是否合法&是否为空 Location next = loc.getAdjacentLocation(direction); if (!gr.isValid(next) || gr.get(next) != null) { return false; } // 判断下下个位置是否合法&是否生物属于AdvancedCritter Location next2 = next.getAdjacentLocation(direction); if (!gr.isValid(next2) || !(gr.get(next2) instanceof AdvancedCritter)) { return false; } AdvancedCritter ac = (AdvancedCritter)gr.get(next2); // 判断体位是否正确 if (Math.abs(direction - ac.getDirection()) != 180) { return false; } return true; } private void bear() { Location loc = getLocation(); int direction = getDirection(); Grid<Actor> gr = getGrid(); Location next = loc.getAdjacentLocation(direction); // 随机出生性别 AdvancedCritter child = new AdvancedCritter(getRandomGender(), generation + 1); child.putSelfInGrid(gr, next); } // 获取随机性别 private int getRandomGender() { double randNum = Math.random(); if (randNum <= RATE1) { return MALE; } else if (randNum <= 2*RATE1) { return FEMALE; } else if (randNum <= 2*RATE1 + RATE2) { return GAY; } else { return LES; } } // 获取年龄 public int getAge() { return age; } // 获取代数 public int getGeneration() { return generation; } // 获取性别 public int getGender() { return gender; } // 获取当前全部AdvancedCritter数据 public String getdata() { SparseBoundedGrid1<Actor> gr = (SparseBoundedGrid1)getGrid(); //获取自定义网格的存储数据 Map<Location, Actor> map = new HashMap<Location, Actor>(); map = (LinkedHashMap<Location, Actor>)gr.getMap(); int maleCount = 0; int femaleCount = 0; int maleGayCount = 0; int femaleLesCount = 0; int allCount = 0; // generationCount用于计数每一代有多少数量的AdvancedCritter HashMap<Integer, Integer>generationCount = new HashMap<Integer, Integer>(); for (Location loc : map.keySet()) { if (gr.get(loc) instanceof AdvancedCritter) { allCount++; AdvancedCritter temp = (AdvancedCritter)gr.get(loc); if (temp.getGender() == 0) { maleCount++; } if (temp.getGender() == 1) { femaleCount++; } if (temp.getGender() == 2) { maleGayCount++; } if (temp.getGender() == 3) { femaleLesCount++; } if (generationCount.containsKey(temp.getGeneration())) { int originCount = generationCount.get(temp.getGeneration()); generationCount.put(temp.getGeneration(), originCount + 1); } else { generationCount.put(temp.getGeneration(), 1); } } } String result = ""; double hundred = 100.0; result += "总的New Jumper数量是 " + allCount + "\n"; result += "男性数量是 " + maleCount + ",占据总数量的"+Double.toString(maleCount*hundred/allCount) + "%\n"; result += "女性数量是 " + femaleCount + ",占据总数量的"+Double.toString(femaleCount*hundred/allCount) + "%\n"; result += "男同性恋数量是 " + maleGayCount + ",占据总数量的"+Double.toString(maleGayCount*hundred/allCount) + "%\n"; result += "女同性恋数量是 " + femaleLesCount + ",占据总数量的"+Double.toString(femaleLesCount*hundred/allCount) + "%\n"; for (Integer g : generationCount.keySet()) { int count = generationCount.get(g); String rate = Double.toString(count*hundred/allCount); result +="第"+g+"代的NewJumper有"+count+"只, 占据总数量的"+ rate + "%\n"; } return result; } }
dayinji/SYSU-GridWorld
stage2/critter/AdvancedCritter/src/AdvancedCritter.java
1,840
// 获取性别
line_comment
zh-cn
/* * AP(r) Computer Science GridWorld Case Study: * Copyright(c) 2005-2006 Cay S. Horstmann (http://horstmann.com) * * This code is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation. * * This code is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @author Chris Nevison * @author Barbara Cloud Wells * @author Cay Horstmann */ import info.gridworld.actor.*; import info.gridworld.grid.Grid; import info.gridworld.grid.Location; import java.awt.Color; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; /** * A <code>CrabCritter</code> looks at a limited set of neighbors when it eats and moves. * <br /> * This class is not tested on the AP CS A and AB exams. */ public class AdvancedCritter extends Critter { private static final int MAXAGE = 100; private static final int HEALTH = 5; private static final double RATE1 = 14.0/30.0; private static final double RATE2 = 1.0/30.0; private static final int MALE = 0; private static final int FEMALE = 1; private static final int GAY = 2; private static final int LES = 3; private int age = 0; /** * Generation indicates the generation of NewJumper */ private int generation; /** * gender: 0=male, 1=female; 2=male&gay, 3=female&les */ private int gender; /** * 性别对应不同的颜色 */ private final Color[] genderColor = {Color.BLACK, Color.WHITE, Color.BLUE, Color.RED}; public AdvancedCritter(int gender, int generation) { this.gender = gender; this.generation = generation; setColor(genderColor[gender]); } public void act() { if (getGrid() == null) { return; } age++; // 判断age是否超过最大,是则死亡 if (age > MAXAGE) { removeSelfFromGrid(); return; } if ((gender == 0 || gender == 1) && canBear()) { bear(); return; } super.act(); } public void processActors(ArrayList<Actor> actors) { for (Actor a : actors) { // 吃到花的延年益寿,少5岁 if (a instanceof Flower) { a.removeSelfFromGrid(); age = age - HEALTH; } } } // 移动的时候改变方向 public void makeMove(Location loc) { setDirection(getLocation().getDirectionToward(loc)); super.makeMove(loc); } // 判断是否可以生孩子 private boolean canBear() { Location loc = getLocation(); int direction = getDirection(); Grid<Actor> gr = getGrid(); // 判断下一个位置是否合法&是否为空 Location next = loc.getAdjacentLocation(direction); if (!gr.isValid(next) || gr.get(next) != null) { return false; } // 判断下下个位置是否合法&是否生物属于AdvancedCritter Location next2 = next.getAdjacentLocation(direction); if (!gr.isValid(next2) || !(gr.get(next2) instanceof AdvancedCritter)) { return false; } AdvancedCritter ac = (AdvancedCritter)gr.get(next2); // 判断体位是否正确 if (Math.abs(direction - ac.getDirection()) != 180) { return false; } return true; } private void bear() { Location loc = getLocation(); int direction = getDirection(); Grid<Actor> gr = getGrid(); Location next = loc.getAdjacentLocation(direction); // 随机出生性别 AdvancedCritter child = new AdvancedCritter(getRandomGender(), generation + 1); child.putSelfInGrid(gr, next); } // 获取随机性别 private int getRandomGender() { double randNum = Math.random(); if (randNum <= RATE1) { return MALE; } else if (randNum <= 2*RATE1) { return FEMALE; } else if (randNum <= 2*RATE1 + RATE2) { return GAY; } else { return LES; } } // 获取年龄 public int getAge() { return age; } // 获取代数 public int getGeneration() { return generation; } // 获取 <SUF> public int getGender() { return gender; } // 获取当前全部AdvancedCritter数据 public String getdata() { SparseBoundedGrid1<Actor> gr = (SparseBoundedGrid1)getGrid(); //获取自定义网格的存储数据 Map<Location, Actor> map = new HashMap<Location, Actor>(); map = (LinkedHashMap<Location, Actor>)gr.getMap(); int maleCount = 0; int femaleCount = 0; int maleGayCount = 0; int femaleLesCount = 0; int allCount = 0; // generationCount用于计数每一代有多少数量的AdvancedCritter HashMap<Integer, Integer>generationCount = new HashMap<Integer, Integer>(); for (Location loc : map.keySet()) { if (gr.get(loc) instanceof AdvancedCritter) { allCount++; AdvancedCritter temp = (AdvancedCritter)gr.get(loc); if (temp.getGender() == 0) { maleCount++; } if (temp.getGender() == 1) { femaleCount++; } if (temp.getGender() == 2) { maleGayCount++; } if (temp.getGender() == 3) { femaleLesCount++; } if (generationCount.containsKey(temp.getGeneration())) { int originCount = generationCount.get(temp.getGeneration()); generationCount.put(temp.getGeneration(), originCount + 1); } else { generationCount.put(temp.getGeneration(), 1); } } } String result = ""; double hundred = 100.0; result += "总的New Jumper数量是 " + allCount + "\n"; result += "男性数量是 " + maleCount + ",占据总数量的"+Double.toString(maleCount*hundred/allCount) + "%\n"; result += "女性数量是 " + femaleCount + ",占据总数量的"+Double.toString(femaleCount*hundred/allCount) + "%\n"; result += "男同性恋数量是 " + maleGayCount + ",占据总数量的"+Double.toString(maleGayCount*hundred/allCount) + "%\n"; result += "女同性恋数量是 " + femaleLesCount + ",占据总数量的"+Double.toString(femaleLesCount*hundred/allCount) + "%\n"; for (Integer g : generationCount.keySet()) { int count = generationCount.get(g); String rate = Double.toString(count*hundred/allCount); result +="第"+g+"代的NewJumper有"+count+"只, 占据总数量的"+ rate + "%\n"; } return result; } }
false
1,682
3
1,840
4
1,920
3
1,840
4
2,255
8
false
false
false
false
false
true
32965_15
package com.ddz.lifestyle.utils; import android.Manifest; import android.app.Activity; 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.provider.Settings; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.util.SparseArray; import com.ddz.lifestyle.LifeStyle; import com.ddz.lifestyle.http.GankApiStores; import com.ddz.lifestyle.http.bean.BookBean; import com.tencent.smtt.sdk.QbSdk; import org.jetbrains.annotations.NotNull; /** * @Author: ddz * Creation time: 17.8.11 17:11 * describe:{Android权限申请的封装,并在内部实现申请结果的处理} */ public class PermissionUtils { private static PermissionUtils permission; private String[] permissions; private Activity mActivity; private RequestPermissionListener PermissionListener; public static int requestCode = 100; //requestCode传值为100 public static PermissionUtils getInstance() { if (null == permission) { synchronized (PermissionUtils.class) { if (null == permission) { permission = new PermissionUtils(); } } } return permission; } /** * 权限检查 * * @param permission * @return */ public boolean checkPermission(@NonNull String permission) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } else { return ContextCompat.checkSelfPermission(LifeStyle.getContext(), permission) == PackageManager.PERMISSION_GRANTED; } } /** * Activity 页面申请权限 * * @param activity * @param permissions * @param requestCode * @param requestPermissionListener */ public void requestPermissiion(final @NonNull Activity activity, final @NonNull String[] permissions, final @IntRange(from = 0) int requestCode, @NonNull RequestPermissionListener requestPermissionListener) { this.mActivity = activity; PermissionListener = requestPermissionListener; this.permissions = permissions; ActivityCompat.requestPermissions(activity, permissions, requestCode); } /** * Fragment页面申请权限 * * @param fragment * @param permissions * @param requestCode * @param requestPermissionListener */ public void requestFragmentPermission(final @NonNull Fragment fragment, final @NonNull String[] permissions, final @IntRange(from = 0) int requestCode, @NonNull RequestPermissionListener requestPermissionListener) { PermissionListener = requestPermissionListener; this.permissions = permissions; fragment.requestPermissions(permissions, requestCode); } /** * 权限申请结果的回调 * * @param activity * @param requestCode * @param permissions * @param grantResults */ public void onRequestPermissionResult(final @NonNull Activity activity, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { this.mActivity = activity; if (null != PermissionListener) { if (requestCode == PermissionUtils.requestCode && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { PermissionListener.requestConfirm(); } else { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permissions[0])) { PermissionListener.requestCancel(); } else { PermissionListener.requestCancelAgain(); } } } } /** * 用户点击拒绝,弹出申请权限的说明弹窗,也可以自定义实现 * * @param context Context * @param title 弹窗标题 * @param message 申请权限解释说明 * @param confirm 确认按钮的文字,默认OK * @param cancel 取消按钮呢的文字,默认不显示取消按钮 */ public void requestDialog(Context context, @NonNull String title, @NonNull String message, String confirm, String cancel) { try { AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(title).setMessage(message); builder.setPositiveButton(confirm == null ? "OK" : confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { requestPermissiion(mActivity, permissions, requestCode, PermissionListener); dialog.dismiss(); } }); if (null != cancel) { builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } builder.setCancelable(false); builder.show(); } catch (Exception e) { e.printStackTrace(); } } /** * 用户勾选不再显示并点击拒绝,弹出打开设置页面申请权限,也可以自定义实现 * * @param context Context * @param title 弹窗标题 * @param message 申请权限解释说明 * @param confirm 确认按钮的文字,默认OK * @param cancel 取消按钮呢的文字,默认不显示取消按钮 */ public void requestDialogAgain(Context context, @NonNull String title, @NonNull String message, String confirm, String cancel) { try { AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(title).setMessage(message); builder.setPositiveButton(confirm == null ? "OK" : confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startSettingActivity(mActivity); dialog.dismiss(); } }); if (null != cancel) { builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } builder.setCancelable(false); builder.show(); } catch (Exception e) { e.printStackTrace(); } } /** * 打开设置页面打开权限 * * @param context */ public void startSettingActivity(@NonNull Activity context) { try { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.getPackageName())); intent.addCategory(Intent.CATEGORY_DEFAULT); context.startActivityForResult(intent, 10); //这里的requestCode和onActivityResult中requestCode要一致 } catch (Exception e) { e.printStackTrace(); } } /** * 打开设置页面的回调 * * @param requestCode * @param resultCode * @param data */ public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 10: //这里值是打开设置页面申请权限的RequestCode,默认为10 try { if (null != PermissionListener) { if (null != permissions && permissions.length > 0) { for (String permission : permissions) { if (checkPermission(permission)) { PermissionListener.requestConfirm(); } else { PermissionListener.requestFailed(); } } } else { PermissionListener.requestFailed(); } } else { PermissionListener.requestFailed(); } } catch (Exception e) { e.printStackTrace(); } break; } } /** * 权限申请回调 */ public interface RequestPermissionListener { void requestConfirm(); //申请成功 void requestCancel(); //拒绝 void requestCancelAgain(); //勾选不再提示并拒绝 void requestFailed(); //在设置页面申请权限失败 } }
dazhaoDai/PermissionUtils
PermissionUtils.java
1,842
//在设置页面申请权限失败
line_comment
zh-cn
package com.ddz.lifestyle.utils; import android.Manifest; import android.app.Activity; 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.provider.Settings; import android.support.annotation.IntRange; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.util.SparseArray; import com.ddz.lifestyle.LifeStyle; import com.ddz.lifestyle.http.GankApiStores; import com.ddz.lifestyle.http.bean.BookBean; import com.tencent.smtt.sdk.QbSdk; import org.jetbrains.annotations.NotNull; /** * @Author: ddz * Creation time: 17.8.11 17:11 * describe:{Android权限申请的封装,并在内部实现申请结果的处理} */ public class PermissionUtils { private static PermissionUtils permission; private String[] permissions; private Activity mActivity; private RequestPermissionListener PermissionListener; public static int requestCode = 100; //requestCode传值为100 public static PermissionUtils getInstance() { if (null == permission) { synchronized (PermissionUtils.class) { if (null == permission) { permission = new PermissionUtils(); } } } return permission; } /** * 权限检查 * * @param permission * @return */ public boolean checkPermission(@NonNull String permission) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { return true; } else { return ContextCompat.checkSelfPermission(LifeStyle.getContext(), permission) == PackageManager.PERMISSION_GRANTED; } } /** * Activity 页面申请权限 * * @param activity * @param permissions * @param requestCode * @param requestPermissionListener */ public void requestPermissiion(final @NonNull Activity activity, final @NonNull String[] permissions, final @IntRange(from = 0) int requestCode, @NonNull RequestPermissionListener requestPermissionListener) { this.mActivity = activity; PermissionListener = requestPermissionListener; this.permissions = permissions; ActivityCompat.requestPermissions(activity, permissions, requestCode); } /** * Fragment页面申请权限 * * @param fragment * @param permissions * @param requestCode * @param requestPermissionListener */ public void requestFragmentPermission(final @NonNull Fragment fragment, final @NonNull String[] permissions, final @IntRange(from = 0) int requestCode, @NonNull RequestPermissionListener requestPermissionListener) { PermissionListener = requestPermissionListener; this.permissions = permissions; fragment.requestPermissions(permissions, requestCode); } /** * 权限申请结果的回调 * * @param activity * @param requestCode * @param permissions * @param grantResults */ public void onRequestPermissionResult(final @NonNull Activity activity, int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { this.mActivity = activity; if (null != PermissionListener) { if (requestCode == PermissionUtils.requestCode && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { PermissionListener.requestConfirm(); } else { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permissions[0])) { PermissionListener.requestCancel(); } else { PermissionListener.requestCancelAgain(); } } } } /** * 用户点击拒绝,弹出申请权限的说明弹窗,也可以自定义实现 * * @param context Context * @param title 弹窗标题 * @param message 申请权限解释说明 * @param confirm 确认按钮的文字,默认OK * @param cancel 取消按钮呢的文字,默认不显示取消按钮 */ public void requestDialog(Context context, @NonNull String title, @NonNull String message, String confirm, String cancel) { try { AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(title).setMessage(message); builder.setPositiveButton(confirm == null ? "OK" : confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { requestPermissiion(mActivity, permissions, requestCode, PermissionListener); dialog.dismiss(); } }); if (null != cancel) { builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } builder.setCancelable(false); builder.show(); } catch (Exception e) { e.printStackTrace(); } } /** * 用户勾选不再显示并点击拒绝,弹出打开设置页面申请权限,也可以自定义实现 * * @param context Context * @param title 弹窗标题 * @param message 申请权限解释说明 * @param confirm 确认按钮的文字,默认OK * @param cancel 取消按钮呢的文字,默认不显示取消按钮 */ public void requestDialogAgain(Context context, @NonNull String title, @NonNull String message, String confirm, String cancel) { try { AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(title).setMessage(message); builder.setPositiveButton(confirm == null ? "OK" : confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { startSettingActivity(mActivity); dialog.dismiss(); } }); if (null != cancel) { builder.setNegativeButton(cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); } builder.setCancelable(false); builder.show(); } catch (Exception e) { e.printStackTrace(); } } /** * 打开设置页面打开权限 * * @param context */ public void startSettingActivity(@NonNull Activity context) { try { Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + context.getPackageName())); intent.addCategory(Intent.CATEGORY_DEFAULT); context.startActivityForResult(intent, 10); //这里的requestCode和onActivityResult中requestCode要一致 } catch (Exception e) { e.printStackTrace(); } } /** * 打开设置页面的回调 * * @param requestCode * @param resultCode * @param data */ public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case 10: //这里值是打开设置页面申请权限的RequestCode,默认为10 try { if (null != PermissionListener) { if (null != permissions && permissions.length > 0) { for (String permission : permissions) { if (checkPermission(permission)) { PermissionListener.requestConfirm(); } else { PermissionListener.requestFailed(); } } } else { PermissionListener.requestFailed(); } } else { PermissionListener.requestFailed(); } } catch (Exception e) { e.printStackTrace(); } break; } } /** * 权限申请回调 */ public interface RequestPermissionListener { void requestConfirm(); //申请成功 void requestCancel(); //拒绝 void requestCancelAgain(); //勾选不再提示并拒绝 void requestFailed(); //在设 <SUF> } }
false
1,641
7
1,842
7
1,963
7
1,842
7
2,425
16
false
false
false
false
false
true
34540_0
package etl.transform; import etl.utils.Transform; import org.apache.spark.sql.SparkSession; /** * 数据转换业务逻辑 */ public class Tran extends Transform { public Tran(SparkSession spark, Integer timeType, String timeID, Integer backDate, Integer frequency) { super(spark, timeType, timeID, backDate, frequency); } /** * stgging层integrate层 * * @throws Exception */ public void s2iD() throws Exception { exeSQLFile("s2i_d.sql", "insert"); // exeType: insert 插入hive表中; view 生成v_${表名}的临时试图,供后续使用 } /** * integerate层到datamart层 * * @throws Exception */ public void i2mD() throws Exception { exeSQLFile("i2m_d.sql", "insert"); } }
dazheng/SparkETL
src/main/java/etl/transform/Tran.java
219
/** * 数据转换业务逻辑 */
block_comment
zh-cn
package etl.transform; import etl.utils.Transform; import org.apache.spark.sql.SparkSession; /** * 数据转 <SUF>*/ public class Tran extends Transform { public Tran(SparkSession spark, Integer timeType, String timeID, Integer backDate, Integer frequency) { super(spark, timeType, timeID, backDate, frequency); } /** * stgging层integrate层 * * @throws Exception */ public void s2iD() throws Exception { exeSQLFile("s2i_d.sql", "insert"); // exeType: insert 插入hive表中; view 生成v_${表名}的临时试图,供后续使用 } /** * integerate层到datamart层 * * @throws Exception */ public void i2mD() throws Exception { exeSQLFile("i2m_d.sql", "insert"); } }
false
205
8
219
9
228
9
219
9
283
18
false
false
false
false
false
true
25540_11
//给你一个长度为 n 下标从 0 开始的整数数组 maxHeights 。 // // 你的任务是在坐标轴上建 n 座塔。第 i 座塔的下标为 i ,高度为 heights[i] 。 // // 如果以下条件满足,我们称这些塔是 美丽 的: // // // 1 <= heights[i] <= maxHeights[i] // heights 是一个 山状 数组。 // // // 如果存在下标 i 满足以下条件,那么我们称数组 heights 是一个 山状 数组: // // // 对于所有 0 < j <= i ,都有 heights[j - 1] <= heights[j] // 对于所有 i <= k < n - 1 ,都有 heights[k + 1] <= heights[k] // // // 请你返回满足 美丽塔 要求的方案中,高度和的最大值 。 // // // // 示例 1: // // //输入:maxHeights = [5,3,4,1,1] //输出:13 //解释:和最大的美丽塔方案为 heights = [5,3,3,1,1] ,这是一个美丽塔方案,因为: //- 1 <= heights[i] <= maxHeights[i] //- heights 是个山状数组,峰值在 i = 0 处。 //13 是所有美丽塔方案中的最大高度和。 // // 示例 2: // // //输入:maxHeights = [6,5,3,9,2,7] //输出:22 //解释: 和最大的美丽塔方案为 heights = [3,3,3,9,2,2] ,这是一个美丽塔方案,因为: //- 1 <= heights[i] <= maxHeights[i] //- heights 是个山状数组,峰值在 i = 3 处。 //22 是所有美丽塔方案中的最大高度和。 // // 示例 3: // // //输入:maxHeights = [3,2,5,5,2,3] //输出:18 //解释:和最大的美丽塔方案为 heights = [2,2,5,5,2,2] ,这是一个美丽塔方案,因为: //- 1 <= heights[i] <= maxHeights[i] //- heights 是个山状数组,最大值在 i = 2 处。 //注意,在这个方案中,i = 3 也是一个峰值。 //18 是所有美丽塔方案中的最大高度和。 // // // // // 提示: // // // 1 <= n == maxHeights <= 10⁵ // 1 <= maxHeights[i] <= 10⁹ // // // 👍 17 👎 0 package cn.db117.leetcode.solution28; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.List; /** * 2866.美丽塔 II.beautiful-towers-ii * * @author db117 * @since 2023-09-26 10:30:49 **/ public class Solution_2866 { public static void main(String[] args) { Solution solution = new Solution_2866().new Solution(); // [5,3,4,1,1] System.out.println(solution.maximumSumOfHeights(Arrays.asList(5, 3, 4, 1, 1))); // [314324228,526196638,971780775,141382951,44825730,92939243,869702460,692214717,396184442,271863091,452818943,124554145,194393992,813279621,476977123,291285997,195696382,80619001,296691434,24194433,834306546,337273583,612960339,252148987,498162770,641751698,580675254,66186200,192009966,590634046,590252844,510204257,235020771,606202644,338253570,224352005,183647397,867961176,521468453,365745792,508222499,360685429,851354307,177768509,955097078,227459453,644376561,467834249,594236609,319781404,648225233,524439197,532203513,463002246,498592686,691351312,208635346,155682966,294639403,341617283,604365123,79112831,22440031,809193898,675993946,99928197,644324211,170555722,218906830,782039120,686747235,356537885] System.out.println(solution.maximumSumOfHeights(Arrays.asList(314324228, 526196638, 971780775, 141382951, 44825730, 92939243, 869702460, 692214717, 396184442, 271863091, 452818943, 124554145, 194393992, 813279621, 476977123, 291285997, 195696382, 80619001, 296691434, 24194433, 834306546, 337273583, 612960339, 252148987, 498162770, 641751698, 580675254, 66186200, 192009966, 590634046, 590252844, 510204257, 235020771, 606202644, 338253570, 224352005, 183647397, 867961176, 521468453, 365745792, 508222499, 360685429, 851354307, 177768509, 955097078, 227459453, 644376561, 467834249, 594236609, 319781404, 648225233, 524439197, 532203513, 463002246, 498592686, 691351312, 208635346, 155682966, 294639403, 341617283, 604365123, 79112831, 22440031, 809193898, 675993946, 99928197, 644324211, 170555722, 218906830, 782039120, 686747235, 356537885))); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public long maximumSumOfHeights(List<Integer> maxHeights) { int[] arr = new int[maxHeights.size()]; for (int i = 0; i < maxHeights.size(); i++) { arr[i] = maxHeights.get(i); } long ans = 0; int n = maxHeights.size(); long[] right = new long[n + 1]; // 单调栈 Deque<Integer> queue = new ArrayDeque<>(); // 计算以当前位置为最高点的右边的和 queue.push(n);// 哨兵 long sum = 0; for (int i = n - 1; i >= 0; i--) { while (queue.size() > 1 && arr[i] <= arr[queue.peek()]) { Integer pre = queue.pop(); // 去掉比当前值小的,之前的都多算了 sum -= (long) (queue.peek() - pre) * arr[pre]; } // 栈里面现在有的都比当前值小,且栈顶到当前索引中间全是当前值 sum += (long) arr[i] * (queue.peek() - i); right[i] = sum; queue.push(i); } // 计算以当前位置为最高点的左边的和 queue.clear(); queue.push(-1);// 哨兵 sum = 0; for (int i = 0; i < n; i++) { while (queue.size() > 1 && arr[i] <= arr[queue.peek()]) { Integer pre = queue.pop(); sum -= (long) (pre - queue.peek()) * arr[pre]; } sum += (long) arr[i] * (i - queue.peek()); queue.push(i); ans = Math.max(ans, sum + right[i + 1]); } return ans; } } //leetcode submit region end(Prohibit modification and deletion) }
db117/algorithm
src/main/java/cn/db117/leetcode/solution28/Solution_2866.java
2,961
//输出:13
line_comment
zh-cn
//给你一个长度为 n 下标从 0 开始的整数数组 maxHeights 。 // // 你的任务是在坐标轴上建 n 座塔。第 i 座塔的下标为 i ,高度为 heights[i] 。 // // 如果以下条件满足,我们称这些塔是 美丽 的: // // // 1 <= heights[i] <= maxHeights[i] // heights 是一个 山状 数组。 // // // 如果存在下标 i 满足以下条件,那么我们称数组 heights 是一个 山状 数组: // // // 对于所有 0 < j <= i ,都有 heights[j - 1] <= heights[j] // 对于所有 i <= k < n - 1 ,都有 heights[k + 1] <= heights[k] // // // 请你返回满足 美丽塔 要求的方案中,高度和的最大值 。 // // // // 示例 1: // // //输入:maxHeights = [5,3,4,1,1] //输出 <SUF> //解释:和最大的美丽塔方案为 heights = [5,3,3,1,1] ,这是一个美丽塔方案,因为: //- 1 <= heights[i] <= maxHeights[i] //- heights 是个山状数组,峰值在 i = 0 处。 //13 是所有美丽塔方案中的最大高度和。 // // 示例 2: // // //输入:maxHeights = [6,5,3,9,2,7] //输出:22 //解释: 和最大的美丽塔方案为 heights = [3,3,3,9,2,2] ,这是一个美丽塔方案,因为: //- 1 <= heights[i] <= maxHeights[i] //- heights 是个山状数组,峰值在 i = 3 处。 //22 是所有美丽塔方案中的最大高度和。 // // 示例 3: // // //输入:maxHeights = [3,2,5,5,2,3] //输出:18 //解释:和最大的美丽塔方案为 heights = [2,2,5,5,2,2] ,这是一个美丽塔方案,因为: //- 1 <= heights[i] <= maxHeights[i] //- heights 是个山状数组,最大值在 i = 2 处。 //注意,在这个方案中,i = 3 也是一个峰值。 //18 是所有美丽塔方案中的最大高度和。 // // // // // 提示: // // // 1 <= n == maxHeights <= 10⁵ // 1 <= maxHeights[i] <= 10⁹ // // // 👍 17 👎 0 package cn.db117.leetcode.solution28; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Deque; import java.util.List; /** * 2866.美丽塔 II.beautiful-towers-ii * * @author db117 * @since 2023-09-26 10:30:49 **/ public class Solution_2866 { public static void main(String[] args) { Solution solution = new Solution_2866().new Solution(); // [5,3,4,1,1] System.out.println(solution.maximumSumOfHeights(Arrays.asList(5, 3, 4, 1, 1))); // [314324228,526196638,971780775,141382951,44825730,92939243,869702460,692214717,396184442,271863091,452818943,124554145,194393992,813279621,476977123,291285997,195696382,80619001,296691434,24194433,834306546,337273583,612960339,252148987,498162770,641751698,580675254,66186200,192009966,590634046,590252844,510204257,235020771,606202644,338253570,224352005,183647397,867961176,521468453,365745792,508222499,360685429,851354307,177768509,955097078,227459453,644376561,467834249,594236609,319781404,648225233,524439197,532203513,463002246,498592686,691351312,208635346,155682966,294639403,341617283,604365123,79112831,22440031,809193898,675993946,99928197,644324211,170555722,218906830,782039120,686747235,356537885] System.out.println(solution.maximumSumOfHeights(Arrays.asList(314324228, 526196638, 971780775, 141382951, 44825730, 92939243, 869702460, 692214717, 396184442, 271863091, 452818943, 124554145, 194393992, 813279621, 476977123, 291285997, 195696382, 80619001, 296691434, 24194433, 834306546, 337273583, 612960339, 252148987, 498162770, 641751698, 580675254, 66186200, 192009966, 590634046, 590252844, 510204257, 235020771, 606202644, 338253570, 224352005, 183647397, 867961176, 521468453, 365745792, 508222499, 360685429, 851354307, 177768509, 955097078, 227459453, 644376561, 467834249, 594236609, 319781404, 648225233, 524439197, 532203513, 463002246, 498592686, 691351312, 208635346, 155682966, 294639403, 341617283, 604365123, 79112831, 22440031, 809193898, 675993946, 99928197, 644324211, 170555722, 218906830, 782039120, 686747235, 356537885))); } //leetcode submit region begin(Prohibit modification and deletion) class Solution { public long maximumSumOfHeights(List<Integer> maxHeights) { int[] arr = new int[maxHeights.size()]; for (int i = 0; i < maxHeights.size(); i++) { arr[i] = maxHeights.get(i); } long ans = 0; int n = maxHeights.size(); long[] right = new long[n + 1]; // 单调栈 Deque<Integer> queue = new ArrayDeque<>(); // 计算以当前位置为最高点的右边的和 queue.push(n);// 哨兵 long sum = 0; for (int i = n - 1; i >= 0; i--) { while (queue.size() > 1 && arr[i] <= arr[queue.peek()]) { Integer pre = queue.pop(); // 去掉比当前值小的,之前的都多算了 sum -= (long) (queue.peek() - pre) * arr[pre]; } // 栈里面现在有的都比当前值小,且栈顶到当前索引中间全是当前值 sum += (long) arr[i] * (queue.peek() - i); right[i] = sum; queue.push(i); } // 计算以当前位置为最高点的左边的和 queue.clear(); queue.push(-1);// 哨兵 sum = 0; for (int i = 0; i < n; i++) { while (queue.size() > 1 && arr[i] <= arr[queue.peek()]) { Integer pre = queue.pop(); sum -= (long) (pre - queue.peek()) * arr[pre]; } sum += (long) arr[i] * (i - queue.peek()); queue.push(i); ans = Math.max(ans, sum + right[i + 1]); } return ans; } } //leetcode submit region end(Prohibit modification and deletion) }
false
2,754
5
2,961
5
2,889
5
2,961
5
3,264
6
false
false
false
false
false
true
64569_10
package top.flagshen.myqq.common.cache; /** * @author dengchao */ public class RedisConstant { public static final String TEMPLATE = "template";//消息模板 public static final String VACATION_TEMPLATE = "VACATION_TEMPLATE";//请假模板 public static final String LATER_TEMPLATE = "LATER_TEMPLATE";//推迟模板 public static final String CHAPTER_NAME = "CHAPTER_NAME";//最新章节名 public static final String CHAPTER_NUM = "CHAPTER_NUM";//最新章节数 public static final String NAME = "NAME";//打赏盟主名单 public static final String TITLE = "TITLE";//章节名 public static final String URL = "URL";//链接 public static final String NUMBER = "NUMBER";//字数 public static final String DIVINATION = "DIVINATION:";//占卜 public static final String DIVINATIONSTR = "DIVINATIONSTR:";//占卜结果文案 public static final String GAIMING = "GAIMING:";//改命 public static final String MENGZHU = "MENGZHU";//盟主列表 public static final String JINYAN = "JINYAN:";//是否开启禁言功能 public static final String CHEHUI = "CHEHUI:";//是否开启撤回功能 public static final String JINYAN_COUNT = "JINYAN_COUNT:";//24小时内连图禁言次数 public static final String JINYAN_FLAG = "JINYAN_FLAG:";//因为连图禁言的标识,存在30秒 public static final String STUDY_SCORE = "STUDY_SCORE";//学习积分 public static final String GET_UP = "GET_UP";//起床 public static final String DAGONG = "DAGONG:";//打工 public static final String JUEDOU = "JUEDOU:";//决斗发起人 public static final String JIESHOU = "JIESHOU:";//决斗接受人 public static final String JUEDOU_JINYAN = "JUEDOU_JINYAN:";//决斗需要禁言的人 public static final String JUEDOU_CD = "JUEDOU_CD:";//决斗发起失败的人要cd1天 public static final String YILIAO_CD = "YILIAO_CD:";//使用医疗包cd10分钟 public static final String JUEDOU_OPEN_SET = "JUEDOU_OPEN_SET";//决斗开启成员 public static final String JUEDOU_7_COUNT = "JUEDOU_7_COUNT:";//决斗小七次数 }
dc0629/seven
src/main/java/top/flagshen/myqq/common/cache/RedisConstant.java
629
//是否开启禁言功能
line_comment
zh-cn
package top.flagshen.myqq.common.cache; /** * @author dengchao */ public class RedisConstant { public static final String TEMPLATE = "template";//消息模板 public static final String VACATION_TEMPLATE = "VACATION_TEMPLATE";//请假模板 public static final String LATER_TEMPLATE = "LATER_TEMPLATE";//推迟模板 public static final String CHAPTER_NAME = "CHAPTER_NAME";//最新章节名 public static final String CHAPTER_NUM = "CHAPTER_NUM";//最新章节数 public static final String NAME = "NAME";//打赏盟主名单 public static final String TITLE = "TITLE";//章节名 public static final String URL = "URL";//链接 public static final String NUMBER = "NUMBER";//字数 public static final String DIVINATION = "DIVINATION:";//占卜 public static final String DIVINATIONSTR = "DIVINATIONSTR:";//占卜结果文案 public static final String GAIMING = "GAIMING:";//改命 public static final String MENGZHU = "MENGZHU";//盟主列表 public static final String JINYAN = "JINYAN:";//是否 <SUF> public static final String CHEHUI = "CHEHUI:";//是否开启撤回功能 public static final String JINYAN_COUNT = "JINYAN_COUNT:";//24小时内连图禁言次数 public static final String JINYAN_FLAG = "JINYAN_FLAG:";//因为连图禁言的标识,存在30秒 public static final String STUDY_SCORE = "STUDY_SCORE";//学习积分 public static final String GET_UP = "GET_UP";//起床 public static final String DAGONG = "DAGONG:";//打工 public static final String JUEDOU = "JUEDOU:";//决斗发起人 public static final String JIESHOU = "JIESHOU:";//决斗接受人 public static final String JUEDOU_JINYAN = "JUEDOU_JINYAN:";//决斗需要禁言的人 public static final String JUEDOU_CD = "JUEDOU_CD:";//决斗发起失败的人要cd1天 public static final String YILIAO_CD = "YILIAO_CD:";//使用医疗包cd10分钟 public static final String JUEDOU_OPEN_SET = "JUEDOU_OPEN_SET";//决斗开启成员 public static final String JUEDOU_7_COUNT = "JUEDOU_7_COUNT:";//决斗小七次数 }
false
556
6
629
6
574
6
629
6
826
13
false
false
false
false
false
true
17069_28
package com.dcl.blog.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.servlet.ServletInputStream; public class WeiXinUrl { /** * 获取access_token是公众号的全局唯一票据, * @param appid * @param secret * @return */ public static String getAccess_token(String appid,String secret){ return "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret; } /** * 图片 */ public static final String UPDATE_TYPE_IMAGE="image"; /** * 声音 */ public static final String UPDATE_TYPE_VOICE="voice"; /** * 视频 */ public static final String UPDATE_TYPE_VIDEO="video"; /** * 缩略图 */ public static final String UPDATE_TYPE_THUMB="thumb"; /** * 上传文件 media form-data中媒体文件标识,有filename、filelength、content-type等信息 * @param access_token * @param type * @return */ public static String getUpdateFile(String access_token,String type){ return "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+access_token+"&type="+type; } /** * 下载多媒体文件 * @param access_token * @param media_id * @return */ public static String getDewnLoad(String access_token,String media_id){ return "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+media_id; } /** * 当用户主动发消息给公众号的时候(包括发送信息、点击自定义菜单click事件、订阅事件、扫描二维码事件、支付成功事件、用户维权),微信将会把消息数据推送给开发者,开发者在一段时间内(目前修改为48小时)可以调用客服消息接口,通过POST一个JSON数据包来发送消息给普通用户,在48小时内不限制发送次数。此接口主要用于客服等有人工消息处理环节的功能,方便开发者为用户提供更加优质的服务。 */ public static String sendMessage(String access_token){ return "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+access_token; } /** * 创建分组 */ public static String getCreateGroup(String access_token){ return "https://api.weixin.qq.com/cgi-bin/groups/create?access_token="+access_token; } /** * 查询分组 */ public static String getLooKUpGroup(String access_token){ return "https://api.weixin.qq.com/cgi-bin/groups/get?access_token="+access_token; } /** * 查询用户所在组 */ public static String queryUserByGroup(String access_token,String openid){ return "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token="+access_token; } /** * 修改分组名 */ public static String updateUserByGroup(String access_token,String id,String name){ return "https://api.weixin.qq.com/cgi-bin/groups/update?access_token="+access_token; } /** * 移动用户分组 */ public static String moveUserToGroup(String access_token,String openid,String to_groupid){ return "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token="+access_token; } /** * 获取用户信息 */ public static String getUserInfo(String access_token,String openid){ return "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN"; } /** * 获取关注用户列表 */ public static String getUserList(String access_token,String next_openid){ return "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token+"&next_openid="+next_openid; } /** * 接口调用请求说明 * button 是 一级菜单数组,个数应为1~3个 sub_button 否 二级菜单数组,个数应为1~5个 type 是 菜单的响应动作类型,目前有click、view两种类型 name 是 菜单标题,不超过16个字节,子菜单不超过40个字节 key click类型必须 菜单KEY值,用于消息接口推送,不超过128字节 url view类型必须 网页链接,用户点击菜单可打开链接,不超过256字节 */ public static String createMenu(String access_token){ return "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+access_token; } /** * 获取菜单 */ public static String getMenu(String access_token){ return "https://api.weixin.qq.com/cgi-bin/menu/get?access_token="+access_token; } /** * 删除 * @param access_token * @return */ public static String deletdMenu(String access_token){ return "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+access_token; } //从输入流读取post参数 public static String readStreamParameter(ServletInputStream in){ StringBuilder buffer = new StringBuilder(); BufferedReader reader=null; try{ reader = new BufferedReader(new InputStreamReader(in)); String line=null; while((line = reader.readLine())!=null){ buffer.append(line); } }catch(Exception e){ e.printStackTrace(); }finally{ if(null!=reader){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return buffer.toString(); } }
dcl8261425/saas
src/main/java/com/dcl/blog/util/WeiXinUrl.java
1,567
/** * 获取菜单 */
block_comment
zh-cn
package com.dcl.blog.util; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import javax.servlet.ServletInputStream; public class WeiXinUrl { /** * 获取access_token是公众号的全局唯一票据, * @param appid * @param secret * @return */ public static String getAccess_token(String appid,String secret){ return "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret; } /** * 图片 */ public static final String UPDATE_TYPE_IMAGE="image"; /** * 声音 */ public static final String UPDATE_TYPE_VOICE="voice"; /** * 视频 */ public static final String UPDATE_TYPE_VIDEO="video"; /** * 缩略图 */ public static final String UPDATE_TYPE_THUMB="thumb"; /** * 上传文件 media form-data中媒体文件标识,有filename、filelength、content-type等信息 * @param access_token * @param type * @return */ public static String getUpdateFile(String access_token,String type){ return "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token="+access_token+"&type="+type; } /** * 下载多媒体文件 * @param access_token * @param media_id * @return */ public static String getDewnLoad(String access_token,String media_id){ return "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+access_token+"&media_id="+media_id; } /** * 当用户主动发消息给公众号的时候(包括发送信息、点击自定义菜单click事件、订阅事件、扫描二维码事件、支付成功事件、用户维权),微信将会把消息数据推送给开发者,开发者在一段时间内(目前修改为48小时)可以调用客服消息接口,通过POST一个JSON数据包来发送消息给普通用户,在48小时内不限制发送次数。此接口主要用于客服等有人工消息处理环节的功能,方便开发者为用户提供更加优质的服务。 */ public static String sendMessage(String access_token){ return "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+access_token; } /** * 创建分组 */ public static String getCreateGroup(String access_token){ return "https://api.weixin.qq.com/cgi-bin/groups/create?access_token="+access_token; } /** * 查询分组 */ public static String getLooKUpGroup(String access_token){ return "https://api.weixin.qq.com/cgi-bin/groups/get?access_token="+access_token; } /** * 查询用户所在组 */ public static String queryUserByGroup(String access_token,String openid){ return "https://api.weixin.qq.com/cgi-bin/groups/getid?access_token="+access_token; } /** * 修改分组名 */ public static String updateUserByGroup(String access_token,String id,String name){ return "https://api.weixin.qq.com/cgi-bin/groups/update?access_token="+access_token; } /** * 移动用户分组 */ public static String moveUserToGroup(String access_token,String openid,String to_groupid){ return "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token="+access_token; } /** * 获取用户信息 */ public static String getUserInfo(String access_token,String openid){ return "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+access_token+"&openid="+openid+"&lang=zh_CN"; } /** * 获取关注用户列表 */ public static String getUserList(String access_token,String next_openid){ return "https://api.weixin.qq.com/cgi-bin/user/get?access_token="+access_token+"&next_openid="+next_openid; } /** * 接口调用请求说明 * button 是 一级菜单数组,个数应为1~3个 sub_button 否 二级菜单数组,个数应为1~5个 type 是 菜单的响应动作类型,目前有click、view两种类型 name 是 菜单标题,不超过16个字节,子菜单不超过40个字节 key click类型必须 菜单KEY值,用于消息接口推送,不超过128字节 url view类型必须 网页链接,用户点击菜单可打开链接,不超过256字节 */ public static String createMenu(String access_token){ return "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+access_token; } /** * 获取菜 <SUF>*/ public static String getMenu(String access_token){ return "https://api.weixin.qq.com/cgi-bin/menu/get?access_token="+access_token; } /** * 删除 * @param access_token * @return */ public static String deletdMenu(String access_token){ return "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token="+access_token; } //从输入流读取post参数 public static String readStreamParameter(ServletInputStream in){ StringBuilder buffer = new StringBuilder(); BufferedReader reader=null; try{ reader = new BufferedReader(new InputStreamReader(in)); String line=null; while((line = reader.readLine())!=null){ buffer.append(line); } }catch(Exception e){ e.printStackTrace(); }finally{ if(null!=reader){ try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } } return buffer.toString(); } }
false
1,234
8
1,558
7
1,549
9
1,558
7
1,973
12
false
false
false
false
false
true
53377_1
package com.zhang.hui.lib_recreation.tool.xfparsebean; import java.io.Serializable; import java.util.List; /** * Created by lenovo on 2018/2/27. */ public class HistoryTodayBean implements Serializable { /** * date : 02-27 * day : 1991年02月27日 * description : 1991年2月27日 (农历正月十三),科威特恢复国家独立和主权。 1991年2月27日,科威特城这个近7个月来全球瞩目的城市,从早到晚到处响彻“自由科威特”的口号声。成百上千辆汽车装饰着标语、彩旗,喇叭长鸣,载着喜形于色、载歌载舞的科威特人在市中心来往穿行。年轻小伙子不时朝天鸣放机枪、冲锋枪,表示庆祝。妇女们则手持国旗和埃米尔画像,笑容满面。 科威特人民议会最高咨询局当日在吉达发表声明,号召科威特人民加强民族团结,以便重建遭受战争破坏的祖国。 科威特最高咨询局26和27日在科威特首相萨阿德王储主持下举行了为期两天的会议。包括内阁成员、议会议员、政治家和商人在内的36名科威特知名人士参加了大会。 声明还要求科威特人民为恢复祖国遭到战争破坏的基本建设而勤奋工作。 科威特的一些反对派领导人表示,支持政府最近宣布的“在特殊的环境中实施的”军事管制法。 28日,中华人民共和国主席杨尚昆打电报给科威特埃米尔贾比尔·艾哈迈德·萨巴赫殿下,热烈祝贺科威特的独立、主权、领土完整得以恢复。 * imgs : [] * source : juhe * title : 科威特恢复国家独立和主权 */ public String date; public String day; public String description; public String source; public String title; public List<String> imgs; public boolean flag; }
dcy000/MLxiao
lib-recreation/src/main/java/com/zhang/hui/lib_recreation/tool/xfparsebean/HistoryTodayBean.java
647
/** * date : 02-27 * day : 1991年02月27日 * description : 1991年2月27日 (农历正月十三),科威特恢复国家独立和主权。 1991年2月27日,科威特城这个近7个月来全球瞩目的城市,从早到晚到处响彻“自由科威特”的口号声。成百上千辆汽车装饰着标语、彩旗,喇叭长鸣,载着喜形于色、载歌载舞的科威特人在市中心来往穿行。年轻小伙子不时朝天鸣放机枪、冲锋枪,表示庆祝。妇女们则手持国旗和埃米尔画像,笑容满面。 科威特人民议会最高咨询局当日在吉达发表声明,号召科威特人民加强民族团结,以便重建遭受战争破坏的祖国。 科威特最高咨询局26和27日在科威特首相萨阿德王储主持下举行了为期两天的会议。包括内阁成员、议会议员、政治家和商人在内的36名科威特知名人士参加了大会。 声明还要求科威特人民为恢复祖国遭到战争破坏的基本建设而勤奋工作。 科威特的一些反对派领导人表示,支持政府最近宣布的“在特殊的环境中实施的”军事管制法。 28日,中华人民共和国主席杨尚昆打电报给科威特埃米尔贾比尔·艾哈迈德·萨巴赫殿下,热烈祝贺科威特的独立、主权、领土完整得以恢复。 * imgs : [] * source : juhe * title : 科威特恢复国家独立和主权 */
block_comment
zh-cn
package com.zhang.hui.lib_recreation.tool.xfparsebean; import java.io.Serializable; import java.util.List; /** * Created by lenovo on 2018/2/27. */ public class HistoryTodayBean implements Serializable { /** * dat <SUF>*/ public String date; public String day; public String description; public String source; public String title; public List<String> imgs; public boolean flag; }
false
480
389
647
535
522
408
647
535
877
749
true
true
true
true
true
false
22586_1
/* * Copyright 2022 learn-netty4 Project * * The learn-netty4 Project 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: * * https://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.flydean08.pojo; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import lombok.extern.slf4j.Slf4j; /** * 处理客户端发来的消息 */ @Slf4j public class PojoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { log.info("server收到对象:{}",msg); ctx.write("加油!"); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 异常处理 log.error("出现异常",cause); ctx.close(); } }
ddean2009/learn-netty4
src/main/java/com/flydean08/pojo/PojoServerHandler.java
348
/** * 处理客户端发来的消息 */
block_comment
zh-cn
/* * Copyright 2022 learn-netty4 Project * * The learn-netty4 Project 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: * * https://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.flydean08.pojo; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import lombok.extern.slf4j.Slf4j; /** * 处理客 <SUF>*/ @Slf4j public class PojoServerHandler extends ChannelInboundHandlerAdapter { @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { log.info("server收到对象:{}",msg); ctx.write("加油!"); } @Override public void channelReadComplete(ChannelHandlerContext ctx) { ctx.flush(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // 异常处理 log.error("出现异常",cause); ctx.close(); } }
false
310
11
348
11
354
10
348
11
428
18
false
false
false
false
false
true
36337_52
package JVA.ACM.面试; //以下是ACM模式 // 单行输入 // 输入 // 1 1 // 输出 // 2 // import java.util.Scanner; // public class Main { // public static void main(String[] args) { // Scanner in = new Scanner(System.in); // while (in.hasNextInt()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例 // int a = in.nextInt(); // int b = in.nextInt(); // System.out.println(a + b); // } // } // } // 多行输入 // 输入描述:输入一个n,表示阶数,然后输入n行n列的矩阵 // 输除描述:输出一个词证书表示n阶方阵的和 // 输入 // 3 // 1 2 3 // 2 1 3 // 3 2 1 // 本题为考试多行输入输出规范示例,无需提交,不计分。 // 答案 // import java.util.Scanner; // public class Main { // public static void main(String[] args) { // Scanner sc = new Scanner(System.in); // int n = sc.nextInt(); // int ans = 0, x; // for(int i = 0; i < n; i++){ // for(int j = 0; j < n; j++){ // x = sc.nextInt(); // ans += x; // } // } // System.out.println(ans); // } // } import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; public class Mayi { // 题目描述:众所周知,在一些消费支付的场合中,往往有“支付宝九五折“的优惠。这天小苯来到了超市购买物品,一共有 // n种物品,每种物品只能购买一个,但有的物品支持优惠活动,有的并不支持。恰好本超市的结账是有“支付宝九五折”优惠的,小苯的支付宝余额还剩 // ん元,他想知道他仅使用支付宝进行支付的话,最多能买几件物的? // 输入描述:输入包含三行。第一行两个正整数n,h(1≤n≤ 10^5),(1≤k≤ 10^9)第二行包含 几 个正整数a;(1 ≤ a;≤ // 104)表示每个物品的价格.第三行一个长度为 7 的只含有0和 1的字符申,表示每个物品是否支持优惠。(如果是 1代表第:个物品支持优惠,否则不支持。) // 输出描述:输出一行一个整数表示答案 // 输入 // 5 9 // 3 4 2 3 1 // 11101 // 输出 // 4 // 说明 // 购买1,3,4,5号物 public static void main1(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[] prices = new int[n]; for (int i = 0; i < n; i++) { prices[i] = sc.nextInt(); } String discounts = sc.next(); // 初始化动态规划数组,所有值为最小可能值 int[] dp = new int[k+1]; for (int i = 0; i <= k; i++) { dp[i] = 0; // 初始状态:没有余额时,不能购买任何物品 } // 动态规划求解 for (int i = 0; i < n; i++) { int price = prices[i]; // 计算打折后的价格 int discountPrice = discounts.charAt(i) == '1' ? (int)Math.ceil(price * 0.95) : price; // 从大到小遍历所有余额 for (int j = k; j >= discountPrice; j--) { dp[j] = Math.max(dp[j], dp[j - discountPrice] + 1); // 比较不购买当前物品和购买当前物品的情况 } } // 输出最大购买物品数量 int maxItems = 0; for (int i = 0; i <= k; i++) { maxItems = Math.max(maxItems, dp[i]); } System.out.println(maxItems); } // 小红定义一个字符串的权值是:字符串辅音数量和元音数量的差的绝对值。例如,"arcaea"的权值是 2,因为有4个元音,2 // 个辅音,权值为|4-2l=2。现在小红拿到了一个字符串,她想把这个字符串切成两个非空字符串,需要满足两个字符串的权值相等。小红想知道,有多少种不同的切割方式?我们定义,元音有"aeiou"这五种,其余字母均为辅音。 // 输入 // arcaea // 输出 // 2 // 说明 // 方案 1:"a"和"rcaea",权值均为 1。 // 方案 2:"arcae"和"a”,权值均为 1。 public static void main2(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int n = s.length(); int[] vowelsPrefixSum = new int[n + 1]; int[] consonantsPrefixSum = new int[n + 1]; // 预计算前缀和 for (int i = 0; i < n; i++) { char c = s.charAt(i); vowelsPrefixSum[i + 1] = vowelsPrefixSum[i] + (isVowel(c) ? 1 : 0); consonantsPrefixSum[i + 1] = consonantsPrefixSum[i] + (isVowel(c) ? 0 : 1); } int count = 0; // 对于每个可能的分割点 for (int i = 1; i < n; i++) { int leftVowels = vowelsPrefixSum[i]; int leftConsonants = consonantsPrefixSum[i]; int rightVowels = vowelsPrefixSum[n] - leftVowels; int rightConsonants = consonantsPrefixSum[n] - leftConsonants; if (Math.abs(leftVowels - leftConsonants) == Math.abs(rightVowels - rightConsonants)) { count++; } } System.out.println(count); sc.close(); } private static boolean isVowel(char c) { return "aeiou".indexOf(c) >= 0; } // 小苯有一个长度为 n 的数组 a。他想要使得所有 // a的最大公因子是一个素数。即:gcd(a1,a2,..,an)是一个素数。他可以对数组进行任意次操作。具体的:每次操作,他会选择i,j两个下标,同时执行:ai=ai+2,aj=aj-2.请问他是否有可能在任意次操作内将数组变成符合要求的,如果可以,请输出所有可能的最大公因数。注意,这里要保证 // a;在操作后仍然是正数,即不能选择 aj< 2. // 输入描述:输入包含两行。第一行一个正整数n(2 ≤n ≤2x10')表示数组长度。第二行 n 个正整数a;(1 ≤ ai < 10“)表示这个数组。 // 输出描述:输入包含一行或两行。如果可以输出“YES”,否则输出“NO(不含双引号)如果答案为“YES”,则第二行按照升序输出所有可行的数组 gcd。 // 输入 // 4 // 1 3 5 9 // 输出 // YES // 3 // 说明 // 可以选择一次i= 1,j=3,这样一来数组变成:[3,3,3,9],gcd=3可以证明只有 3 这一个答案。 // 输入 // 4 // 2 2 2 2 // 输出 // YES // 2 // 输入 // 5 // 2 4 5 6 8 // 输出 // NO }
ddeng36/interview
JVA/ACM/面试/Mayi.java
2,104
// 对于每个可能的分割点
line_comment
zh-cn
package JVA.ACM.面试; //以下是ACM模式 // 单行输入 // 输入 // 1 1 // 输出 // 2 // import java.util.Scanner; // public class Main { // public static void main(String[] args) { // Scanner in = new Scanner(System.in); // while (in.hasNextInt()) {// 注意,如果输入是多个测试用例,请通过while循环处理多个测试用例 // int a = in.nextInt(); // int b = in.nextInt(); // System.out.println(a + b); // } // } // } // 多行输入 // 输入描述:输入一个n,表示阶数,然后输入n行n列的矩阵 // 输除描述:输出一个词证书表示n阶方阵的和 // 输入 // 3 // 1 2 3 // 2 1 3 // 3 2 1 // 本题为考试多行输入输出规范示例,无需提交,不计分。 // 答案 // import java.util.Scanner; // public class Main { // public static void main(String[] args) { // Scanner sc = new Scanner(System.in); // int n = sc.nextInt(); // int ans = 0, x; // for(int i = 0; i < n; i++){ // for(int j = 0; j < n; j++){ // x = sc.nextInt(); // ans += x; // } // } // System.out.println(ans); // } // } import java.util.Scanner; import java.util.ArrayList; import java.util.Collections; public class Mayi { // 题目描述:众所周知,在一些消费支付的场合中,往往有“支付宝九五折“的优惠。这天小苯来到了超市购买物品,一共有 // n种物品,每种物品只能购买一个,但有的物品支持优惠活动,有的并不支持。恰好本超市的结账是有“支付宝九五折”优惠的,小苯的支付宝余额还剩 // ん元,他想知道他仅使用支付宝进行支付的话,最多能买几件物的? // 输入描述:输入包含三行。第一行两个正整数n,h(1≤n≤ 10^5),(1≤k≤ 10^9)第二行包含 几 个正整数a;(1 ≤ a;≤ // 104)表示每个物品的价格.第三行一个长度为 7 的只含有0和 1的字符申,表示每个物品是否支持优惠。(如果是 1代表第:个物品支持优惠,否则不支持。) // 输出描述:输出一行一个整数表示答案 // 输入 // 5 9 // 3 4 2 3 1 // 11101 // 输出 // 4 // 说明 // 购买1,3,4,5号物 public static void main1(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int k = sc.nextInt(); int[] prices = new int[n]; for (int i = 0; i < n; i++) { prices[i] = sc.nextInt(); } String discounts = sc.next(); // 初始化动态规划数组,所有值为最小可能值 int[] dp = new int[k+1]; for (int i = 0; i <= k; i++) { dp[i] = 0; // 初始状态:没有余额时,不能购买任何物品 } // 动态规划求解 for (int i = 0; i < n; i++) { int price = prices[i]; // 计算打折后的价格 int discountPrice = discounts.charAt(i) == '1' ? (int)Math.ceil(price * 0.95) : price; // 从大到小遍历所有余额 for (int j = k; j >= discountPrice; j--) { dp[j] = Math.max(dp[j], dp[j - discountPrice] + 1); // 比较不购买当前物品和购买当前物品的情况 } } // 输出最大购买物品数量 int maxItems = 0; for (int i = 0; i <= k; i++) { maxItems = Math.max(maxItems, dp[i]); } System.out.println(maxItems); } // 小红定义一个字符串的权值是:字符串辅音数量和元音数量的差的绝对值。例如,"arcaea"的权值是 2,因为有4个元音,2 // 个辅音,权值为|4-2l=2。现在小红拿到了一个字符串,她想把这个字符串切成两个非空字符串,需要满足两个字符串的权值相等。小红想知道,有多少种不同的切割方式?我们定义,元音有"aeiou"这五种,其余字母均为辅音。 // 输入 // arcaea // 输出 // 2 // 说明 // 方案 1:"a"和"rcaea",权值均为 1。 // 方案 2:"arcae"和"a”,权值均为 1。 public static void main2(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.next(); int n = s.length(); int[] vowelsPrefixSum = new int[n + 1]; int[] consonantsPrefixSum = new int[n + 1]; // 预计算前缀和 for (int i = 0; i < n; i++) { char c = s.charAt(i); vowelsPrefixSum[i + 1] = vowelsPrefixSum[i] + (isVowel(c) ? 1 : 0); consonantsPrefixSum[i + 1] = consonantsPrefixSum[i] + (isVowel(c) ? 0 : 1); } int count = 0; // 对于 <SUF> for (int i = 1; i < n; i++) { int leftVowels = vowelsPrefixSum[i]; int leftConsonants = consonantsPrefixSum[i]; int rightVowels = vowelsPrefixSum[n] - leftVowels; int rightConsonants = consonantsPrefixSum[n] - leftConsonants; if (Math.abs(leftVowels - leftConsonants) == Math.abs(rightVowels - rightConsonants)) { count++; } } System.out.println(count); sc.close(); } private static boolean isVowel(char c) { return "aeiou".indexOf(c) >= 0; } // 小苯有一个长度为 n 的数组 a。他想要使得所有 // a的最大公因子是一个素数。即:gcd(a1,a2,..,an)是一个素数。他可以对数组进行任意次操作。具体的:每次操作,他会选择i,j两个下标,同时执行:ai=ai+2,aj=aj-2.请问他是否有可能在任意次操作内将数组变成符合要求的,如果可以,请输出所有可能的最大公因数。注意,这里要保证 // a;在操作后仍然是正数,即不能选择 aj< 2. // 输入描述:输入包含两行。第一行一个正整数n(2 ≤n ≤2x10')表示数组长度。第二行 n 个正整数a;(1 ≤ ai < 10“)表示这个数组。 // 输出描述:输入包含一行或两行。如果可以输出“YES”,否则输出“NO(不含双引号)如果答案为“YES”,则第二行按照升序输出所有可行的数组 gcd。 // 输入 // 4 // 1 3 5 9 // 输出 // YES // 3 // 说明 // 可以选择一次i= 1,j=3,这样一来数组变成:[3,3,3,9],gcd=3可以证明只有 3 这一个答案。 // 输入 // 4 // 2 2 2 2 // 输出 // YES // 2 // 输入 // 5 // 2 4 5 6 8 // 输出 // NO }
false
1,895
8
2,104
9
2,040
7
2,104
9
2,788
14
false
false
false
false
false
true
32236_3
package com.jhs.stocklinkscrool; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; /** * 之前都是写在Activity中,感觉代码好多,还是封装到这里好 */ public class UtilTools { /** * 计算ListView的高度 * * @param listView */ public static void setListViewHeightBasedOnChildren(ListView listView) { /** * getAdapter这个方法主要是为了获取到ListView的数据条数,所以设置之前必须设置Adapter */ ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0, len = listAdapter.getCount(); i < len; i++) { View listItem = listAdapter.getView(i, null, listView); //计算每一项的高度 listItem.measure(0, 0); //总高度 totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); //真正的高度需要加上分割线的高度 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } }
ddssingsong/StockLinkScrool
app/src/main/java/com/jhs/stocklinkscrool/UtilTools.java
309
//计算每一项的高度
line_comment
zh-cn
package com.jhs.stocklinkscrool; import android.view.View; import android.view.ViewGroup; import android.widget.ListAdapter; import android.widget.ListView; /** * 之前都是写在Activity中,感觉代码好多,还是封装到这里好 */ public class UtilTools { /** * 计算ListView的高度 * * @param listView */ public static void setListViewHeightBasedOnChildren(ListView listView) { /** * getAdapter这个方法主要是为了获取到ListView的数据条数,所以设置之前必须设置Adapter */ ListAdapter listAdapter = listView.getAdapter(); if (listAdapter == null) { return; } int totalHeight = 0; for (int i = 0, len = listAdapter.getCount(); i < len; i++) { View listItem = listAdapter.getView(i, null, listView); //计算 <SUF> listItem.measure(0, 0); //总高度 totalHeight += listItem.getMeasuredHeight(); } ViewGroup.LayoutParams params = listView.getLayoutParams(); //真正的高度需要加上分割线的高度 params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); listView.setLayoutParams(params); } }
false
267
5
310
7
313
5
309
7
393
9
false
false
false
false
false
true
13784_10
package com.dds.skywebrtc; import android.content.Context; import android.util.Log; import com.dds.skywebrtc.exception.NotInitializedException; import com.dds.skywebrtc.inter.ISkyEvent; /** * main control class * Created by dds on 2019/8/19. */ public class SkyEngineKit { private final static String TAG = "AVEngineKit"; private static SkyEngineKit avEngineKit; private CallSession mCurrentCallSession; private ISkyEvent mEvent; private boolean isAudioOnly = false; public static SkyEngineKit Instance() { SkyEngineKit var; if ((var = avEngineKit) != null) { return var; } else { throw new NotInitializedException(); } } /** * SDK Enter init Engine */ public static void init(ISkyEvent iSocketEvent) { if (avEngineKit == null) { avEngineKit = new SkyEngineKit(); avEngineKit.mEvent = iSocketEvent; } } public void sendRefuseOnPermissionDenied(String room, String inviteId) { // 未初始化 if (avEngineKit == null) { Log.e(TAG, "startOutCall error,please init first"); return; } if (mCurrentCallSession != null) { endCall(); } else { avEngineKit.mEvent.sendRefuse(room, inviteId, EnumType.RefuseType.Hangup.ordinal()); } } public void sendDisconnected(String room, String toId, boolean isCrashed) { // 未初始化 if (avEngineKit == null) { Log.e(TAG, "startOutCall error,please init first"); return; } avEngineKit.mEvent.sendDisConnect(room, toId, isCrashed); } // 拨打电话 public boolean startOutCall(Context context, final String room, final String targetId, final boolean audioOnly) { // 未初始化 if (avEngineKit == null) { Log.e(TAG, "startOutCall error,please init first"); return false; } // 忙线中 if (mCurrentCallSession != null && mCurrentCallSession.getState() != EnumType.CallState.Idle) { Log.i(TAG, "startCall error,currentCallSession is exist"); return false; } isAudioOnly = audioOnly; // 初始化会话 mCurrentCallSession = new CallSession(context, room, audioOnly, mEvent); mCurrentCallSession.setTargetId(targetId); mCurrentCallSession.setIsComing(false); mCurrentCallSession.setCallState(EnumType.CallState.Outgoing); // 创建房间 mCurrentCallSession.createHome(room, 2); return true; } // 接听电话 public boolean startInCall(Context context, final String room, final String targetId, final boolean audioOnly) { if (avEngineKit == null) { Log.e(TAG, "startInCall error,init is not set"); return false; } // 忙线中 if (mCurrentCallSession != null && mCurrentCallSession.getState() != EnumType.CallState.Idle) { // 发送->忙线中... Log.i(TAG, "startInCall busy,currentCallSession is exist,start sendBusyRefuse!"); mCurrentCallSession.sendBusyRefuse(room, targetId); return false; } this.isAudioOnly = audioOnly; // 初始化会话 mCurrentCallSession = new CallSession(context, room, audioOnly, mEvent); mCurrentCallSession.setTargetId(targetId); mCurrentCallSession.setIsComing(true); mCurrentCallSession.setCallState(EnumType.CallState.Incoming); // 开始响铃并回复 mCurrentCallSession.shouldStartRing(); mCurrentCallSession.sendRingBack(targetId, room); return true; } // 挂断会话 public void endCall() { Log.d(TAG, "endCall mCurrentCallSession != null is " + (mCurrentCallSession != null)); if (mCurrentCallSession != null) { // 停止响铃 mCurrentCallSession.shouldStopRing(); if (mCurrentCallSession.isComing()) { if (mCurrentCallSession.getState() == EnumType.CallState.Incoming) { // 接收到邀请,还没同意,发送拒绝 mCurrentCallSession.sendRefuse(); } else { // 已经接通,挂断电话 mCurrentCallSession.leave(); } } else { if (mCurrentCallSession.getState() == EnumType.CallState.Outgoing) { mCurrentCallSession.sendCancel(); } else { // 已经接通,挂断电话 mCurrentCallSession.leave(); } } mCurrentCallSession.setCallState(EnumType.CallState.Idle); } } // 加入房间 public void joinRoom(Context context, String room) { if (avEngineKit == null) { Log.e(TAG, "joinRoom error,init is not set"); return; } // 忙线中 if (mCurrentCallSession != null && mCurrentCallSession.getState() != EnumType.CallState.Idle) { Log.e(TAG, "joinRoom error,currentCallSession is exist"); return; } mCurrentCallSession = new CallSession(context, room, false, mEvent); mCurrentCallSession.setIsComing(true); mCurrentCallSession.joinHome(room); } public void createAndJoinRoom(Context context, String room) { if (avEngineKit == null) { Log.e(TAG, "joinRoom error,init is not set"); return; } // 忙线中 if (mCurrentCallSession != null && mCurrentCallSession.getState() != EnumType.CallState.Idle) { Log.e(TAG, "joinRoom error,currentCallSession is exist"); return; } mCurrentCallSession = new CallSession(context, room, false, mEvent); mCurrentCallSession.setIsComing(false); mCurrentCallSession.createHome(room, 9); } // 离开房间 public void leaveRoom() { if (avEngineKit == null) { Log.e(TAG, "leaveRoom error,init is not set"); return; } if (mCurrentCallSession != null) { mCurrentCallSession.leave(); mCurrentCallSession.setCallState(EnumType.CallState.Idle); } } public boolean isAudioOnly() { return isAudioOnly; } // 获取对话实例 public CallSession getCurrentSession() { return this.mCurrentCallSession; } }
ddssingsong/webrtc_android
rtc-chat/src/main/java/com/dds/skywebrtc/SkyEngineKit.java
1,579
// 忙线中
line_comment
zh-cn
package com.dds.skywebrtc; import android.content.Context; import android.util.Log; import com.dds.skywebrtc.exception.NotInitializedException; import com.dds.skywebrtc.inter.ISkyEvent; /** * main control class * Created by dds on 2019/8/19. */ public class SkyEngineKit { private final static String TAG = "AVEngineKit"; private static SkyEngineKit avEngineKit; private CallSession mCurrentCallSession; private ISkyEvent mEvent; private boolean isAudioOnly = false; public static SkyEngineKit Instance() { SkyEngineKit var; if ((var = avEngineKit) != null) { return var; } else { throw new NotInitializedException(); } } /** * SDK Enter init Engine */ public static void init(ISkyEvent iSocketEvent) { if (avEngineKit == null) { avEngineKit = new SkyEngineKit(); avEngineKit.mEvent = iSocketEvent; } } public void sendRefuseOnPermissionDenied(String room, String inviteId) { // 未初始化 if (avEngineKit == null) { Log.e(TAG, "startOutCall error,please init first"); return; } if (mCurrentCallSession != null) { endCall(); } else { avEngineKit.mEvent.sendRefuse(room, inviteId, EnumType.RefuseType.Hangup.ordinal()); } } public void sendDisconnected(String room, String toId, boolean isCrashed) { // 未初始化 if (avEngineKit == null) { Log.e(TAG, "startOutCall error,please init first"); return; } avEngineKit.mEvent.sendDisConnect(room, toId, isCrashed); } // 拨打电话 public boolean startOutCall(Context context, final String room, final String targetId, final boolean audioOnly) { // 未初始化 if (avEngineKit == null) { Log.e(TAG, "startOutCall error,please init first"); return false; } // 忙线中 if (mCurrentCallSession != null && mCurrentCallSession.getState() != EnumType.CallState.Idle) { Log.i(TAG, "startCall error,currentCallSession is exist"); return false; } isAudioOnly = audioOnly; // 初始化会话 mCurrentCallSession = new CallSession(context, room, audioOnly, mEvent); mCurrentCallSession.setTargetId(targetId); mCurrentCallSession.setIsComing(false); mCurrentCallSession.setCallState(EnumType.CallState.Outgoing); // 创建房间 mCurrentCallSession.createHome(room, 2); return true; } // 接听电话 public boolean startInCall(Context context, final String room, final String targetId, final boolean audioOnly) { if (avEngineKit == null) { Log.e(TAG, "startInCall error,init is not set"); return false; } // 忙线 <SUF> if (mCurrentCallSession != null && mCurrentCallSession.getState() != EnumType.CallState.Idle) { // 发送->忙线中... Log.i(TAG, "startInCall busy,currentCallSession is exist,start sendBusyRefuse!"); mCurrentCallSession.sendBusyRefuse(room, targetId); return false; } this.isAudioOnly = audioOnly; // 初始化会话 mCurrentCallSession = new CallSession(context, room, audioOnly, mEvent); mCurrentCallSession.setTargetId(targetId); mCurrentCallSession.setIsComing(true); mCurrentCallSession.setCallState(EnumType.CallState.Incoming); // 开始响铃并回复 mCurrentCallSession.shouldStartRing(); mCurrentCallSession.sendRingBack(targetId, room); return true; } // 挂断会话 public void endCall() { Log.d(TAG, "endCall mCurrentCallSession != null is " + (mCurrentCallSession != null)); if (mCurrentCallSession != null) { // 停止响铃 mCurrentCallSession.shouldStopRing(); if (mCurrentCallSession.isComing()) { if (mCurrentCallSession.getState() == EnumType.CallState.Incoming) { // 接收到邀请,还没同意,发送拒绝 mCurrentCallSession.sendRefuse(); } else { // 已经接通,挂断电话 mCurrentCallSession.leave(); } } else { if (mCurrentCallSession.getState() == EnumType.CallState.Outgoing) { mCurrentCallSession.sendCancel(); } else { // 已经接通,挂断电话 mCurrentCallSession.leave(); } } mCurrentCallSession.setCallState(EnumType.CallState.Idle); } } // 加入房间 public void joinRoom(Context context, String room) { if (avEngineKit == null) { Log.e(TAG, "joinRoom error,init is not set"); return; } // 忙线中 if (mCurrentCallSession != null && mCurrentCallSession.getState() != EnumType.CallState.Idle) { Log.e(TAG, "joinRoom error,currentCallSession is exist"); return; } mCurrentCallSession = new CallSession(context, room, false, mEvent); mCurrentCallSession.setIsComing(true); mCurrentCallSession.joinHome(room); } public void createAndJoinRoom(Context context, String room) { if (avEngineKit == null) { Log.e(TAG, "joinRoom error,init is not set"); return; } // 忙线中 if (mCurrentCallSession != null && mCurrentCallSession.getState() != EnumType.CallState.Idle) { Log.e(TAG, "joinRoom error,currentCallSession is exist"); return; } mCurrentCallSession = new CallSession(context, room, false, mEvent); mCurrentCallSession.setIsComing(false); mCurrentCallSession.createHome(room, 9); } // 离开房间 public void leaveRoom() { if (avEngineKit == null) { Log.e(TAG, "leaveRoom error,init is not set"); return; } if (mCurrentCallSession != null) { mCurrentCallSession.leave(); mCurrentCallSession.setCallState(EnumType.CallState.Idle); } } public boolean isAudioOnly() { return isAudioOnly; } // 获取对话实例 public CallSession getCurrentSession() { return this.mCurrentCallSession; } }
false
1,454
5
1,579
6
1,681
5
1,579
6
1,924
7
false
false
false
false
false
true
53218_0
package com.wjj.numberdemo.activity; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.wjj.numberdemo.R; import com.wjj.numberdemo.bean.Book; import com.wjj.numberdemo.imp.ReadImp; import com.wjj.numberdemo.listener.CommunicateListener; import com.wjj.numberdemo.thread.ReadThread; import com.wjj.numberdemo.widget.ReadBookTextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener, CommunicateListener { private Button read_btn, send_text; private ReadImp readImp; private EditText edit_baobao; private ReadThread readThread; private Thread thread; private volatile Book<String> book; private ReadBookTextView read_text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { Log.d("--->", "主线程的 ID 是 " + Thread.currentThread().getId()); //给书赋值 addBook(); readImp = new ReadImp(book); readImp.setMessager(this); readThread = new ReadThread(book, readImp); thread = new Thread(readThread); initWidget(); } @Override protected void onStart() { super.onStart(); thread.start(); Log.d("--->", "开启的线程 ID 是 " + thread.getId()); } @Override protected void onStop() { super.onStop(); thread.interrupt(); } @Override protected void onDestroy() { super.onDestroy(); thread = null; readThread = null; } private void initWidget() { read_text = (ReadBookTextView) findViewById(R.id.read_text); read_btn = (Button) findViewById(R.id.read_btn); send_text = (Button) findViewById(R.id.send_text); edit_baobao = (EditText) findViewById(R.id.edit_baobao); send_text.setOnClickListener(this); read_btn.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.read_btn: read_text.setText(""); thread.interrupt(); break; case R.id.send_text: if (edit_baobao.getText().toString().trim().length() > 0) { read_text.setText(edit_baobao.getText().toString().trim()); } break; } } @Override public void setMsg(Message msg) { read_text.setText("补充内容是 " + msg.obj.toString()); } /* * 模拟数据 * */ private Book<String> addBook() { book = new Book<>(); book.setBookMoreMSG("神秘的反派角色"); book.setName("奥特曼打怪兽"); book.setPageCount(15); book.setNowPage(0); return book; } }
ddwhan0123/BlogSample
NumberDemo/app/src/main/java/com/wjj/numberdemo/activity/MainActivity.java
776
//给书赋值
line_comment
zh-cn
package com.wjj.numberdemo.activity; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.wjj.numberdemo.R; import com.wjj.numberdemo.bean.Book; import com.wjj.numberdemo.imp.ReadImp; import com.wjj.numberdemo.listener.CommunicateListener; import com.wjj.numberdemo.thread.ReadThread; import com.wjj.numberdemo.widget.ReadBookTextView; public class MainActivity extends AppCompatActivity implements View.OnClickListener, CommunicateListener { private Button read_btn, send_text; private ReadImp readImp; private EditText edit_baobao; private ReadThread readThread; private Thread thread; private volatile Book<String> book; private ReadBookTextView read_text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); } private void init() { Log.d("--->", "主线程的 ID 是 " + Thread.currentThread().getId()); //给书 <SUF> addBook(); readImp = new ReadImp(book); readImp.setMessager(this); readThread = new ReadThread(book, readImp); thread = new Thread(readThread); initWidget(); } @Override protected void onStart() { super.onStart(); thread.start(); Log.d("--->", "开启的线程 ID 是 " + thread.getId()); } @Override protected void onStop() { super.onStop(); thread.interrupt(); } @Override protected void onDestroy() { super.onDestroy(); thread = null; readThread = null; } private void initWidget() { read_text = (ReadBookTextView) findViewById(R.id.read_text); read_btn = (Button) findViewById(R.id.read_btn); send_text = (Button) findViewById(R.id.send_text); edit_baobao = (EditText) findViewById(R.id.edit_baobao); send_text.setOnClickListener(this); read_btn.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.read_btn: read_text.setText(""); thread.interrupt(); break; case R.id.send_text: if (edit_baobao.getText().toString().trim().length() > 0) { read_text.setText(edit_baobao.getText().toString().trim()); } break; } } @Override public void setMsg(Message msg) { read_text.setText("补充内容是 " + msg.obj.toString()); } /* * 模拟数据 * */ private Book<String> addBook() { book = new Book<>(); book.setBookMoreMSG("神秘的反派角色"); book.setName("奥特曼打怪兽"); book.setPageCount(15); book.setNowPage(0); return book; } }
false
638
5
776
4
836
4
776
4
923
7
false
false
false
false
false
true
13628_3
package com.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.bean.Store; @Repository public interface StoreMapper { List<Store> QueryByNCP(@Param("drugname")String drugname,@Param("changshang")String changshang,@Param("pihao")String pihao);//根据name,changshang,pihao查询 String QueryBpByNCP(@Param("drugname")String drugname,@Param("changshang")String changshang,@Param("pihao")String pihao);//根据name,changshang,pihao查询beginprice void AddStore(Store store); void UpdateStoreCount(@Param("count")String count,@Param("drugname")String drugname,@Param("changshang")String changshang,@Param("pihao")String pihao); void DeleteStore(@Param("drugname")String drugname,@Param("changshang")String changshang,@Param("pihao")String pihao); List<Store> GetAllStore(); List<Store> QueryBySTiao(String tiao); List<Store> QueryBySName(String name); //根据drugname模糊查询 /** * 用于缺货信息那边 */ void DeleteCountZero(); /** * 库存预警 * @param c (预警的数量) * @return */ List<Store> StoreYJ(int c); /** * 使用时这个方法时注意,把原批号pihao就赋值给Store.guige, * 然后把要改的批号pihao赋值给Store.pihao */ void UpdateStoreSomeInfo(Store store); }
deathbreak/drug
src/main/java/com/mapper/StoreMapper.java
422
/** * 用于缺货信息那边 */
block_comment
zh-cn
package com.mapper; import java.util.List; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import com.bean.Store; @Repository public interface StoreMapper { List<Store> QueryByNCP(@Param("drugname")String drugname,@Param("changshang")String changshang,@Param("pihao")String pihao);//根据name,changshang,pihao查询 String QueryBpByNCP(@Param("drugname")String drugname,@Param("changshang")String changshang,@Param("pihao")String pihao);//根据name,changshang,pihao查询beginprice void AddStore(Store store); void UpdateStoreCount(@Param("count")String count,@Param("drugname")String drugname,@Param("changshang")String changshang,@Param("pihao")String pihao); void DeleteStore(@Param("drugname")String drugname,@Param("changshang")String changshang,@Param("pihao")String pihao); List<Store> GetAllStore(); List<Store> QueryBySTiao(String tiao); List<Store> QueryBySName(String name); //根据drugname模糊查询 /** * 用于缺 <SUF>*/ void DeleteCountZero(); /** * 库存预警 * @param c (预警的数量) * @return */ List<Store> StoreYJ(int c); /** * 使用时这个方法时注意,把原批号pihao就赋值给Store.guige, * 然后把要改的批号pihao赋值给Store.pihao */ void UpdateStoreSomeInfo(Store store); }
false
377
12
422
12
398
12
422
12
512
20
false
false
false
false
false
true
31597_0
import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; import java.io.IOException; import java.util.List; import java.util.Iterator; public class MainEval { public static void main(String[] args) throws IOException { CharStream input = CharStreams.fromStream(System.in); Lexer lexer = new ExprLexer(input); TokenStream tokens = new CommonTokenStream(lexer); ExprParser parser = new ExprParser(tokens); parser.setErrorHandler(new BailErrorStrategy()); // 设置错误处理 ParseTree tree = parser.expr(); // 取得一棵以 expr 为根的 AST EvalVisitor visitor = new EvalVisitor(); System.out.println(tree.accept(visitor)); } } class EvalVisitor extends ExprBaseVisitor<Integer> { @Override public Integer visitAdd(ExprParser.AddContext ctx) { // ctx.add() 返回 add 子结点。 if (ctx.add() == null) // 这个结点是 add: mul; return visitChildren(ctx); // 这个结点是 add: add op=(Add|Sub) mul; int lhs = ctx.add().accept(this); int rhs = ctx.mul().accept(this); // 访问 op 子结点不是 ctx.op() 而是 ctx.op. // 用 .getText() 取得字符串 switch (ctx.op.getText()) { case "+": return lhs + rhs; case "-": return lhs - rhs; } return 0; // unreachable } @Override public Integer visitMul(ExprParser.MulContext ctx) { // 包含所有 atom 子结点 List<ExprParser.AtomContext> atoms = ctx.atom(); List<ExprParser.MulOpContext> ops = ctx.mulOp(); int s = atoms.get(0).accept(this); Iterator<ExprParser.AtomContext> itAtom = atoms.iterator(); Iterator<ExprParser.MulOpContext> itOps = ops.iterator(); for (itAtom.next(); itAtom.hasNext();) { // 使用 .getText() 取得字符串 if (itOps.next().getText().equals("*")) s *= itAtom.next().accept(this); else s /= itAtom.next().accept(this); } return s; } @Override public Integer visitAtomParen(ExprParser.AtomParenContext ctx) { // visitChilren 返回的是 ctx.Rparen().accept(this) return ctx.expr().accept(this); } @Override public Integer visitAtomInteger(ExprParser.AtomIntegerContext ctx) { return Integer.parseInt(ctx.Integer().getText()); } }
decaf-lang/minidecaf-tutorial-code
step1/MainEval.java
622
// 设置错误处理
line_comment
zh-cn
import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; import java.io.IOException; import java.util.List; import java.util.Iterator; public class MainEval { public static void main(String[] args) throws IOException { CharStream input = CharStreams.fromStream(System.in); Lexer lexer = new ExprLexer(input); TokenStream tokens = new CommonTokenStream(lexer); ExprParser parser = new ExprParser(tokens); parser.setErrorHandler(new BailErrorStrategy()); // 设置 <SUF> ParseTree tree = parser.expr(); // 取得一棵以 expr 为根的 AST EvalVisitor visitor = new EvalVisitor(); System.out.println(tree.accept(visitor)); } } class EvalVisitor extends ExprBaseVisitor<Integer> { @Override public Integer visitAdd(ExprParser.AddContext ctx) { // ctx.add() 返回 add 子结点。 if (ctx.add() == null) // 这个结点是 add: mul; return visitChildren(ctx); // 这个结点是 add: add op=(Add|Sub) mul; int lhs = ctx.add().accept(this); int rhs = ctx.mul().accept(this); // 访问 op 子结点不是 ctx.op() 而是 ctx.op. // 用 .getText() 取得字符串 switch (ctx.op.getText()) { case "+": return lhs + rhs; case "-": return lhs - rhs; } return 0; // unreachable } @Override public Integer visitMul(ExprParser.MulContext ctx) { // 包含所有 atom 子结点 List<ExprParser.AtomContext> atoms = ctx.atom(); List<ExprParser.MulOpContext> ops = ctx.mulOp(); int s = atoms.get(0).accept(this); Iterator<ExprParser.AtomContext> itAtom = atoms.iterator(); Iterator<ExprParser.MulOpContext> itOps = ops.iterator(); for (itAtom.next(); itAtom.hasNext();) { // 使用 .getText() 取得字符串 if (itOps.next().getText().equals("*")) s *= itAtom.next().accept(this); else s /= itAtom.next().accept(this); } return s; } @Override public Integer visitAtomParen(ExprParser.AtomParenContext ctx) { // visitChilren 返回的是 ctx.Rparen().accept(this) return ctx.expr().accept(this); } @Override public Integer visitAtomInteger(ExprParser.AtomIntegerContext ctx) { return Integer.parseInt(ctx.Integer().getText()); } }
false
570
4
622
4
659
4
622
4
770
10
false
false
false
false
false
true
24036_2
package com.geekbang.learnlock.locksync; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class WorkWithLock implements Runnable { // TODO ReentrantLock 顾名思义,就是可以重复进入的锁,说人话就是一个线程获取到锁之后,可以再一次次的获取锁,ReentrantLock只是给它来个计数而已。而第一次没有获取锁的线程,则无法进入锁 // TODO 这个锁的操作是对标 synchronized 关键字的功能的。 private Lock lock; public WorkWithLock(Lock lock) { this.lock = lock; } @Override public void run() { while (true) { // TODO 尝试获取锁,可以加等待超时时间 // TODO TimeUnit 是枚举一个很优雅的用法 try { // try { // lock.lock(); // // // }finally { // lock.unlock(); // } if (lock.tryLock(1, TimeUnit.SECONDS)) { try { printLockStatus("start"); // TODO 必须再用 try-finally 确保可以 release 锁 // TODO 这感觉是不是像极了 synchronized process1(); } finally { lock.unlock(); printLockStatus("finished"); } } else { printLockFailure(); } } catch (InterruptedException e) { e.printStackTrace(); } } } private void process1() { try { // TODO try里第一行是lock lock.lock(); printLockStatus("process1"); process2(); } finally { // TODO 一定要在finally里第一行unlock lock.unlock(); printLockStatus("process1 finish"); } } private void process2() { try { lock.lock(); printLockStatus("process2"); process3(); } finally { lock.unlock(); printLockStatus("process2 finish"); } } private void process3() { try { lock.lock(); printLockStatus("process3"); Thread.sleep(TimeUnit.SECONDS.toMillis(3)); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); printLockStatus("process3 finish"); } } private void printLockStatus(String phase) { System.out.println("Thread:" + Thread.currentThread().getName() + " " + phase + " hold count = " + ((ReentrantLock) lock).getHoldCount()); } private void printLockFailure() { System.out.println(Thread.currentThread().getName() + " failed to get lock"); } }
deepnighttwo/LetsJava
第五章 Java 中的线程/15. concurrent 包中的锁/code/src/com/geekbang/learnlock/locksync/WorkWithLock.java
631
// TODO 尝试获取锁,可以加等待超时时间
line_comment
zh-cn
package com.geekbang.learnlock.locksync; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class WorkWithLock implements Runnable { // TODO ReentrantLock 顾名思义,就是可以重复进入的锁,说人话就是一个线程获取到锁之后,可以再一次次的获取锁,ReentrantLock只是给它来个计数而已。而第一次没有获取锁的线程,则无法进入锁 // TODO 这个锁的操作是对标 synchronized 关键字的功能的。 private Lock lock; public WorkWithLock(Lock lock) { this.lock = lock; } @Override public void run() { while (true) { // TO <SUF> // TODO TimeUnit 是枚举一个很优雅的用法 try { // try { // lock.lock(); // // // }finally { // lock.unlock(); // } if (lock.tryLock(1, TimeUnit.SECONDS)) { try { printLockStatus("start"); // TODO 必须再用 try-finally 确保可以 release 锁 // TODO 这感觉是不是像极了 synchronized process1(); } finally { lock.unlock(); printLockStatus("finished"); } } else { printLockFailure(); } } catch (InterruptedException e) { e.printStackTrace(); } } } private void process1() { try { // TODO try里第一行是lock lock.lock(); printLockStatus("process1"); process2(); } finally { // TODO 一定要在finally里第一行unlock lock.unlock(); printLockStatus("process1 finish"); } } private void process2() { try { lock.lock(); printLockStatus("process2"); process3(); } finally { lock.unlock(); printLockStatus("process2 finish"); } } private void process3() { try { lock.lock(); printLockStatus("process3"); Thread.sleep(TimeUnit.SECONDS.toMillis(3)); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); printLockStatus("process3 finish"); } } private void printLockStatus(String phase) { System.out.println("Thread:" + Thread.currentThread().getName() + " " + phase + " hold count = " + ((ReentrantLock) lock).getHoldCount()); } private void printLockFailure() { System.out.println(Thread.currentThread().getName() + " failed to get lock"); } }
false
581
14
631
12
676
12
631
12
847
24
false
false
false
false
false
true
45848_64
import com.TreeNode; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.*; import java.util.stream.*; import java.util.stream.Collectors; import java.util.HashSet; import java.util.Set; import static java.util.stream.Collectors.toMap; public class cmp { public static class Solution { // public String digitSum(String s, int k) { // int n = s.length(), cur = 0; // if (n <= k) return s; // String ns = ""; // for (int i = 0; i < n; i += k) { // cur = 0; // for (int j = i; j < i+k && j < n; j++) // cur += s.charAt(j) - '0'; // ns += String.valueOf(cur); // } // if (ns.length() <= k) return ns; // return digitSum(ns, k); // } // int getSum(String t) { // int n = t.length(), ans = 0; // char [] s = t.toCharArray(); // for (char c : s) // ans += c - '0'; // return ans; // } // public int minimumRounds(int[] t) { // int n = t.length, cnt = 0; // Map<Integer, Integer> m = new HashMap<>(); // for (int v : t) // m.put(v, m.getOrDefault(v, 0) + 1); // for (Integer v : m.values()) {// 这样的先行遍历一遍排查会浪费时间吗? // System.out.println("\n v: " + v); // // if (v % 3 != 0 && v % 3 % 2 != 0 && v % 2 != 0) return -1; // 这条件不对呀 // if (v == 1) return -1; // if (v % 3 == 0) cnt += v / 3; // else if (v % 3 != 0) // cnt += v / 3 + 1; // else cnt += v / 2; // System.out.println("cnt: " + cnt); // } // return cnt; // } // public int longestPath(int[] p, String t) { // tle tle tle ??? // int n = t.length(); // if (n == 1) return 1; // s = t.toCharArray(); // adj = new ArrayList [n]; // for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); // for (int i = 0; i < n; i++) { // if (p[i] != -1) { // adj[p[i]].add(i); // 如果它有父节点,那么父节点的孩子链表加上当前的孩子 // adj[i].add(p[i]); // } // } // // for (int i = 0; i < n; i++) // 这里面有大量的重复计算, 这里这种方法就tle了 // // dfs(i, -1, 1); // // dist = new int [n]; // return max; // } // List<Integer> [] adj; // char [] s; // // int [] dist; // int max = 0; // void dijkstra(int u) { // Queue<int []> q = new PriorityQueue<>((x, y) -> x[1] - y[1]); // q.offer(new int [] {u, 1}); // while (!q.isEmpty()) { // 这里有点儿并不起来了:当求的是最长距离的时候,是不是应该用dfs记忆化搜索??? // int [] u = q.poll(); // // if (dist[u[0]] >= u[1]) continue; // 这里的剪枝忘记了。。。。。。 // } // } // void dfs(int u, int p, int cnt) { // if (adj[u].size() == 1 && adj[u].get(0) == p) { // 叶子节点,可以返回 // if (cnt > max) max = cnt; // return ; // } // for (int v : adj[u]) { // if (s[v] == s[u] || v == p) continue; // 是父节点已经访问过了,或者相邻的字符是一样的,路过 // dfs(v, u, cnt+1); // } // } public int maxTrailingZeros(int[][] a) { // 读不懂题目说的是什么意思 int m = a.length, n = a[0].length; int [][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // 这个,对于题目所要求的方向该如何处理,想得不是很清楚。。。。。。前缀和??? // 需要对每个格里的2与5质因子的个数分别作统计 int [][][] cnt = new int [m][n][2]; // 0: 2, 1: 5的统计个数 for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (a[i][j] % 2 == 0) cnt[i][j][0] = getCnt(a[i][j], 2); else if (a[i][j] % 5 == 0) cnt[i][j][1] = getCnt(a[i][j], 5); int [][] u = new int [m+1][n+1], d = new int [m+1][n+1], l = new int [m+1][n+1], r = new int [m+1][n+1]; // up, down, left, right: for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) u[i][j] = getCnt(a[i][j]) + u[i-1][j] + // 这里还要分别统计2和5的个数,感觉这个题的思路没有想对,稍微想复杂了点 // 昨天晚上最后一晚大街边的房间休息,没有休息好,今天感觉整个的状态不对,希望下个周的情况能够好点儿 } int getCnt(int v) { String t = String.valueOf(v); char [] s = t.toCharArray(); int n = t.length(), i = n-1, cnt = 0; while (i >= 0 && s[i] == '0') { cnt++; i--; } return cnt; } int getCnt(int v, int m) { int cnt = 0; if (v % m == 0) { while (v % m == 0) { cnt++; v /= m; } } return cnt; } } public static void main(String args[]) { Solution s = new Solution(); int [][] a = new int [][] {{23,17,15,3,20},{8,1,20,27,11},{9,4,6,2,21},{40,9,1,10,6},{22,7,4,5,3}}; int r = s.maxTrailingZeros(a); System.out.println("r: " + r); } } // ListNode head = new ListNode(a[0]); // head.buildList(head, a); // head.printList(head); // TreeNode root = new TreeNode(a[0]); // root.buildTree(root, a); // root.levelPrintTree(root);
deepwateroooMe/myAlgorithms
prevCmp/cmp_4_16_2.java
1,942
// 这个,对于题目所要求的方向该如何处理,想得不是很清楚。。。。。。前缀和???
line_comment
zh-cn
import com.TreeNode; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import java.util.*; import java.util.stream.*; import java.util.stream.Collectors; import java.util.HashSet; import java.util.Set; import static java.util.stream.Collectors.toMap; public class cmp { public static class Solution { // public String digitSum(String s, int k) { // int n = s.length(), cur = 0; // if (n <= k) return s; // String ns = ""; // for (int i = 0; i < n; i += k) { // cur = 0; // for (int j = i; j < i+k && j < n; j++) // cur += s.charAt(j) - '0'; // ns += String.valueOf(cur); // } // if (ns.length() <= k) return ns; // return digitSum(ns, k); // } // int getSum(String t) { // int n = t.length(), ans = 0; // char [] s = t.toCharArray(); // for (char c : s) // ans += c - '0'; // return ans; // } // public int minimumRounds(int[] t) { // int n = t.length, cnt = 0; // Map<Integer, Integer> m = new HashMap<>(); // for (int v : t) // m.put(v, m.getOrDefault(v, 0) + 1); // for (Integer v : m.values()) {// 这样的先行遍历一遍排查会浪费时间吗? // System.out.println("\n v: " + v); // // if (v % 3 != 0 && v % 3 % 2 != 0 && v % 2 != 0) return -1; // 这条件不对呀 // if (v == 1) return -1; // if (v % 3 == 0) cnt += v / 3; // else if (v % 3 != 0) // cnt += v / 3 + 1; // else cnt += v / 2; // System.out.println("cnt: " + cnt); // } // return cnt; // } // public int longestPath(int[] p, String t) { // tle tle tle ??? // int n = t.length(); // if (n == 1) return 1; // s = t.toCharArray(); // adj = new ArrayList [n]; // for (int i = 0; i < n; i++) adj[i] = new ArrayList<>(); // for (int i = 0; i < n; i++) { // if (p[i] != -1) { // adj[p[i]].add(i); // 如果它有父节点,那么父节点的孩子链表加上当前的孩子 // adj[i].add(p[i]); // } // } // // for (int i = 0; i < n; i++) // 这里面有大量的重复计算, 这里这种方法就tle了 // // dfs(i, -1, 1); // // dist = new int [n]; // return max; // } // List<Integer> [] adj; // char [] s; // // int [] dist; // int max = 0; // void dijkstra(int u) { // Queue<int []> q = new PriorityQueue<>((x, y) -> x[1] - y[1]); // q.offer(new int [] {u, 1}); // while (!q.isEmpty()) { // 这里有点儿并不起来了:当求的是最长距离的时候,是不是应该用dfs记忆化搜索??? // int [] u = q.poll(); // // if (dist[u[0]] >= u[1]) continue; // 这里的剪枝忘记了。。。。。。 // } // } // void dfs(int u, int p, int cnt) { // if (adj[u].size() == 1 && adj[u].get(0) == p) { // 叶子节点,可以返回 // if (cnt > max) max = cnt; // return ; // } // for (int v : adj[u]) { // if (s[v] == s[u] || v == p) continue; // 是父节点已经访问过了,或者相邻的字符是一样的,路过 // dfs(v, u, cnt+1); // } // } public int maxTrailingZeros(int[][] a) { // 读不懂题目说的是什么意思 int m = a.length, n = a[0].length; int [][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; // 这个 <SUF> // 需要对每个格里的2与5质因子的个数分别作统计 int [][][] cnt = new int [m][n][2]; // 0: 2, 1: 5的统计个数 for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) if (a[i][j] % 2 == 0) cnt[i][j][0] = getCnt(a[i][j], 2); else if (a[i][j] % 5 == 0) cnt[i][j][1] = getCnt(a[i][j], 5); int [][] u = new int [m+1][n+1], d = new int [m+1][n+1], l = new int [m+1][n+1], r = new int [m+1][n+1]; // up, down, left, right: for (int i = 1; i <= m; i++) for (int j = 1; j <= n; j++) u[i][j] = getCnt(a[i][j]) + u[i-1][j] + // 这里还要分别统计2和5的个数,感觉这个题的思路没有想对,稍微想复杂了点 // 昨天晚上最后一晚大街边的房间休息,没有休息好,今天感觉整个的状态不对,希望下个周的情况能够好点儿 } int getCnt(int v) { String t = String.valueOf(v); char [] s = t.toCharArray(); int n = t.length(), i = n-1, cnt = 0; while (i >= 0 && s[i] == '0') { cnt++; i--; } return cnt; } int getCnt(int v, int m) { int cnt = 0; if (v % m == 0) { while (v % m == 0) { cnt++; v /= m; } } return cnt; } } public static void main(String args[]) { Solution s = new Solution(); int [][] a = new int [][] {{23,17,15,3,20},{8,1,20,27,11},{9,4,6,2,21},{40,9,1,10,6},{22,7,4,5,3}}; int r = s.maxTrailingZeros(a); System.out.println("r: " + r); } } // ListNode head = new ListNode(a[0]); // head.buildList(head, a); // head.printList(head); // TreeNode root = new TreeNode(a[0]); // root.buildTree(root, a); // root.levelPrintTree(root);
false
1,779
26
1,942
31
1,985
21
1,942
31
2,307
46
false
false
false
false
false
true
16198_4
wqwqwq package testJava; testJava import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author liushen * */ public class RegexUtils { /** * 验证Email * @param email email地址,格式:zhangsan@sina.com,zhangsan@xxx.com.cn,xxx代表邮件服务商 * @return 验证成功返回true,验证失败返回false */ public static boolean checkEmail(String email) { String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; return Pattern.matches(regex, email); } /** * 验证身份证号码 * @param idCard 居民身份证号码18位,第一位不能为0,最后一位可能是数字或字母,中间16位为数字 \d同[0-9] * @return 验证成功返回true,验证失败返回false */ public static boolean checkIdCard(String idCard) { String regex = "[1-9]\\d{16}[a-zA-Z0-9]{1}"; return Pattern.matches(regex,idCard); } /** * 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港)) * @param mobile 移动、联通、电信运营商的号码段 *<p>移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡) *、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用)</p> *<p>联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)</p> *<p>电信的号段:133、153、180(未启用)、189</p> * @return 验证成功返回true,验证失败返回false */ public static boolean checkMobile(String mobile) { String regex = "(\\+\\d+)?1[3458]\\d{9}$"; return Pattern.matches(regex,mobile); } /** * 验证固定电话号码 * @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447 * <p><b>国家(地区) 代码 :</b>标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字, * 数字之后是空格分隔的国家(地区)代码。</p> * <p><b>区号(城市代码):</b>这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号—— * 对不使用地区或城市代码的国家(地区),则省略该组件。</p> * <p><b>电话号码:</b>这包含从 0 到 9 的一个或多个数字 </p> * @return 验证成功返回true,验证失败返回false */ public static boolean checkPhone(String phone) { String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; return Pattern.matches(regex, phone); } /** * 验证整数(正整数和负整数) * @param digit 一位或多位0-9之间的整数 * @return 验证成功返回true,验证失败返回false */ public static boolean checkDigit(String digit) { String regex = "\\-?[1-9]\\d+"; return Pattern.matches(regex,digit); } /** * 验证整数和浮点数(正负整数和正负浮点数) * @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30 * @return 验证成功返回true,验证失败返回false */ public static boolean checkDecimals(String decimals) { String regex = "\\-?[1-9]\\d+(\\.\\d+)?"; return Pattern.matches(regex,decimals); } /** * 验证空白字符 * @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B * @return 验证成功返回true,验证失败返回false */ public static boolean checkBlankSpace(String blankSpace) { String regex = "\\s+"; return Pattern.matches(regex,blankSpace); } /** * 验证中文 * @param chinese 中文字符 * @return 验证成功返回true,验证失败返回false */ public static boolean checkChinese(String chinese) { String regex = "^[\u4E00-\u9FA5]+$"; return Pattern.matches(regex,chinese); } /** * 验证日期(年月日) * @param birthday 日期,格式:1992-09-03,或1992.09.03 * @return 验证成功返回true,验证失败返回false */ public static boolean checkBirthday(String birthday) { String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; return Pattern.matches(regex,birthday); } /** * 验证URL地址 * @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或 http://www.csdn.net:80 * @return 验证成功返回true,验证失败返回false */ public static boolean checkURL(String url) { String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?"; return Pattern.matches(regex, url); } /** * <pre> * 获取网址 URL 的一级域名 * http://detail.tmall.com/item.htm?spm=a230r.1.10.44.1xpDSH&id=15453106243&_u=f4ve1uq1092 ->> tmall.com * </pre> * * @param url * @return */ public static String getDomain(String url) { Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); // 获取完整的域名 // Pattern p=Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(url); matcher.find(); return matcher.group(); } /** * 匹配中国邮政编码 * @param postcode 邮政编码 * @return 验证成功返回true,验证失败返回false */ public static boolean checkPostcode(String postcode) { String regex = "[1-9]\\d{5}"; return Pattern.matches(regex, postcode); } /** * 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小) * @param ipAddress IPv4标准地址 * @return 验证成功返回true,验证失败返回false */ public static boolean checkIpAddress(String ipAddress) { String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))"; return Pattern.matches(regex, ipAddress); } }
deepyu/RegexUtils
RegexUtils.java
2,029
/** * 验证固定电话号码 * @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447 * <p><b>国家(地区) 代码 :</b>标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9 的一位或多位数字, * 数字之后是空格分隔的国家(地区)代码。</p> * <p><b>区号(城市代码):</b>这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号—— * 对不使用地区或城市代码的国家(地区),则省略该组件。</p> * <p><b>电话号码:</b>这包含从 0 到 9 的一个或多个数字 </p> * @return 验证成功返回true,验证失败返回false */
block_comment
zh-cn
wqwqwq package testJava; testJava import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author liushen * */ public class RegexUtils { /** * 验证Email * @param email email地址,格式:zhangsan@sina.com,zhangsan@xxx.com.cn,xxx代表邮件服务商 * @return 验证成功返回true,验证失败返回false */ public static boolean checkEmail(String email) { String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; return Pattern.matches(regex, email); } /** * 验证身份证号码 * @param idCard 居民身份证号码18位,第一位不能为0,最后一位可能是数字或字母,中间16位为数字 \d同[0-9] * @return 验证成功返回true,验证失败返回false */ public static boolean checkIdCard(String idCard) { String regex = "[1-9]\\d{16}[a-zA-Z0-9]{1}"; return Pattern.matches(regex,idCard); } /** * 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港)) * @param mobile 移动、联通、电信运营商的号码段 *<p>移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡) *、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用)</p> *<p>联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)</p> *<p>电信的号段:133、153、180(未启用)、189</p> * @return 验证成功返回true,验证失败返回false */ public static boolean checkMobile(String mobile) { String regex = "(\\+\\d+)?1[3458]\\d{9}$"; return Pattern.matches(regex,mobile); } /** * 验证固 <SUF>*/ public static boolean checkPhone(String phone) { String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; return Pattern.matches(regex, phone); } /** * 验证整数(正整数和负整数) * @param digit 一位或多位0-9之间的整数 * @return 验证成功返回true,验证失败返回false */ public static boolean checkDigit(String digit) { String regex = "\\-?[1-9]\\d+"; return Pattern.matches(regex,digit); } /** * 验证整数和浮点数(正负整数和正负浮点数) * @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30 * @return 验证成功返回true,验证失败返回false */ public static boolean checkDecimals(String decimals) { String regex = "\\-?[1-9]\\d+(\\.\\d+)?"; return Pattern.matches(regex,decimals); } /** * 验证空白字符 * @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B * @return 验证成功返回true,验证失败返回false */ public static boolean checkBlankSpace(String blankSpace) { String regex = "\\s+"; return Pattern.matches(regex,blankSpace); } /** * 验证中文 * @param chinese 中文字符 * @return 验证成功返回true,验证失败返回false */ public static boolean checkChinese(String chinese) { String regex = "^[\u4E00-\u9FA5]+$"; return Pattern.matches(regex,chinese); } /** * 验证日期(年月日) * @param birthday 日期,格式:1992-09-03,或1992.09.03 * @return 验证成功返回true,验证失败返回false */ public static boolean checkBirthday(String birthday) { String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; return Pattern.matches(regex,birthday); } /** * 验证URL地址 * @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或 http://www.csdn.net:80 * @return 验证成功返回true,验证失败返回false */ public static boolean checkURL(String url) { String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?"; return Pattern.matches(regex, url); } /** * <pre> * 获取网址 URL 的一级域名 * http://detail.tmall.com/item.htm?spm=a230r.1.10.44.1xpDSH&id=15453106243&_u=f4ve1uq1092 ->> tmall.com * </pre> * * @param url * @return */ public static String getDomain(String url) { Pattern p = Pattern.compile("(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); // 获取完整的域名 // Pattern p=Pattern.compile("[^//]*?\\.(com|cn|net|org|biz|info|cc|tv)", Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(url); matcher.find(); return matcher.group(); } /** * 匹配中国邮政编码 * @param postcode 邮政编码 * @return 验证成功返回true,验证失败返回false */ public static boolean checkPostcode(String postcode) { String regex = "[1-9]\\d{5}"; return Pattern.matches(regex, postcode); } /** * 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小) * @param ipAddress IPv4标准地址 * @return 验证成功返回true,验证失败返回false */ public static boolean checkIpAddress(String ipAddress) { String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))"; return Pattern.matches(regex, ipAddress); } }
false
2,006
235
2,029
255
2,108
222
2,029
255
2,729
349
false
false
false
false
false
true
18013_9
package cn.definen.utils; import cn.definen.model.ClassInfo; import cn.definen.model.FieldInfo; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.File; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.function.Function; import java.util.logging.Logger; /** * 反射, 加载目录下的 class */ public class ClassUtil { private static final Logger logger = Logger.getLogger(ClassUtil.class.getSimpleName()); /** * 将list 的class 转为 ClassInfo * @param classes clz * @param function 过滤器函数, 如果是 null 返回true, 留下 * @return list */ public static List<ClassInfo> convertClassInfo(List<Class<?>> classes, Function<Class<?>, Boolean> function) { List<ClassInfo> classInfos = new ArrayList<>(); for (Class<?> clz : classes) { // 初步 filter if (function != null && !function.apply(clz)) { continue; } ClassInfo info = convertClassInfo(clz); // 他的 Bean属性必须大于 0 个 if (info.getFields().size() > 0) { classInfos.add(info); } } return classInfos; } /** * 将一个 class 转为 <see>cn.definen.model.ClassInfo</see> * @param clz class * @return ClassInfo */ private static ClassInfo convertClassInfo(Class<?> clz) { List<PropertyDescriptor> fields = ClassUtil.getBeanProperty(clz); ClassInfo info = new ClassInfo(); info.setPackageName(clz.getPackage().getName()); info.setClassName(clz.getSimpleName()); List<FieldInfo> fieldInfos = new ArrayList<>(); for (PropertyDescriptor field : fields) { FieldInfo fieldInfo = new FieldInfo(); fieldInfo.setName(field.getName()); fieldInfo.setType(field.getPropertyType().toString()); fieldInfo.setOrigin(field); calcType(fieldInfo, info); fieldInfos.add(fieldInfo); } info.setFields(fieldInfos); return info; } /** * 计算类型, 通过类型, 计算demo等属性 * @param info fieldInfo * @param classInfo classInfo */ private static void calcType(FieldInfo info, ClassInfo classInfo) { PropertyDescriptor origin = info.getOrigin(); Class<?> type = origin.getPropertyType(); if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class) || type.isAssignableFrom(long.class) || type.isAssignableFrom(Long.class)) { info.setDemo("1"); } else if (type.isAssignableFrom(double.class) || type.isAssignableFrom(Double.class)) { info.setDemo("1.1"); } else if (type.isAssignableFrom(float.class) || type.isAssignableFrom(Float.class)) { info.setDemo("1.1F"); } else if (type.isAssignableFrom(String.class)) { info.setDemo("\"1\""); } else if (type.isAssignableFrom(Date.class)) { classInfo.addImport("import java.util.Date;"); info.setPatchInfo("Date date = new Date();"); info.setDemo("date"); } else { info.setDemo("unknown type: " + type); } } /** * 获取一个类所有符合 bean 规范的属性 * @param clz class * @return list */ public static List<PropertyDescriptor> getBeanProperty(Class<?> clz) { List<PropertyDescriptor> ans = new ArrayList<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(clz); PropertyDescriptor[] fields = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor field : fields) { Method getter = field.getReadMethod(); Method setter = field.getWriteMethod(); if (getter != null && setter != null) { ans.add(field); } } } catch (Throwable ignored) { } return ans; } /** * 递归项目 加载所有的类 * @param projectPath 项目目录, 不能以 / 结尾 * @param path 想扫描的目录, 不能以 / 结尾 * @return list */ public static List<Class<?>> getDirClazzs(String projectPath, String path) { List<Class<?>> ans = new ArrayList<>(); List<File> files = new ArrayList<>(); List<URL> urls = new ArrayList<>(); if (path == null || projectPath.length() > path.length()) { logger.info("传入的扫描目录小于项目目录, 使用项目目录"); path = projectPath; } if (!path.contains(projectPath)) { logger.warning("传入的projectPath, 不是path的子路径, 使用项目目录"); path = projectPath; } try { urls.add(new File(projectPath).toURI().toURL()); } catch (MalformedURLException e) { e.printStackTrace(); } getAllClassFile(new File(path), files); // 构造 loader URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[0])); // 循环加载类 for (File file : files) { String name = getClassName(projectPath.length() + 1, file); try { ans.add(loader.loadClass(name)); } catch (Exception e) { //有些类继承了Spring等, 加载这个类需要加载父类(Spring), 但是没找到父类, 所以抛出异常, 把这个异常捕获掉即可 e.printStackTrace(); } } return ans; } private static String getClassName(int rootPathLength, File file) { String name = file.getAbsolutePath() .substring(rootPathLength); return name.replace(".class", "") .replaceAll("\\\\", "."); } private static void getAllClassFile(File file, List<File> files) { if (file == null) return; if (file.isDirectory()) { // 如果是一个路径, name添加到urls里 // try { // urls.add(file.toURI().toURL()); // } catch (MalformedURLException e) { // System.err.println("[error] 文件夹在转换成 URL 对象时报错"); // e.printStackTrace(); // } File[] listFiles = file.listFiles(); if (listFiles == null) return; for (File f : listFiles) { getAllClassFile(f, files); } } else { if (file.getName().endsWith(".class")) { files.add(file); } } } }
define9/generateCodePlugin
src/cn/definen/utils/ClassUtil.java
1,619
// 循环加载类
line_comment
zh-cn
package cn.definen.utils; import cn.definen.model.ClassInfo; import cn.definen.model.FieldInfo; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.io.File; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.function.Function; import java.util.logging.Logger; /** * 反射, 加载目录下的 class */ public class ClassUtil { private static final Logger logger = Logger.getLogger(ClassUtil.class.getSimpleName()); /** * 将list 的class 转为 ClassInfo * @param classes clz * @param function 过滤器函数, 如果是 null 返回true, 留下 * @return list */ public static List<ClassInfo> convertClassInfo(List<Class<?>> classes, Function<Class<?>, Boolean> function) { List<ClassInfo> classInfos = new ArrayList<>(); for (Class<?> clz : classes) { // 初步 filter if (function != null && !function.apply(clz)) { continue; } ClassInfo info = convertClassInfo(clz); // 他的 Bean属性必须大于 0 个 if (info.getFields().size() > 0) { classInfos.add(info); } } return classInfos; } /** * 将一个 class 转为 <see>cn.definen.model.ClassInfo</see> * @param clz class * @return ClassInfo */ private static ClassInfo convertClassInfo(Class<?> clz) { List<PropertyDescriptor> fields = ClassUtil.getBeanProperty(clz); ClassInfo info = new ClassInfo(); info.setPackageName(clz.getPackage().getName()); info.setClassName(clz.getSimpleName()); List<FieldInfo> fieldInfos = new ArrayList<>(); for (PropertyDescriptor field : fields) { FieldInfo fieldInfo = new FieldInfo(); fieldInfo.setName(field.getName()); fieldInfo.setType(field.getPropertyType().toString()); fieldInfo.setOrigin(field); calcType(fieldInfo, info); fieldInfos.add(fieldInfo); } info.setFields(fieldInfos); return info; } /** * 计算类型, 通过类型, 计算demo等属性 * @param info fieldInfo * @param classInfo classInfo */ private static void calcType(FieldInfo info, ClassInfo classInfo) { PropertyDescriptor origin = info.getOrigin(); Class<?> type = origin.getPropertyType(); if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class) || type.isAssignableFrom(long.class) || type.isAssignableFrom(Long.class)) { info.setDemo("1"); } else if (type.isAssignableFrom(double.class) || type.isAssignableFrom(Double.class)) { info.setDemo("1.1"); } else if (type.isAssignableFrom(float.class) || type.isAssignableFrom(Float.class)) { info.setDemo("1.1F"); } else if (type.isAssignableFrom(String.class)) { info.setDemo("\"1\""); } else if (type.isAssignableFrom(Date.class)) { classInfo.addImport("import java.util.Date;"); info.setPatchInfo("Date date = new Date();"); info.setDemo("date"); } else { info.setDemo("unknown type: " + type); } } /** * 获取一个类所有符合 bean 规范的属性 * @param clz class * @return list */ public static List<PropertyDescriptor> getBeanProperty(Class<?> clz) { List<PropertyDescriptor> ans = new ArrayList<>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(clz); PropertyDescriptor[] fields = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor field : fields) { Method getter = field.getReadMethod(); Method setter = field.getWriteMethod(); if (getter != null && setter != null) { ans.add(field); } } } catch (Throwable ignored) { } return ans; } /** * 递归项目 加载所有的类 * @param projectPath 项目目录, 不能以 / 结尾 * @param path 想扫描的目录, 不能以 / 结尾 * @return list */ public static List<Class<?>> getDirClazzs(String projectPath, String path) { List<Class<?>> ans = new ArrayList<>(); List<File> files = new ArrayList<>(); List<URL> urls = new ArrayList<>(); if (path == null || projectPath.length() > path.length()) { logger.info("传入的扫描目录小于项目目录, 使用项目目录"); path = projectPath; } if (!path.contains(projectPath)) { logger.warning("传入的projectPath, 不是path的子路径, 使用项目目录"); path = projectPath; } try { urls.add(new File(projectPath).toURI().toURL()); } catch (MalformedURLException e) { e.printStackTrace(); } getAllClassFile(new File(path), files); // 构造 loader URLClassLoader loader = new URLClassLoader(urls.toArray(new URL[0])); // 循环 <SUF> for (File file : files) { String name = getClassName(projectPath.length() + 1, file); try { ans.add(loader.loadClass(name)); } catch (Exception e) { //有些类继承了Spring等, 加载这个类需要加载父类(Spring), 但是没找到父类, 所以抛出异常, 把这个异常捕获掉即可 e.printStackTrace(); } } return ans; } private static String getClassName(int rootPathLength, File file) { String name = file.getAbsolutePath() .substring(rootPathLength); return name.replace(".class", "") .replaceAll("\\\\", "."); } private static void getAllClassFile(File file, List<File> files) { if (file == null) return; if (file.isDirectory()) { // 如果是一个路径, name添加到urls里 // try { // urls.add(file.toURI().toURL()); // } catch (MalformedURLException e) { // System.err.println("[error] 文件夹在转换成 URL 对象时报错"); // e.printStackTrace(); // } File[] listFiles = file.listFiles(); if (listFiles == null) return; for (File f : listFiles) { getAllClassFile(f, files); } } else { if (file.getName().endsWith(".class")) { files.add(file); } } } }
false
1,455
6
1,619
5
1,745
5
1,619
5
2,054
11
false
false
false
false
false
true
35126_1
package bean; import java.util.List; /** * 1.类的用途 * 2.@author:Sunyubo * 3.@ 2016/12/21. */ public class Bean { /** * error_code : 0 * reason : Success * result : {"data":[{"content":"有一女挤上火车,看到自己座位坐一帅哥。她核对自己的票,客气地说:\u201c您坐错位置了吧?\u201d 帅哥拿出票嚷嚷着,\u201c看清楚!这是我的座你瞎了?\u201d 女仔细地看了看他的票。女不说话了!帅哥跷着腿,不屑地说,\u201c年纪轻轻,学人搭讪!\u201d 女不再回应,默默退到帅哥身旁。 不久,女见火车开动了,对帅哥说了一声:\u201c~~你没坐错座,你坐错车了!\u2026\u2026 有一种忍叫做让你后悔都来不及!","hashId":"6bfc508b95aba9b05d39259d7d65cd32","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"和妈妈坐沙发上,我打开APP看各大主播直播间人满为患,礼物各种刷。我对妈妈说:妈、我也开直播吧。我妈用深邃的目光看着我说:孩子、做善事有很多种,就你那歌声,人家哭都比你唱歌好听。。。额 妈、咱还能愉快的聊天不。。。。","hashId":"6a57a5e8b7fd308311589213e771dbb9","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"每次吵架,丈夫总是让着妻子,一次,妻子问\u201c你为什么老让着我,明明是我做错事?\u201d丈夫:\u201c因为你是我的,就算我吵赢了,又能怎样?赢了道理,输了感情!\u201d两人世界里总要一个闹着一个笑着一个吵着一个哄着,如果一个人总是输,不是口才不够好,是爱你,一个人输了,两个人才能赢。","hashId":"39713240989f4b0f16c26ae11bbeb022","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"和在外地教书的妹妹电话(她吃学校食堂)。。。妹、你吃午饭了吗?菜味道好吗?我妹回:哥、食堂的菜只能问熟了吗。这......貌似有道理哦!!!","hashId":"b080ca1281bcda9926fbb220f1e401c2","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"假如潘金莲不开窗户,就不会遇见西门庆; 不遇西门庆,就不会出轨; 不出轨,武松就不会逼上梁山。 武松不上梁山,方腊就不会被擒; 方腊不被擒,就可灭大宋江山; 没有了大宋江山,就不会有靖康耻; 金兵就不会入关,就不会有大清朝; 没有大清朝,中国就不会闭关锁国、不会有战争和八国联军入侵。 那么,中国,将是世界上唯一的超级大国!美国等其他诸侯神马的都TM是浮云! 唉!金莲呀,没事你TM开什么窗户啊~~","hashId":"3eab1e5d72d099ad7bbff7639dc164ad","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"学生:口字加舍字念啥?老师:念啥。学生一脸茫然:?老师,我不知道,所以才问你。老师:这个字它念啥。学生:我真不知道它念啥。老师沉住气:你想知道它念啥,但是你又不知道它念啥,它就念啥。学生一脸茫然:??老师终于火了:B孩子,老师不认识,自己查字典!","hashId":"4dce4a421c8e49598d1799e4bf78fb17","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"今天去看下午场电影,发现整个厅貌 似就我一人!这包场的感觉倍 爽,我从前排换到中间、从左边换到右边、玩自 拍、模仿电影讲对白,站到屏幕前亲 吻 女 主\u2026 正玩得挺 嗨,在最后排角落里站起来一 对 男 女快速离开,隐 约有声音传来:换个地方吧,这人脑 袋有毛 病\u2026","hashId":"7c99ab14a711e15561d64dcf3fa86a65","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"刚才和男友再沙发上玩手机,他和我说不要经常玩手机,我正感动呢,他接了一句:对手机不好,玩坏了我还得给你买\u2026\u2026有没有人给我买把西瓜刀","hashId":"837b4b13a26a1599dd97b608008f6cd5","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"单位有一小伙,不知啥原因,不怕冷,冬天别人要穿毛衣棉袄,而他只穿一件T恤外加一件单衣即可,关键他还不会感冒生病。 昨天去相亲,为了显示他的身体好,特意穿得比平时还少\u2026 结果杯 具了,女孩妈妈不同意:都这么冷的天,连件厚衣服都买不起,不是没钱就是特抠门\u2026","hashId":"ca98aa20ea196f5552680c0ccf36cc70","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"一直觉得电视里男女主在车站分别时一人上车一人哭着追火车的桥段好浪漫好煽情。今天我也想这样体验一下,于是去车站送人。才发现电视里的童话都是骗人的。我TM没买票连车站都进不去\u2026\u2026","hashId":"47d4286356f678f3eb127d8f586c2076","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"}]} */ public int error_code; public String reason; public ResultBean result; public static class ResultBean { public List<DataBean> data; public static class DataBean { /** * content : 有一女挤上火车,看到自己座位坐一帅哥。她核对自己的票,客气地说:“您坐错位置了吧?” 帅哥拿出票嚷嚷着,“看清楚!这是我的座你瞎了?” 女仔细地看了看他的票。女不说话了!帅哥跷着腿,不屑地说,“年纪轻轻,学人搭讪!” 女不再回应,默默退到帅哥身旁。 不久,女见火车开动了,对帅哥说了一声:“~~你没坐错座,你坐错车了!…… 有一种忍叫做让你后悔都来不及! * hashId : 6bfc508b95aba9b05d39259d7d65cd32 * unixtime : 1482314630 * updatetime : 2016-12-21 18:03:50 */ public String content; public String hashId; public int unixtime; public String updatetime; } } }
demoing/demo
kaoshi2/app/src/main/java/bean/Bean.java
2,513
/** * error_code : 0 * reason : Success * result : {"data":[{"content":"有一女挤上火车,看到自己座位坐一帅哥。她核对自己的票,客气地说:\u201c您坐错位置了吧?\u201d 帅哥拿出票嚷嚷着,\u201c看清楚!这是我的座你瞎了?\u201d 女仔细地看了看他的票。女不说话了!帅哥跷着腿,不屑地说,\u201c年纪轻轻,学人搭讪!\u201d 女不再回应,默默退到帅哥身旁。 不久,女见火车开动了,对帅哥说了一声:\u201c~~你没坐错座,你坐错车了!\u2026\u2026 有一种忍叫做让你后悔都来不及!","hashId":"6bfc508b95aba9b05d39259d7d65cd32","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"和妈妈坐沙发上,我打开APP看各大主播直播间人满为患,礼物各种刷。我对妈妈说:妈、我也开直播吧。我妈用深邃的目光看着我说:孩子、做善事有很多种,就你那歌声,人家哭都比你唱歌好听。。。额 妈、咱还能愉快的聊天不。。。。","hashId":"6a57a5e8b7fd308311589213e771dbb9","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"每次吵架,丈夫总是让着妻子,一次,妻子问\u201c你为什么老让着我,明明是我做错事?\u201d丈夫:\u201c因为你是我的,就算我吵赢了,又能怎样?赢了道理,输了感情!\u201d两人世界里总要一个闹着一个笑着一个吵着一个哄着,如果一个人总是输,不是口才不够好,是爱你,一个人输了,两个人才能赢。","hashId":"39713240989f4b0f16c26ae11bbeb022","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"和在外地教书的妹妹电话(她吃学校食堂)。。。妹、你吃午饭了吗?菜味道好吗?我妹回:哥、食堂的菜只能问熟了吗。这......貌似有道理哦!!!","hashId":"b080ca1281bcda9926fbb220f1e401c2","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"假如潘金莲不开窗户,就不会遇见西门庆; 不遇西门庆,就不会出轨; 不出轨,武松就不会逼上梁山。 武松不上梁山,方腊就不会被擒; 方腊不被擒,就可灭大宋江山; 没有了大宋江山,就不会有靖康耻; 金兵就不会入关,就不会有大清朝; 没有大清朝,中国就不会闭关锁国、不会有战争和八国联军入侵。 那么,中国,将是世界上唯一的超级大国!美国等其他诸侯神马的都TM是浮云! 唉!金莲呀,没事你TM开什么窗户啊~~","hashId":"3eab1e5d72d099ad7bbff7639dc164ad","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"学生:口字加舍字念啥?老师:念啥。学生一脸茫然:?老师,我不知道,所以才问你。老师:这个字它念啥。学生:我真不知道它念啥。老师沉住气:你想知道它念啥,但是你又不知道它念啥,它就念啥。学生一脸茫然:??老师终于火了:B孩子,老师不认识,自己查字典!","hashId":"4dce4a421c8e49598d1799e4bf78fb17","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"今天去看下午场电影,发现整个厅貌 似就我一人!这包场的感觉倍 爽,我从前排换到中间、从左边换到右边、玩自 拍、模仿电影讲对白,站到屏幕前亲 吻 女 主\u2026 正玩得挺 嗨,在最后排角落里站起来一 对 男 女快速离开,隐 约有声音传来:换个地方吧,这人脑 袋有毛 病\u2026","hashId":"7c99ab14a711e15561d64dcf3fa86a65","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"刚才和男友再沙发上玩手机,他和我说不要经常玩手机,我正感动呢,他接了一句:对手机不好,玩坏了我还得给你买\u2026\u2026有没有人给我买把西瓜刀","hashId":"837b4b13a26a1599dd97b608008f6cd5","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"单位有一小伙,不知啥原因,不怕冷,冬天别人要穿毛衣棉袄,而他只穿一件T恤外加一件单衣即可,关键他还不会感冒生病。 昨天去相亲,为了显示他的身体好,特意穿得比平时还少\u2026 结果杯 具了,女孩妈妈不同意:都这么冷的天,连件厚衣服都买不起,不是没钱就是特抠门\u2026","hashId":"ca98aa20ea196f5552680c0ccf36cc70","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"},{"content":"一直觉得电视里男女主在车站分别时一人上车一人哭着追火车的桥段好浪漫好煽情。今天我也想这样体验一下,于是去车站送人。才发现电视里的童话都是骗人的。我TM没买票连车站都进不去\u2026\u2026","hashId":"47d4286356f678f3eb127d8f586c2076","unixtime":1482314630,"updatetime":"2016-12-21 18:03:50"}]} */
block_comment
zh-cn
package bean; import java.util.List; /** * 1.类的用途 * 2.@author:Sunyubo * 3.@ 2016/12/21. */ public class Bean { /** * err <SUF>*/ public int error_code; public String reason; public ResultBean result; public static class ResultBean { public List<DataBean> data; public static class DataBean { /** * content : 有一女挤上火车,看到自己座位坐一帅哥。她核对自己的票,客气地说:“您坐错位置了吧?” 帅哥拿出票嚷嚷着,“看清楚!这是我的座你瞎了?” 女仔细地看了看他的票。女不说话了!帅哥跷着腿,不屑地说,“年纪轻轻,学人搭讪!” 女不再回应,默默退到帅哥身旁。 不久,女见火车开动了,对帅哥说了一声:“~~你没坐错座,你坐错车了!…… 有一种忍叫做让你后悔都来不及! * hashId : 6bfc508b95aba9b05d39259d7d65cd32 * unixtime : 1482314630 * updatetime : 2016-12-21 18:03:50 */ public String content; public String hashId; public int unixtime; public String updatetime; } } }
false
2,073
1,742
2,513
2,106
2,104
1,751
2,513
2,106
3,247
2,712
true
true
true
true
true
false
21707_5
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true)// 过滤不用的字段 public class ItemRecord { private String uid; // Uid private String name; // 奖品名 @JsonProperty("gacha_type") // 通过注解 更改映射名 private String gachaType; // 卡池信息 武器池302/up池301/常驻池200/新手池100 @JsonProperty("item_type") private String itemType; // 奖品类型 角色/武器 @JsonProperty("rank_type") private String rankType; // 奖品等级 5,4,3 private String id; // 唯一Id private String time; // 获得奖品的时间 public ItemRecord(String uid, String name, String gachaType, String itemType, String rankType, String id, String time) { this.uid = uid; this.name = name; this.gachaType = gachaType; this.itemType = itemType; this.rankType = rankType; this.id = id; this.time = time; } public ItemRecord() { // 默认无参构造函数 } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGachaType() { return gachaType; } public void setGachaType(String gachaType) { this.gachaType = gachaType; } public String getItemType() { return itemType; } public void setItemType(String itemType) { this.itemType = itemType; } public String getRankType() { return rankType; } public void setRankType(String rankType) { this.rankType = rankType; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } @Override public String toString() { return "{" + "uid:'" + uid + '\'' + ", name:'" + name + '\'' + ", gachaType:'" + gachaType + '\'' + ", itemType:'" + itemType + '\'' + ", rankType:'" + rankType + '\'' + ", id:'" + id + '\'' + ", time:'" + time + '\'' + '}'; } }
dengbicheng/YuanShenPrizeRecord
src/main/java/ItemRecord.java
643
// 奖品类型 角色/武器
line_comment
zh-cn
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true)// 过滤不用的字段 public class ItemRecord { private String uid; // Uid private String name; // 奖品名 @JsonProperty("gacha_type") // 通过注解 更改映射名 private String gachaType; // 卡池信息 武器池302/up池301/常驻池200/新手池100 @JsonProperty("item_type") private String itemType; // 奖品 <SUF> @JsonProperty("rank_type") private String rankType; // 奖品等级 5,4,3 private String id; // 唯一Id private String time; // 获得奖品的时间 public ItemRecord(String uid, String name, String gachaType, String itemType, String rankType, String id, String time) { this.uid = uid; this.name = name; this.gachaType = gachaType; this.itemType = itemType; this.rankType = rankType; this.id = id; this.time = time; } public ItemRecord() { // 默认无参构造函数 } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGachaType() { return gachaType; } public void setGachaType(String gachaType) { this.gachaType = gachaType; } public String getItemType() { return itemType; } public void setItemType(String itemType) { this.itemType = itemType; } public String getRankType() { return rankType; } public void setRankType(String rankType) { this.rankType = rankType; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } @Override public String toString() { return "{" + "uid:'" + uid + '\'' + ", name:'" + name + '\'' + ", gachaType:'" + gachaType + '\'' + ", itemType:'" + itemType + '\'' + ", rankType:'" + rankType + '\'' + ", id:'" + id + '\'' + ", time:'" + time + '\'' + '}'; } }
false
610
12
643
11
699
9
643
11
835
14
false
false
false
false
false
true
22296_4
package com.yr.net.app.customer.entity; import java.time.LocalDateTime; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * 用户家庭成员 * * @author dengbp */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class UserMember implements Serializable { private static final long serialVersionUID = 1L; /** * user_id */ private String untitled3; /** * 关系 如:父子,母子,兄妹 */ private String relation; /** * 称呼 如:父亲,母亲,哥哥,妹妹 */ private String appellation; /** * 职业 */ private String profession; /** * 状态 0正常1删除 */ private Integer state; /** * 创建人 */ private String createdBy; /** * 创建时间 */ private LocalDateTime createdTime; /** * 更新人 */ private String updatedBy; /** * 更新时间 */ private LocalDateTime updatedTime; }
dengbp/im-app_server
src/main/java/com/yr/net/app/customer/entity/UserMember.java
282
/** * 职业 */
block_comment
zh-cn
package com.yr.net.app.customer.entity; import java.time.LocalDateTime; import java.io.Serializable; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * 用户家庭成员 * * @author dengbp */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class UserMember implements Serializable { private static final long serialVersionUID = 1L; /** * user_id */ private String untitled3; /** * 关系 如:父子,母子,兄妹 */ private String relation; /** * 称呼 如:父亲,母亲,哥哥,妹妹 */ private String appellation; /** * 职业 <SUF>*/ private String profession; /** * 状态 0正常1删除 */ private Integer state; /** * 创建人 */ private String createdBy; /** * 创建时间 */ private LocalDateTime createdTime; /** * 更新人 */ private String updatedBy; /** * 更新时间 */ private LocalDateTime updatedTime; }
false
243
10
282
8
291
9
282
8
385
12
false
false
false
false
false
true