file_id
stringlengths
5
8
content
stringlengths
86
13.2k
repo
stringlengths
9
59
path
stringlengths
8
120
token_length
int64
31
3.28k
original_comment
stringlengths
5
1k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
masked_comment
stringlengths
87
13.2k
excluded
bool
1 class
file-tokens-Qwen/Qwen2-7B
int64
23
3.19k
comment-tokens-Qwen/Qwen2-7B
int64
2
532
file-tokens-bigcode/starcoder2-7b
int64
31
3.28k
comment-tokens-bigcode/starcoder2-7b
int64
2
654
file-tokens-google/codegemma-7b
int64
27
3.42k
comment-tokens-google/codegemma-7b
int64
2
548
file-tokens-ibm-granite/granite-8b-code-base
int64
31
3.28k
comment-tokens-ibm-granite/granite-8b-code-base
int64
2
654
file-tokens-meta-llama/CodeLlama-7b-hf
int64
37
3.93k
comment-tokens-meta-llama/CodeLlama-7b-hf
int64
4
992
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
31616_0
package Leetcode.Java_code; import java.util.HashMap; /*************************************************** * @question * 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。 * * 字符 数值 * I 1 * V 5 * X 10 * L 50 * C 100 * D 500 * M 1000 * 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。 * * 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况: * * I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。 * X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 * C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。 * 给你一个整数,将其转为罗马数字。 * * @tips * 1 <= num <= 3999 */ public class RomantoInt { HashMap<Character, Integer> table = new HashMap<Character, Integer>(){{ put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000); }}; public int convert(String s){ int result = 0; for(int i = 0; i < s.length(); i++){ if(i < s.length() - 1 && table.get(s.charAt(i)) < table.get(s.charAt(i + 1)) ) result -= table.get(s.charAt(i)); else result += table.get(s.charAt(i)); } return result; } public static void main(String[] args){ quickprint.print(new RomantoInt().convert("MCMXCIV")); } }
MVPYPC/Leetcode
Java_code/RomantoInt.java
623
/*************************************************** * @question * 罗马数字包含以下七种字符: I, V, X, L,C,D 和 M。 * * 字符 数值 * I 1 * V 5 * X 10 * L 50 * C 100 * D 500 * M 1000 * 例如, 罗马数字 2 写做 II ,即为两个并列的 1。12 写做 XII ,即为 X + II 。 27 写做 XXVII, 即为 XX + V + II 。 * * 通常情况下,罗马数字中小的数字在大的数字的右边。但也存在特例,例如 4 不写做 IIII,而是 IV。数字 1 在数字 5 的左边,所表示的数等于大数 5 减小数 1 得到的数值 4 。同样地,数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况: * * I 可以放在 V (5) 和 X (10) 的左边,来表示 4 和 9。 * X 可以放在 L (50) 和 C (100) 的左边,来表示 40 和 90。 * C 可以放在 D (500) 和 M (1000) 的左边,来表示 400 和 900。 * 给你一个整数,将其转为罗马数字。 * * @tips * 1 <= num <= 3999 */
block_comment
zh-cn
package Leetcode.Java_code; import java.util.HashMap; /*************************************************** * @qu <SUF>*/ public class RomantoInt { HashMap<Character, Integer> table = new HashMap<Character, Integer>(){{ put('I', 1); put('V', 5); put('X', 10); put('L', 50); put('C', 100); put('D', 500); put('M', 1000); }}; public int convert(String s){ int result = 0; for(int i = 0; i < s.length(); i++){ if(i < s.length() - 1 && table.get(s.charAt(i)) < table.get(s.charAt(i + 1)) ) result -= table.get(s.charAt(i)); else result += table.get(s.charAt(i)); } return result; } public static void main(String[] args){ quickprint.print(new RomantoInt().convert("MCMXCIV")); } }
false
577
365
623
375
612
347
623
375
758
480
true
true
true
true
true
false
21615_2
package task; /** * 定时任务. * * @author mxh. * @version 2023/3/1 16:23 */ public class DelayTask extends Thread { /** * 延迟时间. */ private long delayTime; /** * 任务. */ private Runnable runnable; public DelayTask(long millis, Runnable runnable) { this.delayTime = millis; this.runnable = runnable; } @Override public void run() { try { Thread.sleep(delayTime); runnable.run(); } catch (InterruptedException ignore) { } } }
MXHDOIT/simple-java
src/task/DelayTask.java
152
/** * 任务. */
block_comment
zh-cn
package task; /** * 定时任务. * * @author mxh. * @version 2023/3/1 16:23 */ public class DelayTask extends Thread { /** * 延迟时间. */ private long delayTime; /** * 任务. <SUF>*/ private Runnable runnable; public DelayTask(long millis, Runnable runnable) { this.delayTime = millis; this.runnable = runnable; } @Override public void run() { try { Thread.sleep(delayTime); runnable.run(); } catch (InterruptedException ignore) { } } }
false
139
8
152
8
168
9
152
8
201
11
false
false
false
false
false
true
45493_7
package com.myxh.chatgpt.domain.qa; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; import lombok.extern.slf4j.Slf4j; import java.io.Serializable; import java.util.List; import java.util.Map; /** * @author MYXH * @date 2023/12/11 * @description 文本问答,请求信息:OpenAI官网API构建参数;https://platform.openai.com/playground * @GitHub <a href="https://github.com/MYXHcode">MYXHcode</a> */ @Data @Builder @Slf4j @JsonInclude(JsonInclude.Include.NON_NULL) @NoArgsConstructor @AllArgsConstructor public class QACompletionRequest implements Serializable { /** * 默认模型 */ @NonNull @Builder.Default private String model = Model.TEXT_DAVINCI_003.getCode(); /** * 问题描述 */ @NonNull private String prompt; private String suffix; /** * 控制温度【随机性】;0 到 2 之间。较高的值(如 0.8)将使输出更加随机,而较低的值(如 0.2)将使输出更加集中和确定 */ private double temperature = 0.2; /** * 多样性控制;使用温度采样的替代方法称为核心采样,其中模型考虑具有 top_p 概率质量的令牌的结果。因此,0.1 意味着只考虑包含前 10% 概率质量的代币 */ @JsonProperty("top_p") private Double topP = 1d; /** * 为每个提示生成的完成次数 */ private Integer n = 1; /** * 是否为流式输出;就是一蹦一蹦的,出来结果 */ private boolean stream = false; /** * 停止输出标识 */ private List<String> stop; /** * 输出字符串限制;0 ~ 4096 */ @JsonProperty("max_tokens") private Integer maxTokens = 2048; @Builder.Default private boolean echo = false; /** * 频率惩罚;降低模型重复同一行的可能性 */ @JsonProperty("frequency_penalty") private double frequencyPenalty = 0; /** * 存在惩罚;增强模型谈论新话题的可能性 */ @JsonProperty("presence_penalty") private double presencePenalty = 0; /** * 生成多个调用结果,只显示最佳的。这样会更多的消耗你的 api token */ @JsonProperty("best_of") @Builder.Default private Integer bestOf = 1; private Integer logprobs; @JsonProperty("logit_bias") private Map logitBias; /** * 调用标识,避免重复调用 */ private String user; @Getter @AllArgsConstructor public enum Model { TEXT_DAVINCI_003("text-davinci-003"), TEXT_DAVINCI_002("text-davinci-002"), DAVINCI("davinci"), ; private String code; } }
MYXHcode/ChatGPT
chatgpt-sdk-java/src/main/java/com/myxh/chatgpt/domain/qa/QACompletionRequest.java
794
/** * 停止输出标识 */
block_comment
zh-cn
package com.myxh.chatgpt.domain.qa; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.*; import lombok.extern.slf4j.Slf4j; import java.io.Serializable; import java.util.List; import java.util.Map; /** * @author MYXH * @date 2023/12/11 * @description 文本问答,请求信息:OpenAI官网API构建参数;https://platform.openai.com/playground * @GitHub <a href="https://github.com/MYXHcode">MYXHcode</a> */ @Data @Builder @Slf4j @JsonInclude(JsonInclude.Include.NON_NULL) @NoArgsConstructor @AllArgsConstructor public class QACompletionRequest implements Serializable { /** * 默认模型 */ @NonNull @Builder.Default private String model = Model.TEXT_DAVINCI_003.getCode(); /** * 问题描述 */ @NonNull private String prompt; private String suffix; /** * 控制温度【随机性】;0 到 2 之间。较高的值(如 0.8)将使输出更加随机,而较低的值(如 0.2)将使输出更加集中和确定 */ private double temperature = 0.2; /** * 多样性控制;使用温度采样的替代方法称为核心采样,其中模型考虑具有 top_p 概率质量的令牌的结果。因此,0.1 意味着只考虑包含前 10% 概率质量的代币 */ @JsonProperty("top_p") private Double topP = 1d; /** * 为每个提示生成的完成次数 */ private Integer n = 1; /** * 是否为流式输出;就是一蹦一蹦的,出来结果 */ private boolean stream = false; /** * 停止输 <SUF>*/ private List<String> stop; /** * 输出字符串限制;0 ~ 4096 */ @JsonProperty("max_tokens") private Integer maxTokens = 2048; @Builder.Default private boolean echo = false; /** * 频率惩罚;降低模型重复同一行的可能性 */ @JsonProperty("frequency_penalty") private double frequencyPenalty = 0; /** * 存在惩罚;增强模型谈论新话题的可能性 */ @JsonProperty("presence_penalty") private double presencePenalty = 0; /** * 生成多个调用结果,只显示最佳的。这样会更多的消耗你的 api token */ @JsonProperty("best_of") @Builder.Default private Integer bestOf = 1; private Integer logprobs; @JsonProperty("logit_bias") private Map logitBias; /** * 调用标识,避免重复调用 */ private String user; @Getter @AllArgsConstructor public enum Model { TEXT_DAVINCI_003("text-davinci-003"), TEXT_DAVINCI_002("text-davinci-002"), DAVINCI("davinci"), ; private String code; } }
false
723
12
794
9
807
11
794
9
1,099
18
false
false
false
false
false
true
60031_38
package com.cretin.www.wheelsruflibrary.view; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Matrix; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.RelativeLayout; import com.cretin.www.wheelsruflibrary.R; import com.cretin.www.wheelsruflibrary.listener.RotateListener; import java.util.ArrayList; import java.util.List; /** * Created by cretin on 2017/12/26. */ public class WheelSurfView extends RelativeLayout { //当前的圆盘VIew private WheelSurfPanView mWheelSurfPanView; //Context private Context mContext; //开始按钮 private ImageView mStart; //动画回调监听 private RotateListener rotateListener; public void setRotateListener(RotateListener rotateListener) { mWheelSurfPanView.setRotateListener(rotateListener); this.rotateListener = rotateListener; } public WheelSurfView(Context context) { super(context); init(context, null); } public WheelSurfView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public WheelSurfView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } //开始抽奖的图标 private Integer mGoImgRes; private void init(Context context, AttributeSet attrs) { mContext = context; if ( attrs != null ) { //获得这个控件对应的属性。 TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.wheelSurfView); try { mGoImgRes = typedArray.getResourceId(R.styleable.wheelSurfView_goImg, 0); } finally { //回收这个对象 typedArray.recycle(); } } //添加圆盘视图 mWheelSurfPanView = new WheelSurfPanView(mContext, attrs); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT); mWheelSurfPanView.setLayoutParams(layoutParams); addView(mWheelSurfPanView); //添加开始按钮 mStart = new ImageView(mContext); //如果用户没有设置自定义的图标就使用默认的 if ( mGoImgRes == 0 ) { mStart.setImageResource(R.mipmap.node); } else { mStart.setImageResource(mGoImgRes); } //给图片设置LayoutParams RelativeLayout.LayoutParams llStart = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); llStart.addRule(RelativeLayout.CENTER_IN_PARENT); mStart.setLayoutParams(llStart); addView(mStart); mStart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //调用此方法是将主动权交个调用者 由调用者调用开始旋转的方法 if ( rotateListener != null ) rotateListener.rotateBefore(( ImageView ) v); } }); } public void setConfig(Builder builder) { if ( builder.mColors != null ) mWheelSurfPanView.setmColors(builder.mColors); if ( builder.mDeses != null ) mWheelSurfPanView.setmDeses(builder.mDeses); if ( builder.mHuanImgRes != 0 ) mWheelSurfPanView.setmHuanImgRes(builder.mHuanImgRes); if ( builder.mIcons != null ) mWheelSurfPanView.setmIcons(builder.mIcons); if ( builder.mMainImgRes != 0 ) mWheelSurfPanView.setmMainImgRes(builder.mMainImgRes); if ( builder.mMinTimes != 0 ) mWheelSurfPanView.setmMinTimes(builder.mMinTimes); if ( builder.mTextColor != 0 ) mWheelSurfPanView.setmTextColor(builder.mTextColor); if ( builder.mTextSize != 0 ) mWheelSurfPanView.setmTextSize(builder.mTextSize); if ( builder.mType != 0 ) mWheelSurfPanView.setmType(builder.mType); if ( builder.mVarTime != 0 ) mWheelSurfPanView.setmVarTime(builder.mVarTime); if ( builder.mTypeNum != 0 ) mWheelSurfPanView.setmTypeNum(builder.mTypeNum); mWheelSurfPanView.show(); } /** * 开始旋转 * * @param pisition 旋转最终的位置 注意 从1 开始 而且是逆时针递增 */ public void startRotate(int pisition) { if ( mWheelSurfPanView != null ) { mWheelSurfPanView.startRotate(pisition); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //视图是个正方形的 所以有宽就足够了 默认值是500 也就是WRAP_CONTENT的时候 setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); // Children are just made to fill our space. final int childWidthSize = getMeasuredWidth(); //高度和宽度一样 heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); //onMeasure调用获取到当前视图大小之后, // 手动按照一定的比例计算出中间开始按钮的大小, // 再设置给那个按钮,免得造成用户传的图片不合适之后显示贼难看 // 只设置一次 if ( isFirst ) { isFirst = !isFirst; //获取中间按钮的大小 ViewTreeObserver vto = mStart.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @TargetApi( Build.VERSION_CODES.KITKAT ) @Override public void onGlobalLayout() { mStart.getViewTreeObserver().removeGlobalOnLayoutListener(this); float w = mStart.getMeasuredWidth(); float h = mStart.getMeasuredHeight(); //计算新的大小 默认为整个大小最大值的0.17 至于为什么是0.17 我只想说我乐意。。。。 int newW = ( int ) ((( float ) childWidthSize) * 0.17); int newH = ( int ) ((( float ) childWidthSize) * 0.17 * h / w); ViewGroup.LayoutParams layoutParams = mStart.getLayoutParams(); layoutParams.width = newW; layoutParams.height = newH; mStart.setLayoutParams(layoutParams); } }); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } //记录当前是否是第一次回调onMeasure private boolean isFirst = true; //建造者模式 public static final class Builder { //当前类型 1 自定义模式 2 暴力模式 private int mType = 0; //最低圈数 默认值3 也就是说每次旋转都会最少转3圈 private int mMinTimes = 0; //分类数量 如果数量为负数 通过代码设置样式 private int mTypeNum = 0; //每个扇形旋转的时间 private int mVarTime = 0; //文字描述集合 private String[] mDeses; //自定义图标集合 private List<Bitmap> mIcons; //背景颜色 private Integer[] mColors; //整个旋转图的背景 只有类型为2时才需要 private Integer mMainImgRes = 0; //GO图标 private Integer mGoImgRes = 0; //圆环的图片引用 private Integer mHuanImgRes = 0; //文字大小 private float mTextSize = 0; //文字颜色 private int mTextColor = 0; public final WheelSurfView.Builder setmType(int mType) { this.mType = mType; return this; } public final WheelSurfView.Builder setmTypeNum(int mTypeNum) { this.mTypeNum = mTypeNum; return this; } public final WheelSurfView.Builder setmGoImgRes(int mGoImgRes) { this.mGoImgRes = mGoImgRes; return this; } public final WheelSurfView.Builder setmMinTimes(int mMinTimes) { this.mMinTimes = mMinTimes; return this; } public final WheelSurfView.Builder setmVarTime(int mVarTime) { this.mVarTime = mVarTime; return this; } public final WheelSurfView.Builder setmDeses(String[] mDeses) { this.mDeses = mDeses; return this; } public final WheelSurfView.Builder setmIcons(List<Bitmap> mIcons) { this.mIcons = mIcons; return this; } public final WheelSurfView.Builder setmColors(Integer[] mColors) { this.mColors = mColors; return this; } public final WheelSurfView.Builder setmMainImgRes(Integer mMainImgRes) { this.mMainImgRes = mMainImgRes; return this; } public final WheelSurfView.Builder setmHuanImgRes(Integer mHuanImgRes) { this.mHuanImgRes = mHuanImgRes; return this; } public final WheelSurfView.Builder setmTextSize(float mTextSize) { this.mTextSize = mTextSize; return this; } public final WheelSurfView.Builder setmTextColor(int mTextColor) { this.mTextColor = mTextColor; return this; } public final Builder build() { return this; } } //旋转图片 public static List<Bitmap> rotateBitmaps(List<Bitmap> source) { float mAngle = ( float ) (360.0 / source.size()); List<Bitmap> result = new ArrayList<>(); for ( int i = 0; i < source.size(); i++ ) { Bitmap bitmap = source.get(i); int ww = bitmap.getWidth(); int hh = bitmap.getHeight(); // 定义矩阵对象 Matrix matrix = new Matrix(); // 缩放原图 matrix.postScale(1f, 1f); // 向左旋转45度,参数为正则向右旋转 matrix.postRotate(mAngle * i); //bmp.getWidth(), 500分别表示重绘后的位图宽高 Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, ww, hh, matrix, true); result.add(dstbmp); } return result; } }
MZCretin/WheelSurfDemo
wheelsruflibrary/src/main/java/com/cretin/www/wheelsruflibrary/view/WheelSurfView.java
2,704
// 定义矩阵对象
line_comment
zh-cn
package com.cretin.www.wheelsruflibrary.view; import android.annotation.TargetApi; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Matrix; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.widget.ImageView; import android.widget.RelativeLayout; import com.cretin.www.wheelsruflibrary.R; import com.cretin.www.wheelsruflibrary.listener.RotateListener; import java.util.ArrayList; import java.util.List; /** * Created by cretin on 2017/12/26. */ public class WheelSurfView extends RelativeLayout { //当前的圆盘VIew private WheelSurfPanView mWheelSurfPanView; //Context private Context mContext; //开始按钮 private ImageView mStart; //动画回调监听 private RotateListener rotateListener; public void setRotateListener(RotateListener rotateListener) { mWheelSurfPanView.setRotateListener(rotateListener); this.rotateListener = rotateListener; } public WheelSurfView(Context context) { super(context); init(context, null); } public WheelSurfView(Context context, AttributeSet attrs) { super(context, attrs); init(context, attrs); } public WheelSurfView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs); } //开始抽奖的图标 private Integer mGoImgRes; private void init(Context context, AttributeSet attrs) { mContext = context; if ( attrs != null ) { //获得这个控件对应的属性。 TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.wheelSurfView); try { mGoImgRes = typedArray.getResourceId(R.styleable.wheelSurfView_goImg, 0); } finally { //回收这个对象 typedArray.recycle(); } } //添加圆盘视图 mWheelSurfPanView = new WheelSurfPanView(mContext, attrs); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT); mWheelSurfPanView.setLayoutParams(layoutParams); addView(mWheelSurfPanView); //添加开始按钮 mStart = new ImageView(mContext); //如果用户没有设置自定义的图标就使用默认的 if ( mGoImgRes == 0 ) { mStart.setImageResource(R.mipmap.node); } else { mStart.setImageResource(mGoImgRes); } //给图片设置LayoutParams RelativeLayout.LayoutParams llStart = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); llStart.addRule(RelativeLayout.CENTER_IN_PARENT); mStart.setLayoutParams(llStart); addView(mStart); mStart.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //调用此方法是将主动权交个调用者 由调用者调用开始旋转的方法 if ( rotateListener != null ) rotateListener.rotateBefore(( ImageView ) v); } }); } public void setConfig(Builder builder) { if ( builder.mColors != null ) mWheelSurfPanView.setmColors(builder.mColors); if ( builder.mDeses != null ) mWheelSurfPanView.setmDeses(builder.mDeses); if ( builder.mHuanImgRes != 0 ) mWheelSurfPanView.setmHuanImgRes(builder.mHuanImgRes); if ( builder.mIcons != null ) mWheelSurfPanView.setmIcons(builder.mIcons); if ( builder.mMainImgRes != 0 ) mWheelSurfPanView.setmMainImgRes(builder.mMainImgRes); if ( builder.mMinTimes != 0 ) mWheelSurfPanView.setmMinTimes(builder.mMinTimes); if ( builder.mTextColor != 0 ) mWheelSurfPanView.setmTextColor(builder.mTextColor); if ( builder.mTextSize != 0 ) mWheelSurfPanView.setmTextSize(builder.mTextSize); if ( builder.mType != 0 ) mWheelSurfPanView.setmType(builder.mType); if ( builder.mVarTime != 0 ) mWheelSurfPanView.setmVarTime(builder.mVarTime); if ( builder.mTypeNum != 0 ) mWheelSurfPanView.setmTypeNum(builder.mTypeNum); mWheelSurfPanView.show(); } /** * 开始旋转 * * @param pisition 旋转最终的位置 注意 从1 开始 而且是逆时针递增 */ public void startRotate(int pisition) { if ( mWheelSurfPanView != null ) { mWheelSurfPanView.startRotate(pisition); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { //视图是个正方形的 所以有宽就足够了 默认值是500 也就是WRAP_CONTENT的时候 setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec)); // Children are just made to fill our space. final int childWidthSize = getMeasuredWidth(); //高度和宽度一样 heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY); //onMeasure调用获取到当前视图大小之后, // 手动按照一定的比例计算出中间开始按钮的大小, // 再设置给那个按钮,免得造成用户传的图片不合适之后显示贼难看 // 只设置一次 if ( isFirst ) { isFirst = !isFirst; //获取中间按钮的大小 ViewTreeObserver vto = mStart.getViewTreeObserver(); vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @TargetApi( Build.VERSION_CODES.KITKAT ) @Override public void onGlobalLayout() { mStart.getViewTreeObserver().removeGlobalOnLayoutListener(this); float w = mStart.getMeasuredWidth(); float h = mStart.getMeasuredHeight(); //计算新的大小 默认为整个大小最大值的0.17 至于为什么是0.17 我只想说我乐意。。。。 int newW = ( int ) ((( float ) childWidthSize) * 0.17); int newH = ( int ) ((( float ) childWidthSize) * 0.17 * h / w); ViewGroup.LayoutParams layoutParams = mStart.getLayoutParams(); layoutParams.width = newW; layoutParams.height = newH; mStart.setLayoutParams(layoutParams); } }); } super.onMeasure(widthMeasureSpec, heightMeasureSpec); } //记录当前是否是第一次回调onMeasure private boolean isFirst = true; //建造者模式 public static final class Builder { //当前类型 1 自定义模式 2 暴力模式 private int mType = 0; //最低圈数 默认值3 也就是说每次旋转都会最少转3圈 private int mMinTimes = 0; //分类数量 如果数量为负数 通过代码设置样式 private int mTypeNum = 0; //每个扇形旋转的时间 private int mVarTime = 0; //文字描述集合 private String[] mDeses; //自定义图标集合 private List<Bitmap> mIcons; //背景颜色 private Integer[] mColors; //整个旋转图的背景 只有类型为2时才需要 private Integer mMainImgRes = 0; //GO图标 private Integer mGoImgRes = 0; //圆环的图片引用 private Integer mHuanImgRes = 0; //文字大小 private float mTextSize = 0; //文字颜色 private int mTextColor = 0; public final WheelSurfView.Builder setmType(int mType) { this.mType = mType; return this; } public final WheelSurfView.Builder setmTypeNum(int mTypeNum) { this.mTypeNum = mTypeNum; return this; } public final WheelSurfView.Builder setmGoImgRes(int mGoImgRes) { this.mGoImgRes = mGoImgRes; return this; } public final WheelSurfView.Builder setmMinTimes(int mMinTimes) { this.mMinTimes = mMinTimes; return this; } public final WheelSurfView.Builder setmVarTime(int mVarTime) { this.mVarTime = mVarTime; return this; } public final WheelSurfView.Builder setmDeses(String[] mDeses) { this.mDeses = mDeses; return this; } public final WheelSurfView.Builder setmIcons(List<Bitmap> mIcons) { this.mIcons = mIcons; return this; } public final WheelSurfView.Builder setmColors(Integer[] mColors) { this.mColors = mColors; return this; } public final WheelSurfView.Builder setmMainImgRes(Integer mMainImgRes) { this.mMainImgRes = mMainImgRes; return this; } public final WheelSurfView.Builder setmHuanImgRes(Integer mHuanImgRes) { this.mHuanImgRes = mHuanImgRes; return this; } public final WheelSurfView.Builder setmTextSize(float mTextSize) { this.mTextSize = mTextSize; return this; } public final WheelSurfView.Builder setmTextColor(int mTextColor) { this.mTextColor = mTextColor; return this; } public final Builder build() { return this; } } //旋转图片 public static List<Bitmap> rotateBitmaps(List<Bitmap> source) { float mAngle = ( float ) (360.0 / source.size()); List<Bitmap> result = new ArrayList<>(); for ( int i = 0; i < source.size(); i++ ) { Bitmap bitmap = source.get(i); int ww = bitmap.getWidth(); int hh = bitmap.getHeight(); // 定义 <SUF> Matrix matrix = new Matrix(); // 缩放原图 matrix.postScale(1f, 1f); // 向左旋转45度,参数为正则向右旋转 matrix.postRotate(mAngle * i); //bmp.getWidth(), 500分别表示重绘后的位图宽高 Bitmap dstbmp = Bitmap.createBitmap(bitmap, 0, 0, ww, hh, matrix, true); result.add(dstbmp); } return result; } }
false
2,411
6
2,708
5
2,748
4
2,704
5
3,395
12
false
false
false
false
false
true
39725_0
package thread; public class ResortSeqDemo { int a=0; boolean flag=false; /* 多线程下flag=true可能先执行,还没走到a=1就被挂起。 其它线程进入method02的判断,修改a的值=5,而不是6。 */ public void method01(){ a=1; flag=true; } public void method02(){ if (flag){ a+=5; System.out.println("*****retValue: "+a); } } }
MaJesTySA/JVM-JUC-Core
src/thread/ResortSeqDemo.java
130
/* 多线程下flag=true可能先执行,还没走到a=1就被挂起。 其它线程进入method02的判断,修改a的值=5,而不是6。 */
block_comment
zh-cn
package thread; public class ResortSeqDemo { int a=0; boolean flag=false; /* 多线程 <SUF>*/ public void method01(){ a=1; flag=true; } public void method02(){ if (flag){ a+=5; System.out.println("*****retValue: "+a); } } }
false
120
47
130
48
138
45
130
48
164
67
false
false
false
false
false
true
380_3
package com.iguigui.maaj.easySample; import com.sun.jna.Pointer; import com.sun.jna.win32.StdCallLibrary; //本质上是对C接口的抽象层 //请参考C接口 https://github.com/MaaAssistantArknights/MaaAssistantArknights/blob/master/include/AsstCaller.h public interface MaaCore extends StdCallLibrary { //回调接口定义 interface AsstApiCallback extends StdCallCallback { void callback(int msg, String detail_json, String custom_arg); } //第一步,加载资源 boolean AsstLoadResource(String path); //选一个你喜欢的create,搞不定回调就用普通create,又不是不能用 Pointer AsstCreate(); /** * 带回调的实例创建 * @param callback 回调方法实例 * @param custom_arg 用户参数,塞什么进去回头就给你回调的时候返回什么,例如填入自己生成的实例ID,回调回来就可以用于查询是哪个实例的回调信息 * @return */ Pointer AsstCreateEx(AsstApiCallback callback, String custom_arg); //销毁实例释放连接 void AsstDestroy(Pointer handle); //连接安卓 boolean AsstConnect(Pointer handle, String adb, String host, String config); //添加任务链 //参考集成文档 https://github.com/MaaAssistantArknights/MaaAssistantArknights/blob/master/docs/3.1-%E9%9B%86%E6%88%90%E6%96%87%E6%A1%A3.md int AsstAppendTask(Pointer handle, String type, String params); //运行时修改参数 boolean AsstSetTaskParams(Pointer handle, int taskId, String params); //开跑! boolean AsstStart(Pointer handle); //爷不想跑了爷要自己玩 boolean AsstStop(Pointer handle); /** * 获取最后一次截图的内容 * (但是这个接口我就没成功用上过 * @param handle Maa实例 * @param buff 图片PNG格式编码内容 * @param buff_size byte[]的长度 * @return 图片长度 */ long AsstGetImage(Pointer handle, byte[] buff, long buff_size); //模拟点击 boolean AsstCtrlerClick(Pointer handle, int x, int y, boolean block); //获取版本号 String AsstGetVersion(); //向maa注入日志 void AsstLog(String level, String message); }
MaaAssistantArknights/MaaAssistantArknights
src/Java/src/main/java/com/iguigui/maaj/easySample/MaaCore.java
616
//第一步,加载资源
line_comment
zh-cn
package com.iguigui.maaj.easySample; import com.sun.jna.Pointer; import com.sun.jna.win32.StdCallLibrary; //本质上是对C接口的抽象层 //请参考C接口 https://github.com/MaaAssistantArknights/MaaAssistantArknights/blob/master/include/AsstCaller.h public interface MaaCore extends StdCallLibrary { //回调接口定义 interface AsstApiCallback extends StdCallCallback { void callback(int msg, String detail_json, String custom_arg); } //第一 <SUF> boolean AsstLoadResource(String path); //选一个你喜欢的create,搞不定回调就用普通create,又不是不能用 Pointer AsstCreate(); /** * 带回调的实例创建 * @param callback 回调方法实例 * @param custom_arg 用户参数,塞什么进去回头就给你回调的时候返回什么,例如填入自己生成的实例ID,回调回来就可以用于查询是哪个实例的回调信息 * @return */ Pointer AsstCreateEx(AsstApiCallback callback, String custom_arg); //销毁实例释放连接 void AsstDestroy(Pointer handle); //连接安卓 boolean AsstConnect(Pointer handle, String adb, String host, String config); //添加任务链 //参考集成文档 https://github.com/MaaAssistantArknights/MaaAssistantArknights/blob/master/docs/3.1-%E9%9B%86%E6%88%90%E6%96%87%E6%A1%A3.md int AsstAppendTask(Pointer handle, String type, String params); //运行时修改参数 boolean AsstSetTaskParams(Pointer handle, int taskId, String params); //开跑! boolean AsstStart(Pointer handle); //爷不想跑了爷要自己玩 boolean AsstStop(Pointer handle); /** * 获取最后一次截图的内容 * (但是这个接口我就没成功用上过 * @param handle Maa实例 * @param buff 图片PNG格式编码内容 * @param buff_size byte[]的长度 * @return 图片长度 */ long AsstGetImage(Pointer handle, byte[] buff, long buff_size); //模拟点击 boolean AsstCtrlerClick(Pointer handle, int x, int y, boolean block); //获取版本号 String AsstGetVersion(); //向maa注入日志 void AsstLog(String level, String message); }
false
558
5
616
6
595
5
616
6
822
13
false
false
false
false
false
true
51092_0
package cn.edu.hrbu.mall.aop; import org.aopalliance.intercept.Joinpoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; // 切面类 @Component @Aspect // 声明当前类是一个切面类 public class Fbi { // 切面类中的方法通常称为通知 // 前置通知 @Before("execution(* cn..Man.eat(*))") // 切入点表达式 public void beforeAdvice(){ System.out.println("执行前置通知,FBI正在调查"); } // 后置通知,连接点之后执行 @After("within(cn..Man)") public void afterAdvice(){ System.out.println("执行后置通知,FBI正在记录"); } // 返回后通知,返回后通知是在目标方法执行之后(Return)执行的 @AfterReturning(pointcut = "execution(* cn..Man.call())", returning = "ret") public void afterReturningAdvice(Object ret){ System.out.printf("执行返回后通知,FBI发现了,截获情报(%s)\t" , ret); } // 异常通知,异常通知是在目标方法执行过程中出现异常时执行的 @AfterThrowing(pointcut = "execution(* cn..Man.drive())", throwing = "exception") public void afterThrowingAdvice(Exception exception){ System.out.println("执行异常通知,FBI发现了异常:" + exception.getMessage()); } // 环绕通知,环绕通知是在目标方法执行之前和之后执行的,可以包裹连接点代码,是唯一可以控制目标方法(连接点)执行的通知 @Around("within(cn..Man)") public Object aroundAdvice(ProceedingJoinPoint joinpoint) throws Throwable{ System.out.println("执行环绕通知(前半部分),FBI正在调查"); Object[] args = joinpoint.getArgs(); Object ret = joinpoint.proceed(); System.out.println("执行环绕通知(后半部分),FBI正在记录"); return ret; } }
MadridWen/Study-MybatisAndSpring
mall/src/main/java/cn/edu/hrbu/mall/aop/Fbi.java
516
// 切面类
line_comment
zh-cn
package cn.edu.hrbu.mall.aop; import org.aopalliance.intercept.Joinpoint; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; // 切面 <SUF> @Component @Aspect // 声明当前类是一个切面类 public class Fbi { // 切面类中的方法通常称为通知 // 前置通知 @Before("execution(* cn..Man.eat(*))") // 切入点表达式 public void beforeAdvice(){ System.out.println("执行前置通知,FBI正在调查"); } // 后置通知,连接点之后执行 @After("within(cn..Man)") public void afterAdvice(){ System.out.println("执行后置通知,FBI正在记录"); } // 返回后通知,返回后通知是在目标方法执行之后(Return)执行的 @AfterReturning(pointcut = "execution(* cn..Man.call())", returning = "ret") public void afterReturningAdvice(Object ret){ System.out.printf("执行返回后通知,FBI发现了,截获情报(%s)\t" , ret); } // 异常通知,异常通知是在目标方法执行过程中出现异常时执行的 @AfterThrowing(pointcut = "execution(* cn..Man.drive())", throwing = "exception") public void afterThrowingAdvice(Exception exception){ System.out.println("执行异常通知,FBI发现了异常:" + exception.getMessage()); } // 环绕通知,环绕通知是在目标方法执行之前和之后执行的,可以包裹连接点代码,是唯一可以控制目标方法(连接点)执行的通知 @Around("within(cn..Man)") public Object aroundAdvice(ProceedingJoinPoint joinpoint) throws Throwable{ System.out.println("执行环绕通知(前半部分),FBI正在调查"); Object[] args = joinpoint.getArgs(); Object ret = joinpoint.proceed(); System.out.println("执行环绕通知(后半部分),FBI正在记录"); return ret; } }
false
456
6
509
6
501
5
509
6
716
6
false
false
false
false
false
true
31537_25
//package net.mafuyu33.mafishmod.networking.packet; // //import net.fabricmc.fabric.api.networking.v1.PacketSender; //import net.mafuyu33.mafishmod.mixinhelper.BowDashMixinHelper; //import net.mafuyu33.mafishmod.particle.ParticleStorage; //import net.minecraft.entity.Entity; //import net.minecraft.entity.LivingEntity; //import net.minecraft.entity.player.PlayerEntity; //import net.minecraft.network.PacketByteBuf; //import net.minecraft.server.MinecraftServer; //import net.minecraft.server.network.ServerPlayNetworkHandler; //import net.minecraft.server.network.ServerPlayerEntity; //import net.minecraft.util.math.Box; //import net.minecraft.util.math.Vec3d; // //import java.util.List; // //public class ParticleColorC2SPacket { // // public static void receive(MinecraftServer server, ServerPlayerEntity player, ServerPlayNetworkHandler handler, // PacketByteBuf buf, PacketSender responseSender) { // int id = buf.readInt(); //// Vec3d pos = ParticleStorage.getOrCreateForWorld().getUUIDByPosition(); // if(pos!=null) { // //想办法让碰到这个粒子的生物(除了玩家被击退+受伤) // // 获取范围内的所有生物 // Box box1 = new Box(pos.x - 1.0, pos.y - 1.0, pos.z - 1.0, pos.x + 1.0, pos.y + 1.0, pos.z + 1.0); // Box box2 = new Box(pos.x - 0.1, pos.y - 0.1, pos.z - 0.1, pos.x + 0.1, pos.y + 0.1, pos.z + 0.1); // List<Entity> entities = player.getWorld().getOtherEntities(null, box1, entity -> entity instanceof LivingEntity && !(entity instanceof PlayerEntity)); // // 遍历每个生物并检查碰撞 // for (Entity entity : entities) { // if (entity.getBoundingBox().intersects(box2)) { // System.out.println("碰撞!"); // // 碰到生物时,除了玩家之外,对其进行击退和受伤 // if (entity instanceof LivingEntity livingEntity) { // System.out.println("造成伤害!"); // Vec3d knockBackVec = new Vec3d(entity.getX() - pos.x, entity.getY() - pos.y, entity.getZ() - pos.z).normalize().multiply(-1.0); // 计算击退向量 // livingEntity.takeKnockback(1.0f, knockBackVec.x, knockBackVec.z); // 进行击退 // livingEntity.damage(player.getWorld().getDamageSources().magic(), 1.0f); // 造成伤害 // } // } // } // } // } //}
Mafuyu33/mafishmod
src/main/java/net/mafuyu33/mafishmod/networking/packet/C2S/ParticleColorC2SPacket.java
776
// // 遍历每个生物并检查碰撞
line_comment
zh-cn
//package net.mafuyu33.mafishmod.networking.packet; // //import net.fabricmc.fabric.api.networking.v1.PacketSender; //import net.mafuyu33.mafishmod.mixinhelper.BowDashMixinHelper; //import net.mafuyu33.mafishmod.particle.ParticleStorage; //import net.minecraft.entity.Entity; //import net.minecraft.entity.LivingEntity; //import net.minecraft.entity.player.PlayerEntity; //import net.minecraft.network.PacketByteBuf; //import net.minecraft.server.MinecraftServer; //import net.minecraft.server.network.ServerPlayNetworkHandler; //import net.minecraft.server.network.ServerPlayerEntity; //import net.minecraft.util.math.Box; //import net.minecraft.util.math.Vec3d; // //import java.util.List; // //public class ParticleColorC2SPacket { // // public static void receive(MinecraftServer server, ServerPlayerEntity player, ServerPlayNetworkHandler handler, // PacketByteBuf buf, PacketSender responseSender) { // int id = buf.readInt(); //// Vec3d pos = ParticleStorage.getOrCreateForWorld().getUUIDByPosition(); // if(pos!=null) { // //想办法让碰到这个粒子的生物(除了玩家被击退+受伤) // // 获取范围内的所有生物 // Box box1 = new Box(pos.x - 1.0, pos.y - 1.0, pos.z - 1.0, pos.x + 1.0, pos.y + 1.0, pos.z + 1.0); // Box box2 = new Box(pos.x - 0.1, pos.y - 0.1, pos.z - 0.1, pos.x + 0.1, pos.y + 0.1, pos.z + 0.1); // List<Entity> entities = player.getWorld().getOtherEntities(null, box1, entity -> entity instanceof LivingEntity && !(entity instanceof PlayerEntity)); // // 遍历 <SUF> // for (Entity entity : entities) { // if (entity.getBoundingBox().intersects(box2)) { // System.out.println("碰撞!"); // // 碰到生物时,除了玩家之外,对其进行击退和受伤 // if (entity instanceof LivingEntity livingEntity) { // System.out.println("造成伤害!"); // Vec3d knockBackVec = new Vec3d(entity.getX() - pos.x, entity.getY() - pos.y, entity.getZ() - pos.z).normalize().multiply(-1.0); // 计算击退向量 // livingEntity.takeKnockback(1.0f, knockBackVec.x, knockBackVec.z); // 进行击退 // livingEntity.damage(player.getWorld().getDamageSources().magic(), 1.0f); // 造成伤害 // } // } // } // } // } //}
false
626
12
776
14
727
10
776
14
896
25
false
false
false
false
false
true
7973_9
package com.antony.mail; import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendMail { public static void main(String[] args) { try { Properties p = new Properties(); p.put("mail.smtp.auth", "true"); p.put("mail.transport.protocol", "smtp"); p.put("mail.smtp.host", "smtp.ym.163.com"); p.put("mail.smtp.port", "25"); // 建立会话 Session session = Session.getInstance(p); Message msg = new MimeMessage(session); // 建立信息 msg.setFrom(new InternetAddress("[email protected]")); // 发件人 msg.setRecipient(Message.RecipientType.TO, new InternetAddress( "[email protected]")); // 收件人 msg.setSentDate(new Date()); // 发送日期 msg.setSubject("答话稀有"); // 主题 msg.setText("快点下在"); // 内容 // 邮件服务器进行验证 Transport tran = session.getTransport("smtp"); tran.connect("smtp.ym.163.com", "[email protected]", "admin1234"); // bluebit_cn是用户名,xiaohao是密码 tran.sendMessage(msg, msg.getAllRecipients()); // 发送 System.out.println("邮件发送成功"); } catch (Exception e) { e.printStackTrace(); } } }
ManGroup/Demo
Che/src/com/antony/mail/SendMail.java
389
// 发送
line_comment
zh-cn
package com.antony.mail; import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class SendMail { public static void main(String[] args) { try { Properties p = new Properties(); p.put("mail.smtp.auth", "true"); p.put("mail.transport.protocol", "smtp"); p.put("mail.smtp.host", "smtp.ym.163.com"); p.put("mail.smtp.port", "25"); // 建立会话 Session session = Session.getInstance(p); Message msg = new MimeMessage(session); // 建立信息 msg.setFrom(new InternetAddress("[email protected]")); // 发件人 msg.setRecipient(Message.RecipientType.TO, new InternetAddress( "[email protected]")); // 收件人 msg.setSentDate(new Date()); // 发送日期 msg.setSubject("答话稀有"); // 主题 msg.setText("快点下在"); // 内容 // 邮件服务器进行验证 Transport tran = session.getTransport("smtp"); tran.connect("smtp.ym.163.com", "[email protected]", "admin1234"); // bluebit_cn是用户名,xiaohao是密码 tran.sendMessage(msg, msg.getAllRecipients()); // 发送 <SUF> System.out.println("邮件发送成功"); } catch (Exception e) { e.printStackTrace(); } } }
false
335
4
386
4
373
3
386
4
500
5
false
false
false
false
false
true
58266_0
package sample; public class Support { //程序能够显示的图片格式包括:.JPG、.JPEG、.GIF、.PNG、和.BMP。 public static String path = "suffix.equals(\"jpg\")||suffix.equals(\"JPG\")||suffix.equals(\"png\")||suffix.equals(\"BMP\")\n" + " ||suffix.equals(\"GIF\")||suffix.equals(\"JPEG\")||suffix.equals(\"gif\")"; }
Maoxim/picture-management-programe-JavaFX
Support.java
104
//程序能够显示的图片格式包括:.JPG、.JPEG、.GIF、.PNG、和.BMP。
line_comment
zh-cn
package sample; public class Support { //程序 <SUF> public static String path = "suffix.equals(\"jpg\")||suffix.equals(\"JPG\")||suffix.equals(\"png\")||suffix.equals(\"BMP\")\n" + " ||suffix.equals(\"GIF\")||suffix.equals(\"JPEG\")||suffix.equals(\"gif\")"; }
false
94
26
104
26
109
24
104
26
154
41
false
false
false
false
false
true
19834_1
package com.tqe.po; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.alibaba.fastjson.JSON; import org.apache.commons.lang3.StringUtils; /** * 评教表 */ public class EvalTable { private Integer id; private String type; //评教表的类型 private String title; //评教表的标题 private String note; //评教须知 private List<EvalItem> itemList = new ArrayList<EvalItem>(); //表单信息 private List<EvalTableItem> tableItemList =new ArrayList<EvalTableItem>(); //打分表 private List<EvalItem> questionList =new ArrayList<EvalItem>(); //问题表 private Date createDate; //创建时间 private String jsonString; //序列化表 private String score; //得分 private String level; //评价结果等级 public String getType() { return type; } public void setType(String type) { this.type = type; } public static class EvalItem { private String context; private String ans; public EvalItem() { } public EvalItem(String context, String ans) { super(); this.context = context; this.ans = ans; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public String getAns() { return ans; } public void setAns(String ans) { if(ans!=null && ans.length()>255){ //截取 数据库不能存放字数大于 255 的 答案 ans = ans.substring(255); } this.ans = ans; } @Override public String toString() { return "EvalItem{" + "context='" + context + '\'' + ", ans='" + ans + '\'' + '}'; } } public static class EvalTableItem { private String context; //文本 private String level; //等级 private Integer ans; //回答(得分) private Integer avgScore; //平均得分 private List<Integer> scoreLevelCnts; //得分等级统计 private Integer maxLevel; //最大分 private Integer percent; //平均得分百分比 public EvalTableItem() { super(); } public EvalTableItem(String context, String level, Integer ans) { super(); this.context = context; this.level = level; this.ans = ans; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public Integer getAns() { return ans; } public void setAns(Integer ans) { this.ans = ans; } public Integer getAvgScore() { return avgScore; } public void setAvgScore(Integer avgScore) { this.avgScore = avgScore; } public List<Integer> getScoreLevelCnts() { return scoreLevelCnts; } public void setScoreLevelCnts(List<Integer> scoreLevelCnts) { this.scoreLevelCnts = scoreLevelCnts; } @Override public String toString() { return "EvalTableItem{" + "context='" + context + '\'' + ", level='" + level + '\'' + ", ans=" + ans + ", avgScore=" + avgScore + ", scoreLevelCnts=" + scoreLevelCnts + '}'; } public Integer getMaxLevel() { return maxLevel; } public void setMaxLevel(Integer maxLevel) { this.maxLevel = maxLevel; } public Integer getPercent() { return percent; } public void setPercent(Integer percent) { this.percent = percent; } } public EvalTable() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public List<EvalItem> getItemList() { return itemList; } public void setItemList(List<EvalItem> itemList) { this.itemList = itemList; } public List<EvalTableItem> getTableItemList() { return tableItemList; } public void setTableItemList(List<EvalTableItem> tableItemList) { this.tableItemList = tableItemList; } public String getJsonString() { return jsonString; } public void setJsonString(String jsonString) { this.jsonString = jsonString; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public List<EvalItem> getQuestionList() { return questionList; } public void setQuestionList(List<EvalItem> questionList) { this.questionList = questionList; } /** * 将评教表中的JSON内容序列化成内存对象 */ public EvalTable json2Object(){ EvalTable tem = JSON.parseObject(this.getJsonString(), EvalTable.class); this.setItemList(tem.getItemList()); this.setQuestionList(tem.getQuestionList()); this.setTableItemList(tem.getTableItemList()); return this; } public static EvalTable json2Object(String jsonString){ if(StringUtils.isNoneBlank(jsonString)){ return JSON.parseObject(jsonString, EvalTable.class); } return null; } public void setAns(EvalTable src,EvalTable ans){ for(int i=0;i<src.getItemList().size();i++){ src.getItemList().get(i).setAns(ans.getItemList().get(i).getAns()); } for(int i=0;i<src.getTableItemList().size();i++){ src.getTableItemList().get(i).setAns(ans.getTableItemList().get(i).getAns()); } for(int i=0;i<src.getQuestionList().size();i++){ src.getQuestionList().get(i).setAns(ans.getQuestionList().get(i).getAns()); } } public String getScore() { return score; } public void setScore(String score) { this.score = score; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } @Override public String toString() { return "EvalTable{" + "id=" + id + ", title='" + title + '\'' + ", note='" + note + '\'' + ", itemList=" + itemList + ", tableItemList=" + tableItemList + ", questionList=" + questionList + ", createDate=" + createDate + ", jsonString='" + jsonString + '\'' + ", score='" + score + '\'' + ", level='" + level + '\'' + '}'; } }
MapleWhisper/TQE
src/com/tqe/po/EvalTable.java
1,890
//评教表的类型
line_comment
zh-cn
package com.tqe.po; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.alibaba.fastjson.JSON; import org.apache.commons.lang3.StringUtils; /** * 评教表 */ public class EvalTable { private Integer id; private String type; //评教 <SUF> private String title; //评教表的标题 private String note; //评教须知 private List<EvalItem> itemList = new ArrayList<EvalItem>(); //表单信息 private List<EvalTableItem> tableItemList =new ArrayList<EvalTableItem>(); //打分表 private List<EvalItem> questionList =new ArrayList<EvalItem>(); //问题表 private Date createDate; //创建时间 private String jsonString; //序列化表 private String score; //得分 private String level; //评价结果等级 public String getType() { return type; } public void setType(String type) { this.type = type; } public static class EvalItem { private String context; private String ans; public EvalItem() { } public EvalItem(String context, String ans) { super(); this.context = context; this.ans = ans; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public String getAns() { return ans; } public void setAns(String ans) { if(ans!=null && ans.length()>255){ //截取 数据库不能存放字数大于 255 的 答案 ans = ans.substring(255); } this.ans = ans; } @Override public String toString() { return "EvalItem{" + "context='" + context + '\'' + ", ans='" + ans + '\'' + '}'; } } public static class EvalTableItem { private String context; //文本 private String level; //等级 private Integer ans; //回答(得分) private Integer avgScore; //平均得分 private List<Integer> scoreLevelCnts; //得分等级统计 private Integer maxLevel; //最大分 private Integer percent; //平均得分百分比 public EvalTableItem() { super(); } public EvalTableItem(String context, String level, Integer ans) { super(); this.context = context; this.level = level; this.ans = ans; } public String getContext() { return context; } public void setContext(String context) { this.context = context; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public Integer getAns() { return ans; } public void setAns(Integer ans) { this.ans = ans; } public Integer getAvgScore() { return avgScore; } public void setAvgScore(Integer avgScore) { this.avgScore = avgScore; } public List<Integer> getScoreLevelCnts() { return scoreLevelCnts; } public void setScoreLevelCnts(List<Integer> scoreLevelCnts) { this.scoreLevelCnts = scoreLevelCnts; } @Override public String toString() { return "EvalTableItem{" + "context='" + context + '\'' + ", level='" + level + '\'' + ", ans=" + ans + ", avgScore=" + avgScore + ", scoreLevelCnts=" + scoreLevelCnts + '}'; } public Integer getMaxLevel() { return maxLevel; } public void setMaxLevel(Integer maxLevel) { this.maxLevel = maxLevel; } public Integer getPercent() { return percent; } public void setPercent(Integer percent) { this.percent = percent; } } public EvalTable() { super(); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public List<EvalItem> getItemList() { return itemList; } public void setItemList(List<EvalItem> itemList) { this.itemList = itemList; } public List<EvalTableItem> getTableItemList() { return tableItemList; } public void setTableItemList(List<EvalTableItem> tableItemList) { this.tableItemList = tableItemList; } public String getJsonString() { return jsonString; } public void setJsonString(String jsonString) { this.jsonString = jsonString; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public List<EvalItem> getQuestionList() { return questionList; } public void setQuestionList(List<EvalItem> questionList) { this.questionList = questionList; } /** * 将评教表中的JSON内容序列化成内存对象 */ public EvalTable json2Object(){ EvalTable tem = JSON.parseObject(this.getJsonString(), EvalTable.class); this.setItemList(tem.getItemList()); this.setQuestionList(tem.getQuestionList()); this.setTableItemList(tem.getTableItemList()); return this; } public static EvalTable json2Object(String jsonString){ if(StringUtils.isNoneBlank(jsonString)){ return JSON.parseObject(jsonString, EvalTable.class); } return null; } public void setAns(EvalTable src,EvalTable ans){ for(int i=0;i<src.getItemList().size();i++){ src.getItemList().get(i).setAns(ans.getItemList().get(i).getAns()); } for(int i=0;i<src.getTableItemList().size();i++){ src.getTableItemList().get(i).setAns(ans.getTableItemList().get(i).getAns()); } for(int i=0;i<src.getQuestionList().size();i++){ src.getQuestionList().get(i).setAns(ans.getQuestionList().get(i).getAns()); } } public String getScore() { return score; } public void setScore(String score) { this.score = score; } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } @Override public String toString() { return "EvalTable{" + "id=" + id + ", title='" + title + '\'' + ", note='" + note + '\'' + ", itemList=" + itemList + ", tableItemList=" + tableItemList + ", questionList=" + questionList + ", createDate=" + createDate + ", jsonString='" + jsonString + '\'' + ", score='" + score + '\'' + ", level='" + level + '\'' + '}'; } }
false
1,586
6
1,890
6
1,907
5
1,890
6
2,344
9
false
false
false
false
false
true
65184_1
package com.zhaopin.po; import java.io.Serializable; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import org.springframework.stereotype.Component; @Entity @Component public class User implements Serializable{ private Integer id; //id private String username; //用户名 private String password; //密码 private String name; //姓名 private String email; //邮箱 private String phoneNumber; //手机号 private Resume resume; //简历 private Set<Apply> applys; //申请 @Id @GeneratedValue(strategy=GenerationType.AUTO) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(unique=true) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(unique=true) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } @OneToOne(cascade=CascadeType.ALL) @JoinColumn(insertable=true,unique=true,name="resume_id") public Resume getResume() { return resume; } public void setResume(Resume resume) { this.resume = resume; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } @OneToMany(cascade={CascadeType.ALL},mappedBy="user") @OrderBy("applyDate") public Set<Apply> getApplys() { return applys; } public void setApplys(Set<Apply> applys) { this.applys = applys; } }
MapleWhisper/ZhaoPin
src/com/zhaopin/po/User.java
647
//手机号
line_comment
zh-cn
package com.zhaopin.po; import java.io.Serializable; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import javax.persistence.OrderBy; import org.springframework.stereotype.Component; @Entity @Component public class User implements Serializable{ private Integer id; //id private String username; //用户名 private String password; //密码 private String name; //姓名 private String email; //邮箱 private String phoneNumber; //手机 <SUF> private Resume resume; //简历 private Set<Apply> applys; //申请 @Id @GeneratedValue(strategy=GenerationType.AUTO) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(unique=true) public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(unique=true) public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhoneNumber() { return phoneNumber; } @OneToOne(cascade=CascadeType.ALL) @JoinColumn(insertable=true,unique=true,name="resume_id") public Resume getResume() { return resume; } public void setResume(Resume resume) { this.resume = resume; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } @OneToMany(cascade={CascadeType.ALL},mappedBy="user") @OrderBy("applyDate") public Set<Apply> getApplys() { return applys; } public void setApplys(Set<Apply> applys) { this.applys = applys; } }
false
469
2
647
3
625
2
647
3
755
4
false
false
false
false
false
true
10563_17
package com.wjc.simpletranslate.model; import java.util.ArrayList; /** * Created by lizhaotailang on 2017/1/1. */ // sample // { // "word": "hi", // "pronunciation": { // "AmE": "haɪ", // "AmEmp3": "https://dictionary.blob.core.chinacloudapi.cn/media/audio/tom/f6/23/F623F7E637597678EB59B9A92D064234.mp3", // "BrE": "haɪ", // "BrEmp3": "https://dictionary.blob.core.chinacloudapi.cn/media/audio/george/f6/23/F623F7E637597678EB59B9A92D064234.mp3" // }, // "defs": // [ // { // "pos": "int.", // "def": "〈非正式〉嗨" // }, // { // "pos": "abbr.", // "def": "夏威夷群岛的书面缩写(=high intensity)高强度" // }, // { // "pos": "Web", // "def": "你好;血凝抑制(hemagglutination inhibition);打招呼" // } // ], // "sams": // [ // { // "eng": "Hi, buddy, he said he likes Peking duck, How about you?", // "chn": "嘿,伙计,他说他喜欢北京烤鸭,你呢?", // "mp3Url": "https://dictionary.blob.core.chinacloudapi.cn/media/audio/tom/66/28/662826A26E031E6DC75C29883B369509.mp3", // "mp4Url": "https://dictionary.blob.core.chinacloudapi.cn/media/video/cissy/66/28/662826A26E031E6DC75C29883B369509.mp4" // } // ] // } public class BingModel { private String word; private Pronunciation pronunciation; private ArrayList<Definition> defs; private ArrayList<Sample> sams; public String getWord() { return word; } public void setWord(String word) { this.word = word; } public Pronunciation getPronunciation() { return pronunciation; } public void setPronunciation(Pronunciation pronunciation) { this.pronunciation = pronunciation; } public ArrayList<Definition> getDefs() { return defs; } public void setDefs(ArrayList<Definition> defs) { this.defs = defs; } public ArrayList<Sample> getSams() { return sams; } public void setSams(ArrayList<Sample> sams) { this.sams = sams; } public class Pronunciation { private String AmE; private String AmEmp3; private String BrE; private String BrEmp3; public String getAmE() { return AmE; } public void setAmE(String amE) { AmE = amE; } public String getAmEmp3() { return AmEmp3; } public void setAmEmp3(String amEmp3) { AmEmp3 = amEmp3; } public String getBrE() { return BrE; } public void setBrE(String brE) { BrE = brE; } public String getBrEmp3() { return BrEmp3; } public void setBrEmp3(String brEmp3) { BrEmp3 = brEmp3; } } public class Definition { private String pos; private String def; public String getPos() { return pos; } public void setPos(String pos) { this.pos = pos; } public String getDef() { return def; } public void setDef(String def) { this.def = def; } } public class Sample { private String eng; private String chn; private String mp3Url; private String mp4Url; public String getEng() { return eng; } public void setEng(String eng) { this.eng = eng; } public String getChn() { return chn; } public void setChn(String chn) { this.chn = chn; } public String getMp3Url() { return mp3Url; } public void setMp3Url(String mp3Url) { this.mp3Url = mp3Url; } public String getMp4Url() { return mp4Url; } public void setMp4Url(String mp4Url) { this.mp4Url = mp4Url; } } }
MarkFrank01/HappyEnglish
app/src/main/java/com/wjc/simpletranslate/model/BingModel.java
1,291
// "chn": "嘿,伙计,他说他喜欢北京烤鸭,你呢?",
line_comment
zh-cn
package com.wjc.simpletranslate.model; import java.util.ArrayList; /** * Created by lizhaotailang on 2017/1/1. */ // sample // { // "word": "hi", // "pronunciation": { // "AmE": "haɪ", // "AmEmp3": "https://dictionary.blob.core.chinacloudapi.cn/media/audio/tom/f6/23/F623F7E637597678EB59B9A92D064234.mp3", // "BrE": "haɪ", // "BrEmp3": "https://dictionary.blob.core.chinacloudapi.cn/media/audio/george/f6/23/F623F7E637597678EB59B9A92D064234.mp3" // }, // "defs": // [ // { // "pos": "int.", // "def": "〈非正式〉嗨" // }, // { // "pos": "abbr.", // "def": "夏威夷群岛的书面缩写(=high intensity)高强度" // }, // { // "pos": "Web", // "def": "你好;血凝抑制(hemagglutination inhibition);打招呼" // } // ], // "sams": // [ // { // "eng": "Hi, buddy, he said he likes Peking duck, How about you?", // "c <SUF> // "mp3Url": "https://dictionary.blob.core.chinacloudapi.cn/media/audio/tom/66/28/662826A26E031E6DC75C29883B369509.mp3", // "mp4Url": "https://dictionary.blob.core.chinacloudapi.cn/media/video/cissy/66/28/662826A26E031E6DC75C29883B369509.mp4" // } // ] // } public class BingModel { private String word; private Pronunciation pronunciation; private ArrayList<Definition> defs; private ArrayList<Sample> sams; public String getWord() { return word; } public void setWord(String word) { this.word = word; } public Pronunciation getPronunciation() { return pronunciation; } public void setPronunciation(Pronunciation pronunciation) { this.pronunciation = pronunciation; } public ArrayList<Definition> getDefs() { return defs; } public void setDefs(ArrayList<Definition> defs) { this.defs = defs; } public ArrayList<Sample> getSams() { return sams; } public void setSams(ArrayList<Sample> sams) { this.sams = sams; } public class Pronunciation { private String AmE; private String AmEmp3; private String BrE; private String BrEmp3; public String getAmE() { return AmE; } public void setAmE(String amE) { AmE = amE; } public String getAmEmp3() { return AmEmp3; } public void setAmEmp3(String amEmp3) { AmEmp3 = amEmp3; } public String getBrE() { return BrE; } public void setBrE(String brE) { BrE = brE; } public String getBrEmp3() { return BrEmp3; } public void setBrEmp3(String brEmp3) { BrEmp3 = brEmp3; } } public class Definition { private String pos; private String def; public String getPos() { return pos; } public void setPos(String pos) { this.pos = pos; } public String getDef() { return def; } public void setDef(String def) { this.def = def; } } public class Sample { private String eng; private String chn; private String mp3Url; private String mp4Url; public String getEng() { return eng; } public void setEng(String eng) { this.eng = eng; } public String getChn() { return chn; } public void setChn(String chn) { this.chn = chn; } public String getMp3Url() { return mp3Url; } public void setMp3Url(String mp3Url) { this.mp3Url = mp3Url; } public String getMp4Url() { return mp4Url; } public void setMp4Url(String mp4Url) { this.mp4Url = mp4Url; } } }
false
1,122
22
1,291
28
1,316
22
1,291
28
1,467
37
false
false
false
false
false
true
11911_1
package com.mark.concurrent12; import java.util.concurrent.TimeUnit; /** * volatile关键字, 是一个变量在多线程间可见 * A, B线程都用到一个变量, Java默认是A线程中保留一份copy, 这样如果B线程修改了该变量, 则线程A未必知道。 * 使用volatile关键字可以使所有线程都会读到变量的修改值 * * 在下面的代码中, running时存在于对内存的t对象中 * 当线程t1开通的时候, 会把running值从内存中读到t1线程的工作区,在运行中直接使用这个copy,并不会每次都去 * 读取内存,这样, 当主线程修改running的值后,t1线程感知不到, 所以不会停止运行。 * * 使用volatile, 将会强制所有线程都去对内存中读取running的值, 缓存过期通知 * * 深入理解请阅读:http://www.cnblogs.com/nexiyi/p/java_memory_model_and_thread.html * * volatile并不能保证多个线程共同修改running变量时所带来的不一致问题, 也就是说volatile不能代替synchronized * * Java线程处理的内存模型, 深入了解《深入Java虚拟机》 JMM * JDK 并发容器, 能用volatile的地方,就不要用锁 * @author MarkShen * */ public class T { /** * https://www.cnblogs.com/Mushrooms/p/5151593.html * * 补充内容:分享点儿知识,内容就是CPU内部的寄存器。就这个程序来说,有两个线程。一个是主线程, * 一个是自己启动的线程。当自己启动的线程运行时,running这个变量的值会被CPU把值从内存中读到 * CPU中的寄存器(即CPU中的cache)中。为什么这么做呢?因为CPU的速度要比内存的速度快,内存的速 * 度比硬盘快。所以要把running中的数据copy一份到内存中处理。但是,没有加volatile关键字的变 * 量running,当主线程已经把running改为false,自己启动的线程依然不能停下来。因为它读的是CPU * 中running。主线程改的内存中的running。两个线程读写的变量的存储位置不同。 * * 而volatile关键字就是为了解决这个问题而出现的。其作用是,当主线程对内存中的变量running修改 * 后,就会通知CPU中的变量running,你那个值已经不是最新的了。这时候,自己启动的线程会重新读一 * 遍内存中的running变量。 */ // volatile 解决了线程间的可见性(观察者模式) volatile boolean running = true; // 对比一下有无volatile情况下, 整个程序运行的结果 void m() { System.out.println("m start"); while(running) { // try { // TimeUnit.SECONDS.sleep(1); // } catch (InterruptedException e) { // e.printStackTrace(); // } } System.out.println("m end"); } public static void main(String[] args) { T t = new T(); new Thread(t::m, "t1").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } t.running = false; } }
MarkShen1992/Mashibing_High_Concurrency
src/main/java/com/mark/concurrent12/T.java
840
/** * https://www.cnblogs.com/Mushrooms/p/5151593.html * * 补充内容:分享点儿知识,内容就是CPU内部的寄存器。就这个程序来说,有两个线程。一个是主线程, * 一个是自己启动的线程。当自己启动的线程运行时,running这个变量的值会被CPU把值从内存中读到 * CPU中的寄存器(即CPU中的cache)中。为什么这么做呢?因为CPU的速度要比内存的速度快,内存的速 * 度比硬盘快。所以要把running中的数据copy一份到内存中处理。但是,没有加volatile关键字的变 * 量running,当主线程已经把running改为false,自己启动的线程依然不能停下来。因为它读的是CPU * 中running。主线程改的内存中的running。两个线程读写的变量的存储位置不同。 * * 而volatile关键字就是为了解决这个问题而出现的。其作用是,当主线程对内存中的变量running修改 * 后,就会通知CPU中的变量running,你那个值已经不是最新的了。这时候,自己启动的线程会重新读一 * 遍内存中的running变量。 */
block_comment
zh-cn
package com.mark.concurrent12; import java.util.concurrent.TimeUnit; /** * volatile关键字, 是一个变量在多线程间可见 * A, B线程都用到一个变量, Java默认是A线程中保留一份copy, 这样如果B线程修改了该变量, 则线程A未必知道。 * 使用volatile关键字可以使所有线程都会读到变量的修改值 * * 在下面的代码中, running时存在于对内存的t对象中 * 当线程t1开通的时候, 会把running值从内存中读到t1线程的工作区,在运行中直接使用这个copy,并不会每次都去 * 读取内存,这样, 当主线程修改running的值后,t1线程感知不到, 所以不会停止运行。 * * 使用volatile, 将会强制所有线程都去对内存中读取running的值, 缓存过期通知 * * 深入理解请阅读:http://www.cnblogs.com/nexiyi/p/java_memory_model_and_thread.html * * volatile并不能保证多个线程共同修改running变量时所带来的不一致问题, 也就是说volatile不能代替synchronized * * Java线程处理的内存模型, 深入了解《深入Java虚拟机》 JMM * JDK 并发容器, 能用volatile的地方,就不要用锁 * @author MarkShen * */ public class T { /** * htt <SUF>*/ // volatile 解决了线程间的可见性(观察者模式) volatile boolean running = true; // 对比一下有无volatile情况下, 整个程序运行的结果 void m() { System.out.println("m start"); while(running) { // try { // TimeUnit.SECONDS.sleep(1); // } catch (InterruptedException e) { // e.printStackTrace(); // } } System.out.println("m end"); } public static void main(String[] args) { T t = new T(); new Thread(t::m, "t1").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } t.running = false; } }
false
768
281
840
295
801
279
840
295
1,245
483
true
true
true
true
true
false
38641_8
package com.example.entity; import com.baomidou.mybatisplus.annotation.TableName; import com.example.entity.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * <p> * * </p> * * @author 公众号:java思维导图 * @since 2019-11-17 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @TableName("m_post") public class Post extends BaseEntity { private static final long serialVersionUID = 1L; /** * 标题 */ @NotBlank(message = "标题不能为空") private String title; /** * 内容 */ @NotBlank(message = "内容不能为空") private String content; /** * 编辑模式:html可视化,markdown .. */ private String editMode; @NotNull(message = "分类不能为空") private Long categoryId; /** * 用户ID */ private Long userId; /** * 支持人数 */ private Integer voteUp; /** * 反对人数 */ private Integer voteDown; /** * 访问量 */ private Integer viewCount; /** * 评论数量 */ private Integer commentCount; /** * 是否为精华 */ private Boolean recommend; /** * 置顶等级 */ private Integer level; }
MarkerHub/eblog
src/main/java/com/example/entity/Post.java
366
/** * 评论数量 */
block_comment
zh-cn
package com.example.entity; import com.baomidou.mybatisplus.annotation.TableName; import com.example.entity.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; /** * <p> * * </p> * * @author 公众号:java思维导图 * @since 2019-11-17 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @TableName("m_post") public class Post extends BaseEntity { private static final long serialVersionUID = 1L; /** * 标题 */ @NotBlank(message = "标题不能为空") private String title; /** * 内容 */ @NotBlank(message = "内容不能为空") private String content; /** * 编辑模式:html可视化,markdown .. */ private String editMode; @NotNull(message = "分类不能为空") private Long categoryId; /** * 用户ID */ private Long userId; /** * 支持人数 */ private Integer voteUp; /** * 反对人数 */ private Integer voteDown; /** * 访问量 */ private Integer viewCount; /** * 评论数 <SUF>*/ private Integer commentCount; /** * 是否为精华 */ private Boolean recommend; /** * 置顶等级 */ private Integer level; }
false
326
9
366
8
393
10
366
8
501
16
false
false
false
false
false
true
40436_3
package com.hugnew.sps.services.pay.strategy; import com.csii.payment.client.core.CebMerchantSignVerify; import com.hugnew.core.util.PropertiesUtil; import com.hugnew.sps.enums.PayType; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 光大网页wap支付 * Created by Martin on 2016/7/01. */ public class CEBWapStragegy implements PayStrategy { private static Logger logger = LoggerFactory.getLogger(CEBWapStragegy.class); @Override public String generatePayParams(PayType payType, Map<String, Object> params) { DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String retUrl = null; if (params.size() > 0 && null != params.get("retUrl")) { retUrl = (String) params.get("retUrl"); } Map<String, String> plainMap = new HashMap<>(); plainMap.put("MerchantId", PropertiesUtil.getValue("pay.request.ceb.merchantId")); plainMap.put("IdentityType", PropertiesUtil.getValue("pay.request.ceb.identityType")); plainMap.put("MerCifId", PropertiesUtil.getValue("pay.request.ceb.merCifId")); plainMap.put("PayType", PropertiesUtil.getValue("pay.request.ceb.payType")); plainMap.put("MerchantSeqNo", (String) params.get("payCode")); plainMap.put("MerchantDateTime", format.format(new Date())); plainMap.put("TransAmount", String.valueOf(((BigDecimal) params.get("toPay")).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())); plainMap.put("TerminalType", PropertiesUtil.getValue("pay.request.ceb.terminalType")); plainMap.put("TerminalId", PropertiesUtil.getValue("pay.request.ceb.terminalId")); plainMap.put("MerSecName", PropertiesUtil.getValue("pay.request.ceb.merSecName")); plainMap.put("ProductCataLog", PropertiesUtil.getValue("pay.request.ceb.productCataLog"));//57:综合服务(固定值) plainMap.put("MerProduct", PropertiesUtil.getValue("pay.request.ceb.merProduct"));//商品名称 ,竟然是必填 ? plainMap.put("MerchantUrl", PropertiesUtil.getValue("pay.notify.ceb.url")); plainMap.put("MerchantUrl1", StringUtils.isNotBlank(retUrl) ? retUrl : PropertiesUtil.getValue("pay.request.retUrl")); plainMap.put("UserIp", "");//客户在商户网站上生成订单时的客户IP 我感觉没必要传 plainMap.put("msgExt", PropertiesUtil.getValue("pay.request.ceb.msgExt"));//附加信息 String plain = concatMap(plainMap); String sign = CebMerchantSignVerify.merchantSignData_ABA(plain); Map<String, String> toRet = new HashMap<>(); toRet.put("transName", PropertiesUtil.getValue("pay.request.ceb.wap.transName")); toRet.put("Plain", plain); toRet.put("Signature", sign); if(logger.isDebugEnabled()){ logger.debug("ceb参数信息:{}", toRet.toString()); } return buildRequestParams(toRet); } private String concatMap(Map<String, String> plainMap) { StringBuffer toRetBuff = new StringBuffer(); for (Map.Entry<String, String> entry : plainMap.entrySet()) { toRetBuff.append(entry.getKey()).append("=").append(entry.getValue()).append("~|~"); } return toRetBuff.substring(0, toRetBuff.length() - 3); } private String buildRequestParams(Map<String, String> sParaTemp) { StringBuffer toRet = new StringBuffer(); for (Map.Entry<String, String> entry : sParaTemp.entrySet()) { toRet.append(entry.getKey()).append("=").append("\"").append(entry.getValue()).append("\"").append("&"); } return toRet.substring(0, toRet.length() - 1); } }
Martin404/PayMap
src/main/java/com/hugnew/sps/services/pay/strategy/CEBWapStragegy.java
1,054
//客户在商户网站上生成订单时的客户IP 我感觉没必要传
line_comment
zh-cn
package com.hugnew.sps.services.pay.strategy; import com.csii.payment.client.core.CebMerchantSignVerify; import com.hugnew.core.util.PropertiesUtil; import com.hugnew.sps.enums.PayType; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * 光大网页wap支付 * Created by Martin on 2016/7/01. */ public class CEBWapStragegy implements PayStrategy { private static Logger logger = LoggerFactory.getLogger(CEBWapStragegy.class); @Override public String generatePayParams(PayType payType, Map<String, Object> params) { DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); String retUrl = null; if (params.size() > 0 && null != params.get("retUrl")) { retUrl = (String) params.get("retUrl"); } Map<String, String> plainMap = new HashMap<>(); plainMap.put("MerchantId", PropertiesUtil.getValue("pay.request.ceb.merchantId")); plainMap.put("IdentityType", PropertiesUtil.getValue("pay.request.ceb.identityType")); plainMap.put("MerCifId", PropertiesUtil.getValue("pay.request.ceb.merCifId")); plainMap.put("PayType", PropertiesUtil.getValue("pay.request.ceb.payType")); plainMap.put("MerchantSeqNo", (String) params.get("payCode")); plainMap.put("MerchantDateTime", format.format(new Date())); plainMap.put("TransAmount", String.valueOf(((BigDecimal) params.get("toPay")).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue())); plainMap.put("TerminalType", PropertiesUtil.getValue("pay.request.ceb.terminalType")); plainMap.put("TerminalId", PropertiesUtil.getValue("pay.request.ceb.terminalId")); plainMap.put("MerSecName", PropertiesUtil.getValue("pay.request.ceb.merSecName")); plainMap.put("ProductCataLog", PropertiesUtil.getValue("pay.request.ceb.productCataLog"));//57:综合服务(固定值) plainMap.put("MerProduct", PropertiesUtil.getValue("pay.request.ceb.merProduct"));//商品名称 ,竟然是必填 ? plainMap.put("MerchantUrl", PropertiesUtil.getValue("pay.notify.ceb.url")); plainMap.put("MerchantUrl1", StringUtils.isNotBlank(retUrl) ? retUrl : PropertiesUtil.getValue("pay.request.retUrl")); plainMap.put("UserIp", "");//客户 <SUF> plainMap.put("msgExt", PropertiesUtil.getValue("pay.request.ceb.msgExt"));//附加信息 String plain = concatMap(plainMap); String sign = CebMerchantSignVerify.merchantSignData_ABA(plain); Map<String, String> toRet = new HashMap<>(); toRet.put("transName", PropertiesUtil.getValue("pay.request.ceb.wap.transName")); toRet.put("Plain", plain); toRet.put("Signature", sign); if(logger.isDebugEnabled()){ logger.debug("ceb参数信息:{}", toRet.toString()); } return buildRequestParams(toRet); } private String concatMap(Map<String, String> plainMap) { StringBuffer toRetBuff = new StringBuffer(); for (Map.Entry<String, String> entry : plainMap.entrySet()) { toRetBuff.append(entry.getKey()).append("=").append(entry.getValue()).append("~|~"); } return toRetBuff.substring(0, toRetBuff.length() - 3); } private String buildRequestParams(Map<String, String> sParaTemp) { StringBuffer toRet = new StringBuffer(); for (Map.Entry<String, String> entry : sParaTemp.entrySet()) { toRet.append(entry.getKey()).append("=").append("\"").append(entry.getValue()).append("\"").append("&"); } return toRet.substring(0, toRet.length() - 1); } }
false
882
18
1,054
20
1,073
17
1,054
20
1,219
32
false
false
false
false
false
true
60453_7
package com.martin.postermaster; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.widget.ImageView; /** * 我收集的颜色滤镜 * Created by Martin on 2016/8/1 0001. */ public class ColorFilter { /** * 为imageView设置颜色滤镜 * * @param imageView * @param colormatrix */ public static void imageViewColorFilter(ImageView imageView, float[] colormatrix) { setColorMatrixColorFilter(imageView, new ColorMatrixColorFilter(new ColorMatrix(colormatrix))); } /** * 为imageView设置颜色偏向滤镜 * * @param imageView * @param color */ public static void imageViewColorFilter(ImageView imageView, int color) { ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.setScale(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color)); setColorMatrixColorFilter(imageView, new ColorMatrixColorFilter(colorMatrix)); } /** * 生成对应颜色偏向滤镜的图片,并回收原图 * * @param bitmap * @param color * @return */ public static Bitmap bitmapColorFilter(Bitmap bitmap, int color) { ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.setScale(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color)); return setColorMatrixColorFilter(bitmap, new ColorMatrixColorFilter(colorMatrix), true); } /** * 生成对应颜色滤镜的图片,并回收原图 * * @param bitmap * @param colormatrix * @return */ public static Bitmap bitmapColorFilter(Bitmap bitmap, float[] colormatrix) { return setColorMatrix(bitmap, colormatrix, true); } /** * 生成对应颜色滤镜的图片 * * @param bitmap * @param colormatrix * @param isRecycle * @return */ public static Bitmap setColorMatrix(Bitmap bitmap, float[] colormatrix, boolean isRecycle) { return setColorMatrixColorFilter(bitmap, new ColorMatrixColorFilter(new ColorMatrix(colormatrix)), isRecycle); } public static void setColorMatrixColorFilter(ImageView imageView, ColorMatrixColorFilter matrixColorFilter) { imageView.setColorFilter(matrixColorFilter); } public static Bitmap setColorMatrixColorFilter(Bitmap bitmap, ColorMatrixColorFilter matrixColorFilter, boolean isRecycle) { Bitmap resource = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColorFilter(matrixColorFilter); Canvas canvas = new Canvas(resource); canvas.drawBitmap(bitmap, 0, 0, paint); if (isRecycle) BitmapUtils.destroyBitmap(bitmap); return resource; } // 黑白 public static final float colormatrix_heibai[] = {0.8f, 1.6f, 0.2f, 0, -163.9f, 0.8f, 1.6f, 0.2f, 0, -163.9f, 0.8f, 1.6f, 0.2f, 0, -163.9f, 0, 0, 0, 1.0f, 0}; // 怀旧 public static final float colormatrix_huajiu[] = {0.2f, 0.5f, 0.1f, 0, 40.8f, 0.2f, 0.5f, 0.1f, 0, 40.8f, 0.2f, 0.5f, 0.1f, 0, 40.8f, 0, 0, 0, 1, 0}; // 哥特 public static final float colormatrix_gete[] = {1.9f, -0.3f, -0.2f, 0, -87.0f, -0.2f, 1.7f, -0.1f, 0, -87.0f, -0.1f, -0.6f, 2.0f, 0, -87.0f, 0, 0, 0, 1.0f, 0}; // 淡雅 public static final float colormatrix_danya[] = {0.6f, 0.3f, 0.1f, 0, 73.3f, 0.2f, 0.7f, 0.1f, 0, 73.3f, 0.2f, 0.3f, 0.4f, 0, 73.3f, 0, 0, 0, 1.0f, 0}; // 蓝调 public static final float colormatrix_landiao[] = {2.1f, -1.4f, 0.6f, 0.0f, -71.0f, -0.3f, 2.0f, -0.3f, 0.0f, -71.0f, -1.1f, -0.2f, 2.6f, 0.0f, -71.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 光晕 public static final float colormatrix_guangyun[] = {0.9f, 0, 0, 0, 64.9f, 0, 0.9f, 0, 0, 64.9f, 0, 0, 0.9f, 0, 64.9f, 0, 0, 0, 1.0f, 0}; // 梦幻 public static final float colormatrix_menghuan[] = {0.8f, 0.3f, 0.1f, 0.0f, 46.5f, 0.1f, 0.9f, 0.0f, 0.0f, 46.5f, 0.1f, 0.3f, 0.7f, 0.0f, 46.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 酒红 public static final float colormatrix_jiuhong[] = {1.2f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 胶片 public static final float colormatrix_fanse[] = {-1.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, -1.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, -1.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 湖光掠影 public static final float colormatrix_huguang[] = {0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 褐片 public static final float colormatrix_hepian[] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 复古 public static final float colormatrix_fugu[] = {0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 泛黄 public static final float colormatrix_huan_huang[] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 传统 public static final float colormatrix_chuan_tong[] = {1.0f, 0.0f, 0.0f, 0, -10f, 0.0f, 1.0f, 0.0f, 0, -10f, 0.0f, 0.0f, 1.0f, 0, -10f, 0, 0, 0, 1, 0}; // 胶片2 public static final float colormatrix_jiao_pian[] = {0.71f, 0.2f, 0.0f, 0.0f, 60.0f, 0.0f, 0.94f, 0.0f, 0.0f, 60.0f, 0.0f, 0.0f, 0.62f, 0.0f, 60.0f, 0, 0, 0, 1.0f, 0}; // 锐色 public static final float colormatrix_ruise[] = {4.8f, -1.0f, -0.1f, 0, -388.4f, -0.5f, 4.4f, -0.1f, 0, -388.4f, -0.5f, -1.0f, 5.2f, 0, -388.4f, 0, 0, 0, 1.0f, 0}; // 清宁 public static final float colormatrix_qingning[] = {0.9f, 0, 0, 0, 0, 0, 1.1f, 0, 0, 0, 0, 0, 0.9f, 0, 0, 0, 0, 0, 1.0f, 0}; // 浪漫 public static final float colormatrix_langman[] = {0.9f, 0, 0, 0, 63.0f, 0, 0.9f, 0, 0, 63.0f, 0, 0, 0.9f, 0, 63.0f, 0, 0, 0, 1.0f, 0}; // 夜色 public static final float colormatrix_yese[] = {1.0f, 0.0f, 0.0f, 0.0f, -66.6f, 0.0f, 1.1f, 0.0f, 0.0f, -66.6f, 0.0f, 0.0f, 1.0f, 0.0f, -66.6f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; }
MartinHY/PosterMaster
app/src/main/java/com/martin/postermaster/ColorFilter.java
3,136
// 胶片2
line_comment
zh-cn
package com.martin.postermaster; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.widget.ImageView; /** * 我收集的颜色滤镜 * Created by Martin on 2016/8/1 0001. */ public class ColorFilter { /** * 为imageView设置颜色滤镜 * * @param imageView * @param colormatrix */ public static void imageViewColorFilter(ImageView imageView, float[] colormatrix) { setColorMatrixColorFilter(imageView, new ColorMatrixColorFilter(new ColorMatrix(colormatrix))); } /** * 为imageView设置颜色偏向滤镜 * * @param imageView * @param color */ public static void imageViewColorFilter(ImageView imageView, int color) { ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.setScale(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color)); setColorMatrixColorFilter(imageView, new ColorMatrixColorFilter(colorMatrix)); } /** * 生成对应颜色偏向滤镜的图片,并回收原图 * * @param bitmap * @param color * @return */ public static Bitmap bitmapColorFilter(Bitmap bitmap, int color) { ColorMatrix colorMatrix = new ColorMatrix(); colorMatrix.setScale(Color.alpha(color), Color.red(color), Color.green(color), Color.blue(color)); return setColorMatrixColorFilter(bitmap, new ColorMatrixColorFilter(colorMatrix), true); } /** * 生成对应颜色滤镜的图片,并回收原图 * * @param bitmap * @param colormatrix * @return */ public static Bitmap bitmapColorFilter(Bitmap bitmap, float[] colormatrix) { return setColorMatrix(bitmap, colormatrix, true); } /** * 生成对应颜色滤镜的图片 * * @param bitmap * @param colormatrix * @param isRecycle * @return */ public static Bitmap setColorMatrix(Bitmap bitmap, float[] colormatrix, boolean isRecycle) { return setColorMatrixColorFilter(bitmap, new ColorMatrixColorFilter(new ColorMatrix(colormatrix)), isRecycle); } public static void setColorMatrixColorFilter(ImageView imageView, ColorMatrixColorFilter matrixColorFilter) { imageView.setColorFilter(matrixColorFilter); } public static Bitmap setColorMatrixColorFilter(Bitmap bitmap, ColorMatrixColorFilter matrixColorFilter, boolean isRecycle) { Bitmap resource = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Paint paint = new Paint(); paint.setAntiAlias(true); paint.setColorFilter(matrixColorFilter); Canvas canvas = new Canvas(resource); canvas.drawBitmap(bitmap, 0, 0, paint); if (isRecycle) BitmapUtils.destroyBitmap(bitmap); return resource; } // 黑白 public static final float colormatrix_heibai[] = {0.8f, 1.6f, 0.2f, 0, -163.9f, 0.8f, 1.6f, 0.2f, 0, -163.9f, 0.8f, 1.6f, 0.2f, 0, -163.9f, 0, 0, 0, 1.0f, 0}; // 怀旧 public static final float colormatrix_huajiu[] = {0.2f, 0.5f, 0.1f, 0, 40.8f, 0.2f, 0.5f, 0.1f, 0, 40.8f, 0.2f, 0.5f, 0.1f, 0, 40.8f, 0, 0, 0, 1, 0}; // 哥特 public static final float colormatrix_gete[] = {1.9f, -0.3f, -0.2f, 0, -87.0f, -0.2f, 1.7f, -0.1f, 0, -87.0f, -0.1f, -0.6f, 2.0f, 0, -87.0f, 0, 0, 0, 1.0f, 0}; // 淡雅 public static final float colormatrix_danya[] = {0.6f, 0.3f, 0.1f, 0, 73.3f, 0.2f, 0.7f, 0.1f, 0, 73.3f, 0.2f, 0.3f, 0.4f, 0, 73.3f, 0, 0, 0, 1.0f, 0}; // 蓝调 public static final float colormatrix_landiao[] = {2.1f, -1.4f, 0.6f, 0.0f, -71.0f, -0.3f, 2.0f, -0.3f, 0.0f, -71.0f, -1.1f, -0.2f, 2.6f, 0.0f, -71.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 光晕 public static final float colormatrix_guangyun[] = {0.9f, 0, 0, 0, 64.9f, 0, 0.9f, 0, 0, 64.9f, 0, 0, 0.9f, 0, 64.9f, 0, 0, 0, 1.0f, 0}; // 梦幻 public static final float colormatrix_menghuan[] = {0.8f, 0.3f, 0.1f, 0.0f, 46.5f, 0.1f, 0.9f, 0.0f, 0.0f, 46.5f, 0.1f, 0.3f, 0.7f, 0.0f, 46.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 酒红 public static final float colormatrix_jiuhong[] = {1.2f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 胶片 public static final float colormatrix_fanse[] = {-1.0f, 0.0f, 0.0f, 0.0f, 255.0f, 0.0f, -1.0f, 0.0f, 0.0f, 255.0f, 0.0f, 0.0f, -1.0f, 0.0f, 255.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; // 湖光掠影 public static final float colormatrix_huguang[] = {0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.9f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 褐片 public static final float colormatrix_hepian[] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 复古 public static final float colormatrix_fugu[] = {0.9f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 泛黄 public static final float colormatrix_huan_huang[] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0, 0, 0, 1.0f, 0}; // 传统 public static final float colormatrix_chuan_tong[] = {1.0f, 0.0f, 0.0f, 0, -10f, 0.0f, 1.0f, 0.0f, 0, -10f, 0.0f, 0.0f, 1.0f, 0, -10f, 0, 0, 0, 1, 0}; // 胶片 <SUF> public static final float colormatrix_jiao_pian[] = {0.71f, 0.2f, 0.0f, 0.0f, 60.0f, 0.0f, 0.94f, 0.0f, 0.0f, 60.0f, 0.0f, 0.0f, 0.62f, 0.0f, 60.0f, 0, 0, 0, 1.0f, 0}; // 锐色 public static final float colormatrix_ruise[] = {4.8f, -1.0f, -0.1f, 0, -388.4f, -0.5f, 4.4f, -0.1f, 0, -388.4f, -0.5f, -1.0f, 5.2f, 0, -388.4f, 0, 0, 0, 1.0f, 0}; // 清宁 public static final float colormatrix_qingning[] = {0.9f, 0, 0, 0, 0, 0, 1.1f, 0, 0, 0, 0, 0, 0.9f, 0, 0, 0, 0, 0, 1.0f, 0}; // 浪漫 public static final float colormatrix_langman[] = {0.9f, 0, 0, 0, 63.0f, 0, 0.9f, 0, 0, 63.0f, 0, 0, 0.9f, 0, 63.0f, 0, 0, 0, 1.0f, 0}; // 夜色 public static final float colormatrix_yese[] = {1.0f, 0.0f, 0.0f, 0.0f, -66.6f, 0.0f, 1.1f, 0.0f, 0.0f, -66.6f, 0.0f, 0.0f, 1.0f, 0.0f, -66.6f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f}; }
false
3,053
6
3,136
6
3,153
4
3,136
6
3,410
7
false
false
false
false
false
true
42570_1
package com.richardtang.androidkiller4j.ui.border; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.*; /** * 组件边框的显示效果 */ public class MLineBorder extends LineBorder { // 想起项目UI风格中边框的默认颜色 public static Color defaultBorderColor = UIManager.getColor("Component.borderColor"); private boolean left = true, right = true, top = true, bottom = true; /** * 返回默认颜色的边框 */ public MLineBorder() { super(defaultBorderColor); } /** * 配置边框颜色 * * @param color 颜色 */ public MLineBorder(Color color) { super(color); } /** * 配置边框颜色、厚度。 * * @param color 颜色 * @param thickness 厚度 */ public MLineBorder(Color color, int thickness) { super(color, thickness); } /** * 配置边框四条边、颜色、厚度。 * * @param color 边框颜色 * @param thickness 厚度 * @param left 左边线 * @param right 右边线 * @param top 上边线 * @param bottom 下边线 */ public MLineBorder(Color color, int thickness, boolean left, boolean right, boolean top, boolean bottom) { super(color, thickness); this.left = left; this.right = right; this.bottom = bottom; this.top = top; } /** * 配置边框四条边、厚度,使用项目默认颜色作为边框颜色。 * * @param thickness 厚度 * @param left 左边线 * @param right 右边线 * @param top 上边线 * @param bottom 下边线 */ public MLineBorder(int thickness, boolean left, boolean right, boolean top, boolean bottom) { super(defaultBorderColor, thickness); this.left = left; this.right = right; this.bottom = bottom; this.top = top; } public void setInsets(boolean left, boolean right, boolean top, boolean bottom) { this.left = left; this.right = right; this.bottom = bottom; this.top = top; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if ((this.thickness > 0) && (g instanceof Graphics2D)) { Graphics2D g2d = (Graphics2D) g; Color oldColor = g2d.getColor(); g2d.setColor(this.lineColor); if (left) { g2d.drawLine(x, y, x, y + height); } if (top) { g2d.drawLine(x, y, x + width, y); } if (right) { g2d.drawLine(x + width, y, x + width, y + height); } if (bottom) { g2d.drawLine(x, y + height, x + width, y + height); } g2d.setColor(oldColor); } } }
MaskCyberSecurityTeam/AndroidKiller4J
src/main/java/com/richardtang/androidkiller4j/ui/border/MLineBorder.java
774
// 想起项目UI风格中边框的默认颜色
line_comment
zh-cn
package com.richardtang.androidkiller4j.ui.border; import javax.swing.*; import javax.swing.border.LineBorder; import java.awt.*; /** * 组件边框的显示效果 */ public class MLineBorder extends LineBorder { // 想起 <SUF> public static Color defaultBorderColor = UIManager.getColor("Component.borderColor"); private boolean left = true, right = true, top = true, bottom = true; /** * 返回默认颜色的边框 */ public MLineBorder() { super(defaultBorderColor); } /** * 配置边框颜色 * * @param color 颜色 */ public MLineBorder(Color color) { super(color); } /** * 配置边框颜色、厚度。 * * @param color 颜色 * @param thickness 厚度 */ public MLineBorder(Color color, int thickness) { super(color, thickness); } /** * 配置边框四条边、颜色、厚度。 * * @param color 边框颜色 * @param thickness 厚度 * @param left 左边线 * @param right 右边线 * @param top 上边线 * @param bottom 下边线 */ public MLineBorder(Color color, int thickness, boolean left, boolean right, boolean top, boolean bottom) { super(color, thickness); this.left = left; this.right = right; this.bottom = bottom; this.top = top; } /** * 配置边框四条边、厚度,使用项目默认颜色作为边框颜色。 * * @param thickness 厚度 * @param left 左边线 * @param right 右边线 * @param top 上边线 * @param bottom 下边线 */ public MLineBorder(int thickness, boolean left, boolean right, boolean top, boolean bottom) { super(defaultBorderColor, thickness); this.left = left; this.right = right; this.bottom = bottom; this.top = top; } public void setInsets(boolean left, boolean right, boolean top, boolean bottom) { this.left = left; this.right = right; this.bottom = bottom; this.top = top; } @Override public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) { if ((this.thickness > 0) && (g instanceof Graphics2D)) { Graphics2D g2d = (Graphics2D) g; Color oldColor = g2d.getColor(); g2d.setColor(this.lineColor); if (left) { g2d.drawLine(x, y, x, y + height); } if (top) { g2d.drawLine(x, y, x + width, y); } if (right) { g2d.drawLine(x + width, y, x + width, y + height); } if (bottom) { g2d.drawLine(x, y + height, x + width, y + height); } g2d.setColor(oldColor); } } }
false
734
14
774
15
826
12
774
15
957
23
false
false
false
false
false
true
62234_1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.framework.starter.common.toolkit; import com.github.dozermapper.core.DozerBeanMapperBuilder; import com.github.dozermapper.core.Mapper; import com.github.dozermapper.core.loader.api.BeanMappingBuilder; import lombok.NoArgsConstructor; import java.lang.reflect.Array; import java.util.*; import static com.github.dozermapper.core.loader.api.TypeMappingOptions.mapEmptyString; import static com.github.dozermapper.core.loader.api.TypeMappingOptions.mapNull; /** * 对象属性复制工具类 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */ @NoArgsConstructor(access = lombok.AccessLevel.PRIVATE) public class BeanUtil { protected static Mapper BEAN_MAPPER_BUILDER; static { BEAN_MAPPER_BUILDER = DozerBeanMapperBuilder.buildDefault(); } /** * 属性复制 * * @param source 数据对象 * @param target 目标对象 * @param <T> * @param <S> * @return 转换后对象 */ public static <T, S> T convert(S source, T target) { Optional.ofNullable(source) .ifPresent(each -> BEAN_MAPPER_BUILDER.map(each, target)); return target; } /** * 复制单个对象 * * @param source 数据对象 * @param clazz 复制目标类型 * @param <T> * @param <S> * @return 转换后对象 */ public static <T, S> T convert(S source, Class<T> clazz) { return Optional.ofNullable(source) .map(each -> BEAN_MAPPER_BUILDER.map(each, clazz)) .orElse(null); } /** * 复制多个对象 * * @param sources 数据对象 * @param clazz 复制目标类型 * @param <T> * @param <S> * @return 转换后对象集合 */ public static <T, S> List<T> convert(List<S> sources, Class<T> clazz) { return Optional.ofNullable(sources) .map(each -> { List<T> targetList = new ArrayList<T>(each.size()); each.stream() .forEach(item -> targetList.add(BEAN_MAPPER_BUILDER.map(item, clazz))); return targetList; }) .orElse(null); } /** * 复制多个对象 * * @param sources 数据对象 * @param clazz 复制目标类型 * @param <T> * @param <S> * @return 转换后对象集合 */ public static <T, S> Set<T> convert(Set<S> sources, Class<T> clazz) { return Optional.ofNullable(sources) .map(each -> { Set<T> targetSize = new HashSet<T>(each.size()); each.stream() .forEach(item -> targetSize.add(BEAN_MAPPER_BUILDER.map(item, clazz))); return targetSize; }) .orElse(null); } /** * 复制多个对象 * * @param sources 数据对象 * @param clazz 复制目标类型 * @param <T> * @param <S> * @return 转换后对象集合 */ public static <T, S> T[] convert(S[] sources, Class<T> clazz) { return Optional.ofNullable(sources) .map(each -> { @SuppressWarnings("unchecked") T[] targetArray = (T[]) Array.newInstance(clazz, sources.length); for (int i = 0; i < targetArray.length; i++) { targetArray[i] = BEAN_MAPPER_BUILDER.map(sources[i], clazz); } return targetArray; }) .orElse(null); } /** * 拷贝非空且非空串属性 * * @param source 数据源 * @param target 指向源 */ public static void convertIgnoreNullAndBlank(Object source, Object target) { DozerBeanMapperBuilder dozerBeanMapperBuilder = DozerBeanMapperBuilder.create(); Mapper mapper = dozerBeanMapperBuilder.withMappingBuilders(new BeanMappingBuilder() { @Override protected void configure() { mapping(source.getClass(), target.getClass(), mapNull(false), mapEmptyString(false)); } }).build(); mapper.map(source, target); } /** * 拷贝非空属性 * * @param source 数据源 * @param target 指向源 */ public static void convertIgnoreNull(Object source, Object target) { DozerBeanMapperBuilder dozerBeanMapperBuilder = DozerBeanMapperBuilder.create(); Mapper mapper = dozerBeanMapperBuilder.withMappingBuilders(new BeanMappingBuilder() { @Override protected void configure() { mapping(source.getClass(), target.getClass(), mapNull(false)); } }).build(); mapper.map(source, target); } }
Master-sudo-doct/my12306
frameworks/common/src/main/java/org/opengoofy/index12306/framework/starter/common/toolkit/BeanUtil.java
1,398
/** * 对象属性复制工具类 * * @公众号:马丁玩编程,回复:加群,添加马哥微信(备注:12306)获取项目资料 */
block_comment
zh-cn
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opengoofy.index12306.framework.starter.common.toolkit; import com.github.dozermapper.core.DozerBeanMapperBuilder; import com.github.dozermapper.core.Mapper; import com.github.dozermapper.core.loader.api.BeanMappingBuilder; import lombok.NoArgsConstructor; import java.lang.reflect.Array; import java.util.*; import static com.github.dozermapper.core.loader.api.TypeMappingOptions.mapEmptyString; import static com.github.dozermapper.core.loader.api.TypeMappingOptions.mapNull; /** * 对象属 <SUF>*/ @NoArgsConstructor(access = lombok.AccessLevel.PRIVATE) public class BeanUtil { protected static Mapper BEAN_MAPPER_BUILDER; static { BEAN_MAPPER_BUILDER = DozerBeanMapperBuilder.buildDefault(); } /** * 属性复制 * * @param source 数据对象 * @param target 目标对象 * @param <T> * @param <S> * @return 转换后对象 */ public static <T, S> T convert(S source, T target) { Optional.ofNullable(source) .ifPresent(each -> BEAN_MAPPER_BUILDER.map(each, target)); return target; } /** * 复制单个对象 * * @param source 数据对象 * @param clazz 复制目标类型 * @param <T> * @param <S> * @return 转换后对象 */ public static <T, S> T convert(S source, Class<T> clazz) { return Optional.ofNullable(source) .map(each -> BEAN_MAPPER_BUILDER.map(each, clazz)) .orElse(null); } /** * 复制多个对象 * * @param sources 数据对象 * @param clazz 复制目标类型 * @param <T> * @param <S> * @return 转换后对象集合 */ public static <T, S> List<T> convert(List<S> sources, Class<T> clazz) { return Optional.ofNullable(sources) .map(each -> { List<T> targetList = new ArrayList<T>(each.size()); each.stream() .forEach(item -> targetList.add(BEAN_MAPPER_BUILDER.map(item, clazz))); return targetList; }) .orElse(null); } /** * 复制多个对象 * * @param sources 数据对象 * @param clazz 复制目标类型 * @param <T> * @param <S> * @return 转换后对象集合 */ public static <T, S> Set<T> convert(Set<S> sources, Class<T> clazz) { return Optional.ofNullable(sources) .map(each -> { Set<T> targetSize = new HashSet<T>(each.size()); each.stream() .forEach(item -> targetSize.add(BEAN_MAPPER_BUILDER.map(item, clazz))); return targetSize; }) .orElse(null); } /** * 复制多个对象 * * @param sources 数据对象 * @param clazz 复制目标类型 * @param <T> * @param <S> * @return 转换后对象集合 */ public static <T, S> T[] convert(S[] sources, Class<T> clazz) { return Optional.ofNullable(sources) .map(each -> { @SuppressWarnings("unchecked") T[] targetArray = (T[]) Array.newInstance(clazz, sources.length); for (int i = 0; i < targetArray.length; i++) { targetArray[i] = BEAN_MAPPER_BUILDER.map(sources[i], clazz); } return targetArray; }) .orElse(null); } /** * 拷贝非空且非空串属性 * * @param source 数据源 * @param target 指向源 */ public static void convertIgnoreNullAndBlank(Object source, Object target) { DozerBeanMapperBuilder dozerBeanMapperBuilder = DozerBeanMapperBuilder.create(); Mapper mapper = dozerBeanMapperBuilder.withMappingBuilders(new BeanMappingBuilder() { @Override protected void configure() { mapping(source.getClass(), target.getClass(), mapNull(false), mapEmptyString(false)); } }).build(); mapper.map(source, target); } /** * 拷贝非空属性 * * @param source 数据源 * @param target 指向源 */ public static void convertIgnoreNull(Object source, Object target) { DozerBeanMapperBuilder dozerBeanMapperBuilder = DozerBeanMapperBuilder.create(); Mapper mapper = dozerBeanMapperBuilder.withMappingBuilders(new BeanMappingBuilder() { @Override protected void configure() { mapping(source.getClass(), target.getClass(), mapNull(false)); } }).build(); mapper.map(source, target); } }
false
1,297
41
1,398
49
1,502
42
1,398
49
1,760
70
false
false
false
false
false
true
51732_2
package StereoMatching; import java.awt.image.BufferedImage; public class ASW extends SSD{ //通过查表还原Lab的值 private int[] LabTable = new int[1024]; public ASW(BufferedImage leftImg, BufferedImage rightImg) { super(leftImg, rightImg); for (int i = 0; i < 1024; i++) { if (i > 9) LabTable[i] = (int)(Math.pow((float)i / 1020, 1.0F / 3) * (1 << 10) + 0.5 ); else LabTable[i] = (int)((29 * 29.0 * i / (6 * 6 * 3 * 1020) + 4.0 / 29) * (1 << 10) + 0.5 ); } } @Override protected double getDist(int[] left, int[] right) { int len = left.length; double topSum = 0; double downSum = 0; for (int i = 0; i < len; i++) { double swl = getAdaptiveSupportWeight(left, i); double swr = getAdaptiveSupportWeight(right, i); topSum += swl*swr*getIntensityDistance(left[i], right[i]); downSum += swl*swr; } return topSum/downSum; } /* * window是传入的特征矩阵,n是指特征矩阵中的第n个 */ private double getAdaptiveSupportWeight(int[] window, int n) { final int k = 100; double colorCost = getColorDistance(window, n); double disCost = getSpatialDistance(window, n); return (double)(k*Math.exp(-(colorCost + disCost))); } private double getColorDistance(int[] window, int n) { int len = window.length; //经验值 final int yc = 45; int[] center = RGBToLab(window[len/2]); int[] neighbor = RGBToLab(window[n]); double c = (double)Math.sqrt((center[0] - neighbor[0])*(center[0] - neighbor[0])+(center[1] - neighbor[1])*(center[1] - neighbor[1]) + (center[2] - neighbor[2])*(center[2] - neighbor[2])); return c/yc; } //欧几里得距离 private double getSpatialDistance(int[] window, int n) { int len = (int)Math.sqrt(window.length); //经验值 final int yp = 5; double dis = (double)Math.sqrt((n/len - len/2)*(n/len - len/2) + (n%len - len/2)*(n%len - len/2)); return dis/yp; } private int getIntensityDistance(int left, int right) { int r = ((left&0x00ff0000)>>16) - ((right&0x00ff0000)>>16); int g = ((left&0x0000ff00)>>8) - ((right&0x0000ff00)>>8); int b = (left&0x000000ff) - (right&0x000000ff); return (r > 0 ? r : -r) + (g > 0 ? g : -g) + (b > 0 ? b : -b); } //牺牲一点精确度,将浮点数换成整数运算,提高运算速度 private int[] RGBToLab(int pixel) { final int big_shift = 18; final int HalfShiftValue = 512; final int shift = 10; final int offset = 128 << shift; final int ScaleLC = (16 * (1 << shift)); final int ScaleLT = 116; final int ScaleY = 903; final int para1 = 500; final int para2 = 200; final int ThPara = 9; int[] rgbImg = new int[3]; rgbImg[0] = (pixel&0x00ff0000) >> 16; rgbImg[1] = (pixel&0x0000ff00) >> 8; rgbImg[2] = pixel&0x000000ff; int[] labImg = new int[3]; int X = (rgbImg[0] * 199049 + rgbImg[1] * 394494 + rgbImg[2] * 455033 + 524288) >> (big_shift); int Y = (rgbImg[0] * 75675 + rgbImg[1] * 749900 + rgbImg[2] * 223002 + 524288) >> (big_shift); int Z = (rgbImg[0] * 915161 + rgbImg[1] * 114795 + rgbImg[2] * 18621 + 524288) >> (big_shift); labImg[0] = Y > ThPara ? ((ScaleLT * LabTable[Y] - ScaleLC + HalfShiftValue) >> shift) : ((ScaleY * Y) >> shift); labImg[1] = (para1 * (LabTable[X] - LabTable[Y]) + HalfShiftValue + offset) >> shift; labImg[2] = (para2 * (LabTable[Y] - LabTable[Z]) + HalfShiftValue + offset) >> shift; return labImg; } }
Matthew1994/Stereo-Matching
src/StereoMatching/ASW.java
1,457
//经验值
line_comment
zh-cn
package StereoMatching; import java.awt.image.BufferedImage; public class ASW extends SSD{ //通过查表还原Lab的值 private int[] LabTable = new int[1024]; public ASW(BufferedImage leftImg, BufferedImage rightImg) { super(leftImg, rightImg); for (int i = 0; i < 1024; i++) { if (i > 9) LabTable[i] = (int)(Math.pow((float)i / 1020, 1.0F / 3) * (1 << 10) + 0.5 ); else LabTable[i] = (int)((29 * 29.0 * i / (6 * 6 * 3 * 1020) + 4.0 / 29) * (1 << 10) + 0.5 ); } } @Override protected double getDist(int[] left, int[] right) { int len = left.length; double topSum = 0; double downSum = 0; for (int i = 0; i < len; i++) { double swl = getAdaptiveSupportWeight(left, i); double swr = getAdaptiveSupportWeight(right, i); topSum += swl*swr*getIntensityDistance(left[i], right[i]); downSum += swl*swr; } return topSum/downSum; } /* * window是传入的特征矩阵,n是指特征矩阵中的第n个 */ private double getAdaptiveSupportWeight(int[] window, int n) { final int k = 100; double colorCost = getColorDistance(window, n); double disCost = getSpatialDistance(window, n); return (double)(k*Math.exp(-(colorCost + disCost))); } private double getColorDistance(int[] window, int n) { int len = window.length; //经验 <SUF> final int yc = 45; int[] center = RGBToLab(window[len/2]); int[] neighbor = RGBToLab(window[n]); double c = (double)Math.sqrt((center[0] - neighbor[0])*(center[0] - neighbor[0])+(center[1] - neighbor[1])*(center[1] - neighbor[1]) + (center[2] - neighbor[2])*(center[2] - neighbor[2])); return c/yc; } //欧几里得距离 private double getSpatialDistance(int[] window, int n) { int len = (int)Math.sqrt(window.length); //经验值 final int yp = 5; double dis = (double)Math.sqrt((n/len - len/2)*(n/len - len/2) + (n%len - len/2)*(n%len - len/2)); return dis/yp; } private int getIntensityDistance(int left, int right) { int r = ((left&0x00ff0000)>>16) - ((right&0x00ff0000)>>16); int g = ((left&0x0000ff00)>>8) - ((right&0x0000ff00)>>8); int b = (left&0x000000ff) - (right&0x000000ff); return (r > 0 ? r : -r) + (g > 0 ? g : -g) + (b > 0 ? b : -b); } //牺牲一点精确度,将浮点数换成整数运算,提高运算速度 private int[] RGBToLab(int pixel) { final int big_shift = 18; final int HalfShiftValue = 512; final int shift = 10; final int offset = 128 << shift; final int ScaleLC = (16 * (1 << shift)); final int ScaleLT = 116; final int ScaleY = 903; final int para1 = 500; final int para2 = 200; final int ThPara = 9; int[] rgbImg = new int[3]; rgbImg[0] = (pixel&0x00ff0000) >> 16; rgbImg[1] = (pixel&0x0000ff00) >> 8; rgbImg[2] = pixel&0x000000ff; int[] labImg = new int[3]; int X = (rgbImg[0] * 199049 + rgbImg[1] * 394494 + rgbImg[2] * 455033 + 524288) >> (big_shift); int Y = (rgbImg[0] * 75675 + rgbImg[1] * 749900 + rgbImg[2] * 223002 + 524288) >> (big_shift); int Z = (rgbImg[0] * 915161 + rgbImg[1] * 114795 + rgbImg[2] * 18621 + 524288) >> (big_shift); labImg[0] = Y > ThPara ? ((ScaleLT * LabTable[Y] - ScaleLC + HalfShiftValue) >> shift) : ((ScaleY * Y) >> shift); labImg[1] = (para1 * (LabTable[X] - LabTable[Y]) + HalfShiftValue + offset) >> shift; labImg[2] = (para2 * (LabTable[Y] - LabTable[Z]) + HalfShiftValue + offset) >> shift; return labImg; } }
false
1,342
2
1,457
4
1,492
3
1,457
4
1,673
6
false
false
false
false
false
true
27393_1
package com.mc6m.mod.dlampmod; import com.mc6m.mod.dlampmod.save.DLWorldSavedData; import com.mc6m.mod.dlampmod.save.SetColorType; import com.mclans.dlamplib.api.Device; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.Map; public class DLampVirtualDevice { private String did; private String name; private Device device; private boolean isOnline = true; private boolean isMobTarget = true; //怪物盯上 private boolean isDynamicLight = false; // 动态光源 private boolean isHealthWarning = true; // 低血量警告 private boolean isDamageWarning = true; // 被攻击警告 private boolean isPickupNotice = true; // 拾取物品通知 private boolean isPickupEXPNotice = true; // 拾取经验通知 private boolean isFishing = true; // 钓鱼通知 private DLWorldSavedData dlwsd; private String color = "#ffffff"; private boolean isLightOpen = false; private int defaultR = 0, defaultG = 0, defaultB = 0; public DLampVirtualDevice(World world, BlockPos pos, Device device, boolean isLightOpen) { String worldname = world.getSeed() + ""; int posX = pos.getX(); int posY = pos.getY(); int posZ = pos.getZ(); this.isLightOpen = isLightOpen; String mac = device.getMac(); this.name = "次元矿灯(" + mac.substring(mac.length() - 6) + ")"; this.device = device; this.isOnline = true; this.dlwsd = DLWorldSavedData.get(world); this.did = device.getDid(); // 如果数据中有此 did if (dlwsd.getDid2Pos().containsKey(did)) { Map map = dlwsd.getSetting(did); this.isMobTarget = (boolean) map.get("isMobTarget"); this.isDynamicLight = (boolean) map.get("isDynamicLight"); this.isHealthWarning = (boolean) map.get("isHealthWarning"); this.isDamageWarning = (boolean) map.get("isDamageWarning"); this.isPickupNotice = (boolean) map.get("isPickupNotice"); this.isPickupEXPNotice = (boolean) map.get("isPickupEXPNotice"); this.isFishing = (boolean) map.get("isFishing"); this.color = (String) map.get("color"); } else { // 没有则存储 DLWorldSavedData.get(world).add(did, pos); } } private boolean isLightOpen() { return isLightOpen; } public String getDid() { return did; } void setLightOpen(boolean lightOpen) { isLightOpen = lightOpen; } public boolean isOnline() { return this.isOnline; } public boolean dynamicLight() { return this.isDynamicLight; } public void setSetting(Map map) { this.isMobTarget = (boolean) map.get("isMobTarget"); this.isDynamicLight = (boolean) map.get("isDynamicLight"); this.isHealthWarning = (boolean) map.get("isHealthWarning"); this.isDamageWarning = (boolean) map.get("isDamageWarning"); this.isPickupNotice = (boolean) map.get("isPickupNotice"); this.isPickupEXPNotice = (boolean) map.get("isPickupEXPNotice"); this.isFishing = (boolean) map.get("isFishing"); this.color = (String) map.get("color"); dlwsd.addSetting(did, map); } public boolean getLEDOn() { return this.device.getDataPoint().isLamp_on(); } public String getName() { return this.name; } // 设置默认颜色 public void setDefault(int r, int g, int b, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("设置默认颜色:" + r + "," + g + "," + b); defaultR = r; defaultG = g; defaultB = b; colorSetRGB(r, g, b); } } // 设置颜色 private void colorSetRGB(int r, int g, int b) { System.out.println("设置颜色:" + r + "," + g + "," + b); device.setRGB(r, g, b); } // 带权限的RGB public void colorSetRGB(int r, int g, int b, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("带权限的RGB:" + r + "," + g + "," + b); colorSetRGB(r, g, b); } } // 设置心跳 public void colorSetMonoHeartbeat(int r, int g, int b, int off2on_interval, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("设置心跳:" + r + "," + g + "," + b); device.setMonoHeartbeat(new int[]{r, g, b}, off2on_interval); } } // 闪一下 public void colorBlink(int r, int g, int b, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("闪一下:" + r + "," + g + "," + b); device.runBlink(new int[]{r, g, b}, 1, 500, 0); // device.setBlink(new int[]{r, g, b}); } } // 呼吸 public void colorSetBLN(int r, int g, int b, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("呼吸:" + r + "," + g + "," + b); device.setMonoBLN(new int[]{r, g, b}, 500, 500, 100); } } // 恢复默认 public void colorReset() { System.out.println("恢复默认"); colorSetRGB(defaultR, defaultG, defaultB); } // 清除各种效果 public void colorClear() { System.out.println("清除各种效果"); device.clearAll(); defaultR = 0; defaultG = 0; defaultB = 0; } // void setTempRGB(int r, int g, int b, SetColorType sct) { // if (getIsOpen(sct)) { // if (sct == SetColorType.IS_MOB_TARGET && r == 0 && g == 0 && b == 0 && this.isLightOpen) { // r = Tools.scale16To10(this.color.substring(1, 3)); // g = Tools.scale16To10(this.color.substring(3, 5)); // b = Tools.scale16To10(this.color.substring(5, 7)); // } // tempR = r; // tempG = g; // tempB = b; // setRGB(r, g, b); // } // } // void setRGB(int r, int g, int b) { // device.setRGB(r, g, b); // } // void flash(int r, int g, int b, int millisec, SetColorType sct) { // if (getIsOpen(sct)) { // if (flashing) { // timer.cancel(); // timer = new Timer(); // } // flashing = true; // device.setRGB(r, g, b); // TimerTask task = new TimerTask() { // // @Override // public void run() { // // TODO Auto-generated method stub // device.setRGB(tempR, tempG, tempB); // flashing = false; // } // }; // timer.schedule(task, millisec); // } // } // // void timedFlash(final int r, final int g, final int b, int period, SetColorType sct) { // if (getIsOpen(sct)) { // stopTimedFlash(); // timedflashing = true; //// device.setRGB(0, 0, 0); // device.setBlink(new int[]{r, g, b}, period, period); // TimerTask task = new TimerTask() { // boolean on = false; // // @Override // public void run() { // // TODO Auto-generated method stub // if (flashing) return; // if (on) { // device.setRGB(tempR, tempG, tempB); // on = false; // } else { // device.setRGB(r, g, b); // on = true; // } // } // }; // timedtimer.schedule(task, 0, period); // } // } // // void stopTimedFlash() { // device.clearAll(); // // timedflashing = false; // timedtimer.cancel(); // setRGB(tempR, tempG, tempB); // timedtimer = new Timer(); // } // // void reset() { // stopTimedFlash(); // tempR = 0; // tempG = 0; // tempB = 0; // setRGB(0, 0, 0); // } private boolean getIsOpen(SetColorType sct) { boolean isOpen = false; switch (sct) { case IS_MOB_TARGET: isOpen = this.isMobTarget; break; case IS_PICKUP_EXP_NPTICE: isOpen = this.isPickupEXPNotice; break; case IS_PICKUP_NOTICE: isOpen = this.isPickupNotice; break; case IS_DAMAGE_WARNING: isOpen = this.isDamageWarning; break; case IS_DYNAMEIC_LIGHT: isOpen = this.isDynamicLight; break; case IS_HEALTH_WARNING: isOpen = this.isHealthWarning; break; case IS_FINSHING: isOpen = this.isFishing; break; case FINAL_TRUE: isOpen = true; break; case FINAL_FALSE: isOpen = false; break; } return isOpen; } }
MclansCN/DLampMod
src/main/java/com/mc6m/mod/dlampmod/DLampVirtualDevice.java
2,579
// 动态光源
line_comment
zh-cn
package com.mc6m.mod.dlampmod; import com.mc6m.mod.dlampmod.save.DLWorldSavedData; import com.mc6m.mod.dlampmod.save.SetColorType; import com.mclans.dlamplib.api.Device; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import java.util.Map; public class DLampVirtualDevice { private String did; private String name; private Device device; private boolean isOnline = true; private boolean isMobTarget = true; //怪物盯上 private boolean isDynamicLight = false; // 动态 <SUF> private boolean isHealthWarning = true; // 低血量警告 private boolean isDamageWarning = true; // 被攻击警告 private boolean isPickupNotice = true; // 拾取物品通知 private boolean isPickupEXPNotice = true; // 拾取经验通知 private boolean isFishing = true; // 钓鱼通知 private DLWorldSavedData dlwsd; private String color = "#ffffff"; private boolean isLightOpen = false; private int defaultR = 0, defaultG = 0, defaultB = 0; public DLampVirtualDevice(World world, BlockPos pos, Device device, boolean isLightOpen) { String worldname = world.getSeed() + ""; int posX = pos.getX(); int posY = pos.getY(); int posZ = pos.getZ(); this.isLightOpen = isLightOpen; String mac = device.getMac(); this.name = "次元矿灯(" + mac.substring(mac.length() - 6) + ")"; this.device = device; this.isOnline = true; this.dlwsd = DLWorldSavedData.get(world); this.did = device.getDid(); // 如果数据中有此 did if (dlwsd.getDid2Pos().containsKey(did)) { Map map = dlwsd.getSetting(did); this.isMobTarget = (boolean) map.get("isMobTarget"); this.isDynamicLight = (boolean) map.get("isDynamicLight"); this.isHealthWarning = (boolean) map.get("isHealthWarning"); this.isDamageWarning = (boolean) map.get("isDamageWarning"); this.isPickupNotice = (boolean) map.get("isPickupNotice"); this.isPickupEXPNotice = (boolean) map.get("isPickupEXPNotice"); this.isFishing = (boolean) map.get("isFishing"); this.color = (String) map.get("color"); } else { // 没有则存储 DLWorldSavedData.get(world).add(did, pos); } } private boolean isLightOpen() { return isLightOpen; } public String getDid() { return did; } void setLightOpen(boolean lightOpen) { isLightOpen = lightOpen; } public boolean isOnline() { return this.isOnline; } public boolean dynamicLight() { return this.isDynamicLight; } public void setSetting(Map map) { this.isMobTarget = (boolean) map.get("isMobTarget"); this.isDynamicLight = (boolean) map.get("isDynamicLight"); this.isHealthWarning = (boolean) map.get("isHealthWarning"); this.isDamageWarning = (boolean) map.get("isDamageWarning"); this.isPickupNotice = (boolean) map.get("isPickupNotice"); this.isPickupEXPNotice = (boolean) map.get("isPickupEXPNotice"); this.isFishing = (boolean) map.get("isFishing"); this.color = (String) map.get("color"); dlwsd.addSetting(did, map); } public boolean getLEDOn() { return this.device.getDataPoint().isLamp_on(); } public String getName() { return this.name; } // 设置默认颜色 public void setDefault(int r, int g, int b, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("设置默认颜色:" + r + "," + g + "," + b); defaultR = r; defaultG = g; defaultB = b; colorSetRGB(r, g, b); } } // 设置颜色 private void colorSetRGB(int r, int g, int b) { System.out.println("设置颜色:" + r + "," + g + "," + b); device.setRGB(r, g, b); } // 带权限的RGB public void colorSetRGB(int r, int g, int b, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("带权限的RGB:" + r + "," + g + "," + b); colorSetRGB(r, g, b); } } // 设置心跳 public void colorSetMonoHeartbeat(int r, int g, int b, int off2on_interval, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("设置心跳:" + r + "," + g + "," + b); device.setMonoHeartbeat(new int[]{r, g, b}, off2on_interval); } } // 闪一下 public void colorBlink(int r, int g, int b, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("闪一下:" + r + "," + g + "," + b); device.runBlink(new int[]{r, g, b}, 1, 500, 0); // device.setBlink(new int[]{r, g, b}); } } // 呼吸 public void colorSetBLN(int r, int g, int b, SetColorType sct) { if (getIsOpen(sct)) { System.out.println("呼吸:" + r + "," + g + "," + b); device.setMonoBLN(new int[]{r, g, b}, 500, 500, 100); } } // 恢复默认 public void colorReset() { System.out.println("恢复默认"); colorSetRGB(defaultR, defaultG, defaultB); } // 清除各种效果 public void colorClear() { System.out.println("清除各种效果"); device.clearAll(); defaultR = 0; defaultG = 0; defaultB = 0; } // void setTempRGB(int r, int g, int b, SetColorType sct) { // if (getIsOpen(sct)) { // if (sct == SetColorType.IS_MOB_TARGET && r == 0 && g == 0 && b == 0 && this.isLightOpen) { // r = Tools.scale16To10(this.color.substring(1, 3)); // g = Tools.scale16To10(this.color.substring(3, 5)); // b = Tools.scale16To10(this.color.substring(5, 7)); // } // tempR = r; // tempG = g; // tempB = b; // setRGB(r, g, b); // } // } // void setRGB(int r, int g, int b) { // device.setRGB(r, g, b); // } // void flash(int r, int g, int b, int millisec, SetColorType sct) { // if (getIsOpen(sct)) { // if (flashing) { // timer.cancel(); // timer = new Timer(); // } // flashing = true; // device.setRGB(r, g, b); // TimerTask task = new TimerTask() { // // @Override // public void run() { // // TODO Auto-generated method stub // device.setRGB(tempR, tempG, tempB); // flashing = false; // } // }; // timer.schedule(task, millisec); // } // } // // void timedFlash(final int r, final int g, final int b, int period, SetColorType sct) { // if (getIsOpen(sct)) { // stopTimedFlash(); // timedflashing = true; //// device.setRGB(0, 0, 0); // device.setBlink(new int[]{r, g, b}, period, period); // TimerTask task = new TimerTask() { // boolean on = false; // // @Override // public void run() { // // TODO Auto-generated method stub // if (flashing) return; // if (on) { // device.setRGB(tempR, tempG, tempB); // on = false; // } else { // device.setRGB(r, g, b); // on = true; // } // } // }; // timedtimer.schedule(task, 0, period); // } // } // // void stopTimedFlash() { // device.clearAll(); // // timedflashing = false; // timedtimer.cancel(); // setRGB(tempR, tempG, tempB); // timedtimer = new Timer(); // } // // void reset() { // stopTimedFlash(); // tempR = 0; // tempG = 0; // tempB = 0; // setRGB(0, 0, 0); // } private boolean getIsOpen(SetColorType sct) { boolean isOpen = false; switch (sct) { case IS_MOB_TARGET: isOpen = this.isMobTarget; break; case IS_PICKUP_EXP_NPTICE: isOpen = this.isPickupEXPNotice; break; case IS_PICKUP_NOTICE: isOpen = this.isPickupNotice; break; case IS_DAMAGE_WARNING: isOpen = this.isDamageWarning; break; case IS_DYNAMEIC_LIGHT: isOpen = this.isDynamicLight; break; case IS_HEALTH_WARNING: isOpen = this.isHealthWarning; break; case IS_FINSHING: isOpen = this.isFishing; break; case FINAL_TRUE: isOpen = true; break; case FINAL_FALSE: isOpen = false; break; } return isOpen; } }
false
2,307
5
2,579
5
2,665
4
2,579
5
3,024
6
false
false
false
false
false
true
56846_2
package com.aliyun.auipusher; import java.io.Serializable; /** * 角色 */ public enum LiveRole implements Serializable { /** * 主播 */ ANCHOR("anchor"), /** * 观众 */ AUDIENCE("audience"), ; public final String value; LiveRole(String value) { this.value = value; } public static LiveRole ofValue(String value) { return ANCHOR.value.equals(value) ? ANCHOR : AUDIENCE; } }
MediaBox-AUIKits/AUIInteractionLive
Android/AUICore/AUIPusher/src/main/java/com/aliyun/auipusher/LiveRole.java
132
/** * 观众 */
block_comment
zh-cn
package com.aliyun.auipusher; import java.io.Serializable; /** * 角色 */ public enum LiveRole implements Serializable { /** * 主播 */ ANCHOR("anchor"), /** * 观众 <SUF>*/ AUDIENCE("audience"), ; public final String value; LiveRole(String value) { this.value = value; } public static LiveRole ofValue(String value) { return ANCHOR.value.equals(value) ? ANCHOR : AUDIENCE; } }
false
114
9
132
8
136
9
132
8
165
14
false
false
false
false
false
true
8520_3
package com.aliyun.auikits.rtc; public enum VoiceChangeType { //关闭 OFF(0), //老人 Oldman(1), //男孩 Babyboy(2), //女孩 Babygirl(3), //机器人 Robot(4), //大魔王 Daimo(5), //KTV Ktv(6), //回声 Echo(7), //方言 Dialect(8), //怒吼 Howl(9), //电音 Electronic(10), //留声机 Phonograph(11); private final int mVal; VoiceChangeType(int val){ this.mVal = val; } public int getVal(){ return this.mVal; } public static VoiceChangeType fromInt(int val){ for(VoiceChangeType type : VoiceChangeType.values()){ if(type.getVal() == val) return type; } return VoiceChangeType.OFF; } }
MediaBox-AUIKits/AUIVoiceRoom
Android/AUIVoiceRoomEngine/src/main/java/com/aliyun/auikits/rtc/VoiceChangeType.java
242
//留声机
line_comment
zh-cn
package com.aliyun.auikits.rtc; public enum VoiceChangeType { //关闭 OFF(0), //老人 Oldman(1), //男孩 Babyboy(2), //女孩 Babygirl(3), //机器人 Robot(4), //大魔王 Daimo(5), //KTV Ktv(6), //回声 Echo(7), //方言 Dialect(8), //怒吼 Howl(9), //电音 Electronic(10), //留声 <SUF> Phonograph(11); private final int mVal; VoiceChangeType(int val){ this.mVal = val; } public int getVal(){ return this.mVal; } public static VoiceChangeType fromInt(int val){ for(VoiceChangeType type : VoiceChangeType.values()){ if(type.getVal() == val) return type; } return VoiceChangeType.OFF; } }
false
229
4
242
4
263
4
242
4
320
8
false
false
false
false
false
true
31490_1
public class Dom1 { public static void main(String[]args){ int[]a={1,2,3,4,5,6,7}; for(int arr:a){ //增强for循环 System.out.println(arr); } // 求奇数德和 int sum=0; for(int arr1:a){ if(arr1%2==0){ continue; //跳过本次循环 } sum+=arr1; } System.out.println("奇数和:"+sum); } }
MengDongDust/java
Dom1.java
135
// 求奇数德和
line_comment
zh-cn
public class Dom1 { public static void main(String[]args){ int[]a={1,2,3,4,5,6,7}; for(int arr:a){ //增强for循环 System.out.println(arr); } // 求奇 <SUF> int sum=0; for(int arr1:a){ if(arr1%2==0){ continue; //跳过本次循环 } sum+=arr1; } System.out.println("奇数和:"+sum); } }
false
120
10
134
10
143
8
134
10
171
8
false
false
false
false
false
true
26522_3
import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; public class crawler { @SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { // 采集的网址 String url = "https://etherscan.io/contractsVerified/"; Document document = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36").get(); // 获取审查页面的页数信息 int total_page = Integer.parseInt(document.select("body > div.wrapper > div.profile.container > div:nth-child(4) > div:nth-child(2) > p > span > b:nth-child(2)").text()); System.out.println(total_page); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("sheet1"); HSSFRow row = sheet.createRow(0); HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); HSSFCell cell1 = row.createCell(0); cell1.setCellValue("contract"); cell1.setCellStyle(style); HSSFCell cell2 = row.createCell(1); cell2.setCellValue("name"); cell2.setCellStyle(style); HSSFCell cell3 = row.createCell(2); cell3.setCellValue("compiler"); cell3.setCellStyle(style); HSSFCell cell4 = row.createCell(3); cell4.setCellValue("balance"); cell4.setCellStyle(style); HSSFCell cell5 = row.createCell(4); cell5.setCellValue("txCount"); cell5.setCellStyle(style); HSSFCell cell6 = row.createCell(5); cell6.setCellValue("settings"); cell6.setCellStyle(style); HSSFCell cell7 = row.createCell(6); cell7.setCellValue("dateTime"); cell7.setCellStyle(style); for (int current_page = 1; current_page <= total_page; current_page++) { if (current_page == 1) { List<Contract> list = getData(url); JSONArray array = new JSONArray(); array.add(list); for (int i = 0; i < list.size(); i++) { row = sheet.createRow(i + 1); row.createCell(0).setCellValue(list.get(i).getAddress()); row.createCell(1).setCellValue(list.get(i).getName()); row.createCell(2).setCellValue(list.get(i).getCompiler()); row.createCell(3).setCellValue(list.get(i).getBalance()); row.createCell(4).setCellValue(list.get(i).getTxCount()); row.createCell(5).setCellValue(list.get(i).getSettings()); row.createCell(6).setCellValue(list.get(i).getDateTime()); } } else { List<Contract> list = getData(url + current_page); JSONArray array = new JSONArray(); array.add(list); System.out.println("**************************************"); for (int i = 0; i < list.size(); i++) { row = sheet.createRow((short) (sheet.getLastRowNum() + 1)); //现有的行号后面追加 //row = sheet.createRow(i + 1); row.createCell(0).setCellValue(list.get(i).getAddress()); row.createCell(1).setCellValue(list.get(i).getName()); row.createCell(2).setCellValue(list.get(i).getCompiler()); row.createCell(3).setCellValue(list.get(i).getBalance()); row.createCell(4).setCellValue(list.get(i).getTxCount()); row.createCell(5).setCellValue(list.get(i).getSettings()); row.createCell(6).setCellValue(list.get(i).getDateTime()); } } try { FileOutputStream fos = new FileOutputStream("/home/jion1/crawler_data/data_contract2.xls"); wb.write(fos); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("done"); } public static List<Contract> getData(String url) throws Exception { List<Contract> contractList = new ArrayList<Contract>(); Document doc = Jsoup.connect(url) .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0") .timeout(600000).get(); Elements elements2 = doc.select("div.table-responsive").select("table").select("tbody").select("tr"); for (int i = 0; i < elements2.size(); i++) { String contract = elements2.get(i).select("td").get(0).text(); String name = elements2.get(i).select("td").get(1).text(); String compiler = elements2.get(i).select("td").get(2).text(); String balance = elements2.get(i).select("td").get(3).text(); String txCount = elements2.get(i).select("td").get(4).text(); String settings = elements2.get(i).select("td").get(5).text(); String dateTime = elements2.get(i).select("td").get(6).text(); contractList.add(new Contract(contract, name, compiler, balance, txCount, settings, dateTime)); } return contractList; } }
Messi-Q/Crawler
crawler.java
1,534
//现有的行号后面追加
line_comment
zh-cn
import java.io.FileOutputStream; import java.util.ArrayList; import java.util.List; import net.sf.json.JSONArray; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.select.Elements; public class crawler { @SuppressWarnings("deprecation") public static void main(String[] args) throws Exception { // 采集的网址 String url = "https://etherscan.io/contractsVerified/"; Document document = Jsoup.connect(url).userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36").get(); // 获取审查页面的页数信息 int total_page = Integer.parseInt(document.select("body > div.wrapper > div.profile.container > div:nth-child(4) > div:nth-child(2) > p > span > b:nth-child(2)").text()); System.out.println(total_page); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("sheet1"); HSSFRow row = sheet.createRow(0); HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_CENTER); HSSFCell cell1 = row.createCell(0); cell1.setCellValue("contract"); cell1.setCellStyle(style); HSSFCell cell2 = row.createCell(1); cell2.setCellValue("name"); cell2.setCellStyle(style); HSSFCell cell3 = row.createCell(2); cell3.setCellValue("compiler"); cell3.setCellStyle(style); HSSFCell cell4 = row.createCell(3); cell4.setCellValue("balance"); cell4.setCellStyle(style); HSSFCell cell5 = row.createCell(4); cell5.setCellValue("txCount"); cell5.setCellStyle(style); HSSFCell cell6 = row.createCell(5); cell6.setCellValue("settings"); cell6.setCellStyle(style); HSSFCell cell7 = row.createCell(6); cell7.setCellValue("dateTime"); cell7.setCellStyle(style); for (int current_page = 1; current_page <= total_page; current_page++) { if (current_page == 1) { List<Contract> list = getData(url); JSONArray array = new JSONArray(); array.add(list); for (int i = 0; i < list.size(); i++) { row = sheet.createRow(i + 1); row.createCell(0).setCellValue(list.get(i).getAddress()); row.createCell(1).setCellValue(list.get(i).getName()); row.createCell(2).setCellValue(list.get(i).getCompiler()); row.createCell(3).setCellValue(list.get(i).getBalance()); row.createCell(4).setCellValue(list.get(i).getTxCount()); row.createCell(5).setCellValue(list.get(i).getSettings()); row.createCell(6).setCellValue(list.get(i).getDateTime()); } } else { List<Contract> list = getData(url + current_page); JSONArray array = new JSONArray(); array.add(list); System.out.println("**************************************"); for (int i = 0; i < list.size(); i++) { row = sheet.createRow((short) (sheet.getLastRowNum() + 1)); //现有 <SUF> //row = sheet.createRow(i + 1); row.createCell(0).setCellValue(list.get(i).getAddress()); row.createCell(1).setCellValue(list.get(i).getName()); row.createCell(2).setCellValue(list.get(i).getCompiler()); row.createCell(3).setCellValue(list.get(i).getBalance()); row.createCell(4).setCellValue(list.get(i).getTxCount()); row.createCell(5).setCellValue(list.get(i).getSettings()); row.createCell(6).setCellValue(list.get(i).getDateTime()); } } try { FileOutputStream fos = new FileOutputStream("/home/jion1/crawler_data/data_contract2.xls"); wb.write(fos); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("done"); } public static List<Contract> getData(String url) throws Exception { List<Contract> contractList = new ArrayList<Contract>(); Document doc = Jsoup.connect(url) .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0") .timeout(600000).get(); Elements elements2 = doc.select("div.table-responsive").select("table").select("tbody").select("tr"); for (int i = 0; i < elements2.size(); i++) { String contract = elements2.get(i).select("td").get(0).text(); String name = elements2.get(i).select("td").get(1).text(); String compiler = elements2.get(i).select("td").get(2).text(); String balance = elements2.get(i).select("td").get(3).text(); String txCount = elements2.get(i).select("td").get(4).text(); String settings = elements2.get(i).select("td").get(5).text(); String dateTime = elements2.get(i).select("td").get(6).text(); contractList.add(new Contract(contract, name, compiler, balance, txCount, settings, dateTime)); } return contractList; } }
false
1,248
7
1,534
8
1,538
7
1,534
8
1,794
12
false
false
false
false
false
true
65914_10
package com.model; /** * Created by Administrator on 2016/11/9. */ public class LagouModel implements Model{ private String channelId = "0"; /** * 多选一 后端开发 移动开发 前端开发 测试 运维 DBA 高端技术职位 项目管理 硬件开发 企业软件 产品经理 产品设计师 高端产品职位 视觉设计 用户研究 * 高端设计职位 交互设计 运营 编辑 客服 高端运营职位 市场/营销 公关 销售 高端市场职位 供应链 采购 投资 人力资源 行政 财务 高端职能职位 法务 * 投融资 风控 审计税务 高端金融职位 * 职位类别”与“职位名称”在发布后不可修改,请谨慎填写 */ private String positionType; private String positionName; /** * positionType为主类别,从主类别下属中选一个副类别,对应关系详见职位分布.txt */ private String positionThirdType; /** * 部门,任填 */ private String department; /** * 全职 兼职 实习 三选一 */ private String jobNature; private String salaryMin; /** * 最高工资和最低工资差距不超过2倍 */ private String salaryMax; /** * 不限 应届毕业生 1年以下 1-3年 3-5年 5-10年 10年以上 7选1 */ private String workYear; /** * 不限 大专 本科 硕士 博士 5选1 */ private String education; /** * 任填,多个用英文逗号隔开,每个最多5个字 */ private String positionBrightPoint; /** * 20-2000字html格式 */ private String positionDesc; /** * 从地址列表中取 */ private String workAddressId; public String getChannelId() { return channelId; } public void setChannelId(String channelId) { this.channelId = channelId; } public String getPositionType() { return positionType; } public void setPositionType(String positionType) { this.positionType = positionType; } public String getPositionName() { return positionName; } public void setPositionName(String positionName) { this.positionName = positionName; } public String getPositionThirdType() { return positionThirdType; } public void setPositionThirdType(String positionThirdType) { this.positionThirdType = positionThirdType; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getJobNature() { return jobNature; } public void setJobNature(String jobNature) { this.jobNature = jobNature; } public String getSalaryMin() { return salaryMin; } public void setSalaryMin(String salaryMin) { this.salaryMin = salaryMin; } public String getSalaryMax() { return salaryMax; } public void setSalaryMax(String salaryMax) { this.salaryMax = salaryMax; } public String getWorkYear() { return workYear; } public void setWorkYear(String workYear) { this.workYear = workYear; } public String getEducation() { return education; } public void setEducation(String education) { this.education = education; } public String getPositionBrightPoint() { return positionBrightPoint; } public void setPositionBrightPoint(String positionBrightPoint) { this.positionBrightPoint = positionBrightPoint; } public String getPositionDesc() { return positionDesc; } public void setPositionDesc(String positionDesc) { this.positionDesc = positionDesc; } public String getWorkAddressId() { return workAddressId; } public void setWorkAddressId(String workAddressId) { this.workAddressId = workAddressId; } }
MessiMercy/MessiCrawler
src/main/java/com/model/LagouModel.java
1,035
/** * 从地址列表中取 */
block_comment
zh-cn
package com.model; /** * Created by Administrator on 2016/11/9. */ public class LagouModel implements Model{ private String channelId = "0"; /** * 多选一 后端开发 移动开发 前端开发 测试 运维 DBA 高端技术职位 项目管理 硬件开发 企业软件 产品经理 产品设计师 高端产品职位 视觉设计 用户研究 * 高端设计职位 交互设计 运营 编辑 客服 高端运营职位 市场/营销 公关 销售 高端市场职位 供应链 采购 投资 人力资源 行政 财务 高端职能职位 法务 * 投融资 风控 审计税务 高端金融职位 * 职位类别”与“职位名称”在发布后不可修改,请谨慎填写 */ private String positionType; private String positionName; /** * positionType为主类别,从主类别下属中选一个副类别,对应关系详见职位分布.txt */ private String positionThirdType; /** * 部门,任填 */ private String department; /** * 全职 兼职 实习 三选一 */ private String jobNature; private String salaryMin; /** * 最高工资和最低工资差距不超过2倍 */ private String salaryMax; /** * 不限 应届毕业生 1年以下 1-3年 3-5年 5-10年 10年以上 7选1 */ private String workYear; /** * 不限 大专 本科 硕士 博士 5选1 */ private String education; /** * 任填,多个用英文逗号隔开,每个最多5个字 */ private String positionBrightPoint; /** * 20-2000字html格式 */ private String positionDesc; /** * 从地址 <SUF>*/ private String workAddressId; public String getChannelId() { return channelId; } public void setChannelId(String channelId) { this.channelId = channelId; } public String getPositionType() { return positionType; } public void setPositionType(String positionType) { this.positionType = positionType; } public String getPositionName() { return positionName; } public void setPositionName(String positionName) { this.positionName = positionName; } public String getPositionThirdType() { return positionThirdType; } public void setPositionThirdType(String positionThirdType) { this.positionThirdType = positionThirdType; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getJobNature() { return jobNature; } public void setJobNature(String jobNature) { this.jobNature = jobNature; } public String getSalaryMin() { return salaryMin; } public void setSalaryMin(String salaryMin) { this.salaryMin = salaryMin; } public String getSalaryMax() { return salaryMax; } public void setSalaryMax(String salaryMax) { this.salaryMax = salaryMax; } public String getWorkYear() { return workYear; } public void setWorkYear(String workYear) { this.workYear = workYear; } public String getEducation() { return education; } public void setEducation(String education) { this.education = education; } public String getPositionBrightPoint() { return positionBrightPoint; } public void setPositionBrightPoint(String positionBrightPoint) { this.positionBrightPoint = positionBrightPoint; } public String getPositionDesc() { return positionDesc; } public void setPositionDesc(String positionDesc) { this.positionDesc = positionDesc; } public String getWorkAddressId() { return workAddressId; } public void setWorkAddressId(String workAddressId) { this.workAddressId = workAddressId; } }
false
944
12
1,035
10
1,051
12
1,035
10
1,413
15
false
false
false
false
false
true
55681_3
package dynamicprogramming; /** * @author lei.X */ public class HouseRobber198 { public int rob(int[] nums) { int size = nums.length; if (size ==0) return 0; int[] dp = new int[size+1]; dp[1] = nums[0]; for(int i =2;i<=size;i++){ dp[i] = Math.max(dp[i-1],nums[i-1]+ dp[i-2]); } return dp[size]; } public int backUp(int[] nums){ int size = nums.length; int[] dp = new int[size]; for (int i=0;i<size;i++){ if (i==0){ dp[i] = nums[i]; }else if (i==1){ dp[i] = Math.max(nums[i],nums[i-1]); }else { dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]); } } return dp[size-1]; } /** * 房子是首位相连的 * 所以选了第一个屋子就不能选最后一个屋子,翻转同理 * @param nums * @return */ public int backUp2(int[] nums){ int size = nums.length; int[] dp = new int[size]; // 第一个屋子被选的情况 dp[0] = nums[0]; dp[1] = dp[0]; for (int i=2;i<size-1;i++){ dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]); } // 第一个屋子没有被选 dp[0] = 0; dp[1] = nums[1]; for (int i=2;i<size;i++){ dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]); } return dp[size-1]; } }
Metatronxl/leetcode-java-version
src/dynamicprogramming/HouseRobber198.java
498
// 第一个屋子没有被选
line_comment
zh-cn
package dynamicprogramming; /** * @author lei.X */ public class HouseRobber198 { public int rob(int[] nums) { int size = nums.length; if (size ==0) return 0; int[] dp = new int[size+1]; dp[1] = nums[0]; for(int i =2;i<=size;i++){ dp[i] = Math.max(dp[i-1],nums[i-1]+ dp[i-2]); } return dp[size]; } public int backUp(int[] nums){ int size = nums.length; int[] dp = new int[size]; for (int i=0;i<size;i++){ if (i==0){ dp[i] = nums[i]; }else if (i==1){ dp[i] = Math.max(nums[i],nums[i-1]); }else { dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]); } } return dp[size-1]; } /** * 房子是首位相连的 * 所以选了第一个屋子就不能选最后一个屋子,翻转同理 * @param nums * @return */ public int backUp2(int[] nums){ int size = nums.length; int[] dp = new int[size]; // 第一个屋子被选的情况 dp[0] = nums[0]; dp[1] = dp[0]; for (int i=2;i<size-1;i++){ dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]); } // 第一 <SUF> dp[0] = 0; dp[1] = nums[1]; for (int i=2;i<size;i++){ dp[i] = Math.max(dp[i-1],dp[i-2]+nums[i]); } return dp[size-1]; } }
false
429
7
499
9
532
8
498
9
610
11
false
false
false
false
false
true
59739_1
package util; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import java.util.Collections; /** * @Author Method.Jiao * @Date 2019/10/19 13:36 */ public class MongoUtil { /** * 不通过认证获取连接数据库对象 */ public static MongoDatabase getConnect() { ConnectConfig connectConfig = new ConnectConfig(); //连接到 mongodb 服务 MongoClient mongoClient = MongoClients.create("mongodb://" + connectConfig.getMongodbIp() + ":" + connectConfig.getMongodbPort()); //返回连接数据库对象 return mongoClient.getDatabase("mydb"); } /** * 需要密码认证方式连接 */ public static MongoDatabase getConnect2() { //通过连接认证获取MongoDB连接 String user = ""; String database = ""; char[] password = {'p', 'a', 's', 's'}; MongoCredential credential = MongoCredential.createCredential(user, database, password); MongoClientSettings settings = MongoClientSettings.builder() .credential(credential) .applyToSslSettings(builder -> builder.enabled(true)) .applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(new ServerAddress("host1", 27017)))) .build(); MongoClient mongoClient = MongoClients.create(settings); //返回连接数据库对象 return mongoClient.getDatabase("mydb"); } }
MethodJiao/Kafka2Mongodb
src/main/java/util/MongoUtil.java
384
/** * 不通过认证获取连接数据库对象 */
block_comment
zh-cn
package util; import com.mongodb.MongoClientSettings; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoDatabase; import java.util.Collections; /** * @Author Method.Jiao * @Date 2019/10/19 13:36 */ public class MongoUtil { /** * 不通过 <SUF>*/ public static MongoDatabase getConnect() { ConnectConfig connectConfig = new ConnectConfig(); //连接到 mongodb 服务 MongoClient mongoClient = MongoClients.create("mongodb://" + connectConfig.getMongodbIp() + ":" + connectConfig.getMongodbPort()); //返回连接数据库对象 return mongoClient.getDatabase("mydb"); } /** * 需要密码认证方式连接 */ public static MongoDatabase getConnect2() { //通过连接认证获取MongoDB连接 String user = ""; String database = ""; char[] password = {'p', 'a', 's', 's'}; MongoCredential credential = MongoCredential.createCredential(user, database, password); MongoClientSettings settings = MongoClientSettings.builder() .credential(credential) .applyToSslSettings(builder -> builder.enabled(true)) .applyToClusterSettings(builder -> builder.hosts(Collections.singletonList(new ServerAddress("host1", 27017)))) .build(); MongoClient mongoClient = MongoClients.create(settings); //返回连接数据库对象 return mongoClient.getDatabase("mydb"); } }
false
338
13
384
13
398
14
384
13
482
24
false
false
false
false
false
true
47504_1
package com.csjbot.mobileshop.ai; import android.text.TextUtils; import com.csjbot.mobileshop.feature.nearbyservice.NearByActivity; import com.csjbot.mobileshop.global.Constants; import java.util.ArrayList; import java.util.List; /** * Created by jingwc on 2017/10/26. */ public class NearByAI extends AI<NearByActivity>{ public static NearByAI newInstance(){ return new NearByAI(); } @Override public Intent getIntent(String text) { String pinyin = strConvertPinyin(text); Intent intent = null; boolean isStop = false; int size = AIParams.datas.size(); for (int i = 0; i < size;i++){ int paramSize = AIParams.datas.get(i)[0].length; for (int j = 0;j < paramSize;j++){ if(pinyin.contains(AIParams.datas.get(i)[0][j].toString())){ intent = (Intent) AIParams.datas.get(i)[1][0]; isStop = true; break; } } if(isStop){ break; } } return intent; } @Override public void handleIntent(Enum e) { super.handleIntent(e); Intent intent = (Intent) e; switch (intent){ case FOOD: activity.goPoiSearchAct("美食"); break; case SCENIC_SPOT: activity.goPoiSearchAct("景点"); break; case HOTEL: activity.goPoiSearchAct("酒店"); break; case ENTERTAINMENT: activity.goPoiSearchAct("休闲娱乐"); break; case SHARING_BIKES: activity.goPoiSearchAct("共享单车"); break; case SUPERMARKET: activity.goPoiSearchAct("超市"); break; case ATM: activity.goPoiSearchAct("ATM"); break; case TOILET: activity.goPoiSearchAct("厕所"); break; case BUDGET_HOTEL: activity.goPoiSearchAct("快捷酒店"); break; case INTERNET_BAR: activity.goPoiSearchAct("网吧"); break; case METRO: activity.goPoiSearchAct("地铁"); break; case GAS_STATION: activity.goPoiSearchAct("加油站"); break; case BUS_STATION: if (TextUtils.equals(Constants.Scene.CurrentScene,"lvyou")) { activity.goPoiSearchAct("公交车站"); } break; case SHARABLE_CHARGE: if (TextUtils.equals(Constants.Scene.CurrentScene,"lvyou")) { activity.goPoiSearchAct("共享充电宝"); } break; case PARK: if (TextUtils.equals(Constants.Scene.CurrentScene,"lvyou")) { activity.goPoiSearchAct("停车场"); } break; case HOSPITAL: if (TextUtils.equals(Constants.Scene.CurrentScene,"lvyou")) { activity.goPoiSearchAct("医院"); } break; default: break; } } static class AIParams{ static final String[] FOOD = {"MEISHI","SHIWU","FANDIAN"}; static final String[] SCENIC_SPOT = {"JINGDIAN","JINGQU"}; static final String[] HOTEL = {"JIUDIAN"}; static final String[] ENTERTAINMENT = {"YULE","XIUXIAN"}; static final String[] SHARING_BIKES = {"GONGXIANGDANCHE"}; static final String[] SUPERMARKET = {"CHAOSHI","SHANGCHANG","SHANGDIAN"}; static final String[] ATM = {"ATM","QUKUANJI","QUQIAN"}; static final String[] TOILET = {"CESUO","WEISHENGJIAN"}; static final String[] BUDGET_HOTEL = {"KUAIJIEJIUDIAN"}; static final String[] INTERNET_BAR = {"WANGBA"}; static final String[] METRO = {"DITIE"}; static final String[] GAS_STATION = {"JIAYOUZHAN"}; //旅游 static final String[] BUS_STATION = {"GONGJIAOCHEZHAN"}; static final String[] SHARABLE_CHARGE = {"CHONGDIANBAO","GONGXIANGCHONGDIANBAO"}; static final String[] PARK = {"TINGCHECHANG"}; static final String[] HOSPITAL = {"YIYUAN"}; static List<Object[][]> datas; static { datas = new ArrayList<>(); datas.add(new Object[][]{FOOD,{Intent.FOOD}}); datas.add(new Object[][]{SCENIC_SPOT,{Intent.SCENIC_SPOT}}); datas.add(new Object[][]{BUDGET_HOTEL,{Intent.BUDGET_HOTEL}}); datas.add(new Object[][]{HOTEL,{Intent.HOTEL}}); datas.add(new Object[][]{ENTERTAINMENT,{Intent.ENTERTAINMENT}}); datas.add(new Object[][]{SHARING_BIKES,{Intent.SHARING_BIKES}}); datas.add(new Object[][]{SUPERMARKET,{Intent.SUPERMARKET}}); datas.add(new Object[][]{ATM,{Intent.ATM}}); datas.add(new Object[][]{TOILET,{Intent.TOILET}}); datas.add(new Object[][]{INTERNET_BAR,{Intent.INTERNET_BAR}}); datas.add(new Object[][]{METRO,{Intent.METRO}}); datas.add(new Object[][]{GAS_STATION,{Intent.GAS_STATION}}); //旅游 datas.add(new Object[][]{BUS_STATION,{Intent.BUS_STATION}}); datas.add(new Object[][]{SHARABLE_CHARGE,{Intent.SHARABLE_CHARGE}}); datas.add(new Object[][]{PARK,{Intent.PARK}}); datas.add(new Object[][]{HOSPITAL,{Intent.HOSPITAL}}); } } public enum Intent{ FOOD,SCENIC_SPOT,HOTEL ,ENTERTAINMENT,SHARING_BIKES ,SUPERMARKET,ATM,TOILET ,BUDGET_HOTEL,INTERNET_BAR,METRO,GAS_STATION ,BUS_STATION,SHARABLE_CHARGE,PARK,HOSPITAL //旅游场景 } }
MiRobotic/csj-new-demo
app/src/main/java/com/csjbot/mobileshop/ai/NearByAI.java
1,554
//旅游场景
line_comment
zh-cn
package com.csjbot.mobileshop.ai; import android.text.TextUtils; import com.csjbot.mobileshop.feature.nearbyservice.NearByActivity; import com.csjbot.mobileshop.global.Constants; import java.util.ArrayList; import java.util.List; /** * Created by jingwc on 2017/10/26. */ public class NearByAI extends AI<NearByActivity>{ public static NearByAI newInstance(){ return new NearByAI(); } @Override public Intent getIntent(String text) { String pinyin = strConvertPinyin(text); Intent intent = null; boolean isStop = false; int size = AIParams.datas.size(); for (int i = 0; i < size;i++){ int paramSize = AIParams.datas.get(i)[0].length; for (int j = 0;j < paramSize;j++){ if(pinyin.contains(AIParams.datas.get(i)[0][j].toString())){ intent = (Intent) AIParams.datas.get(i)[1][0]; isStop = true; break; } } if(isStop){ break; } } return intent; } @Override public void handleIntent(Enum e) { super.handleIntent(e); Intent intent = (Intent) e; switch (intent){ case FOOD: activity.goPoiSearchAct("美食"); break; case SCENIC_SPOT: activity.goPoiSearchAct("景点"); break; case HOTEL: activity.goPoiSearchAct("酒店"); break; case ENTERTAINMENT: activity.goPoiSearchAct("休闲娱乐"); break; case SHARING_BIKES: activity.goPoiSearchAct("共享单车"); break; case SUPERMARKET: activity.goPoiSearchAct("超市"); break; case ATM: activity.goPoiSearchAct("ATM"); break; case TOILET: activity.goPoiSearchAct("厕所"); break; case BUDGET_HOTEL: activity.goPoiSearchAct("快捷酒店"); break; case INTERNET_BAR: activity.goPoiSearchAct("网吧"); break; case METRO: activity.goPoiSearchAct("地铁"); break; case GAS_STATION: activity.goPoiSearchAct("加油站"); break; case BUS_STATION: if (TextUtils.equals(Constants.Scene.CurrentScene,"lvyou")) { activity.goPoiSearchAct("公交车站"); } break; case SHARABLE_CHARGE: if (TextUtils.equals(Constants.Scene.CurrentScene,"lvyou")) { activity.goPoiSearchAct("共享充电宝"); } break; case PARK: if (TextUtils.equals(Constants.Scene.CurrentScene,"lvyou")) { activity.goPoiSearchAct("停车场"); } break; case HOSPITAL: if (TextUtils.equals(Constants.Scene.CurrentScene,"lvyou")) { activity.goPoiSearchAct("医院"); } break; default: break; } } static class AIParams{ static final String[] FOOD = {"MEISHI","SHIWU","FANDIAN"}; static final String[] SCENIC_SPOT = {"JINGDIAN","JINGQU"}; static final String[] HOTEL = {"JIUDIAN"}; static final String[] ENTERTAINMENT = {"YULE","XIUXIAN"}; static final String[] SHARING_BIKES = {"GONGXIANGDANCHE"}; static final String[] SUPERMARKET = {"CHAOSHI","SHANGCHANG","SHANGDIAN"}; static final String[] ATM = {"ATM","QUKUANJI","QUQIAN"}; static final String[] TOILET = {"CESUO","WEISHENGJIAN"}; static final String[] BUDGET_HOTEL = {"KUAIJIEJIUDIAN"}; static final String[] INTERNET_BAR = {"WANGBA"}; static final String[] METRO = {"DITIE"}; static final String[] GAS_STATION = {"JIAYOUZHAN"}; //旅游 static final String[] BUS_STATION = {"GONGJIAOCHEZHAN"}; static final String[] SHARABLE_CHARGE = {"CHONGDIANBAO","GONGXIANGCHONGDIANBAO"}; static final String[] PARK = {"TINGCHECHANG"}; static final String[] HOSPITAL = {"YIYUAN"}; static List<Object[][]> datas; static { datas = new ArrayList<>(); datas.add(new Object[][]{FOOD,{Intent.FOOD}}); datas.add(new Object[][]{SCENIC_SPOT,{Intent.SCENIC_SPOT}}); datas.add(new Object[][]{BUDGET_HOTEL,{Intent.BUDGET_HOTEL}}); datas.add(new Object[][]{HOTEL,{Intent.HOTEL}}); datas.add(new Object[][]{ENTERTAINMENT,{Intent.ENTERTAINMENT}}); datas.add(new Object[][]{SHARING_BIKES,{Intent.SHARING_BIKES}}); datas.add(new Object[][]{SUPERMARKET,{Intent.SUPERMARKET}}); datas.add(new Object[][]{ATM,{Intent.ATM}}); datas.add(new Object[][]{TOILET,{Intent.TOILET}}); datas.add(new Object[][]{INTERNET_BAR,{Intent.INTERNET_BAR}}); datas.add(new Object[][]{METRO,{Intent.METRO}}); datas.add(new Object[][]{GAS_STATION,{Intent.GAS_STATION}}); //旅游 datas.add(new Object[][]{BUS_STATION,{Intent.BUS_STATION}}); datas.add(new Object[][]{SHARABLE_CHARGE,{Intent.SHARABLE_CHARGE}}); datas.add(new Object[][]{PARK,{Intent.PARK}}); datas.add(new Object[][]{HOSPITAL,{Intent.HOSPITAL}}); } } public enum Intent{ FOOD,SCENIC_SPOT,HOTEL ,ENTERTAINMENT,SHARING_BIKES ,SUPERMARKET,ATM,TOILET ,BUDGET_HOTEL,INTERNET_BAR,METRO,GAS_STATION ,BUS_STATION,SHARABLE_CHARGE,PARK,HOSPITAL //旅游 <SUF> } }
false
1,367
3
1,554
5
1,536
3
1,554
5
1,941
9
false
false
false
false
false
true
39793_3
package hamsteryds.nereusopus.utils.api.display.impl; import hamsteryds.nereusopus.NereusOpus; import hamsteryds.nereusopus.utils.api.ConfigUtils; import hamsteryds.nereusopus.utils.api.EnchantmentUtils; import hamsteryds.nereusopus.utils.api.MathUtils; import hamsteryds.nereusopus.utils.api.StringUtils; import hamsteryds.nereusopus.utils.api.display.DisplayAdaptor; import hamsteryds.nereusopus.utils.api.display.DisplayUtils; import org.bukkit.NamespacedKey; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; import java.util.*; public class EnchantmentDisplay extends DisplayAdaptor { public static final List<String> rarityOrder; private static final boolean levelOrder; private static final String displayFormat; private static final String combinedDisplayFormat; private static final boolean combine; private static final int combineLeast; private static final int combieAmount; private static final String combineLayout; static { ConfigurationSection config = ConfigUtils.config.getConfigurationSection("display"); levelOrder = config.getBoolean("levelorder"); rarityOrder = config.getStringList("rarityorder"); displayFormat = config.getString("format"); combinedDisplayFormat = config.getString("combine.format", displayFormat); combine = config.getBoolean("combine.enable"); combineLeast = config.getInt("combine.least"); combieAmount = config.getInt("combine.amount"); combineLayout = config.getString("combine.layout"); } private NamespacedKey hideFlag = new NamespacedKey(NereusOpus.plugin, namespace + "_hide_flag"); public EnchantmentDisplay() { super("enchant_display"); DisplayUtils.registerAdaptor(namespace, this); } public static String getLayout(List<Enchantment> enchants, LinkedHashMap<Enchantment, Integer> levelMap) { String result = combineLayout; if (enchants.size() < combieAmount) { result = result.substring(0, result.indexOf("{" + (enchants.size()) + "}") + 3); } int i = 1; for (; i <= enchants.size(); i++) { Enchantment tmp = enchants.get(i - 1); result = result.replace("{" + i + "}", getDisplay(tmp, levelMap.get(tmp), true)); } return result; } public static String getDisplay(Enchantment enchant, int level, boolean isCombined) { String tmp = isCombined ? combinedDisplayFormat : displayFormat; return StringUtils.replace(tmp, "{displayname}", EnchantmentUtils.getDisplayName(enchant), "{roman}", MathUtils.numToRoman(level, enchant.getMaxLevel() <= 1), "{level}", level, "{description}", EnchantmentUtils.getDescription(enchant), "{rarity}", EnchantmentUtils.getRarity(enchant).displayName()); } public static LinkedHashMap<Enchantment, Integer> sortEnchants(Map<Enchantment, Integer> enchants) { List<Enchantment> sorted = new ArrayList<>(); LinkedHashMap<Enchantment, Integer> result = new LinkedHashMap<>(); for (Enchantment enchant : enchants.keySet()) { if (EnchantmentUtils.getRarity(enchant) == null) { continue; } sorted.add(enchant); } sorted.sort(Comparator.comparing((Enchantment enchant) -> { if (levelOrder) { return rarityOrder.indexOf(EnchantmentUtils.getRarity(enchant).id()) * 100000 + enchants.get(enchant); } else { return rarityOrder.indexOf(EnchantmentUtils.getRarity(enchant).id()) * 100000 - enchants.get(enchant); } })); for (Enchantment enchant : sorted) { result.put(enchant, enchants.get(enchant)); } return result; } @Override public ItemStack revert(ItemStack item) { ItemStack result = item.clone(); ItemMeta meta = item.getItemMeta(); PersistentDataContainer pdc = meta.getPersistentDataContainer(); if (pdc.has(loreKey_1, PersistentDataType.INTEGER)) { List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); String startLine = pdc.get(loreKey_1, PersistentDataType.STRING); String endLine = pdc.get(loreKey_2, PersistentDataType.STRING); int startIndex = lore.indexOf(startLine); int endIndex = lore.indexOf(endLine); for (int i = 0; i <= endIndex - startIndex; i++) { lore.remove(startIndex); } meta.setLore(lore); pdc.remove(loreKey_1); pdc.remove(loreKey_2); } if (pdc.has(hideFlag, PersistentDataType.INTEGER)) { boolean hasFlag = pdc.get(hideFlag, PersistentDataType.INTEGER) == 1; if (!hasFlag) { if (meta instanceof EnchantmentStorageMeta) { meta.removeItemFlags(ItemFlag.HIDE_POTION_EFFECTS); } meta.removeItemFlags(ItemFlag.HIDE_ENCHANTS); } pdc.remove(hideFlag); } if (pdc.has(dataKey, PersistentDataType.STRING) && meta instanceof EnchantmentStorageMeta bookMeta) { String enchants = pdc.get(dataKey, PersistentDataType.STRING); for (String string : enchants.split("@")) { String[] enchantInfo = string.split(","); if (enchantInfo.length <= 0) { continue; } NamespacedKey key = NamespacedKey.fromString(enchantInfo[0]); int level = Integer.parseInt(enchantInfo[1]); Enchantment enchant = Enchantment.getByKey(key); if (enchant != null) { bookMeta.addStoredEnchant(enchant, level, true); } } pdc.remove(dataKey); } item.setItemMeta(meta); return result; } @Override public ItemStack adapt(ItemStack item) { ItemStack result = item.clone(); ItemMeta meta = item.getItemMeta(); Map<Enchantment, Integer> enchants; PersistentDataContainer pdc = meta.getPersistentDataContainer(); // //TODO 防止二次生成lore,赘余代码,待测试是否必要 // if (pdc.has(loreKey_1, PersistentDataType.STRING)) { // return item; // } if (meta instanceof EnchantmentStorageMeta enchantMeta) { pdc.set(hideFlag, PersistentDataType.INTEGER, meta.hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS) ? 1 : 0); meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); enchants = enchantMeta.getStoredEnchants(); } else { pdc.set(hideFlag, PersistentDataType.INTEGER, meta.hasItemFlag(ItemFlag.HIDE_ENCHANTS) ? 1 : 0); meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); enchants = meta.getEnchants(); } if (enchants.size() > 0) { List<String> enchantLore = new ArrayList<>(); LinkedHashMap<Enchantment, Integer> sorted = sortEnchants(enchants); List<Enchantment> stack = new ArrayList<>(); //合并附魔显示,狗屎代码 if (combine && sorted.size() >= combineLeast) { for (Enchantment enchant : sorted.keySet()) { if (stack.size() < combieAmount) { stack.add(enchant); } else { enchantLore.add(getLayout(stack, sorted)); stack.clear(); stack.add(enchant); } } if (stack.size() != 0) { enchantLore.add(getLayout(stack, sorted)); stack.clear(); } } else { for (Enchantment enchant : sorted.keySet()) { enchantLore.add(getDisplay(enchant, sorted.get(enchant), false)); } } //TODO 对创造模式下附魔书的特殊处理,以便于在恢复物品时重新附魔(防止创造模式附魔书重置问题),暂时未测试1.18+还需不需要 if (meta instanceof EnchantmentStorageMeta) { StringBuilder text = new StringBuilder(); for (Enchantment enchant : sorted.keySet()) { text.append(enchant.getKey().asString()) .append(",").append(sorted.get(enchant)).append("@"); } pdc.set(dataKey, PersistentDataType.STRING, text.toString()); } List<String> resultLore = new ArrayList<>(); enchantLore.forEach((String line) -> Collections.addAll(resultLore, line.split("/n"))); resultLore.addAll(meta.hasLore() ? meta.getLore() : new ArrayList<>()); //TODO 开头行和结尾行标记,应该调查客户端是否会影响标记行中的颜色代码 if (resultLore.size() > 0) { pdc.set(loreKey_1, PersistentDataType.STRING, resultLore.get(0)); pdc.set(loreKey_2, PersistentDataType.STRING, resultLore.get(resultLore.size() - 1)); } meta.setLore(resultLore); } result.setItemMeta(meta); return result; } }
Micalhl/NereusOpusBase
src/main/java/hamsteryds/nereusopus/utils/api/display/impl/EnchantmentDisplay.java
2,408
//合并附魔显示,狗屎代码
line_comment
zh-cn
package hamsteryds.nereusopus.utils.api.display.impl; import hamsteryds.nereusopus.NereusOpus; import hamsteryds.nereusopus.utils.api.ConfigUtils; import hamsteryds.nereusopus.utils.api.EnchantmentUtils; import hamsteryds.nereusopus.utils.api.MathUtils; import hamsteryds.nereusopus.utils.api.StringUtils; import hamsteryds.nereusopus.utils.api.display.DisplayAdaptor; import hamsteryds.nereusopus.utils.api.display.DisplayUtils; import org.bukkit.NamespacedKey; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.EnchantmentStorageMeta; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.persistence.PersistentDataContainer; import org.bukkit.persistence.PersistentDataType; import java.util.*; public class EnchantmentDisplay extends DisplayAdaptor { public static final List<String> rarityOrder; private static final boolean levelOrder; private static final String displayFormat; private static final String combinedDisplayFormat; private static final boolean combine; private static final int combineLeast; private static final int combieAmount; private static final String combineLayout; static { ConfigurationSection config = ConfigUtils.config.getConfigurationSection("display"); levelOrder = config.getBoolean("levelorder"); rarityOrder = config.getStringList("rarityorder"); displayFormat = config.getString("format"); combinedDisplayFormat = config.getString("combine.format", displayFormat); combine = config.getBoolean("combine.enable"); combineLeast = config.getInt("combine.least"); combieAmount = config.getInt("combine.amount"); combineLayout = config.getString("combine.layout"); } private NamespacedKey hideFlag = new NamespacedKey(NereusOpus.plugin, namespace + "_hide_flag"); public EnchantmentDisplay() { super("enchant_display"); DisplayUtils.registerAdaptor(namespace, this); } public static String getLayout(List<Enchantment> enchants, LinkedHashMap<Enchantment, Integer> levelMap) { String result = combineLayout; if (enchants.size() < combieAmount) { result = result.substring(0, result.indexOf("{" + (enchants.size()) + "}") + 3); } int i = 1; for (; i <= enchants.size(); i++) { Enchantment tmp = enchants.get(i - 1); result = result.replace("{" + i + "}", getDisplay(tmp, levelMap.get(tmp), true)); } return result; } public static String getDisplay(Enchantment enchant, int level, boolean isCombined) { String tmp = isCombined ? combinedDisplayFormat : displayFormat; return StringUtils.replace(tmp, "{displayname}", EnchantmentUtils.getDisplayName(enchant), "{roman}", MathUtils.numToRoman(level, enchant.getMaxLevel() <= 1), "{level}", level, "{description}", EnchantmentUtils.getDescription(enchant), "{rarity}", EnchantmentUtils.getRarity(enchant).displayName()); } public static LinkedHashMap<Enchantment, Integer> sortEnchants(Map<Enchantment, Integer> enchants) { List<Enchantment> sorted = new ArrayList<>(); LinkedHashMap<Enchantment, Integer> result = new LinkedHashMap<>(); for (Enchantment enchant : enchants.keySet()) { if (EnchantmentUtils.getRarity(enchant) == null) { continue; } sorted.add(enchant); } sorted.sort(Comparator.comparing((Enchantment enchant) -> { if (levelOrder) { return rarityOrder.indexOf(EnchantmentUtils.getRarity(enchant).id()) * 100000 + enchants.get(enchant); } else { return rarityOrder.indexOf(EnchantmentUtils.getRarity(enchant).id()) * 100000 - enchants.get(enchant); } })); for (Enchantment enchant : sorted) { result.put(enchant, enchants.get(enchant)); } return result; } @Override public ItemStack revert(ItemStack item) { ItemStack result = item.clone(); ItemMeta meta = item.getItemMeta(); PersistentDataContainer pdc = meta.getPersistentDataContainer(); if (pdc.has(loreKey_1, PersistentDataType.INTEGER)) { List<String> lore = meta.hasLore() ? meta.getLore() : new ArrayList<>(); String startLine = pdc.get(loreKey_1, PersistentDataType.STRING); String endLine = pdc.get(loreKey_2, PersistentDataType.STRING); int startIndex = lore.indexOf(startLine); int endIndex = lore.indexOf(endLine); for (int i = 0; i <= endIndex - startIndex; i++) { lore.remove(startIndex); } meta.setLore(lore); pdc.remove(loreKey_1); pdc.remove(loreKey_2); } if (pdc.has(hideFlag, PersistentDataType.INTEGER)) { boolean hasFlag = pdc.get(hideFlag, PersistentDataType.INTEGER) == 1; if (!hasFlag) { if (meta instanceof EnchantmentStorageMeta) { meta.removeItemFlags(ItemFlag.HIDE_POTION_EFFECTS); } meta.removeItemFlags(ItemFlag.HIDE_ENCHANTS); } pdc.remove(hideFlag); } if (pdc.has(dataKey, PersistentDataType.STRING) && meta instanceof EnchantmentStorageMeta bookMeta) { String enchants = pdc.get(dataKey, PersistentDataType.STRING); for (String string : enchants.split("@")) { String[] enchantInfo = string.split(","); if (enchantInfo.length <= 0) { continue; } NamespacedKey key = NamespacedKey.fromString(enchantInfo[0]); int level = Integer.parseInt(enchantInfo[1]); Enchantment enchant = Enchantment.getByKey(key); if (enchant != null) { bookMeta.addStoredEnchant(enchant, level, true); } } pdc.remove(dataKey); } item.setItemMeta(meta); return result; } @Override public ItemStack adapt(ItemStack item) { ItemStack result = item.clone(); ItemMeta meta = item.getItemMeta(); Map<Enchantment, Integer> enchants; PersistentDataContainer pdc = meta.getPersistentDataContainer(); // //TODO 防止二次生成lore,赘余代码,待测试是否必要 // if (pdc.has(loreKey_1, PersistentDataType.STRING)) { // return item; // } if (meta instanceof EnchantmentStorageMeta enchantMeta) { pdc.set(hideFlag, PersistentDataType.INTEGER, meta.hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS) ? 1 : 0); meta.addItemFlags(ItemFlag.HIDE_POTION_EFFECTS); meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); enchants = enchantMeta.getStoredEnchants(); } else { pdc.set(hideFlag, PersistentDataType.INTEGER, meta.hasItemFlag(ItemFlag.HIDE_ENCHANTS) ? 1 : 0); meta.addItemFlags(ItemFlag.HIDE_ENCHANTS); enchants = meta.getEnchants(); } if (enchants.size() > 0) { List<String> enchantLore = new ArrayList<>(); LinkedHashMap<Enchantment, Integer> sorted = sortEnchants(enchants); List<Enchantment> stack = new ArrayList<>(); //合并 <SUF> if (combine && sorted.size() >= combineLeast) { for (Enchantment enchant : sorted.keySet()) { if (stack.size() < combieAmount) { stack.add(enchant); } else { enchantLore.add(getLayout(stack, sorted)); stack.clear(); stack.add(enchant); } } if (stack.size() != 0) { enchantLore.add(getLayout(stack, sorted)); stack.clear(); } } else { for (Enchantment enchant : sorted.keySet()) { enchantLore.add(getDisplay(enchant, sorted.get(enchant), false)); } } //TODO 对创造模式下附魔书的特殊处理,以便于在恢复物品时重新附魔(防止创造模式附魔书重置问题),暂时未测试1.18+还需不需要 if (meta instanceof EnchantmentStorageMeta) { StringBuilder text = new StringBuilder(); for (Enchantment enchant : sorted.keySet()) { text.append(enchant.getKey().asString()) .append(",").append(sorted.get(enchant)).append("@"); } pdc.set(dataKey, PersistentDataType.STRING, text.toString()); } List<String> resultLore = new ArrayList<>(); enchantLore.forEach((String line) -> Collections.addAll(resultLore, line.split("/n"))); resultLore.addAll(meta.hasLore() ? meta.getLore() : new ArrayList<>()); //TODO 开头行和结尾行标记,应该调查客户端是否会影响标记行中的颜色代码 if (resultLore.size() > 0) { pdc.set(loreKey_1, PersistentDataType.STRING, resultLore.get(0)); pdc.set(loreKey_2, PersistentDataType.STRING, resultLore.get(resultLore.size() - 1)); } meta.setLore(resultLore); } result.setItemMeta(meta); return result; } }
false
2,025
9
2,408
12
2,435
9
2,408
12
2,878
18
false
false
false
false
false
true
23688_3
package com.michael.BaseExcercise; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /* 试题 基础练习 完美的代价 资源限制 时间限制:1.0s 内存限制:512.0MB 问题描述   回文串,是一种特殊的字符串,它从左往右读和从右往左读是一样的。小龙龙认为回文串才是完美的。现在给你一个串,它不一定是回文的,请你计算最少的交换次数使得该串变成一个完美的回文串。   (*)交换的定义是:交换两个相邻的字符(*)   例如mamad   第一次交换 ad : mamda   第二次交换 md : madma   第三次交换 ma : madam (回文!完美!) 输入格式   第一行是一个整数N,表示接下来的字符串的长度(N <= 8000)   第二行是一个字符串,长度为N.只包含小写字母 输出格式   如果可能,输出最少的交换次数。   否则输出Impossible 样例输入 5 mamad 样例输出 3 */ /* https://blog.csdn.net/qq_40605470/article/details/79268979 https://blog.csdn.net/u011506951/article/details/26382569 首先先明确Impossible的情况: 一:长度为奇数的情况,如果字符串中存在不止一个字符的出现次数为1 二:长度为偶数的情况,如果字符串中存在出现次数为一次的字符 要知道这道题要求的只是最少的交换次数,而不是求出交换后的回文串,所以我们可以模拟交换的过程。 假设第一个字符是正确的,那么从后往前找与这个字符一致的,将它交换至尾部,此时n–1 (因为接下来的判断已经不涉及最后一个字符了) 以此类推。 比如:mamad 第一次:maadm 找到与m相同的放在最后面 2次交换 长度减1,此时的最后是d 第二次:madam 找到与a相同的放在最后面 1次交换 总共3次 */ public class PerfectCost_19 { private static int count=0; private static char[] ch; public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); ch=new char[n]; String str=sc.next(); ch=str.toCharArray(); sc.close(); //1、首先先明确Impossible的情况 HashMap<Character, Integer> m=new HashMap<>(); for (int i = 0; i < n; i++) { Integer temp = m.get(ch[i]); if (temp == null) { m.put(ch[i], 1); } else { m.put(ch[i], temp+1); } } int len=0; for(Map.Entry<Character, Integer> entry:m.entrySet()){ if(entry.getValue()==1){ len++; } } if (n % 2 != 0) { if(len>1){ System.out.println("Impossible"); return; } } else { if(len>0){ System.out.println("Impossible"); return; } } //2、假设第一个字符是正确的,那么从后往前找与这个字符一致的,将它交换至尾部,此时n–1 (因为接下来的判断已经不涉及最后一个字符了)以此类推。 // change(ch); change2(ch); System.out.println(Arrays.toString(ch)); System.out.println(count); } static void change(char[] ch){ int left=0; int mid=(ch.length-1)/2; int right=ch.length-1; int i; boolean flag=true; while(left<mid){ flag=true; if(ch[left]!=ch[right]){ //如果是相等的就没有必要交换 i=left+1; while(ch[left]!=ch[i]){ //一直向右边搜索,直到扎到 ch[left]==ch[i] i++;//一直要找到right所指的位置 if(i>right){ //如果i==right 还能进入循环说明当前所指的left是奇数的,或者单次,就先把他的位置记录下,让lef向后走一步 adjust(left, mid); flag=false; if(check(ch)){ return; } break; } } if(i<right){ adjust(i, right);//需要交换 } if(check(ch)){ return; } } if(flag){ left++; right--; } } } static boolean check(char[] ch){ //每次调整之后判断下是否是回文串了 for(int i=0,j=ch.length-1;i<ch.length;i++,j--){ if(ch[i]!=ch[j]){ return false; } } return true; } static void adjust(int start,int end){ char temp;//保存临时值 for(int j=start;j<end;j++){ //需要交换 temp=ch[j]; ch[j]=ch[j+1]; ch[j+1]=temp; count++;//交换次数加1 } } static void change2(char[] ch){ int left=0; int mid=(ch.length-1)/2; int right=ch.length-1; int i; int odd=-1; boolean flag=true; while(left<mid){ flag=true; if(ch[left]!=ch[right]){ //如果是相等的就没有必要交换 i=left+1; while(ch[left]!=ch[i]){ //一直向右边搜索,直到扎到 ch[left]==ch[i] i++;//一直要找到right所指的位置 if(i>right){ //如果i==right 还能进入循环说明当前所指的left是奇数的,或者单次,就先把他的位置记录下,让left向后走一步 odd=left; left++; flag=false; if(check(ch)){ return; } break; } } if(i<right){ adjust(i, right);//需要交换 } if(check(ch)){ return; } } if(flag){ left++; right--; } } if(odd!=-1){ adjust(odd, mid); } } }
Michael-linghuchong/BlueBridge
src/com/michael/BaseExcercise/PerfectCost_19.java
1,865
//2、假设第一个字符是正确的,那么从后往前找与这个字符一致的,将它交换至尾部,此时n–1 (因为接下来的判断已经不涉及最后一个字符了)以此类推。
line_comment
zh-cn
package com.michael.BaseExcercise; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Scanner; /* 试题 基础练习 完美的代价 资源限制 时间限制:1.0s 内存限制:512.0MB 问题描述   回文串,是一种特殊的字符串,它从左往右读和从右往左读是一样的。小龙龙认为回文串才是完美的。现在给你一个串,它不一定是回文的,请你计算最少的交换次数使得该串变成一个完美的回文串。   (*)交换的定义是:交换两个相邻的字符(*)   例如mamad   第一次交换 ad : mamda   第二次交换 md : madma   第三次交换 ma : madam (回文!完美!) 输入格式   第一行是一个整数N,表示接下来的字符串的长度(N <= 8000)   第二行是一个字符串,长度为N.只包含小写字母 输出格式   如果可能,输出最少的交换次数。   否则输出Impossible 样例输入 5 mamad 样例输出 3 */ /* https://blog.csdn.net/qq_40605470/article/details/79268979 https://blog.csdn.net/u011506951/article/details/26382569 首先先明确Impossible的情况: 一:长度为奇数的情况,如果字符串中存在不止一个字符的出现次数为1 二:长度为偶数的情况,如果字符串中存在出现次数为一次的字符 要知道这道题要求的只是最少的交换次数,而不是求出交换后的回文串,所以我们可以模拟交换的过程。 假设第一个字符是正确的,那么从后往前找与这个字符一致的,将它交换至尾部,此时n–1 (因为接下来的判断已经不涉及最后一个字符了) 以此类推。 比如:mamad 第一次:maadm 找到与m相同的放在最后面 2次交换 长度减1,此时的最后是d 第二次:madam 找到与a相同的放在最后面 1次交换 总共3次 */ public class PerfectCost_19 { private static int count=0; private static char[] ch; public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); ch=new char[n]; String str=sc.next(); ch=str.toCharArray(); sc.close(); //1、首先先明确Impossible的情况 HashMap<Character, Integer> m=new HashMap<>(); for (int i = 0; i < n; i++) { Integer temp = m.get(ch[i]); if (temp == null) { m.put(ch[i], 1); } else { m.put(ch[i], temp+1); } } int len=0; for(Map.Entry<Character, Integer> entry:m.entrySet()){ if(entry.getValue()==1){ len++; } } if (n % 2 != 0) { if(len>1){ System.out.println("Impossible"); return; } } else { if(len>0){ System.out.println("Impossible"); return; } } //2、 <SUF> // change(ch); change2(ch); System.out.println(Arrays.toString(ch)); System.out.println(count); } static void change(char[] ch){ int left=0; int mid=(ch.length-1)/2; int right=ch.length-1; int i; boolean flag=true; while(left<mid){ flag=true; if(ch[left]!=ch[right]){ //如果是相等的就没有必要交换 i=left+1; while(ch[left]!=ch[i]){ //一直向右边搜索,直到扎到 ch[left]==ch[i] i++;//一直要找到right所指的位置 if(i>right){ //如果i==right 还能进入循环说明当前所指的left是奇数的,或者单次,就先把他的位置记录下,让lef向后走一步 adjust(left, mid); flag=false; if(check(ch)){ return; } break; } } if(i<right){ adjust(i, right);//需要交换 } if(check(ch)){ return; } } if(flag){ left++; right--; } } } static boolean check(char[] ch){ //每次调整之后判断下是否是回文串了 for(int i=0,j=ch.length-1;i<ch.length;i++,j--){ if(ch[i]!=ch[j]){ return false; } } return true; } static void adjust(int start,int end){ char temp;//保存临时值 for(int j=start;j<end;j++){ //需要交换 temp=ch[j]; ch[j]=ch[j+1]; ch[j+1]=temp; count++;//交换次数加1 } } static void change2(char[] ch){ int left=0; int mid=(ch.length-1)/2; int right=ch.length-1; int i; int odd=-1; boolean flag=true; while(left<mid){ flag=true; if(ch[left]!=ch[right]){ //如果是相等的就没有必要交换 i=left+1; while(ch[left]!=ch[i]){ //一直向右边搜索,直到扎到 ch[left]==ch[i] i++;//一直要找到right所指的位置 if(i>right){ //如果i==right 还能进入循环说明当前所指的left是奇数的,或者单次,就先把他的位置记录下,让left向后走一步 odd=left; left++; flag=false; if(check(ch)){ return; } break; } } if(i<right){ adjust(i, right);//需要交换 } if(check(ch)){ return; } } if(flag){ left++; right--; } } if(odd!=-1){ adjust(odd, mid); } } }
false
1,494
47
1,820
58
1,747
47
1,820
58
2,610
88
false
false
false
false
false
true
46346_3
package com.oa.model; /** * 用户角色 */ import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="oa_acl") public class Acl implements Serializable{ /** * */ private static final long serialVersionUID = -7012078162997556118L; private Integer id; /** * 主要类型 */ private String principalType; /** * 角色id */ private Role principalId; /** * 模块ID */ private Module moduleId; /** * 增删查改 分别对应 1 2 4 8 表示某个模块的权限操作 */ private Integer aclState; /** * 这个字段暂时没有用到 * */ private Integer alcTriState; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPrincipalType() { return principalType; } public void setPrincipalType(String principalType) { this.principalType = principalType; } @ManyToOne @JoinColumn(name="moduleId", referencedColumnName = "id") public Module getModuleId() { return moduleId; } public void setModuleId(Module moduleId) { this.moduleId = moduleId; } public Integer getAclState() { return aclState; } public void setAclState(Integer aclState) { this.aclState = aclState; } public Integer getAlcTriState() { return alcTriState; } public void setAlcTriState(Integer alcTriState) { this.alcTriState = alcTriState; } @ManyToOne @JoinColumn(name="principalId", referencedColumnName = "id") public Role getPrincipalId() { return principalId; } public void setPrincipalId(Role principalId) { this.principalId = principalId; } }
Micheal-Bigmac/OA
src/com/oa/model/Acl.java
569
/** * 模块ID */
block_comment
zh-cn
package com.oa.model; /** * 用户角色 */ import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="oa_acl") public class Acl implements Serializable{ /** * */ private static final long serialVersionUID = -7012078162997556118L; private Integer id; /** * 主要类型 */ private String principalType; /** * 角色id */ private Role principalId; /** * 模块I <SUF>*/ private Module moduleId; /** * 增删查改 分别对应 1 2 4 8 表示某个模块的权限操作 */ private Integer aclState; /** * 这个字段暂时没有用到 * */ private Integer alcTriState; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPrincipalType() { return principalType; } public void setPrincipalType(String principalType) { this.principalType = principalType; } @ManyToOne @JoinColumn(name="moduleId", referencedColumnName = "id") public Module getModuleId() { return moduleId; } public void setModuleId(Module moduleId) { this.moduleId = moduleId; } public Integer getAclState() { return aclState; } public void setAclState(Integer aclState) { this.aclState = aclState; } public Integer getAlcTriState() { return alcTriState; } public void setAlcTriState(Integer alcTriState) { this.alcTriState = alcTriState; } @ManyToOne @JoinColumn(name="principalId", referencedColumnName = "id") public Role getPrincipalId() { return principalId; } public void setPrincipalId(Role principalId) { this.principalId = principalId; } }
false
451
10
569
8
570
10
569
8
663
13
false
false
false
false
false
true
36332_3
//牛客网 JZ13 机器人的运动范围 //import java.util.*; // //public class Solution { // //计算每一位的数字之和 // public int cal(int n) { // int sum = 0; // while (n != 0) { // sum += (n % 10); // n /= 10; // } // return sum; // } // // //答案 // public int res = 0; // // public int movingCount(int threshold, int rows, int cols) { // if (threshold <= 0) { // return 1; // } // boolean[][] flg = new boolean[rows][cols]; // dfs(threshold, 0, 0, rows, cols, flg); // return res; // } // // public void dfs(int threshold, int i, int j, int rows, int cols, // boolean[][] flg) { // //越界 // if (i < 0 || i >= rows || j < 0 || j >= cols || flg[i][j] == true) { // return; // } // //大于 // if (cal(i) + cal(j) > threshold) { // return; // } // res += 1; // flg[i][j] = true; // //上下左右四个方向走 // dfs(threshold, i + 1, j, rows, cols, flg); // dfs(threshold, i - 1, j, rows, cols, flg); // dfs(threshold, i, j + 1, rows, cols, flg); // dfs(threshold, i, j - 1, rows, cols, flg); // } //}
Mikammm3/Java
exercise_2023_9_9.java
495
// //计算每一位的数字之和
line_comment
zh-cn
//牛客网 JZ13 机器人的运动范围 //import java.util.*; // //public class Solution { // //计算 <SUF> // public int cal(int n) { // int sum = 0; // while (n != 0) { // sum += (n % 10); // n /= 10; // } // return sum; // } // // //答案 // public int res = 0; // // public int movingCount(int threshold, int rows, int cols) { // if (threshold <= 0) { // return 1; // } // boolean[][] flg = new boolean[rows][cols]; // dfs(threshold, 0, 0, rows, cols, flg); // return res; // } // // public void dfs(int threshold, int i, int j, int rows, int cols, // boolean[][] flg) { // //越界 // if (i < 0 || i >= rows || j < 0 || j >= cols || flg[i][j] == true) { // return; // } // //大于 // if (cal(i) + cal(j) > threshold) { // return; // } // res += 1; // flg[i][j] = true; // //上下左右四个方向走 // dfs(threshold, i + 1, j, rows, cols, flg); // dfs(threshold, i - 1, j, rows, cols, flg); // dfs(threshold, i, j + 1, rows, cols, flg); // dfs(threshold, i, j - 1, rows, cols, flg); // } //}
false
398
10
450
12
442
11
450
12
487
14
false
false
false
false
false
true
15025_7
package com.example.pad; import android.util.Log; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import java.util.ArrayList; public class StartViewModel extends ViewModel { // 常数 private int DELTA = 70; // 和目标值小于10cm都算正确 // 前端绑定 private MutableLiveData<Integer> curDistance = new MutableLiveData<>(); // 当前距离 // public void setCurDistance(int curDistance){ Log.v("MikeDean","设置:"+String.valueOf(curDistance));this.curDistance.setValue(curDistance); } public MutableLiveData<Integer> getCurDistance(){ return curDistance; } private MutableLiveData<Integer> settingDistance = new MutableLiveData<>(); // 选择的距离 public void setSettingDistance(int settingDistance){ this.settingDistance.setValue(settingDistance); } public MutableLiveData<Integer> getSettingDistance(){ return settingDistance; } // Constructor public StartViewModel(){ curDistance.setValue(0); settingDistance.setValue(0); } // 当前位于第几个 private int curStage = 0; // 测试距离 private int distance = 0; // 眼睛 0-左眼 1-右眼 private int eyes = 0; // 传过来的参数 private int preDirection = -1; // 前一个时刻的手势方向 private int preNum = -1; // 前一个时刻的数字 private int curDirection = -1; // 当前时刻的方向 private int curNum = -1; // 当前时刻的数字 private int keepCnt = 0; // 持续个数 // 设置 public void nextStage(){ curStage++; } public void setDistance(int Distance){ this.distance = Distance; } public void setEyes(int Eyes){ this.eyes = Eyes; } private int cur_distance; public void setCurDistance(int CurDistance) { Log.v("MikeDean","设置:"+String.valueOf(CurDistance)); cur_distance = CurDistance; } public void updateDirection(int Direction){ this.preDirection = this.curDirection; this.curDirection = Direction; } public void updateNum(int Num){ this.preNum = this.curNum; this.curNum = Num; } // 判断是否和前一个一样 public void resetKeep(){ keepCnt = 0; } public boolean ifKeep(String type){ if (type.equals("direction")){ if (preDirection==-1) { keepCnt = 0; return false; } if (this.preDirection == this.curDirection){ keepCnt++; return true; }else{ keepCnt = 0; return false; } }else if(type.equals("num")){ if (preNum==-1){ keepCnt = 0; return false; } if (this.preNum == this.curNum){ keepCnt++; return true; }else{ keepCnt=0; return false; } }else{ curDistance.setValue(cur_distance); // 距离是否符合要求 if (Math.abs(curDistance.getValue()-settingDistance.getValue())<=DELTA){ keepCnt++; return true; }else{ keepCnt = 0; return false; } } } // 获取 public int getCurStage(){ return curStage; } public int getEyes(){ return eyes; } public int getDistance(){ return distance; } public int getKeepCnt(){ return keepCnt; } }
MikeDean2367/AI-EYE
pad/app/src/main/java/com/example/pad/StartViewModel.java
856
// 当前位于第几个
line_comment
zh-cn
package com.example.pad; import android.util.Log; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import java.util.ArrayList; public class StartViewModel extends ViewModel { // 常数 private int DELTA = 70; // 和目标值小于10cm都算正确 // 前端绑定 private MutableLiveData<Integer> curDistance = new MutableLiveData<>(); // 当前距离 // public void setCurDistance(int curDistance){ Log.v("MikeDean","设置:"+String.valueOf(curDistance));this.curDistance.setValue(curDistance); } public MutableLiveData<Integer> getCurDistance(){ return curDistance; } private MutableLiveData<Integer> settingDistance = new MutableLiveData<>(); // 选择的距离 public void setSettingDistance(int settingDistance){ this.settingDistance.setValue(settingDistance); } public MutableLiveData<Integer> getSettingDistance(){ return settingDistance; } // Constructor public StartViewModel(){ curDistance.setValue(0); settingDistance.setValue(0); } // 当前 <SUF> private int curStage = 0; // 测试距离 private int distance = 0; // 眼睛 0-左眼 1-右眼 private int eyes = 0; // 传过来的参数 private int preDirection = -1; // 前一个时刻的手势方向 private int preNum = -1; // 前一个时刻的数字 private int curDirection = -1; // 当前时刻的方向 private int curNum = -1; // 当前时刻的数字 private int keepCnt = 0; // 持续个数 // 设置 public void nextStage(){ curStage++; } public void setDistance(int Distance){ this.distance = Distance; } public void setEyes(int Eyes){ this.eyes = Eyes; } private int cur_distance; public void setCurDistance(int CurDistance) { Log.v("MikeDean","设置:"+String.valueOf(CurDistance)); cur_distance = CurDistance; } public void updateDirection(int Direction){ this.preDirection = this.curDirection; this.curDirection = Direction; } public void updateNum(int Num){ this.preNum = this.curNum; this.curNum = Num; } // 判断是否和前一个一样 public void resetKeep(){ keepCnt = 0; } public boolean ifKeep(String type){ if (type.equals("direction")){ if (preDirection==-1) { keepCnt = 0; return false; } if (this.preDirection == this.curDirection){ keepCnt++; return true; }else{ keepCnt = 0; return false; } }else if(type.equals("num")){ if (preNum==-1){ keepCnt = 0; return false; } if (this.preNum == this.curNum){ keepCnt++; return true; }else{ keepCnt=0; return false; } }else{ curDistance.setValue(cur_distance); // 距离是否符合要求 if (Math.abs(curDistance.getValue()-settingDistance.getValue())<=DELTA){ keepCnt++; return true; }else{ keepCnt = 0; return false; } } } // 获取 public int getCurStage(){ return curStage; } public int getEyes(){ return eyes; } public int getDistance(){ return distance; } public int getKeepCnt(){ return keepCnt; } }
false
795
7
854
7
912
6
854
7
1,102
12
false
false
false
false
false
true
17225_15
package cn.mikulink.rabbitbot.utils; import cn.mikulink.rabbitbot.constant.ConstantImage; import cn.mikulink.rabbitbot.entity.ImageInfo; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.io.*; import java.net.HttpURLConnection; import java.net.Proxy; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * create by MikuLink on 2019/12/12 17:38 * for the Reisen * 图片 */ public class ImageUtil { private static final List<String> IMAGE_SUFFIXS = Arrays.asList(".jpg", ".jpeg", ".gif", ".png"); /** * 下载图片到本地 * * @param imageUrl 网络图片url * @return 图片名称 */ public static String downloadImage(String imageUrl) throws IOException { return downloadImage(imageUrl, ConstantImage.DEFAULT_IMAGE_SAVE_PATH, null); } /** * 下载图片到本地 * * @param imageUrl 网络图片url * @param localUrl 本地储存地址 * @param fileName 文件名称,带后缀的那种,如果为空则取链接最后一段作为文件名 * @return 图片路径 */ public static String downloadImage(String imageUrl, String localUrl, String fileName) throws IOException { return downloadImage(null, imageUrl, localUrl, fileName); } /** * 下载图片到本地 * * @param header http请求header * @param imageUrl 网络图片url * @param localUrl 本地储存地址 * @param fileName 文件名称,带后缀的那种,如果为空则取链接最后一段作为文件名 * @return 本地图片相对路径 * @throws IOException 异常 */ public static String downloadImage(HashMap<String, String> header, String imageUrl, String localUrl, String fileName) throws IOException { return downloadImage(header, imageUrl, localUrl, fileName, null); } /** * 下载图片到本地 * * @param header http请求header * @param imageUrl 网络图片url * @param localUrl 本地储存地址 * @param fileName 文件名称,带后缀的那种,如果为空则取链接最后一段作为文件名 * @param proxy 代理 * @return 本地图片相对路径 * @throws IOException 异常 */ public static String downloadImage(HashMap<String, String> header, String imageUrl, String localUrl, String fileName, Proxy proxy) throws IOException { if (StringUtil.isEmpty(imageUrl)) { throw new IOException("网络图片链接为空"); } //类型根据创建连接 HttpURLConnection conn = null; if (imageUrl.startsWith("https")) { conn = HttpsUtil.getHttpsURLConnection(imageUrl, HttpUtil.REQUEST_METHOD_GET, header, proxy); } else { conn = HttpUtil.getHttpURLConnection(imageUrl, HttpUtil.REQUEST_METHOD_GET, proxy); } //设置链接超时时间 // conn.setConnectTimeout(5 * 1000); //请求header if (null != header) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } //获取输出流 InputStream inStream = conn.getInputStream(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); //把图片信息存下来,写入内存 byte[] data = outStream.toByteArray(); //使用网络图片的中段目录 // String path = imageUrl.substring(imageUrl.indexOf("n/") + 1, imageUrl.lastIndexOf("/")); //创建本地文件 File result = new File(localUrl); if (!result.exists()) { result.mkdirs(); } //如果为空,使用网络图片的名称和后缀 if (StringUtil.isEmpty(fileName)) { fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1); } //写入图片数据 String fileFullName = result + File.separator + fileName; FileOutputStream fileOutputStream = new FileOutputStream(fileFullName); fileOutputStream.write(data); fileOutputStream.flush(); fileOutputStream.close(); //返回文件路径 return fileFullName; } /** * 判断文件是否存在 * * @param imageUrl 文件路径 * @return 是否存在 */ public static boolean isExists(String imageUrl) { if (StringUtil.isEmpty(imageUrl)) { return false; } //创建本地文件 File result = new File(imageUrl); return result.exists(); } /** * 是否为图片文件 * * @param fileName 文件名称 * @return 是否为图片 */ public static boolean isImage(String fileName) { String suffix = FileUtil.getFileSuffix(fileName); if (StringUtil.isEmpty(suffix)) { return false; } return IMAGE_SUFFIXS.contains(suffix); } /** * 获取本地图片信息 * * @param imagePath 图片文件路径 * @return 图片信息 */ public static ImageInfo getImageInfo(String imagePath) throws IOException { //这个方法太慢了 // BufferedImage sourceImg = ImageIO.read(new FileInputStream(new File(imagePath))); // sourceImg.getWidth(); // sourceImg.getHeight(); //没研究透,复制来的代码,但比上面的快多了 //获取图片后缀,不要"." String imgType = FileUtil.getFileSuffix(imagePath).replace(".", ""); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imgType.toLowerCase()); ImageReader reader = readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(new File(imagePath)); reader.setInput(iis, true); int width = reader.getWidth(0); int height = reader.getHeight(0); ImageInfo imageInfo = new ImageInfo(); imageInfo.setLocalPath(imagePath); imageInfo.setWidth(width); imageInfo.setHeight(height); imageInfo.setType(imgType); imageInfo.setSize(new File(imagePath).length()); return imageInfo; } }
MikuNyanya/RabbitBot_RE
src/main/java/cn/mikulink/rabbitbot/utils/ImageUtil.java
1,495
//写入图片数据
line_comment
zh-cn
package cn.mikulink.rabbitbot.utils; import cn.mikulink.rabbitbot.constant.ConstantImage; import cn.mikulink.rabbitbot.entity.ImageInfo; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; import java.io.*; import java.net.HttpURLConnection; import java.net.Proxy; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; /** * create by MikuLink on 2019/12/12 17:38 * for the Reisen * 图片 */ public class ImageUtil { private static final List<String> IMAGE_SUFFIXS = Arrays.asList(".jpg", ".jpeg", ".gif", ".png"); /** * 下载图片到本地 * * @param imageUrl 网络图片url * @return 图片名称 */ public static String downloadImage(String imageUrl) throws IOException { return downloadImage(imageUrl, ConstantImage.DEFAULT_IMAGE_SAVE_PATH, null); } /** * 下载图片到本地 * * @param imageUrl 网络图片url * @param localUrl 本地储存地址 * @param fileName 文件名称,带后缀的那种,如果为空则取链接最后一段作为文件名 * @return 图片路径 */ public static String downloadImage(String imageUrl, String localUrl, String fileName) throws IOException { return downloadImage(null, imageUrl, localUrl, fileName); } /** * 下载图片到本地 * * @param header http请求header * @param imageUrl 网络图片url * @param localUrl 本地储存地址 * @param fileName 文件名称,带后缀的那种,如果为空则取链接最后一段作为文件名 * @return 本地图片相对路径 * @throws IOException 异常 */ public static String downloadImage(HashMap<String, String> header, String imageUrl, String localUrl, String fileName) throws IOException { return downloadImage(header, imageUrl, localUrl, fileName, null); } /** * 下载图片到本地 * * @param header http请求header * @param imageUrl 网络图片url * @param localUrl 本地储存地址 * @param fileName 文件名称,带后缀的那种,如果为空则取链接最后一段作为文件名 * @param proxy 代理 * @return 本地图片相对路径 * @throws IOException 异常 */ public static String downloadImage(HashMap<String, String> header, String imageUrl, String localUrl, String fileName, Proxy proxy) throws IOException { if (StringUtil.isEmpty(imageUrl)) { throw new IOException("网络图片链接为空"); } //类型根据创建连接 HttpURLConnection conn = null; if (imageUrl.startsWith("https")) { conn = HttpsUtil.getHttpsURLConnection(imageUrl, HttpUtil.REQUEST_METHOD_GET, header, proxy); } else { conn = HttpUtil.getHttpURLConnection(imageUrl, HttpUtil.REQUEST_METHOD_GET, proxy); } //设置链接超时时间 // conn.setConnectTimeout(5 * 1000); //请求header if (null != header) { for (String key : header.keySet()) { conn.setRequestProperty(key, header.get(key)); } } //获取输出流 InputStream inStream = conn.getInputStream(); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); //把图片信息存下来,写入内存 byte[] data = outStream.toByteArray(); //使用网络图片的中段目录 // String path = imageUrl.substring(imageUrl.indexOf("n/") + 1, imageUrl.lastIndexOf("/")); //创建本地文件 File result = new File(localUrl); if (!result.exists()) { result.mkdirs(); } //如果为空,使用网络图片的名称和后缀 if (StringUtil.isEmpty(fileName)) { fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1); } //写入 <SUF> String fileFullName = result + File.separator + fileName; FileOutputStream fileOutputStream = new FileOutputStream(fileFullName); fileOutputStream.write(data); fileOutputStream.flush(); fileOutputStream.close(); //返回文件路径 return fileFullName; } /** * 判断文件是否存在 * * @param imageUrl 文件路径 * @return 是否存在 */ public static boolean isExists(String imageUrl) { if (StringUtil.isEmpty(imageUrl)) { return false; } //创建本地文件 File result = new File(imageUrl); return result.exists(); } /** * 是否为图片文件 * * @param fileName 文件名称 * @return 是否为图片 */ public static boolean isImage(String fileName) { String suffix = FileUtil.getFileSuffix(fileName); if (StringUtil.isEmpty(suffix)) { return false; } return IMAGE_SUFFIXS.contains(suffix); } /** * 获取本地图片信息 * * @param imagePath 图片文件路径 * @return 图片信息 */ public static ImageInfo getImageInfo(String imagePath) throws IOException { //这个方法太慢了 // BufferedImage sourceImg = ImageIO.read(new FileInputStream(new File(imagePath))); // sourceImg.getWidth(); // sourceImg.getHeight(); //没研究透,复制来的代码,但比上面的快多了 //获取图片后缀,不要"." String imgType = FileUtil.getFileSuffix(imagePath).replace(".", ""); Iterator<ImageReader> readers = ImageIO.getImageReadersByFormatName(imgType.toLowerCase()); ImageReader reader = readers.next(); ImageInputStream iis = ImageIO.createImageInputStream(new File(imagePath)); reader.setInput(iis, true); int width = reader.getWidth(0); int height = reader.getHeight(0); ImageInfo imageInfo = new ImageInfo(); imageInfo.setLocalPath(imagePath); imageInfo.setWidth(width); imageInfo.setHeight(height); imageInfo.setType(imgType); imageInfo.setSize(new File(imagePath).length()); return imageInfo; } }
false
1,384
5
1,495
4
1,583
4
1,495
4
2,002
7
false
false
false
false
false
true
49820_1
package JavaCode.contest.weekly.n0_200.n171; import java.util.HashMap; import java.util.Map; /** * author:fangjie * time:2020/1/12 */ public class N4 { private final static Map<Character,int[]> map; static { map=new HashMap<>(26); for (int i=0;i<26;i++) { map.put((char)(i+'A'),new int[]{i/6,i%6}); } } public int minimumDistance(String word) { char[] strs=word.toCharArray(); Map<String,Integer> dp=new HashMap<>(); return slove(0,strs,'#','#',dp); } private int slove(int idx, char[] strs, char pre1, char pre2, Map<String, Integer> dp) { if (idx==strs.length)return 0; String key=pre1+pre2+","+idx; if(dp.containsKey(key))return dp.get(key); int res=Math.min(getDis(pre1,strs[idx])+slove(idx+1,strs,strs[idx],pre2,dp), getDis(pre2,strs[idx])+slove(idx+1,strs,pre1,strs[idx],dp)); dp.put(key,res); return res; } private int getDis(char a,char b) { if(a=='#'||b=='#')return 0; int[] x1=map.get(a); int[] x2=map.get(b); return Math.abs(x1[0]-x2[0])+Math.abs(x1[1]-x2[1]); } } /* 二指输入法定制键盘在 XY 平面上的布局如上图所示,其中每个大写英文字母都位于某个坐标处,例如字母 A 位于坐标 (0,0),字母 B 位于坐标 (0,1),字母 P 位于坐标 (2,3) 且字母 Z 位于坐标 (4,1)。 给你一个待输入字符串 word,请你计算并返回在仅使用两根手指的情况下,键入该字符串需要的最小移动总距离。坐标 (x1,y1) 和 (x2,y2) 之间的距离是 |x1 - x2| + |y1 - y2|。 注意,两根手指的起始位置是零代价的,不计入移动总距离。你的两根手指的起始位置也不必从首字母或者前两个字母开始。 示例 1: 输入:word = "CAKE" 输出:3 解释: 使用两根手指输入 "CAKE" 的最佳方案之一是: 手指 1 在字母 'C' 上 -> 移动距离 = 0 手指 1 在字母 'A' 上 -> 移动距离 = 从字母 'C' 到字母 'A' 的距离 = 2 手指 2 在字母 'K' 上 -> 移动距离 = 0 手指 2 在字母 'E' 上 -> 移动距离 = 从字母 'K' 到字母 'E' 的距离 = 1 总距离 = 3 示例 2: 输入:word = "HAPPY" 输出:6 解释: 使用两根手指输入 "HAPPY" 的最佳方案之一是: 手指 1 在字母 'H' 上 -> 移动距离 = 0 手指 1 在字母 'A' 上 -> 移动距离 = 从字母 'H' 到字母 'A' 的距离 = 2 手指 2 在字母 'P' 上 -> 移动距离 = 0 手指 2 在字母 'P' 上 -> 移动距离 = 从字母 'P' 到字母 'P' 的距离 = 0 手指 1 在字母 'Y' 上 -> 移动距离 = 从字母 'A' 到字母 'Y' 的距离 = 4 总距离 = 6 示例 3: 输入:word = "NEW" 输出:3 示例 4: 输入:word = "YEAR" 输出:7 */
MikuSugar/LeetCode
JavaCode/contest/weekly/n0_200/n171/N4.java
1,024
/* 二指输入法定制键盘在 XY 平面上的布局如上图所示,其中每个大写英文字母都位于某个坐标处,例如字母 A 位于坐标 (0,0),字母 B 位于坐标 (0,1),字母 P 位于坐标 (2,3) 且字母 Z 位于坐标 (4,1)。 给你一个待输入字符串 word,请你计算并返回在仅使用两根手指的情况下,键入该字符串需要的最小移动总距离。坐标 (x1,y1) 和 (x2,y2) 之间的距离是 |x1 - x2| + |y1 - y2|。 注意,两根手指的起始位置是零代价的,不计入移动总距离。你的两根手指的起始位置也不必从首字母或者前两个字母开始。 示例 1: 输入:word = "CAKE" 输出:3 解释: 使用两根手指输入 "CAKE" 的最佳方案之一是: 手指 1 在字母 'C' 上 -> 移动距离 = 0 手指 1 在字母 'A' 上 -> 移动距离 = 从字母 'C' 到字母 'A' 的距离 = 2 手指 2 在字母 'K' 上 -> 移动距离 = 0 手指 2 在字母 'E' 上 -> 移动距离 = 从字母 'K' 到字母 'E' 的距离 = 1 总距离 = 3 示例 2: 输入:word = "HAPPY" 输出:6 解释: 使用两根手指输入 "HAPPY" 的最佳方案之一是: 手指 1 在字母 'H' 上 -> 移动距离 = 0 手指 1 在字母 'A' 上 -> 移动距离 = 从字母 'H' 到字母 'A' 的距离 = 2 手指 2 在字母 'P' 上 -> 移动距离 = 0 手指 2 在字母 'P' 上 -> 移动距离 = 从字母 'P' 到字母 'P' 的距离 = 0 手指 1 在字母 'Y' 上 -> 移动距离 = 从字母 'A' 到字母 'Y' 的距离 = 4 总距离 = 6 示例 3: 输入:word = "NEW" 输出:3 示例 4: 输入:word = "YEAR" 输出:7 */
block_comment
zh-cn
package JavaCode.contest.weekly.n0_200.n171; import java.util.HashMap; import java.util.Map; /** * author:fangjie * time:2020/1/12 */ public class N4 { private final static Map<Character,int[]> map; static { map=new HashMap<>(26); for (int i=0;i<26;i++) { map.put((char)(i+'A'),new int[]{i/6,i%6}); } } public int minimumDistance(String word) { char[] strs=word.toCharArray(); Map<String,Integer> dp=new HashMap<>(); return slove(0,strs,'#','#',dp); } private int slove(int idx, char[] strs, char pre1, char pre2, Map<String, Integer> dp) { if (idx==strs.length)return 0; String key=pre1+pre2+","+idx; if(dp.containsKey(key))return dp.get(key); int res=Math.min(getDis(pre1,strs[idx])+slove(idx+1,strs,strs[idx],pre2,dp), getDis(pre2,strs[idx])+slove(idx+1,strs,pre1,strs[idx],dp)); dp.put(key,res); return res; } private int getDis(char a,char b) { if(a=='#'||b=='#')return 0; int[] x1=map.get(a); int[] x2=map.get(b); return Math.abs(x1[0]-x2[0])+Math.abs(x1[1]-x2[1]); } } /* 二指输 <SUF>*/
false
892
532
1,024
597
960
510
1,024
597
1,336
848
true
true
true
true
true
false
23585_2
package cn.misection.cvac.ast; import cn.misection.cvac.ast.clas.AbstractCvaClass; import cn.misection.cvac.ast.clas.CvaClass; import cn.misection.cvac.ast.decl.AbstractDeclaration; import cn.misection.cvac.ast.decl.CvaDeclaration; import cn.misection.cvac.ast.decl.nullobj.CvaNullDecl; import cn.misection.cvac.ast.entry.AbstractEntryClass; import cn.misection.cvac.ast.entry.CvaEntryClass; import cn.misection.cvac.ast.expr.AbstractExpression; import cn.misection.cvac.ast.expr.nonterminal.binary.CvaAndAndExpr; import cn.misection.cvac.ast.expr.nonterminal.binary.CvaLessOrMoreThanExpr; import cn.misection.cvac.ast.expr.nonterminal.binary.CvaOperandOperatorExpr; import cn.misection.cvac.ast.expr.nonterminal.unary.CvaCallExpr; import cn.misection.cvac.ast.expr.nonterminal.unary.CvaIncDecExpr; import cn.misection.cvac.ast.expr.nonterminal.unary.CvaNegateExpr; import cn.misection.cvac.ast.expr.nonterminal.unary.CvaNewExpr; import cn.misection.cvac.ast.expr.terminator.*; import cn.misection.cvac.ast.method.AbstractMethod; import cn.misection.cvac.ast.method.CvaMainMethod; import cn.misection.cvac.ast.method.CvaMethod; import cn.misection.cvac.ast.program.AbstractProgram; import cn.misection.cvac.ast.program.CvaProgram; import cn.misection.cvac.ast.statement.*; import cn.misection.cvac.ast.type.AbstractType; import cn.misection.cvac.ast.type.ICvaType; import cn.misection.cvac.ast.type.advance.CvaStringType; import cn.misection.cvac.ast.type.basic.EnumCvaType; import cn.misection.cvac.ast.type.reference.CvaClassType; /** * Created by MI6 root 1/7. */ public interface IVisitor { /** * type * * @param type t; */ default void visit(ICvaType type) { // 不是枚举; if (type instanceof AbstractType) { switch ((type.toEnum())) { case STRING: { visit((CvaStringType) type); break; } case POINTER: { // TODO; break; } case ARRAY: { // TODO; break; } case CLASS: { visit((CvaClassType) type); } default: { break; } } } // 基本枚举类型; else { visit((EnumCvaType) type); } } void visit(EnumCvaType basicType); void visit(CvaStringType type); void visit(CvaClassType type); /** * decl * * @param abstDecl decl; */ default void visit(AbstractDeclaration abstDecl) { if (!(abstDecl instanceof CvaNullDecl)) { visit(((CvaDeclaration) abstDecl)); } } void visit(CvaDeclaration decl); /** * 做成map之后, 可以精简代码分散, 但是这里要用反射, 算了; * * @param expr e; */ default void visit(AbstractExpression expr) { // 用typeCode代替, 可以避免反射以及改名麻烦; switch (expr.toEnum()) { case AND_AND: { visit((CvaAndAndExpr) expr); break; } case CALL: { visit((CvaCallExpr) expr); break; } case IDENTIFIER: { visit((CvaIdentifierExpr) expr); break; } case LESS_OR_MORE_THAN: { visit((CvaLessOrMoreThanExpr) expr); break; } case NEW: { visit((CvaNewExpr) expr); break; } case NEGATE: { visit((CvaNegateExpr) expr); break; } case CONST_INT: { visit((CvaConstIntExpr) expr); break; } case CONST_STRING: { visit((CvaConstStringExpr) expr); break; } case CONST_TRUE: { visit((CvaConstTrueExpr) expr); break; } case CONST_FALSE: { visit((CvaConstFalseExpr) expr); break; } case CONST_NULL: { // TODO; break; } case THIS: { visit((CvaThisExpr) expr); break; } case BINARY_OPERAND_OP: { visit((CvaOperandOperatorExpr) expr); break; } case INCREMENT: case DECREMENT: { visit((CvaIncDecExpr) expr); break; } case NULL_POINTER: { // 直接忽略, 转都不转; break; } default: { // 将所有的都用绑定的enum判定; System.err.println("unknown expr"); } } } void visit(CvaAndAndExpr expr); void visit(CvaCallExpr expr); void visit(CvaConstFalseExpr expr); void visit(CvaIdentifierExpr expr); void visit(CvaLessOrMoreThanExpr expr); void visit(CvaNewExpr expr); void visit(CvaNegateExpr expr); void visit(CvaConstIntExpr expr); void visit(CvaConstStringExpr expr); void visit(CvaThisExpr expr); void visit(CvaConstTrueExpr expr); void visit(CvaOperandOperatorExpr expr); void visit(CvaIncDecExpr expr); /** * stm; * * @param abstStm stm; */ default void visit(AbstractStatement abstStm) { switch (abstStm.toEnum()) { case ASSIGN: { visit((CvaAssignStatement) abstStm); break; } case BLOCK: { visit((CvaBlockStatement) abstStm); break; } case IF: { visit((CvaIfStatement) abstStm); break; } case WRITE: { visit((CvaWriteStatement) abstStm); break; } case WHILE_FOR: { visit((CvaWhileForStatement) abstStm); break; } case NULL_POINTER: { // 直接忽略, 转都不用转; break; } case EXPR_STATEMENT: { // decl statement 不需要用, 其只是辅助数据结构, 用完就扔; visit((CvaExprStatement) abstStm); break; } default: { System.err.println("unknown statement"); break; } } } void visit(CvaAssignStatement stm); void visit(CvaBlockStatement stm); void visit(CvaIfStatement stm); void visit(CvaWriteStatement stm); void visit(CvaWhileForStatement stm); void visit(CvaExprStatement stm); /** * Method */ default void visit(AbstractMethod abstMethod) { visit(((CvaMethod) abstMethod)); } void visit(CvaMethod cvaMethod); /** * class; * * @param abstClass class; */ default void visit(AbstractCvaClass abstClass) { visit(((CvaClass) abstClass)); } void visit(CvaClass cvaClass); default void visit(AbstractEntryClass entryClass) { visit(((CvaEntryClass) entryClass)); } void visit(CvaEntryClass entryClass); void visit(CvaMainMethod entryMethod); // Program default void visit(AbstractProgram program) { visit(((CvaProgram) program)); } void visit(CvaProgram program); }
MilitaryIntelligence6/Cva
Cvac/src/main/java/cn/misection/cvac/ast/IVisitor.java
1,971
// 不是枚举;
line_comment
zh-cn
package cn.misection.cvac.ast; import cn.misection.cvac.ast.clas.AbstractCvaClass; import cn.misection.cvac.ast.clas.CvaClass; import cn.misection.cvac.ast.decl.AbstractDeclaration; import cn.misection.cvac.ast.decl.CvaDeclaration; import cn.misection.cvac.ast.decl.nullobj.CvaNullDecl; import cn.misection.cvac.ast.entry.AbstractEntryClass; import cn.misection.cvac.ast.entry.CvaEntryClass; import cn.misection.cvac.ast.expr.AbstractExpression; import cn.misection.cvac.ast.expr.nonterminal.binary.CvaAndAndExpr; import cn.misection.cvac.ast.expr.nonterminal.binary.CvaLessOrMoreThanExpr; import cn.misection.cvac.ast.expr.nonterminal.binary.CvaOperandOperatorExpr; import cn.misection.cvac.ast.expr.nonterminal.unary.CvaCallExpr; import cn.misection.cvac.ast.expr.nonterminal.unary.CvaIncDecExpr; import cn.misection.cvac.ast.expr.nonterminal.unary.CvaNegateExpr; import cn.misection.cvac.ast.expr.nonterminal.unary.CvaNewExpr; import cn.misection.cvac.ast.expr.terminator.*; import cn.misection.cvac.ast.method.AbstractMethod; import cn.misection.cvac.ast.method.CvaMainMethod; import cn.misection.cvac.ast.method.CvaMethod; import cn.misection.cvac.ast.program.AbstractProgram; import cn.misection.cvac.ast.program.CvaProgram; import cn.misection.cvac.ast.statement.*; import cn.misection.cvac.ast.type.AbstractType; import cn.misection.cvac.ast.type.ICvaType; import cn.misection.cvac.ast.type.advance.CvaStringType; import cn.misection.cvac.ast.type.basic.EnumCvaType; import cn.misection.cvac.ast.type.reference.CvaClassType; /** * Created by MI6 root 1/7. */ public interface IVisitor { /** * type * * @param type t; */ default void visit(ICvaType type) { // 不是 <SUF> if (type instanceof AbstractType) { switch ((type.toEnum())) { case STRING: { visit((CvaStringType) type); break; } case POINTER: { // TODO; break; } case ARRAY: { // TODO; break; } case CLASS: { visit((CvaClassType) type); } default: { break; } } } // 基本枚举类型; else { visit((EnumCvaType) type); } } void visit(EnumCvaType basicType); void visit(CvaStringType type); void visit(CvaClassType type); /** * decl * * @param abstDecl decl; */ default void visit(AbstractDeclaration abstDecl) { if (!(abstDecl instanceof CvaNullDecl)) { visit(((CvaDeclaration) abstDecl)); } } void visit(CvaDeclaration decl); /** * 做成map之后, 可以精简代码分散, 但是这里要用反射, 算了; * * @param expr e; */ default void visit(AbstractExpression expr) { // 用typeCode代替, 可以避免反射以及改名麻烦; switch (expr.toEnum()) { case AND_AND: { visit((CvaAndAndExpr) expr); break; } case CALL: { visit((CvaCallExpr) expr); break; } case IDENTIFIER: { visit((CvaIdentifierExpr) expr); break; } case LESS_OR_MORE_THAN: { visit((CvaLessOrMoreThanExpr) expr); break; } case NEW: { visit((CvaNewExpr) expr); break; } case NEGATE: { visit((CvaNegateExpr) expr); break; } case CONST_INT: { visit((CvaConstIntExpr) expr); break; } case CONST_STRING: { visit((CvaConstStringExpr) expr); break; } case CONST_TRUE: { visit((CvaConstTrueExpr) expr); break; } case CONST_FALSE: { visit((CvaConstFalseExpr) expr); break; } case CONST_NULL: { // TODO; break; } case THIS: { visit((CvaThisExpr) expr); break; } case BINARY_OPERAND_OP: { visit((CvaOperandOperatorExpr) expr); break; } case INCREMENT: case DECREMENT: { visit((CvaIncDecExpr) expr); break; } case NULL_POINTER: { // 直接忽略, 转都不转; break; } default: { // 将所有的都用绑定的enum判定; System.err.println("unknown expr"); } } } void visit(CvaAndAndExpr expr); void visit(CvaCallExpr expr); void visit(CvaConstFalseExpr expr); void visit(CvaIdentifierExpr expr); void visit(CvaLessOrMoreThanExpr expr); void visit(CvaNewExpr expr); void visit(CvaNegateExpr expr); void visit(CvaConstIntExpr expr); void visit(CvaConstStringExpr expr); void visit(CvaThisExpr expr); void visit(CvaConstTrueExpr expr); void visit(CvaOperandOperatorExpr expr); void visit(CvaIncDecExpr expr); /** * stm; * * @param abstStm stm; */ default void visit(AbstractStatement abstStm) { switch (abstStm.toEnum()) { case ASSIGN: { visit((CvaAssignStatement) abstStm); break; } case BLOCK: { visit((CvaBlockStatement) abstStm); break; } case IF: { visit((CvaIfStatement) abstStm); break; } case WRITE: { visit((CvaWriteStatement) abstStm); break; } case WHILE_FOR: { visit((CvaWhileForStatement) abstStm); break; } case NULL_POINTER: { // 直接忽略, 转都不用转; break; } case EXPR_STATEMENT: { // decl statement 不需要用, 其只是辅助数据结构, 用完就扔; visit((CvaExprStatement) abstStm); break; } default: { System.err.println("unknown statement"); break; } } } void visit(CvaAssignStatement stm); void visit(CvaBlockStatement stm); void visit(CvaIfStatement stm); void visit(CvaWriteStatement stm); void visit(CvaWhileForStatement stm); void visit(CvaExprStatement stm); /** * Method */ default void visit(AbstractMethod abstMethod) { visit(((CvaMethod) abstMethod)); } void visit(CvaMethod cvaMethod); /** * class; * * @param abstClass class; */ default void visit(AbstractCvaClass abstClass) { visit(((CvaClass) abstClass)); } void visit(CvaClass cvaClass); default void visit(AbstractEntryClass entryClass) { visit(((CvaEntryClass) entryClass)); } void visit(CvaEntryClass entryClass); void visit(CvaMainMethod entryMethod); // Program default void visit(AbstractProgram program) { visit(((CvaProgram) program)); } void visit(CvaProgram program); }
false
1,708
6
1,971
6
2,111
5
1,971
6
2,403
11
false
false
false
false
false
true
65882_1
// 按两次 Shift 打开“随处搜索”对话框并输入 `show whitespaces`, // 然后按 Enter 键。现在,您可以在代码中看到 import java.sql.SQLOutput; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); role s1=new role(); role s2=new role("兴佳",500,20,10,40,10,100,300); System.out.println("请选择职业"); System.out.println("*****1.战士******"); System.out.println("*****2.法师******"); System.out.println("*****3.射手******"); int a=sc.nextInt(); switch(a){ case 1:{ s1.setrole("焕杰",500,10,5,30,15,100,100); break; } case 2:{ s1.setrole("焕杰",300,40,5,50,5,300,100); break; } case 3:{ s1.setrole("焕杰",300,50,30,50,5,100,100); break; } } while(true){ System.out.println("***** 选择 *****"); System.out.println("*****1.普攻*****"); System.out.println("*****2.防御*****"); System.out.println("*****使用药剂*****"); int b=sc.nextInt(); switch(b){ case 1: { s1.attack(s2); break; } case 2:{ s1.setdefenses(true); break; } case 3:{ s1.Ubloodnum(s1); break; } } if (win(s2.getblood())) { s1.setG(s1.getG() + s2.getG()); System.out.println(s1.getname() + "win"); break; } s2.attack(s1); s1.setdefenses(false); if(win(s1.getblood())) { System.out.println(s2.getname() + "win"); break; } } } public static boolean win(int blood){ if(blood==0) return true; return false; } }
MindbniM/tensetusnoyume
文字游戏/Main.java
611
// 然后按 Enter 键。现在,您可以在代码中看到
line_comment
zh-cn
// 按两次 Shift 打开“随处搜索”对话框并输入 `show whitespaces`, // 然后 <SUF> import java.sql.SQLOutput; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc=new Scanner(System.in); role s1=new role(); role s2=new role("兴佳",500,20,10,40,10,100,300); System.out.println("请选择职业"); System.out.println("*****1.战士******"); System.out.println("*****2.法师******"); System.out.println("*****3.射手******"); int a=sc.nextInt(); switch(a){ case 1:{ s1.setrole("焕杰",500,10,5,30,15,100,100); break; } case 2:{ s1.setrole("焕杰",300,40,5,50,5,300,100); break; } case 3:{ s1.setrole("焕杰",300,50,30,50,5,100,100); break; } } while(true){ System.out.println("***** 选择 *****"); System.out.println("*****1.普攻*****"); System.out.println("*****2.防御*****"); System.out.println("*****使用药剂*****"); int b=sc.nextInt(); switch(b){ case 1: { s1.attack(s2); break; } case 2:{ s1.setdefenses(true); break; } case 3:{ s1.Ubloodnum(s1); break; } } if (win(s2.getblood())) { s1.setG(s1.getG() + s2.getG()); System.out.println(s1.getname() + "win"); break; } s2.attack(s1); s1.setdefenses(false); if(win(s1.getblood())) { System.out.println(s2.getname() + "win"); break; } } } public static boolean win(int blood){ if(blood==0) return true; return false; } }
false
527
17
611
15
648
15
611
15
747
25
false
false
false
false
false
true
58593_9
package moe.gensoukyo.lib.rpg; import moe.gensoukyo.lib.constants.ModIds; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.DamageSource; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.fml.common.Optional; import noppes.npcs.api.entity.IEntityLivingBase; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.function.Supplier; /** * @author ChloePrime */ @SuppressWarnings("unused") public class DamageUtils { private DamageUtils() { } /** * 造成伤害并自定义死亡消息 * * @param victim 受到伤害的实体,被攻击者 * @param amount 伤害量 * @param deathMsg 自定义的死亡信息 */ public static void attackEntityWithCustomDeathMessage( @Nonnull EntityLivingBase victim, float amount, Supplier<ITextComponent> deathMsg) { attackEntityWithCustomDeathMessage0(victim, null, amount, deathMsg); } @Deprecated public static void attackEntityWithCustomDeathMessage( @Nonnull EntityLivingBase victim, float amount, ITextComponent deathMsg) { attackEntityWithCustomDeathMessage(victim, amount, () -> deathMsg); } /** * 造成伤害并自定义死亡消息 * * @param victim 受到伤害的实体,被攻击者 * @param damager 造成伤害的实体,攻击者 * @param amount 伤害量 * @param deathMsg 自定义的死亡信息 */ public static void attackEntityWithCustomDeathMessage( @Nonnull EntityLivingBase victim, @Nonnull EntityLivingBase damager, float amount, @Nonnull Supplier<ITextComponent> deathMsg ) { attackEntityWithCustomDeathMessage0(victim, damager, amount, deathMsg); } @Deprecated public static void attackEntityWithCustomDeathMessage( @Nonnull EntityLivingBase victim, @Nonnull EntityLivingBase damager, float amount, @Nonnull ITextComponent deathMsg ) { attackEntityWithCustomDeathMessage(victim, damager, amount, () -> deathMsg); } /** * Internal Method */ private static void attackEntityWithCustomDeathMessage0( @Nonnull EntityLivingBase victim, @Nullable EntityLivingBase damager, float amount, @Nonnull Supplier<ITextComponent> deathMsg ) { DamageSource damageSource = causeMsgCustomizedDamage(damager, deathMsg); victim.attackEntityFrom(damageSource, amount); } /** * Create a damage source * with customized death message. * * @param deathMsg Death Message(Lazy Computed) * @return DamageSource with death msg */ public static DamageSource causeMsgCustomizedDamage( @Nonnull Supplier<ITextComponent> deathMsg ) { return causeMsgCustomizedDamage(null, deathMsg); } @Deprecated public static DamageSource causeMsgCustomizedDamage(@Nonnull ITextComponent deathMsg) { return causeMsgCustomizedDamage(() -> deathMsg); } /** * Create a damage source * with customized death message. * * @param damager the attacker * @param deathMsg Death Message(Lazy Computed) * @return DamageSource with death msg */ public static DamageSource causeMsgCustomizedDamage( @Nullable EntityLivingBase damager, @Nonnull Supplier<ITextComponent> deathMsg ) { return (damager != null) ? new MsgCustomizedEntityDamageSource(damager, deathMsg) : new MsgCustomizedDamageSource(deathMsg); } @Deprecated public static DamageSource causeMsgCustomizedDamage( @Nullable EntityLivingBase damager, @Nonnull ITextComponent deathMsg ) { return causeMsgCustomizedDamage(damager, () -> deathMsg); } /** * 制造包式真伤 * 在致死前使用setHealth来扣除生命, * 致死时使用穿透伤害 * * @param victim 受害者 * @param amount 伤害量 */ public static void doBunStyleTrueDamage(EntityLivingBase victim, float amount) { if (victim.world.isRemote) { return; } doBunStyleTrueDamage(victim, amount, () -> victim.getDisplayName().appendText("被神奇的魔法杀死了") ); } /** * 制造包式真伤 * 在致死前使用setHealth来扣除生命, * 致死时使用穿透伤害 * * @param victim 受害者 * @param amount 伤害量 * @param deathMsg 自定义死亡消息 */ public static void doBunStyleTrueDamage( EntityLivingBase victim, float amount, Supplier<ITextComponent> deathMsg ) { if (victim.world.isRemote) { return; } if (victim instanceof EntityPlayerMP) { boolean isPlayerMode = ((EntityPlayerMP) victim).interactionManager.getGameType().isSurvivalOrAdventure(); if (!isPlayerMode) { return; } } float curHealth = victim.getHealth(); if (curHealth > amount) { victim.setHealth(curHealth - amount); } else { victim.attackEntityFrom(causeFinalHitDamage(deathMsg), Float.MAX_VALUE); } } @Deprecated public static void doBunStyleTrueDamage( EntityLivingBase victim, float amount, ITextComponent deathMsg ) { doBunStyleTrueDamage(victim, amount, () -> deathMsg); } private static DamageSource causeFinalHitDamage(Supplier<ITextComponent> msg) { return new MsgCustomizedDamageSource(msg).setDamageBypassesArmor(); } // CNPC支持 @Optional.Method(modid = ModIds.CNPC) public static void attackEntityWithCustomDeathMessage( @Nonnull IEntityLivingBase<?> victim, float amount, Supplier<String> deathMsg) { attackEntityWithCustomDeathMessage0( victim.getMCEntity(), null, amount, () -> new TextComponentString(deathMsg.get()) ); } @Optional.Method(modid = ModIds.CNPC) public static void attackEntityWithCustomDeathMessage( @Nonnull IEntityLivingBase<?> victim, @Nonnull IEntityLivingBase<?> damager, float amount, @Nonnull Supplier<String> deathMsg ) { attackEntityWithCustomDeathMessage0( victim.getMCEntity(), damager.getMCEntity(), amount, () -> new TextComponentString(deathMsg.get()) ); } @Optional.Method(modid = ModIds.CNPC) public static void doBunStyleTrueDamage(IEntityLivingBase<?> victim, float amount) { doBunStyleTrueDamage(victim.getMCEntity(), amount); } @Optional.Method(modid = ModIds.CNPC) public static void doBunStyleTrueDamage( IEntityLivingBase<?> victim, float amount, Supplier<String> deathMsg ) { doBunStyleTrueDamage( victim.getMCEntity(), amount, ()->new TextComponentString(deathMsg.get()) ); } // CNPC支持(旧版) @Deprecated @Optional.Method(modid = ModIds.CNPC) public static void attackEntityWithCustomDeathMessage( @Nonnull IEntityLivingBase<?> victim, float amount, String deathMsg ) { attackEntityWithCustomDeathMessage(victim, amount, ()-> deathMsg); } @Deprecated @Optional.Method(modid = ModIds.CNPC) public static void attackEntityWithCustomDeathMessage( @Nonnull IEntityLivingBase<?> victim, @Nonnull IEntityLivingBase<?> damager, float amount, @Nonnull String deathMsg ) { attackEntityWithCustomDeathMessage( victim, damager, amount, ()->deathMsg ); } @Deprecated @Optional.Method(modid = ModIds.CNPC) public static void doBunStyleTrueDamage( IEntityLivingBase<?> victim, float amount, String deathMsg ) { doBunStyleTrueDamage(victim, amount, () -> deathMsg); } }
MineCraftGensoukyo/mcglib
src/main/java/moe/gensoukyo/lib/rpg/DamageUtils.java
2,014
// CNPC支持(旧版)
line_comment
zh-cn
package moe.gensoukyo.lib.rpg; import moe.gensoukyo.lib.constants.ModIds; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.util.DamageSource; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.TextComponentString; import net.minecraftforge.fml.common.Optional; import noppes.npcs.api.entity.IEntityLivingBase; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.function.Supplier; /** * @author ChloePrime */ @SuppressWarnings("unused") public class DamageUtils { private DamageUtils() { } /** * 造成伤害并自定义死亡消息 * * @param victim 受到伤害的实体,被攻击者 * @param amount 伤害量 * @param deathMsg 自定义的死亡信息 */ public static void attackEntityWithCustomDeathMessage( @Nonnull EntityLivingBase victim, float amount, Supplier<ITextComponent> deathMsg) { attackEntityWithCustomDeathMessage0(victim, null, amount, deathMsg); } @Deprecated public static void attackEntityWithCustomDeathMessage( @Nonnull EntityLivingBase victim, float amount, ITextComponent deathMsg) { attackEntityWithCustomDeathMessage(victim, amount, () -> deathMsg); } /** * 造成伤害并自定义死亡消息 * * @param victim 受到伤害的实体,被攻击者 * @param damager 造成伤害的实体,攻击者 * @param amount 伤害量 * @param deathMsg 自定义的死亡信息 */ public static void attackEntityWithCustomDeathMessage( @Nonnull EntityLivingBase victim, @Nonnull EntityLivingBase damager, float amount, @Nonnull Supplier<ITextComponent> deathMsg ) { attackEntityWithCustomDeathMessage0(victim, damager, amount, deathMsg); } @Deprecated public static void attackEntityWithCustomDeathMessage( @Nonnull EntityLivingBase victim, @Nonnull EntityLivingBase damager, float amount, @Nonnull ITextComponent deathMsg ) { attackEntityWithCustomDeathMessage(victim, damager, amount, () -> deathMsg); } /** * Internal Method */ private static void attackEntityWithCustomDeathMessage0( @Nonnull EntityLivingBase victim, @Nullable EntityLivingBase damager, float amount, @Nonnull Supplier<ITextComponent> deathMsg ) { DamageSource damageSource = causeMsgCustomizedDamage(damager, deathMsg); victim.attackEntityFrom(damageSource, amount); } /** * Create a damage source * with customized death message. * * @param deathMsg Death Message(Lazy Computed) * @return DamageSource with death msg */ public static DamageSource causeMsgCustomizedDamage( @Nonnull Supplier<ITextComponent> deathMsg ) { return causeMsgCustomizedDamage(null, deathMsg); } @Deprecated public static DamageSource causeMsgCustomizedDamage(@Nonnull ITextComponent deathMsg) { return causeMsgCustomizedDamage(() -> deathMsg); } /** * Create a damage source * with customized death message. * * @param damager the attacker * @param deathMsg Death Message(Lazy Computed) * @return DamageSource with death msg */ public static DamageSource causeMsgCustomizedDamage( @Nullable EntityLivingBase damager, @Nonnull Supplier<ITextComponent> deathMsg ) { return (damager != null) ? new MsgCustomizedEntityDamageSource(damager, deathMsg) : new MsgCustomizedDamageSource(deathMsg); } @Deprecated public static DamageSource causeMsgCustomizedDamage( @Nullable EntityLivingBase damager, @Nonnull ITextComponent deathMsg ) { return causeMsgCustomizedDamage(damager, () -> deathMsg); } /** * 制造包式真伤 * 在致死前使用setHealth来扣除生命, * 致死时使用穿透伤害 * * @param victim 受害者 * @param amount 伤害量 */ public static void doBunStyleTrueDamage(EntityLivingBase victim, float amount) { if (victim.world.isRemote) { return; } doBunStyleTrueDamage(victim, amount, () -> victim.getDisplayName().appendText("被神奇的魔法杀死了") ); } /** * 制造包式真伤 * 在致死前使用setHealth来扣除生命, * 致死时使用穿透伤害 * * @param victim 受害者 * @param amount 伤害量 * @param deathMsg 自定义死亡消息 */ public static void doBunStyleTrueDamage( EntityLivingBase victim, float amount, Supplier<ITextComponent> deathMsg ) { if (victim.world.isRemote) { return; } if (victim instanceof EntityPlayerMP) { boolean isPlayerMode = ((EntityPlayerMP) victim).interactionManager.getGameType().isSurvivalOrAdventure(); if (!isPlayerMode) { return; } } float curHealth = victim.getHealth(); if (curHealth > amount) { victim.setHealth(curHealth - amount); } else { victim.attackEntityFrom(causeFinalHitDamage(deathMsg), Float.MAX_VALUE); } } @Deprecated public static void doBunStyleTrueDamage( EntityLivingBase victim, float amount, ITextComponent deathMsg ) { doBunStyleTrueDamage(victim, amount, () -> deathMsg); } private static DamageSource causeFinalHitDamage(Supplier<ITextComponent> msg) { return new MsgCustomizedDamageSource(msg).setDamageBypassesArmor(); } // CNPC支持 @Optional.Method(modid = ModIds.CNPC) public static void attackEntityWithCustomDeathMessage( @Nonnull IEntityLivingBase<?> victim, float amount, Supplier<String> deathMsg) { attackEntityWithCustomDeathMessage0( victim.getMCEntity(), null, amount, () -> new TextComponentString(deathMsg.get()) ); } @Optional.Method(modid = ModIds.CNPC) public static void attackEntityWithCustomDeathMessage( @Nonnull IEntityLivingBase<?> victim, @Nonnull IEntityLivingBase<?> damager, float amount, @Nonnull Supplier<String> deathMsg ) { attackEntityWithCustomDeathMessage0( victim.getMCEntity(), damager.getMCEntity(), amount, () -> new TextComponentString(deathMsg.get()) ); } @Optional.Method(modid = ModIds.CNPC) public static void doBunStyleTrueDamage(IEntityLivingBase<?> victim, float amount) { doBunStyleTrueDamage(victim.getMCEntity(), amount); } @Optional.Method(modid = ModIds.CNPC) public static void doBunStyleTrueDamage( IEntityLivingBase<?> victim, float amount, Supplier<String> deathMsg ) { doBunStyleTrueDamage( victim.getMCEntity(), amount, ()->new TextComponentString(deathMsg.get()) ); } // CN <SUF> @Deprecated @Optional.Method(modid = ModIds.CNPC) public static void attackEntityWithCustomDeathMessage( @Nonnull IEntityLivingBase<?> victim, float amount, String deathMsg ) { attackEntityWithCustomDeathMessage(victim, amount, ()-> deathMsg); } @Deprecated @Optional.Method(modid = ModIds.CNPC) public static void attackEntityWithCustomDeathMessage( @Nonnull IEntityLivingBase<?> victim, @Nonnull IEntityLivingBase<?> damager, float amount, @Nonnull String deathMsg ) { attackEntityWithCustomDeathMessage( victim, damager, amount, ()->deathMsg ); } @Deprecated @Optional.Method(modid = ModIds.CNPC) public static void doBunStyleTrueDamage( IEntityLivingBase<?> victim, float amount, String deathMsg ) { doBunStyleTrueDamage(victim, amount, () -> deathMsg); } }
false
1,853
8
2,014
8
2,084
8
2,014
8
2,582
12
false
false
false
false
false
true
56895_1
package top.mpt.xzystudio.flywars.listeners; import jdk.nashorn.internal.runtime.regexp.joni.Config; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import top.mpt.xzystudio.flywars.Main; import top.mpt.xzystudio.flywars.events.GameOverEvent; import top.mpt.xzystudio.flywars.events.TeamEliminatedEvent; import top.mpt.xzystudio.flywars.game.Game; import top.mpt.xzystudio.flywars.game.team.GameTeam; import top.mpt.xzystudio.flywars.game.team.TeamInfo; import top.mpt.xzystudio.flywars.utils.*; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** * 游戏相关事件监听器 */ public class GameEventListener implements Listener { @EventHandler public void onTeamEliminated(TeamEliminatedEvent event) { Player p = event.getPlayer(); GameTeam team = event.getTeam(); GameTeam killer = event.getKiller(); Player op = team.getTheOtherPlayer(p); // 获取到同一个团队的另一名玩家 // 将嗝屁的玩家设置为旁观者模式 if (op.isOnline()) op.setGameMode(GameMode.SPECTATOR); if (p.isOnline()) p.setGameMode(GameMode.SPECTATOR); PlayerUtils.showTitle(op, "#RED#你的队友 %s 寄了!", "即将变为观察者模式", Collections.singletonList(p.getName()), null); // 给另一名无辜的队友展示消息 // 这里无需在%s外面加<>,因为会有[] ChatUtils.broadcast("[FlyWars] %s被%s淘汰了!", team.getTeamDisplayName(), killer != null ? killer.getTeamDisplayName() : ""); // 公开处刑 TeamInfo info = Game.scoreboardManager.getInfo(team); info.setAlive(false); if (killer != null) { TeamInfo killerInfo = Game.scoreboardManager.getInfo(killer); killerInfo.addKillCount(); } Game.scoreboardManager.renderScoreboard(); // 判断是不是只剩最后一个队伍(胜利) AtomicInteger ifGameOver = new AtomicInteger(); GameTeam aliveTeam = GameUtils.getTeamBy(t -> Game.scoreboardManager.getInfo(t).getAlive()); if (aliveTeam != null) ifGameOver.getAndIncrement(); // TODO EJECT不知道管不管用,同时解散队伍 p.eject(); op.eject(); team.unregTeam(); // GameOver if (ifGameOver.get() == 1){ assert aliveTeam != null; GameOverEvent gameOverEvent = new GameOverEvent(aliveTeam, aliveTeam.getTeamDisplayName()); GameUtils.callEvent(gameOverEvent); } else if (ifGameOver.get() == 0) { LoggerUtils.warning("#RED#请勿在玩家数不足4个时开始游戏"); GameOverEvent gameOverEvent = new GameOverEvent(team, team.getTeamDisplayName()); GameUtils.callEvent(gameOverEvent); } } @EventHandler public void onGameOver(GameOverEvent event) { // 重置计分板 Game.scoreboardManager.reset(); // 取消资源刷新 if (Game.resUpdater != null) Game.resUpdater.cancel(); // 清除世界内的掉落物 if (event.getWinner() != null) { event.getWinner().getP1().getWorld().getEntities().forEach(it -> { if (it.getType() == EntityType.DROPPED_ITEM) it.remove(); }); } // 遍历teams数组 Game.teams.forEach(team -> { // 把每个team注销 // team.unregTeam(); // 上面队伍解散事件中已经unreg过了,重复unreg可能异常 // 获取团队信息 TeamInfo info = Game.scoreboardManager.getInfo(team); // 获取每个玩家 ArrayList<Player> players = new ArrayList<>(team.players.keySet()); // 遍历每个玩家 players.forEach(p -> { // 发放奖励 if (info.getAlive()){ ConfigUtils.getMapListConfig("prize").forEach(it -> { String material = (String) it.get("material"); material = material.toUpperCase(); int amount = (Integer) it.get("amount"); String name = (String) it.get("name"); p.getInventory().addItem(GameUtils.newItem(Material.valueOf(material), name, amount)); }); } // 给玩家显示标题 PlayerUtils.showTitle(p, "#GREEN#游戏结束!", "#GOLD#恭喜#RESET#%s#GOLD#取得胜利!", null, Collections.singletonList(event.getWinnerDisplayName()));// 不知道为啥这样会显示#GOLD#[#AQUA#[青队#AQUA#]#RESET#] // 给胜利者和失败着分别显示不同消息 PlayerUtils.send(p, " %s ", info.getAlive() ? "#GOLD#你的队伍胜利了!" : "#RED#你的队伍失败了!"); PlayerUtils.send(p, " 队伍成员:#AQUA# %s ", players.stream().map(Player::getName).collect(Collectors.joining(", "))); PlayerUtils.send(p, " 本局游戏队伍击杀数: #YELLOW#%s ", info.getKillCount()); // 不能让玩家白嫖鞘翅金苹果和烟花火箭吧 - addd p.getInventory().clear(); // 将玩家传送至指定的坐标 // 不能让玩家在空中就切生存吧qwq Location loc = new Location(p.getWorld(), (Integer) ConfigUtils.getConfig("end-x", 0), (Integer) ConfigUtils.getConfig("end-y", 0), (Integer) ConfigUtils.getConfig("end-z", 0)); p.teleport(loc); // 切换回冒险 p.setGameMode(GameMode.ADVENTURE); }); }); // 清空数组 Game.teams.clear(); Main.gameStatus = false; } }
MinecraftProgrammingTeam/FlyWars
src/main/java/top/mpt/xzystudio/flywars/listeners/GameEventListener.java
1,621
// 获取到同一个团队的另一名玩家
line_comment
zh-cn
package top.mpt.xzystudio.flywars.listeners; import jdk.nashorn.internal.runtime.regexp.joni.Config; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.inventory.ItemStack; import top.mpt.xzystudio.flywars.Main; import top.mpt.xzystudio.flywars.events.GameOverEvent; import top.mpt.xzystudio.flywars.events.TeamEliminatedEvent; import top.mpt.xzystudio.flywars.game.Game; import top.mpt.xzystudio.flywars.game.team.GameTeam; import top.mpt.xzystudio.flywars.game.team.TeamInfo; import top.mpt.xzystudio.flywars.utils.*; import java.util.ArrayList; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Collectors; /** * 游戏相关事件监听器 */ public class GameEventListener implements Listener { @EventHandler public void onTeamEliminated(TeamEliminatedEvent event) { Player p = event.getPlayer(); GameTeam team = event.getTeam(); GameTeam killer = event.getKiller(); Player op = team.getTheOtherPlayer(p); // 获取 <SUF> // 将嗝屁的玩家设置为旁观者模式 if (op.isOnline()) op.setGameMode(GameMode.SPECTATOR); if (p.isOnline()) p.setGameMode(GameMode.SPECTATOR); PlayerUtils.showTitle(op, "#RED#你的队友 %s 寄了!", "即将变为观察者模式", Collections.singletonList(p.getName()), null); // 给另一名无辜的队友展示消息 // 这里无需在%s外面加<>,因为会有[] ChatUtils.broadcast("[FlyWars] %s被%s淘汰了!", team.getTeamDisplayName(), killer != null ? killer.getTeamDisplayName() : ""); // 公开处刑 TeamInfo info = Game.scoreboardManager.getInfo(team); info.setAlive(false); if (killer != null) { TeamInfo killerInfo = Game.scoreboardManager.getInfo(killer); killerInfo.addKillCount(); } Game.scoreboardManager.renderScoreboard(); // 判断是不是只剩最后一个队伍(胜利) AtomicInteger ifGameOver = new AtomicInteger(); GameTeam aliveTeam = GameUtils.getTeamBy(t -> Game.scoreboardManager.getInfo(t).getAlive()); if (aliveTeam != null) ifGameOver.getAndIncrement(); // TODO EJECT不知道管不管用,同时解散队伍 p.eject(); op.eject(); team.unregTeam(); // GameOver if (ifGameOver.get() == 1){ assert aliveTeam != null; GameOverEvent gameOverEvent = new GameOverEvent(aliveTeam, aliveTeam.getTeamDisplayName()); GameUtils.callEvent(gameOverEvent); } else if (ifGameOver.get() == 0) { LoggerUtils.warning("#RED#请勿在玩家数不足4个时开始游戏"); GameOverEvent gameOverEvent = new GameOverEvent(team, team.getTeamDisplayName()); GameUtils.callEvent(gameOverEvent); } } @EventHandler public void onGameOver(GameOverEvent event) { // 重置计分板 Game.scoreboardManager.reset(); // 取消资源刷新 if (Game.resUpdater != null) Game.resUpdater.cancel(); // 清除世界内的掉落物 if (event.getWinner() != null) { event.getWinner().getP1().getWorld().getEntities().forEach(it -> { if (it.getType() == EntityType.DROPPED_ITEM) it.remove(); }); } // 遍历teams数组 Game.teams.forEach(team -> { // 把每个team注销 // team.unregTeam(); // 上面队伍解散事件中已经unreg过了,重复unreg可能异常 // 获取团队信息 TeamInfo info = Game.scoreboardManager.getInfo(team); // 获取每个玩家 ArrayList<Player> players = new ArrayList<>(team.players.keySet()); // 遍历每个玩家 players.forEach(p -> { // 发放奖励 if (info.getAlive()){ ConfigUtils.getMapListConfig("prize").forEach(it -> { String material = (String) it.get("material"); material = material.toUpperCase(); int amount = (Integer) it.get("amount"); String name = (String) it.get("name"); p.getInventory().addItem(GameUtils.newItem(Material.valueOf(material), name, amount)); }); } // 给玩家显示标题 PlayerUtils.showTitle(p, "#GREEN#游戏结束!", "#GOLD#恭喜#RESET#%s#GOLD#取得胜利!", null, Collections.singletonList(event.getWinnerDisplayName()));// 不知道为啥这样会显示#GOLD#[#AQUA#[青队#AQUA#]#RESET#] // 给胜利者和失败着分别显示不同消息 PlayerUtils.send(p, " %s ", info.getAlive() ? "#GOLD#你的队伍胜利了!" : "#RED#你的队伍失败了!"); PlayerUtils.send(p, " 队伍成员:#AQUA# %s ", players.stream().map(Player::getName).collect(Collectors.joining(", "))); PlayerUtils.send(p, " 本局游戏队伍击杀数: #YELLOW#%s ", info.getKillCount()); // 不能让玩家白嫖鞘翅金苹果和烟花火箭吧 - addd p.getInventory().clear(); // 将玩家传送至指定的坐标 // 不能让玩家在空中就切生存吧qwq Location loc = new Location(p.getWorld(), (Integer) ConfigUtils.getConfig("end-x", 0), (Integer) ConfigUtils.getConfig("end-y", 0), (Integer) ConfigUtils.getConfig("end-z", 0)); p.teleport(loc); // 切换回冒险 p.setGameMode(GameMode.ADVENTURE); }); }); // 清空数组 Game.teams.clear(); Main.gameStatus = false; } }
false
1,346
9
1,621
13
1,557
9
1,621
13
2,101
24
false
false
false
false
false
true
35324_3
package com.model; /** * (admin)管理员实体类 */ public class Admin extends ComData{ private static final long serialVersionUID = 884547634457472L; private Integer aid; //ID private String lname; //用户名 private String password; //登录密码 private String aname; //姓名 private String sex; //性别 private String tel; //手机号码 private String sf; //身份 public Integer getAid() { return aid; } public void setAid(Integer aid) { this.aid = aid; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAname() { return aname; } public void setAname(String aname) { this.aname = aname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getSf() { return sf; } public void setSf(String sf) { this.sf = sf; } }
Mineminen/VendingMachine
src/com/model/Admin.java
405
//手机号码
line_comment
zh-cn
package com.model; /** * (admin)管理员实体类 */ public class Admin extends ComData{ private static final long serialVersionUID = 884547634457472L; private Integer aid; //ID private String lname; //用户名 private String password; //登录密码 private String aname; //姓名 private String sex; //性别 private String tel; //手机 <SUF> private String sf; //身份 public Integer getAid() { return aid; } public void setAid(Integer aid) { this.aid = aid; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAname() { return aname; } public void setAname(String aname) { this.aname = aname; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getTel() { return tel; } public void setTel(String tel) { this.tel = tel; } public String getSf() { return sf; } public void setSf(String sf) { this.sf = sf; } }
false
313
3
405
4
395
3
405
4
461
5
false
false
false
false
false
true
21132_11
// LeetCode 75 Sliding Window Q3 class Solution { public int longestOnes(int[] nums, int k) { int n = nums.length; if (n <= k) { return n; } int l = 0; for (int r = 0; r < n; r++) { // 减少库存 k -= nums[r] ^ 1; if (k < 0) { // 欠费了 k += nums[l] ^ 1; // window 无法上涨,要跟着向右滑动 l++; } } return n - l; } } // beat 99% idea: // // 想象一下构造上升subseq, 构造的结果不一定是满足条件的,但是长度是满足的 // 更贴近的:340_Longest Substring with At Most K Distinct Characters // "不用左边缩到valid sub为止,只用缩到ans长度, // 不valid也无所谓,如果left到right大于ans且valid,更新ans" // 长度只上升不下降,因此不需要缩左边到valid // 只需要记录"欠了几个" 即可 // 想法: 滑动, 是1直接加, 是0看看够不够,够也直接加 // 不够就从左边减少 // class Solution { // public int longestOnes(int[] nums, int k) { // int n = nums.length; // if (k >= n) { // return n; // } // int count = 0; // int used = 0; // int l = 0; // int r = l; // int max = 0; // while (r < n) { // int curr = nums[r]; // if (curr == 0 && used == k) { // while (nums[l] == 1 && l < r) { // // count--; // l++; // } // l++; // used--; // } // // count += curr; // used += 1 - curr; // r++; // max = Math.max(max, r - l); // } // return max; // } // }
Ming91/CodingChallenges
java/1004. Max Consecutive Ones III.java
572
// 想法: 滑动, 是1直接加, 是0看看够不够,够也直接加
line_comment
zh-cn
// LeetCode 75 Sliding Window Q3 class Solution { public int longestOnes(int[] nums, int k) { int n = nums.length; if (n <= k) { return n; } int l = 0; for (int r = 0; r < n; r++) { // 减少库存 k -= nums[r] ^ 1; if (k < 0) { // 欠费了 k += nums[l] ^ 1; // window 无法上涨,要跟着向右滑动 l++; } } return n - l; } } // beat 99% idea: // // 想象一下构造上升subseq, 构造的结果不一定是满足条件的,但是长度是满足的 // 更贴近的:340_Longest Substring with At Most K Distinct Characters // "不用左边缩到valid sub为止,只用缩到ans长度, // 不valid也无所谓,如果left到right大于ans且valid,更新ans" // 长度只上升不下降,因此不需要缩左边到valid // 只需要记录"欠了几个" 即可 // 想法 <SUF> // 不够就从左边减少 // class Solution { // public int longestOnes(int[] nums, int k) { // int n = nums.length; // if (k >= n) { // return n; // } // int count = 0; // int used = 0; // int l = 0; // int r = l; // int max = 0; // while (r < n) { // int curr = nums[r]; // if (curr == 0 && used == k) { // while (nums[l] == 1 && l < r) { // // count--; // l++; // } // l++; // used--; // } // // count += curr; // used += 1 - curr; // r++; // max = Math.max(max, r - l); // } // return max; // } // }
false
509
26
570
28
548
22
572
28
678
38
false
false
false
false
false
true
56855_4
package model.enums; /** * Created by Quark on 16/8/12. */ public enum PollPlayerTypeEnum { /** * 房间创建者,即第一个进入房间的人 */ CREAT0R("CREATOR","房间创建者"), /** * 观众,可以看到所有选手的状态 */ SPECTATOR("SPECTATOR","观众"), /** * 参与者,只能看到自己的击球状况 */ PLAYER("PLAYER","参与者"); /** 参数名称 */ private String code; /** 参数业务描述 */ private String desc; /** * 构造方法 * * @param code 参数名称 * @param desc 参数含义描述 */ PollPlayerTypeEnum(String code, String desc) { this.code = code; this.desc = desc; } }
MirQuarK/pollpool
src/main/java/model/enums/PollPlayerTypeEnum.java
202
/** 参数名称 */
block_comment
zh-cn
package model.enums; /** * Created by Quark on 16/8/12. */ public enum PollPlayerTypeEnum { /** * 房间创建者,即第一个进入房间的人 */ CREAT0R("CREATOR","房间创建者"), /** * 观众,可以看到所有选手的状态 */ SPECTATOR("SPECTATOR","观众"), /** * 参与者,只能看到自己的击球状况 */ PLAYER("PLAYER","参与者"); /** 参数名 <SUF>*/ private String code; /** 参数业务描述 */ private String desc; /** * 构造方法 * * @param code 参数名称 * @param desc 参数含义描述 */ PollPlayerTypeEnum(String code, String desc) { this.code = code; this.desc = desc; } }
false
187
4
202
4
209
4
202
4
301
7
false
false
false
false
false
true
45311_9
public class NBody { /** * 读取文件中的宇宙半径 * @param fileName 文件名 * @return 宇宙半径 */ public static double readRadius(String fileName) { In in = new In(fileName); in.readInt(); return in.readDouble(); } /** * 读取文件中的多个行星 * @param fileName 文件名 * @return 包含多个行星的数组 */ public static Planet[] readPlanets(String fileName) { In in = new In(fileName); int planetNum = in.readInt(); in.readDouble(); Planet[] planets = new Planet[planetNum]; int cnt = 0; while (!in.isEmpty()) { if (cnt == planetNum) { break; } double xxPos = in.readDouble(); double yyPos = in.readDouble(); double xxVel = in.readDouble(); double yyVel = in.readDouble(); double mass = in.readDouble(); String imgFileName = in.readString(); planets[cnt] = new Planet(xxPos, yyPos, xxVel, yyVel, mass, imgFileName); cnt += 1; } return planets; } public static void main(String[] args) { // T 是总时间,dt 是时间增量 double T = Double.parseDouble(args[0]); double dt = Double.parseDouble(args[1]); // 包含着行星数据的文本文件名 String filename = args[2]; // 宇宙半径 double radius = NBody.readRadius(filename); Planet[] planets = NBody.readPlanets(filename); drawAnimation(T, dt, radius, planets); } /** * 以 radius 为比例绘制背景图 * @param radius 比例 */ private static void drawBackground(double radius) { StdDraw.setScale(-radius, radius); StdDraw.clear(); StdDraw.picture(0, 0, "images/starfield.jpg"); // StdDraw.show(); } /** * 绘制所有行星 * @param planets 包含所有行星的数组 */ private static void drawPlanets(Planet[] planets) { for (Planet planet: planets) { planet.draw(); } } /** * 创建动画 */ private static void drawAnimation(double T, double dt, double radius, Planet[] planets) { // 启用双缓冲 StdDraw.enableDoubleBuffering(); double t = 0.0; while (t < T) { double[] xForces = new double[planets.length]; double[] yForces = new double[planets.length]; // 根据提示需要先计算完所有的力,再调用 update,所以此处分成两个 for 循环 for (int i = 0; i < planets.length; i++) { // 计算对每个行星在 x 和 y 方向所受到的力 xForces[i] = planets[i].calcNetForceExertedByX(planets); yForces[i] = planets[i].calcNetForceExertedByY(planets); } for (int i = 0; i < planets.length; i++) { // 更新行星的位置、速度、加速度等 planets[i].update(dt, xForces[i], yForces[i]); } // 绘制背景图像 drawBackground(radius); // 绘制所有行星 drawPlanets(planets); // 显示 StdDraw.show(); // 将动画暂停 10 毫秒 StdDraw.pause(10); t += dt; } StdOut.printf("%d\n", planets.length); StdOut.printf("%.2e\n", radius); for (int i = 0; i < planets.length; i++) { StdOut.printf("%11.4e %11.4e %11.4e %11.4e %11.4e %12s\n", planets[i].xxPos, planets[i].yyPos, planets[i].xxVel, planets[i].yyVel, planets[i].mass, planets[i].imgFileName); } } }
MirRoR4s/CS-61B
proj0/NBody.java
1,017
// 启用双缓冲
line_comment
zh-cn
public class NBody { /** * 读取文件中的宇宙半径 * @param fileName 文件名 * @return 宇宙半径 */ public static double readRadius(String fileName) { In in = new In(fileName); in.readInt(); return in.readDouble(); } /** * 读取文件中的多个行星 * @param fileName 文件名 * @return 包含多个行星的数组 */ public static Planet[] readPlanets(String fileName) { In in = new In(fileName); int planetNum = in.readInt(); in.readDouble(); Planet[] planets = new Planet[planetNum]; int cnt = 0; while (!in.isEmpty()) { if (cnt == planetNum) { break; } double xxPos = in.readDouble(); double yyPos = in.readDouble(); double xxVel = in.readDouble(); double yyVel = in.readDouble(); double mass = in.readDouble(); String imgFileName = in.readString(); planets[cnt] = new Planet(xxPos, yyPos, xxVel, yyVel, mass, imgFileName); cnt += 1; } return planets; } public static void main(String[] args) { // T 是总时间,dt 是时间增量 double T = Double.parseDouble(args[0]); double dt = Double.parseDouble(args[1]); // 包含着行星数据的文本文件名 String filename = args[2]; // 宇宙半径 double radius = NBody.readRadius(filename); Planet[] planets = NBody.readPlanets(filename); drawAnimation(T, dt, radius, planets); } /** * 以 radius 为比例绘制背景图 * @param radius 比例 */ private static void drawBackground(double radius) { StdDraw.setScale(-radius, radius); StdDraw.clear(); StdDraw.picture(0, 0, "images/starfield.jpg"); // StdDraw.show(); } /** * 绘制所有行星 * @param planets 包含所有行星的数组 */ private static void drawPlanets(Planet[] planets) { for (Planet planet: planets) { planet.draw(); } } /** * 创建动画 */ private static void drawAnimation(double T, double dt, double radius, Planet[] planets) { // 启用 <SUF> StdDraw.enableDoubleBuffering(); double t = 0.0; while (t < T) { double[] xForces = new double[planets.length]; double[] yForces = new double[planets.length]; // 根据提示需要先计算完所有的力,再调用 update,所以此处分成两个 for 循环 for (int i = 0; i < planets.length; i++) { // 计算对每个行星在 x 和 y 方向所受到的力 xForces[i] = planets[i].calcNetForceExertedByX(planets); yForces[i] = planets[i].calcNetForceExertedByY(planets); } for (int i = 0; i < planets.length; i++) { // 更新行星的位置、速度、加速度等 planets[i].update(dt, xForces[i], yForces[i]); } // 绘制背景图像 drawBackground(radius); // 绘制所有行星 drawPlanets(planets); // 显示 StdDraw.show(); // 将动画暂停 10 毫秒 StdDraw.pause(10); t += dt; } StdOut.printf("%d\n", planets.length); StdOut.printf("%.2e\n", radius); for (int i = 0; i < planets.length; i++) { StdOut.printf("%11.4e %11.4e %11.4e %11.4e %11.4e %12s\n", planets[i].xxPos, planets[i].yyPos, planets[i].xxVel, planets[i].yyVel, planets[i].mass, planets[i].imgFileName); } } }
false
932
6
1,017
6
1,040
5
1,017
6
1,278
13
false
false
false
false
false
true
35158_2
package composite; import java.util.ArrayList; public class Client { public static void main(String[] args) { IRoot ceo = new Root(" 王 大麻子", " 总经理", 100000); //产生 三个 部门 经理, 也就是 树枝 节点 IBranch developDep = new Branch("刘大瘸子", " 研发 部门 经理", 10000); IBranch salesDep = new Branch(" 马 二 拐子", " 销售 部门 经理", 20000); IBranch financeDep = new Branch(" 赵 三 驼 子", " 财务 部 经理", 30000); //再把 三个 小组长 产生 出来 IBranch firstDevGroup = new Branch(" 杨 三 乜 斜", " 开发 一组 组长", 5000); IBranch secondDevGroup = new Branch(" 吴 大 棒槌", " 开发 二 组 组长", 6000); ILeaf a = new Leaf(" a", " 开发 人员", 2000); ILeaf b = new Leaf(" b", " 开发 人员", 2000); ILeaf c = new Leaf(" c", " 开发 人员", 2000); ILeaf d = new Leaf(" d", " 开发 人员", 2000); ILeaf e = new Leaf(" e", " 开发 人员", 2000); ILeaf f = new Leaf(" f", " 开发 人员", 2000); ILeaf g = new Leaf(" g", " 开发 人员", 2000); ILeaf h = new Leaf(" h", " 销售 人员", 5000); ILeaf i = new Leaf(" i", " 销售 人员", 4000); ILeaf j = new Leaf(" j", " 财务 人员", 5000); ILeaf k = new Leaf(" k", " CEO 秘书", 8000); ILeaf zhengLaoLiu = new Leaf("郑老六", "研发部副总", 20000); ceo.add(developDep); ceo.add(salesDep); ceo.add(financeDep); developDep.add(firstDevGroup); developDep.add(secondDevGroup); developDep.add(zhengLaoLiu); firstDevGroup.add(a); firstDevGroup.add(b); firstDevGroup.add(c); secondDevGroup.add(d); secondDevGroup.add(e); secondDevGroup.add(f); secondDevGroup.add(g); salesDep.add(h); salesDep.add(i); financeDep.add(j); ceo.add(k); // 打印结果 System.out.println(ceo.getInfo()); getAllSubordinateInfo(ceo.getSubordinateInfo()); } private static void getAllSubordinateInfo(ArrayList subordinateList) { for (Object obj : subordinateList) { if (obj instanceof Leaf) { ILeaf employee = (ILeaf)obj; System.out.println(employee.getInfo()); }else{ IBranch branch = (IBranch) obj; getAllSubordinateInfo(branch.getSubordinateInfo()); } } } }
MirZhou/DesignPattern
src/composite/Client.java
836
// 打印结果
line_comment
zh-cn
package composite; import java.util.ArrayList; public class Client { public static void main(String[] args) { IRoot ceo = new Root(" 王 大麻子", " 总经理", 100000); //产生 三个 部门 经理, 也就是 树枝 节点 IBranch developDep = new Branch("刘大瘸子", " 研发 部门 经理", 10000); IBranch salesDep = new Branch(" 马 二 拐子", " 销售 部门 经理", 20000); IBranch financeDep = new Branch(" 赵 三 驼 子", " 财务 部 经理", 30000); //再把 三个 小组长 产生 出来 IBranch firstDevGroup = new Branch(" 杨 三 乜 斜", " 开发 一组 组长", 5000); IBranch secondDevGroup = new Branch(" 吴 大 棒槌", " 开发 二 组 组长", 6000); ILeaf a = new Leaf(" a", " 开发 人员", 2000); ILeaf b = new Leaf(" b", " 开发 人员", 2000); ILeaf c = new Leaf(" c", " 开发 人员", 2000); ILeaf d = new Leaf(" d", " 开发 人员", 2000); ILeaf e = new Leaf(" e", " 开发 人员", 2000); ILeaf f = new Leaf(" f", " 开发 人员", 2000); ILeaf g = new Leaf(" g", " 开发 人员", 2000); ILeaf h = new Leaf(" h", " 销售 人员", 5000); ILeaf i = new Leaf(" i", " 销售 人员", 4000); ILeaf j = new Leaf(" j", " 财务 人员", 5000); ILeaf k = new Leaf(" k", " CEO 秘书", 8000); ILeaf zhengLaoLiu = new Leaf("郑老六", "研发部副总", 20000); ceo.add(developDep); ceo.add(salesDep); ceo.add(financeDep); developDep.add(firstDevGroup); developDep.add(secondDevGroup); developDep.add(zhengLaoLiu); firstDevGroup.add(a); firstDevGroup.add(b); firstDevGroup.add(c); secondDevGroup.add(d); secondDevGroup.add(e); secondDevGroup.add(f); secondDevGroup.add(g); salesDep.add(h); salesDep.add(i); financeDep.add(j); ceo.add(k); // 打印 <SUF> System.out.println(ceo.getInfo()); getAllSubordinateInfo(ceo.getSubordinateInfo()); } private static void getAllSubordinateInfo(ArrayList subordinateList) { for (Object obj : subordinateList) { if (obj instanceof Leaf) { ILeaf employee = (ILeaf)obj; System.out.println(employee.getInfo()); }else{ IBranch branch = (IBranch) obj; getAllSubordinateInfo(branch.getSubordinateInfo()); } } } }
false
785
5
836
4
804
3
836
4
1,015
8
false
false
false
false
false
true
24157_1
import java.util.Scanner; /** * 猜数字游戏 * <p>Create time: 2020-05-08 15:51</p> * * @author 周光兵 **/ public class GuessNumber { private static Scanner scanner; public static void main(String[] args) { scanner = new Scanner(System.in); // 游戏设置 int rangeStart = getMinValue(); int rangeEnd = getMaxValue(); int mod = rangeEnd - rangeStart; if (mod <= 1) { System.out.println("非法的数字范围:(" + rangeStart + "," + rangeEnd + ")"); return; } System.out.print("请输入单轮最大猜测次数:"); int guessTotal = scanner.nextInt(); // 统计信息 int totalGameCount = 0; int correctGuessCount = 0; // 是否结束游戏 boolean gameEnd = false; while (!gameEnd) { // 生成指定范围内的随机数 int bigRandom = (int) (Math.random() * rangeEnd * 100.0); int numberToGuess = (bigRandom % mod) + rangeStart; if (numberToGuess <= rangeStart) { numberToGuess = rangeStart + 1; } else { numberToGuess = rangeEnd - 1; } // 剩余的猜测次数 int leftToGuess = guessTotal; boolean currentGameCounted = false; boolean correctGuess = false; System.out.println("数字范围:(" + rangeStart + "," + rangeEnd + ")。输入-1代表游戏结束"); while (leftToGuess > 0) { System.out.print("请输入范围内的数字(剩余次数:" + leftToGuess + "):"); int guess = scanner.nextInt(); if (guess == -1) { gameEnd = true; System.out.println("用户退出游戏"); break; } if (!currentGameCounted) { // 表示进入游戏 totalGameCount++; currentGameCounted = true; } leftToGuess--; if (guess > numberToGuess) { System.out.println("太大"); } else if (guess < numberToGuess) { System.out.println("太小"); } else { correctGuess = true; correctGuessCount++; System.out.println("正确!"); break; } } if (!correctGuess) { System.out.println("目标数字:" + numberToGuess); } System.out.println("共进行" + totalGameCount + "次游戏,猜中" + correctGuessCount + "次"); } } private static int getMinValue() { int value; do { System.out.print("请输入最小值:"); value = scanner.nextInt(); if (value >= 0) { break; } System.out.println("最小值必须是正数或者0"); } while (true); return value; } private static int getMaxValue() { int value; do { System.out.print("请输入最大值:"); value = scanner.nextInt(); if (value >= 0) { return value; } System.out.println("最大值必须是正数或者0"); } while (true); } }
MirZhou/java-example
src/GuessNumber.java
786
// 游戏设置
line_comment
zh-cn
import java.util.Scanner; /** * 猜数字游戏 * <p>Create time: 2020-05-08 15:51</p> * * @author 周光兵 **/ public class GuessNumber { private static Scanner scanner; public static void main(String[] args) { scanner = new Scanner(System.in); // 游戏 <SUF> int rangeStart = getMinValue(); int rangeEnd = getMaxValue(); int mod = rangeEnd - rangeStart; if (mod <= 1) { System.out.println("非法的数字范围:(" + rangeStart + "," + rangeEnd + ")"); return; } System.out.print("请输入单轮最大猜测次数:"); int guessTotal = scanner.nextInt(); // 统计信息 int totalGameCount = 0; int correctGuessCount = 0; // 是否结束游戏 boolean gameEnd = false; while (!gameEnd) { // 生成指定范围内的随机数 int bigRandom = (int) (Math.random() * rangeEnd * 100.0); int numberToGuess = (bigRandom % mod) + rangeStart; if (numberToGuess <= rangeStart) { numberToGuess = rangeStart + 1; } else { numberToGuess = rangeEnd - 1; } // 剩余的猜测次数 int leftToGuess = guessTotal; boolean currentGameCounted = false; boolean correctGuess = false; System.out.println("数字范围:(" + rangeStart + "," + rangeEnd + ")。输入-1代表游戏结束"); while (leftToGuess > 0) { System.out.print("请输入范围内的数字(剩余次数:" + leftToGuess + "):"); int guess = scanner.nextInt(); if (guess == -1) { gameEnd = true; System.out.println("用户退出游戏"); break; } if (!currentGameCounted) { // 表示进入游戏 totalGameCount++; currentGameCounted = true; } leftToGuess--; if (guess > numberToGuess) { System.out.println("太大"); } else if (guess < numberToGuess) { System.out.println("太小"); } else { correctGuess = true; correctGuessCount++; System.out.println("正确!"); break; } } if (!correctGuess) { System.out.println("目标数字:" + numberToGuess); } System.out.println("共进行" + totalGameCount + "次游戏,猜中" + correctGuessCount + "次"); } } private static int getMinValue() { int value; do { System.out.print("请输入最小值:"); value = scanner.nextInt(); if (value >= 0) { break; } System.out.println("最小值必须是正数或者0"); } while (true); return value; } private static int getMaxValue() { int value; do { System.out.print("请输入最大值:"); value = scanner.nextInt(); if (value >= 0) { return value; } System.out.println("最大值必须是正数或者0"); } while (true); } }
false
739
5
786
5
849
3
786
5
1,073
10
false
false
false
false
false
true
48957_0
package en.model; import com.jfinal.kit.PathKit; import com.jfinal.kit.PropKit; import com.jfinal.plugin.activerecord.generator.Generator; import com.jfinal.plugin.druid.DruidPlugin; import en.DemoConfig; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; /** * demo 仅表达最为粗浅的 jfinal 用法,更为有价的实用的企业级用法 * 详见 JFinal 俱乐部: http://jfinal.com/club * * 在数据库表有任何变动时,运行 main 方法,极速响应变化进行代码重 */ public class _JFinalDemoGenerator { public static DataSource getDataSource() { PropKit.use("application.properties"); DruidPlugin druidPlugin = DemoConfig.createDruidPlugin(); druidPlugin.start(); return druidPlugin.getDataSource(); } public static void main(String[] args) { // base model 使用的包 String baseModelPackageName = "en.model.base"; // base model 文件保存路径 String baseModelOutputDir = PathKit.getWebRootPath() + "/src/main/java/en/model/base"; // model 使用的包 (MappingKit 默认使用的包) String modelPackageName = "en.model"; // model 文件保存路径 (MappingKit 和 DataDictionary 文件默认保存路径) String modelOutputDir = baseModelOutputDir + "/.."; // 创建生成 Generator generator = new Generator(getDataSource(), baseModelPackageName, baseModelOutputDir, modelPackageName, modelOutputDir); // 设置是否生成链式 setter 方法 generator.setGenerateChainSetter(false); // 添加不需要生成的表名 generator.addExcludedTable(getExcTab("exclude_")); // 设置是否 Model 中生 dao 对象 generator.setGenerateDaoInModel(true); // 设置是否生成链式 setter 方法 generator.setGenerateChainSetter(true); // 设置是否生成字典文件 generator.setGenerateDataDictionary(true); // 设置要被移除的表名前用于生成modelName。例如 "osc_user",移除前 "osc_"后生成的model名为 "User"而非 OscUser generator.setRemovedTableNamePrefixes("t_"); // 生成 generator.generate(); } private static String[] getExcTab(String preName) { String sql = "SELECT table_name from information_schema.tables WHERE table_name LIKE '" + preName + "%'"; List<String> list = new ArrayList<String>(); Connection conn = null; try { conn = getDataSource().getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { list.add(rs.getString(1)); } } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } String[] s = new String[list.size()]; for (int i = 0; i < list.size(); i++) { s[i] = list.get(i); } return s; } }
Miracle287/environment
src/main/java/en/model/_JFinalDemoGenerator.java
836
/** * demo 仅表达最为粗浅的 jfinal 用法,更为有价的实用的企业级用法 * 详见 JFinal 俱乐部: http://jfinal.com/club * * 在数据库表有任何变动时,运行 main 方法,极速响应变化进行代码重 */
block_comment
zh-cn
package en.model; import com.jfinal.kit.PathKit; import com.jfinal.kit.PropKit; import com.jfinal.plugin.activerecord.generator.Generator; import com.jfinal.plugin.druid.DruidPlugin; import en.DemoConfig; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; /** * dem <SUF>*/ public class _JFinalDemoGenerator { public static DataSource getDataSource() { PropKit.use("application.properties"); DruidPlugin druidPlugin = DemoConfig.createDruidPlugin(); druidPlugin.start(); return druidPlugin.getDataSource(); } public static void main(String[] args) { // base model 使用的包 String baseModelPackageName = "en.model.base"; // base model 文件保存路径 String baseModelOutputDir = PathKit.getWebRootPath() + "/src/main/java/en/model/base"; // model 使用的包 (MappingKit 默认使用的包) String modelPackageName = "en.model"; // model 文件保存路径 (MappingKit 和 DataDictionary 文件默认保存路径) String modelOutputDir = baseModelOutputDir + "/.."; // 创建生成 Generator generator = new Generator(getDataSource(), baseModelPackageName, baseModelOutputDir, modelPackageName, modelOutputDir); // 设置是否生成链式 setter 方法 generator.setGenerateChainSetter(false); // 添加不需要生成的表名 generator.addExcludedTable(getExcTab("exclude_")); // 设置是否 Model 中生 dao 对象 generator.setGenerateDaoInModel(true); // 设置是否生成链式 setter 方法 generator.setGenerateChainSetter(true); // 设置是否生成字典文件 generator.setGenerateDataDictionary(true); // 设置要被移除的表名前用于生成modelName。例如 "osc_user",移除前 "osc_"后生成的model名为 "User"而非 OscUser generator.setRemovedTableNamePrefixes("t_"); // 生成 generator.generate(); } private static String[] getExcTab(String preName) { String sql = "SELECT table_name from information_schema.tables WHERE table_name LIKE '" + preName + "%'"; List<String> list = new ArrayList<String>(); Connection conn = null; try { conn = getDataSource().getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql); while (rs.next()) { list.add(rs.getString(1)); } } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } String[] s = new String[list.size()]; for (int i = 0; i < list.size(); i++) { s[i] = list.get(i); } return s; } }
false
719
65
836
78
827
70
836
78
1,072
113
false
false
false
false
false
true
62237_0
package com.nageoffer.shortlink.project.mq.producer; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.util.Map; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.SHORT_LINK_STATS_STREAM_TOPIC_KEY; /** * 短链接监控状态保存消息队列生产者 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Component @RequiredArgsConstructor public class ShortLinkStatsSaveProducer { private final StringRedisTemplate stringRedisTemplate; /** * 发送延迟消费短链接统计 */ public void send(Map<String, String> producerMap) { stringRedisTemplate.opsForStream().add(SHORT_LINK_STATS_STREAM_TOPIC_KEY, producerMap); } }
MiracleStep/shortlink
project/src/main/java/com/nageoffer/shortlink/project/mq/producer/ShortLinkStatsSaveProducer.java
232
/** * 短链接监控状态保存消息队列生产者 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */
block_comment
zh-cn
package com.nageoffer.shortlink.project.mq.producer; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import java.util.Map; import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.SHORT_LINK_STATS_STREAM_TOPIC_KEY; /** * 短链接 <SUF>*/ @Component @RequiredArgsConstructor public class ShortLinkStatsSaveProducer { private final StringRedisTemplate stringRedisTemplate; /** * 发送延迟消费短链接统计 */ public void send(Map<String, String> producerMap) { stringRedisTemplate.opsForStream().add(SHORT_LINK_STATS_STREAM_TOPIC_KEY, producerMap); } }
false
179
44
232
49
223
42
232
49
317
79
false
false
false
false
false
true
52509_3
package com.mixiaoxiao.weather.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.RectF; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; import com.mixiaoxiao.weather.MainActivity; import com.mixiaoxiao.weather.api.entity.Aqi; import com.mixiaoxiao.weather.api.entity.City; /** * 空气质量的弧形“表” 10行 120dp * * @author Mixiaoxiao * */ public class AqiView extends View { private final float density; // private float lineSize;//每一行高度 private TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); private RectF rectF = new RectF(); private City aqiCity; public AqiView(Context context, AttributeSet attrs) { super(context, attrs); density = context.getResources().getDisplayMetrics().density; textPaint.setTextAlign(Align.CENTER); if(isInEditMode()){ return; } textPaint.setTypeface(MainActivity.getTypeface(context)); } @Override protected void onDraw(Canvas canvas) { // super.onDraw(canvas); final float w = getWidth(); final float h = getHeight(); if (w <= 0 || h <= 0) { return; } final float lineSize = h / 10f;// 大约是12dp if (aqiCity == null) { textPaint.setStyle(Style.FILL); textPaint.setTextSize(lineSize * 1.25f); textPaint.setColor(0xaaffffff); canvas.drawText("暂无数据", w / 2f, h / 2f, textPaint); return; } float currAqiPercent = -1f; try { currAqiPercent = Float.valueOf(aqiCity.aqi) / 500f;// 污染% currAqiPercent = Math.min(currAqiPercent, 1f); } catch (Exception e) { e.printStackTrace(); } // canvas.drawColor(0x33ffffff); float aqiArcRadius = lineSize * 4f; textPaint.setStyle(Style.STROKE); textPaint.setStrokeWidth(lineSize * 1); textPaint.setColor(0x55ffffff); rectF.set(-aqiArcRadius, -aqiArcRadius, aqiArcRadius, aqiArcRadius); final int saveCount = canvas.save(); canvas.translate(w / 2f, h / 2f); // draw aqi restPercent arc final float startAngle = -210f; final float sweepAngle = 240f; canvas.drawArc(rectF, startAngle + sweepAngle * currAqiPercent, sweepAngle * (1f - currAqiPercent), false, textPaint); if (currAqiPercent >= 0f) { // draw aqi aqiPercent arc textPaint.setColor(0x99ffffff); canvas.drawArc(rectF, startAngle, sweepAngle * currAqiPercent, false, textPaint); // draw aqi arc center circle textPaint.setColor(0xffffffff); textPaint.setStrokeWidth(lineSize / 8f); canvas.drawCircle(0, 0, lineSize / 3f, textPaint); // draw aqi number and text textPaint.setStyle(Style.FILL); textPaint.setTextSize(lineSize * 1.5f); textPaint.setColor(0xffffffff); try { canvas.drawText(aqiCity.aqi + "", 0, lineSize * 3, textPaint); } catch (Exception e) { } textPaint.setTextSize(lineSize * 1f); textPaint.setColor(0x88ffffff); try { canvas.drawText(aqiCity.qlty + "", 0, lineSize * 4.25f, textPaint); } catch (Exception e) { } // draw the aqi line canvas.rotate(startAngle + sweepAngle * currAqiPercent - 180f); textPaint.setStyle(Style.STROKE); textPaint.setColor(0xffffffff); float startX = lineSize / 3f; canvas.drawLine(-startX, 0, -lineSize * 4.5f, 0, textPaint); } canvas.restoreToCount(saveCount); } public void setData(Aqi aqi) { if (aqi != null && aqi.city != null) { this.aqiCity = aqi.city; invalidate(); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // this.lineSize = h / 10f; } }
Mixiaoxiao/Weather
WeatherGithub/src/com/mixiaoxiao/weather/widget/AqiView.java
1,301
// 大约是12dp
line_comment
zh-cn
package com.mixiaoxiao.weather.widget; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.RectF; import android.text.TextPaint; import android.util.AttributeSet; import android.view.View; import com.mixiaoxiao.weather.MainActivity; import com.mixiaoxiao.weather.api.entity.Aqi; import com.mixiaoxiao.weather.api.entity.City; /** * 空气质量的弧形“表” 10行 120dp * * @author Mixiaoxiao * */ public class AqiView extends View { private final float density; // private float lineSize;//每一行高度 private TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); private RectF rectF = new RectF(); private City aqiCity; public AqiView(Context context, AttributeSet attrs) { super(context, attrs); density = context.getResources().getDisplayMetrics().density; textPaint.setTextAlign(Align.CENTER); if(isInEditMode()){ return; } textPaint.setTypeface(MainActivity.getTypeface(context)); } @Override protected void onDraw(Canvas canvas) { // super.onDraw(canvas); final float w = getWidth(); final float h = getHeight(); if (w <= 0 || h <= 0) { return; } final float lineSize = h / 10f;// 大约 <SUF> if (aqiCity == null) { textPaint.setStyle(Style.FILL); textPaint.setTextSize(lineSize * 1.25f); textPaint.setColor(0xaaffffff); canvas.drawText("暂无数据", w / 2f, h / 2f, textPaint); return; } float currAqiPercent = -1f; try { currAqiPercent = Float.valueOf(aqiCity.aqi) / 500f;// 污染% currAqiPercent = Math.min(currAqiPercent, 1f); } catch (Exception e) { e.printStackTrace(); } // canvas.drawColor(0x33ffffff); float aqiArcRadius = lineSize * 4f; textPaint.setStyle(Style.STROKE); textPaint.setStrokeWidth(lineSize * 1); textPaint.setColor(0x55ffffff); rectF.set(-aqiArcRadius, -aqiArcRadius, aqiArcRadius, aqiArcRadius); final int saveCount = canvas.save(); canvas.translate(w / 2f, h / 2f); // draw aqi restPercent arc final float startAngle = -210f; final float sweepAngle = 240f; canvas.drawArc(rectF, startAngle + sweepAngle * currAqiPercent, sweepAngle * (1f - currAqiPercent), false, textPaint); if (currAqiPercent >= 0f) { // draw aqi aqiPercent arc textPaint.setColor(0x99ffffff); canvas.drawArc(rectF, startAngle, sweepAngle * currAqiPercent, false, textPaint); // draw aqi arc center circle textPaint.setColor(0xffffffff); textPaint.setStrokeWidth(lineSize / 8f); canvas.drawCircle(0, 0, lineSize / 3f, textPaint); // draw aqi number and text textPaint.setStyle(Style.FILL); textPaint.setTextSize(lineSize * 1.5f); textPaint.setColor(0xffffffff); try { canvas.drawText(aqiCity.aqi + "", 0, lineSize * 3, textPaint); } catch (Exception e) { } textPaint.setTextSize(lineSize * 1f); textPaint.setColor(0x88ffffff); try { canvas.drawText(aqiCity.qlty + "", 0, lineSize * 4.25f, textPaint); } catch (Exception e) { } // draw the aqi line canvas.rotate(startAngle + sweepAngle * currAqiPercent - 180f); textPaint.setStyle(Style.STROKE); textPaint.setColor(0xffffffff); float startX = lineSize / 3f; canvas.drawLine(-startX, 0, -lineSize * 4.5f, 0, textPaint); } canvas.restoreToCount(saveCount); } public void setData(Aqi aqi) { if (aqi != null && aqi.city != null) { this.aqiCity = aqi.city; invalidate(); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // this.lineSize = h / 10f; } }
false
1,082
8
1,301
7
1,271
7
1,301
7
1,514
10
false
false
false
false
false
true
57217_2
package com.motiedsune.system.bots.model.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.time.LocalDateTime; /** * 用途: 用于记录早安和晚安 * * @author MoTIEdsuNe * @date 2023-12-07 星期四 */ @Data @TableName("BOT_GREETING") public class BotGreeting extends BaseEntity { @TableId(type = IdType.AUTO) private Long id; // 触发用户 id private Long userId; // 早安、晚安、午安等 private String type; // 记录时间 private LocalDateTime recordTime; // 记录地点(触发时的 chatId) private Long recordId; }
MoTIEdsuNe/suihan-bot
src/main/java/com/motiedsune/system/bots/model/entity/BotGreeting.java
220
// 早安、晚安、午安等
line_comment
zh-cn
package com.motiedsune.system.bots.model.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.time.LocalDateTime; /** * 用途: 用于记录早安和晚安 * * @author MoTIEdsuNe * @date 2023-12-07 星期四 */ @Data @TableName("BOT_GREETING") public class BotGreeting extends BaseEntity { @TableId(type = IdType.AUTO) private Long id; // 触发用户 id private Long userId; // 早安 <SUF> private String type; // 记录时间 private LocalDateTime recordTime; // 记录地点(触发时的 chatId) private Long recordId; }
false
186
11
220
12
212
9
220
12
288
17
false
false
false
false
false
true
57654_6
package com.mob.analysdk.demo; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.mob.analysdk.AnalySDK; import com.mob.game.GameUserEvent; import com.mob.game.PayEvent; import com.mob.game.RoleEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; /** * Created by yjin on 2018/1/29. */ public class GameActivity extends Activity implements View.OnClickListener { private boolean isOnlyEvent; private ArrayList<String> onlyEventTags; private Random random; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); onlyEventTags = new ArrayList<String>(); random = new Random(); init(); } private void init(){ findViewById(R.id.payEvent).setOnClickListener(this); findViewById(R.id.userCreate).setOnClickListener(this); findViewById(R.id.userLogin).setOnClickListener(this); findViewById(R.id.userUpdate).setOnClickListener(this); findViewById(R.id.roleCreate).setOnClickListener(this); findViewById(R.id.roleLogin).setOnClickListener(this); findViewById(R.id.roleUpdate).setOnClickListener(this); findViewById(R.id.setEventOnly).setOnClickListener(this); findViewById(R.id.setEventStack).setOnClickListener(this); findViewById(R.id.behaviorStart).setOnClickListener(this); findViewById(R.id.behaviorEnd).setOnClickListener(this); } @Override protected void onResume() { super.onResume(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("params", "openGamePage"); AnalySDK.behaviorStart("GamePage", map); } @Override protected void onPause() { super.onPause(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("params", "closeGamePage"); AnalySDK.behaviorEnd("GamePage", map); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.payEvent: trackPayEvent(); break; case R.id.userCreate: userRegist(); break; case R.id.userLogin: userLogin(); break; case R.id.userUpdate: userUpdate(); break; case R.id.roleCreate: roleCreate(); break; case R.id.roleLogin: roleLogin(); break; case R.id.roleUpdate: roleUpdate(); break; case R.id.behaviorStart: if (isOnlyEvent) { Object object = new Object(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("onlyEventTag", String.valueOf(object.hashCode())); onlyEventTags.add(String.valueOf(object.hashCode())); AnalySDK.behaviorStart("gameEvent", String.valueOf(object.hashCode()), map); } else { AnalySDK.behaviorStart("stackEvent", null); } break; case R.id.behaviorEnd: if (isOnlyEvent) { String onlyEventTag = "test"; if (onlyEventTags.size() > 0) { onlyEventTag = onlyEventTags.get(random.nextInt(onlyEventTags.size())); } HashMap<String, Object> map = new HashMap<String, Object>(); map.put("onlyEventTag", onlyEventTag); onlyEventTags.remove(onlyEventTag); AnalySDK.behaviorEnd("gameEvent", onlyEventTag, map); } else { AnalySDK.behaviorEnd("stackEvent", null); } break; case R.id.setEventStack: isOnlyEvent = false; break; case R.id.setEventOnly: isOnlyEvent = true; break; } } private static PayEvent createPayEvent(){ PayEvent payEvent = new PayEvent("12313123","hehheh"); payEvent.payMoney = 33; payEvent.payContent = "月卡"; payEvent.payType = "微信"; payEvent.payActivity = "圣诞活动"; payEvent.payDiscount = 12; payEvent.discountReason = "新用户打折"; return payEvent; } private static GameUserEvent createUserEvent(){ GameUserEvent gameUserEvent = new GameUserEvent("1231312","小伙子"); gameUserEvent.regType = "微信"; gameUserEvent.regChannel ="应用宝"; gameUserEvent.userType = "测试账号"; gameUserEvent.addication = "是"; gameUserEvent.money = 12; gameUserEvent.gender = "男"; gameUserEvent.county = "中国"; gameUserEvent.province = "上海"; gameUserEvent.city = "上海"; gameUserEvent.age = 19; gameUserEvent.constellation ="处女"; gameUserEvent.zodiac = "long"; gameUserEvent.nickname = "西装情兽"; return gameUserEvent; } private static RoleEvent createRoleEvent(){ RoleEvent roleEvent = new RoleEvent("23123131","小米子"); roleEvent.roServer ="绝命一区"; roleEvent.roName = "剥皮人"; roleEvent.roCareer = "九魂道人"; roleEvent.roLevel = 999+1; roleEvent.roVip = "vip4"; roleEvent.roRankLevel = "青铜"; roleEvent.roEnergy = 32; roleEvent.roMoney = 55; roleEvent.roCoin = 33; roleEvent.roSource1 = 11; roleEvent.roSource2 = 22; roleEvent.roSource3 =33; roleEvent.roSource4 = 44; return roleEvent; } /** * 支付事件统计 */ public static synchronized void trackPayEvent(){ AnalySDK.trackPayEvent(createPayEvent()); } /** * 用户注册 */ public static synchronized void userRegist(){ AnalySDK.userRegist(createUserEvent()); } /** * 用户登记 */ public static synchronized void userLogin(){ AnalySDK.userLogin(createUserEvent()); } /** * 用户信息更新 */ public static synchronized void userUpdate(){ AnalySDK.userUpdate(createUserEvent()); } /** * 角色创建 */ public static synchronized void roleCreate(){ AnalySDK.roleCreate(createRoleEvent()); } /** * 角色登录 */ public static synchronized void roleLogin(){ AnalySDK.roleLogin(createRoleEvent()); } /** * 角色信息更新 */ public static synchronized void roleUpdate(){ AnalySDK.roleUpdate(createRoleEvent()); } }
MobClub/AnalySDK-For-Android
AnalySDKSample/Sample/src/com/mob/analysdk/demo/GameActivity.java
1,810
/** * 角色登录 */
block_comment
zh-cn
package com.mob.analysdk.demo; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.mob.analysdk.AnalySDK; import com.mob.game.GameUserEvent; import com.mob.game.PayEvent; import com.mob.game.RoleEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.Random; /** * Created by yjin on 2018/1/29. */ public class GameActivity extends Activity implements View.OnClickListener { private boolean isOnlyEvent; private ArrayList<String> onlyEventTags; private Random random; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_game); onlyEventTags = new ArrayList<String>(); random = new Random(); init(); } private void init(){ findViewById(R.id.payEvent).setOnClickListener(this); findViewById(R.id.userCreate).setOnClickListener(this); findViewById(R.id.userLogin).setOnClickListener(this); findViewById(R.id.userUpdate).setOnClickListener(this); findViewById(R.id.roleCreate).setOnClickListener(this); findViewById(R.id.roleLogin).setOnClickListener(this); findViewById(R.id.roleUpdate).setOnClickListener(this); findViewById(R.id.setEventOnly).setOnClickListener(this); findViewById(R.id.setEventStack).setOnClickListener(this); findViewById(R.id.behaviorStart).setOnClickListener(this); findViewById(R.id.behaviorEnd).setOnClickListener(this); } @Override protected void onResume() { super.onResume(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("params", "openGamePage"); AnalySDK.behaviorStart("GamePage", map); } @Override protected void onPause() { super.onPause(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("params", "closeGamePage"); AnalySDK.behaviorEnd("GamePage", map); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.payEvent: trackPayEvent(); break; case R.id.userCreate: userRegist(); break; case R.id.userLogin: userLogin(); break; case R.id.userUpdate: userUpdate(); break; case R.id.roleCreate: roleCreate(); break; case R.id.roleLogin: roleLogin(); break; case R.id.roleUpdate: roleUpdate(); break; case R.id.behaviorStart: if (isOnlyEvent) { Object object = new Object(); HashMap<String, Object> map = new HashMap<String, Object>(); map.put("onlyEventTag", String.valueOf(object.hashCode())); onlyEventTags.add(String.valueOf(object.hashCode())); AnalySDK.behaviorStart("gameEvent", String.valueOf(object.hashCode()), map); } else { AnalySDK.behaviorStart("stackEvent", null); } break; case R.id.behaviorEnd: if (isOnlyEvent) { String onlyEventTag = "test"; if (onlyEventTags.size() > 0) { onlyEventTag = onlyEventTags.get(random.nextInt(onlyEventTags.size())); } HashMap<String, Object> map = new HashMap<String, Object>(); map.put("onlyEventTag", onlyEventTag); onlyEventTags.remove(onlyEventTag); AnalySDK.behaviorEnd("gameEvent", onlyEventTag, map); } else { AnalySDK.behaviorEnd("stackEvent", null); } break; case R.id.setEventStack: isOnlyEvent = false; break; case R.id.setEventOnly: isOnlyEvent = true; break; } } private static PayEvent createPayEvent(){ PayEvent payEvent = new PayEvent("12313123","hehheh"); payEvent.payMoney = 33; payEvent.payContent = "月卡"; payEvent.payType = "微信"; payEvent.payActivity = "圣诞活动"; payEvent.payDiscount = 12; payEvent.discountReason = "新用户打折"; return payEvent; } private static GameUserEvent createUserEvent(){ GameUserEvent gameUserEvent = new GameUserEvent("1231312","小伙子"); gameUserEvent.regType = "微信"; gameUserEvent.regChannel ="应用宝"; gameUserEvent.userType = "测试账号"; gameUserEvent.addication = "是"; gameUserEvent.money = 12; gameUserEvent.gender = "男"; gameUserEvent.county = "中国"; gameUserEvent.province = "上海"; gameUserEvent.city = "上海"; gameUserEvent.age = 19; gameUserEvent.constellation ="处女"; gameUserEvent.zodiac = "long"; gameUserEvent.nickname = "西装情兽"; return gameUserEvent; } private static RoleEvent createRoleEvent(){ RoleEvent roleEvent = new RoleEvent("23123131","小米子"); roleEvent.roServer ="绝命一区"; roleEvent.roName = "剥皮人"; roleEvent.roCareer = "九魂道人"; roleEvent.roLevel = 999+1; roleEvent.roVip = "vip4"; roleEvent.roRankLevel = "青铜"; roleEvent.roEnergy = 32; roleEvent.roMoney = 55; roleEvent.roCoin = 33; roleEvent.roSource1 = 11; roleEvent.roSource2 = 22; roleEvent.roSource3 =33; roleEvent.roSource4 = 44; return roleEvent; } /** * 支付事件统计 */ public static synchronized void trackPayEvent(){ AnalySDK.trackPayEvent(createPayEvent()); } /** * 用户注册 */ public static synchronized void userRegist(){ AnalySDK.userRegist(createUserEvent()); } /** * 用户登记 */ public static synchronized void userLogin(){ AnalySDK.userLogin(createUserEvent()); } /** * 用户信息更新 */ public static synchronized void userUpdate(){ AnalySDK.userUpdate(createUserEvent()); } /** * 角色创建 */ public static synchronized void roleCreate(){ AnalySDK.roleCreate(createRoleEvent()); } /** * 角色登 <SUF>*/ public static synchronized void roleLogin(){ AnalySDK.roleLogin(createRoleEvent()); } /** * 角色信息更新 */ public static synchronized void roleUpdate(){ AnalySDK.roleUpdate(createRoleEvent()); } }
false
1,481
10
1,810
8
1,796
9
1,810
8
2,200
12
false
false
false
false
false
true
51615_4
/** * The MIT License (MIT) * * Copyright (c) 2014 MoboPlayer.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.clov4r.moboplayer.android.nil.codec.activity; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.PorterDuff.Mode; import android.os.Bundle; import android.os.Environment; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.Toast; import com.clov4r.moboplayer.android.nil.codec.ScreenShotLibJni; import com.clov4r.moboplayer.android.nil.codec.SubtitleJni; import com.clov4r.moboplayer.android.nil.codec.ScreenShotLibJni.OnBitmapCreatedListener; public class MoboThumbnailTestActivity extends Activity { String videoName = "/sdcard/Movies/静流-恋文.mkv";// [阳光电影www.ygdy8.com].安妮:纽约奇缘.BD.720p.中英双字幕.rmvb //rtsp://192.168.42.1/tmp/fuse_d/share/2015-01-01-16-50-47.MP4 final String img_save_path = Environment.getExternalStorageDirectory() + "/mobo_screen_shot_%d.png"; int index = 1; LinearLayout layout; ImageView imageView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); imageView = new ImageView(this); SubtitleJni h = new SubtitleJni(); String libpath = getFilesDir().getParent() + "/lib/"; String libname = "libffmpeg.so";// libffmpeg_armv7_neon.so h.loadFFmpegLibs(libpath, libname); Button button = new Button(this); layout.addView(button); layout.addView(imageView); button.setText("截图"); setContentView(layout); button.setOnClickListener(mOnClickListener); } Bitmap bitmap = null; int flag = 1; int time = 165;//纽约奇缘第3600 + 1200 + 57秒花屏 OnClickListener mOnClickListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // ScreenShotLibJni.getInstance().setOnBitmapCreatedListener( // mOnBitmapCreatedListener); // if (flag++ % 2 == 0) // bitmap=ScreenShotLibJni.getInstance().getScreenShot(videoName, // "/sdcard/test.png", 1, 150, 150);// // else // bitmap=ScreenShotLibJni.getInstance().getIDRFrameThumbnail(videoName, // "/sdcard/test.png", 0, 0); // time += 10; // bitmap=ScreenShotLibJni.getInstance().getScreenShot(videoName, // "/sdcard/test.png", time, 1280, 720);// if(bitmap!=null){ imageView.setImageBitmap(null); bitmap.recycle(); } // long currentTime = System.currentTimeMillis(); // Log.e("", "getKeyFrameScreenShot---current=" + currentTime); // bitmap = ScreenShotLibJni.getInstance().getKeyFrameScreenShot_2( // videoName, "/sdcard/test.png", time, 1280, 720); // currentTime = System.currentTimeMillis(); // Log.e("", "getKeyFrameScreenShot---current=" + currentTime); // // currentTime = System.currentTimeMillis(); // Log.e("", "getIDRFrameThumbnail---current=" + currentTime); // bitmap = ScreenShotLibJni.getInstance().getIDRFrameThumbnail( // videoName, "/sdcard/test.png", 1280, 720); // // currentTime = System.currentTimeMillis(); Log.e("", "gen time = " + time); // videoName // ="/sdcard/电影/[欧美][预告][长发公主][高清RMVB][1280&times;720][中文字幕].rmvb"; // for(int i = 0;i< 20; i++){ final int index = i; new Thread(){ @Override public void run(){ bitmap=ScreenShotLibJni.getInstance().getScreenShot(videoName, "/sdcard/test_"+ index +".png", time, 1280, 720);// } }.start(); time += 3; } // RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap); // roundedBitmapDrawable.setCornerRadius(6); //设置圆角半径为正方形边长的一半 // roundedBitmapDrawable.setAntiAlias(true); // imageView.setImageDrawable(roundedBitmapDrawable); // Bitmap tmpBitmap = getRoundedCornerBitmap(bitmap, 6); // bitmap.recycle(); // imageView.setImageBitmap(tmpBitmap); // layout.addView(imageView); imageView.setScaleType(ScaleType.CENTER_CROP); imageView.setImageBitmap(bitmap); // Intent intent=new Intent(); // intent.setComponent(new // ComponentName("com.clov4r.moboplayer.android.nil", // "com.clov4r.moboplayer.android.nil.MainInterface")); // // intent.setData(Uri.parse(videoName)); // startActivity(intent); } }; public Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) { try { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight())); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(Color.BLACK); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); final Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); canvas.drawBitmap(bitmap, src, rect, paint); return output; } catch (Exception e) { return bitmap; } } OnBitmapCreatedListener mOnBitmapCreatedListener = new OnBitmapCreatedListener() { @Override public void onBitmapCreated(final Bitmap bitmap, String fileName, String screenshotSavePath) { // TODO Auto-generated method stub // runOnUiThread(new Runnable() { // @Override // public void run() { // TODO Auto-generated method stub layout.removeView(imageView); layout.addView(imageView); imageView.setImageBitmap(bitmap); // } // }); } @Override public void onBitmapCreatedFailed(String videoPath) { // TODO Auto-generated method stub Toast.makeText(MoboThumbnailTestActivity.this, "截图失败", Toast.LENGTH_SHORT).show(); } }; }
MoboPlayer/NdkTest
src/com/clov4r/moboplayer/android/nil/codec/activity/MoboThumbnailTestActivity.java
2,266
//纽约奇缘第3600 + 1200 + 57秒花屏
line_comment
zh-cn
/** * The MIT License (MIT) * * Copyright (c) 2014 MoboPlayer.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.clov4r.moboplayer.android.nil.codec.activity; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.PorterDuff.Mode; import android.os.Bundle; import android.os.Environment; import android.support.v4.graphics.drawable.RoundedBitmapDrawable; import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ImageView.ScaleType; import android.widget.LinearLayout; import android.widget.Toast; import com.clov4r.moboplayer.android.nil.codec.ScreenShotLibJni; import com.clov4r.moboplayer.android.nil.codec.SubtitleJni; import com.clov4r.moboplayer.android.nil.codec.ScreenShotLibJni.OnBitmapCreatedListener; public class MoboThumbnailTestActivity extends Activity { String videoName = "/sdcard/Movies/静流-恋文.mkv";// [阳光电影www.ygdy8.com].安妮:纽约奇缘.BD.720p.中英双字幕.rmvb //rtsp://192.168.42.1/tmp/fuse_d/share/2015-01-01-16-50-47.MP4 final String img_save_path = Environment.getExternalStorageDirectory() + "/mobo_screen_shot_%d.png"; int index = 1; LinearLayout layout; ImageView imageView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); imageView = new ImageView(this); SubtitleJni h = new SubtitleJni(); String libpath = getFilesDir().getParent() + "/lib/"; String libname = "libffmpeg.so";// libffmpeg_armv7_neon.so h.loadFFmpegLibs(libpath, libname); Button button = new Button(this); layout.addView(button); layout.addView(imageView); button.setText("截图"); setContentView(layout); button.setOnClickListener(mOnClickListener); } Bitmap bitmap = null; int flag = 1; int time = 165;//纽约 <SUF> OnClickListener mOnClickListener = new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub // ScreenShotLibJni.getInstance().setOnBitmapCreatedListener( // mOnBitmapCreatedListener); // if (flag++ % 2 == 0) // bitmap=ScreenShotLibJni.getInstance().getScreenShot(videoName, // "/sdcard/test.png", 1, 150, 150);// // else // bitmap=ScreenShotLibJni.getInstance().getIDRFrameThumbnail(videoName, // "/sdcard/test.png", 0, 0); // time += 10; // bitmap=ScreenShotLibJni.getInstance().getScreenShot(videoName, // "/sdcard/test.png", time, 1280, 720);// if(bitmap!=null){ imageView.setImageBitmap(null); bitmap.recycle(); } // long currentTime = System.currentTimeMillis(); // Log.e("", "getKeyFrameScreenShot---current=" + currentTime); // bitmap = ScreenShotLibJni.getInstance().getKeyFrameScreenShot_2( // videoName, "/sdcard/test.png", time, 1280, 720); // currentTime = System.currentTimeMillis(); // Log.e("", "getKeyFrameScreenShot---current=" + currentTime); // // currentTime = System.currentTimeMillis(); // Log.e("", "getIDRFrameThumbnail---current=" + currentTime); // bitmap = ScreenShotLibJni.getInstance().getIDRFrameThumbnail( // videoName, "/sdcard/test.png", 1280, 720); // // currentTime = System.currentTimeMillis(); Log.e("", "gen time = " + time); // videoName // ="/sdcard/电影/[欧美][预告][长发公主][高清RMVB][1280&times;720][中文字幕].rmvb"; // for(int i = 0;i< 20; i++){ final int index = i; new Thread(){ @Override public void run(){ bitmap=ScreenShotLibJni.getInstance().getScreenShot(videoName, "/sdcard/test_"+ index +".png", time, 1280, 720);// } }.start(); time += 3; } // RoundedBitmapDrawable roundedBitmapDrawable = RoundedBitmapDrawableFactory.create(getResources(), bitmap); // roundedBitmapDrawable.setCornerRadius(6); //设置圆角半径为正方形边长的一半 // roundedBitmapDrawable.setAntiAlias(true); // imageView.setImageDrawable(roundedBitmapDrawable); // Bitmap tmpBitmap = getRoundedCornerBitmap(bitmap, 6); // bitmap.recycle(); // imageView.setImageBitmap(tmpBitmap); // layout.addView(imageView); imageView.setScaleType(ScaleType.CENTER_CROP); imageView.setImageBitmap(bitmap); // Intent intent=new Intent(); // intent.setComponent(new // ComponentName("com.clov4r.moboplayer.android.nil", // "com.clov4r.moboplayer.android.nil.MainInterface")); // // intent.setData(Uri.parse(videoName)); // startActivity(intent); } }; public Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) { try { Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); final Paint paint = new Paint(); final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); final RectF rectF = new RectF(new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight())); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(Color.BLACK); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); final Rect src = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight()); canvas.drawBitmap(bitmap, src, rect, paint); return output; } catch (Exception e) { return bitmap; } } OnBitmapCreatedListener mOnBitmapCreatedListener = new OnBitmapCreatedListener() { @Override public void onBitmapCreated(final Bitmap bitmap, String fileName, String screenshotSavePath) { // TODO Auto-generated method stub // runOnUiThread(new Runnable() { // @Override // public void run() { // TODO Auto-generated method stub layout.removeView(imageView); layout.addView(imageView); imageView.setImageBitmap(bitmap); // } // }); } @Override public void onBitmapCreatedFailed(String videoPath) { // TODO Auto-generated method stub Toast.makeText(MoboThumbnailTestActivity.this, "截图失败", Toast.LENGTH_SHORT).show(); } }; }
false
1,897
22
2,266
25
2,235
22
2,266
25
2,861
33
false
false
false
false
false
true
48670_1
package cn.academy.block.tileentity; import cn.academy.ACItems; import cn.academy.block.block.ACFluids; import cn.academy.block.container.ContainerPhaseGen; import cn.academy.energy.IFConstants; import cn.academy.item.ItemMatterUnit; import cn.lambdalib2.registry.mc.RegTileEntity; import cn.lambdalib2.s11n.network.NetworkMessage; import cn.lambdalib2.s11n.network.TargetPoints; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.fml.relauncher.Side; /** * @author WeAthFolD */ @RegTileEntity public class TilePhaseGen extends TileGeneratorBase implements IFluidHandler { // 废话~~~ public static final int SLOT_LIQUID_IN = ContainerPhaseGen.SLOT_LIQUID_IN, SLOT_LIQUID_OUT = ContainerPhaseGen.SLOT_LIQUID_OUT, SLOT_OUTPUT = ContainerPhaseGen.SLOT_OUTPUT; // TODO // @RegTileEntity.Render // @SideOnly(Side.CLIENT) // public static RenderPhaseGen renderer; // static final int CONSUME_PER_TICK = 100; static final double GEN_PER_MB = 0.5; int untilSync; public TilePhaseGen() { super("phase_gen", 3, 6000, IFConstants.LATENCY_MK1); } @Override public double getGeneration(double required) { int maxDrain = (int) Math.min(CONSUME_PER_TICK, required / GEN_PER_MB); FluidStack fs = tank.drain(maxDrain, true); return fs == null ? 0 : fs.amount * GEN_PER_MB; } @Override public void update() { super.update(); if(!getWorld().isRemote) { if(++untilSync == 10) { untilSync = 0; sync(); } ItemStack stack; { // Sink in liquid stack = getStackInSlot(SLOT_LIQUID_IN); if(!stack.isEmpty() && isPhaseLiquid(stack) && isOutputSlotAvailable() && (getTankSize() - getLiquidAmount() > PER_UNIT)) { if(stack.getCount() > 0) { tank.fill(new FluidStack(ACFluids.fluidImagProj, PER_UNIT), true); stack.shrink(1); } ItemStack output = getStackInSlot(SLOT_LIQUID_OUT); if(!output.isEmpty()) { output.grow(1); } else { this.setInventorySlotContents(SLOT_LIQUID_OUT, ACItems.matter_unit.create(ItemMatterUnit.MAT_NONE)); } } } { // Output energy stack = getStackInSlot(SLOT_OUTPUT); if(!stack.isEmpty()) this.tryChargeStack(stack); } } } // Fluid handling static final int TANK_SIZE = 8000; static final int PER_UNIT = 1000; protected FluidTank tank = new FluidTank(TANK_SIZE); public int getLiquidAmount() { return tank.getFluidAmount(); } public int getTankSize() { return tank.getCapacity(); } @Override public IFluidTankProperties[] getTankProperties() { FluidTankInfo info = tank.getInfo(); return new IFluidTankProperties[] { new FluidTankProperties(info.fluid, info.capacity) }; } @Override public int fill(FluidStack resource, boolean doFill) { if(resource.getFluid() != ACFluids.fluidImagProj) { return 0; } return tank.fill(resource, doFill); } @Override public FluidStack drain(FluidStack resource, boolean doDrain) { if (resource.getFluid() != ACFluids.fluidImagProj) return null; return tank.drain(resource.amount, doDrain); } @Override public FluidStack drain(int maxDrain, boolean doDrain) { return tank.drain(maxDrain, doDrain); } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); tank.readFromNBT(tag); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); tank.writeToNBT(tag); return tag; } private void sync() { NBTTagCompound nbt = new NBTTagCompound(); writeToNBT(nbt); NetworkMessage.sendToAllAround(TargetPoints.convert(this, 15), this, "MSG_INFO_SYNC", nbt); } @NetworkMessage.Listener(channel="MSG_INFO_SYNC", side= Side.CLIENT) private void onSync(NBTTagCompound nbt) { readFromNBT(nbt); } private boolean isPhaseLiquid(ItemStack stack) { return stack.getItem() == ACItems.matter_unit && ACItems.matter_unit.getMaterial(stack) == ItemMatterUnit.MAT_PHASE_LIQUID; } private boolean isOutputSlotAvailable() { ItemStack stack = getStackInSlot(SLOT_LIQUID_OUT); return stack.isEmpty() || (stack.getItem() == ACItems.matter_unit && ACItems.matter_unit.getMaterial(stack) == ItemMatterUnit.MAT_NONE && stack.getCount() < stack.getMaxStackSize()); } }
MohistMC/AcademyCraft
src/main/java/cn/academy/block/tileentity/TilePhaseGen.java
1,405
// 废话~~~
line_comment
zh-cn
package cn.academy.block.tileentity; import cn.academy.ACItems; import cn.academy.block.block.ACFluids; import cn.academy.block.container.ContainerPhaseGen; import cn.academy.energy.IFConstants; import cn.academy.item.ItemMatterUnit; import cn.lambdalib2.registry.mc.RegTileEntity; import cn.lambdalib2.s11n.network.NetworkMessage; import cn.lambdalib2.s11n.network.TargetPoints; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTank; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; import net.minecraftforge.fml.relauncher.Side; /** * @author WeAthFolD */ @RegTileEntity public class TilePhaseGen extends TileGeneratorBase implements IFluidHandler { // 废话 <SUF> public static final int SLOT_LIQUID_IN = ContainerPhaseGen.SLOT_LIQUID_IN, SLOT_LIQUID_OUT = ContainerPhaseGen.SLOT_LIQUID_OUT, SLOT_OUTPUT = ContainerPhaseGen.SLOT_OUTPUT; // TODO // @RegTileEntity.Render // @SideOnly(Side.CLIENT) // public static RenderPhaseGen renderer; // static final int CONSUME_PER_TICK = 100; static final double GEN_PER_MB = 0.5; int untilSync; public TilePhaseGen() { super("phase_gen", 3, 6000, IFConstants.LATENCY_MK1); } @Override public double getGeneration(double required) { int maxDrain = (int) Math.min(CONSUME_PER_TICK, required / GEN_PER_MB); FluidStack fs = tank.drain(maxDrain, true); return fs == null ? 0 : fs.amount * GEN_PER_MB; } @Override public void update() { super.update(); if(!getWorld().isRemote) { if(++untilSync == 10) { untilSync = 0; sync(); } ItemStack stack; { // Sink in liquid stack = getStackInSlot(SLOT_LIQUID_IN); if(!stack.isEmpty() && isPhaseLiquid(stack) && isOutputSlotAvailable() && (getTankSize() - getLiquidAmount() > PER_UNIT)) { if(stack.getCount() > 0) { tank.fill(new FluidStack(ACFluids.fluidImagProj, PER_UNIT), true); stack.shrink(1); } ItemStack output = getStackInSlot(SLOT_LIQUID_OUT); if(!output.isEmpty()) { output.grow(1); } else { this.setInventorySlotContents(SLOT_LIQUID_OUT, ACItems.matter_unit.create(ItemMatterUnit.MAT_NONE)); } } } { // Output energy stack = getStackInSlot(SLOT_OUTPUT); if(!stack.isEmpty()) this.tryChargeStack(stack); } } } // Fluid handling static final int TANK_SIZE = 8000; static final int PER_UNIT = 1000; protected FluidTank tank = new FluidTank(TANK_SIZE); public int getLiquidAmount() { return tank.getFluidAmount(); } public int getTankSize() { return tank.getCapacity(); } @Override public IFluidTankProperties[] getTankProperties() { FluidTankInfo info = tank.getInfo(); return new IFluidTankProperties[] { new FluidTankProperties(info.fluid, info.capacity) }; } @Override public int fill(FluidStack resource, boolean doFill) { if(resource.getFluid() != ACFluids.fluidImagProj) { return 0; } return tank.fill(resource, doFill); } @Override public FluidStack drain(FluidStack resource, boolean doDrain) { if (resource.getFluid() != ACFluids.fluidImagProj) return null; return tank.drain(resource.amount, doDrain); } @Override public FluidStack drain(int maxDrain, boolean doDrain) { return tank.drain(maxDrain, doDrain); } @Override public void readFromNBT(NBTTagCompound tag) { super.readFromNBT(tag); tank.readFromNBT(tag); } @Override public NBTTagCompound writeToNBT(NBTTagCompound tag) { super.writeToNBT(tag); tank.writeToNBT(tag); return tag; } private void sync() { NBTTagCompound nbt = new NBTTagCompound(); writeToNBT(nbt); NetworkMessage.sendToAllAround(TargetPoints.convert(this, 15), this, "MSG_INFO_SYNC", nbt); } @NetworkMessage.Listener(channel="MSG_INFO_SYNC", side= Side.CLIENT) private void onSync(NBTTagCompound nbt) { readFromNBT(nbt); } private boolean isPhaseLiquid(ItemStack stack) { return stack.getItem() == ACItems.matter_unit && ACItems.matter_unit.getMaterial(stack) == ItemMatterUnit.MAT_PHASE_LIQUID; } private boolean isOutputSlotAvailable() { ItemStack stack = getStackInSlot(SLOT_LIQUID_OUT); return stack.isEmpty() || (stack.getItem() == ACItems.matter_unit && ACItems.matter_unit.getMaterial(stack) == ItemMatterUnit.MAT_NONE && stack.getCount() < stack.getMaxStackSize()); } }
false
1,264
6
1,405
6
1,512
4
1,405
6
1,810
8
false
false
false
false
false
true
41987_2
public class Solution { /** * @param m: An integer m denotes the size of a backpack * @param A: Given n items with size A[i] * @return: The maximum size */ public int backPack(int m, int[] A) { //终极优化 if (A == null || A.length == 0) { return 0; } int n = A.length; boolean[] f = new boolean[m + 1]; f[0] = true; for (int i = 1; i <= m; i++) { f[i] = false; } for (int i = 1; i <= n; i++) { for (int j = m; j >= A[i - 1]; j--) { f[j] |= f[j - A[i - 1]]; } } for (int i = m; i >= 0; i--) { if (f[i]) { return i; } } return 0; //动态规划班 // if (A == null || A.length == 0) { // return 0; // } // int n = A.length; // boolean[][] f = new boolean[n + 1][m + 1]; // f[0][0] = true; // for (int i = 1; i <= m; i++) { // f[0][i] = false; // } // for (int i = 1; i <= n; i++) { // for (int j = 0; j <= m; j++) { // f[i][j] = f[i - 1][j]; // if (j >= A[i - 1]) { // f[i][j] |= f[i - 1][j - A[i - 1]]; // } // } // } // for (int i = m; i >= 0; i--) { // if (f[n][i]) { // return i; // } // } // return 0; // int n = A.length; // int[] f = new int[m + 1]; // for (int i = 0; i < n; i++) { // for (int j = m; j >= A[i]; j--) { // f[j] = Math.max(f[j], f[j - A[i]] + A[i]); // } // } // return f[m]; } } /* 动态规划班思想: ** 时间复杂度:O(MN), ** 优化后空间复杂度:O(M), 难点:不可以用mod2去优化row 算法:f[i][w] = 能否用前i个物品拼出重量w 可以把每个物品的大小当做每个物品的价值,这样就可以用0-1背包的问题解决 */
Mol1122/leetcode
92. Backpack.java
703
//动态规划班
line_comment
zh-cn
public class Solution { /** * @param m: An integer m denotes the size of a backpack * @param A: Given n items with size A[i] * @return: The maximum size */ public int backPack(int m, int[] A) { //终极优化 if (A == null || A.length == 0) { return 0; } int n = A.length; boolean[] f = new boolean[m + 1]; f[0] = true; for (int i = 1; i <= m; i++) { f[i] = false; } for (int i = 1; i <= n; i++) { for (int j = m; j >= A[i - 1]; j--) { f[j] |= f[j - A[i - 1]]; } } for (int i = m; i >= 0; i--) { if (f[i]) { return i; } } return 0; //动态 <SUF> // if (A == null || A.length == 0) { // return 0; // } // int n = A.length; // boolean[][] f = new boolean[n + 1][m + 1]; // f[0][0] = true; // for (int i = 1; i <= m; i++) { // f[0][i] = false; // } // for (int i = 1; i <= n; i++) { // for (int j = 0; j <= m; j++) { // f[i][j] = f[i - 1][j]; // if (j >= A[i - 1]) { // f[i][j] |= f[i - 1][j - A[i - 1]]; // } // } // } // for (int i = m; i >= 0; i--) { // if (f[n][i]) { // return i; // } // } // return 0; // int n = A.length; // int[] f = new int[m + 1]; // for (int i = 0; i < n; i++) { // for (int j = m; j >= A[i]; j--) { // f[j] = Math.max(f[j], f[j - A[i]] + A[i]); // } // } // return f[m]; } } /* 动态规划班思想: ** 时间复杂度:O(MN), ** 优化后空间复杂度:O(M), 难点:不可以用mod2去优化row 算法:f[i][w] = 能否用前i个物品拼出重量w 可以把每个物品的大小当做每个物品的价值,这样就可以用0-1背包的问题解决 */
false
657
4
703
5
760
4
703
5
847
12
false
false
false
false
false
true
65784_31
package com.example.model; import java.io.Serializable; import java.util.Date; import java.util.Set; /** * * 活动信息类 */ public class Activity implements Serializable{ /** * */ private static final long serialVersionUID = 1L; /**活动id*/ private int aId; /**团队,如果是个人活动就为空*/ private Team team; /**活动名称*/ private String name; /**活动简介*/ private String description; /**开始时间*/ private Date startTime; /**结束时间*/ private Date endTime; /**地点*/ private String place; /**提醒时间*/ private Date remindTime; /**活动类型,type为1的时候为团队活动,type为2的时候为任务,type3 是个人活动,type4是单独的活动*/ private int type; /**活动的所有参与者*/ private Set participants; /** * 活动信息类默认构造函数 */ public Activity(){ this.aId = 0; this.name = ""; this.description = ""; this.startTime = new Date(); this.endTime = new Date(); this.place = ""; this.remindTime = new Date(); this.type = 0; this.team = null; this.participants = null; } /** * * * @param activity */ public Activity(Activity activity){ this.aId = activity.getaId(); this.name = activity.getName(); this.description = activity.getDescription(); this.startTime = activity.getStartTime(); this.endTime = activity.getEndTime(); this.place = activity.getPlace(); this.remindTime = activity.getRemindTime(); this.type = activity.getType(); this.team = new Team(activity.getTeam()); this.participants = null; } /** * * 获得活动的Id * @return 活动Id */ public int getaId() { return aId; } /** * * 设置活动的Id * @param aId */ public void setaId(int aId) { this.aId = aId; } /** * * 获得活动名 * @return 活动名 */ public String getName() { return name; } /** * * 设置活动名 * @param name */ public void setName(String name) { this.name = name; } /** * * 获得活动描述 * @return 活动描述 */ public String getDescription() { return description; } /** * * 设置活动描述 * @param description */ public void setDescription(String description) { this.description = description; } /** * * 获得活动描述 * @return 活动描述 */ public Date getStartTime() { return startTime; } /** * * 设置活动开始时间 * @param startTime */ public void setStartTime(Date startTime) { this.startTime = startTime; } /** * * 获得活动结束时间 * @return 活动结束时间 */ public Date getEndTime() { return endTime; } /** * * 设置活动结束时间 * @param endTime */ public void setEndTime(Date endTime) { this.endTime = endTime; } /** * * 获得活动举办地 * @return 活动举办地 */ public String getPlace() { return place; } /** * * 设置活动举办地 * @param place */ public void setPlace(String place) { this.place = place; } /** * * 得到活动提醒时间 * @return 活动提醒时间 */ public Date getRemindTime() { return remindTime; } /** * * 设置活动提醒时间 * @param remindTime */ public void setRemindTime(Date remindTime) { this.remindTime = remindTime; } /** * * 获得活动类型:type为1的时候为团队活动,type为2的时候为任务,type3 是个人活动,type4是单独的活动 * @return 活动类型 */ public int getType() { return type; } /** * * 设置活动类型 * @param type */ public void setType(int type) { this.type = type; } /** * * 获得活动的举办团队 * @return 举办团队 */ public Team getTeam() { return team; } /** * 设置活动的举办团队 * @param team */ public void setTeam(Team team) { this.team = team; } /** * * 获得活动的参与人员列表 * @return 参与人员列表 */ public Set getParticipants() { return participants; } /** * * 设置活动的参与人员 * @param participants */ public void setParticipants(Set participants) { this.participants = participants; } }
MonksTemple/Daily
src/com/example/model/Activity.java
1,347
/** * * 获得活动的参与人员列表 * @return 参与人员列表 */
block_comment
zh-cn
package com.example.model; import java.io.Serializable; import java.util.Date; import java.util.Set; /** * * 活动信息类 */ public class Activity implements Serializable{ /** * */ private static final long serialVersionUID = 1L; /**活动id*/ private int aId; /**团队,如果是个人活动就为空*/ private Team team; /**活动名称*/ private String name; /**活动简介*/ private String description; /**开始时间*/ private Date startTime; /**结束时间*/ private Date endTime; /**地点*/ private String place; /**提醒时间*/ private Date remindTime; /**活动类型,type为1的时候为团队活动,type为2的时候为任务,type3 是个人活动,type4是单独的活动*/ private int type; /**活动的所有参与者*/ private Set participants; /** * 活动信息类默认构造函数 */ public Activity(){ this.aId = 0; this.name = ""; this.description = ""; this.startTime = new Date(); this.endTime = new Date(); this.place = ""; this.remindTime = new Date(); this.type = 0; this.team = null; this.participants = null; } /** * * * @param activity */ public Activity(Activity activity){ this.aId = activity.getaId(); this.name = activity.getName(); this.description = activity.getDescription(); this.startTime = activity.getStartTime(); this.endTime = activity.getEndTime(); this.place = activity.getPlace(); this.remindTime = activity.getRemindTime(); this.type = activity.getType(); this.team = new Team(activity.getTeam()); this.participants = null; } /** * * 获得活动的Id * @return 活动Id */ public int getaId() { return aId; } /** * * 设置活动的Id * @param aId */ public void setaId(int aId) { this.aId = aId; } /** * * 获得活动名 * @return 活动名 */ public String getName() { return name; } /** * * 设置活动名 * @param name */ public void setName(String name) { this.name = name; } /** * * 获得活动描述 * @return 活动描述 */ public String getDescription() { return description; } /** * * 设置活动描述 * @param description */ public void setDescription(String description) { this.description = description; } /** * * 获得活动描述 * @return 活动描述 */ public Date getStartTime() { return startTime; } /** * * 设置活动开始时间 * @param startTime */ public void setStartTime(Date startTime) { this.startTime = startTime; } /** * * 获得活动结束时间 * @return 活动结束时间 */ public Date getEndTime() { return endTime; } /** * * 设置活动结束时间 * @param endTime */ public void setEndTime(Date endTime) { this.endTime = endTime; } /** * * 获得活动举办地 * @return 活动举办地 */ public String getPlace() { return place; } /** * * 设置活动举办地 * @param place */ public void setPlace(String place) { this.place = place; } /** * * 得到活动提醒时间 * @return 活动提醒时间 */ public Date getRemindTime() { return remindTime; } /** * * 设置活动提醒时间 * @param remindTime */ public void setRemindTime(Date remindTime) { this.remindTime = remindTime; } /** * * 获得活动类型:type为1的时候为团队活动,type为2的时候为任务,type3 是个人活动,type4是单独的活动 * @return 活动类型 */ public int getType() { return type; } /** * * 设置活动类型 * @param type */ public void setType(int type) { this.type = type; } /** * * 获得活动的举办团队 * @return 举办团队 */ public Team getTeam() { return team; } /** * 设置活动的举办团队 * @param team */ public void setTeam(Team team) { this.team = team; } /** * * 获得活 <SUF>*/ public Set getParticipants() { return participants; } /** * * 设置活动的参与人员 * @param participants */ public void setParticipants(Set participants) { this.participants = participants; } }
false
1,184
27
1,347
24
1,412
25
1,347
24
1,781
35
false
false
false
false
false
true
33024_45
package Service; import JavaBean.Producter; import Utils.GSBuilder; import java.util.*; /** * Try2LL1主要提供了两个方法————「提取公因子extractCommonFactor」+「消除左递归removeRecursin」 * 类如其名————一切都是为了"尝试将一个非LL1文法转化为等价的LL1文法",即"Try to LL1" */ public class Try2LL1 { /** *【提取公因子】直接在文法gs的基础上进行等价的修改 */ public void extractCommonFactor(Set<Producter> gs){ // 提取公因子之前,先消除隐式的情况 transGs(gs); Map<Character, List<String>> gs2 = GSBuilder.gsHelper(gs); Set<Character> VN = GSBuilder.getVN(gs); // 维护了一个给新的VN命名的候选数组 int k = 0; char[] unUsedCase = getUnUsedCase(gs); for(Character vn : VN){ // 对于每个非终结符(产生式的左侧),都尝试消除左递归 List<String> list = gs2.get(vn); // 不是所有的文法,都能在有限步骤内提取出所有的左公因子。换句话说,明明算法正确,但仍有可能死循环————因此设置一个阀值 int cnt = 10; boolean flag = true; while (flag && cnt > 0){ cnt--; flag = false; // 循环实在是太深了(封装太少的恶果),这里使用了一个flag+here标签实现跳出多层循环后,再次重新循环 here: for(int i = 0; i < list.size(); i++){ String curI = list.get(i); while (curI.length() > 0){ for(int j = i + 1; j < list.size(); j++){ String curJ = list.get(j); if(curJ.indexOf(curI) != 0){ continue; }else{ // 出现公共前缀 String s1 = list.get(i); String s2 = list.get(j); String commonFactor = curI; char newVN = unUsedCase[k++]; String s3 = commonFactor + newVN; list.remove(s1); list.remove(s2); list.add(s3); removeFromGs(gs, vn, s1); removeFromGs(gs, vn, s2); gs.add(new Producter(vn + "->" + s3)); gs.add(new Producter(newVN + "->" + (s1.length() == commonFactor.length() ? "ε" : s1.replaceFirst(commonFactor, "")))); gs.add(new Producter(newVN + "->" + (s2.length() == commonFactor.length() ? "ε" : s2.replaceFirst(commonFactor, "")))); flag = true; break here; } } curI = curI.substring(0, curI.length() - 1); } } } } // 提取公因子之后,删掉不可达的产生式 removeUnReachable(gs); } /** *【消除左递归】直接在文法gs的基础上进行等价的修改 */ public void removeRecursin(Set<Producter> gs){ Set<Character> VN = GSBuilder.getVN(gs); Map<Character, List<String>> gs2 = GSBuilder.gsHelper(gs); int k = 0; char[] unUsedCase = getUnUsedCase(gs); // 消除隐式 transGs(gs); for(Character vn : VN){ List<String> list = gs2.get(vn); List<String> alpha = new ArrayList<>(); List<String> beta = new ArrayList<>(); for(String str : list){ if(str.charAt(0) == vn){ alpha.add(str.substring(1)); }else{ if(str.equals("ε")){ str = ""; } beta.add(str); } } if(alpha.size() > 0){ removeFromGs(gs, vn); char newVN = unUsedCase[k++]; for(String s : beta){ gs.add(new Producter(vn + "->" + s + newVN)); } for(String s : alpha){ gs.add(new Producter(newVN + "->" + s + newVN)); } gs.add(new Producter(newVN + "->" + "ε")); } } // 同样,删掉不可到达的生成式 removeUnReachable(gs); } // 简单的功能性方法————比如目前已有的VN有SABC,这个方法会返回除了这几个之外的所有大写字母,作为候选 private char[] getUnUsedCase(Set<Producter> gs){ Set<Character> set = new HashSet<>(); Set<Character> VN = GSBuilder.getVN(gs); for(int i = 0; i < 26; i++){ set.add((char)('A' + i)); } set.removeAll(VN); char[] res = new char[set.size()]; int k = 0; for(char c : set){ res[k++] = c; } return res; } /** * 消除隐式 * 在「提取公因子」「消除左递归」之前进行隐式的消除————如果产生式的右部以非终结符(ABC)开头,那么公因子有可能是隐式的;递归同理 */ private void transGs(Set<Producter> gs){ Set<Character> VN = GSBuilder.getVN(gs); boolean flag = true; while (flag){ flag = false; Set<Producter> trash = new HashSet<>(); Set<Producter> wait = new HashSet<>(); for(Producter producter : gs){ Character c = producter.getRight().charAt(0); // 这里多讨论了一下:比如 A->Aa|b,这就属于左递归的范畴。 // 如果执迷于消除全部产生式的右部第一个VN,会死循环的————这就是「左递归」的陷阱,也是之后的工作 if(VN.contains(c) && c != producter.getLeft()){ flag = true; Map<Character, List<String>> gs2 = GSBuilder.gsHelper(gs); List<String> arr = gs2.get(c); trash.add(producter); for(String s : arr){ // 你不能用一个递归的式子去进行首字母的替换 if(s.charAt(0) == c){ continue; } Character newLeft = producter.getLeft(); String newRight = producter.getRight().replaceFirst(String.valueOf(c), s); wait.add(new Producter(newLeft + "->" + newRight)); } } } gs.removeAll(trash); gs.addAll(wait); } } // private void transGs2(Set<Producter> gs){ // Set<Character> VN = GSBuilder.getVN(gs); // List<Character> listVN = new ArrayList<>(VN); // int k = 0; // Map<Character, List<String>> gs2 = GSBuilder.gsHelper(gs); // for(Character vn : listVN){ // Set<Character> availableVN = new HashSet<>(); // for(int i = 0 ; i < k; i++){ // availableVN.add(listVN.get(i)); // } // k++; // List<String> list = gs2.get(vn); // for(String str : list){ // // 左边为vn // // 右边为str // // 右边第一个字母c // char c = str.charAt(0); // if (availableVN.contains(c)){ // removeFromGs(gs, vn, str); // Map<Character, List<String>> gs3 = GSBuilder.gsHelper(gs); // List<String> arr = gs3.get(c); // for(String s : arr){ // // 你不能用一个递归的式子去进行首字母的替换 // if(s.charAt(0) == c){ // continue; // } // gs.add(new Producter(vn + "->" + str.replaceFirst(String.valueOf(c), s))); // } // } // } // } // } /** * 删除不可达 * 在「提取公因子」「消除左递归」之后进行不可达生成式的删除————有些生成式可能会变得不可达,完全可以删掉 */ private void removeUnReachable(Set<Producter> gs){ Set<Character> reachableVN = new HashSet<>(); Set<Character> unreachableVN = GSBuilder.getVN(gs); for(Producter producter : gs){ for(char vn : unreachableVN){ if(producter.getRight().indexOf(vn) >= 0){ reachableVN.add(vn); } } } // 排除"可达到"的非终结符VN,以及S(S作为起始符号,必然是"可到达"的) unreachableVN.removeAll(reachableVN); unreachableVN.remove('S'); Set<Producter> trash = new HashSet<>(); for(Producter producter : gs){ if(unreachableVN.contains(producter.getLeft())){ trash.add(producter); } } gs.removeAll(trash); } // 封装了一个简单的功能:从文法中删除某些产生式 // 的是使上面的代码美观清晰 private void removeFromGs(Set<Producter> gs, Character left, String right){ Set<Producter> trash = new HashSet<>(); for(Producter producter : gs){ if(producter.getLeft() == left && producter.getRight().equals(right)){ trash.add(producter); } } gs.removeAll(trash); } private void removeFromGs(Set<Producter> gs, Character left){ Set<Producter> trash = new HashSet<>(); for(Producter producter : gs){ if(producter.getLeft() == left){ trash.add(producter); } } gs.removeAll(trash); } // 封装了一个简单的功能:向文法中添加某些产生式 // 的是使上面的代码美观清晰 private void addToGs(Set<Producter> gs, Character newVN, String s, String commonFactor){ String newRight = s.replaceFirst(commonFactor, ""); if(newRight.equals("")){ newRight = "ε"; } gs.add(new Producter(newVN + "->" + newRight)); } }
MonsterSamarua/Top_2_Bottom
src/Service/Try2LL1.java
2,629
// 的是使上面的代码美观清晰
line_comment
zh-cn
package Service; import JavaBean.Producter; import Utils.GSBuilder; import java.util.*; /** * Try2LL1主要提供了两个方法————「提取公因子extractCommonFactor」+「消除左递归removeRecursin」 * 类如其名————一切都是为了"尝试将一个非LL1文法转化为等价的LL1文法",即"Try to LL1" */ public class Try2LL1 { /** *【提取公因子】直接在文法gs的基础上进行等价的修改 */ public void extractCommonFactor(Set<Producter> gs){ // 提取公因子之前,先消除隐式的情况 transGs(gs); Map<Character, List<String>> gs2 = GSBuilder.gsHelper(gs); Set<Character> VN = GSBuilder.getVN(gs); // 维护了一个给新的VN命名的候选数组 int k = 0; char[] unUsedCase = getUnUsedCase(gs); for(Character vn : VN){ // 对于每个非终结符(产生式的左侧),都尝试消除左递归 List<String> list = gs2.get(vn); // 不是所有的文法,都能在有限步骤内提取出所有的左公因子。换句话说,明明算法正确,但仍有可能死循环————因此设置一个阀值 int cnt = 10; boolean flag = true; while (flag && cnt > 0){ cnt--; flag = false; // 循环实在是太深了(封装太少的恶果),这里使用了一个flag+here标签实现跳出多层循环后,再次重新循环 here: for(int i = 0; i < list.size(); i++){ String curI = list.get(i); while (curI.length() > 0){ for(int j = i + 1; j < list.size(); j++){ String curJ = list.get(j); if(curJ.indexOf(curI) != 0){ continue; }else{ // 出现公共前缀 String s1 = list.get(i); String s2 = list.get(j); String commonFactor = curI; char newVN = unUsedCase[k++]; String s3 = commonFactor + newVN; list.remove(s1); list.remove(s2); list.add(s3); removeFromGs(gs, vn, s1); removeFromGs(gs, vn, s2); gs.add(new Producter(vn + "->" + s3)); gs.add(new Producter(newVN + "->" + (s1.length() == commonFactor.length() ? "ε" : s1.replaceFirst(commonFactor, "")))); gs.add(new Producter(newVN + "->" + (s2.length() == commonFactor.length() ? "ε" : s2.replaceFirst(commonFactor, "")))); flag = true; break here; } } curI = curI.substring(0, curI.length() - 1); } } } } // 提取公因子之后,删掉不可达的产生式 removeUnReachable(gs); } /** *【消除左递归】直接在文法gs的基础上进行等价的修改 */ public void removeRecursin(Set<Producter> gs){ Set<Character> VN = GSBuilder.getVN(gs); Map<Character, List<String>> gs2 = GSBuilder.gsHelper(gs); int k = 0; char[] unUsedCase = getUnUsedCase(gs); // 消除隐式 transGs(gs); for(Character vn : VN){ List<String> list = gs2.get(vn); List<String> alpha = new ArrayList<>(); List<String> beta = new ArrayList<>(); for(String str : list){ if(str.charAt(0) == vn){ alpha.add(str.substring(1)); }else{ if(str.equals("ε")){ str = ""; } beta.add(str); } } if(alpha.size() > 0){ removeFromGs(gs, vn); char newVN = unUsedCase[k++]; for(String s : beta){ gs.add(new Producter(vn + "->" + s + newVN)); } for(String s : alpha){ gs.add(new Producter(newVN + "->" + s + newVN)); } gs.add(new Producter(newVN + "->" + "ε")); } } // 同样,删掉不可到达的生成式 removeUnReachable(gs); } // 简单的功能性方法————比如目前已有的VN有SABC,这个方法会返回除了这几个之外的所有大写字母,作为候选 private char[] getUnUsedCase(Set<Producter> gs){ Set<Character> set = new HashSet<>(); Set<Character> VN = GSBuilder.getVN(gs); for(int i = 0; i < 26; i++){ set.add((char)('A' + i)); } set.removeAll(VN); char[] res = new char[set.size()]; int k = 0; for(char c : set){ res[k++] = c; } return res; } /** * 消除隐式 * 在「提取公因子」「消除左递归」之前进行隐式的消除————如果产生式的右部以非终结符(ABC)开头,那么公因子有可能是隐式的;递归同理 */ private void transGs(Set<Producter> gs){ Set<Character> VN = GSBuilder.getVN(gs); boolean flag = true; while (flag){ flag = false; Set<Producter> trash = new HashSet<>(); Set<Producter> wait = new HashSet<>(); for(Producter producter : gs){ Character c = producter.getRight().charAt(0); // 这里多讨论了一下:比如 A->Aa|b,这就属于左递归的范畴。 // 如果执迷于消除全部产生式的右部第一个VN,会死循环的————这就是「左递归」的陷阱,也是之后的工作 if(VN.contains(c) && c != producter.getLeft()){ flag = true; Map<Character, List<String>> gs2 = GSBuilder.gsHelper(gs); List<String> arr = gs2.get(c); trash.add(producter); for(String s : arr){ // 你不能用一个递归的式子去进行首字母的替换 if(s.charAt(0) == c){ continue; } Character newLeft = producter.getLeft(); String newRight = producter.getRight().replaceFirst(String.valueOf(c), s); wait.add(new Producter(newLeft + "->" + newRight)); } } } gs.removeAll(trash); gs.addAll(wait); } } // private void transGs2(Set<Producter> gs){ // Set<Character> VN = GSBuilder.getVN(gs); // List<Character> listVN = new ArrayList<>(VN); // int k = 0; // Map<Character, List<String>> gs2 = GSBuilder.gsHelper(gs); // for(Character vn : listVN){ // Set<Character> availableVN = new HashSet<>(); // for(int i = 0 ; i < k; i++){ // availableVN.add(listVN.get(i)); // } // k++; // List<String> list = gs2.get(vn); // for(String str : list){ // // 左边为vn // // 右边为str // // 右边第一个字母c // char c = str.charAt(0); // if (availableVN.contains(c)){ // removeFromGs(gs, vn, str); // Map<Character, List<String>> gs3 = GSBuilder.gsHelper(gs); // List<String> arr = gs3.get(c); // for(String s : arr){ // // 你不能用一个递归的式子去进行首字母的替换 // if(s.charAt(0) == c){ // continue; // } // gs.add(new Producter(vn + "->" + str.replaceFirst(String.valueOf(c), s))); // } // } // } // } // } /** * 删除不可达 * 在「提取公因子」「消除左递归」之后进行不可达生成式的删除————有些生成式可能会变得不可达,完全可以删掉 */ private void removeUnReachable(Set<Producter> gs){ Set<Character> reachableVN = new HashSet<>(); Set<Character> unreachableVN = GSBuilder.getVN(gs); for(Producter producter : gs){ for(char vn : unreachableVN){ if(producter.getRight().indexOf(vn) >= 0){ reachableVN.add(vn); } } } // 排除"可达到"的非终结符VN,以及S(S作为起始符号,必然是"可到达"的) unreachableVN.removeAll(reachableVN); unreachableVN.remove('S'); Set<Producter> trash = new HashSet<>(); for(Producter producter : gs){ if(unreachableVN.contains(producter.getLeft())){ trash.add(producter); } } gs.removeAll(trash); } // 封装了一个简单的功能:从文法中删除某些产生式 // 的是 <SUF> private void removeFromGs(Set<Producter> gs, Character left, String right){ Set<Producter> trash = new HashSet<>(); for(Producter producter : gs){ if(producter.getLeft() == left && producter.getRight().equals(right)){ trash.add(producter); } } gs.removeAll(trash); } private void removeFromGs(Set<Producter> gs, Character left){ Set<Producter> trash = new HashSet<>(); for(Producter producter : gs){ if(producter.getLeft() == left){ trash.add(producter); } } gs.removeAll(trash); } // 封装了一个简单的功能:向文法中添加某些产生式 // 的是使上面的代码美观清晰 private void addToGs(Set<Producter> gs, Character newVN, String s, String commonFactor){ String newRight = s.replaceFirst(commonFactor, ""); if(newRight.equals("")){ newRight = "ε"; } gs.add(new Producter(newVN + "->" + newRight)); } }
false
2,258
9
2,629
12
2,706
9
2,629
12
3,473
18
false
false
false
false
false
true
59239_4
package yibudownload; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.example.yibudownload.R; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; public class IcoUtilsCommon { public static void Doinit(final Activity activity) { try { //获取累模板 Class classes = activity.getClass(); Field[] fields = classes.getDeclaredFields(); for (Field field : fields) { InjectionName anntion =field.getAnnotation(InjectionName.class); if (anntion != null ) { //打破封装 field.setAccessible(true); //获取findViewById方法 Method findId = classes.getMethod("findViewById", new Class[] { int.class }); //获取R文件的从的Id模板 Class classid = R.id.class; //获取这个变量 Field theid = classid.getDeclaredField(field.getName()); //获取变量的id Object getid = theid.getInt(theid); //找到这个变量的id地址 Object value = findId.invoke(activity, new Object[]{getid}); //给变量赋值 field.set(activity, value); final String vlauesmeath=anntion.values(); System.out.println("Qwe111"); if( !vlauesmeath.equals("")) { final Method myshow = classes.getDeclaredMethod(vlauesmeath, new Class[]{}); if ( myshow != null) { final View myView = activity.findViewById((Integer) getid); myView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { myshow.invoke(activity, null); } catch (Exception e) { System.out.println("Qwe111"+e.toString()); } } }); } } } } } catch (Exception e) { System.out.println("q "+e.toString()); } } }
Moon-College/May_PublicWork
TZ-自知/第十一次作业/yibudownload/src/yibudownload/IcoUtilsCommon.java
534
//获取这个变量
line_comment
zh-cn
package yibudownload; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import com.example.yibudownload.R; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; public class IcoUtilsCommon { public static void Doinit(final Activity activity) { try { //获取累模板 Class classes = activity.getClass(); Field[] fields = classes.getDeclaredFields(); for (Field field : fields) { InjectionName anntion =field.getAnnotation(InjectionName.class); if (anntion != null ) { //打破封装 field.setAccessible(true); //获取findViewById方法 Method findId = classes.getMethod("findViewById", new Class[] { int.class }); //获取R文件的从的Id模板 Class classid = R.id.class; //获取 <SUF> Field theid = classid.getDeclaredField(field.getName()); //获取变量的id Object getid = theid.getInt(theid); //找到这个变量的id地址 Object value = findId.invoke(activity, new Object[]{getid}); //给变量赋值 field.set(activity, value); final String vlauesmeath=anntion.values(); System.out.println("Qwe111"); if( !vlauesmeath.equals("")) { final Method myshow = classes.getDeclaredMethod(vlauesmeath, new Class[]{}); if ( myshow != null) { final View myView = activity.findViewById((Integer) getid); myView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { myshow.invoke(activity, null); } catch (Exception e) { System.out.println("Qwe111"+e.toString()); } } }); } } } } } catch (Exception e) { System.out.println("q "+e.toString()); } } }
false
445
4
534
4
524
4
534
4
790
7
false
false
false
false
false
true
55851_9
package database; import java.sql.*; import javax.swing.JOptionPane; /** * 登录连接数据库 * @author 可恶 * */ public class ConnectDatabase { public Connection connection; /** * 连接数据库 * @param user 用户名 * @param password 密码 * @return */ public int connect(String user,String password) { final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; final String URL = "jdbc:mysql://localhost:3306/course_design?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"; final String USER1 = "root"; final String USER2 = "normal"; final String PASSWORD1 = "cyf0709fzy"; final String PASSWORD2 = "123456789"; if (!(USER1.equals(user)||USER2.equals(user))) //用户名错误 return 0; if ((user.equals(USER1)&&!password.equals(PASSWORD1))||(user.equals(USER2)&&!password.equals(PASSWORD2))) return 1;//密码错误 try { /*加载驱动*/ Class.forName(JDBC_DRIVER); /*连接操作*/ connection = DriverManager.getConnection(URL,user,password);//待修改 //connection.close(); } catch (ClassNotFoundException e) { // 处理异常 JOptionPane.showMessageDialog(null, "驱动加载失败!", "警告", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); return 2; }catch (SQLException e) { JOptionPane.showMessageDialog(null, "数据库连接异常!", "警告", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); return 3; } return -1; } }
Moran-0/Java_Enterprise_Devices_ManageMent_System
database/ConnectDatabase.java
438
// 处理异常
line_comment
zh-cn
package database; import java.sql.*; import javax.swing.JOptionPane; /** * 登录连接数据库 * @author 可恶 * */ public class ConnectDatabase { public Connection connection; /** * 连接数据库 * @param user 用户名 * @param password 密码 * @return */ public int connect(String user,String password) { final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver"; final String URL = "jdbc:mysql://localhost:3306/course_design?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC"; final String USER1 = "root"; final String USER2 = "normal"; final String PASSWORD1 = "cyf0709fzy"; final String PASSWORD2 = "123456789"; if (!(USER1.equals(user)||USER2.equals(user))) //用户名错误 return 0; if ((user.equals(USER1)&&!password.equals(PASSWORD1))||(user.equals(USER2)&&!password.equals(PASSWORD2))) return 1;//密码错误 try { /*加载驱动*/ Class.forName(JDBC_DRIVER); /*连接操作*/ connection = DriverManager.getConnection(URL,user,password);//待修改 //connection.close(); } catch (ClassNotFoundException e) { // 处理 <SUF> JOptionPane.showMessageDialog(null, "驱动加载失败!", "警告", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); return 2; }catch (SQLException e) { JOptionPane.showMessageDialog(null, "数据库连接异常!", "警告", JOptionPane.WARNING_MESSAGE); e.printStackTrace(); return 3; } return -1; } }
false
373
5
438
4
451
3
438
4
607
8
false
false
false
false
false
true
64905_3
package com.oral.model.vo; import lombok.Data; import java.time.LocalDateTime; @Data public class SickroomVO { /** * 创建时间 */ private LocalDateTime createTime; /** * id */ private Long id; /** * 护士 */ private String nurse; /** * 病房号 */ private Integer roomNo; /** * 病床数 */ private Integer roomNumber; /** * 0-普通病房,1-重症病房 */ private Integer type; /** * 更新时间 */ private LocalDateTime updateTime; }
Moriic/oral-backend
src/main/java/com/oral/model/vo/SickroomVO.java
152
/** * 病房号 */
block_comment
zh-cn
package com.oral.model.vo; import lombok.Data; import java.time.LocalDateTime; @Data public class SickroomVO { /** * 创建时间 */ private LocalDateTime createTime; /** * id */ private Long id; /** * 护士 */ private String nurse; /** * 病房号 <SUF>*/ private Integer roomNo; /** * 病床数 */ private Integer roomNumber; /** * 0-普通病房,1-重症病房 */ private Integer type; /** * 更新时间 */ private LocalDateTime updateTime; }
false
139
11
152
9
166
10
152
9
207
13
false
false
false
false
false
true
30685_13
package com.mosect.viewutils; import android.content.Context; import android.util.TypedValue; import android.view.MotionEvent; /** * 手势辅助器 */ public class GestureHelper { /** * 无手势,还不能确定手势 */ public static final int GESTURE_NONE = 0; /** * 手势:按住 */ public static final int GESTURE_PRESSED = 1; /** * 手势:点击 */ public static final int GESTURE_CLICK = 2; /** * 手势:长按 */ public static final int GESTURE_LONG_CLICK = 3; /** * 手势:左滑 */ public static final int GESTURE_LEFT = 4; /** * 手势:上滑 */ public static final int GESTURE_UP = 5; /** * 手势:右滑 */ public static final int GESTURE_RIGHT = 6; /** * 手势:下滑 */ public static final int GESTURE_DOWN = 7; /** * 默认的点大小,单位:dip */ public static final float DEFAULT_FONT_SIZE_DP = 5; /** * 默认的长按时间 */ public static final int DEFAULT_LONG_CLICK_TIME = 800; private float pointSize; // 点的大小 private int longClickTime; // 长按判定时间 private float xyScale; private int gesture = GESTURE_NONE; // 手势 private long downTime; private float downX = 0f; private float downY = 0f; private float preX = 0f; private float preY = 0f; /** * 创建一个手势帮助器 * * @param pointSize 点的大小,超出此大小的滑动手势会被判定为非点击手势 * @param longClickTime 长按点击时间,超过或等于此时间的按住手势算长按点击事件 * @param xyScale X轴与Y轴比例,影响方向手势的判定,默认是1; * 越小,手势判定越偏重于水平方向; * 越大,手势判定偏重于垂直方向; * 1,不偏重任何方向; * 如果是专注于水平方向,可以将此值设置小于1的数, * 如果是专注于垂直方向,可以将此值设置大于1的数; * 如果是垂直与水平同等重要,将此值设置成1 */ public GestureHelper(float pointSize, int longClickTime, float xyScale) { if (pointSize <= 0) { throw new IllegalArgumentException("Illegal:pointSize <= 0"); } if (longClickTime <= 0) { throw new IllegalArgumentException("Illegal:longClickTime <= 0"); } if (xyScale == 0) { throw new IllegalArgumentException("Illegal:xyScale equals 0"); } this.pointSize = pointSize; this.longClickTime = longClickTime; this.xyScale = xyScale; } /** * 创建默认的手势辅助器 * * @param context 上下文对象 * @return 手势器 */ public static GestureHelper createDefault(Context context) { float pointSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_FONT_SIZE_DP, context.getResources().getDisplayMetrics()); return new GestureHelper(pointSize, DEFAULT_LONG_CLICK_TIME, 1f); } /** * 触发触摸滑动事件 * * @param event 事件 */ public void onTouchEvent(MotionEvent event) { // System.out.println("onTouchEvent:action=" + event.getAction()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 按下 touchDown(event); break; case MotionEvent.ACTION_MOVE: // 移动 touchMove(event); break; case MotionEvent.ACTION_CANCEL: // 取消 case MotionEvent.ACTION_UP: // 抬起 touchFinish(event); break; } // System.out.println("onTouchEvent:" + gesture); } /** * 获取手势 * * @return 手势 */ public int getGesture() { return gesture; } /** * 判定是否为水平滑动手势 * * @return true,水平滑动手势 */ public boolean isHorizontalGesture() { return gesture == GESTURE_LEFT || gesture == GESTURE_RIGHT; } /** * 判定是否为垂直滑动手势 * * @return true,垂直滑动手势 */ public boolean isVerticalGesture() { return gesture == GESTURE_UP || gesture == GESTURE_DOWN; } private void touchDown(MotionEvent event) { downTime = System.currentTimeMillis(); downX = preX = event.getRawX(); downY = preY = event.getRawY(); gesture = GESTURE_PRESSED; } private void touchMove(MotionEvent event) { float rangeX = event.getRawX() - downX; float rangeY = event.getRawY() - downY; // System.out.println(String.format("touchMove:rangeX=%f,rangeY=%f,pointSize=%f", // rangeX, rangeY, pointSize)); if (gesture == GESTURE_NONE || gesture == GESTURE_PRESSED) { // 未确定手势或正在长按 if (Math.abs(rangeX) > pointSize || Math.abs(rangeY) > pointSize) { // 超出点的范围,不算点击、按住手势,应该是滑动手势 float ox = event.getRawX() - preX; float oy = event.getRawY() - preY; if (Math.abs(ox) > xyScale * Math.abs(oy)) { // 水平方向滑动 if (ox < 0) { gesture = GESTURE_LEFT; } else { gesture = GESTURE_RIGHT; } } else { // 垂直方向滑动 if (oy < 0) { gesture = GESTURE_UP; } else { gesture = GESTURE_DOWN; } } } else { gesture = GESTURE_PRESSED; // 按住手势 } } if (gesture == GESTURE_PRESSED) { // 按住中 if (System.currentTimeMillis() - downTime >= longClickTime) { // 按住超过长按时间,算长按时间 gesture = GESTURE_LONG_CLICK; } } preX = event.getRawX(); preY = event.getRawY(); } private void touchFinish(MotionEvent event) { if (gesture == GESTURE_PRESSED) { // 按住到释放,应该算点击手势 if (System.currentTimeMillis() - downTime >= longClickTime) { // 按住超过长按时间,算长按时间 gesture = GESTURE_LONG_CLICK; } else { gesture = GESTURE_CLICK; } } } }
Mosect/ViewUtils
library/src/main/java/com/mosect/viewutils/GestureHelper.java
1,742
/** * 创建一个手势帮助器 * * @param pointSize 点的大小,超出此大小的滑动手势会被判定为非点击手势 * @param longClickTime 长按点击时间,超过或等于此时间的按住手势算长按点击事件 * @param xyScale X轴与Y轴比例,影响方向手势的判定,默认是1; * 越小,手势判定越偏重于水平方向; * 越大,手势判定偏重于垂直方向; * 1,不偏重任何方向; * 如果是专注于水平方向,可以将此值设置小于1的数, * 如果是专注于垂直方向,可以将此值设置大于1的数; * 如果是垂直与水平同等重要,将此值设置成1 */
block_comment
zh-cn
package com.mosect.viewutils; import android.content.Context; import android.util.TypedValue; import android.view.MotionEvent; /** * 手势辅助器 */ public class GestureHelper { /** * 无手势,还不能确定手势 */ public static final int GESTURE_NONE = 0; /** * 手势:按住 */ public static final int GESTURE_PRESSED = 1; /** * 手势:点击 */ public static final int GESTURE_CLICK = 2; /** * 手势:长按 */ public static final int GESTURE_LONG_CLICK = 3; /** * 手势:左滑 */ public static final int GESTURE_LEFT = 4; /** * 手势:上滑 */ public static final int GESTURE_UP = 5; /** * 手势:右滑 */ public static final int GESTURE_RIGHT = 6; /** * 手势:下滑 */ public static final int GESTURE_DOWN = 7; /** * 默认的点大小,单位:dip */ public static final float DEFAULT_FONT_SIZE_DP = 5; /** * 默认的长按时间 */ public static final int DEFAULT_LONG_CLICK_TIME = 800; private float pointSize; // 点的大小 private int longClickTime; // 长按判定时间 private float xyScale; private int gesture = GESTURE_NONE; // 手势 private long downTime; private float downX = 0f; private float downY = 0f; private float preX = 0f; private float preY = 0f; /** * 创建一 <SUF>*/ public GestureHelper(float pointSize, int longClickTime, float xyScale) { if (pointSize <= 0) { throw new IllegalArgumentException("Illegal:pointSize <= 0"); } if (longClickTime <= 0) { throw new IllegalArgumentException("Illegal:longClickTime <= 0"); } if (xyScale == 0) { throw new IllegalArgumentException("Illegal:xyScale equals 0"); } this.pointSize = pointSize; this.longClickTime = longClickTime; this.xyScale = xyScale; } /** * 创建默认的手势辅助器 * * @param context 上下文对象 * @return 手势器 */ public static GestureHelper createDefault(Context context) { float pointSize = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_FONT_SIZE_DP, context.getResources().getDisplayMetrics()); return new GestureHelper(pointSize, DEFAULT_LONG_CLICK_TIME, 1f); } /** * 触发触摸滑动事件 * * @param event 事件 */ public void onTouchEvent(MotionEvent event) { // System.out.println("onTouchEvent:action=" + event.getAction()); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // 按下 touchDown(event); break; case MotionEvent.ACTION_MOVE: // 移动 touchMove(event); break; case MotionEvent.ACTION_CANCEL: // 取消 case MotionEvent.ACTION_UP: // 抬起 touchFinish(event); break; } // System.out.println("onTouchEvent:" + gesture); } /** * 获取手势 * * @return 手势 */ public int getGesture() { return gesture; } /** * 判定是否为水平滑动手势 * * @return true,水平滑动手势 */ public boolean isHorizontalGesture() { return gesture == GESTURE_LEFT || gesture == GESTURE_RIGHT; } /** * 判定是否为垂直滑动手势 * * @return true,垂直滑动手势 */ public boolean isVerticalGesture() { return gesture == GESTURE_UP || gesture == GESTURE_DOWN; } private void touchDown(MotionEvent event) { downTime = System.currentTimeMillis(); downX = preX = event.getRawX(); downY = preY = event.getRawY(); gesture = GESTURE_PRESSED; } private void touchMove(MotionEvent event) { float rangeX = event.getRawX() - downX; float rangeY = event.getRawY() - downY; // System.out.println(String.format("touchMove:rangeX=%f,rangeY=%f,pointSize=%f", // rangeX, rangeY, pointSize)); if (gesture == GESTURE_NONE || gesture == GESTURE_PRESSED) { // 未确定手势或正在长按 if (Math.abs(rangeX) > pointSize || Math.abs(rangeY) > pointSize) { // 超出点的范围,不算点击、按住手势,应该是滑动手势 float ox = event.getRawX() - preX; float oy = event.getRawY() - preY; if (Math.abs(ox) > xyScale * Math.abs(oy)) { // 水平方向滑动 if (ox < 0) { gesture = GESTURE_LEFT; } else { gesture = GESTURE_RIGHT; } } else { // 垂直方向滑动 if (oy < 0) { gesture = GESTURE_UP; } else { gesture = GESTURE_DOWN; } } } else { gesture = GESTURE_PRESSED; // 按住手势 } } if (gesture == GESTURE_PRESSED) { // 按住中 if (System.currentTimeMillis() - downTime >= longClickTime) { // 按住超过长按时间,算长按时间 gesture = GESTURE_LONG_CLICK; } } preX = event.getRawX(); preY = event.getRawY(); } private void touchFinish(MotionEvent event) { if (gesture == GESTURE_PRESSED) { // 按住到释放,应该算点击手势 if (System.currentTimeMillis() - downTime >= longClickTime) { // 按住超过长按时间,算长按时间 gesture = GESTURE_LONG_CLICK; } else { gesture = GESTURE_CLICK; } } } }
false
1,614
192
1,742
214
1,785
196
1,742
214
2,300
298
true
true
true
true
true
false
65553_0
package org.mossmc.mosscg.DGLABOI.Bluetooth; import org.mossmc.mosscg.DGLABOI.BasicInfo; public class BluetoothWave { @SuppressWarnings({"InfiniteLoopStatement"}) public static void waveSender() { while (true) { try { //随便照着郊狼文档搓了个波形,无所谓,能用就行 sendBoth(5,135,20); sendBoth(5,125,20); sendBoth(5,115,20); sendBoth(5,105,20); sendBoth(5,95,20); sendBoth(4,86,20); sendBoth(4,76,20); sendBoth(4,66,20); sendBoth(3,57,20); sendBoth(3,47,20); sendBoth(3,37,20); sendBoth(2,28,20); sendBoth(2,18,20); sendBoth(1,14,20); sendBoth(1,9,20); } catch (Exception e) { BasicInfo.logger.sendException(e); } } } public static void sendBoth(int x,int y,int z) throws InterruptedException { BluetoothControl.sendWave("A",x,y,z); BluetoothControl.sendWave("B",x,y,z); Thread.sleep(100); } }
MossCG/DGLAB-OI
src/main/java/org/mossmc/mosscg/DGLABOI/Bluetooth/BluetoothWave.java
369
//随便照着郊狼文档搓了个波形,无所谓,能用就行
line_comment
zh-cn
package org.mossmc.mosscg.DGLABOI.Bluetooth; import org.mossmc.mosscg.DGLABOI.BasicInfo; public class BluetoothWave { @SuppressWarnings({"InfiniteLoopStatement"}) public static void waveSender() { while (true) { try { //随便 <SUF> sendBoth(5,135,20); sendBoth(5,125,20); sendBoth(5,115,20); sendBoth(5,105,20); sendBoth(5,95,20); sendBoth(4,86,20); sendBoth(4,76,20); sendBoth(4,66,20); sendBoth(3,57,20); sendBoth(3,47,20); sendBoth(3,37,20); sendBoth(2,28,20); sendBoth(2,18,20); sendBoth(1,14,20); sendBoth(1,9,20); } catch (Exception e) { BasicInfo.logger.sendException(e); } } } public static void sendBoth(int x,int y,int z) throws InterruptedException { BluetoothControl.sendWave("A",x,y,z); BluetoothControl.sendWave("B",x,y,z); Thread.sleep(100); } }
false
340
17
369
26
386
18
369
26
451
41
false
false
false
false
false
true
39178_0
package com.guiguli.string_ArrayList; import java.util.ArrayList; /* 案例 集合存储自定义元素并遍历 需求:定义电影类(名称 分值 演员) 创建三个电影对象 代表三部影片 《肖申克的救赎》 9.7 罗宾斯 《霸王别姬》 9.6 张国荣 张丰毅 《阿甘正传》 9.5 汤姆.汉克斯 */ public class ArrayListMovie { public static void main(String[] args) { Movie m1=new Movie("《肖申克的救赎》",9.7,"罗宾斯"); Movie m2=new Movie("《霸王别姬》",9.7,"张国荣、张丰毅"); Movie m3=new Movie("《阿甘正传》",9.5,"汤姆.汉克斯"); ArrayList<Movie>movies=new ArrayList<>(); movies.add(m1); movies.add(m2); movies.add(m3); //遍历 for(int i=0;i<movies.size();i++){ Movie m =movies.get(i); System.out.println("电影名称:"+m.getName()); System.out.println("电影得分:"+m.getScore()); System.out.println("电影主演:"+m.getActotor()); System.out.println("---------------"); } } }
Mq-b/-2022-5-4-
Java/基础/ArrayLIst/ArrayListMovie.java
374
/* 案例 集合存储自定义元素并遍历 需求:定义电影类(名称 分值 演员) 创建三个电影对象 代表三部影片 《肖申克的救赎》 9.7 罗宾斯 《霸王别姬》 9.6 张国荣 张丰毅 《阿甘正传》 9.5 汤姆.汉克斯 */
block_comment
zh-cn
package com.guiguli.string_ArrayList; import java.util.ArrayList; /* 案例 <SUF>*/ public class ArrayListMovie { public static void main(String[] args) { Movie m1=new Movie("《肖申克的救赎》",9.7,"罗宾斯"); Movie m2=new Movie("《霸王别姬》",9.7,"张国荣、张丰毅"); Movie m3=new Movie("《阿甘正传》",9.5,"汤姆.汉克斯"); ArrayList<Movie>movies=new ArrayList<>(); movies.add(m1); movies.add(m2); movies.add(m3); //遍历 for(int i=0;i<movies.size();i++){ Movie m =movies.get(i); System.out.println("电影名称:"+m.getName()); System.out.println("电影得分:"+m.getScore()); System.out.println("电影主演:"+m.getActotor()); System.out.println("---------------"); } } }
false
310
107
372
112
340
85
372
112
465
153
false
false
false
false
false
true
55270_2
package com.guigu.domain.info; public class Talk { String talk_id;//谈话编号 String talk_person;//谈话人编号 String talk_time;//谈话日期 public String getTalk_id() { return talk_id; } public void setTalk_id(String talk_id) { this.talk_id = talk_id; } public String getTalk_person() { return talk_person; } public void setTalk_person(String talk_person) { this.talk_person = talk_person; } public String getTalk_time() { return talk_time; } public void setTalk_time(String talk_time) { this.talk_time = talk_time; } @Override public String toString() { return "Talk [talk_id=" + talk_id + ", talk_person=" + talk_person + ", talk_time=" + talk_time + "]"; } public Talk(String talk_id, String talk_person, String talk_time) { super(); this.talk_id = talk_id; this.talk_person = talk_person; this.talk_time = talk_time; } public Talk() { super(); } }
Mr-Orang/StuMgr-Java
guigu_domain/src/main/java/com/guigu/domain/info/Talk.java
331
//谈话日期
line_comment
zh-cn
package com.guigu.domain.info; public class Talk { String talk_id;//谈话编号 String talk_person;//谈话人编号 String talk_time;//谈话 <SUF> public String getTalk_id() { return talk_id; } public void setTalk_id(String talk_id) { this.talk_id = talk_id; } public String getTalk_person() { return talk_person; } public void setTalk_person(String talk_person) { this.talk_person = talk_person; } public String getTalk_time() { return talk_time; } public void setTalk_time(String talk_time) { this.talk_time = talk_time; } @Override public String toString() { return "Talk [talk_id=" + talk_id + ", talk_person=" + talk_person + ", talk_time=" + talk_time + "]"; } public Talk(String talk_id, String talk_person, String talk_time) { super(); this.talk_id = talk_id; this.talk_person = talk_person; this.talk_time = talk_time; } public Talk() { super(); } }
false
236
3
331
5
329
4
331
5
376
7
false
false
false
false
false
true
56335_3
package xiaoliang.ltool.bean; import android.graphics.Color; import java.io.Serializable; /** * Created by Liuj on 2016/11/4. * 记事本的Bean */ public class NoteBean implements Serializable { public int id; public String title;//标题 public String note;//内容 public float money;//金额 public boolean income = false;//是否是收入 public long startTime;//开始时间 public long endTime;//结束时间 public long createTime;//创建时间 public long advance;//提前时间 public int noteType;//颜色ID public int color;//颜色色值 public boolean alert;//提醒 public boolean oneDay;//一整天 public String address;//地址 public NoteBean() { this(-1,"","",0,false,-1,-1,-1,-1,Color.BLACK,false,false,"",0); } public NoteBean(int id,String title, String note, float money, boolean income, long startTime, long endTime, long advance, int noteType, int color, boolean alert, boolean oneDay, String address,long createTime) { this.id = id; this.title = title; this.note = note; this.money = money; this.income = income; this.startTime = startTime; this.endTime = endTime; this.advance = advance; this.noteType = noteType; this.color = color; this.alert = alert; this.oneDay = oneDay; this.address = address; this.createTime = createTime; } }
Mr-XiaoLiang/LTool
app/src/main/java/xiaoliang/ltool/bean/NoteBean.java
367
//结束时间
line_comment
zh-cn
package xiaoliang.ltool.bean; import android.graphics.Color; import java.io.Serializable; /** * Created by Liuj on 2016/11/4. * 记事本的Bean */ public class NoteBean implements Serializable { public int id; public String title;//标题 public String note;//内容 public float money;//金额 public boolean income = false;//是否是收入 public long startTime;//开始时间 public long endTime;//结束 <SUF> public long createTime;//创建时间 public long advance;//提前时间 public int noteType;//颜色ID public int color;//颜色色值 public boolean alert;//提醒 public boolean oneDay;//一整天 public String address;//地址 public NoteBean() { this(-1,"","",0,false,-1,-1,-1,-1,Color.BLACK,false,false,"",0); } public NoteBean(int id,String title, String note, float money, boolean income, long startTime, long endTime, long advance, int noteType, int color, boolean alert, boolean oneDay, String address,long createTime) { this.id = id; this.title = title; this.note = note; this.money = money; this.income = income; this.startTime = startTime; this.endTime = endTime; this.advance = advance; this.noteType = noteType; this.color = color; this.alert = alert; this.oneDay = oneDay; this.address = address; this.createTime = createTime; } }
false
336
3
367
3
386
3
367
3
458
7
false
false
false
false
false
true
64448_3
package com.hansheng.csdnspider; import java.util.List; /** * Created by hansheng on 2016/7/14. */ public class Text { public static void main(String... args){ NewsItemBiz biz = new NewsItemBiz(); int currentPage = 1; try { /** * 业界 */ List<NewsItem> newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YEJIE, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 程序员杂志 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_CHENGXUYUAN, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 研发 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YANFA, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 移动 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YIDONG, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); } catch (CommonException e) { e.printStackTrace(); } } }
MrWu94/AndroidNote
java/src/main/java/com/hansheng/csdnspider/Text.java
371
/** * 研发 */
block_comment
zh-cn
package com.hansheng.csdnspider; import java.util.List; /** * Created by hansheng on 2016/7/14. */ public class Text { public static void main(String... args){ NewsItemBiz biz = new NewsItemBiz(); int currentPage = 1; try { /** * 业界 */ List<NewsItem> newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YEJIE, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 程序员杂志 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_CHENGXUYUAN, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 研发 <SUF>*/ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YANFA, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); /** * 移动 */ newsItems = biz.getNewsItems(Constaint.NEWS_TYPE_YIDONG, currentPage); for (NewsItem item : newsItems) { System.out.println(item); } System.out.println("----------------------"); } catch (CommonException e) { e.printStackTrace(); } } }
false
331
10
371
8
410
9
371
8
442
10
false
false
false
false
false
true
4719_0
package com.zzj.blog.pojo; import javax.persistence.*; @Entity @Table(name="t_friend") public class Friend { @Id @GeneratedValue private Long id; private String nickname; private String occupation; private String description; @Basic(fetch = FetchType.LAZY) @Lob private String avatar; private String flag;//大佬,朋友,网站 private String website; public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public Friend(String nickname, String occupation, String description, String avatar, String flag) { this.nickname = nickname; this.occupation = occupation; this.description = description; this.avatar = avatar; this.flag = flag; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getOccupation() { return occupation; } public void setOccupation(String occupation) { this.occupation = occupation; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } @Override public String toString() { return "Friend{" + "id=" + id + ", nickname='" + nickname + '\'' + ", occupation='" + occupation + '\'' + ", description='" + description + '\'' + ", avatar='" + avatar + '\'' + ", flag='" + flag + '\'' + '}'; } public Friend() { } }
Mretron/MyBlogWebSite
src/main/java/com/zzj/blog/pojo/Friend.java
475
//大佬,朋友,网站
line_comment
zh-cn
package com.zzj.blog.pojo; import javax.persistence.*; @Entity @Table(name="t_friend") public class Friend { @Id @GeneratedValue private Long id; private String nickname; private String occupation; private String description; @Basic(fetch = FetchType.LAZY) @Lob private String avatar; private String flag;//大佬 <SUF> private String website; public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public Friend(String nickname, String occupation, String description, String avatar, String flag) { this.nickname = nickname; this.occupation = occupation; this.description = description; this.avatar = avatar; this.flag = flag; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getNickname() { return nickname; } public void setNickname(String nickname) { this.nickname = nickname; } public String getOccupation() { return occupation; } public void setOccupation(String occupation) { this.occupation = occupation; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } @Override public String toString() { return "Friend{" + "id=" + id + ", nickname='" + nickname + '\'' + ", occupation='" + occupation + '\'' + ", description='" + description + '\'' + ", avatar='" + avatar + '\'' + ", flag='" + flag + '\'' + '}'; } public Friend() { } }
false
426
6
475
10
524
6
475
10
617
13
false
false
false
false
false
true
57535_16
package com.feng.freader.constant; import com.feng.freader.app.App; import java.util.Arrays; import java.util.List; /** * @author Feng Zhaohao * Created on 2019/11/6 */ public class Constant { /* 热门榜单相关 */ // 男生热门榜单的榜单数 public static final int MALE_HOT_RANK_NUM = 5; // 男生热门榜单的 id private static String sZYHotRankId = "564d8003aca44f4f61850fcd"; // 掌阅热销榜 private static String sSQHotRankId = "564d80457408cfcd63ae2dd0"; // 书旗热搜榜 private static String sZHHotRankId = "54d430962c12d3740e4a3ed2"; // 纵横月票榜 private static String sZLHotRankId = "5732aac02dbb268b5f037fc4"; // 逐浪点击榜 private static String sBDHotRankId = "564ef4f985ed965d0280c9c2"; // 百度热搜榜 public static final List<String> MALE_HOT_RANK_ID = Arrays.asList(sZYHotRankId, sSQHotRankId, sZHHotRankId, sZLHotRankId, sBDHotRankId); // 男生热门榜单的榜单名字 public static final List<String> MALE_HOT_RANK_NAME = Arrays.asList("掌阅热销榜", "书旗热搜榜", "纵横月票榜", "逐浪点击榜", "百度热搜榜"); // 女生热门榜单的榜单数 public static final int FEMALE_HOT_RANK_NUM = 3; // 女生热门榜单的 id private static String sKHotRankId = "550b841715db45cd4b022107"; // 17K订阅榜 private static String sNZYHotRankId = "564d80d0e8c613016446c5aa"; // 掌阅热销榜 private static String sNSQHotRankId = "564d81151109835664770ad7"; // 书旗热搜榜 public static final List<String> FEMALE_HOT_RANK_ID = Arrays.asList( sKHotRankId, sNZYHotRankId, sNSQHotRankId); // 女生热门榜单的榜单名字 public static final List<String> FEMALE_HOT_RANK_NAME = Arrays.asList( "17K订阅榜", "掌阅热销榜", "书旗热搜榜"); /* 错误信息 */ // 小说源 api 没有找到相关小说 public static final String NOT_FOUND_NOVELS = "没有找到相关小说"; // 没有获取到相关目录信息 public static final String NOT_FOUND_CATALOG_INFO = "没有找到相关目录"; // json 格式错误 public static final String JSON_ERROR = "json 格式错误"; // 该小说已从本地删除 public static final String NOT_FOUND_FROM_LOCAL = "该小说已从本地删除"; /* 数据库相关 */ // 数据库名 public static final String DB_NAME = "FReader.db"; // 历史记录表 public static final String TABLE_HISTORY = "TABLE_HISTORY"; // 历史记录表的记录 public static final String TABLE_HISTORY_ID = "TABLE_HISTORY_ID"; // 自增 id(主键) public static final String TABLE_HISTORY_WORD = "TABLE_HISTORY_WORD"; // 搜索词 // 书架书籍表 public static final String TABLE_BOOKSHELF_NOVEL = "TABLE_BOOKSHELF_NOVEL"; // 书架书籍表的记录 public static final String TABLE_BOOKSHELF_NOVEL_NOVEL_URL = "TABLE_BOOKSHELF_NOVEL_NOVEL_URL"; // 小说 URL(主键) public static final String TABLE_BOOKSHELF_NOVEL_NAME = "TABLE_BOOKSHELF_NOVEL_NAME"; // 小说名 public static final String TABLE_BOOKSHELF_NOVEL_COVER = "TABLE_BOOKSHELF_NOVEL_COVER"; // 小说封面 // 章节索引:网络小说和本地 epub 小说为目录索引,本地 txt 小说无需该属性 public static final String TABLE_BOOKSHELF_NOVEL_CHAPTER_INDEX = "TABLE_BOOKSHELF_NOVEL_CHAPTER_INDEX"; // 位置索引(用于跳转到上一次进度):网络小说和 txt 是 String 文本的位置 public static final String TABLE_BOOKSHELF_NOVEL_POSITION = "TABLE_BOOKSHELF_NOVEL_POSITION"; // 第二位置索引(epub 解析用) public static final String TABLE_BOOKSHELF_NOVEL_SECOND_POSITION = "TABLE_BOOKSHELF_NOVEL_SECOND_POSITION"; // 类型:0 为网络小说, 1 为本地 txt 小说, 2 为本地 epub 小说 public static final String TABLE_BOOKSHELF_NOVEL_TYPE = "TABLE_BOOKSHELF_NOVEL_TYPE"; /* 文件存储 */ public static final String EPUB_SAVE_PATH = App.getContext().getFilesDir() + "/epubFile"; /* 分类小说相关 */ // gender public static final String CATEGORY_GENDER_MALE = "male"; // 男生 public static final String CATEGORY_GENDER_FEMALE = "female"; // 女生 public static final String CATEGORY_GENDER_PRESS = "press"; // 出版 public static final String CATEGORY_GENDER_MALE_TEXT = "男生"; public static final String CATEGORY_GENDER_FEMALE_TEXT = "女生"; public static final String CATEGORY_GENDER_PRESS_TEXT = "出版"; // type public static final String CATEGORY_TYPE_HOT = "hot"; // 热门 public static final String CATEGORY_TYPE_NEW = "new"; // 新书 public static final String CATEGORY_TYPE_REPUTATION = "reputation"; // 好评 public static final String CATEGORY_TYPE_OVER = "over"; // 完结 public static final String CATEGORY_TYPE_MONTH = "month"; // 包月 public static final String CATEGORY_TYPE_HOT_TEXT = "热门"; public static final String CATEGORY_TYPE_NEW_TEXT = "新书"; public static final String CATEGORY_TYPE_REPUTATION_TEXT = "好评"; public static final String CATEGORY_TYPE_OVER_TEXT = "完结"; public static final String CATEGORY_TYPE_MONTH_TEXT = "包月"; // major(男生) public static final String CATEGORY_MAJOR_XH = "玄幻"; public static final String CATEGORY_MAJOR_QH = "奇幻"; public static final String CATEGORY_MAJOR_WX = "武侠"; public static final String CATEGORY_MAJOR_XX = "仙侠"; public static final String CATEGORY_MAJOR_DS = "都市"; public static final String CATEGORY_MAJOR_ZC = "职场"; public static final String CATEGORY_MAJOR_LS = "历史"; public static final String CATEGORY_MAJOR_JS = "军事"; public static final String CATEGORY_MAJOR_YX = "游戏"; public static final String CATEGORY_MAJOR_JJ = "竞技"; public static final String CATEGORY_MAJOR_KH = "科幻"; public static final String CATEGORY_MAJOR_LY = "灵异"; public static final String CATEGORY_MAJOR_TR = "同人"; public static final String CATEGORY_MAJOR_QXS = "轻小说"; // major(女生) public static final String CATEGORY_MAJOR_GDYQ = "古代言情"; public static final String CATEGORY_MAJOR_XDYQ = "现代言情"; public static final String CATEGORY_MAJOR_QCXY = "青春校园"; public static final String CATEGORY_MAJOR_CA = "纯爱"; public static final String CATEGORY_MAJOR_XHQH = "玄幻奇幻"; public static final String CATEGORY_MAJOR_WXXX = "武侠仙侠"; // major(出版) public static final String CATEGORY_MAJOR_CBXS = "出版小说"; public static final String CATEGORY_MAJOR_ZJMZ = "传记名著"; public static final String CATEGORY_MAJOR_CGLZ = "成功励志"; public static final String CATEGORY_MAJOR_RWSK = "人文社科"; public static final String CATEGORY_MAJOR_JGLC = "经管理财"; public static final String CATEGORY_MAJOR_SHSS = "生活时尚"; public static final String CATEGORY_MAJOR_YEJK = "育儿健康"; public static final String CATEGORY_MAJOR_QCYQ = "青春言情"; public static final String CATEGORY_MAJOR_WWYB = "外文原版"; public static final String CATEGORY_MAJOR_ZZJS = "政治军事"; /* 全部小说 */ public static final int NOVEL_PAGE_NUM = 10; // 每页的小说数 }
Mrfzh/FReader
app/src/main/java/com/feng/freader/constant/Constant.java
2,425
/* 错误信息 */
block_comment
zh-cn
package com.feng.freader.constant; import com.feng.freader.app.App; import java.util.Arrays; import java.util.List; /** * @author Feng Zhaohao * Created on 2019/11/6 */ public class Constant { /* 热门榜单相关 */ // 男生热门榜单的榜单数 public static final int MALE_HOT_RANK_NUM = 5; // 男生热门榜单的 id private static String sZYHotRankId = "564d8003aca44f4f61850fcd"; // 掌阅热销榜 private static String sSQHotRankId = "564d80457408cfcd63ae2dd0"; // 书旗热搜榜 private static String sZHHotRankId = "54d430962c12d3740e4a3ed2"; // 纵横月票榜 private static String sZLHotRankId = "5732aac02dbb268b5f037fc4"; // 逐浪点击榜 private static String sBDHotRankId = "564ef4f985ed965d0280c9c2"; // 百度热搜榜 public static final List<String> MALE_HOT_RANK_ID = Arrays.asList(sZYHotRankId, sSQHotRankId, sZHHotRankId, sZLHotRankId, sBDHotRankId); // 男生热门榜单的榜单名字 public static final List<String> MALE_HOT_RANK_NAME = Arrays.asList("掌阅热销榜", "书旗热搜榜", "纵横月票榜", "逐浪点击榜", "百度热搜榜"); // 女生热门榜单的榜单数 public static final int FEMALE_HOT_RANK_NUM = 3; // 女生热门榜单的 id private static String sKHotRankId = "550b841715db45cd4b022107"; // 17K订阅榜 private static String sNZYHotRankId = "564d80d0e8c613016446c5aa"; // 掌阅热销榜 private static String sNSQHotRankId = "564d81151109835664770ad7"; // 书旗热搜榜 public static final List<String> FEMALE_HOT_RANK_ID = Arrays.asList( sKHotRankId, sNZYHotRankId, sNSQHotRankId); // 女生热门榜单的榜单名字 public static final List<String> FEMALE_HOT_RANK_NAME = Arrays.asList( "17K订阅榜", "掌阅热销榜", "书旗热搜榜"); /* 错误信 <SUF>*/ // 小说源 api 没有找到相关小说 public static final String NOT_FOUND_NOVELS = "没有找到相关小说"; // 没有获取到相关目录信息 public static final String NOT_FOUND_CATALOG_INFO = "没有找到相关目录"; // json 格式错误 public static final String JSON_ERROR = "json 格式错误"; // 该小说已从本地删除 public static final String NOT_FOUND_FROM_LOCAL = "该小说已从本地删除"; /* 数据库相关 */ // 数据库名 public static final String DB_NAME = "FReader.db"; // 历史记录表 public static final String TABLE_HISTORY = "TABLE_HISTORY"; // 历史记录表的记录 public static final String TABLE_HISTORY_ID = "TABLE_HISTORY_ID"; // 自增 id(主键) public static final String TABLE_HISTORY_WORD = "TABLE_HISTORY_WORD"; // 搜索词 // 书架书籍表 public static final String TABLE_BOOKSHELF_NOVEL = "TABLE_BOOKSHELF_NOVEL"; // 书架书籍表的记录 public static final String TABLE_BOOKSHELF_NOVEL_NOVEL_URL = "TABLE_BOOKSHELF_NOVEL_NOVEL_URL"; // 小说 URL(主键) public static final String TABLE_BOOKSHELF_NOVEL_NAME = "TABLE_BOOKSHELF_NOVEL_NAME"; // 小说名 public static final String TABLE_BOOKSHELF_NOVEL_COVER = "TABLE_BOOKSHELF_NOVEL_COVER"; // 小说封面 // 章节索引:网络小说和本地 epub 小说为目录索引,本地 txt 小说无需该属性 public static final String TABLE_BOOKSHELF_NOVEL_CHAPTER_INDEX = "TABLE_BOOKSHELF_NOVEL_CHAPTER_INDEX"; // 位置索引(用于跳转到上一次进度):网络小说和 txt 是 String 文本的位置 public static final String TABLE_BOOKSHELF_NOVEL_POSITION = "TABLE_BOOKSHELF_NOVEL_POSITION"; // 第二位置索引(epub 解析用) public static final String TABLE_BOOKSHELF_NOVEL_SECOND_POSITION = "TABLE_BOOKSHELF_NOVEL_SECOND_POSITION"; // 类型:0 为网络小说, 1 为本地 txt 小说, 2 为本地 epub 小说 public static final String TABLE_BOOKSHELF_NOVEL_TYPE = "TABLE_BOOKSHELF_NOVEL_TYPE"; /* 文件存储 */ public static final String EPUB_SAVE_PATH = App.getContext().getFilesDir() + "/epubFile"; /* 分类小说相关 */ // gender public static final String CATEGORY_GENDER_MALE = "male"; // 男生 public static final String CATEGORY_GENDER_FEMALE = "female"; // 女生 public static final String CATEGORY_GENDER_PRESS = "press"; // 出版 public static final String CATEGORY_GENDER_MALE_TEXT = "男生"; public static final String CATEGORY_GENDER_FEMALE_TEXT = "女生"; public static final String CATEGORY_GENDER_PRESS_TEXT = "出版"; // type public static final String CATEGORY_TYPE_HOT = "hot"; // 热门 public static final String CATEGORY_TYPE_NEW = "new"; // 新书 public static final String CATEGORY_TYPE_REPUTATION = "reputation"; // 好评 public static final String CATEGORY_TYPE_OVER = "over"; // 完结 public static final String CATEGORY_TYPE_MONTH = "month"; // 包月 public static final String CATEGORY_TYPE_HOT_TEXT = "热门"; public static final String CATEGORY_TYPE_NEW_TEXT = "新书"; public static final String CATEGORY_TYPE_REPUTATION_TEXT = "好评"; public static final String CATEGORY_TYPE_OVER_TEXT = "完结"; public static final String CATEGORY_TYPE_MONTH_TEXT = "包月"; // major(男生) public static final String CATEGORY_MAJOR_XH = "玄幻"; public static final String CATEGORY_MAJOR_QH = "奇幻"; public static final String CATEGORY_MAJOR_WX = "武侠"; public static final String CATEGORY_MAJOR_XX = "仙侠"; public static final String CATEGORY_MAJOR_DS = "都市"; public static final String CATEGORY_MAJOR_ZC = "职场"; public static final String CATEGORY_MAJOR_LS = "历史"; public static final String CATEGORY_MAJOR_JS = "军事"; public static final String CATEGORY_MAJOR_YX = "游戏"; public static final String CATEGORY_MAJOR_JJ = "竞技"; public static final String CATEGORY_MAJOR_KH = "科幻"; public static final String CATEGORY_MAJOR_LY = "灵异"; public static final String CATEGORY_MAJOR_TR = "同人"; public static final String CATEGORY_MAJOR_QXS = "轻小说"; // major(女生) public static final String CATEGORY_MAJOR_GDYQ = "古代言情"; public static final String CATEGORY_MAJOR_XDYQ = "现代言情"; public static final String CATEGORY_MAJOR_QCXY = "青春校园"; public static final String CATEGORY_MAJOR_CA = "纯爱"; public static final String CATEGORY_MAJOR_XHQH = "玄幻奇幻"; public static final String CATEGORY_MAJOR_WXXX = "武侠仙侠"; // major(出版) public static final String CATEGORY_MAJOR_CBXS = "出版小说"; public static final String CATEGORY_MAJOR_ZJMZ = "传记名著"; public static final String CATEGORY_MAJOR_CGLZ = "成功励志"; public static final String CATEGORY_MAJOR_RWSK = "人文社科"; public static final String CATEGORY_MAJOR_JGLC = "经管理财"; public static final String CATEGORY_MAJOR_SHSS = "生活时尚"; public static final String CATEGORY_MAJOR_YEJK = "育儿健康"; public static final String CATEGORY_MAJOR_QCYQ = "青春言情"; public static final String CATEGORY_MAJOR_WWYB = "外文原版"; public static final String CATEGORY_MAJOR_ZZJS = "政治军事"; /* 全部小说 */ public static final int NOVEL_PAGE_NUM = 10; // 每页的小说数 }
false
2,014
6
2,425
5
2,198
4
2,425
5
3,075
9
false
false
false
false
false
true
32582_3
package com.wxsf.fhr.model; import java.awt.Graphics; import com.wxsf.fhr.main.GamePanel; public class SuperObject { public SuperObject() { px = py = vx = vy = 0.0; frame = size = type = life = 0; color = 'r'; th = 0.0D; exist = false; anime = 0; } public static void gameObjectInit(GamePanel gamepanel) { p = gamepanel; } public void setData(double d, double d1, double d2, double d3, int i, int j, int k, int l, char c) { px = d; py = d1; vx = d2; vy = d3; size = i; frame = j; type = k; life = l; color = c; exist = true; }//th = Math.toRadians(-9D); public double setTh(double d, double d1) { if(d1 == 0.0D) th = Math.toRadians(90D); else th = Math.atan(d / d1); return th; } public double setTh(double d) { return th = d; } public void move() { px += vx; py += vy; frame++; //每次移动是frame+1 if(px < 0.0D || py < 0.0D || px > 640D || py > 640D) exist = false; } public void draw(Graphics g) { if(!exist) return; int c = 0; // boolean flag = false; if(color == 'g') //绿弹弹 c = 65; if(color == 'b') //蓝弹弹 c = 128; if(color == 'c') //笨蛋 c = 194; if(color == 'w') //巫女 c = 224; if(color == 'h') //小黑 c = 256; if(color == 'p') //噗噗 c = 320; if(color == 'x') c=10; /////////////////////////////////////TODO if(size <= 32) //小boss { int i = ((size / 4 - 1)) * 32; g.drawImage(p.image, (int)px - 16, (int)py - 16, (int)px + 16, (int)py + 16, c, i, c + 32, i + 32, null); } ////////////////////////////////////////////////////////大boss if(size==100){ //普通状态 g.drawImage(p.image, (int)px - 32, (int)py - 32, (int)px + 32, (int)py + 32, 195, 449, 255, 510, null); } else if(size>100&&size<200) //狂怒状态 g.drawImage(p.image, (int)px - 32, (int)py - 32, (int)px + 32, (int)py + 32, 259, 449, 319, 510, null); } public void erase() { exist = false; } public void eraseWithEffect() { if(!exist) return; if((tmp2 = p.effects.getEmpty()) != null) tmp2.setData(px, py, 0.0D, 0.0D, size / 2, 0, size / 4, 5, color); erase(); } public double getPx() { return px; } public double getPy() { return py; } public double getVx() { return vx; } public double getVy() { return vy; } public double getTh() { return th; } public int getSize() { return size; } public int getFrame() { return frame; } public int getType() { return type; } public int getLife() { return life; } public char getColor() { return color; } public boolean getExist() { return exist; } protected static GamePanel p; protected double px; protected double py; protected double vx; protected double vy; protected double th; protected int size; protected int frame; protected int type; protected int life; protected int anime; protected char color; protected boolean exist; protected SuperObject tmp; protected SuperObject tmp2; }
Mtora/Touhou-Rage-Danmaku
src/com/wxsf/fhr/model/SuperObject.java
1,180
//绿弹弹
line_comment
zh-cn
package com.wxsf.fhr.model; import java.awt.Graphics; import com.wxsf.fhr.main.GamePanel; public class SuperObject { public SuperObject() { px = py = vx = vy = 0.0; frame = size = type = life = 0; color = 'r'; th = 0.0D; exist = false; anime = 0; } public static void gameObjectInit(GamePanel gamepanel) { p = gamepanel; } public void setData(double d, double d1, double d2, double d3, int i, int j, int k, int l, char c) { px = d; py = d1; vx = d2; vy = d3; size = i; frame = j; type = k; life = l; color = c; exist = true; }//th = Math.toRadians(-9D); public double setTh(double d, double d1) { if(d1 == 0.0D) th = Math.toRadians(90D); else th = Math.atan(d / d1); return th; } public double setTh(double d) { return th = d; } public void move() { px += vx; py += vy; frame++; //每次移动是frame+1 if(px < 0.0D || py < 0.0D || px > 640D || py > 640D) exist = false; } public void draw(Graphics g) { if(!exist) return; int c = 0; // boolean flag = false; if(color == 'g') //绿弹 <SUF> c = 65; if(color == 'b') //蓝弹弹 c = 128; if(color == 'c') //笨蛋 c = 194; if(color == 'w') //巫女 c = 224; if(color == 'h') //小黑 c = 256; if(color == 'p') //噗噗 c = 320; if(color == 'x') c=10; /////////////////////////////////////TODO if(size <= 32) //小boss { int i = ((size / 4 - 1)) * 32; g.drawImage(p.image, (int)px - 16, (int)py - 16, (int)px + 16, (int)py + 16, c, i, c + 32, i + 32, null); } ////////////////////////////////////////////////////////大boss if(size==100){ //普通状态 g.drawImage(p.image, (int)px - 32, (int)py - 32, (int)px + 32, (int)py + 32, 195, 449, 255, 510, null); } else if(size>100&&size<200) //狂怒状态 g.drawImage(p.image, (int)px - 32, (int)py - 32, (int)px + 32, (int)py + 32, 259, 449, 319, 510, null); } public void erase() { exist = false; } public void eraseWithEffect() { if(!exist) return; if((tmp2 = p.effects.getEmpty()) != null) tmp2.setData(px, py, 0.0D, 0.0D, size / 2, 0, size / 4, 5, color); erase(); } public double getPx() { return px; } public double getPy() { return py; } public double getVx() { return vx; } public double getVy() { return vy; } public double getTh() { return th; } public int getSize() { return size; } public int getFrame() { return frame; } public int getType() { return type; } public int getLife() { return life; } public char getColor() { return color; } public boolean getExist() { return exist; } protected static GamePanel p; protected double px; protected double py; protected double vx; protected double vy; protected double th; protected int size; protected int frame; protected int type; protected int life; protected int anime; protected char color; protected boolean exist; protected SuperObject tmp; protected SuperObject tmp2; }
false
1,123
4
1,180
5
1,304
4
1,180
5
1,457
10
false
false
false
false
false
true
23148_1
package cse.ooad.project.model; import jakarta.persistence.*; import lombok.*; import java.sql.Timestamp; import java.util.Objects; /** * {@link Comment}用于表示评论信息的实体类,包括评论的基本信息和属性。<br> * 属性列表: * <ul> * <li>commentId: 评论ID,唯一标识评论。</li> * <li>title: 评论标题。</li> * <li>body: 评论内容。</li> * <li>userId: 评论发表者的帐户ID。老师和学生都可以评论。</li> * <li>postId: 评论所属的帖子ID。</li> * <li>creationTime: 评论创建时间。</li> * <li>disabled: 评论是否被禁用。</li> * <li>[映射][未使用]post: 评论所属的帖子。</li> * <li>[映射][未使用]replyList: 评论的回复列表。</li> * </ul> * 评论的嵌套方式:<br> * 每个房间拥有一条元评论,元评论的postId为0,userId为房间的ID。<br> * 对这个房间发起的评论视为对元评论的回复,其postId为元评论的commentId,userId为发起评论的用户ID。<br> * 若对评论发起的评论,其postId为被回复的评论的commentId,userId为发起评论的用户ID。<br> */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "comments", schema = "public", catalog = "cs309a") public class Comment { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id @Column(name = "comment_id") private Long commentId; @Basic @Column(name = "title") private String title; @Basic @Column(name = "body") private String body; @Basic @Column(name = "user_id") private Long userId; @Basic @Column(name = "post_id") private Long postId; @Basic @Column(name = "creation_date") private Timestamp creationTime; @Basic @Column(name = "disabled") private Boolean disabled; /* 映射实体 */ // todo: 不加了 增加工作量 或者加上也可以?再说 // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "post_id", insertable = false, updatable = false) // private Comment post; // // @Exclude // @JsonIgnore // @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) // private List<Comment> replyList; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Comment comment = (Comment) o; return Objects.equals(commentId, comment.commentId) && Objects.equals(title, comment.title) && Objects.equals(body, comment.body) && Objects.equals(userId, comment.userId) && Objects.equals(postId, comment.postId) && Objects.equals(creationTime, comment.creationTime) && Objects.equals(disabled, comment.disabled); } @Override public int hashCode() { return Objects.hash(commentId, title, body, userId, postId, creationTime, disabled); } }
MuuuShin/CS309_23Fall_Project
project/project/model/Comment.java
860
/* 映射实体 */
block_comment
zh-cn
package cse.ooad.project.model; import jakarta.persistence.*; import lombok.*; import java.sql.Timestamp; import java.util.Objects; /** * {@link Comment}用于表示评论信息的实体类,包括评论的基本信息和属性。<br> * 属性列表: * <ul> * <li>commentId: 评论ID,唯一标识评论。</li> * <li>title: 评论标题。</li> * <li>body: 评论内容。</li> * <li>userId: 评论发表者的帐户ID。老师和学生都可以评论。</li> * <li>postId: 评论所属的帖子ID。</li> * <li>creationTime: 评论创建时间。</li> * <li>disabled: 评论是否被禁用。</li> * <li>[映射][未使用]post: 评论所属的帖子。</li> * <li>[映射][未使用]replyList: 评论的回复列表。</li> * </ul> * 评论的嵌套方式:<br> * 每个房间拥有一条元评论,元评论的postId为0,userId为房间的ID。<br> * 对这个房间发起的评论视为对元评论的回复,其postId为元评论的commentId,userId为发起评论的用户ID。<br> * 若对评论发起的评论,其postId为被回复的评论的commentId,userId为发起评论的用户ID。<br> */ @Getter @Setter @ToString @AllArgsConstructor @NoArgsConstructor @Entity @Table(name = "comments", schema = "public", catalog = "cs309a") public class Comment { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id @Column(name = "comment_id") private Long commentId; @Basic @Column(name = "title") private String title; @Basic @Column(name = "body") private String body; @Basic @Column(name = "user_id") private Long userId; @Basic @Column(name = "post_id") private Long postId; @Basic @Column(name = "creation_date") private Timestamp creationTime; @Basic @Column(name = "disabled") private Boolean disabled; /* 映射实 <SUF>*/ // todo: 不加了 增加工作量 或者加上也可以?再说 // @ManyToOne(fetch = FetchType.LAZY) // @JoinColumn(name = "post_id", insertable = false, updatable = false) // private Comment post; // // @Exclude // @JsonIgnore // @OneToMany(mappedBy = "post", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY) // private List<Comment> replyList; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Comment comment = (Comment) o; return Objects.equals(commentId, comment.commentId) && Objects.equals(title, comment.title) && Objects.equals(body, comment.body) && Objects.equals(userId, comment.userId) && Objects.equals(postId, comment.postId) && Objects.equals(creationTime, comment.creationTime) && Objects.equals(disabled, comment.disabled); } @Override public int hashCode() { return Objects.hash(commentId, title, body, userId, postId, creationTime, disabled); } }
false
745
6
860
5
836
5
860
5
1,154
11
false
false
false
false
false
true
55300_0
package com.lhm; /* 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的 是原来第几号的那位。 */ public class PeopleWeiCircle { public static void main(String[] args) { } public static void method(int n){ } }
MuziMin0222/muzimin-bigdata-study
muzimin-arithmetic-study/arithmetic-01/src/main/java/com/lhm/PeopleWeiCircle.java
98
/* 有n个人围成一圈,顺序排号。从第一个人开始报数(从1到3报数),凡报到3的人退出圈子,问最后留下的 是原来第几号的那位。 */
block_comment
zh-cn
package com.lhm; /* 有n个 <SUF>*/ public class PeopleWeiCircle { public static void main(String[] args) { } public static void method(int n){ } }
false
82
48
98
57
97
52
98
57
137
88
false
false
false
false
false
true
51544_7
package zliu.elliot.huawei; import java.util.Scanner; public class solution3 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 地图大小 int n = scanner.nextInt(); // 怪兽 boolean[][] monster = new boolean[n][n]; int k = scanner.nextInt(); for (int i = 0; i < k; ++i) { int r = scanner.nextInt(); int c = scanner.nextInt(); monster[r][c] = true; } // 公主位置 int princessR = scanner.nextInt(); int princessC = scanner.nextInt(); // 王子 int knightR = scanner.nextInt(); int knightC = scanner.nextInt(); String[][] carrier = new String[n][n]; scanner.nextLine(); for (int i = 0; i < n; ++i) { String line = scanner.nextLine(); carrier[i] = line.trim().split(" "); } solution3 solution3 = new solution3(); solution3.carrier = carrier; solution3.monster = monster; solution3.princess = new int[]{princessR, princessC}; solution3.dfsSave(knightR, knightC, 0, 1); System.out.println(solution3.minTime); } int minTime = Integer.MAX_VALUE; boolean[][] monster = null; String[][] carrier = null; int[] princess = null; /** * * @param r 当前行 * @param c * @param timestamp 当前时间点 */ public void dfsSave(int r, int c, int timestamp, int wait) { if (timestamp>minTime) { // 超时剪枝 return; } if (r == princess[0] && c == princess[1]) { // 到达目标 minTime = Math.min(timestamp, minTime); return; } int nextCarrier = (timestamp+1)%3; if (r-1 >= 0 && !monster[r-1][c] && carrier[r-1][c].charAt(nextCarrier)=='0') { // 向上走 dfsSave(r-1, c, timestamp+1, 1); } if (r+1 < monster.length && !monster[r+1][c] && carrier[r+1][c].charAt(nextCarrier)=='0') { // 向下走 dfsSave(r+1, c, timestamp+1, 1); } if (c-1 >= 0 && !monster[r][c-1] && carrier[r][c-1].charAt(nextCarrier)=='0') { // 向左走 dfsSave(r, c-1, timestamp+1, 1); } if (c+1 < monster.length && !monster[r][c+1] && carrier[r][c+1].charAt(nextCarrier)=='0') { // 向右走 dfsSave(r, c+1, timestamp+1, 1); } if (carrier[r][c].charAt(nextCarrier)=='0' && wait <= 3) { // 原地不动 dfsSave(r,c, timestamp+1, wait+1); } } }
My-captain/algorithm
src/zliu/elliot/huawei/solution3.java
791
// 向左走
line_comment
zh-cn
package zliu.elliot.huawei; import java.util.Scanner; public class solution3 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // 地图大小 int n = scanner.nextInt(); // 怪兽 boolean[][] monster = new boolean[n][n]; int k = scanner.nextInt(); for (int i = 0; i < k; ++i) { int r = scanner.nextInt(); int c = scanner.nextInt(); monster[r][c] = true; } // 公主位置 int princessR = scanner.nextInt(); int princessC = scanner.nextInt(); // 王子 int knightR = scanner.nextInt(); int knightC = scanner.nextInt(); String[][] carrier = new String[n][n]; scanner.nextLine(); for (int i = 0; i < n; ++i) { String line = scanner.nextLine(); carrier[i] = line.trim().split(" "); } solution3 solution3 = new solution3(); solution3.carrier = carrier; solution3.monster = monster; solution3.princess = new int[]{princessR, princessC}; solution3.dfsSave(knightR, knightC, 0, 1); System.out.println(solution3.minTime); } int minTime = Integer.MAX_VALUE; boolean[][] monster = null; String[][] carrier = null; int[] princess = null; /** * * @param r 当前行 * @param c * @param timestamp 当前时间点 */ public void dfsSave(int r, int c, int timestamp, int wait) { if (timestamp>minTime) { // 超时剪枝 return; } if (r == princess[0] && c == princess[1]) { // 到达目标 minTime = Math.min(timestamp, minTime); return; } int nextCarrier = (timestamp+1)%3; if (r-1 >= 0 && !monster[r-1][c] && carrier[r-1][c].charAt(nextCarrier)=='0') { // 向上走 dfsSave(r-1, c, timestamp+1, 1); } if (r+1 < monster.length && !monster[r+1][c] && carrier[r+1][c].charAt(nextCarrier)=='0') { // 向下走 dfsSave(r+1, c, timestamp+1, 1); } if (c-1 >= 0 && !monster[r][c-1] && carrier[r][c-1].charAt(nextCarrier)=='0') { // 向左 <SUF> dfsSave(r, c-1, timestamp+1, 1); } if (c+1 < monster.length && !monster[r][c+1] && carrier[r][c+1].charAt(nextCarrier)=='0') { // 向右走 dfsSave(r, c+1, timestamp+1, 1); } if (carrier[r][c].charAt(nextCarrier)=='0' && wait <= 3) { // 原地不动 dfsSave(r,c, timestamp+1, wait+1); } } }
false
722
5
791
5
821
4
791
5
953
7
false
false
false
false
false
true
13686_6
/* * Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.config; import java.io.IOException; import java.net.StandardSocketOptions; import java.nio.channels.NetworkChannel; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; import io.mycat.backend.datasource.PhysicalDBNode; import io.mycat.backend.datasource.PhysicalDBPool; import io.mycat.config.model.FirewallConfig; import io.mycat.config.model.SchemaConfig; import io.mycat.config.model.SystemConfig; import io.mycat.config.model.UserConfig; import io.mycat.net.AbstractConnection; import io.mycat.util.TimeUtil; /** * @author mycat */ public class MycatConfig { private static final int RELOAD = 1; private static final int ROLLBACK = 2; private static final int RELOAD_ALL = 3; private volatile SystemConfig system; private volatile MycatCluster cluster; private volatile MycatCluster _cluster; private volatile FirewallConfig firewall; private volatile FirewallConfig _firewall; private volatile Map<String, UserConfig> users; private volatile Map<String, UserConfig> _users; private volatile Map<String, SchemaConfig> schemas; private volatile Map<String, SchemaConfig> _schemas; private volatile Map<String, PhysicalDBNode> dataNodes; private volatile Map<String, PhysicalDBNode> _dataNodes; private volatile Map<String, PhysicalDBPool> dataHosts; private volatile Map<String, PhysicalDBPool> _dataHosts; private long reloadTime; private long rollbackTime; private int status; private final ReentrantLock lock; public MycatConfig() { //读取schema.xml,rule.xml和server.xml ConfigInitializer confInit = new ConfigInitializer(true); this.system = confInit.getSystem(); this.users = confInit.getUsers(); this.schemas = confInit.getSchemas(); this.dataHosts = confInit.getDataHosts(); this.dataNodes = confInit.getDataNodes(); for (PhysicalDBPool dbPool : dataHosts.values()) { dbPool.setSchemas(getDataNodeSchemasOfDataHost(dbPool.getHostName())); } this.firewall = confInit.getFirewall(); this.cluster = confInit.getCluster(); //初始化重加载配置时间 this.reloadTime = TimeUtil.currentTimeMillis(); this.rollbackTime = -1L; this.status = RELOAD; //配置加载锁 this.lock = new ReentrantLock(); } public SystemConfig getSystem() { return system; } public void setSocketParams(AbstractConnection con, boolean isFrontChannel) throws IOException { int sorcvbuf = 0; int sosndbuf = 0; int soNoDelay = 0; if ( isFrontChannel ) { sorcvbuf = system.getFrontsocketsorcvbuf(); sosndbuf = system.getFrontsocketsosndbuf(); soNoDelay = system.getFrontSocketNoDelay(); } else { sorcvbuf = system.getBacksocketsorcvbuf(); sosndbuf = system.getBacksocketsosndbuf(); soNoDelay = system.getBackSocketNoDelay(); } NetworkChannel channel = con.getChannel(); channel.setOption(StandardSocketOptions.SO_RCVBUF, sorcvbuf); channel.setOption(StandardSocketOptions.SO_SNDBUF, sosndbuf); channel.setOption(StandardSocketOptions.TCP_NODELAY, soNoDelay == 1); channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); con.setMaxPacketSize(system.getMaxPacketSize()); con.setPacketHeaderSize(system.getPacketHeaderSize()); con.setIdleTimeout(system.getIdleTimeout()); con.setCharset(system.getCharset()); } public Map<String, UserConfig> getUsers() { return users; } public Map<String, UserConfig> getBackupUsers() { return _users; } public Map<String, SchemaConfig> getSchemas() { return schemas; } public Map<String, SchemaConfig> getBackupSchemas() { return _schemas; } public Map<String, PhysicalDBNode> getDataNodes() { return dataNodes; } public void setDataNodes( Map<String, PhysicalDBNode> map) { this.dataNodes = map; } public String[] getDataNodeSchemasOfDataHost(String dataHost) { ArrayList<String> schemas = new ArrayList<String>(30); for (PhysicalDBNode dn: dataNodes.values()) { if (dn.getDbPool().getHostName().equals(dataHost)) { schemas.add(dn.getDatabase()); } } return schemas.toArray(new String[schemas.size()]); } public Map<String, PhysicalDBNode> getBackupDataNodes() { return _dataNodes; } public Map<String, PhysicalDBPool> getDataHosts() { return dataHosts; } public Map<String, PhysicalDBPool> getBackupDataHosts() { return _dataHosts; } public MycatCluster getCluster() { return cluster; } public MycatCluster getBackupCluster() { return _cluster; } public FirewallConfig getFirewall() { return firewall; } public FirewallConfig getBackupFirewall() { return _firewall; } public ReentrantLock getLock() { return lock; } public long getReloadTime() { return reloadTime; } public long getRollbackTime() { return rollbackTime; } public void reload( Map<String, UserConfig> newUsers, Map<String, SchemaConfig> newSchemas, Map<String, PhysicalDBNode> newDataNodes, Map<String, PhysicalDBPool> newDataHosts, MycatCluster newCluster, FirewallConfig newFirewall, boolean reloadAll) { apply(newUsers, newSchemas, newDataNodes, newDataHosts, newCluster, newFirewall, reloadAll); this.reloadTime = TimeUtil.currentTimeMillis(); this.status = reloadAll?RELOAD_ALL:RELOAD; } public boolean canRollback() { if (_users == null || _schemas == null || _dataNodes == null || _dataHosts == null || _cluster == null || _firewall == null || status == ROLLBACK) { return false; } else { return true; } } public void rollback( Map<String, UserConfig> users, Map<String, SchemaConfig> schemas, Map<String, PhysicalDBNode> dataNodes, Map<String, PhysicalDBPool> dataHosts, MycatCluster cluster, FirewallConfig firewall) { apply(users, schemas, dataNodes, dataHosts, cluster, firewall, status==RELOAD_ALL); this.rollbackTime = TimeUtil.currentTimeMillis(); this.status = ROLLBACK; } private void apply(Map<String, UserConfig> newUsers, Map<String, SchemaConfig> newSchemas, Map<String, PhysicalDBNode> newDataNodes, Map<String, PhysicalDBPool> newDataHosts, MycatCluster newCluster, FirewallConfig newFirewall, boolean isLoadAll) { final ReentrantLock lock = this.lock; lock.lock(); try { // old 处理 // 1、停止老的数据源心跳 // 2、备份老的数据源配置 //-------------------------------------------- if (isLoadAll) { Map<String, PhysicalDBPool> oldDataHosts = this.dataHosts; if (oldDataHosts != null) { for (PhysicalDBPool oldDbPool : oldDataHosts.values()) { if (oldDbPool != null) { oldDbPool.stopHeartbeat(); } } } this._dataNodes = this.dataNodes; this._dataHosts = this.dataHosts; } this._users = this.users; this._schemas = this.schemas; this._cluster = this.cluster; this._firewall = this.firewall; // new 处理 // 1、启动新的数据源心跳 // 2、执行新的配置 //--------------------------------------------------- if (isLoadAll) { if (newDataHosts != null) { for (PhysicalDBPool newDbPool : newDataHosts.values()) { if ( newDbPool != null) { newDbPool.startHeartbeat(); } } } this.dataNodes = newDataNodes; this.dataHosts = newDataHosts; } this.users = newUsers; this.schemas = newSchemas; this.cluster = newCluster; this.firewall = newFirewall; } finally { lock.unlock(); } } }
MyCATApache/Mycat-Server
src/main/java/io/mycat/config/MycatConfig.java
2,528
// 1、停止老的数据源心跳
line_comment
zh-cn
/* * Copyright (c) 2020, OpenCloudDB/MyCAT and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software;Designed and Developed mainly by many Chinese * opensource volunteers. you can redistribute it and/or modify it under the * terms of the GNU General Public License version 2 only, 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Any questions about this component can be directed to it's project Web address * https://code.google.com/p/opencloudb/. * */ package io.mycat.config; import java.io.IOException; import java.net.StandardSocketOptions; import java.nio.channels.NetworkChannel; import java.util.ArrayList; import java.util.Map; import java.util.concurrent.locks.ReentrantLock; import io.mycat.backend.datasource.PhysicalDBNode; import io.mycat.backend.datasource.PhysicalDBPool; import io.mycat.config.model.FirewallConfig; import io.mycat.config.model.SchemaConfig; import io.mycat.config.model.SystemConfig; import io.mycat.config.model.UserConfig; import io.mycat.net.AbstractConnection; import io.mycat.util.TimeUtil; /** * @author mycat */ public class MycatConfig { private static final int RELOAD = 1; private static final int ROLLBACK = 2; private static final int RELOAD_ALL = 3; private volatile SystemConfig system; private volatile MycatCluster cluster; private volatile MycatCluster _cluster; private volatile FirewallConfig firewall; private volatile FirewallConfig _firewall; private volatile Map<String, UserConfig> users; private volatile Map<String, UserConfig> _users; private volatile Map<String, SchemaConfig> schemas; private volatile Map<String, SchemaConfig> _schemas; private volatile Map<String, PhysicalDBNode> dataNodes; private volatile Map<String, PhysicalDBNode> _dataNodes; private volatile Map<String, PhysicalDBPool> dataHosts; private volatile Map<String, PhysicalDBPool> _dataHosts; private long reloadTime; private long rollbackTime; private int status; private final ReentrantLock lock; public MycatConfig() { //读取schema.xml,rule.xml和server.xml ConfigInitializer confInit = new ConfigInitializer(true); this.system = confInit.getSystem(); this.users = confInit.getUsers(); this.schemas = confInit.getSchemas(); this.dataHosts = confInit.getDataHosts(); this.dataNodes = confInit.getDataNodes(); for (PhysicalDBPool dbPool : dataHosts.values()) { dbPool.setSchemas(getDataNodeSchemasOfDataHost(dbPool.getHostName())); } this.firewall = confInit.getFirewall(); this.cluster = confInit.getCluster(); //初始化重加载配置时间 this.reloadTime = TimeUtil.currentTimeMillis(); this.rollbackTime = -1L; this.status = RELOAD; //配置加载锁 this.lock = new ReentrantLock(); } public SystemConfig getSystem() { return system; } public void setSocketParams(AbstractConnection con, boolean isFrontChannel) throws IOException { int sorcvbuf = 0; int sosndbuf = 0; int soNoDelay = 0; if ( isFrontChannel ) { sorcvbuf = system.getFrontsocketsorcvbuf(); sosndbuf = system.getFrontsocketsosndbuf(); soNoDelay = system.getFrontSocketNoDelay(); } else { sorcvbuf = system.getBacksocketsorcvbuf(); sosndbuf = system.getBacksocketsosndbuf(); soNoDelay = system.getBackSocketNoDelay(); } NetworkChannel channel = con.getChannel(); channel.setOption(StandardSocketOptions.SO_RCVBUF, sorcvbuf); channel.setOption(StandardSocketOptions.SO_SNDBUF, sosndbuf); channel.setOption(StandardSocketOptions.TCP_NODELAY, soNoDelay == 1); channel.setOption(StandardSocketOptions.SO_REUSEADDR, true); channel.setOption(StandardSocketOptions.SO_KEEPALIVE, true); con.setMaxPacketSize(system.getMaxPacketSize()); con.setPacketHeaderSize(system.getPacketHeaderSize()); con.setIdleTimeout(system.getIdleTimeout()); con.setCharset(system.getCharset()); } public Map<String, UserConfig> getUsers() { return users; } public Map<String, UserConfig> getBackupUsers() { return _users; } public Map<String, SchemaConfig> getSchemas() { return schemas; } public Map<String, SchemaConfig> getBackupSchemas() { return _schemas; } public Map<String, PhysicalDBNode> getDataNodes() { return dataNodes; } public void setDataNodes( Map<String, PhysicalDBNode> map) { this.dataNodes = map; } public String[] getDataNodeSchemasOfDataHost(String dataHost) { ArrayList<String> schemas = new ArrayList<String>(30); for (PhysicalDBNode dn: dataNodes.values()) { if (dn.getDbPool().getHostName().equals(dataHost)) { schemas.add(dn.getDatabase()); } } return schemas.toArray(new String[schemas.size()]); } public Map<String, PhysicalDBNode> getBackupDataNodes() { return _dataNodes; } public Map<String, PhysicalDBPool> getDataHosts() { return dataHosts; } public Map<String, PhysicalDBPool> getBackupDataHosts() { return _dataHosts; } public MycatCluster getCluster() { return cluster; } public MycatCluster getBackupCluster() { return _cluster; } public FirewallConfig getFirewall() { return firewall; } public FirewallConfig getBackupFirewall() { return _firewall; } public ReentrantLock getLock() { return lock; } public long getReloadTime() { return reloadTime; } public long getRollbackTime() { return rollbackTime; } public void reload( Map<String, UserConfig> newUsers, Map<String, SchemaConfig> newSchemas, Map<String, PhysicalDBNode> newDataNodes, Map<String, PhysicalDBPool> newDataHosts, MycatCluster newCluster, FirewallConfig newFirewall, boolean reloadAll) { apply(newUsers, newSchemas, newDataNodes, newDataHosts, newCluster, newFirewall, reloadAll); this.reloadTime = TimeUtil.currentTimeMillis(); this.status = reloadAll?RELOAD_ALL:RELOAD; } public boolean canRollback() { if (_users == null || _schemas == null || _dataNodes == null || _dataHosts == null || _cluster == null || _firewall == null || status == ROLLBACK) { return false; } else { return true; } } public void rollback( Map<String, UserConfig> users, Map<String, SchemaConfig> schemas, Map<String, PhysicalDBNode> dataNodes, Map<String, PhysicalDBPool> dataHosts, MycatCluster cluster, FirewallConfig firewall) { apply(users, schemas, dataNodes, dataHosts, cluster, firewall, status==RELOAD_ALL); this.rollbackTime = TimeUtil.currentTimeMillis(); this.status = ROLLBACK; } private void apply(Map<String, UserConfig> newUsers, Map<String, SchemaConfig> newSchemas, Map<String, PhysicalDBNode> newDataNodes, Map<String, PhysicalDBPool> newDataHosts, MycatCluster newCluster, FirewallConfig newFirewall, boolean isLoadAll) { final ReentrantLock lock = this.lock; lock.lock(); try { // old 处理 // 1、 <SUF> // 2、备份老的数据源配置 //-------------------------------------------- if (isLoadAll) { Map<String, PhysicalDBPool> oldDataHosts = this.dataHosts; if (oldDataHosts != null) { for (PhysicalDBPool oldDbPool : oldDataHosts.values()) { if (oldDbPool != null) { oldDbPool.stopHeartbeat(); } } } this._dataNodes = this.dataNodes; this._dataHosts = this.dataHosts; } this._users = this.users; this._schemas = this.schemas; this._cluster = this.cluster; this._firewall = this.firewall; // new 处理 // 1、启动新的数据源心跳 // 2、执行新的配置 //--------------------------------------------------- if (isLoadAll) { if (newDataHosts != null) { for (PhysicalDBPool newDbPool : newDataHosts.values()) { if ( newDbPool != null) { newDbPool.startHeartbeat(); } } } this.dataNodes = newDataNodes; this.dataHosts = newDataHosts; } this.users = newUsers; this.schemas = newSchemas; this.cluster = newCluster; this.firewall = newFirewall; } finally { lock.unlock(); } } }
false
2,187
9
2,528
10
2,545
9
2,528
10
3,170
17
false
false
false
false
false
true
9755_3
package io.mycat.fabric.phdc.entity; import java.util.Date; import javax.persistence.*; @Table(name = "tb_result") public class Result { /** * ID */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 预约ID */ @Column(name = "reserve_id") private Integer reserveId; /** * 预约人ID */ @Column(name = "member_id") private Integer memberId; /** * 检查项ID */ @Column(name = "exam_dict_id") private Integer examDictId; /** * 科室医生 */ @Column(name = "depart_doctor") private String departDoctor; /** * 医生 */ @Column(name = "check_doctor") private String checkDoctor; /** * 创建时间 */ @Column(name = "create_time") private Date createTime; /** * 结果状态 1)未出结果 2)已出结果 */ private Byte status; /** * 检查结果 */ private String result; /** * 结论 */ private String summary; /** * 获取ID * * @return id - ID */ public Integer getId() { return id; } /** * 设置ID * * @param id ID */ public void setId(Integer id) { this.id = id; } /** * 获取预约ID * * @return reserve_id - 预约ID */ public Integer getReserveId() { return reserveId; } /** * 设置预约ID * * @param reserveId 预约ID */ public void setReserveId(Integer reserveId) { this.reserveId = reserveId; } /** * 获取预约人ID * * @return member_id - 预约人ID */ public Integer getMemberId() { return memberId; } /** * 设置预约人ID * * @param memberId 预约人ID */ public void setMemberId(Integer memberId) { this.memberId = memberId; } /** * 获取检查项ID * * @return exam_dict_id - 检查项ID */ public Integer getExamDictId() { return examDictId; } /** * 设置检查项ID * * @param examDictId 检查项ID */ public void setExamDictId(Integer examDictId) { this.examDictId = examDictId; } /** * 获取科室医生 * * @return depart_doctor - 科室医生 */ public String getDepartDoctor() { return departDoctor; } /** * 设置科室医生 * * @param departDoctor 科室医生 */ public void setDepartDoctor(String departDoctor) { this.departDoctor = departDoctor == null ? null : departDoctor.trim(); } /** * 获取医生 * * @return check_doctor - 医生 */ public String getCheckDoctor() { return checkDoctor; } /** * 设置医生 * * @param checkDoctor 医生 */ public void setCheckDoctor(String checkDoctor) { this.checkDoctor = checkDoctor == null ? null : checkDoctor.trim(); } /** * 获取创建时间 * * @return create_time - 创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置创建时间 * * @param createTime 创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取结果状态 1)未出结果 2)已出结果 * * @return status - 结果状态 1)未出结果 2)已出结果 */ public Byte getStatus() { return status; } /** * 设置结果状态 1)未出结果 2)已出结果 * * @param status 结果状态 1)未出结果 2)已出结果 */ public void setStatus(Byte status) { this.status = status; } /** * 获取检查结果 * * @return result - 检查结果 */ public String getResult() { return result; } /** * 设置检查结果 * * @param result 检查结果 */ public void setResult(String result) { this.result = result == null ? null : result.trim(); } /** * 获取结论 * * @return summary - 结论 */ public String getSummary() { return summary; } /** * 设置结论 * * @param summary 结论 */ public void setSummary(String summary) { this.summary = summary == null ? null : summary.trim(); } }
MyCATApache/SuperLedger
PHDC/java/src/main/java/io/mycat/fabric/phdc/entity/Result.java
1,151
/** * 检查项ID */
block_comment
zh-cn
package io.mycat.fabric.phdc.entity; import java.util.Date; import javax.persistence.*; @Table(name = "tb_result") public class Result { /** * ID */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; /** * 预约ID */ @Column(name = "reserve_id") private Integer reserveId; /** * 预约人ID */ @Column(name = "member_id") private Integer memberId; /** * 检查项 <SUF>*/ @Column(name = "exam_dict_id") private Integer examDictId; /** * 科室医生 */ @Column(name = "depart_doctor") private String departDoctor; /** * 医生 */ @Column(name = "check_doctor") private String checkDoctor; /** * 创建时间 */ @Column(name = "create_time") private Date createTime; /** * 结果状态 1)未出结果 2)已出结果 */ private Byte status; /** * 检查结果 */ private String result; /** * 结论 */ private String summary; /** * 获取ID * * @return id - ID */ public Integer getId() { return id; } /** * 设置ID * * @param id ID */ public void setId(Integer id) { this.id = id; } /** * 获取预约ID * * @return reserve_id - 预约ID */ public Integer getReserveId() { return reserveId; } /** * 设置预约ID * * @param reserveId 预约ID */ public void setReserveId(Integer reserveId) { this.reserveId = reserveId; } /** * 获取预约人ID * * @return member_id - 预约人ID */ public Integer getMemberId() { return memberId; } /** * 设置预约人ID * * @param memberId 预约人ID */ public void setMemberId(Integer memberId) { this.memberId = memberId; } /** * 获取检查项ID * * @return exam_dict_id - 检查项ID */ public Integer getExamDictId() { return examDictId; } /** * 设置检查项ID * * @param examDictId 检查项ID */ public void setExamDictId(Integer examDictId) { this.examDictId = examDictId; } /** * 获取科室医生 * * @return depart_doctor - 科室医生 */ public String getDepartDoctor() { return departDoctor; } /** * 设置科室医生 * * @param departDoctor 科室医生 */ public void setDepartDoctor(String departDoctor) { this.departDoctor = departDoctor == null ? null : departDoctor.trim(); } /** * 获取医生 * * @return check_doctor - 医生 */ public String getCheckDoctor() { return checkDoctor; } /** * 设置医生 * * @param checkDoctor 医生 */ public void setCheckDoctor(String checkDoctor) { this.checkDoctor = checkDoctor == null ? null : checkDoctor.trim(); } /** * 获取创建时间 * * @return create_time - 创建时间 */ public Date getCreateTime() { return createTime; } /** * 设置创建时间 * * @param createTime 创建时间 */ public void setCreateTime(Date createTime) { this.createTime = createTime; } /** * 获取结果状态 1)未出结果 2)已出结果 * * @return status - 结果状态 1)未出结果 2)已出结果 */ public Byte getStatus() { return status; } /** * 设置结果状态 1)未出结果 2)已出结果 * * @param status 结果状态 1)未出结果 2)已出结果 */ public void setStatus(Byte status) { this.status = status; } /** * 获取检查结果 * * @return result - 检查结果 */ public String getResult() { return result; } /** * 设置检查结果 * * @param result 检查结果 */ public void setResult(String result) { this.result = result == null ? null : result.trim(); } /** * 获取结论 * * @return summary - 结论 */ public String getSummary() { return summary; } /** * 设置结论 * * @param summary 结论 */ public void setSummary(String summary) { this.summary = summary == null ? null : summary.trim(); } }
false
1,139
12
1,151
9
1,304
10
1,151
9
1,626
14
false
false
false
false
false
true
871_1
package com.xu.drools.rule.complexProblem; import com.xu.drools.bean.Golfer; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; /** * 使用kmodule的方式调用drools * /resources/META-INF/kmodule.xml * 高尔夫球员站位问题 */ public class GolferProblem { /** * 已知有四个高尔夫球员,他们的名字是Fred,Joe,Bob,Tom; * 今天他们分别穿着红色,蓝色,橙色,以及格子衣服,并且他们按照从左往右的顺序站成一排。 * 我们将最左边的位置定为1,最右边的位置定为4,中间依次是2,3位置。 * 现在我们了解的情况是: * 1.高尔夫球员Fred,目前不知道他的位置和衣服颜色 * 2.Fred右边紧挨着的球员穿蓝色衣服 * 3.Joe排在第2个位置 * 4.Bob穿着格子短裤 * 5.Tom没有排在第1位或第4位,也没有穿橙色衣服 * 请问,这四名球员的位置和衣服颜色。 */ public static void main(final String[] args) { KieContainer kc = KieServices.Factory.get().getKieClasspathContainer(); System.out.println(kc.verify().getMessages().toString()); execute(kc); } private static void execute(KieContainer kc) { KieSession ksession = kc.newKieSession("mingKS"); String[] names = new String[]{"Fred", "Joe", "Bob", "Tom"}; String[] colors = new String[]{"red", "blue", "plaid", "orange"}; int[] positions = new int[]{1, 2, 3, 4}; for (String name : names) { for (String color : colors) { for (int position : positions) { ksession.insert(new Golfer(name, color, position)); } } } ksession.fireAllRules(); ksession.dispose(); } }
MyHerux/drools-springboot
src/main/java/com/xu/drools/rule/complexProblem/GolferProblem.java
566
/** * 已知有四个高尔夫球员,他们的名字是Fred,Joe,Bob,Tom; * 今天他们分别穿着红色,蓝色,橙色,以及格子衣服,并且他们按照从左往右的顺序站成一排。 * 我们将最左边的位置定为1,最右边的位置定为4,中间依次是2,3位置。 * 现在我们了解的情况是: * 1.高尔夫球员Fred,目前不知道他的位置和衣服颜色 * 2.Fred右边紧挨着的球员穿蓝色衣服 * 3.Joe排在第2个位置 * 4.Bob穿着格子短裤 * 5.Tom没有排在第1位或第4位,也没有穿橙色衣服 * 请问,这四名球员的位置和衣服颜色。 */
block_comment
zh-cn
package com.xu.drools.rule.complexProblem; import com.xu.drools.bean.Golfer; import org.kie.api.KieServices; import org.kie.api.runtime.KieContainer; import org.kie.api.runtime.KieSession; /** * 使用kmodule的方式调用drools * /resources/META-INF/kmodule.xml * 高尔夫球员站位问题 */ public class GolferProblem { /** * 已知有 <SUF>*/ public static void main(final String[] args) { KieContainer kc = KieServices.Factory.get().getKieClasspathContainer(); System.out.println(kc.verify().getMessages().toString()); execute(kc); } private static void execute(KieContainer kc) { KieSession ksession = kc.newKieSession("mingKS"); String[] names = new String[]{"Fred", "Joe", "Bob", "Tom"}; String[] colors = new String[]{"red", "blue", "plaid", "orange"}; int[] positions = new int[]{1, 2, 3, 4}; for (String name : names) { for (String color : colors) { for (int position : positions) { ksession.insert(new Golfer(name, color, position)); } } } ksession.fireAllRules(); ksession.dispose(); } }
false
479
191
566
234
525
194
566
234
695
323
true
true
true
true
true
false
32044_4
package v1; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.mllib.classification.LogisticRegressionModel; import org.apache.spark.mllib.classification.LogisticRegressionWithSGD; import org.apache.spark.mllib.linalg.Vector; import org.apache.spark.mllib.regression.LabeledPoint; import org.apache.spark.sql.SparkSession; import org.apache.spark.mllib.feature.HashingTF; import java.util.Arrays; import java.util.regex.Pattern; /** * Created by 張燿峰 * 机器学习入门案例 * 过滤垃圾邮件 * 这 个 程 序 使 用 了 MLlib 中 的 两 个 函 数:HashingTF 与 * LogisticRegressionWithSGD,前者从文本数据构建词频(term frequency)特征向量,后者 * 使用随机梯度下降法(Stochastic Gradient Descent,简称 SGD)实现逻辑回归。假设我们 * 从两个文件 spam.txt 与 normal.txt 开始,两个文件分别包含垃圾邮件和非垃圾邮件的例子, * 每行一个。接下来我们就根据词频把每个文件中的文本转化为特征向量,然后训练出一个 可以把两类消息分开的逻辑回归模型 * @author 孤 * @date 2019/5/7 * @Varsion 1.0 */ public class SpamEmail { private static final Pattern SPACE = Pattern.compile(" "); public static void main(String[] args) { SparkSession sparkSession = SparkSession.builder().appName("spam-email").master("local[2]").getOrCreate(); JavaSparkContext javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); //垃圾邮件数据 JavaRDD<String> spamEmail = javaSparkContext.textFile("spam.json"); //优质邮件数据 JavaRDD<String> normalEmail = javaSparkContext.textFile("normal.json"); //创建hashingTF实例把邮件文本映射为包含10000个特征的向量 final HashingTF hashingTF = new HashingTF(10000); JavaRDD<LabeledPoint> spamExamples = spamEmail.map(new Function<String, LabeledPoint>() { @Override public LabeledPoint call(String v1) throws Exception { return new LabeledPoint(0, hashingTF.transform(Arrays.asList(SPACE.split(v1)))); } }); JavaRDD<LabeledPoint> normaExamples = normalEmail.map(new Function<String, LabeledPoint>() { @Override public LabeledPoint call(String v1) throws Exception { return new LabeledPoint(1, hashingTF.transform(Arrays.asList(SPACE.split(v1)))); } }); //训练数据 JavaRDD<LabeledPoint> trainData = spamExamples.union(normaExamples); trainData.cache(); //逻辑回归需要迭代,先缓存 //随机梯度下降法 SGD 逻辑回归 LogisticRegressionModel model = new LogisticRegressionWithSGD().run(trainData.rdd()); Vector spamModel = hashingTF.transform(Arrays.asList(SPACE.split("垃 圾 钱 恶 心 色 情 赌 博 毒 品 败 类 犯罪"))); Vector normaModel = hashingTF.transform(Arrays.asList(SPACE.split("work 工作 你好 我们 请问 时间 领导"))); System.out.println("预测负面的例子: " + model.predict(spamModel)); System.out.println("预测积极的例子: " + model.predict(normaModel)); } }
Mydreamandreality/sparkResearch
chapter23/src/main/java/v1/SpamEmail.java
934
//训练数据
line_comment
zh-cn
package v1; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function; import org.apache.spark.mllib.classification.LogisticRegressionModel; import org.apache.spark.mllib.classification.LogisticRegressionWithSGD; import org.apache.spark.mllib.linalg.Vector; import org.apache.spark.mllib.regression.LabeledPoint; import org.apache.spark.sql.SparkSession; import org.apache.spark.mllib.feature.HashingTF; import java.util.Arrays; import java.util.regex.Pattern; /** * Created by 張燿峰 * 机器学习入门案例 * 过滤垃圾邮件 * 这 个 程 序 使 用 了 MLlib 中 的 两 个 函 数:HashingTF 与 * LogisticRegressionWithSGD,前者从文本数据构建词频(term frequency)特征向量,后者 * 使用随机梯度下降法(Stochastic Gradient Descent,简称 SGD)实现逻辑回归。假设我们 * 从两个文件 spam.txt 与 normal.txt 开始,两个文件分别包含垃圾邮件和非垃圾邮件的例子, * 每行一个。接下来我们就根据词频把每个文件中的文本转化为特征向量,然后训练出一个 可以把两类消息分开的逻辑回归模型 * @author 孤 * @date 2019/5/7 * @Varsion 1.0 */ public class SpamEmail { private static final Pattern SPACE = Pattern.compile(" "); public static void main(String[] args) { SparkSession sparkSession = SparkSession.builder().appName("spam-email").master("local[2]").getOrCreate(); JavaSparkContext javaSparkContext = JavaSparkContext.fromSparkContext(sparkSession.sparkContext()); //垃圾邮件数据 JavaRDD<String> spamEmail = javaSparkContext.textFile("spam.json"); //优质邮件数据 JavaRDD<String> normalEmail = javaSparkContext.textFile("normal.json"); //创建hashingTF实例把邮件文本映射为包含10000个特征的向量 final HashingTF hashingTF = new HashingTF(10000); JavaRDD<LabeledPoint> spamExamples = spamEmail.map(new Function<String, LabeledPoint>() { @Override public LabeledPoint call(String v1) throws Exception { return new LabeledPoint(0, hashingTF.transform(Arrays.asList(SPACE.split(v1)))); } }); JavaRDD<LabeledPoint> normaExamples = normalEmail.map(new Function<String, LabeledPoint>() { @Override public LabeledPoint call(String v1) throws Exception { return new LabeledPoint(1, hashingTF.transform(Arrays.asList(SPACE.split(v1)))); } }); //训练 <SUF> JavaRDD<LabeledPoint> trainData = spamExamples.union(normaExamples); trainData.cache(); //逻辑回归需要迭代,先缓存 //随机梯度下降法 SGD 逻辑回归 LogisticRegressionModel model = new LogisticRegressionWithSGD().run(trainData.rdd()); Vector spamModel = hashingTF.transform(Arrays.asList(SPACE.split("垃 圾 钱 恶 心 色 情 赌 博 毒 品 败 类 犯罪"))); Vector normaModel = hashingTF.transform(Arrays.asList(SPACE.split("work 工作 你好 我们 请问 时间 领导"))); System.out.println("预测负面的例子: " + model.predict(spamModel)); System.out.println("预测积极的例子: " + model.predict(normaModel)); } }
false
788
3
934
3
874
3
934
3
1,253
9
false
false
false
false
false
true
61351_19
package mail.demo; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.springframework.core.io.support.PropertiesLoaderUtils; import com.sun.mail.util.MailSSLSocketFactory; public class SendEmailUtil { private static String account; //登录用户名 private static String pass; //登录密码 private static String host; //服务器地址(邮件服务器) private static String port; //端口 private static String protocol; //协议 static{ Properties prop = new Properties(); // InputStream instream = ClassLoader.getSystemResourceAsStream("email.properties");//测试环境 try { // prop.load(instream);//测试环境 prop = PropertiesLoaderUtils.loadAllProperties("email.properties");//生产环境 } catch (IOException e) { System.out.println("加载属性文件失败"); } account = prop.getProperty("e.account"); pass = prop.getProperty("e.pass"); host = prop.getProperty("e.host"); port = prop.getProperty("e.port"); protocol = prop.getProperty("e.protocol"); } static class MyAuthenricator extends Authenticator{ String u = null; String p = null; public MyAuthenricator(String u,String p){ this.u=u; this.p=p; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(u,p); } } private String to; //收件人 private String subject; //主题 private String content; //内容 private String fileStr; //附件路径 public SendEmailUtil(String to, String subject, String content, String fileStr) { this.to = to; this.subject = subject; this.content = content; this.fileStr = fileStr; } public void send(){ Properties prop = new Properties(); //协议 prop.setProperty("mail.transport.protocol", protocol); //服务器 prop.setProperty("mail.smtp.host", host); //端口 prop.setProperty("mail.smtp.port", port); //使用smtp身份验证 prop.setProperty("mail.smtp.auth", "true"); //使用SSL,企业邮箱必需! //开启安全协议 MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); } catch (GeneralSecurityException e1) { e1.printStackTrace(); } prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(prop, new MyAuthenricator(account, pass)); session.setDebug(true); MimeMessage mimeMessage = new MimeMessage(session); try { //发件人 mimeMessage.setFrom(new InternetAddress(account,"XXX")); //可以设置发件人的别名 //mimeMessage.setFrom(new InternetAddress(account)); //如果不需要就省略 //收件人 mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); //主题 mimeMessage.setSubject(subject); //时间 mimeMessage.setSentDate(new Date()); //容器类,可以包含多个MimeBodyPart对象 Multipart mp = new MimeMultipart(); //MimeBodyPart可以包装文本,图片,附件 MimeBodyPart body = new MimeBodyPart(); //HTML正文 body.setContent(content, "text/html; charset=UTF-8"); mp.addBodyPart(body); //添加图片&附件 body = new MimeBodyPart(); body.attachFile(fileStr); mp.addBodyPart(body); //设置邮件内容 mimeMessage.setContent(mp); //仅仅发送文本 //mimeMessage.setText(content); mimeMessage.saveChanges(); Transport.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Mysakura/Javamail-demo
src/mail/demo/SendEmailUtil.java
1,177
//添加图片&附件
line_comment
zh-cn
package mail.demo; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.GeneralSecurityException; import java.util.Date; import java.util.Properties; import javax.mail.Authenticator; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.PasswordAuthentication; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import org.springframework.core.io.support.PropertiesLoaderUtils; import com.sun.mail.util.MailSSLSocketFactory; public class SendEmailUtil { private static String account; //登录用户名 private static String pass; //登录密码 private static String host; //服务器地址(邮件服务器) private static String port; //端口 private static String protocol; //协议 static{ Properties prop = new Properties(); // InputStream instream = ClassLoader.getSystemResourceAsStream("email.properties");//测试环境 try { // prop.load(instream);//测试环境 prop = PropertiesLoaderUtils.loadAllProperties("email.properties");//生产环境 } catch (IOException e) { System.out.println("加载属性文件失败"); } account = prop.getProperty("e.account"); pass = prop.getProperty("e.pass"); host = prop.getProperty("e.host"); port = prop.getProperty("e.port"); protocol = prop.getProperty("e.protocol"); } static class MyAuthenricator extends Authenticator{ String u = null; String p = null; public MyAuthenricator(String u,String p){ this.u=u; this.p=p; } @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(u,p); } } private String to; //收件人 private String subject; //主题 private String content; //内容 private String fileStr; //附件路径 public SendEmailUtil(String to, String subject, String content, String fileStr) { this.to = to; this.subject = subject; this.content = content; this.fileStr = fileStr; } public void send(){ Properties prop = new Properties(); //协议 prop.setProperty("mail.transport.protocol", protocol); //服务器 prop.setProperty("mail.smtp.host", host); //端口 prop.setProperty("mail.smtp.port", port); //使用smtp身份验证 prop.setProperty("mail.smtp.auth", "true"); //使用SSL,企业邮箱必需! //开启安全协议 MailSSLSocketFactory sf = null; try { sf = new MailSSLSocketFactory(); sf.setTrustAllHosts(true); } catch (GeneralSecurityException e1) { e1.printStackTrace(); } prop.put("mail.smtp.ssl.enable", "true"); prop.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(prop, new MyAuthenricator(account, pass)); session.setDebug(true); MimeMessage mimeMessage = new MimeMessage(session); try { //发件人 mimeMessage.setFrom(new InternetAddress(account,"XXX")); //可以设置发件人的别名 //mimeMessage.setFrom(new InternetAddress(account)); //如果不需要就省略 //收件人 mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); //主题 mimeMessage.setSubject(subject); //时间 mimeMessage.setSentDate(new Date()); //容器类,可以包含多个MimeBodyPart对象 Multipart mp = new MimeMultipart(); //MimeBodyPart可以包装文本,图片,附件 MimeBodyPart body = new MimeBodyPart(); //HTML正文 body.setContent(content, "text/html; charset=UTF-8"); mp.addBodyPart(body); //添加 <SUF> body = new MimeBodyPart(); body.attachFile(fileStr); mp.addBodyPart(body); //设置邮件内容 mimeMessage.setContent(mp); //仅仅发送文本 //mimeMessage.setText(content); mimeMessage.saveChanges(); Transport.send(mimeMessage); } catch (MessagingException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
false
999
5
1,177
6
1,189
5
1,177
6
1,534
10
false
false
false
false
false
true
38946_0
package solutions._674; class Solution { public int findLengthOfLCIS(int[] nums) { if (nums.length == 0) { return 0; } int[] dp = new int[nums.length]; int result = 1; dp[0] = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] > nums[i - 1]) { dp[i] = dp[i - 1] + 1; if (dp[i] > result) { result = dp[i]; } } else { dp[i] = 1; } } return result; } public static void main(String[] args) { System.out.println(new Solution().findLengthOfLCIS(new int[]{1, 3, 5, 4, 7})); System.out.println(new Solution().findLengthOfLCIS(new int[]{2, 2, 2, 2, 2})); } } /* 给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。 连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。 示例 1: 输入:nums = [1,3,5,4,7] 输出:3 解释:最长连续递增序列是 [1,3,5], 长度为3。 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。 示例 2: 输入:nums = [2,2,2,2,2] 输出:1 解释:最长连续递增序列是 [2], 长度为1。 提示: 0 <= nums.length <= 104 -109 <= nums[i] <= 109 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */
N3verL4nd/leetcode
src/main/java/solutions/_674/Solution.java
599
/* 给定一个未经排序的整数数组,找到最长且 连续递增的子序列,并返回该序列的长度。 连续递增的子序列 可以由两个下标 l 和 r(l < r)确定,如果对于每个 l <= i < r,都有 nums[i] < nums[i + 1] ,那么子序列 [nums[l], nums[l + 1], ..., nums[r - 1], nums[r]] 就是连续递增子序列。 示例 1: 输入:nums = [1,3,5,4,7] 输出:3 解释:最长连续递增序列是 [1,3,5], 长度为3。 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为 5 和 7 在原数组里被 4 隔开。 示例 2: 输入:nums = [2,2,2,2,2] 输出:1 解释:最长连续递增序列是 [2], 长度为1。 提示: 0 <= nums.length <= 104 -109 <= nums[i] <= 109 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */
block_comment
zh-cn
package solutions._674; class Solution { public int findLengthOfLCIS(int[] nums) { if (nums.length == 0) { return 0; } int[] dp = new int[nums.length]; int result = 1; dp[0] = 1; for (int i = 1; i < nums.length; i++) { if (nums[i] > nums[i - 1]) { dp[i] = dp[i - 1] + 1; if (dp[i] > result) { result = dp[i]; } } else { dp[i] = 1; } } return result; } public static void main(String[] args) { System.out.println(new Solution().findLengthOfLCIS(new int[]{1, 3, 5, 4, 7})); System.out.println(new Solution().findLengthOfLCIS(new int[]{2, 2, 2, 2, 2})); } } /* 给定一 <SUF>*/
false
530
306
599
350
595
325
599
350
781
491
true
true
true
true
true
false
46314_2
package org.apache.struts.actions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 同一个后端控制器类,对应多个<action>,也就是说,同一个后端控制器可以有多个控制函数, * 例如,CalcAction类,有add,subtract,multiply,divide函数,DispatchAction类的execute函数完成dispatch * 那么如何dispatch呢?execute函数如何转发调用到add,subtract,multipy,divide函数呢? * MappingDispatchAction函数改写(覆盖,override)了getMethodName函数,该函数返回的控制函数名称来自 * <action>元素的parameter属性的值。这样,可以把有一定相关性,聚合性的函数封装在一个后端控制器中。 * 然后为这个后端控制器定义多个path。例如: * * <action path="/add" type="action.CalcAction" parameter="add"/> * <action path="/subtract" type="action.CalcAction" parameter="subtract"/> * <action path="/multiply" type="action.CalcAction" parameter="multiply"/> * <action path="/divide" type="action.CalcAction" parameter="divide"/> * * 只要action.CalcAction类继承MappingDispatchAction类就可以了。 * parameter直接定义控制函数名称。 */ public class MappingDispatchAction extends DispatchAction { // 这个函数没有存在的必要,直接继承DispatchAction类就可以了。 // 毫无意义的覆盖。 protected String getParameter(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.getParameter(); } // MappingDispatchAction唯一有意义的函数,覆盖了DispatchAction类的getMethodName函数。 protected String getMethodName(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String parameter) throws Exception { // 派发的控制函数的函数名称就是在<action>元素中parameter属性的值。 return parameter; } }
NAOSI-DLUT/DLUT_SE_Courses
大三上/JavaEE/exam_22_代码大题/MappingDispatchAction.java
534
// 毫无意义的覆盖。
line_comment
zh-cn
package org.apache.struts.actions; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 同一个后端控制器类,对应多个<action>,也就是说,同一个后端控制器可以有多个控制函数, * 例如,CalcAction类,有add,subtract,multiply,divide函数,DispatchAction类的execute函数完成dispatch * 那么如何dispatch呢?execute函数如何转发调用到add,subtract,multipy,divide函数呢? * MappingDispatchAction函数改写(覆盖,override)了getMethodName函数,该函数返回的控制函数名称来自 * <action>元素的parameter属性的值。这样,可以把有一定相关性,聚合性的函数封装在一个后端控制器中。 * 然后为这个后端控制器定义多个path。例如: * * <action path="/add" type="action.CalcAction" parameter="add"/> * <action path="/subtract" type="action.CalcAction" parameter="subtract"/> * <action path="/multiply" type="action.CalcAction" parameter="multiply"/> * <action path="/divide" type="action.CalcAction" parameter="divide"/> * * 只要action.CalcAction类继承MappingDispatchAction类就可以了。 * parameter直接定义控制函数名称。 */ public class MappingDispatchAction extends DispatchAction { // 这个函数没有存在的必要,直接继承DispatchAction类就可以了。 // 毫无 <SUF> protected String getParameter(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.getParameter(); } // MappingDispatchAction唯一有意义的函数,覆盖了DispatchAction类的getMethodName函数。 protected String getMethodName(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String parameter) throws Exception { // 派发的控制函数的函数名称就是在<action>元素中parameter属性的值。 return parameter; } }
false
460
9
524
10
524
8
524
10
719
17
false
false
false
false
false
true
58991_17
package com.eron.practice.model; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.lang.NonNull; @Entity @Table(name = "ship") public class Ship implements Cloneable { private static final Logger log = LoggerFactory.getLogger(Ship.class); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Long id; // 自动生成的id @Column(name = "user_id") @NonNull private Long userId; // 用户ID @See User **必须赋值** @Column(name = "name") private String name; // 船舶名称 **必须赋值** @Column(name = "mmsi") private String mmsi; // mmsi Maritime Mobile Service Identify 水上移动通信业务标识码 @Column(name = "imo_number") private String imoNumber; // IMO ship identification number @Column(name = "call_number") private String callNumber; // CALL SIGN,是国际海事组织IMO指定给每条船舶唯一的识别信号,CALL SIGN主要的作用就是在船舶海上联络、码头靠泊、信息报告的时候使用 @Column(name = "type") private Integer type; // 船舶类型 @Column(name = "electronic_type") private Integer electronicType; // 船舶电子设备类型 GPS AIS 等电子设备, router项目有编码 @Column(name = "draft") private Float draft; // 船舶吃水 m/dt @Column(name = "create_time", insertable = false, updatable = false) private LocalDateTime createTime; // 船舶创建时间 @Column(name = "update_time", insertable = false, updatable = false) private LocalDateTime updateTime; // 船舶属性修改时间 @Deprecated public Ship() { // 禁用 this.userId = 0L; this.name = "NULL"; } public Ship(Long userId, String name) { this.userId = userId; this.name = name; } public Ship(Builder builder) { this.userId = builder.userId; this.name = builder.name; this.mmsi = builder.mmsi; this.imoNumber = builder.imoNumber; this.callNumber = builder.callNumber; this.type = builder.type; this.electronicType = builder.electronicType; this.draft = builder.draft; } /** * 使用 Ship.createBuilder().build(); * @return Builder obj */ public static Builder createBuilder() { return new Builder(); } public static class Builder { //private Long id; // 自动生成的id private Long userId; // 用户ID @See User **必须赋值** private String name = "NULL"; // 船舶名称 **必须赋值** private String mmsi = "NULL"; // mmsi Maritime Mobile Service Identify 水上移动通信业务标识码 private String imoNumber = "NULL"; // IMO ship identification number private String callNumber = "NULL"; // CALL SIGN,是国际海事组织IMO指定给每条船舶唯一的识别信号,CALL SIGN主要的作用就是在船舶海上联络、码头靠泊、信息报告的时候使用 private Integer type = 0; // 船舶类型 private Integer electronicType = 0; // 船舶电子设备类型 GPS AIS 等电子设备, router项目有编码 private Float draft = 0F; // 船舶吃水 m/dt //private LocalDateTime createTime; // 船舶创建时间 //private LocalDateTime updateTime; // 船舶属性修改时间 public Builder() {} public Builder userId(Long userId) { this.userId = userId; return this; } public Builder name(String name) { this.name = name; return this; } public Builder mmsi(String mmsi) { this.mmsi = mmsi; return this; } public Builder imoNumber(String imoNumber) { this.imoNumber = imoNumber; return this; } public Builder callNumber(String callNumber) { this.callNumber = callNumber; return this; } public Builder type(Integer type) { this.type = type; return this; } public Builder electronicType(Integer electronicType) { this.electronicType = electronicType; return this; } public Builder draft(Float draft) { this.draft = draft; return this; } public Ship build() { // 检查参数合法化 if (this.userId == null) { throw new IllegalArgumentException("userId of Ship is Required !"); } return new Ship(this); } } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } // id 和 updatetime不覆盖 public void overrideAttributes(Ship another) { if (another == null) { log.error("another User is null !!!"); return; } this.userId = another.userId; this.name = another.name; this.mmsi = another.mmsi; this.imoNumber = another.imoNumber; this.callNumber = another.callNumber; this.type = another.type; this.electronicType = another.electronicType; this.draft = another.draft; this.createTime = another.createTime; } /** * pojo 通用 getter 和 setter * @return */ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMmsi() { return mmsi; } public void setMmsi(String mmsi) { this.mmsi = mmsi; } public String getImoNumber() { return imoNumber; } public void setImoNumber(String imoNumber) { this.imoNumber = imoNumber; } public String getCallNumber() { return callNumber; } public void setCallNumber(String callNumber) { this.callNumber = callNumber; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getElectronicType() { return electronicType; } public void setElectronicType(Integer electronicType) { this.electronicType = electronicType; } public Float getDraft() { return draft; } public void setDraft(Float draft) { this.draft = draft; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "Ship [id=" + id + ", userId=" + userId + ", name=" + name + ", mmsi=" + mmsi + ", imoNumber=" + imoNumber + ", callNumber=" + callNumber + ", type=" + type + ", electronicType=" + electronicType + ", draft=" + draft + ", createTime=" + createTime + ", updateTime=" + updateTime + "]"; } }
NAVERON/PracticeSpringboot
src/main/java/com/eron/practice/model/Ship.java
2,069
// CALL SIGN,是国际海事组织IMO指定给每条船舶唯一的识别信号,CALL SIGN主要的作用就是在船舶海上联络、码头靠泊、信息报告的时候使用
line_comment
zh-cn
package com.eron.practice.model; import java.time.LocalDateTime; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.lang.NonNull; @Entity @Table(name = "ship") public class Ship implements Cloneable { private static final Logger log = LoggerFactory.getLogger(Ship.class); @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Long id; // 自动生成的id @Column(name = "user_id") @NonNull private Long userId; // 用户ID @See User **必须赋值** @Column(name = "name") private String name; // 船舶名称 **必须赋值** @Column(name = "mmsi") private String mmsi; // mmsi Maritime Mobile Service Identify 水上移动通信业务标识码 @Column(name = "imo_number") private String imoNumber; // IMO ship identification number @Column(name = "call_number") private String callNumber; // CALL SIGN,是国际海事组织IMO指定给每条船舶唯一的识别信号,CALL SIGN主要的作用就是在船舶海上联络、码头靠泊、信息报告的时候使用 @Column(name = "type") private Integer type; // 船舶类型 @Column(name = "electronic_type") private Integer electronicType; // 船舶电子设备类型 GPS AIS 等电子设备, router项目有编码 @Column(name = "draft") private Float draft; // 船舶吃水 m/dt @Column(name = "create_time", insertable = false, updatable = false) private LocalDateTime createTime; // 船舶创建时间 @Column(name = "update_time", insertable = false, updatable = false) private LocalDateTime updateTime; // 船舶属性修改时间 @Deprecated public Ship() { // 禁用 this.userId = 0L; this.name = "NULL"; } public Ship(Long userId, String name) { this.userId = userId; this.name = name; } public Ship(Builder builder) { this.userId = builder.userId; this.name = builder.name; this.mmsi = builder.mmsi; this.imoNumber = builder.imoNumber; this.callNumber = builder.callNumber; this.type = builder.type; this.electronicType = builder.electronicType; this.draft = builder.draft; } /** * 使用 Ship.createBuilder().build(); * @return Builder obj */ public static Builder createBuilder() { return new Builder(); } public static class Builder { //private Long id; // 自动生成的id private Long userId; // 用户ID @See User **必须赋值** private String name = "NULL"; // 船舶名称 **必须赋值** private String mmsi = "NULL"; // mmsi Maritime Mobile Service Identify 水上移动通信业务标识码 private String imoNumber = "NULL"; // IMO ship identification number private String callNumber = "NULL"; // CA <SUF> private Integer type = 0; // 船舶类型 private Integer electronicType = 0; // 船舶电子设备类型 GPS AIS 等电子设备, router项目有编码 private Float draft = 0F; // 船舶吃水 m/dt //private LocalDateTime createTime; // 船舶创建时间 //private LocalDateTime updateTime; // 船舶属性修改时间 public Builder() {} public Builder userId(Long userId) { this.userId = userId; return this; } public Builder name(String name) { this.name = name; return this; } public Builder mmsi(String mmsi) { this.mmsi = mmsi; return this; } public Builder imoNumber(String imoNumber) { this.imoNumber = imoNumber; return this; } public Builder callNumber(String callNumber) { this.callNumber = callNumber; return this; } public Builder type(Integer type) { this.type = type; return this; } public Builder electronicType(Integer electronicType) { this.electronicType = electronicType; return this; } public Builder draft(Float draft) { this.draft = draft; return this; } public Ship build() { // 检查参数合法化 if (this.userId == null) { throw new IllegalArgumentException("userId of Ship is Required !"); } return new Ship(this); } } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } // id 和 updatetime不覆盖 public void overrideAttributes(Ship another) { if (another == null) { log.error("another User is null !!!"); return; } this.userId = another.userId; this.name = another.name; this.mmsi = another.mmsi; this.imoNumber = another.imoNumber; this.callNumber = another.callNumber; this.type = another.type; this.electronicType = another.electronicType; this.draft = another.draft; this.createTime = another.createTime; } /** * pojo 通用 getter 和 setter * @return */ public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMmsi() { return mmsi; } public void setMmsi(String mmsi) { this.mmsi = mmsi; } public String getImoNumber() { return imoNumber; } public void setImoNumber(String imoNumber) { this.imoNumber = imoNumber; } public String getCallNumber() { return callNumber; } public void setCallNumber(String callNumber) { this.callNumber = callNumber; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Integer getElectronicType() { return electronicType; } public void setElectronicType(Integer electronicType) { this.electronicType = electronicType; } public Float getDraft() { return draft; } public void setDraft(Float draft) { this.draft = draft; } public LocalDateTime getCreateTime() { return createTime; } public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; } public LocalDateTime getUpdateTime() { return updateTime; } public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "Ship [id=" + id + ", userId=" + userId + ", name=" + name + ", mmsi=" + mmsi + ", imoNumber=" + imoNumber + ", callNumber=" + callNumber + ", type=" + type + ", electronicType=" + electronicType + ", draft=" + draft + ", createTime=" + createTime + ", updateTime=" + updateTime + "]"; } }
false
1,706
37
2,069
54
1,993
41
2,069
54
2,600
90
false
false
false
false
false
true
7680_17
import java.util.Scanner; public class World { // 這世界能裝一千人 private static Human[] people = new Human[1000]; // 紀錄現在裝了幾人 public static int count; public static void main(String[] args) { Scanner input = new Scanner(System.in); // 世界一開始有兩個天降人(沒父母) people[0] = new Human("憲一", null, null); people[1] = new Human("展瑩", null, null); count += 2; // 運作吧,世界! while (true) { // 列出世界上每個人的資訊 for (int i = 0; i < count; i++) { // 先取得這人的雙親 Human[] parents = people[i].getParents(); // 顯示姓名 System.out.print("[" + people[i].getName() + "] "); // 若有父母,顯示父母 if (parents[0] != null && parents[1] != null) { System.out.print("父母: " + parents[0].getName() + " & " + parents[1].getName() + " "); } // 若有伴侶,顯示伴侶 if (people[i].getCompanion() != null) { System.out.print("伴侶: " + people[i].getCompanion().getName()); } System.out.println(); } System.out.println(); // 取得指令 String cmd = input.next(); // 找尋既存於世界之二人 // 預設找不到 Human a = null; Human b = null; // 輸入到找到為止 while (a == null) { String name = input.next(); a = search(name); } while (b == null) { String name = input.next(); b = search(name); } // 執行指令 if (cmd.equals("marry")) { // 互結連理 a.setCompanion(b); b.setCompanion(a); } else if (cmd.equals("deliver")) { // 若互為伴侶,才可生小孩 if (couldDeliver(a, b)) { System.out.print("請取個名字: "); people[count++] = new Human(input.next(), a, b); } else { System.out.println("互為伴侶才能生喔~"); } } System.out.println(); } } // 判斷這兩人是否能孩子 private static boolean couldDeliver(Human a, Human b) { return a.getCompanion() == b && b.getCompanion() == a; } // 找尋叫這名字的人 private static Human search(String name) { for (int i = 0; i < count; i++) { if (name.equals(people[i].getName())) { return people[i]; } } return null; } }
NCNU-OpenSource/programming-course
1042/judge4-2/World.java
744
// 找尋叫這名字的人
line_comment
zh-cn
import java.util.Scanner; public class World { // 這世界能裝一千人 private static Human[] people = new Human[1000]; // 紀錄現在裝了幾人 public static int count; public static void main(String[] args) { Scanner input = new Scanner(System.in); // 世界一開始有兩個天降人(沒父母) people[0] = new Human("憲一", null, null); people[1] = new Human("展瑩", null, null); count += 2; // 運作吧,世界! while (true) { // 列出世界上每個人的資訊 for (int i = 0; i < count; i++) { // 先取得這人的雙親 Human[] parents = people[i].getParents(); // 顯示姓名 System.out.print("[" + people[i].getName() + "] "); // 若有父母,顯示父母 if (parents[0] != null && parents[1] != null) { System.out.print("父母: " + parents[0].getName() + " & " + parents[1].getName() + " "); } // 若有伴侶,顯示伴侶 if (people[i].getCompanion() != null) { System.out.print("伴侶: " + people[i].getCompanion().getName()); } System.out.println(); } System.out.println(); // 取得指令 String cmd = input.next(); // 找尋既存於世界之二人 // 預設找不到 Human a = null; Human b = null; // 輸入到找到為止 while (a == null) { String name = input.next(); a = search(name); } while (b == null) { String name = input.next(); b = search(name); } // 執行指令 if (cmd.equals("marry")) { // 互結連理 a.setCompanion(b); b.setCompanion(a); } else if (cmd.equals("deliver")) { // 若互為伴侶,才可生小孩 if (couldDeliver(a, b)) { System.out.print("請取個名字: "); people[count++] = new Human(input.next(), a, b); } else { System.out.println("互為伴侶才能生喔~"); } } System.out.println(); } } // 判斷這兩人是否能孩子 private static boolean couldDeliver(Human a, Human b) { return a.getCompanion() == b && b.getCompanion() == a; } // 找尋 <SUF> private static Human search(String name) { for (int i = 0; i < count; i++) { if (name.equals(people[i].getName())) { return people[i]; } } return null; } }
false
677
8
744
9
748
8
744
9
962
18
false
false
false
false
false
true
6633_12
package com.ansj.vec; import java.io.*; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import com.ansj.vec.domain.WordEntry; public class Word2VEC { public static void main(String[] args) throws IOException { // Learn learn = new Learn(); // learn.learnFile(new File("library/xh.txt")); // learn.saveModel(new File("library/javaSkip1")); Word2VEC vec = new Word2VEC(); vec.loadJavaModel("library/javaSkip1"); // System.out.println("中国" + "\t" + // Arrays.toString(vec.getWordVector("中国"))); // ; // System.out.println("毛泽东" + "\t" + // Arrays.toString(vec.getWordVector("毛泽东"))); // ; // System.out.println("足球" + "\t" + // Arrays.toString(vec.getWordVector("足球"))); // Word2VEC vec2 = new Word2VEC(); // vec2.loadGoogleModel("library/vectors.bin") ; // // String str = "毛泽东"; long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { System.out.println(vec.distance(str)); ; } System.out.println(System.currentTimeMillis() - start); System.out.println(System.currentTimeMillis() - start); // System.out.println(vec2.distance(str)); // // // //男人 国王 女人 // System.out.println(vec.analogy("邓小平", "毛泽东思想", "毛泽东")); // System.out.println(vec2.analogy("毛泽东", "毛泽东思想", "邓小平")); } private HashMap<String, float[]> wordMap = new HashMap<String, float[]>(); private int words; private int size; private int topNSize = 40; /** * 加载模型 * * @param path * 模型的路径 * @throws IOException */ public void loadGoogleModel(String path) throws IOException { DataInputStream dis = null; BufferedInputStream bis = null; double len = 0; float vector = 0; try { bis = new BufferedInputStream(new FileInputStream(path)); dis = new DataInputStream(bis); // //读取词数 words = Integer.parseInt(readString(dis)); // //大小 size = Integer.parseInt(readString(dis)); String word; float[] vectors = null; for (int i = 0; i < words; i++) { word = readString(dis); vectors = new float[size]; len = 0; for (int j = 0; j < size; j++) { vector = readFloat(dis); len += vector * vector; vectors[j] = (float) vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { vectors[j] /= len; } wordMap.put(word, vectors); dis.read(); } } finally { bis.close(); dis.close(); } } /** * 加载模型 * * @param path * 模型的路径 * @throws IOException */ public void loadJavaModel(String path) throws IOException { try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(path)))) { words = dis.readInt(); size = dis.readInt(); float vector = 0; String key = null; float[] value = null; for (int i = 0; i < words; i++) { double len = 0; key = dis.readUTF(); value = new float[size]; for (int j = 0; j < size; j++) { vector = dis.readFloat(); len += vector * vector; value[j] = vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { value[j] /= len; } wordMap.put(key, value); } } } private static final int MAX_SIZE = 50; /** * 近义词 * * @return */ public TreeSet<WordEntry> analogy(String word0, String word1, String word2) { float[] wv0 = getWordVector(word0); float[] wv1 = getWordVector(word1); float[] wv2 = getWordVector(word2); if (wv1 == null || wv2 == null || wv0 == null) { return null; } float[] wordVector = new float[size]; for (int i = 0; i < size; i++) { wordVector[i] = wv1[i] - wv0[i] + wv2[i]; } float[] tempVector; String name; List<WordEntry> wordEntrys = new ArrayList<WordEntry>(topNSize); for (Entry<String, float[]> entry : wordMap.entrySet()) { name = entry.getKey(); if (name.equals(word0) || name.equals(word1) || name.equals(word2)) { continue; } float dist = 0; tempVector = entry.getValue(); for (int i = 0; i < wordVector.length; i++) { dist += wordVector[i] * tempVector[i]; } insertTopN(name, dist, wordEntrys); } return new TreeSet<WordEntry>(wordEntrys); } private void insertTopN(String name, float score, List<WordEntry> wordsEntrys) { // TODO Auto-generated method stub if (wordsEntrys.size() < topNSize) { wordsEntrys.add(new WordEntry(name, score)); return; } float min = Float.MAX_VALUE; int minOffe = 0; for (int i = 0; i < topNSize; i++) { WordEntry wordEntry = wordsEntrys.get(i); if (min > wordEntry.score) { min = wordEntry.score; minOffe = i; } } if (score > min) { wordsEntrys.set(minOffe, new WordEntry(name, score)); } } public Set<WordEntry> distance(String queryWord) { float[] center = wordMap.get(queryWord); if (center == null) { return Collections.emptySet(); } int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize; TreeSet<WordEntry> result = new TreeSet<WordEntry>(); double min = Float.MIN_VALUE; for (Map.Entry<String, float[]> entry : wordMap.entrySet()) { float[] vector = entry.getValue(); float dist = 0; for (int i = 0; i < vector.length; i++) { dist += center[i] * vector[i]; } if (dist > min) { result.add(new WordEntry(entry.getKey(), dist)); if (resultSize < result.size()) { result.pollLast(); } min = result.last().score; } } result.pollFirst(); return result; } public Set<WordEntry> distance(List<String> words) { float[] center = null; for (String word : words) { center = sum(center, wordMap.get(word)); } if (center == null) { return Collections.emptySet(); } int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize; TreeSet<WordEntry> result = new TreeSet<WordEntry>(); double min = Float.MIN_VALUE; for (Map.Entry<String, float[]> entry : wordMap.entrySet()) { float[] vector = entry.getValue(); float dist = 0; for (int i = 0; i < vector.length; i++) { dist += center[i] * vector[i]; } if (dist > min) { result.add(new WordEntry(entry.getKey(), dist)); if (resultSize < result.size()) { result.pollLast(); } min = result.last().score; } } result.pollFirst(); return result; } private float[] sum(float[] center, float[] fs) { // TODO Auto-generated method stub if (center == null && fs == null) { return null; } if (fs == null) { return center; } if (center == null) { return fs; } for (int i = 0; i < fs.length; i++) { center[i] += fs[i]; } return center; } /** * 得到词向量 * * @param word * @return */ public float[] getWordVector(String word) { return wordMap.get(word); } public static float readFloat(InputStream is) throws IOException { byte[] bytes = new byte[4]; is.read(bytes); return getFloat(bytes); } /** * 读取一个float * * @param b * @return */ public static float getFloat(byte[] b) { int accum = 0; accum = accum | (b[0] & 0xff) << 0; accum = accum | (b[1] & 0xff) << 8; accum = accum | (b[2] & 0xff) << 16; accum = accum | (b[3] & 0xff) << 24; return Float.intBitsToFloat(accum); } /** * 读取一个字符串 * * @param dis * @return * @throws IOException */ private static String readString(DataInputStream dis) throws IOException { // TODO Auto-generated method stub byte[] bytes = new byte[MAX_SIZE]; byte b = dis.readByte(); int i = -1; StringBuilder sb = new StringBuilder(); while (b != 32 && b != 10) { i++; bytes[i] = b; b = dis.readByte(); if (i == 49) { sb.append(new String(bytes)); i = -1; bytes = new byte[MAX_SIZE]; } } sb.append(new String(bytes, 0, i + 1)); return sb.toString(); } public int getTopNSize() { return topNSize; } public void setTopNSize(int topNSize) { this.topNSize = topNSize; } public HashMap<String, float[]> getWordMap() { return wordMap; } public int getWords() { return words; } public int getSize() { return size; } }
NLPchina/Word2VEC_java
src/main/java/com/ansj/vec/Word2VEC.java
2,945
// //男人 国王 女人
line_comment
zh-cn
package com.ansj.vec; import java.io.*; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import com.ansj.vec.domain.WordEntry; public class Word2VEC { public static void main(String[] args) throws IOException { // Learn learn = new Learn(); // learn.learnFile(new File("library/xh.txt")); // learn.saveModel(new File("library/javaSkip1")); Word2VEC vec = new Word2VEC(); vec.loadJavaModel("library/javaSkip1"); // System.out.println("中国" + "\t" + // Arrays.toString(vec.getWordVector("中国"))); // ; // System.out.println("毛泽东" + "\t" + // Arrays.toString(vec.getWordVector("毛泽东"))); // ; // System.out.println("足球" + "\t" + // Arrays.toString(vec.getWordVector("足球"))); // Word2VEC vec2 = new Word2VEC(); // vec2.loadGoogleModel("library/vectors.bin") ; // // String str = "毛泽东"; long start = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { System.out.println(vec.distance(str)); ; } System.out.println(System.currentTimeMillis() - start); System.out.println(System.currentTimeMillis() - start); // System.out.println(vec2.distance(str)); // // // //男人 <SUF> // System.out.println(vec.analogy("邓小平", "毛泽东思想", "毛泽东")); // System.out.println(vec2.analogy("毛泽东", "毛泽东思想", "邓小平")); } private HashMap<String, float[]> wordMap = new HashMap<String, float[]>(); private int words; private int size; private int topNSize = 40; /** * 加载模型 * * @param path * 模型的路径 * @throws IOException */ public void loadGoogleModel(String path) throws IOException { DataInputStream dis = null; BufferedInputStream bis = null; double len = 0; float vector = 0; try { bis = new BufferedInputStream(new FileInputStream(path)); dis = new DataInputStream(bis); // //读取词数 words = Integer.parseInt(readString(dis)); // //大小 size = Integer.parseInt(readString(dis)); String word; float[] vectors = null; for (int i = 0; i < words; i++) { word = readString(dis); vectors = new float[size]; len = 0; for (int j = 0; j < size; j++) { vector = readFloat(dis); len += vector * vector; vectors[j] = (float) vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { vectors[j] /= len; } wordMap.put(word, vectors); dis.read(); } } finally { bis.close(); dis.close(); } } /** * 加载模型 * * @param path * 模型的路径 * @throws IOException */ public void loadJavaModel(String path) throws IOException { try (DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(path)))) { words = dis.readInt(); size = dis.readInt(); float vector = 0; String key = null; float[] value = null; for (int i = 0; i < words; i++) { double len = 0; key = dis.readUTF(); value = new float[size]; for (int j = 0; j < size; j++) { vector = dis.readFloat(); len += vector * vector; value[j] = vector; } len = Math.sqrt(len); for (int j = 0; j < size; j++) { value[j] /= len; } wordMap.put(key, value); } } } private static final int MAX_SIZE = 50; /** * 近义词 * * @return */ public TreeSet<WordEntry> analogy(String word0, String word1, String word2) { float[] wv0 = getWordVector(word0); float[] wv1 = getWordVector(word1); float[] wv2 = getWordVector(word2); if (wv1 == null || wv2 == null || wv0 == null) { return null; } float[] wordVector = new float[size]; for (int i = 0; i < size; i++) { wordVector[i] = wv1[i] - wv0[i] + wv2[i]; } float[] tempVector; String name; List<WordEntry> wordEntrys = new ArrayList<WordEntry>(topNSize); for (Entry<String, float[]> entry : wordMap.entrySet()) { name = entry.getKey(); if (name.equals(word0) || name.equals(word1) || name.equals(word2)) { continue; } float dist = 0; tempVector = entry.getValue(); for (int i = 0; i < wordVector.length; i++) { dist += wordVector[i] * tempVector[i]; } insertTopN(name, dist, wordEntrys); } return new TreeSet<WordEntry>(wordEntrys); } private void insertTopN(String name, float score, List<WordEntry> wordsEntrys) { // TODO Auto-generated method stub if (wordsEntrys.size() < topNSize) { wordsEntrys.add(new WordEntry(name, score)); return; } float min = Float.MAX_VALUE; int minOffe = 0; for (int i = 0; i < topNSize; i++) { WordEntry wordEntry = wordsEntrys.get(i); if (min > wordEntry.score) { min = wordEntry.score; minOffe = i; } } if (score > min) { wordsEntrys.set(minOffe, new WordEntry(name, score)); } } public Set<WordEntry> distance(String queryWord) { float[] center = wordMap.get(queryWord); if (center == null) { return Collections.emptySet(); } int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize; TreeSet<WordEntry> result = new TreeSet<WordEntry>(); double min = Float.MIN_VALUE; for (Map.Entry<String, float[]> entry : wordMap.entrySet()) { float[] vector = entry.getValue(); float dist = 0; for (int i = 0; i < vector.length; i++) { dist += center[i] * vector[i]; } if (dist > min) { result.add(new WordEntry(entry.getKey(), dist)); if (resultSize < result.size()) { result.pollLast(); } min = result.last().score; } } result.pollFirst(); return result; } public Set<WordEntry> distance(List<String> words) { float[] center = null; for (String word : words) { center = sum(center, wordMap.get(word)); } if (center == null) { return Collections.emptySet(); } int resultSize = wordMap.size() < topNSize ? wordMap.size() : topNSize; TreeSet<WordEntry> result = new TreeSet<WordEntry>(); double min = Float.MIN_VALUE; for (Map.Entry<String, float[]> entry : wordMap.entrySet()) { float[] vector = entry.getValue(); float dist = 0; for (int i = 0; i < vector.length; i++) { dist += center[i] * vector[i]; } if (dist > min) { result.add(new WordEntry(entry.getKey(), dist)); if (resultSize < result.size()) { result.pollLast(); } min = result.last().score; } } result.pollFirst(); return result; } private float[] sum(float[] center, float[] fs) { // TODO Auto-generated method stub if (center == null && fs == null) { return null; } if (fs == null) { return center; } if (center == null) { return fs; } for (int i = 0; i < fs.length; i++) { center[i] += fs[i]; } return center; } /** * 得到词向量 * * @param word * @return */ public float[] getWordVector(String word) { return wordMap.get(word); } public static float readFloat(InputStream is) throws IOException { byte[] bytes = new byte[4]; is.read(bytes); return getFloat(bytes); } /** * 读取一个float * * @param b * @return */ public static float getFloat(byte[] b) { int accum = 0; accum = accum | (b[0] & 0xff) << 0; accum = accum | (b[1] & 0xff) << 8; accum = accum | (b[2] & 0xff) << 16; accum = accum | (b[3] & 0xff) << 24; return Float.intBitsToFloat(accum); } /** * 读取一个字符串 * * @param dis * @return * @throws IOException */ private static String readString(DataInputStream dis) throws IOException { // TODO Auto-generated method stub byte[] bytes = new byte[MAX_SIZE]; byte b = dis.readByte(); int i = -1; StringBuilder sb = new StringBuilder(); while (b != 32 && b != 10) { i++; bytes[i] = b; b = dis.readByte(); if (i == 49) { sb.append(new String(bytes)); i = -1; bytes = new byte[MAX_SIZE]; } } sb.append(new String(bytes, 0, i + 1)); return sb.toString(); } public int getTopNSize() { return topNSize; } public void setTopNSize(int topNSize) { this.topNSize = topNSize; } public HashMap<String, float[]> getWordMap() { return wordMap; } public int getWords() { return words; } public int getSize() { return size; } }
false
2,473
10
2,945
10
2,921
6
2,945
10
3,548
10
false
false
false
false
false
true
43520_0
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.List; import java.util.Map.Entry; import org.ansj.domain.Term; import org.ansj.splitWord.analysis.NlpAnalysis; import org.ansj.splitWord.analysis.ToAnalysis; import org.nlpcn.commons.lang.util.CollectionUtil; import org.nlpcn.commons.lang.util.IOUtil; import org.nlpcn.commons.lang.util.MapCount; import org.nlpcn.commons.lang.util.WordWeight; public class HotFinder { public static void main(String[] args) throws IOException { //用来寻找热点 WordWeight ww = new WordWeight(500000, 200000) ; String temp = null ; try(BufferedReader reader = IOUtil.getReader("test_data/fl.txt", IOUtil.UTF8)){ while((temp=reader.readLine())!=null){ List<Term> parse = NlpAnalysis.parse(temp) ; for (Term term : parse) { ww.add(term.getName(), "all"); } } } try(BufferedReader reader = IOUtil.getReader("test_data/corpus.txt", IOUtil.UTF8)){ while((temp=reader.readLine())!=null){ List<Term> parse = NlpAnalysis.parse(temp) ; for (Term term : parse) { ww.add(term.getName(), "sport"); } } } MapCount<String> mapCount = ww.exportChiSquare().get("sport") ; List<Entry<String, Double>> sortMapByValue = CollectionUtil.sortMapByValue(mapCount.get(), 2) ; int i = 0 ; for (Entry<String, Double> entry : sortMapByValue) { System.out.println(entry); if(i++>20){ break ; } } } }
NLPchina/ansj_fast_lda
src/HotFinder.java
523
//用来寻找热点
line_comment
zh-cn
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.List; import java.util.Map.Entry; import org.ansj.domain.Term; import org.ansj.splitWord.analysis.NlpAnalysis; import org.ansj.splitWord.analysis.ToAnalysis; import org.nlpcn.commons.lang.util.CollectionUtil; import org.nlpcn.commons.lang.util.IOUtil; import org.nlpcn.commons.lang.util.MapCount; import org.nlpcn.commons.lang.util.WordWeight; public class HotFinder { public static void main(String[] args) throws IOException { //用来 <SUF> WordWeight ww = new WordWeight(500000, 200000) ; String temp = null ; try(BufferedReader reader = IOUtil.getReader("test_data/fl.txt", IOUtil.UTF8)){ while((temp=reader.readLine())!=null){ List<Term> parse = NlpAnalysis.parse(temp) ; for (Term term : parse) { ww.add(term.getName(), "all"); } } } try(BufferedReader reader = IOUtil.getReader("test_data/corpus.txt", IOUtil.UTF8)){ while((temp=reader.readLine())!=null){ List<Term> parse = NlpAnalysis.parse(temp) ; for (Term term : parse) { ww.add(term.getName(), "sport"); } } } MapCount<String> mapCount = ww.exportChiSquare().get("sport") ; List<Entry<String, Double>> sortMapByValue = CollectionUtil.sortMapByValue(mapCount.get(), 2) ; int i = 0 ; for (Entry<String, Double> entry : sortMapByValue) { System.out.println(entry); if(i++>20){ break ; } } } }
false
415
4
523
7
547
4
523
7
641
13
false
false
false
false
false
true
133_3
package org.ansj.util; import org.ansj.domain.AnsjItem; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.domain.TermNatures; import org.ansj.library.DATDictionary; import org.ansj.splitWord.Analysis.Merger; import org.ansj.util.TermUtil.InsertTermType; import org.nlpcn.commons.lang.util.WordAlert; import java.util.List; import java.util.Map; /** * 最短路径 * * @author ansj */ public class Graph { public char[] chars = null; public Term[] terms = null; protected Term end = null; protected Term root = null; protected static final String B = "BEGIN"; protected static final String E = "END"; // 是否有人名 public boolean hasPerson; public boolean hasNumQua; public String str ; // 是否需有歧异 public Graph(String str) { this.str = str ; this.chars = WordAlert.alertStr(str); terms = new Term[chars.length + 1]; end = new Term(E, chars.length, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[chars.length] = end; } public Graph(Result result) { Term last = result.get(result.size() - 1); int beginOff = result.get(0).getOffe(); int len = last.getOffe() - beginOff + last.getName().length(); terms = new Term[len + 1]; end = new Term(E, len, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[len] = end; for (Term term : result) { terms[term.getOffe() - beginOff] = term; } } /** * 构建最优路径 */ public List<Term> getResult(Merger merger) { return merger.merger(); } /** * 增加一个词语到图中 * * @param term */ public void addTerm(Term term) { // 是否有人名 if (!hasPerson && term.termNatures().personAttr.isActive()) { hasPerson = true; } if (!hasNumQua && term.termNatures().numAttr.isQua()) { hasNumQua = true; } TermUtil.insertTerm(terms, term, InsertTermType.REPLACE); } /** * 取得最优路径的root Term * * @return */ protected Term optimalRoot() { Term to = end; to.clearScore(); Term from = null; while ((from = to.from()) != null) { for (int i = from.getOffe() + 1; i < to.getOffe(); i++) { terms[i] = null; } if (from.getOffe() > -1) { terms[from.getOffe()] = from; } // 断开横向链表.节省内存 from.setNext(null); from.setTo(to); from.clearScore(); to = from; } return root; } /** * 删除最短的节点 */ public void rmLittlePath() { int maxTo = -1; Term temp = null; Term maxTerm = null; // 是否有交叉 boolean flag = false; final int length = terms.length - 1; for (int i = 0; i < length; i++) { maxTerm = getMaxTerm(i); if (maxTerm == null) { continue; } maxTo = maxTerm.toValue(); /** * 对字数进行优化.如果一个字.就跳过..两个字.且第二个为null则.也跳过.从第二个后开始 */ switch (maxTerm.getName().length()) { case 1: continue; case 2: if (terms[i + 1] == null) { i = i + 1; continue; } } /** * 判断是否有交叉 */ for (int j = i + 1; j < maxTo; j++) { temp = getMaxTerm(j); if (temp == null) { continue; } if (maxTo < temp.toValue()) { maxTo = temp.toValue(); flag = true; } } if (flag) { i = maxTo - 1; flag = false; } else { maxTerm.setNext(null); terms[i] = maxTerm; for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } } /** * 得道最到本行最大term,也就是最右面的term * * @param i * @return */ private Term getMaxTerm(int i) { Term maxTerm = terms[i]; if (maxTerm == null) { return null; } Term term = maxTerm; while ((term = term.next()) != null) { maxTerm = term; } return maxTerm; } /** * 删除无意义的节点,防止viterbi太多 */ public void rmLittleSinglePath() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } maxTo = terms[i].toValue(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp != null && temp.toValue() <= maxTo && temp.getName().length() == 1) { terms[j] = null; } } } } /** * 删除小节点。保证被删除的小节点的单个分数小于等于大节点的分数 */ public void rmLittlePathByScore() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } Term maxTerm = null; double maxScore = 0; Term term = terms[i]; // 找到自身分数对大最长的 do { if (maxTerm == null || maxScore > term.score()) { maxTerm = term; } else if (maxScore == term.score() && maxTerm.getName().length() < term.getName().length()) { maxTerm = term; } } while ((term = term.next()) != null); term = maxTerm; do { maxTo = term.toValue(); maxScore = term.score(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } boolean flag = true;// 可以删除 out: for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp == null) { continue; } do { if (temp.toValue() > maxTo || temp.score() < maxScore) { flag = false; break out; } } while ((temp = temp.next()) != null); } // 验证通过可以删除了 if (flag) { for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } while ((term = term.next()) != null); } } /** * 默认按照最大分数作为路径 */ public void walkPathByScore(){ walkPathByScore(true); } /** * 路径方式 * @param asc true 最大路径,false 最小路径 */ public void walkPathByScore(boolean asc) { Term term = null; // BEGIN先行打分 mergerByScore(root, 0, asc); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); mergerByScore(term, to, asc); term = term.next(); } } optimalRoot(); } public void walkPath() { walkPath(null); } /** * 干涉性增加相对权重 * * @param relationMap */ public void walkPath(Map<String, Double> relationMap) { Term term = null; // BEGIN先行打分 merger(root, 0, relationMap); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); merger(term, to, relationMap); term = term.next(); } } optimalRoot(); } /** * 具体的遍历打分方法 * * @param to */ private void merger(Term fromTerm, int to, Map<String, Double> relationMap) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathScore(fromTerm, relationMap); term = term.next(); } } else { char c = chars[to]; TermNatures tn = DATDictionary.getItem(c).termNatures; if (tn == null || tn == TermNatures.NULL) { tn = TermNatures.NULL; } terms[to] = new Term(String.valueOf(c), to, tn); terms[to].setPathScore(fromTerm, relationMap); } } /** * 根据分数 */ private void mergerByScore(Term fromTerm, int to, boolean asc) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathSelfScore(fromTerm, asc); term = term.next(); } } } /** * 对graph进行调试用的 */ public void printGraph() { for (Term term : terms) { if (term == null) { continue; } System.out.print(term.getName() + "\t" + term.score() + " ,"); while ((term = term.next()) != null) { System.out.print(term + "\t" + term.score() + " ,"); } System.out.println(); } } }
NLPchina/ansj_seg
src/main/java/org/ansj/util/Graph.java
2,888
/** * 构建最优路径 */
block_comment
zh-cn
package org.ansj.util; import org.ansj.domain.AnsjItem; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.domain.TermNatures; import org.ansj.library.DATDictionary; import org.ansj.splitWord.Analysis.Merger; import org.ansj.util.TermUtil.InsertTermType; import org.nlpcn.commons.lang.util.WordAlert; import java.util.List; import java.util.Map; /** * 最短路径 * * @author ansj */ public class Graph { public char[] chars = null; public Term[] terms = null; protected Term end = null; protected Term root = null; protected static final String B = "BEGIN"; protected static final String E = "END"; // 是否有人名 public boolean hasPerson; public boolean hasNumQua; public String str ; // 是否需有歧异 public Graph(String str) { this.str = str ; this.chars = WordAlert.alertStr(str); terms = new Term[chars.length + 1]; end = new Term(E, chars.length, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[chars.length] = end; } public Graph(Result result) { Term last = result.get(result.size() - 1); int beginOff = result.get(0).getOffe(); int len = last.getOffe() - beginOff + last.getName().length(); terms = new Term[len + 1]; end = new Term(E, len, AnsjItem.END); root = new Term(B, -1, AnsjItem.BEGIN); terms[len] = end; for (Term term : result) { terms[term.getOffe() - beginOff] = term; } } /** * 构建最 <SUF>*/ public List<Term> getResult(Merger merger) { return merger.merger(); } /** * 增加一个词语到图中 * * @param term */ public void addTerm(Term term) { // 是否有人名 if (!hasPerson && term.termNatures().personAttr.isActive()) { hasPerson = true; } if (!hasNumQua && term.termNatures().numAttr.isQua()) { hasNumQua = true; } TermUtil.insertTerm(terms, term, InsertTermType.REPLACE); } /** * 取得最优路径的root Term * * @return */ protected Term optimalRoot() { Term to = end; to.clearScore(); Term from = null; while ((from = to.from()) != null) { for (int i = from.getOffe() + 1; i < to.getOffe(); i++) { terms[i] = null; } if (from.getOffe() > -1) { terms[from.getOffe()] = from; } // 断开横向链表.节省内存 from.setNext(null); from.setTo(to); from.clearScore(); to = from; } return root; } /** * 删除最短的节点 */ public void rmLittlePath() { int maxTo = -1; Term temp = null; Term maxTerm = null; // 是否有交叉 boolean flag = false; final int length = terms.length - 1; for (int i = 0; i < length; i++) { maxTerm = getMaxTerm(i); if (maxTerm == null) { continue; } maxTo = maxTerm.toValue(); /** * 对字数进行优化.如果一个字.就跳过..两个字.且第二个为null则.也跳过.从第二个后开始 */ switch (maxTerm.getName().length()) { case 1: continue; case 2: if (terms[i + 1] == null) { i = i + 1; continue; } } /** * 判断是否有交叉 */ for (int j = i + 1; j < maxTo; j++) { temp = getMaxTerm(j); if (temp == null) { continue; } if (maxTo < temp.toValue()) { maxTo = temp.toValue(); flag = true; } } if (flag) { i = maxTo - 1; flag = false; } else { maxTerm.setNext(null); terms[i] = maxTerm; for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } } /** * 得道最到本行最大term,也就是最右面的term * * @param i * @return */ private Term getMaxTerm(int i) { Term maxTerm = terms[i]; if (maxTerm == null) { return null; } Term term = maxTerm; while ((term = term.next()) != null) { maxTerm = term; } return maxTerm; } /** * 删除无意义的节点,防止viterbi太多 */ public void rmLittleSinglePath() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } maxTo = terms[i].toValue(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp != null && temp.toValue() <= maxTo && temp.getName().length() == 1) { terms[j] = null; } } } } /** * 删除小节点。保证被删除的小节点的单个分数小于等于大节点的分数 */ public void rmLittlePathByScore() { int maxTo = -1; Term temp = null; for (int i = 0; i < terms.length; i++) { if (terms[i] == null) { continue; } Term maxTerm = null; double maxScore = 0; Term term = terms[i]; // 找到自身分数对大最长的 do { if (maxTerm == null || maxScore > term.score()) { maxTerm = term; } else if (maxScore == term.score() && maxTerm.getName().length() < term.getName().length()) { maxTerm = term; } } while ((term = term.next()) != null); term = maxTerm; do { maxTo = term.toValue(); maxScore = term.score(); if (maxTo - i == 1 || i + 1 == terms.length) { continue; } boolean flag = true;// 可以删除 out: for (int j = i; j < maxTo; j++) { temp = terms[j]; if (temp == null) { continue; } do { if (temp.toValue() > maxTo || temp.score() < maxScore) { flag = false; break out; } } while ((temp = temp.next()) != null); } // 验证通过可以删除了 if (flag) { for (int j = i + 1; j < maxTo; j++) { terms[j] = null; } } } while ((term = term.next()) != null); } } /** * 默认按照最大分数作为路径 */ public void walkPathByScore(){ walkPathByScore(true); } /** * 路径方式 * @param asc true 最大路径,false 最小路径 */ public void walkPathByScore(boolean asc) { Term term = null; // BEGIN先行打分 mergerByScore(root, 0, asc); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); mergerByScore(term, to, asc); term = term.next(); } } optimalRoot(); } public void walkPath() { walkPath(null); } /** * 干涉性增加相对权重 * * @param relationMap */ public void walkPath(Map<String, Double> relationMap) { Term term = null; // BEGIN先行打分 merger(root, 0, relationMap); // 从第一个词开始往后打分 for (int i = 0; i < terms.length; i++) { term = terms[i]; while (term != null && term.from() != null && term != end) { int to = term.toValue(); merger(term, to, relationMap); term = term.next(); } } optimalRoot(); } /** * 具体的遍历打分方法 * * @param to */ private void merger(Term fromTerm, int to, Map<String, Double> relationMap) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathScore(fromTerm, relationMap); term = term.next(); } } else { char c = chars[to]; TermNatures tn = DATDictionary.getItem(c).termNatures; if (tn == null || tn == TermNatures.NULL) { tn = TermNatures.NULL; } terms[to] = new Term(String.valueOf(c), to, tn); terms[to].setPathScore(fromTerm, relationMap); } } /** * 根据分数 */ private void mergerByScore(Term fromTerm, int to, boolean asc) { Term term = null; if (terms[to] != null) { term = terms[to]; while (term != null) { // 关系式to.set(from) term.setPathSelfScore(fromTerm, asc); term = term.next(); } } } /** * 对graph进行调试用的 */ public void printGraph() { for (Term term : terms) { if (term == null) { continue; } System.out.print(term.getName() + "\t" + term.score() + " ,"); while ((term = term.next()) != null) { System.out.print(term + "\t" + term.score() + " ,"); } System.out.println(); } } }
false
2,531
11
2,888
10
2,871
12
2,888
10
3,657
18
false
false
false
false
false
true
60140_21
package com.tf.npu; import com.tf.npu.Init.SUPER2FH.ModBlocks.*; import com.tf.npu.Items.ItemLoader; import com.tf.npu.Proxy.CommonProxy; import com.tf.npu.Util.Reference; import com.tf.npu.Util.LoggerUtil; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.client.model.obj.OBJLoader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION) public class NPU { //**************************************************************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //**************************************************************************** public static final CreativeTabs MY_TAB = new CreativeTabs(Reference.MODID) { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.InnerPng); } }; public static final CreativeTabs MY_TAB1 = new CreativeTabs("constructions") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.ConsPng); } }; public static final CreativeTabs MY_TAB2 = new CreativeTabs("titles") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.TitlePng); } }; public static final CreativeTabs MY_TAB3 = new CreativeTabs("blocksonroad") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.OutPng); } }; public static final CreativeTabs MY_TAB4 = new CreativeTabs("windoor") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.WinDoorPng); } }; public static final CreativeTabs MY_TAB5 = new CreativeTabs("sign") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.Homework); } }; // ************************************SUPER2FH********************************************* public static final CreativeTabs TEMPORARY = new CreativeTabs("temporary") { @Override public ItemStack createIcon() { return new ItemStack(Blocks.BEDROCK); } }; /** * 椅子 */ public static final CreativeTabs CHAIR = new CreativeTabs("chair") { @Override public ItemStack createIcon() { return new ItemStack(ChairBlocks.CHAIR_AUDITORIUM_BLUE); } }; /** * 方块 */ public static final CreativeTabs CUBE = new CreativeTabs("cube") { @Override public ItemStack createIcon() { return new ItemStack(CubeBlocks.CEMENT_LIGHTBLUE); } }; /** * 设施 */ public static final CreativeTabs FACILITY = new CreativeTabs("facility") { @Override public ItemStack createIcon() { return new ItemStack(FacilityBlocks.TRASH_CLASSIFICATION_MEDICAL); } }; /** * 桌子 */ public static final CreativeTabs DESK = new CreativeTabs("desk") { @Override public ItemStack createIcon() { return new ItemStack(DeskBlocks.DESK_FOLDABLE); } }; /** * 障碍 */ public static final CreativeTabs FENCE = new CreativeTabs("fence") { @Override public ItemStack createIcon() { return new ItemStack(FenceBlocks.ROADBLOCK_DOUBLE); } }; public static final CreativeTabs NPUARMOR = new CreativeTabs("npu_armor") { @Override public ItemStack createIcon() { return new ItemStack(TemporaryBlocks.MASK_MEDICAL); } }; /** * 展示相关 */ public static final CreativeTabs RACK = new CreativeTabs("rack") { @Override public ItemStack createIcon() { return new ItemStack(RackBlocks.FLAG_CY); } }; /** * 栏杆 */ public static final CreativeTabs RAILING = new CreativeTabs("railing") { @Override public ItemStack createIcon() { return new ItemStack(RailingBlocks.RAILING_HALF); } }; /** * 楼梯 */ public static final CreativeTabs STAIR = new CreativeTabs("stair") { @Override public ItemStack createIcon() { return new ItemStack(StairBlocks.STAIR_CEMENT_LIGHTBLUE); } }; /** * 杂物 */ public static final CreativeTabs SUNDRIES = new CreativeTabs("sundries") { @Override public ItemStack createIcon() { return new ItemStack(SundriesBlocks.ADMISSION_LETTER_2021); } }; /** * 车辆 */ public static final CreativeTabs VEHICLE = new CreativeTabs("vehicle") { @Override public ItemStack createIcon() { return new ItemStack(VehicleBlocks.BIKE1); } }; /** * 机械机器 */ public static final CreativeTabs MACHINE = new CreativeTabs("machine") { @Override public ItemStack createIcon() { return new ItemStack(Blocks.BEDROCK); } }; /** * 家具相关 */ public static final CreativeTabs FURNITURE = new CreativeTabs("furniture") { @Override public ItemStack createIcon() { return new ItemStack(FurnitureBlocks.AIRCONDITIONER_VERTICAL); } }; /** * 灯光相关 */ public static final CreativeTabs LIGHT = new CreativeTabs("light_dormitory_bathroom") { @Override public ItemStack createIcon() { return new ItemStack(LightBlocks.LIGHT_CEILING_LONG); } }; /** * 窗户相关 */ public static final CreativeTabs WINDOW = new CreativeTabs("window") { @Override public ItemStack createIcon() { return new ItemStack(WindowBlocks.GLASS_WALL_HALF); } }; @Instance public static NPU instance; @SidedProxy(serverSide = Reference.SERVER_PROXY_CLASS, clientSide = Reference.CLIENT_PROXY_CLASS) public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent event) { if (event.getSide().isClient()) { OBJLoader.INSTANCE.addDomain("NPU"); } proxy.preInit(event); LoggerUtil.logger = event.getModLog(); LoggerUtil.logger.warn("Project Npu Reconstruction!"); } @EventHandler public void init(FMLInitializationEvent event) { proxy.init(event); LoggerUtil.logger.warn("Project Npu Reconstruction."); } @EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(event); LoggerUtil.logger.warn("Project Npu Reconstruction."); } public static boolean DISABLE_IN_DEV = false; // private static CreativeTabs geckolibItemGroup; private boolean deobfuscatedEnvironment; // public static CreativeTabs getGeckolibItemGroup() // { // if (geckolibItemGroup == null) // { // geckolibItemGroup = new CreativeTabs(CreativeTabs.getNextID(), "geckolib_examples") // { // @Override // public ItemStack createIcon() // { // return new ItemStack(ItemRegistry.JACK_IN_THE_BOX); // } // }; // } // // return geckolibItemGroup; // } // @SideOnly(Side.CLIENT) // @Mod.EventHandler // public void registerRenderers(FMLPreInitializationEvent event) // { // ClientRegistry.bindTileEntitySpecialRenderer(CNCTileEntity.class, new CNCRenderer()); // // } }
NPUcraft/build-the-world-for-npu
src/main/java/com/tf/npu/NPU.java
2,057
/** * 机械机器 */
block_comment
zh-cn
package com.tf.npu; import com.tf.npu.Init.SUPER2FH.ModBlocks.*; import com.tf.npu.Items.ItemLoader; import com.tf.npu.Proxy.CommonProxy; import com.tf.npu.Util.Reference; import com.tf.npu.Util.LoggerUtil; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraftforge.client.model.obj.OBJLoader; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; import net.minecraftforge.fml.common.Mod.Instance; import net.minecraftforge.fml.common.SidedProxy; import net.minecraftforge.fml.common.event.FMLInitializationEvent; import net.minecraftforge.fml.common.event.FMLPostInitializationEvent; import net.minecraftforge.fml.common.event.FMLPreInitializationEvent; @Mod(modid = Reference.MODID, name = Reference.NAME, version = Reference.VERSION) public class NPU { //**************************************************************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //***************************请在CommonProxy里注册!*************************** //**************************************************************************** public static final CreativeTabs MY_TAB = new CreativeTabs(Reference.MODID) { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.InnerPng); } }; public static final CreativeTabs MY_TAB1 = new CreativeTabs("constructions") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.ConsPng); } }; public static final CreativeTabs MY_TAB2 = new CreativeTabs("titles") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.TitlePng); } }; public static final CreativeTabs MY_TAB3 = new CreativeTabs("blocksonroad") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.OutPng); } }; public static final CreativeTabs MY_TAB4 = new CreativeTabs("windoor") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.WinDoorPng); } }; public static final CreativeTabs MY_TAB5 = new CreativeTabs("sign") { @Override public ItemStack createIcon() { return new ItemStack(ItemLoader.Homework); } }; // ************************************SUPER2FH********************************************* public static final CreativeTabs TEMPORARY = new CreativeTabs("temporary") { @Override public ItemStack createIcon() { return new ItemStack(Blocks.BEDROCK); } }; /** * 椅子 */ public static final CreativeTabs CHAIR = new CreativeTabs("chair") { @Override public ItemStack createIcon() { return new ItemStack(ChairBlocks.CHAIR_AUDITORIUM_BLUE); } }; /** * 方块 */ public static final CreativeTabs CUBE = new CreativeTabs("cube") { @Override public ItemStack createIcon() { return new ItemStack(CubeBlocks.CEMENT_LIGHTBLUE); } }; /** * 设施 */ public static final CreativeTabs FACILITY = new CreativeTabs("facility") { @Override public ItemStack createIcon() { return new ItemStack(FacilityBlocks.TRASH_CLASSIFICATION_MEDICAL); } }; /** * 桌子 */ public static final CreativeTabs DESK = new CreativeTabs("desk") { @Override public ItemStack createIcon() { return new ItemStack(DeskBlocks.DESK_FOLDABLE); } }; /** * 障碍 */ public static final CreativeTabs FENCE = new CreativeTabs("fence") { @Override public ItemStack createIcon() { return new ItemStack(FenceBlocks.ROADBLOCK_DOUBLE); } }; public static final CreativeTabs NPUARMOR = new CreativeTabs("npu_armor") { @Override public ItemStack createIcon() { return new ItemStack(TemporaryBlocks.MASK_MEDICAL); } }; /** * 展示相关 */ public static final CreativeTabs RACK = new CreativeTabs("rack") { @Override public ItemStack createIcon() { return new ItemStack(RackBlocks.FLAG_CY); } }; /** * 栏杆 */ public static final CreativeTabs RAILING = new CreativeTabs("railing") { @Override public ItemStack createIcon() { return new ItemStack(RailingBlocks.RAILING_HALF); } }; /** * 楼梯 */ public static final CreativeTabs STAIR = new CreativeTabs("stair") { @Override public ItemStack createIcon() { return new ItemStack(StairBlocks.STAIR_CEMENT_LIGHTBLUE); } }; /** * 杂物 */ public static final CreativeTabs SUNDRIES = new CreativeTabs("sundries") { @Override public ItemStack createIcon() { return new ItemStack(SundriesBlocks.ADMISSION_LETTER_2021); } }; /** * 车辆 */ public static final CreativeTabs VEHICLE = new CreativeTabs("vehicle") { @Override public ItemStack createIcon() { return new ItemStack(VehicleBlocks.BIKE1); } }; /** * 机械机 <SUF>*/ public static final CreativeTabs MACHINE = new CreativeTabs("machine") { @Override public ItemStack createIcon() { return new ItemStack(Blocks.BEDROCK); } }; /** * 家具相关 */ public static final CreativeTabs FURNITURE = new CreativeTabs("furniture") { @Override public ItemStack createIcon() { return new ItemStack(FurnitureBlocks.AIRCONDITIONER_VERTICAL); } }; /** * 灯光相关 */ public static final CreativeTabs LIGHT = new CreativeTabs("light_dormitory_bathroom") { @Override public ItemStack createIcon() { return new ItemStack(LightBlocks.LIGHT_CEILING_LONG); } }; /** * 窗户相关 */ public static final CreativeTabs WINDOW = new CreativeTabs("window") { @Override public ItemStack createIcon() { return new ItemStack(WindowBlocks.GLASS_WALL_HALF); } }; @Instance public static NPU instance; @SidedProxy(serverSide = Reference.SERVER_PROXY_CLASS, clientSide = Reference.CLIENT_PROXY_CLASS) public static CommonProxy proxy; @EventHandler public void preInit(FMLPreInitializationEvent event) { if (event.getSide().isClient()) { OBJLoader.INSTANCE.addDomain("NPU"); } proxy.preInit(event); LoggerUtil.logger = event.getModLog(); LoggerUtil.logger.warn("Project Npu Reconstruction!"); } @EventHandler public void init(FMLInitializationEvent event) { proxy.init(event); LoggerUtil.logger.warn("Project Npu Reconstruction."); } @EventHandler public void postInit(FMLPostInitializationEvent event) { proxy.postInit(event); LoggerUtil.logger.warn("Project Npu Reconstruction."); } public static boolean DISABLE_IN_DEV = false; // private static CreativeTabs geckolibItemGroup; private boolean deobfuscatedEnvironment; // public static CreativeTabs getGeckolibItemGroup() // { // if (geckolibItemGroup == null) // { // geckolibItemGroup = new CreativeTabs(CreativeTabs.getNextID(), "geckolib_examples") // { // @Override // public ItemStack createIcon() // { // return new ItemStack(ItemRegistry.JACK_IN_THE_BOX); // } // }; // } // // return geckolibItemGroup; // } // @SideOnly(Side.CLIENT) // @Mod.EventHandler // public void registerRenderers(FMLPreInitializationEvent event) // { // ClientRegistry.bindTileEntitySpecialRenderer(CNCTileEntity.class, new CNCRenderer()); // // } }
false
1,827
9
2,018
10
2,139
9
2,018
10
2,618
14
false
false
false
false
false
true
60604_1
package me.http.utils; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import me.app.global.Constant; import android.util.Log; public class MyThreadPool { private static MyThreadPool mThreadPool = null; private static final boolean D = Constant.DEBUG; private static final String TAG = "MyThreadPool"; private static final int THREAD_NUM = 2; private ExecutorService executorService = null; protected MyThreadPool() { executorService = Executors.newFixedThreadPool(THREAD_NUM); } public static MyThreadPool getInstance() { if (mThreadPool == null) { mThreadPool = new MyThreadPool(); } return mThreadPool; } public ExecutorService getExecutorService() { return executorService; } public void mHandleGetTask(String url, Map<String, String> mapParams) { executorService.submit(new Runnable() { @Override public void run() { // TODO Auto-generated method stub } }); } /** * 描述:立即关闭. */ public void shutdownNow() { if (!executorService.isTerminated()) { executorService.shutdownNow(); listenShutdown(); } } /** * 描述:平滑关闭. */ public void shutdown() { if (!executorService.isTerminated()) { executorService.shutdown(); listenShutdown(); } } /** * 描述:关闭监听. */ public void listenShutdown() { try { while (!executorService.awaitTermination(1, TimeUnit.MILLISECONDS)) { if (D) Log.d(TAG, "线程池未关闭"); } if (D) Log.d(TAG, "线程池已关闭"); } catch (Exception e) { e.printStackTrace(); } } }
NUTEGG/where
src/me/http/utils/MyThreadPool.java
493
/** * 描述:立即关闭. */
block_comment
zh-cn
package me.http.utils; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import me.app.global.Constant; import android.util.Log; public class MyThreadPool { private static MyThreadPool mThreadPool = null; private static final boolean D = Constant.DEBUG; private static final String TAG = "MyThreadPool"; private static final int THREAD_NUM = 2; private ExecutorService executorService = null; protected MyThreadPool() { executorService = Executors.newFixedThreadPool(THREAD_NUM); } public static MyThreadPool getInstance() { if (mThreadPool == null) { mThreadPool = new MyThreadPool(); } return mThreadPool; } public ExecutorService getExecutorService() { return executorService; } public void mHandleGetTask(String url, Map<String, String> mapParams) { executorService.submit(new Runnable() { @Override public void run() { // TODO Auto-generated method stub } }); } /** * 描述: <SUF>*/ public void shutdownNow() { if (!executorService.isTerminated()) { executorService.shutdownNow(); listenShutdown(); } } /** * 描述:平滑关闭. */ public void shutdown() { if (!executorService.isTerminated()) { executorService.shutdown(); listenShutdown(); } } /** * 描述:关闭监听. */ public void listenShutdown() { try { while (!executorService.awaitTermination(1, TimeUnit.MILLISECONDS)) { if (D) Log.d(TAG, "线程池未关闭"); } if (D) Log.d(TAG, "线程池已关闭"); } catch (Exception e) { e.printStackTrace(); } } }
false
396
11
489
13
487
12
489
13
642
24
false
false
false
false
false
true
42303_11
package top.naccl.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import top.naccl.model.vo.BlogIdAndTitle; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @Description: 博客评论 * @Author: Naccl * @Date: 2020-07-27 */ @NoArgsConstructor @Getter @Setter @ToString public class Comment { private Long id; private String nickname;//昵称 private String email;//邮箱 private String content;//评论内容 private String avatar;//头像(图片路径) private Date createTime;//评论时间 private String website;//个人网站 private String ip;//评论者ip地址 private Boolean published;//公开或回收站 private Boolean adminComment;//博主回复 private Integer page;//0普通文章,1关于我页面 private Boolean notice;//接收邮件提醒 private Long parentCommentId;//父评论id private String qq;//如果评论昵称为QQ号,则将昵称和头像置为QQ昵称和QQ头像,并将此字段置为QQ号备份 private BlogIdAndTitle blog;//所属的文章 private List<Comment> replyComments = new ArrayList<>();//回复该评论的评论 }
Naccl/NBlog
blog-api/src/main/java/top/naccl/entity/Comment.java
333
//如果评论昵称为QQ号,则将昵称和头像置为QQ昵称和QQ头像,并将此字段置为QQ号备份
line_comment
zh-cn
package top.naccl.entity; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; import top.naccl.model.vo.BlogIdAndTitle; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @Description: 博客评论 * @Author: Naccl * @Date: 2020-07-27 */ @NoArgsConstructor @Getter @Setter @ToString public class Comment { private Long id; private String nickname;//昵称 private String email;//邮箱 private String content;//评论内容 private String avatar;//头像(图片路径) private Date createTime;//评论时间 private String website;//个人网站 private String ip;//评论者ip地址 private Boolean published;//公开或回收站 private Boolean adminComment;//博主回复 private Integer page;//0普通文章,1关于我页面 private Boolean notice;//接收邮件提醒 private Long parentCommentId;//父评论id private String qq;//如果 <SUF> private BlogIdAndTitle blog;//所属的文章 private List<Comment> replyComments = new ArrayList<>();//回复该评论的评论 }
false
268
32
333
39
312
29
333
39
456
57
false
false
false
false
false
true
18877_1
package main; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MainFrame extends JFrame implements ActionListener { private static final int DEFAULT_WIDTH = 600; private static final int DEFAULT_HEIGHT = 400; private JMenuBar menuBar = new JMenuBar(); // 用户菜单 private JMenu userMenu = new JMenu("用户"); private JMenuItem changePasswordMenuItem = new JMenuItem("修改密码"); private JMenuItem exitMenuItem = new JMenuItem("退出游戏"); // 游戏菜单 private JMenu gameMenu = new JMenu("游戏"); private JMenuItem createRoomItem = new JMenuItem("创建房间"); private JMenuItem enterRoomItem = new JMenuItem("进入房间"); private JPanel panel = new JPanel(); private JButton createRoomButton = new JButton("创建房间"); private JButton enterRoomButton = new JButton("进入房间"); // 欢迎界面 private JLabel welcomeLabel = new JLabel("五子棋"); private void addMenu() { userMenu.add(changePasswordMenuItem); userMenu.add(exitMenuItem); menuBar.add(userMenu); gameMenu.add(createRoomItem); gameMenu.add(enterRoomItem); menuBar.add(gameMenu); this.setJMenuBar(menuBar); exitMenuItem.addActionListener(this); createRoomItem.addActionListener(this); } private void addButton() { panel.add(createRoomButton); panel.add(enterRoomButton); this.getContentPane().add(panel, BorderLayout.SOUTH); // 注册监听 Button createRoomButton.addActionListener(this); } private void addLabel() { welcomeLabel.setFont(new java.awt.Font("welcome", 1, 48)); welcomeLabel.setHorizontalAlignment(SwingConstants.CENTER); this.getContentPane().add(welcomeLabel); } public MainFrame() throws HeadlessException { addMenu(); addButton(); addLabel(); this.setTitle("五子棋"); this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } private game.GameFrame game; @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == exitMenuItem) {//退出 if (JOptionPane.showConfirmDialog(this, "确认要退出游戏?", "退出", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { System.exit(0); } } else if (e.getSource() == createRoomButton || e.getSource() == createRoomItem) {// 创建游戏 if (game == null) game = new game.GameFrame(); game.setVisible(true); } } }
Naccl/gobang-java-swing
src/main/MainFrame.java
706
// 游戏菜单
line_comment
zh-cn
package main; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class MainFrame extends JFrame implements ActionListener { private static final int DEFAULT_WIDTH = 600; private static final int DEFAULT_HEIGHT = 400; private JMenuBar menuBar = new JMenuBar(); // 用户菜单 private JMenu userMenu = new JMenu("用户"); private JMenuItem changePasswordMenuItem = new JMenuItem("修改密码"); private JMenuItem exitMenuItem = new JMenuItem("退出游戏"); // 游戏 <SUF> private JMenu gameMenu = new JMenu("游戏"); private JMenuItem createRoomItem = new JMenuItem("创建房间"); private JMenuItem enterRoomItem = new JMenuItem("进入房间"); private JPanel panel = new JPanel(); private JButton createRoomButton = new JButton("创建房间"); private JButton enterRoomButton = new JButton("进入房间"); // 欢迎界面 private JLabel welcomeLabel = new JLabel("五子棋"); private void addMenu() { userMenu.add(changePasswordMenuItem); userMenu.add(exitMenuItem); menuBar.add(userMenu); gameMenu.add(createRoomItem); gameMenu.add(enterRoomItem); menuBar.add(gameMenu); this.setJMenuBar(menuBar); exitMenuItem.addActionListener(this); createRoomItem.addActionListener(this); } private void addButton() { panel.add(createRoomButton); panel.add(enterRoomButton); this.getContentPane().add(panel, BorderLayout.SOUTH); // 注册监听 Button createRoomButton.addActionListener(this); } private void addLabel() { welcomeLabel.setFont(new java.awt.Font("welcome", 1, 48)); welcomeLabel.setHorizontalAlignment(SwingConstants.CENTER); this.getContentPane().add(welcomeLabel); } public MainFrame() throws HeadlessException { addMenu(); addButton(); addLabel(); this.setTitle("五子棋"); this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); this.setLocationRelativeTo(null); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } private game.GameFrame game; @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == exitMenuItem) {//退出 if (JOptionPane.showConfirmDialog(this, "确认要退出游戏?", "退出", JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) { System.exit(0); } } else if (e.getSource() == createRoomButton || e.getSource() == createRoomItem) {// 创建游戏 if (game == null) game = new game.GameFrame(); game.setVisible(true); } } }
false
541
5
706
5
674
3
706
5
900
10
false
false
false
false
false
true
61178_3
package ustcsoft.bean; import java.math.BigDecimal; import java.text.DateFormat; import java.util.Date; public class Teacher { private String teacherID;// 工号 private String teacherName;// 名字 private int time;// 入职时长 private int age;// 年纪 private BigDecimal pay;// 工资 private Date startTime;// 入职时间 private String text;// 备考 @Override public String toString() { // TODO 自动生成的方法存根 return "学号:" + this.getTeacherID() + " " + "姓名:" + this.getTeacherName() + " " + "年龄:" + this.getAge() + " " + "入学时间:" + this.getStartTime() + " " + "备考:" + this.getText() + " " + "工资:" + this.getPay() + " " + "入职时长:" + this.getTime(); } public String getTeacherID() { return teacherID; } public void setTeacherID(String teacherID) { this.teacherID = teacherID; } public String getTeacherName() { return teacherName; } public void setTeacherName(String teacherName) { this.teacherName = teacherName; } public int getTime() { return time; } public void setTime(Integer time) { this.time = time; } public int getAge() { return age; } public void setAge(Integer age) { this.age = age; } public BigDecimal getPay() { return pay; } public void setPay(BigDecimal pay) { this.pay = pay; } public String getStartTime() { return DateFormat.getDateInstance(DateFormat.FULL).format(startTime);// 格式化时间 } public void setStartTime(Date startTime) { this.startTime = startTime; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
NaiHeKK/JAVA-Study
src/ustcsoft/bean/Teacher.java
538
// 年纪
line_comment
zh-cn
package ustcsoft.bean; import java.math.BigDecimal; import java.text.DateFormat; import java.util.Date; public class Teacher { private String teacherID;// 工号 private String teacherName;// 名字 private int time;// 入职时长 private int age;// 年纪 <SUF> private BigDecimal pay;// 工资 private Date startTime;// 入职时间 private String text;// 备考 @Override public String toString() { // TODO 自动生成的方法存根 return "学号:" + this.getTeacherID() + " " + "姓名:" + this.getTeacherName() + " " + "年龄:" + this.getAge() + " " + "入学时间:" + this.getStartTime() + " " + "备考:" + this.getText() + " " + "工资:" + this.getPay() + " " + "入职时长:" + this.getTime(); } public String getTeacherID() { return teacherID; } public void setTeacherID(String teacherID) { this.teacherID = teacherID; } public String getTeacherName() { return teacherName; } public void setTeacherName(String teacherName) { this.teacherName = teacherName; } public int getTime() { return time; } public void setTime(Integer time) { this.time = time; } public int getAge() { return age; } public void setAge(Integer age) { this.age = age; } public BigDecimal getPay() { return pay; } public void setPay(BigDecimal pay) { this.pay = pay; } public String getStartTime() { return DateFormat.getDateInstance(DateFormat.FULL).format(startTime);// 格式化时间 } public void setStartTime(Date startTime) { this.startTime = startTime; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
false
420
5
536
4
514
4
536
4
654
7
false
false
false
false
false
true
44067_4
package com.southernbox.indexbar.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.southernbox.indexbar.R; import com.southernbox.indexbar.adapter.MainAdapter; import com.southernbox.indexbar.entity.Entity; import com.southernbox.indexbar.widget.IndexBar; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by SouthernBox on 2016/10/25 0025. * 主页面 */ public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private MainAdapter mAdapter; private List<Entity> mList = new ArrayList<>(); private IndexBar mIndexBar; private View vFlow; private TextView tvFlowIndex; private LinearLayoutManager layoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initRecyclerView(); initIndexBar(); initData(); initFlowIndex(); } /** * 初始化列表 */ private void initRecyclerView() { mRecyclerView = findViewById(R.id.rv); layoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(layoutManager); mAdapter = new MainAdapter(this, mList); mRecyclerView.setAdapter(mAdapter); } /** * 初始化快速索引栏 */ private void initIndexBar() { mIndexBar = findViewById(R.id.indexbar); TextView tvToast = findViewById(R.id.tv_toast); mIndexBar.setSelectedIndexTextView(tvToast); mIndexBar.setOnIndexChangedListener(new IndexBar.OnIndexChangedListener() { @Override public void onIndexChanged(String index) { for (int i = 0; i < mList.size(); i++) { String firstWord = mList.get(i).getFirstWord(); if (index.equals(firstWord)) { // 滚动列表到指定的位置 layoutManager.scrollToPositionWithOffset(i, 0); return; } } } }); } /** * 加载数据 */ @SuppressWarnings("unchecked") private void initData() { Map<String, Object> map = convertSortList(getData()); mList.clear(); mList.addAll((List<Entity>) map.get("sortList")); Object[] keys = (Object[]) map.get("keys"); String[] letters = new String[keys.length]; for (int i = 0; i < keys.length; i++) { letters[i] = keys[i].toString(); } mIndexBar.setIndexs(letters); mAdapter.notifyDataSetChanged(); } /** * 初始化顶部悬浮标签 */ private void initFlowIndex() { vFlow = findViewById(R.id.ll_index); tvFlowIndex = findViewById(R.id.tv_index); mRecyclerView.addOnScrollListener(new mScrollListener()); //设置首项的索引字母 if (mList.size() > 0) { tvFlowIndex.setText(mList.get(0).getFirstWord()); vFlow.setVisibility(View.VISIBLE); } } private class mScrollListener extends RecyclerView.OnScrollListener { private int mFlowHeight; private int mCurrentPosition = -1; @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { mFlowHeight = vFlow.getMeasuredHeight(); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition(); View view = layoutManager.findViewByPosition(firstVisibleItemPosition + 1); if (view != null) { if (view.getTop() <= mFlowHeight && isItem(firstVisibleItemPosition + 1)) { vFlow.setY(view.getTop() - mFlowHeight); } else { vFlow.setY(0); } } if (mCurrentPosition != firstVisibleItemPosition) { mCurrentPosition = firstVisibleItemPosition; tvFlowIndex.setText(mList.get(mCurrentPosition).getFirstWord()); } } /** * @param position 对应项的下标 * @return 是否为标签项 */ private boolean isItem(int position) { return mAdapter.getItemViewType(position) == MainAdapter.VIEW_INDEX; } } /** * 按首字母将数据排序 * * @param list 需要排序的数组 * @return 返回按首字母排序的集合(集合中插入标签项),及所有出现的首字母数组 */ public Map<String, Object> convertSortList(List<Entity> list) { HashMap<String, List<Entity>> map = new HashMap<>(); for (Entity item : list) { String firstWord; if (TextUtils.isEmpty(item.getFirstWord())) { firstWord = "#"; } else { firstWord = item.getFirstWord().toUpperCase(); } if (map.containsKey(firstWord)) { map.get(firstWord).add(item); } else { List<Entity> mList = new ArrayList<>(); mList.add(item); map.put(firstWord, mList); } } Object[] keys = map.keySet().toArray(); Arrays.sort(keys); List<Entity> sortList = new ArrayList<>(); for (Object key : keys) { Entity t = getIndexItem(key.toString()); sortList.add(t); sortList.addAll(map.get(key.toString())); } HashMap<String, Object> resultMap = new HashMap<>(); resultMap.put("sortList", sortList); resultMap.put("keys", keys); return resultMap; } private Entity getIndexItem(String firstWord) { Entity entity = new Entity(); entity.setFirstWord(firstWord); entity.setIndex(true); return entity; } private List<Entity> getData() { List<Entity> list = new ArrayList<>(); list.add(new Entity("加内特", "J")); list.add(new Entity("韦德", "W")); list.add(new Entity("詹姆斯", "Z")); list.add(new Entity("安东尼", "A")); list.add(new Entity("科比", "K")); list.add(new Entity("乔丹", "Q")); list.add(new Entity("奥尼尔", "A")); list.add(new Entity("麦格雷迪", "M")); list.add(new Entity("艾弗森", "A")); list.add(new Entity("哈达威", "H")); list.add(new Entity("纳什", "N")); list.add(new Entity("弗朗西斯", "F")); list.add(new Entity("姚明", "Y")); list.add(new Entity("库里", "K")); list.add(new Entity("邓肯", "D")); list.add(new Entity("吉诺比利", "J")); list.add(new Entity("帕克", "P")); list.add(new Entity("杜兰特", "D")); list.add(new Entity("韦伯", "W")); list.add(new Entity("威斯布鲁克", "W")); list.add(new Entity("霍华德", "H")); list.add(new Entity("保罗", "B")); list.add(new Entity("罗斯", "L")); list.add(new Entity("加索尔", "J")); list.add(new Entity("隆多", "L")); list.add(new Entity("诺维斯基", "N")); list.add(new Entity("格里芬", "G")); list.add(new Entity("波什", "B")); list.add(new Entity("伊戈达拉", "Y")); return list; } }
NanBox/IndexBar
app/src/main/java/com/southernbox/indexbar/activity/MainActivity.java
1,961
/** * 加载数据 */
block_comment
zh-cn
package com.southernbox.indexbar.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.southernbox.indexbar.R; import com.southernbox.indexbar.adapter.MainAdapter; import com.southernbox.indexbar.entity.Entity; import com.southernbox.indexbar.widget.IndexBar; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by SouthernBox on 2016/10/25 0025. * 主页面 */ public class MainActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private MainAdapter mAdapter; private List<Entity> mList = new ArrayList<>(); private IndexBar mIndexBar; private View vFlow; private TextView tvFlowIndex; private LinearLayoutManager layoutManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initRecyclerView(); initIndexBar(); initData(); initFlowIndex(); } /** * 初始化列表 */ private void initRecyclerView() { mRecyclerView = findViewById(R.id.rv); layoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(layoutManager); mAdapter = new MainAdapter(this, mList); mRecyclerView.setAdapter(mAdapter); } /** * 初始化快速索引栏 */ private void initIndexBar() { mIndexBar = findViewById(R.id.indexbar); TextView tvToast = findViewById(R.id.tv_toast); mIndexBar.setSelectedIndexTextView(tvToast); mIndexBar.setOnIndexChangedListener(new IndexBar.OnIndexChangedListener() { @Override public void onIndexChanged(String index) { for (int i = 0; i < mList.size(); i++) { String firstWord = mList.get(i).getFirstWord(); if (index.equals(firstWord)) { // 滚动列表到指定的位置 layoutManager.scrollToPositionWithOffset(i, 0); return; } } } }); } /** * 加载数 <SUF>*/ @SuppressWarnings("unchecked") private void initData() { Map<String, Object> map = convertSortList(getData()); mList.clear(); mList.addAll((List<Entity>) map.get("sortList")); Object[] keys = (Object[]) map.get("keys"); String[] letters = new String[keys.length]; for (int i = 0; i < keys.length; i++) { letters[i] = keys[i].toString(); } mIndexBar.setIndexs(letters); mAdapter.notifyDataSetChanged(); } /** * 初始化顶部悬浮标签 */ private void initFlowIndex() { vFlow = findViewById(R.id.ll_index); tvFlowIndex = findViewById(R.id.tv_index); mRecyclerView.addOnScrollListener(new mScrollListener()); //设置首项的索引字母 if (mList.size() > 0) { tvFlowIndex.setText(mList.get(0).getFirstWord()); vFlow.setVisibility(View.VISIBLE); } } private class mScrollListener extends RecyclerView.OnScrollListener { private int mFlowHeight; private int mCurrentPosition = -1; @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { mFlowHeight = vFlow.getMeasuredHeight(); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition(); View view = layoutManager.findViewByPosition(firstVisibleItemPosition + 1); if (view != null) { if (view.getTop() <= mFlowHeight && isItem(firstVisibleItemPosition + 1)) { vFlow.setY(view.getTop() - mFlowHeight); } else { vFlow.setY(0); } } if (mCurrentPosition != firstVisibleItemPosition) { mCurrentPosition = firstVisibleItemPosition; tvFlowIndex.setText(mList.get(mCurrentPosition).getFirstWord()); } } /** * @param position 对应项的下标 * @return 是否为标签项 */ private boolean isItem(int position) { return mAdapter.getItemViewType(position) == MainAdapter.VIEW_INDEX; } } /** * 按首字母将数据排序 * * @param list 需要排序的数组 * @return 返回按首字母排序的集合(集合中插入标签项),及所有出现的首字母数组 */ public Map<String, Object> convertSortList(List<Entity> list) { HashMap<String, List<Entity>> map = new HashMap<>(); for (Entity item : list) { String firstWord; if (TextUtils.isEmpty(item.getFirstWord())) { firstWord = "#"; } else { firstWord = item.getFirstWord().toUpperCase(); } if (map.containsKey(firstWord)) { map.get(firstWord).add(item); } else { List<Entity> mList = new ArrayList<>(); mList.add(item); map.put(firstWord, mList); } } Object[] keys = map.keySet().toArray(); Arrays.sort(keys); List<Entity> sortList = new ArrayList<>(); for (Object key : keys) { Entity t = getIndexItem(key.toString()); sortList.add(t); sortList.addAll(map.get(key.toString())); } HashMap<String, Object> resultMap = new HashMap<>(); resultMap.put("sortList", sortList); resultMap.put("keys", keys); return resultMap; } private Entity getIndexItem(String firstWord) { Entity entity = new Entity(); entity.setFirstWord(firstWord); entity.setIndex(true); return entity; } private List<Entity> getData() { List<Entity> list = new ArrayList<>(); list.add(new Entity("加内特", "J")); list.add(new Entity("韦德", "W")); list.add(new Entity("詹姆斯", "Z")); list.add(new Entity("安东尼", "A")); list.add(new Entity("科比", "K")); list.add(new Entity("乔丹", "Q")); list.add(new Entity("奥尼尔", "A")); list.add(new Entity("麦格雷迪", "M")); list.add(new Entity("艾弗森", "A")); list.add(new Entity("哈达威", "H")); list.add(new Entity("纳什", "N")); list.add(new Entity("弗朗西斯", "F")); list.add(new Entity("姚明", "Y")); list.add(new Entity("库里", "K")); list.add(new Entity("邓肯", "D")); list.add(new Entity("吉诺比利", "J")); list.add(new Entity("帕克", "P")); list.add(new Entity("杜兰特", "D")); list.add(new Entity("韦伯", "W")); list.add(new Entity("威斯布鲁克", "W")); list.add(new Entity("霍华德", "H")); list.add(new Entity("保罗", "B")); list.add(new Entity("罗斯", "L")); list.add(new Entity("加索尔", "J")); list.add(new Entity("隆多", "L")); list.add(new Entity("诺维斯基", "N")); list.add(new Entity("格里芬", "G")); list.add(new Entity("波什", "B")); list.add(new Entity("伊戈达拉", "Y")); return list; } }
false
1,635
9
1,962
8
2,046
9
1,961
8
2,355
12
false
false
false
false
false
true
7948_0
/** * 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 * * 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花? * 能则返回True,不能则返回False。 * * 示例 1: * * 输入: flowerbed = [1,0,0,0,1], n = 1 * 输出: True * 示例 2: * * 输入: flowerbed = [1,0,0,0,1], n = 2 * 输出: False * 注意: * * 数组内已种好的花不会违反种植规则。 * 输入的数组长度范围为 [1, 20000]。 * n 是非负整数,且不会超过输入数组的大小。 * @author:xzj * @date: 2018/8/6 16:09 */ class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int index = 0; int count = 0; if (flowerbed.length ==1) { if (flowerbed[0] == 0) { return n == 0 || n == 1; }else { return n==0; } } else { while (index < flowerbed.length) { if (index == 0) { if (flowerbed[0] == 0 && flowerbed[1] == 0) { flowerbed[0] = 1; count++; } } else if (index == flowerbed.length - 1) { if (flowerbed[index] == 0 && flowerbed[index - 1] == 0) { flowerbed[index] = 1; count++; } } else { if (flowerbed[index] == 0 && flowerbed[index - 1] == 0 && flowerbed[index + 1] == 0) { flowerbed[index] = 1; count++; } } if(count >=n) return true; index++; } return false; } } }
NanayaHaruki/leetcode
序号/605. Can Place Flowers.java
605
/** * 假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有。可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去。 * * 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花),和一个数 n 。能否在不打破种植规则的情况下种入 n 朵花? * 能则返回True,不能则返回False。 * * 示例 1: * * 输入: flowerbed = [1,0,0,0,1], n = 1 * 输出: True * 示例 2: * * 输入: flowerbed = [1,0,0,0,1], n = 2 * 输出: False * 注意: * * 数组内已种好的花不会违反种植规则。 * 输入的数组长度范围为 [1, 20000]。 * n 是非负整数,且不会超过输入数组的大小。 * @author:xzj * @date: 2018/8/6 16:09 */
block_comment
zh-cn
/** * 假设你 <SUF>*/ class Solution { public boolean canPlaceFlowers(int[] flowerbed, int n) { int index = 0; int count = 0; if (flowerbed.length ==1) { if (flowerbed[0] == 0) { return n == 0 || n == 1; }else { return n==0; } } else { while (index < flowerbed.length) { if (index == 0) { if (flowerbed[0] == 0 && flowerbed[1] == 0) { flowerbed[0] = 1; count++; } } else if (index == flowerbed.length - 1) { if (flowerbed[index] == 0 && flowerbed[index - 1] == 0) { flowerbed[index] = 1; count++; } } else { if (flowerbed[index] == 0 && flowerbed[index - 1] == 0 && flowerbed[index + 1] == 0) { flowerbed[index] = 1; count++; } } if(count >=n) return true; index++; } return false; } } }
false
521
251
605
310
584
266
605
310
741
405
true
true
true
true
true
false
35730_4
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Main { public static void main(String[] args) { if (args.length > 0) { unusedCleaner(args[0]); } } static ArrayList<TypeSource> currents = new ArrayList<>(); static final ArrayList<File> AllFiles = new ArrayList<>(); static String encoding = "utf-8"; static boolean LastIsPath = false; public static void unusedCleaner(String filePath) { int crtLine = 0; ArrayList<TypeSource> files = new ArrayList<>(); try { File file = new File(filePath); if (file.isFile() && file.exists()) { InputStreamReader read = new InputStreamReader( new FileInputStream(file), encoding); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { if (crtLine == 0) { parsellFiles(lineTxt); } else { if (!parseType(lineTxt)) { String trim = lineTxt.trim(); if (new File(trim).exists()) { for (Iterator<TypeSource> iterator = currents .iterator(); iterator.hasNext();) { TypeSource typeSource = (TypeSource) iterator .next().clone(); typeSource.path = trim; typeSource.xmlTag = typeSource.getXmlTag(); files.add(typeSource); } LastIsPath = true; } } } crtLine++; } read.close(); } else { System.out.println("noFile"); } } catch (Exception e) { System.out.println("Failed"); e.printStackTrace(); } for (Iterator<TypeSource> iterator = files.iterator(); iterator .hasNext();) { TypeSource typeSource = (TypeSource) iterator.next(); System.out.println(typeSource); typeSource.cleanSelf(); } System.out.println("done"); } public static void parsellFiles(String line) { String reg = "Running in:\\s+(\\S+)"; Matcher matcher = Pattern.compile(reg).matcher(line); if (matcher.find()) { String path = matcher.group(1); File file = new File(path); scanSourceFiles(file); } } public static boolean parseType(String lineTxt) { // drawable/anim/layout/ String reg = "((drawable)|(anim)|(layout)|(dimen)|(string)|(attr)|(style)|(styleable)|(color)|(id))\\s*:\\s*(\\S+)"; Matcher matcher = Pattern.compile(reg).matcher(lineTxt); if (matcher.find()) { if (LastIsPath) { currents.clear(); } LastIsPath = false; TypeSource typeSource = new TypeSource(); typeSource.type = matcher.group(1); typeSource.name = matcher.group(matcher.groupCount()); currents.add(typeSource); return true; } else { return false; } } @SuppressWarnings("unchecked") public static void deleteNodeByName(String path, String tag, String name) { try { SAXReader reader = new SAXReader(); Document document = reader.read(new File(path)); Element element = document.getRootElement(); List<Element> list = element.elements("dimen"); for (int i = 0; i < list.size(); i++) { Element ele = list.get(i); String tName = ele.attributeValue("name"); if (tName != null && tName.length() > 0) { if (name.equals(ele.attributeValue("name"))) { element.remove(ele); break; } } } OutputFormat format = new OutputFormat("", false);// XMLWriter xmlWriter = new XMLWriter(new FileWriter(path), format); xmlWriter.write(document); xmlWriter.flush(); } catch (Exception e1) { e1.printStackTrace(); } } public static void scanSourceFiles(File parentFile) { File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { scanSourceFiles(file); } else { AllFiles.add(file); } } } } static class TypeSource { String type = "";// 类型 String name = "";// xml中的name属性 String xmlTag = "";// xml的tag名 String path = "";// 属于哪个文件 public String getXmlTag() { if ("styleable".equals(type)) { return "declare-styleable"; } else { return type; } } @Override public String toString() { return type + " | " + name + " | " + xmlTag + " | " + path; } /** * 一个一个的单独删,要啥效率啊 */ public void cleanSelf() { try { if (type == null) { return; } if (type.equals("drawable") || type.equals("layout") || type.equals("anim")) { checkAndDeleteFile(); } else if (type.equals("color")) { if (pathMatchesWithType()) { new File(path).delete(); } else { deleteNodeByName(path, xmlTag, name); } } else if (type.equals("id") || type.equals("")) { // do nothing } else { deleteNodeByName(path, xmlTag, name); } } catch (Exception e) { } } public void checkAndDeleteFile() { if (pathMatchesWithType()) { new File(path).delete(); } else { //不放心的话可以跳过,不执行这一块,这种情况很少见,一般是过期的R文件导致 if (type.equals("drawable")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("drawable")) { file.delete(); } } } else if (type.equals("layout")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("layout")) { file.delete(); } } } else if (type.equals("anim")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("anim")) { file.delete(); } } } } } public boolean pathMatchesWithType() { boolean flag = false; File file = new File(path); File parentFile = file.getParentFile(); if (type.equals("drawable")) { flag = parentFile.getName().startsWith("drawable"); } else if (type.equals("layout")) { flag = parentFile.getName().startsWith("layout"); } else if (type.equals("anim")) { flag = parentFile.getName().startsWith("anim"); } else if (type.equals("color")) { flag = parentFile.getName().startsWith("color"); } return flag; } public TypeSource clone() { TypeSource ts = new TypeSource(); ts.type = type; ts.name = name; ts.xmlTag = xmlTag; ts.path = path; return ts; } } }
NashLegend/AndroidResourceCleaner
src/Main.java
2,163
/** * 一个一个的单独删,要啥效率啊 */
block_comment
zh-cn
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.dom4j.Document; import org.dom4j.Element; import org.dom4j.io.OutputFormat; import org.dom4j.io.SAXReader; import org.dom4j.io.XMLWriter; public class Main { public static void main(String[] args) { if (args.length > 0) { unusedCleaner(args[0]); } } static ArrayList<TypeSource> currents = new ArrayList<>(); static final ArrayList<File> AllFiles = new ArrayList<>(); static String encoding = "utf-8"; static boolean LastIsPath = false; public static void unusedCleaner(String filePath) { int crtLine = 0; ArrayList<TypeSource> files = new ArrayList<>(); try { File file = new File(filePath); if (file.isFile() && file.exists()) { InputStreamReader read = new InputStreamReader( new FileInputStream(file), encoding); BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; while ((lineTxt = bufferedReader.readLine()) != null) { if (crtLine == 0) { parsellFiles(lineTxt); } else { if (!parseType(lineTxt)) { String trim = lineTxt.trim(); if (new File(trim).exists()) { for (Iterator<TypeSource> iterator = currents .iterator(); iterator.hasNext();) { TypeSource typeSource = (TypeSource) iterator .next().clone(); typeSource.path = trim; typeSource.xmlTag = typeSource.getXmlTag(); files.add(typeSource); } LastIsPath = true; } } } crtLine++; } read.close(); } else { System.out.println("noFile"); } } catch (Exception e) { System.out.println("Failed"); e.printStackTrace(); } for (Iterator<TypeSource> iterator = files.iterator(); iterator .hasNext();) { TypeSource typeSource = (TypeSource) iterator.next(); System.out.println(typeSource); typeSource.cleanSelf(); } System.out.println("done"); } public static void parsellFiles(String line) { String reg = "Running in:\\s+(\\S+)"; Matcher matcher = Pattern.compile(reg).matcher(line); if (matcher.find()) { String path = matcher.group(1); File file = new File(path); scanSourceFiles(file); } } public static boolean parseType(String lineTxt) { // drawable/anim/layout/ String reg = "((drawable)|(anim)|(layout)|(dimen)|(string)|(attr)|(style)|(styleable)|(color)|(id))\\s*:\\s*(\\S+)"; Matcher matcher = Pattern.compile(reg).matcher(lineTxt); if (matcher.find()) { if (LastIsPath) { currents.clear(); } LastIsPath = false; TypeSource typeSource = new TypeSource(); typeSource.type = matcher.group(1); typeSource.name = matcher.group(matcher.groupCount()); currents.add(typeSource); return true; } else { return false; } } @SuppressWarnings("unchecked") public static void deleteNodeByName(String path, String tag, String name) { try { SAXReader reader = new SAXReader(); Document document = reader.read(new File(path)); Element element = document.getRootElement(); List<Element> list = element.elements("dimen"); for (int i = 0; i < list.size(); i++) { Element ele = list.get(i); String tName = ele.attributeValue("name"); if (tName != null && tName.length() > 0) { if (name.equals(ele.attributeValue("name"))) { element.remove(ele); break; } } } OutputFormat format = new OutputFormat("", false);// XMLWriter xmlWriter = new XMLWriter(new FileWriter(path), format); xmlWriter.write(document); xmlWriter.flush(); } catch (Exception e1) { e1.printStackTrace(); } } public static void scanSourceFiles(File parentFile) { File[] files = parentFile.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isDirectory()) { scanSourceFiles(file); } else { AllFiles.add(file); } } } } static class TypeSource { String type = "";// 类型 String name = "";// xml中的name属性 String xmlTag = "";// xml的tag名 String path = "";// 属于哪个文件 public String getXmlTag() { if ("styleable".equals(type)) { return "declare-styleable"; } else { return type; } } @Override public String toString() { return type + " | " + name + " | " + xmlTag + " | " + path; } /** * 一个一 <SUF>*/ public void cleanSelf() { try { if (type == null) { return; } if (type.equals("drawable") || type.equals("layout") || type.equals("anim")) { checkAndDeleteFile(); } else if (type.equals("color")) { if (pathMatchesWithType()) { new File(path).delete(); } else { deleteNodeByName(path, xmlTag, name); } } else if (type.equals("id") || type.equals("")) { // do nothing } else { deleteNodeByName(path, xmlTag, name); } } catch (Exception e) { } } public void checkAndDeleteFile() { if (pathMatchesWithType()) { new File(path).delete(); } else { //不放心的话可以跳过,不执行这一块,这种情况很少见,一般是过期的R文件导致 if (type.equals("drawable")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("drawable")) { file.delete(); } } } else if (type.equals("layout")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("layout")) { file.delete(); } } } else if (type.equals("anim")) { for (int i = 0; i < AllFiles.size(); i++) { File file = AllFiles.get(i); if (file.getName().equals(name + ".xml") && file.getParentFile().getName() .startsWith("anim")) { file.delete(); } } } } } public boolean pathMatchesWithType() { boolean flag = false; File file = new File(path); File parentFile = file.getParentFile(); if (type.equals("drawable")) { flag = parentFile.getName().startsWith("drawable"); } else if (type.equals("layout")) { flag = parentFile.getName().startsWith("layout"); } else if (type.equals("anim")) { flag = parentFile.getName().startsWith("anim"); } else if (type.equals("color")) { flag = parentFile.getName().startsWith("color"); } return flag; } public TypeSource clone() { TypeSource ts = new TypeSource(); ts.type = type; ts.name = name; ts.xmlTag = xmlTag; ts.path = path; return ts; } } }
false
1,802
17
2,163
19
2,126
17
2,163
19
2,909
32
false
false
false
false
false
true
33115_0
package net.nashlegend.legendutils.BuildIn; import java.util.ArrayList; import net.nashlegend.legendutils.Tools.DisplayUtil; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class WPLoading extends RelativeLayout { private int size = 10; private int delay = 300; private int duration = 3200; private String color = "#0000ff"; private AnimatorSet animatorSet = new AnimatorSet(); public WPLoading(Context context) { super(context); LayoutParams params0 = new LayoutParams( DisplayUtil.getScreenWidth(context), size); View view = new View(context); view.setLayoutParams(params0); addView(view); } public void startAnimate() { LayoutParams params = new LayoutParams(size, size); animatorSet = new AnimatorSet(); ArrayList<Animator> animators = new ArrayList<Animator>(); for (int i = 0; i < 5; i++) { View view = new View(getContext()); view.setBackgroundColor(Color.parseColor(color)); addView(view); view.setLayoutParams(params); view.setX(-size); ObjectAnimator headAnimator = ObjectAnimator.ofFloat(view, "x", view.getX(), DisplayUtil.getScreenWidth(getContext())); headAnimator.setDuration(duration); headAnimator .setInterpolator(new DecelerateAccelerateStopInterpolator()); headAnimator.setStartDelay(delay * i); headAnimator.setRepeatCount(-1); animators.add(headAnimator); } animatorSet.playTogether(animators); animatorSet.start(); } public WPLoading(Context context, AttributeSet attrs) { super(context, attrs); } public WPLoading(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void cancel() { animatorSet.end(); } // 先减速,再加速,再停止一会儿 class DecelerateAccelerateStopInterpolator implements android.view.animation.Interpolator { private float mFactor = 1.0f; private float tailFactor = 0.6f; public DecelerateAccelerateStopInterpolator() { } public DecelerateAccelerateStopInterpolator(float factor) { mFactor = factor; } public float getInterpolation(float x) { float result; if (x > tailFactor) { result = 1; } else if (x > tailFactor / 2) { result = (float) Math.pow( (x - tailFactor / 2) * 2 / tailFactor, 2 * mFactor) / 2 + 0.5f; } else { result = (float) (1.0f - Math.pow((tailFactor - 2 * x) / tailFactor, 2 * mFactor)) / 2; } return result; } } }
NashLegend/LegendUtils
src/net/nashlegend/legendutils/BuildIn/WPLoading.java
859
// 先减速,再加速,再停止一会儿
line_comment
zh-cn
package net.nashlegend.legendutils.BuildIn; import java.util.ArrayList; import net.nashlegend.legendutils.Tools.DisplayUtil; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.content.Context; import android.graphics.Color; import android.os.Build; import android.util.AttributeSet; import android.view.View; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class WPLoading extends RelativeLayout { private int size = 10; private int delay = 300; private int duration = 3200; private String color = "#0000ff"; private AnimatorSet animatorSet = new AnimatorSet(); public WPLoading(Context context) { super(context); LayoutParams params0 = new LayoutParams( DisplayUtil.getScreenWidth(context), size); View view = new View(context); view.setLayoutParams(params0); addView(view); } public void startAnimate() { LayoutParams params = new LayoutParams(size, size); animatorSet = new AnimatorSet(); ArrayList<Animator> animators = new ArrayList<Animator>(); for (int i = 0; i < 5; i++) { View view = new View(getContext()); view.setBackgroundColor(Color.parseColor(color)); addView(view); view.setLayoutParams(params); view.setX(-size); ObjectAnimator headAnimator = ObjectAnimator.ofFloat(view, "x", view.getX(), DisplayUtil.getScreenWidth(getContext())); headAnimator.setDuration(duration); headAnimator .setInterpolator(new DecelerateAccelerateStopInterpolator()); headAnimator.setStartDelay(delay * i); headAnimator.setRepeatCount(-1); animators.add(headAnimator); } animatorSet.playTogether(animators); animatorSet.start(); } public WPLoading(Context context, AttributeSet attrs) { super(context, attrs); } public WPLoading(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public void cancel() { animatorSet.end(); } // 先减 <SUF> class DecelerateAccelerateStopInterpolator implements android.view.animation.Interpolator { private float mFactor = 1.0f; private float tailFactor = 0.6f; public DecelerateAccelerateStopInterpolator() { } public DecelerateAccelerateStopInterpolator(float factor) { mFactor = factor; } public float getInterpolation(float x) { float result; if (x > tailFactor) { result = 1; } else if (x > tailFactor / 2) { result = (float) Math.pow( (x - tailFactor / 2) * 2 / tailFactor, 2 * mFactor) / 2 + 0.5f; } else { result = (float) (1.0f - Math.pow((tailFactor - 2 * x) / tailFactor, 2 * mFactor)) / 2; } return result; } } }
false
683
11
859
15
823
11
859
15
1,031
22
false
false
false
false
false
true
42550_3
package net.nashlegend.sourcewall.model; import android.os.Parcel; /** * Created by NashLegend on 2014/10/31 0031 */ public class SubItem extends AceModel { public static final int Type_Group = -1;//集合,如科学人、热贴、精彩问答、热门问答 public static final int Type_Collections = 0;//集合,如科学人、热贴、精彩问答、热门问答 public static final int Type_Single_Channel = 1;//单项 public static final int Type_Private_Channel = 2;//私人频道,我的小组 public static final int Type_Subject_Channel = 3;//科学人学科频道 public static final int Section_Article = 0; public static final int Section_Post = 1; public static final int Section_Question = 2; public static final int Section_Favor = 3; private int section;//分组 比如科学人、小组、问答 private int type;//类型,比如Type_Collections,Type_Single_Channel private String name = "";//名字 比如Geek笑点低 private String value = "";//id 比如63 public SubItem(int section, int type, String name, String value) { setSection(section); setType(type); setName(name); setValue(value); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getName() { if (name == null) { name = ""; } return name; } public void setName(String name) { this.name = name; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getSection() { return section; } public void setSection(int section) { this.section = section; } @Override public boolean equals(Object o) { if (o != null && o instanceof SubItem) { SubItem sb = (SubItem) o; return sb.getName().equals(getName()) && sb.getSection() == getSection() && sb.getType() == getType() && sb.getValue().equals(getValue()); } return false; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.section); dest.writeInt(this.type); dest.writeString(this.name); dest.writeString(this.value); } protected SubItem(Parcel in) { this.section = in.readInt(); this.type = in.readInt(); this.name = in.readString(); this.value = in.readString(); } public static final Creator<SubItem> CREATOR = new Creator<SubItem>() { @Override public SubItem createFromParcel(Parcel source) { return new SubItem(source); } @Override public SubItem[] newArray(int size) { return new SubItem[size]; } }; }
NashLegend/SourceWall
app/src/main/java/net/nashlegend/sourcewall/model/SubItem.java
753
//私人频道,我的小组
line_comment
zh-cn
package net.nashlegend.sourcewall.model; import android.os.Parcel; /** * Created by NashLegend on 2014/10/31 0031 */ public class SubItem extends AceModel { public static final int Type_Group = -1;//集合,如科学人、热贴、精彩问答、热门问答 public static final int Type_Collections = 0;//集合,如科学人、热贴、精彩问答、热门问答 public static final int Type_Single_Channel = 1;//单项 public static final int Type_Private_Channel = 2;//私人 <SUF> public static final int Type_Subject_Channel = 3;//科学人学科频道 public static final int Section_Article = 0; public static final int Section_Post = 1; public static final int Section_Question = 2; public static final int Section_Favor = 3; private int section;//分组 比如科学人、小组、问答 private int type;//类型,比如Type_Collections,Type_Single_Channel private String name = "";//名字 比如Geek笑点低 private String value = "";//id 比如63 public SubItem(int section, int type, String name, String value) { setSection(section); setType(type); setName(name); setValue(value); } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getName() { if (name == null) { name = ""; } return name; } public void setName(String name) { this.name = name; } public int getType() { return type; } public void setType(int type) { this.type = type; } public int getSection() { return section; } public void setSection(int section) { this.section = section; } @Override public boolean equals(Object o) { if (o != null && o instanceof SubItem) { SubItem sb = (SubItem) o; return sb.getName().equals(getName()) && sb.getSection() == getSection() && sb.getType() == getType() && sb.getValue().equals(getValue()); } return false; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(this.section); dest.writeInt(this.type); dest.writeString(this.name); dest.writeString(this.value); } protected SubItem(Parcel in) { this.section = in.readInt(); this.type = in.readInt(); this.name = in.readString(); this.value = in.readString(); } public static final Creator<SubItem> CREATOR = new Creator<SubItem>() { @Override public SubItem createFromParcel(Parcel source) { return new SubItem(source); } @Override public SubItem[] newArray(int size) { return new SubItem[size]; } }; }
false
674
6
753
9
802
6
753
9
932
14
false
false
false
false
false
true
36426_5
/** * */ package com.carryondown.app.util; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.amap.api.services.core.AMapException; public class ToastUtil { public static void show(Context context, String info) { Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } public static void show(Context context, int info) { Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } public static void showerror(Context context, int rCode){ try { switch (rCode) { //服务错误码 case 1001: throw new AMapException(AMapException.AMAP_SIGNATURE_ERROR); case 1002: throw new AMapException(AMapException.AMAP_INVALID_USER_KEY); case 1003: throw new AMapException(AMapException.AMAP_SERVICE_NOT_AVAILBALE); case 1004: throw new AMapException(AMapException.AMAP_DAILY_QUERY_OVER_LIMIT); case 1005: throw new AMapException(AMapException.AMAP_ACCESS_TOO_FREQUENT); case 1006: throw new AMapException(AMapException.AMAP_INVALID_USER_IP); case 1007: throw new AMapException(AMapException.AMAP_INVALID_USER_DOMAIN); case 1008: throw new AMapException(AMapException.AMAP_INVALID_USER_SCODE); case 1009: throw new AMapException(AMapException.AMAP_USERKEY_PLAT_NOMATCH); case 1010: throw new AMapException(AMapException.AMAP_IP_QUERY_OVER_LIMIT); case 1011: throw new AMapException(AMapException.AMAP_NOT_SUPPORT_HTTPS); case 1012: throw new AMapException(AMapException.AMAP_INSUFFICIENT_PRIVILEGES); case 1013: throw new AMapException(AMapException.AMAP_USER_KEY_RECYCLED); case 1100: throw new AMapException(AMapException.AMAP_ENGINE_RESPONSE_ERROR); case 1101: throw new AMapException(AMapException.AMAP_ENGINE_RESPONSE_DATA_ERROR); case 1102: throw new AMapException(AMapException.AMAP_ENGINE_CONNECT_TIMEOUT); case 1103: throw new AMapException(AMapException.AMAP_ENGINE_RETURN_TIMEOUT); case 1200: throw new AMapException(AMapException.AMAP_SERVICE_INVALID_PARAMS); case 1201: throw new AMapException(AMapException.AMAP_SERVICE_MISSING_REQUIRED_PARAMS); case 1202: throw new AMapException(AMapException.AMAP_SERVICE_ILLEGAL_REQUEST); case 1203: throw new AMapException(AMapException.AMAP_SERVICE_UNKNOWN_ERROR); //sdk返回错误 case 1800: throw new AMapException(AMapException.AMAP_CLIENT_ERRORCODE_MISSSING); case 1801: throw new AMapException(AMapException.AMAP_CLIENT_ERROR_PROTOCOL); case 1802: throw new AMapException(AMapException.AMAP_CLIENT_SOCKET_TIMEOUT_EXCEPTION); case 1803: throw new AMapException(AMapException.AMAP_CLIENT_URL_EXCEPTION); case 1804: throw new AMapException("网络异常,请检查您的网络是否连接"); // throw new AMapException(AMapException.AMAP_CLIENT_UNKNOWHOST_EXCEPTION); case 1806: throw new AMapException(AMapException.AMAP_CLIENT_NETWORK_EXCEPTION); case 1900: throw new AMapException(AMapException.AMAP_CLIENT_UNKNOWN_ERROR); case 1901: throw new AMapException(AMapException.AMAP_CLIENT_INVALID_PARAMETER); case 1902: throw new AMapException(AMapException.AMAP_CLIENT_IO_EXCEPTION); case 1903: throw new AMapException(AMapException.AMAP_CLIENT_NULLPOINT_EXCEPTION); //云图和附近错误码 case 2000: throw new AMapException(AMapException.AMAP_SERVICE_TABLEID_NOT_EXIST); case 2001: throw new AMapException(AMapException.AMAP_ID_NOT_EXIST); case 2002: throw new AMapException(AMapException.AMAP_SERVICE_MAINTENANCE); case 2003: throw new AMapException(AMapException.AMAP_ENGINE_TABLEID_NOT_EXIST); case 2100: throw new AMapException(AMapException.AMAP_NEARBY_INVALID_USERID); case 2101: throw new AMapException(AMapException.AMAP_NEARBY_KEY_NOT_BIND); case 2200: throw new AMapException(AMapException.AMAP_CLIENT_UPLOADAUTO_STARTED_ERROR); case 2201: throw new AMapException(AMapException.AMAP_CLIENT_USERID_ILLEGAL); case 2202: throw new AMapException(AMapException.AMAP_CLIENT_NEARBY_NULL_RESULT); case 2203: throw new AMapException(AMapException.AMAP_CLIENT_UPLOAD_TOO_FREQUENT); case 2204: throw new AMapException(AMapException.AMAP_CLIENT_UPLOAD_LOCATION_ERROR); //路径规划 case 3000: throw new AMapException(AMapException.AMAP_ROUTE_OUT_OF_SERVICE); case 3001: throw new AMapException(AMapException.AMAP_ROUTE_NO_ROADS_NEARBY); case 3002: throw new AMapException(AMapException.AMAP_ROUTE_FAIL); case 3003: throw new AMapException(AMapException.AMAP_OVER_DIRECTION_RANGE); //短传分享 case 4000: throw new AMapException(AMapException.AMAP_SHARE_LICENSE_IS_EXPIRED); case 4001: throw new AMapException(AMapException.AMAP_SHARE_FAILURE); default: Toast.makeText(context,"查询失败:"+rCode , Toast.LENGTH_LONG).show(); logError("查询失败", rCode); break; } } catch (Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); logError(e.getMessage(), rCode); } } private static void logError(String info, int errorCode) { print(LINE);//start print(" 错误信息 "); print(LINE);//title print(info); print("错误码: " + errorCode); print(" "); print("如果需要更多信息,请根据错误码到以下地址进行查询"); print(" http://lbs.amap.com/api/android-sdk/guide/map-tools/error-code/"); print("如若仍无法解决问题,请将全部log信息提交到工单系统,多谢合作"); print(LINE);//end } //log public static final String TAG = "AMAP_ERROR"; static final String LINE_CHAR="="; static final String BOARD_CHAR="|"; static final int LENGTH = 80; static String LINE; static{ StringBuilder sb = new StringBuilder(); for(int i = 0;i<LENGTH;i++){ sb .append(LINE_CHAR); } LINE = sb.toString(); } private static void printLog(String s){ if(s.length()<LENGTH-2){ StringBuilder sb = new StringBuilder(); sb.append(BOARD_CHAR).append(s); for(int i = 0 ;i <LENGTH-2-s.length();i++){ sb.append(" "); } sb.append(BOARD_CHAR); print(sb.toString()); }else{ String line = s.substring(0,LENGTH-2); print(BOARD_CHAR+line+BOARD_CHAR); printLog(s.substring(LENGTH-2)); } } private static void print(String s) { Log.i(TAG,s); } }
NativeMonkey/ofo
app/src/main/java/com/carryondown/app/util/ToastUtil.java
2,112
//短传分享
line_comment
zh-cn
/** * */ package com.carryondown.app.util; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.amap.api.services.core.AMapException; public class ToastUtil { public static void show(Context context, String info) { Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } public static void show(Context context, int info) { Toast.makeText(context, info, Toast.LENGTH_LONG).show(); } public static void showerror(Context context, int rCode){ try { switch (rCode) { //服务错误码 case 1001: throw new AMapException(AMapException.AMAP_SIGNATURE_ERROR); case 1002: throw new AMapException(AMapException.AMAP_INVALID_USER_KEY); case 1003: throw new AMapException(AMapException.AMAP_SERVICE_NOT_AVAILBALE); case 1004: throw new AMapException(AMapException.AMAP_DAILY_QUERY_OVER_LIMIT); case 1005: throw new AMapException(AMapException.AMAP_ACCESS_TOO_FREQUENT); case 1006: throw new AMapException(AMapException.AMAP_INVALID_USER_IP); case 1007: throw new AMapException(AMapException.AMAP_INVALID_USER_DOMAIN); case 1008: throw new AMapException(AMapException.AMAP_INVALID_USER_SCODE); case 1009: throw new AMapException(AMapException.AMAP_USERKEY_PLAT_NOMATCH); case 1010: throw new AMapException(AMapException.AMAP_IP_QUERY_OVER_LIMIT); case 1011: throw new AMapException(AMapException.AMAP_NOT_SUPPORT_HTTPS); case 1012: throw new AMapException(AMapException.AMAP_INSUFFICIENT_PRIVILEGES); case 1013: throw new AMapException(AMapException.AMAP_USER_KEY_RECYCLED); case 1100: throw new AMapException(AMapException.AMAP_ENGINE_RESPONSE_ERROR); case 1101: throw new AMapException(AMapException.AMAP_ENGINE_RESPONSE_DATA_ERROR); case 1102: throw new AMapException(AMapException.AMAP_ENGINE_CONNECT_TIMEOUT); case 1103: throw new AMapException(AMapException.AMAP_ENGINE_RETURN_TIMEOUT); case 1200: throw new AMapException(AMapException.AMAP_SERVICE_INVALID_PARAMS); case 1201: throw new AMapException(AMapException.AMAP_SERVICE_MISSING_REQUIRED_PARAMS); case 1202: throw new AMapException(AMapException.AMAP_SERVICE_ILLEGAL_REQUEST); case 1203: throw new AMapException(AMapException.AMAP_SERVICE_UNKNOWN_ERROR); //sdk返回错误 case 1800: throw new AMapException(AMapException.AMAP_CLIENT_ERRORCODE_MISSSING); case 1801: throw new AMapException(AMapException.AMAP_CLIENT_ERROR_PROTOCOL); case 1802: throw new AMapException(AMapException.AMAP_CLIENT_SOCKET_TIMEOUT_EXCEPTION); case 1803: throw new AMapException(AMapException.AMAP_CLIENT_URL_EXCEPTION); case 1804: throw new AMapException("网络异常,请检查您的网络是否连接"); // throw new AMapException(AMapException.AMAP_CLIENT_UNKNOWHOST_EXCEPTION); case 1806: throw new AMapException(AMapException.AMAP_CLIENT_NETWORK_EXCEPTION); case 1900: throw new AMapException(AMapException.AMAP_CLIENT_UNKNOWN_ERROR); case 1901: throw new AMapException(AMapException.AMAP_CLIENT_INVALID_PARAMETER); case 1902: throw new AMapException(AMapException.AMAP_CLIENT_IO_EXCEPTION); case 1903: throw new AMapException(AMapException.AMAP_CLIENT_NULLPOINT_EXCEPTION); //云图和附近错误码 case 2000: throw new AMapException(AMapException.AMAP_SERVICE_TABLEID_NOT_EXIST); case 2001: throw new AMapException(AMapException.AMAP_ID_NOT_EXIST); case 2002: throw new AMapException(AMapException.AMAP_SERVICE_MAINTENANCE); case 2003: throw new AMapException(AMapException.AMAP_ENGINE_TABLEID_NOT_EXIST); case 2100: throw new AMapException(AMapException.AMAP_NEARBY_INVALID_USERID); case 2101: throw new AMapException(AMapException.AMAP_NEARBY_KEY_NOT_BIND); case 2200: throw new AMapException(AMapException.AMAP_CLIENT_UPLOADAUTO_STARTED_ERROR); case 2201: throw new AMapException(AMapException.AMAP_CLIENT_USERID_ILLEGAL); case 2202: throw new AMapException(AMapException.AMAP_CLIENT_NEARBY_NULL_RESULT); case 2203: throw new AMapException(AMapException.AMAP_CLIENT_UPLOAD_TOO_FREQUENT); case 2204: throw new AMapException(AMapException.AMAP_CLIENT_UPLOAD_LOCATION_ERROR); //路径规划 case 3000: throw new AMapException(AMapException.AMAP_ROUTE_OUT_OF_SERVICE); case 3001: throw new AMapException(AMapException.AMAP_ROUTE_NO_ROADS_NEARBY); case 3002: throw new AMapException(AMapException.AMAP_ROUTE_FAIL); case 3003: throw new AMapException(AMapException.AMAP_OVER_DIRECTION_RANGE); //短传 <SUF> case 4000: throw new AMapException(AMapException.AMAP_SHARE_LICENSE_IS_EXPIRED); case 4001: throw new AMapException(AMapException.AMAP_SHARE_FAILURE); default: Toast.makeText(context,"查询失败:"+rCode , Toast.LENGTH_LONG).show(); logError("查询失败", rCode); break; } } catch (Exception e) { Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); logError(e.getMessage(), rCode); } } private static void logError(String info, int errorCode) { print(LINE);//start print(" 错误信息 "); print(LINE);//title print(info); print("错误码: " + errorCode); print(" "); print("如果需要更多信息,请根据错误码到以下地址进行查询"); print(" http://lbs.amap.com/api/android-sdk/guide/map-tools/error-code/"); print("如若仍无法解决问题,请将全部log信息提交到工单系统,多谢合作"); print(LINE);//end } //log public static final String TAG = "AMAP_ERROR"; static final String LINE_CHAR="="; static final String BOARD_CHAR="|"; static final int LENGTH = 80; static String LINE; static{ StringBuilder sb = new StringBuilder(); for(int i = 0;i<LENGTH;i++){ sb .append(LINE_CHAR); } LINE = sb.toString(); } private static void printLog(String s){ if(s.length()<LENGTH-2){ StringBuilder sb = new StringBuilder(); sb.append(BOARD_CHAR).append(s); for(int i = 0 ;i <LENGTH-2-s.length();i++){ sb.append(" "); } sb.append(BOARD_CHAR); print(sb.toString()); }else{ String line = s.substring(0,LENGTH-2); print(BOARD_CHAR+line+BOARD_CHAR); printLog(s.substring(LENGTH-2)); } } private static void print(String s) { Log.i(TAG,s); } }
false
1,788
4
2,112
4
2,263
4
2,112
4
2,565
9
false
false
false
false
false
true
10201_0
package com.design.structural.decorator; /** * 你眼中的女神 */ public class YourGirl extends AbstractGirl { @Override protected String feature() { return "是一个女生"; } @Override protected String getDesc() { return "漂亮"; } }
NealLemon/design_patterns
src/main/java/com/design/structural/decorator/YourGirl.java
73
/** * 你眼中的女神 */
block_comment
zh-cn
package com.design.structural.decorator; /** * 你眼中 <SUF>*/ public class YourGirl extends AbstractGirl { @Override protected String feature() { return "是一个女生"; } @Override protected String getDesc() { return "漂亮"; } }
false
62
9
73
11
73
9
73
11
94
14
false
false
false
false
false
true
51169_1
/** * -*- coding: utf-8 -*- * * @Time : 2021/3/14 23:30 * @Author : NekoSilverfox * @FileName: template * @Software: IntelliJ IDEA * @Versions: v0.1 * @Github :https://github.com/NekoSilverFox */ import java.util.ArrayList; import java.util.Iterator; public class template { public static void main(String[] args) { show02(); } /* 创建集合对象,使用泛型 好处: 1.避免了类型转换的麻烦,存储的是什么类型,取出的就是什么类型 2.把运行期异常(代码运行之后会抛出的异常),提升到了编译期(写代码的时候会报错) 弊端: 泛型是什么类型,只能存储什么类型的数据 */ private static void show02() { ArrayList<String> list = new ArrayList<>(); list.add("abc"); //list.add(1);//add(java.lang.String)in ArrayList cannot be applied to (int) //使用迭代器遍历list集合 Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s + "->" + s.length()); } } /* 创建集合对象,不使用泛型 好处: 集合不使用泛型,默认的类型就是Object类型,【可以存储任意类型的数据】 弊端: 不安全,会引发异常 */ private static void show01() { ArrayList list = new ArrayList(); list.add("abc"); list.add(1); //使用迭代器遍历list集合 //获取迭代器 Iterator it = list.iterator(); //使用迭代器中的方法hasNext和next遍历集合 while (it.hasNext()) { //取出元素也是Object类型 Object obj = it.next(); System.out.println(obj); //想要使用String类特有的方法,length获取字符串的长度;不能使用 多态 Object obj = "abc"; //需要向下转型 //会抛出ClassCastException类型转换异常,不能把Integer类型转换为String类型 String s = (String) obj; System.out.println(s.length()); } } }
NekoSilverFox/Java
190 - OOP_泛型编程/src/template.java
551
/* 创建集合对象,使用泛型 好处: 1.避免了类型转换的麻烦,存储的是什么类型,取出的就是什么类型 2.把运行期异常(代码运行之后会抛出的异常),提升到了编译期(写代码的时候会报错) 弊端: 泛型是什么类型,只能存储什么类型的数据 */
block_comment
zh-cn
/** * -*- coding: utf-8 -*- * * @Time : 2021/3/14 23:30 * @Author : NekoSilverfox * @FileName: template * @Software: IntelliJ IDEA * @Versions: v0.1 * @Github :https://github.com/NekoSilverFox */ import java.util.ArrayList; import java.util.Iterator; public class template { public static void main(String[] args) { show02(); } /* 创建集 <SUF>*/ private static void show02() { ArrayList<String> list = new ArrayList<>(); list.add("abc"); //list.add(1);//add(java.lang.String)in ArrayList cannot be applied to (int) //使用迭代器遍历list集合 Iterator<String> it = list.iterator(); while (it.hasNext()) { String s = it.next(); System.out.println(s + "->" + s.length()); } } /* 创建集合对象,不使用泛型 好处: 集合不使用泛型,默认的类型就是Object类型,【可以存储任意类型的数据】 弊端: 不安全,会引发异常 */ private static void show01() { ArrayList list = new ArrayList(); list.add("abc"); list.add(1); //使用迭代器遍历list集合 //获取迭代器 Iterator it = list.iterator(); //使用迭代器中的方法hasNext和next遍历集合 while (it.hasNext()) { //取出元素也是Object类型 Object obj = it.next(); System.out.println(obj); //想要使用String类特有的方法,length获取字符串的长度;不能使用 多态 Object obj = "abc"; //需要向下转型 //会抛出ClassCastException类型转换异常,不能把Integer类型转换为String类型 String s = (String) obj; System.out.println(s.length()); } } }
false
516
88
551
86
572
83
551
86
785
163
false
false
false
false
false
true
59127_5
package Reader; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.library.DicLibrary; import org.ansj.splitWord.analysis.DicAnalysis; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import javax.security.auth.login.AppConfigurationEntry; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; public class NovelRead { public static class ReaderMapper extends Mapper<LongWritable, Text, TextPair, IntWritable> { @Override protected void setup(Context context) throws IOException, InterruptedException { /** * 读取用户自定义字典 */ Configuration conf = context.getConfiguration(); String nameFile = context.getConfiguration().get("nameFile"); // System.out.print("--------" + nameFile); /*BufferedReader in = new BufferedReader(new InputStreamReader(FileSystem.get(context.getConfiguration()).open(new Path(nameFile)))); */ // StringBuffer buffer = new StringBuffer(); FileSystem fs = FileSystem.get(URI.create(nameFile), conf); FSDataInputStream fsr = fs.open(new Path(nameFile)); BufferedReader in = new BufferedReader(new InputStreamReader(fsr)); String name; while ((name = in.readLine()) != null) { DicLibrary.insert(DicLibrary.DEFAULT, name); } fsr.close(); in.close(); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { /** * key : offset * value : 一行文件内容 * * 读取小说内容,分词得到小说人物姓名,传出任意姓名对 * * key : <name1,name2> * value : 1 * **/ String data = value.toString(); Result res = DicAnalysis.parse(data); // 得到分词结果 List<Term> terms = res.getTerms(); List<String> nameList = new ArrayList<String>(); // 提取分词内容中的姓名 for (int i = 0; i < terms.size(); i++) { String word = terms.get(i).toString(); String wordNature = terms.get(i).getNatureStr(); if (wordNature.equals(DicLibrary.DEFAULT_NATURE)) { // 存储符合用户自定义词典中的内容 String name = word.substring(0, word.length()-11); if (name.equals("哈利波特") || name.equals("哈利·波特")) name = "哈利"; else if (name.equals("赫敏·简·格兰杰") || name.equals("赫敏·格兰杰") || name.equals("赫敏格兰杰")) name = "赫敏"; else if (name.equals("罗恩·比利尔斯·韦斯莱")) name = "罗恩"; nameList.add(name); } } // 两两不相同姓名对之间进行统计 int length = nameList.size(); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (!(nameList.get(i).equals(nameList.get(j)))) context.write(new TextPair(nameList.get(i), nameList.get(j)), new IntWritable(1)); } } } } public static class ReaderCombiner extends Reducer<TextPair, IntWritable, TextPair, IntWritable> { protected void reduce(TextPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { /** * 合并重复姓名对 * **/ int cnt = 0; for (IntWritable num : values) { cnt += num.get(); } context.write(key, new IntWritable(cnt)); } } public static class ReaderReducer extends Reducer<TextPair, IntWritable, Text, NullWritable> { protected void reduce(TextPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { /** * key : <name1,name2> * values : times1,times2,... * * 统计同一个姓名对总共出现次数 * * key : name1,name2,times * value : null * **/ int cnt = 0; for (IntWritable num : values) { cnt += num.get(); } context.write(new Text(key.toString() + "," + Integer.toString(cnt)), NullWritable.get()); } } }
NellyZhou/HadoopLab
CODE/src/main/java/Reader/NovelRead.java
1,227
// 得到分词结果
line_comment
zh-cn
package Reader; import org.ansj.domain.Result; import org.ansj.domain.Term; import org.ansj.library.DicLibrary; import org.ansj.splitWord.analysis.DicAnalysis; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import javax.security.auth.login.AppConfigurationEntry; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; public class NovelRead { public static class ReaderMapper extends Mapper<LongWritable, Text, TextPair, IntWritable> { @Override protected void setup(Context context) throws IOException, InterruptedException { /** * 读取用户自定义字典 */ Configuration conf = context.getConfiguration(); String nameFile = context.getConfiguration().get("nameFile"); // System.out.print("--------" + nameFile); /*BufferedReader in = new BufferedReader(new InputStreamReader(FileSystem.get(context.getConfiguration()).open(new Path(nameFile)))); */ // StringBuffer buffer = new StringBuffer(); FileSystem fs = FileSystem.get(URI.create(nameFile), conf); FSDataInputStream fsr = fs.open(new Path(nameFile)); BufferedReader in = new BufferedReader(new InputStreamReader(fsr)); String name; while ((name = in.readLine()) != null) { DicLibrary.insert(DicLibrary.DEFAULT, name); } fsr.close(); in.close(); } @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { /** * key : offset * value : 一行文件内容 * * 读取小说内容,分词得到小说人物姓名,传出任意姓名对 * * key : <name1,name2> * value : 1 * **/ String data = value.toString(); Result res = DicAnalysis.parse(data); // 得到 <SUF> List<Term> terms = res.getTerms(); List<String> nameList = new ArrayList<String>(); // 提取分词内容中的姓名 for (int i = 0; i < terms.size(); i++) { String word = terms.get(i).toString(); String wordNature = terms.get(i).getNatureStr(); if (wordNature.equals(DicLibrary.DEFAULT_NATURE)) { // 存储符合用户自定义词典中的内容 String name = word.substring(0, word.length()-11); if (name.equals("哈利波特") || name.equals("哈利·波特")) name = "哈利"; else if (name.equals("赫敏·简·格兰杰") || name.equals("赫敏·格兰杰") || name.equals("赫敏格兰杰")) name = "赫敏"; else if (name.equals("罗恩·比利尔斯·韦斯莱")) name = "罗恩"; nameList.add(name); } } // 两两不相同姓名对之间进行统计 int length = nameList.size(); for (int i = 0; i < length; i++) { for (int j = 0; j < length; j++) { if (!(nameList.get(i).equals(nameList.get(j)))) context.write(new TextPair(nameList.get(i), nameList.get(j)), new IntWritable(1)); } } } } public static class ReaderCombiner extends Reducer<TextPair, IntWritable, TextPair, IntWritable> { protected void reduce(TextPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { /** * 合并重复姓名对 * **/ int cnt = 0; for (IntWritable num : values) { cnt += num.get(); } context.write(key, new IntWritable(cnt)); } } public static class ReaderReducer extends Reducer<TextPair, IntWritable, Text, NullWritable> { protected void reduce(TextPair key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { /** * key : <name1,name2> * values : times1,times2,... * * 统计同一个姓名对总共出现次数 * * key : name1,name2,times * value : null * **/ int cnt = 0; for (IntWritable num : values) { cnt += num.get(); } context.write(new Text(key.toString() + "," + Integer.toString(cnt)), NullWritable.get()); } } }
false
1,041
7
1,227
6
1,277
5
1,227
6
1,529
10
false
false
false
false
false
true
37480_2
public class Solution885 { public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { int size = rows * cols; int x = rStart, y = cStart; // 返回的二维矩阵 int[][] matrix = new int[size][2]; // 传入的参数就是入口第一个 matrix[0][0] = rStart; matrix[0][1] = cStart; // 作为数量 int z = 1; // 步进,1,1,2,2,3,3,4 ... 螺旋矩阵的增长 int a = 1; // 方向 1 表示右,2 表示下,3 表示左,4 表示上 int dir = 1; while (z < size) { for (int i = 0; i < 2; i++) { for (int j = 0; j < a; j++) { // 处理方向 if (dir % 4 == 1) { y++; } else if (dir % 4 == 2) { x++; } else if (dir % 4 == 3) { y--; } else { x--; } // 如果在实际矩阵内 if (x < rows && y < cols && x >= 0 && y >= 0) { matrix[z][0] = x; matrix[z][1] = y; z++; } } // 转变方向 dir++; } // 步进++ a++; } return matrix; } }
Nicksxs/Nicksxs.github.io
code/Solution885.java
367
// 作为数量
line_comment
zh-cn
public class Solution885 { public int[][] spiralMatrixIII(int rows, int cols, int rStart, int cStart) { int size = rows * cols; int x = rStart, y = cStart; // 返回的二维矩阵 int[][] matrix = new int[size][2]; // 传入的参数就是入口第一个 matrix[0][0] = rStart; matrix[0][1] = cStart; // 作为 <SUF> int z = 1; // 步进,1,1,2,2,3,3,4 ... 螺旋矩阵的增长 int a = 1; // 方向 1 表示右,2 表示下,3 表示左,4 表示上 int dir = 1; while (z < size) { for (int i = 0; i < 2; i++) { for (int j = 0; j < a; j++) { // 处理方向 if (dir % 4 == 1) { y++; } else if (dir % 4 == 2) { x++; } else if (dir % 4 == 3) { y--; } else { x--; } // 如果在实际矩阵内 if (x < rows && y < cols && x >= 0 && y >= 0) { matrix[z][0] = x; matrix[z][1] = y; z++; } } // 转变方向 dir++; } // 步进++ a++; } return matrix; } }
false
375
4
367
4
398
4
367
4
466
6
false
false
false
false
false
true
38356_0
/* * 分支结构1: if-else条件判断结构 * * 1.格式 * if(条件表达式){ * 语句块; * } * * 2.格式2 * if(条件表达式){ * 语句块1; * }else { * 语句块2; * } * * 3. 格式3 * if(条件表达式1){ * 语句块1; * }else if(条件表达式2){ * 语句块2; * } else { * 语句块n+1; * } * * TODO: * 1.如果多个条件表达式之间没有交集(理解是互斥关系),则哪个条件表达式声明在上面,哪个条件表达式在下面都可以 * 2.如果多个条件表达式之间是包含关系,则需要将范围小的条件表达式声明在范围大的条件表达式上面。否则范围小的条件表达式不会被执行 * 3.从开发经验来说,没有写过超过三层的if-else结构 * 4. 如果if-else中的执行语句块中只有一行执行语句,则此执行语句所在的一对{}可以省略,但是不建议省略 * * * */ public class c1 { } class IfElseTest{ public static void main(String[] args){ int heartBeats = 89; if (60 >= heartBeats && heartBeats > 100){ System.out.println("More check "); } System.out.println("Finish"); } } class NumberTest{ public static void main(String[] args){ int num = 11; if (num%2==0){ System.out.println("Yes"); }else { System.out.println("No"); } } } class IfElseIfTest{ public static void main(String[] args){ int grade = 80; if(grade==100){ System.out.println("race car"); } else if (grade>80 && grade<=99) { System.out.println("bike"); } else if (grade>=60 && grade <=80) { System.out.println("playground"); } else { System.out.println("nothing"); } } }
Niki9001/Java-Study-charpter2
src/c1.java
551
/* * 分支结构1: if-else条件判断结构 * * 1.格式 * if(条件表达式){ * 语句块; * } * * 2.格式2 * if(条件表达式){ * 语句块1; * }else { * 语句块2; * } * * 3. 格式3 * if(条件表达式1){ * 语句块1; * }else if(条件表达式2){ * 语句块2; * } else { * 语句块n+1; * } * * TODO: * 1.如果多个条件表达式之间没有交集(理解是互斥关系),则哪个条件表达式声明在上面,哪个条件表达式在下面都可以 * 2.如果多个条件表达式之间是包含关系,则需要将范围小的条件表达式声明在范围大的条件表达式上面。否则范围小的条件表达式不会被执行 * 3.从开发经验来说,没有写过超过三层的if-else结构 * 4. 如果if-else中的执行语句块中只有一行执行语句,则此执行语句所在的一对{}可以省略,但是不建议省略 * * * */
block_comment
zh-cn
/* * 分支结 <SUF>*/ public class c1 { } class IfElseTest{ public static void main(String[] args){ int heartBeats = 89; if (60 >= heartBeats && heartBeats > 100){ System.out.println("More check "); } System.out.println("Finish"); } } class NumberTest{ public static void main(String[] args){ int num = 11; if (num%2==0){ System.out.println("Yes"); }else { System.out.println("No"); } } } class IfElseIfTest{ public static void main(String[] args){ int grade = 80; if(grade==100){ System.out.println("race car"); } else if (grade>80 && grade<=99) { System.out.println("bike"); } else if (grade>=60 && grade <=80) { System.out.println("playground"); } else { System.out.println("nothing"); } } }
false
513
288
551
295
552
277
551
295
745
459
true
true
true
true
true
false
35688_29
//在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。 // // 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。 // // 如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。 // // 说明: // // // 如果题目有解,该答案即为唯一答案。 // 输入数组均为非空数组,且长度相同。 // 输入数组中的元素均为非负数。 // // // 示例 1: // // 输入: //gas = [1,2,3,4,5] //cost = [3,4,5,1,2] // //输出: 3 // //解释: //从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油 //开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油 //开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油 //开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油 //开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油 //开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。 //因此,3 可为起始索引。 // // 示例 2: // // 输入: //gas = [2,3,4] //cost = [3,4,3] // //输出: -1 // //解释: //你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。 //我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油 //开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油 //开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油 //你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。 //因此,无论怎样,你都不可能绕环路行驶一周。 // Related Topics 贪心算法 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { // 解题思路大概是遍历一遍数组,设定两个变量 // 第一个变量是总油量,如果总油量加起来还不够cost的,就宣布失败,返回-1 // 如果没失败,说明必有一个点是开始点 int total = 0; int cur = 0; int start = 0; for(int i = 0; i < gas.length; i++){ total += gas[i] - cost[i]; cur += gas[i] - cost[i]; if(cur < 0){ // 如果当前邮箱已经坚持不下去了,就从下一个节点处开始 cur = 0; start = i + 1; } } return total >= 0 ? start : -1; } } //leetcode submit region end(Prohibit modification and deletion)
Noahhhhha/leetcode
src/problem/greedy/[134]加油站.java
1,056
//开往 1 号加油站,此时油箱有 3 - 3 + 3 = 3 升汽油
line_comment
zh-cn
//在一条环路上有 N 个加油站,其中第 i 个加油站有汽油 gas[i] 升。 // // 你有一辆油箱容量无限的的汽车,从第 i 个加油站开往第 i+1 个加油站需要消耗汽油 cost[i] 升。你从其中的一个加油站出发,开始时油箱为空。 // // 如果你可以绕环路行驶一周,则返回出发时加油站的编号,否则返回 -1。 // // 说明: // // // 如果题目有解,该答案即为唯一答案。 // 输入数组均为非空数组,且长度相同。 // 输入数组中的元素均为非负数。 // // // 示例 1: // // 输入: //gas = [1,2,3,4,5] //cost = [3,4,5,1,2] // //输出: 3 // //解释: //从 3 号加油站(索引为 3 处)出发,可获得 4 升汽油。此时油箱有 = 0 + 4 = 4 升汽油 //开往 4 号加油站,此时油箱有 4 - 1 + 5 = 8 升汽油 //开往 0 号加油站,此时油箱有 8 - 2 + 1 = 7 升汽油 //开往 1 号加油站,此时油箱有 7 - 3 + 2 = 6 升汽油 //开往 2 号加油站,此时油箱有 6 - 4 + 3 = 5 升汽油 //开往 3 号加油站,你需要消耗 5 升汽油,正好足够你返回到 3 号加油站。 //因此,3 可为起始索引。 // // 示例 2: // // 输入: //gas = [2,3,4] //cost = [3,4,3] // //输出: -1 // //解释: //你不能从 0 号或 1 号加油站出发,因为没有足够的汽油可以让你行驶到下一个加油站。 //我们从 2 号加油站出发,可以获得 4 升汽油。 此时油箱有 = 0 + 4 = 4 升汽油 //开往 0 号加油站,此时油箱有 4 - 3 + 2 = 3 升汽油 //开往 <SUF> //你无法返回 2 号加油站,因为返程需要消耗 4 升汽油,但是你的油箱只有 3 升汽油。 //因此,无论怎样,你都不可能绕环路行驶一周。 // Related Topics 贪心算法 //leetcode submit region begin(Prohibit modification and deletion) class Solution { public int canCompleteCircuit(int[] gas, int[] cost) { // 解题思路大概是遍历一遍数组,设定两个变量 // 第一个变量是总油量,如果总油量加起来还不够cost的,就宣布失败,返回-1 // 如果没失败,说明必有一个点是开始点 int total = 0; int cur = 0; int start = 0; for(int i = 0; i < gas.length; i++){ total += gas[i] - cost[i]; cur += gas[i] - cost[i]; if(cur < 0){ // 如果当前邮箱已经坚持不下去了,就从下一个节点处开始 cur = 0; start = i + 1; } } return total >= 0 ? start : -1; } } //leetcode submit region end(Prohibit modification and deletion)
false
831
27
1,056
35
892
27
1,056
35
1,389
45
false
false
false
false
false
true