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
64189_9
package xu.problem.mc; import java.util.ArrayList; import core.problem.Action; import core.problem.Problem; import core.problem.State; public class McProblem extends Problem { @Override public State result(State parent, Action action) { int m = ((McState) parent).getM(); int c = ((McState) parent).getC(); int m1 = ((McAction) action).getM(); int c1 = ((McAction) action).getC(); int d = ((McAction) action).getD(); if (d == 1) { //从左岸划到右岸 return new McState(m - m1, c - c1, 0).setSize(size); //左岸人数减少,船到了右岸 } else { //从右岸划到左岸 return new McState(m + m1, c + c1, 1).setSize(size); //左岸人数增多,船到了左岸 } } @Override public int stepCost(State parent, Action action) { // TODO Auto-generated method stub return 1; } @Override public int heuristic(State state) { // TODO Auto-generated method stub McState s = (McState) state; return s.heuristic(); } //左右岸,船上的任意情况下,传教士野人个数分别为m和c时,是否安全 private boolean isSafe(int m, int c) { return m == 0 || m >= c; } @Override public ArrayList<Action> Actions(State state) { // TODO Auto-generated method stub ArrayList<Action> actions = new ArrayList<>(); int m = ((McState) state).getM(); int c = ((McState) state).getC(); int b = ((McState) state).getB(); //在左岸还是右岸? //如果船在右岸,计算出右岸的人数 if (b == 0) { m = size - m; c = size - c; } for (int i = 0; i <= m; i++) for (int j = 0; j <= c; j++) { if (i + j > 0 && i + j <= k && isSafe(i, j) && isSafe(m - i, c - j) && isSafe(size - m + i, size - c + j)) { McAction action = new McAction(i, j, b); //划船方向,从所在岸划向对岸 actions.add(action); } } return actions; } //帮助自己检查是否正确的复写了父类中已有的方法 //告诉读代码的人,这是一个复写的方法 @Override public void drawWorld() { // TODO Auto-generated method stub this.getInitialState().draw(); } @Override public void simulateResult(State parent, Action action) { // TODO Auto-generated method stub State child = result(parent, action); action.draw(); child.draw(); } public McProblem(McState initialState, McState goal, int size, int k) { super(initialState, goal); this.size = size; this.k = k; } public McProblem(int size, int k) { super(new McState(size, size, 1).setSize(size), new McState(0, 0, 0).setSize(size)); this.size = size; this.k = k; } private int size; //传教士和野人的个数,问题的规模 private int k; //船上可载人数的上限 @Override public boolean solvable() { // TODO Auto-generated method stub return true; } }
Du-Sen-Lin/AI
Searching_student/src/xu/problem/mc/McProblem.java
984
//如果船在右岸,计算出右岸的人数
line_comment
zh-cn
package xu.problem.mc; import java.util.ArrayList; import core.problem.Action; import core.problem.Problem; import core.problem.State; public class McProblem extends Problem { @Override public State result(State parent, Action action) { int m = ((McState) parent).getM(); int c = ((McState) parent).getC(); int m1 = ((McAction) action).getM(); int c1 = ((McAction) action).getC(); int d = ((McAction) action).getD(); if (d == 1) { //从左岸划到右岸 return new McState(m - m1, c - c1, 0).setSize(size); //左岸人数减少,船到了右岸 } else { //从右岸划到左岸 return new McState(m + m1, c + c1, 1).setSize(size); //左岸人数增多,船到了左岸 } } @Override public int stepCost(State parent, Action action) { // TODO Auto-generated method stub return 1; } @Override public int heuristic(State state) { // TODO Auto-generated method stub McState s = (McState) state; return s.heuristic(); } //左右岸,船上的任意情况下,传教士野人个数分别为m和c时,是否安全 private boolean isSafe(int m, int c) { return m == 0 || m >= c; } @Override public ArrayList<Action> Actions(State state) { // TODO Auto-generated method stub ArrayList<Action> actions = new ArrayList<>(); int m = ((McState) state).getM(); int c = ((McState) state).getC(); int b = ((McState) state).getB(); //在左岸还是右岸? //如果 <SUF> if (b == 0) { m = size - m; c = size - c; } for (int i = 0; i <= m; i++) for (int j = 0; j <= c; j++) { if (i + j > 0 && i + j <= k && isSafe(i, j) && isSafe(m - i, c - j) && isSafe(size - m + i, size - c + j)) { McAction action = new McAction(i, j, b); //划船方向,从所在岸划向对岸 actions.add(action); } } return actions; } //帮助自己检查是否正确的复写了父类中已有的方法 //告诉读代码的人,这是一个复写的方法 @Override public void drawWorld() { // TODO Auto-generated method stub this.getInitialState().draw(); } @Override public void simulateResult(State parent, Action action) { // TODO Auto-generated method stub State child = result(parent, action); action.draw(); child.draw(); } public McProblem(McState initialState, McState goal, int size, int k) { super(initialState, goal); this.size = size; this.k = k; } public McProblem(int size, int k) { super(new McState(size, size, 1).setSize(size), new McState(0, 0, 0).setSize(size)); this.size = size; this.k = k; } private int size; //传教士和野人的个数,问题的规模 private int k; //船上可载人数的上限 @Override public boolean solvable() { // TODO Auto-generated method stub return true; } }
false
844
13
983
16
971
13
984
16
1,209
22
false
false
false
false
false
true
669_2
package cn.itcast_03; import java.util.ArrayList; import java.util.Collections; /* * 模拟斗地主洗牌和发牌 * * 扑克牌:54 * 小王 * 大王 * 黑桃A,黑桃2,黑桃3,黑桃4,黑桃...,黑桃10,黑桃J,黑桃Q,黑桃K * 红桃... * 梅花... * 方块... * * 分析: * A:造一个牌盒(集合) * B:造每一张牌,然后存储到牌盒里面去 * C:洗牌 * D:发牌 * E:看牌 */ public class PokerDemo { public static void main(String[] args) { // 造一个牌盒(集合) ArrayList<String> array = new ArrayList<String>(); // 造每一张牌,然后存储到牌盒里面去 // 定义花色数组 String[] colors = { "♠", "♥", "♣", "♦" }; // 定义点数数组 String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" }; for (String color : colors) { for (String number : numbers) { array.add(color.concat(number)); } } array.add("小王"); array.add("大王"); // 看牌 // System.out.println(array); // 洗牌 Collections.shuffle(array); // 发牌 // 三个选手 ArrayList<String> linQingXia = new ArrayList<String>(); ArrayList<String> fengQingYang = new ArrayList<String>(); ArrayList<String> liuYi = new ArrayList<String>(); // 底牌 ArrayList<String> diPai = new ArrayList<String>(); for (int x = 0; x < array.size(); x++) { if (x >= array.size() - 3) { diPai.add(array.get(x)); } else if (x % 3 == 0) { linQingXia.add(array.get(x)); } else if (x % 3 == 1) { fengQingYang.add(array.get(x)); } else if (x % 3 == 2) { liuYi.add(array.get(x)); } } // 看牌 lookPoker("林青霞", linQingXia); lookPoker("风清扬", fengQingYang); lookPoker("刘意", liuYi); lookPoker("底牌", diPai); } // 写一个功能实现遍历 public static void lookPoker(String name, ArrayList<String> array) { System.out.print(name + "的牌是:"); for (String s : array) { System.out.print(s + " "); } System.out.println(); } }
DuGuQiuBai/Java
day18/code/day18_Collections/src/cn/itcast_03/PokerDemo.java
813
// 造每一张牌,然后存储到牌盒里面去
line_comment
zh-cn
package cn.itcast_03; import java.util.ArrayList; import java.util.Collections; /* * 模拟斗地主洗牌和发牌 * * 扑克牌:54 * 小王 * 大王 * 黑桃A,黑桃2,黑桃3,黑桃4,黑桃...,黑桃10,黑桃J,黑桃Q,黑桃K * 红桃... * 梅花... * 方块... * * 分析: * A:造一个牌盒(集合) * B:造每一张牌,然后存储到牌盒里面去 * C:洗牌 * D:发牌 * E:看牌 */ public class PokerDemo { public static void main(String[] args) { // 造一个牌盒(集合) ArrayList<String> array = new ArrayList<String>(); // 造每 <SUF> // 定义花色数组 String[] colors = { "♠", "♥", "♣", "♦" }; // 定义点数数组 String[] numbers = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" }; for (String color : colors) { for (String number : numbers) { array.add(color.concat(number)); } } array.add("小王"); array.add("大王"); // 看牌 // System.out.println(array); // 洗牌 Collections.shuffle(array); // 发牌 // 三个选手 ArrayList<String> linQingXia = new ArrayList<String>(); ArrayList<String> fengQingYang = new ArrayList<String>(); ArrayList<String> liuYi = new ArrayList<String>(); // 底牌 ArrayList<String> diPai = new ArrayList<String>(); for (int x = 0; x < array.size(); x++) { if (x >= array.size() - 3) { diPai.add(array.get(x)); } else if (x % 3 == 0) { linQingXia.add(array.get(x)); } else if (x % 3 == 1) { fengQingYang.add(array.get(x)); } else if (x % 3 == 2) { liuYi.add(array.get(x)); } } // 看牌 lookPoker("林青霞", linQingXia); lookPoker("风清扬", fengQingYang); lookPoker("刘意", liuYi); lookPoker("底牌", diPai); } // 写一个功能实现遍历 public static void lookPoker(String name, ArrayList<String> array) { System.out.print(name + "的牌是:"); for (String s : array) { System.out.print(s + " "); } System.out.println(); } }
false
710
14
813
16
747
13
813
16
1,025
26
false
false
false
false
false
true
51009_11
package com.duan.musicoco.modle; import android.provider.MediaStore; /** * Created by DuanJiaNing on 2017/5/24. */ final public class SongInfo implements MediaStore.Audio.AudioColumns { //用于搜索、排序、分类 private String title_key; private String artist_key; private String album_key; private int id; //时间 ms private long duration; //艺术家 private String artist; //所属专辑 private String album; //专辑 ID private String album_id; //专辑图片路径 private String album_path; //专辑录制时间 private long year; //磁盘上的保存路径 //与服务端的 path 域对应,对于同一首歌曲(文件路径相同),两者应该相同 private String data; //文件大小 bytes private long size; //显示的名字 private String display_name; //内容标题 private String title; //文件被加入媒体库的时间 private long date_added; //文件最后修改时间 private long date_modified; //MIME type private String mime_type; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SongInfo songInfo = (SongInfo) o; return data.equals(songInfo.data); } @Override public int hashCode() { return data.hashCode(); } public void setAlbum_id(String album_id) { this.album_id = album_id; } public void setAlbum_path(String album_path) { this.album_path = album_path; } public void setTitle_key(String title_key) { this.title_key = title_key; } public void setArtist_key(String artist_key) { this.artist_key = artist_key; } public void setAlbum_key(String album_key) { this.album_key = album_key; } public void setArtist(String artist) { this.artist = artist; } public void setAlbum(String album) { this.album = album; } public void setData(String data) { this.data = data; } public void setDisplay_name(String display_name) { this.display_name = display_name; } public void setTitle(String title) { this.title = title; } public void setMime_type(String mime_type) { this.mime_type = mime_type; } public void setYear(long year) { this.year = year; } public void setDuration(long duration) { this.duration = duration; } public void setSize(long size) { this.size = size; } public void setDate_added(long date_added) { this.date_added = date_added; } public void setDate_modified(long date_modified) { this.date_modified = date_modified; } public String getTitle_key() { return title_key; } public String getArtist_key() { return artist_key; } public String getAlbum_key() { return album_key; } public long getDuration() { return duration; } public String getArtist() { return artist; } public String getAlbum() { return album; } public long getYear() { return year; } public String getData() { return data; } public long getSize() { return size; } public String getDisplay_name() { return display_name; } public String getTitle() { return title; } public long getDate_added() { return date_added; } public long getDate_modified() { return date_modified; } public String getMime_type() { return mime_type; } public String getAlbum_id() { return album_id; } public String getAlbum_path() { return album_path; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
DuanJiaNing/Musicoco
app/src/main/java/com/duan/musicoco/modle/SongInfo.java
1,007
//显示的名字
line_comment
zh-cn
package com.duan.musicoco.modle; import android.provider.MediaStore; /** * Created by DuanJiaNing on 2017/5/24. */ final public class SongInfo implements MediaStore.Audio.AudioColumns { //用于搜索、排序、分类 private String title_key; private String artist_key; private String album_key; private int id; //时间 ms private long duration; //艺术家 private String artist; //所属专辑 private String album; //专辑 ID private String album_id; //专辑图片路径 private String album_path; //专辑录制时间 private long year; //磁盘上的保存路径 //与服务端的 path 域对应,对于同一首歌曲(文件路径相同),两者应该相同 private String data; //文件大小 bytes private long size; //显示 <SUF> private String display_name; //内容标题 private String title; //文件被加入媒体库的时间 private long date_added; //文件最后修改时间 private long date_modified; //MIME type private String mime_type; @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; SongInfo songInfo = (SongInfo) o; return data.equals(songInfo.data); } @Override public int hashCode() { return data.hashCode(); } public void setAlbum_id(String album_id) { this.album_id = album_id; } public void setAlbum_path(String album_path) { this.album_path = album_path; } public void setTitle_key(String title_key) { this.title_key = title_key; } public void setArtist_key(String artist_key) { this.artist_key = artist_key; } public void setAlbum_key(String album_key) { this.album_key = album_key; } public void setArtist(String artist) { this.artist = artist; } public void setAlbum(String album) { this.album = album; } public void setData(String data) { this.data = data; } public void setDisplay_name(String display_name) { this.display_name = display_name; } public void setTitle(String title) { this.title = title; } public void setMime_type(String mime_type) { this.mime_type = mime_type; } public void setYear(long year) { this.year = year; } public void setDuration(long duration) { this.duration = duration; } public void setSize(long size) { this.size = size; } public void setDate_added(long date_added) { this.date_added = date_added; } public void setDate_modified(long date_modified) { this.date_modified = date_modified; } public String getTitle_key() { return title_key; } public String getArtist_key() { return artist_key; } public String getAlbum_key() { return album_key; } public long getDuration() { return duration; } public String getArtist() { return artist; } public String getAlbum() { return album; } public long getYear() { return year; } public String getData() { return data; } public long getSize() { return size; } public String getDisplay_name() { return display_name; } public String getTitle() { return title; } public long getDate_added() { return date_added; } public long getDate_modified() { return date_modified; } public String getMime_type() { return mime_type; } public String getAlbum_id() { return album_id; } public String getAlbum_path() { return album_path; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
false
885
3
1,007
4
1,122
3
1,007
4
1,317
6
false
false
false
false
false
true
11959_6
package com.fuckwzxy.util; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.fuckwzxy.bean.ApiInfo; import com.fuckwzxy.bean.SignMessage; import com.fuckwzxy.bean.UserInfo; import com.fuckwzxy.common.ApiConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import javax.sound.midi.Soundbank; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author wzh * 2020/9/23 19:15 */ @Component @Slf4j public class SendUtil { @Async public void sendCheckRequest(UserInfo userInfo, ApiInfo apiInfo, int seq) { HttpRequest request = createHttpRequest(apiInfo,userInfo); //body request.body(apiInfo.getBody().replace("seq=3", "seq=" + seq)); //return body request.execute(); } /** * 获取签到的id和logId * * @param userInfo user * @param getSignMessageApiInfo 接口 */ public SignMessage getSignMessage(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到返回的JSON并解析 String body = request.execute().body(); JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(0); return new SignMessage((String) data.getObj("id"), (String) data.get("logId")); } @Async public void sendSignRequest(UserInfo userInfo, ApiInfo signApiInfo, SignMessage signMessage) { HttpRequest request = createHttpRequest(signApiInfo,userInfo); //JSON data JSONObject data = new JSONObject(); data.set("id", signMessage.getLogId()); data.set("signId", signMessage.getId()); data.set("latitude", "23.090164"); data.set("longitude", "113.354053"); data.set("country", "中国"); data.set("province", "广东省"); data.set("district", "海珠区"); data.set("township", "官洲街道"); data.set("city", "广州市"); request.body(data.toString()); request.execute(); } public String GetJSON(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到返回的JSON并解析 String body = request.execute().body(); return body; } public boolean needCheck(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); HttpResponse response = request.execute(); String body = response.body(); if(!JSONUtil.parseObj(body).containsKey("data")) return false; JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(seq-1); return Integer.parseInt(data.get("type").toString()) == 0; } public List<String> getAllNoSign(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式 String date = df.format(new Date()); String httpbody = apiInfo.getBody().replace("seq=3", "seq=" + seq); httpbody = httpbody.replace("date=20201030","date="+date); request.body(httpbody); String body = request.execute().body(); if(!JSONUtil.parseObj(body).containsKey("data") ){ return null; }else{ List<String> list = new ArrayList<>(); JSONArray arr = (JSONArray) JSONUtil.parseObj(body).get("data"); for (int i = 0; i < arr.size() ; i++) { JSONObject stu = (JSONObject) arr.get(i); list.add((String) stu.get("userId")); } return list; } } public void replaceSign(ApiInfo apiInfo,UserInfo userInfo, int seq,String userId){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body String httpbody = apiInfo.getBody().replace("seq=", "seq=" + seq); httpbody = httpbody.replace("userId=","userId="+userId); request.body(httpbody); //return body request.execute(); } public boolean JudgeTokenIsValid(ApiInfo apiInfo,UserInfo userInfo){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //得到返回的JSON并解析 String body = request.execute().body(); if(JSONUtil.parseObj(body).containsKey("data")) return true; else return false; } /** * 创建HttpRequest对象 */ private HttpRequest createHttpRequest(ApiInfo apiInfo,UserInfo userInfo) { //请求方法和请求url HttpRequest request = request = apiInfo.getMethod().equals(ApiConstant.METHOD_GET)?HttpRequest.get(apiInfo.getUrl()):HttpRequest.post(apiInfo.getUrl()); //报文头 request.contentType(apiInfo.getContenttype()); //token request.header("token", userInfo.getToken().trim());//总有混蛋 带空格存进来 return request; } }
Duangdi/fuck-wozaixiaoyuan
src/main/java/com/fuckwzxy/util/SendUtil.java
1,384
//得到返回的JSON并解析
line_comment
zh-cn
package com.fuckwzxy.util; import cn.hutool.http.HttpRequest; import cn.hutool.http.HttpResponse; import cn.hutool.json.JSONArray; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.fuckwzxy.bean.ApiInfo; import com.fuckwzxy.bean.SignMessage; import com.fuckwzxy.bean.UserInfo; import com.fuckwzxy.common.ApiConstant; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import javax.sound.midi.Soundbank; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @author wzh * 2020/9/23 19:15 */ @Component @Slf4j public class SendUtil { @Async public void sendCheckRequest(UserInfo userInfo, ApiInfo apiInfo, int seq) { HttpRequest request = createHttpRequest(apiInfo,userInfo); //body request.body(apiInfo.getBody().replace("seq=3", "seq=" + seq)); //return body request.execute(); } /** * 获取签到的id和logId * * @param userInfo user * @param getSignMessageApiInfo 接口 */ public SignMessage getSignMessage(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到返回的JSON并解析 String body = request.execute().body(); JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(0); return new SignMessage((String) data.getObj("id"), (String) data.get("logId")); } @Async public void sendSignRequest(UserInfo userInfo, ApiInfo signApiInfo, SignMessage signMessage) { HttpRequest request = createHttpRequest(signApiInfo,userInfo); //JSON data JSONObject data = new JSONObject(); data.set("id", signMessage.getLogId()); data.set("signId", signMessage.getId()); data.set("latitude", "23.090164"); data.set("longitude", "113.354053"); data.set("country", "中国"); data.set("province", "广东省"); data.set("district", "海珠区"); data.set("township", "官洲街道"); data.set("city", "广州市"); request.body(data.toString()); request.execute(); } public String GetJSON(UserInfo userInfo, ApiInfo getSignMessageApiInfo) { HttpRequest request = createHttpRequest(getSignMessageApiInfo,userInfo); //参数 request.form("page", 1); request.form("size", 5); //得到 <SUF> String body = request.execute().body(); return body; } public boolean needCheck(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); HttpResponse response = request.execute(); String body = response.body(); if(!JSONUtil.parseObj(body).containsKey("data")) return false; JSONObject data = (JSONObject) ((JSONArray) JSONUtil.parseObj(body).get("data")).get(seq-1); return Integer.parseInt(data.get("type").toString()) == 0; } public List<String> getAllNoSign(ApiInfo apiInfo,UserInfo userInfo, int seq){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");// 设置日期格式 String date = df.format(new Date()); String httpbody = apiInfo.getBody().replace("seq=3", "seq=" + seq); httpbody = httpbody.replace("date=20201030","date="+date); request.body(httpbody); String body = request.execute().body(); if(!JSONUtil.parseObj(body).containsKey("data") ){ return null; }else{ List<String> list = new ArrayList<>(); JSONArray arr = (JSONArray) JSONUtil.parseObj(body).get("data"); for (int i = 0; i < arr.size() ; i++) { JSONObject stu = (JSONObject) arr.get(i); list.add((String) stu.get("userId")); } return list; } } public void replaceSign(ApiInfo apiInfo,UserInfo userInfo, int seq,String userId){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //body String httpbody = apiInfo.getBody().replace("seq=", "seq=" + seq); httpbody = httpbody.replace("userId=","userId="+userId); request.body(httpbody); //return body request.execute(); } public boolean JudgeTokenIsValid(ApiInfo apiInfo,UserInfo userInfo){ HttpRequest request = createHttpRequest(apiInfo,userInfo); //得到返回的JSON并解析 String body = request.execute().body(); if(JSONUtil.parseObj(body).containsKey("data")) return true; else return false; } /** * 创建HttpRequest对象 */ private HttpRequest createHttpRequest(ApiInfo apiInfo,UserInfo userInfo) { //请求方法和请求url HttpRequest request = request = apiInfo.getMethod().equals(ApiConstant.METHOD_GET)?HttpRequest.get(apiInfo.getUrl()):HttpRequest.post(apiInfo.getUrl()); //报文头 request.contentType(apiInfo.getContenttype()); //token request.header("token", userInfo.getToken().trim());//总有混蛋 带空格存进来 return request; } }
false
1,236
7
1,384
7
1,466
7
1,384
7
1,673
12
false
false
false
false
false
true
36283_1
package com.boring.duanqifeng.tku; /* 段其沣于2017年10月9日 在四川大学江安校区创建 */ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class Leibie extends AppCompatActivity { SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leibie); //每种类别的题目数 sharedPreferences = getSharedPreferences("TMS",MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("gjs_danx",79); editor.putInt("gjs_dx",102); editor.putInt("gjs_pd",191); editor.putInt("jbz_danx",60); editor.putInt("jbz_dx",54); editor.putInt("jbz_lw",3); editor.putInt("jbz_pd",124); editor.putInt("jcjs_danx",47); editor.putInt("jcjs_dx",31); editor.putInt("jcjs_pd",58); editor.putInt("jl_danx",91); editor.putInt("jl_dx",21); editor.putInt("jl_pd",110); editor.putInt("jsll_danx",386); editor.putInt("jsll_dx",41); editor.putInt("jsll_pd",42); editor.putInt("nw_danx",84); editor.putInt("nw_dx",111); editor.putInt("nw_pd",18); editor.putInt("nw_lw",262); editor.putInt("xljc_danx",39); editor.putInt("xljc_dx",45); editor.putInt("xljc_pd",29); editor.putInt("zzjc_danx",24); editor.putInt("zzjc_dx",37); editor.putInt("zzjc_pd",42); editor.putInt("dl_danx",91); editor.putInt("dl_dx",18); editor.putInt("dl_pd",394); editor.apply(); Button 内务 = (Button) findViewById(R.id.内务); Button 队列 = (Button) findViewById(R.id.队列); Button 纪律 = (Button) findViewById(R.id.纪律); Button 军兵种 = (Button) findViewById(R.id.军兵种); Button 军事理论 = (Button) findViewById(R.id.军事理论); Button 军事高技术 = (Button) findViewById(R.id.军事高技术); Button 军队基层建设 = (Button) findViewById(R.id.军队基层建设); Button 训练基础理论 = (Button) findViewById(R.id.训练基础理论); Button 作战基础知识 = (Button) findViewById(R.id.作战基础知识); Button 模拟考试 = (Button) findViewById(R.id.kaoShi); Button 错题集 = (Button) findViewById(R.id.cuoTi); 内务.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Neiwu.class)); } }); 队列.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Duilie.class)); } }); 纪律.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jilv.class)); } }); 军兵种.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jbz.class)); } }); 军事理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jsll.class)); } }); 军事高技术.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Gjs.class)); } }); 军队基层建设.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jcjs.class)); } }); 训练基础理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Xljc.class)); } }); 作战基础知识.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Zzjc.class)); } }); 模拟考试.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Moni.class)); } }); 错题集.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Cuotiji.class)); } }); } }
Duanxiaoer/Android_TKU
app/src/main/java/com/boring/duanqifeng/tku/Leibie.java
1,362
//每种类别的题目数
line_comment
zh-cn
package com.boring.duanqifeng.tku; /* 段其沣于2017年10月9日 在四川大学江安校区创建 */ import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; public class Leibie extends AppCompatActivity { SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leibie); //每种 <SUF> sharedPreferences = getSharedPreferences("TMS",MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt("gjs_danx",79); editor.putInt("gjs_dx",102); editor.putInt("gjs_pd",191); editor.putInt("jbz_danx",60); editor.putInt("jbz_dx",54); editor.putInt("jbz_lw",3); editor.putInt("jbz_pd",124); editor.putInt("jcjs_danx",47); editor.putInt("jcjs_dx",31); editor.putInt("jcjs_pd",58); editor.putInt("jl_danx",91); editor.putInt("jl_dx",21); editor.putInt("jl_pd",110); editor.putInt("jsll_danx",386); editor.putInt("jsll_dx",41); editor.putInt("jsll_pd",42); editor.putInt("nw_danx",84); editor.putInt("nw_dx",111); editor.putInt("nw_pd",18); editor.putInt("nw_lw",262); editor.putInt("xljc_danx",39); editor.putInt("xljc_dx",45); editor.putInt("xljc_pd",29); editor.putInt("zzjc_danx",24); editor.putInt("zzjc_dx",37); editor.putInt("zzjc_pd",42); editor.putInt("dl_danx",91); editor.putInt("dl_dx",18); editor.putInt("dl_pd",394); editor.apply(); Button 内务 = (Button) findViewById(R.id.内务); Button 队列 = (Button) findViewById(R.id.队列); Button 纪律 = (Button) findViewById(R.id.纪律); Button 军兵种 = (Button) findViewById(R.id.军兵种); Button 军事理论 = (Button) findViewById(R.id.军事理论); Button 军事高技术 = (Button) findViewById(R.id.军事高技术); Button 军队基层建设 = (Button) findViewById(R.id.军队基层建设); Button 训练基础理论 = (Button) findViewById(R.id.训练基础理论); Button 作战基础知识 = (Button) findViewById(R.id.作战基础知识); Button 模拟考试 = (Button) findViewById(R.id.kaoShi); Button 错题集 = (Button) findViewById(R.id.cuoTi); 内务.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Neiwu.class)); } }); 队列.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Duilie.class)); } }); 纪律.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jilv.class)); } }); 军兵种.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jbz.class)); } }); 军事理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jsll.class)); } }); 军事高技术.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Gjs.class)); } }); 军队基层建设.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Jcjs.class)); } }); 训练基础理论.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Xljc.class)); } }); 作战基础知识.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Zzjc.class)); } }); 模拟考试.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Moni.class)); } }); 错题集.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(Leibie.this,Cuotiji.class)); } }); } }
false
1,129
6
1,362
9
1,410
6
1,362
9
1,663
11
false
false
false
false
false
true
33092_8
package net.messi.early.controller; import net.messi.early.request.ProductInventoryCacheRefreshRequest; import net.messi.early.request.ProductInventoryDBUpdateRequest; import net.messi.early.request.Request; import net.messi.early.service.GoodsService; import net.messi.early.service.ProductInventoryService; import net.messi.early.service.RequestAsyncProcessService; import net.messi.early.utils.JSONResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("inventory") public class ProductInventoryController { @Autowired private GoodsService goodsService; @Autowired private RequestAsyncProcessService requestAsyncProcessService; @Autowired private ProductInventoryService productInventoryService; /** * 更新缓存 * * @param goodsId * @param inventoryCnt * @return */ @ResponseBody @RequestMapping("/updateInventory") public JSONResult updateInventory(Integer goodsId) { try { Request request = new ProductInventoryDBUpdateRequest(goodsId, goodsService); requestAsyncProcessService.process(request); } catch (Exception e) { e.printStackTrace(); } return JSONResult.ok(); } /** * 获取商品库存的缓存 * * @param goodsId * @return */ @ResponseBody @RequestMapping("/getInventory") public JSONResult getInventory(Integer goodsId) { try { Request request = new ProductInventoryCacheRefreshRequest(goodsId, goodsService); requestAsyncProcessService.process(request); long startTime = System.currentTimeMillis(); long endTime = 0L; long waitTime = 0L; Integer inventoryCnt = 0; //将请求仍给service异步处理以后,就需要while(true)一会儿,在这里hang住 //去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 while (true) { if (waitTime > 200) { break; } //尝试去redis中读取一次商品库存的缓存 inventoryCnt = productInventoryService.getProductInventoryCache(goodsId); //如果读取到了结果,那么就返回 if (inventoryCnt != null) { return new JSONResult(inventoryCnt); } else { //如果没有读取到 Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } //直接从数据库查询 inventoryCnt = goodsService.lasteInventory(goodsId); if (inventoryCnt != null) return new JSONResult(inventoryCnt); } catch (Exception e) { e.printStackTrace(); } //没有查到 return JSONResult.ok(new Long(-1L)); } }
DuncanPlayer/quickearly
controller/ProductInventoryController.java
684
//没有查到
line_comment
zh-cn
package net.messi.early.controller; import net.messi.early.request.ProductInventoryCacheRefreshRequest; import net.messi.early.request.ProductInventoryDBUpdateRequest; import net.messi.early.request.Request; import net.messi.early.service.GoodsService; import net.messi.early.service.ProductInventoryService; import net.messi.early.service.RequestAsyncProcessService; import net.messi.early.utils.JSONResult; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("inventory") public class ProductInventoryController { @Autowired private GoodsService goodsService; @Autowired private RequestAsyncProcessService requestAsyncProcessService; @Autowired private ProductInventoryService productInventoryService; /** * 更新缓存 * * @param goodsId * @param inventoryCnt * @return */ @ResponseBody @RequestMapping("/updateInventory") public JSONResult updateInventory(Integer goodsId) { try { Request request = new ProductInventoryDBUpdateRequest(goodsId, goodsService); requestAsyncProcessService.process(request); } catch (Exception e) { e.printStackTrace(); } return JSONResult.ok(); } /** * 获取商品库存的缓存 * * @param goodsId * @return */ @ResponseBody @RequestMapping("/getInventory") public JSONResult getInventory(Integer goodsId) { try { Request request = new ProductInventoryCacheRefreshRequest(goodsId, goodsService); requestAsyncProcessService.process(request); long startTime = System.currentTimeMillis(); long endTime = 0L; long waitTime = 0L; Integer inventoryCnt = 0; //将请求仍给service异步处理以后,就需要while(true)一会儿,在这里hang住 //去尝试等待前面有商品库存更新的操作,同时缓存刷新的操作,将最新的数据刷新到缓存中 while (true) { if (waitTime > 200) { break; } //尝试去redis中读取一次商品库存的缓存 inventoryCnt = productInventoryService.getProductInventoryCache(goodsId); //如果读取到了结果,那么就返回 if (inventoryCnt != null) { return new JSONResult(inventoryCnt); } else { //如果没有读取到 Thread.sleep(20); endTime = System.currentTimeMillis(); waitTime = endTime - startTime; } } //直接从数据库查询 inventoryCnt = goodsService.lasteInventory(goodsId); if (inventoryCnt != null) return new JSONResult(inventoryCnt); } catch (Exception e) { e.printStackTrace(); } //没有 <SUF> return JSONResult.ok(new Long(-1L)); } }
false
628
4
684
4
731
4
684
4
923
5
false
false
false
false
false
true
64649_2
package org.lanqiao.algo.elementary._03sort; import org.assertj.core.api.Assertions; import org.lanqiao.algo.util.Util; import java.util.Arrays; /** * 思路:首先要知道大顶堆和小顶堆,数组就是一个堆,每个i节点的左右孩子是2i+1和2i+2<br /> * 有了堆,将其堆化:从n/2-1个元素开始向下修复,将每个节点修复为小(大)顶堆<br /> * 修复完成后,数组具有小(大)顶堆的性质<br /> * 按序输出:小顶堆可以对数组逆序排序,每次交换栈顶和末尾元素,对栈顶进行向下修复,这样次小元素又到堆顶了<br /> * * 时间复杂度: 堆化:一半的元素修复,修复是单分支的,所以整体堆化为nlgn/2<br /> * 排序:n个元素都要取出,因此调整n次,每次调整修复同上是lgn的,整体为nlgn * 空间复杂度:不需要开辟辅助空间<br /> * 原址排序<br /> * 稳定性:<br /> */ public class _7HeapSort { static void makeMinHeap(int[] A) { int n = A.length; for (int i = n / 2 - 1; i >= 0; i--) { MinHeapFixDown(A, i, n); } } static void MinHeapFixDown(int[] A, int i, int n) { // 找到左右孩子 int left = 2 * i + 1; int right = 2 * i + 2; //左孩子已经越界,i就是叶子节点 if (left >= n) { return; } int min = left; if (right >= n) { min = left; } else { if (A[right] < A[left]) { min = right; } } //min指向了左右孩子中较小的那个 // 如果A[i]比两个孩子都要小,不用调整 if (A[i] <= A[min]) { return; } //否则,找到两个孩子中较小的,和i交换 int temp = A[i]; A[i] = A[min]; A[min] = temp; //小孩子那个位置的值发生了变化,i变更为小孩子那个位置,递归调整 MinHeapFixDown(A, min, n); } // // public static void sortDesc(int[] arr) { // makeMinHeap( arr ); // 1.建立小顶堆 // int length = arr.length; // for (int i = length - 1; i >= 1; i--) { // Util.swap( arr, i, 0 ); // 堆顶(最小)元素换到元素末尾,末尾元素到了堆顶 // MinHeapFixDown( arr, 0, i );// 调整堆顶,边界递减 // } // } static void sort(int[] A) { //先对A进行堆化 makeMinHeap(A); for (int x = A.length - 1; x >= 0; x--) { //把堆顶,0号元素和最后一个元素对调 Util.swap(A, 0, x); //缩小堆的范围,对堆顶元素进行向下调整 MinHeapFixDown(A, 0, x); } } public static void main(String[] args) { int[] arr = Util.getRandomArr(10, 1, 100); System.out.println( "begin..." + Arrays.toString( arr ) ); sort(arr); System.out.println( "final..." + Arrays.toString( arr ) ); Assertions.assertThat( Util.checkOrdered( arr, false ) ).isTrue(); } }
Dxoca/Algorithm_LanQiao
src/main/java/org/lanqiao/algo/elementary/_03sort/_7HeapSort.java
982
//左孩子已经越界,i就是叶子节点
line_comment
zh-cn
package org.lanqiao.algo.elementary._03sort; import org.assertj.core.api.Assertions; import org.lanqiao.algo.util.Util; import java.util.Arrays; /** * 思路:首先要知道大顶堆和小顶堆,数组就是一个堆,每个i节点的左右孩子是2i+1和2i+2<br /> * 有了堆,将其堆化:从n/2-1个元素开始向下修复,将每个节点修复为小(大)顶堆<br /> * 修复完成后,数组具有小(大)顶堆的性质<br /> * 按序输出:小顶堆可以对数组逆序排序,每次交换栈顶和末尾元素,对栈顶进行向下修复,这样次小元素又到堆顶了<br /> * * 时间复杂度: 堆化:一半的元素修复,修复是单分支的,所以整体堆化为nlgn/2<br /> * 排序:n个元素都要取出,因此调整n次,每次调整修复同上是lgn的,整体为nlgn * 空间复杂度:不需要开辟辅助空间<br /> * 原址排序<br /> * 稳定性:<br /> */ public class _7HeapSort { static void makeMinHeap(int[] A) { int n = A.length; for (int i = n / 2 - 1; i >= 0; i--) { MinHeapFixDown(A, i, n); } } static void MinHeapFixDown(int[] A, int i, int n) { // 找到左右孩子 int left = 2 * i + 1; int right = 2 * i + 2; //左孩 <SUF> if (left >= n) { return; } int min = left; if (right >= n) { min = left; } else { if (A[right] < A[left]) { min = right; } } //min指向了左右孩子中较小的那个 // 如果A[i]比两个孩子都要小,不用调整 if (A[i] <= A[min]) { return; } //否则,找到两个孩子中较小的,和i交换 int temp = A[i]; A[i] = A[min]; A[min] = temp; //小孩子那个位置的值发生了变化,i变更为小孩子那个位置,递归调整 MinHeapFixDown(A, min, n); } // // public static void sortDesc(int[] arr) { // makeMinHeap( arr ); // 1.建立小顶堆 // int length = arr.length; // for (int i = length - 1; i >= 1; i--) { // Util.swap( arr, i, 0 ); // 堆顶(最小)元素换到元素末尾,末尾元素到了堆顶 // MinHeapFixDown( arr, 0, i );// 调整堆顶,边界递减 // } // } static void sort(int[] A) { //先对A进行堆化 makeMinHeap(A); for (int x = A.length - 1; x >= 0; x--) { //把堆顶,0号元素和最后一个元素对调 Util.swap(A, 0, x); //缩小堆的范围,对堆顶元素进行向下调整 MinHeapFixDown(A, 0, x); } } public static void main(String[] args) { int[] arr = Util.getRandomArr(10, 1, 100); System.out.println( "begin..." + Arrays.toString( arr ) ); sort(arr); System.out.println( "final..." + Arrays.toString( arr ) ); Assertions.assertThat( Util.checkOrdered( arr, false ) ).isTrue(); } }
false
879
11
982
14
969
11
982
14
1,301
20
false
false
false
false
false
true
16805_4
package comm; import java.sql.*; import java.util.Objects; import static comm.DBConfig.*; public class Card { private String cardID; private String userName; private String passWord; private int balance; private boolean exist; public int getBalance() { return balance; } // public void setBanlance(float banlance) {this.banlance = banlance;} public String getUserName() {return userName;} public void setUserName(String userName) {this.userName = userName; } public String getCardID() { return cardID; } public void setCardID(String cardID) { this.cardID = cardID; } public String getPassWord() { return passWord; } // public void setPassWord(String passWord) { // this.passWord = passWord; // } public Card(String cardID, String passWord, int balance){ this.cardID = cardID; this.passWord = passWord; this.balance = balance; getInfo(cardID); } public Card(String cardID){ getInfo(cardID); } //从数据库获取信息 public void getInfo(String cardID){ exist = false; Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 stmt = conn.createStatement(); String sql; sql = "SELECT CardID, UserName, PassWord, Balance FROM user where CardID =" + cardID; ResultSet rs = stmt.executeQuery(sql); // 展开结果集数据库 while(rs.next()){ // 通过字段检索 String id = rs.getString("CardID"); String name = rs.getString("UserName"); String pwd = rs.getString("PassWord"); int balance = rs.getInt("Balance"); // 输出数据 System.out.print("CardID: " + id); System.out.print(" UserName: " + name); System.out.print(" PassWord: " + pwd); System.out.print(" Balance: " + balance); System.out.print("\n"); this.cardID = id; this.userName = name; this.balance = balance; this.passWord=pwd; if(!Objects.equals(id, "")) exist=true; } // 完成后关闭 rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } // 判断账号是否存在 public boolean exist(){ System.out.println(exist); return exist; } // 判断密码是否正确 public boolean judgePwd(String pwd){ return Objects.equals(pwd, this.passWord); } // 改密 public boolean setPassWord(String pwd){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Password=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1,pwd); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } passWord=pwd; } return true; } //修改余额 public boolean setBanlance(int balance){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Balance=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1,balance); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } this.balance=balance; } return true; } }
Dycley/ATM
src/comm/Card.java
1,527
// 注册 JDBC 驱动
line_comment
zh-cn
package comm; import java.sql.*; import java.util.Objects; import static comm.DBConfig.*; public class Card { private String cardID; private String userName; private String passWord; private int balance; private boolean exist; public int getBalance() { return balance; } // public void setBanlance(float banlance) {this.banlance = banlance;} public String getUserName() {return userName;} public void setUserName(String userName) {this.userName = userName; } public String getCardID() { return cardID; } public void setCardID(String cardID) { this.cardID = cardID; } public String getPassWord() { return passWord; } // public void setPassWord(String passWord) { // this.passWord = passWord; // } public Card(String cardID, String passWord, int balance){ this.cardID = cardID; this.passWord = passWord; this.balance = balance; getInfo(cardID); } public Card(String cardID){ getInfo(cardID); } //从数据库获取信息 public void getInfo(String cardID){ exist = false; Connection conn = null; Statement stmt = null; try{ // 注册 <SUF> Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行查询 stmt = conn.createStatement(); String sql; sql = "SELECT CardID, UserName, PassWord, Balance FROM user where CardID =" + cardID; ResultSet rs = stmt.executeQuery(sql); // 展开结果集数据库 while(rs.next()){ // 通过字段检索 String id = rs.getString("CardID"); String name = rs.getString("UserName"); String pwd = rs.getString("PassWord"); int balance = rs.getInt("Balance"); // 输出数据 System.out.print("CardID: " + id); System.out.print(" UserName: " + name); System.out.print(" PassWord: " + pwd); System.out.print(" Balance: " + balance); System.out.print("\n"); this.cardID = id; this.userName = name; this.balance = balance; this.passWord=pwd; if(!Objects.equals(id, "")) exist=true; } // 完成后关闭 rs.close(); stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } } // 判断账号是否存在 public boolean exist(){ System.out.println(exist); return exist; } // 判断密码是否正确 public boolean judgePwd(String pwd){ return Objects.equals(pwd, this.passWord); } // 改密 public boolean setPassWord(String pwd){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Password=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1,pwd); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } passWord=pwd; } return true; } //修改余额 public boolean setBanlance(int balance){ if(exist()){ Connection conn = null; Statement stmt = null; try{ // 注册 JDBC 驱动 Class.forName(JDBC_DRIVER); // 打开链接 System.out.println("连接数据库..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); // 执行修改 stmt = conn.createStatement(); String sql; sql = "UPDATE user SET Balance=? where CardID =?"; PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1,balance); pst.setString(2,cardID); pst.executeUpdate(); // 完成后关闭 stmt.close(); conn.close(); }catch(SQLException se){ // 处理 JDBC 错误 se.printStackTrace(); }catch(Exception e){ // 处理 Class.forName 错误 e.printStackTrace(); }finally{ // 关闭资源 try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// 什么都不做 try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); } } this.balance=balance; } return true; } }
false
1,278
8
1,527
6
1,478
5
1,527
6
2,171
13
false
false
false
false
false
true
34199_18
package com.aochat.ui; import com.aochat.ui.module.*; import com.aochat.ui.module.Labels; import com.aochat.ui.module.Menu; import javax.swing.*; import java.awt.*; public class Frame { JPanel rootPanel = new JPanel(); // 新建根窗口 JFrame frame = new JFrame("AoChat"); // 初始化窗口,并命名 Menu menuBar = new Menu(rootPanel, frame); // 新建菜单栏 IPText ipText = new IPText(rootPanel); // 新建IP输入栏 PortTexts portTexts = new PortTexts(rootPanel); // 新建端口输入栏 EnterTextArea enterTextArea = new EnterTextArea(rootPanel); // 新建信息输入栏 public MessageArea messageArea = new MessageArea(rootPanel); // 新建消息输入栏 Labels labels = new Labels(rootPanel); // 新建信息栏 Buttons buttons = new Buttons(rootPanel, menuBar); // 新建按钮组 public Frame(){ panelInit(); // 窗口初始化 setPosition(); // 设置每个组件位置 addActionListener(); // 添加监听器 } private void panelInit(){ // 窗口初始化 // 设置图标 Toolkit took = Toolkit.getDefaultToolkit(); Image image = took.getImage("src/img/icon.png"); frame.setIconImage(image); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时关闭进程 frame.setContentPane(rootPanel); // 容器添加到面板 frame.setResizable(false); // 不准改大小 frame.setSize(800, 600); // 设置窗口大小 frame.setVisible(true); // 显示窗口 } private void setPosition(){ // 设置每个组件位置 rootPanel.setLayout(null);// 禁用布局器 menuBar.setPosition(); enterTextArea.setPosition(); ipText.setPosition(); portTexts.setPosition(); messageArea.setPosition(); labels.setPosition(); buttons.setPosition(); } private void addActionListener(){ // 添加监听器 menuBar.addActionListener(); buttons.addButtonActionListener(enterTextArea, ipText, portTexts, messageArea, labels, menuBar.ipHistorySet); } }
DylanAo/AHU-AI-Repository
专业选修课/Java/AoChat/com/aochat/ui/Frame.java
519
// 显示窗口
line_comment
zh-cn
package com.aochat.ui; import com.aochat.ui.module.*; import com.aochat.ui.module.Labels; import com.aochat.ui.module.Menu; import javax.swing.*; import java.awt.*; public class Frame { JPanel rootPanel = new JPanel(); // 新建根窗口 JFrame frame = new JFrame("AoChat"); // 初始化窗口,并命名 Menu menuBar = new Menu(rootPanel, frame); // 新建菜单栏 IPText ipText = new IPText(rootPanel); // 新建IP输入栏 PortTexts portTexts = new PortTexts(rootPanel); // 新建端口输入栏 EnterTextArea enterTextArea = new EnterTextArea(rootPanel); // 新建信息输入栏 public MessageArea messageArea = new MessageArea(rootPanel); // 新建消息输入栏 Labels labels = new Labels(rootPanel); // 新建信息栏 Buttons buttons = new Buttons(rootPanel, menuBar); // 新建按钮组 public Frame(){ panelInit(); // 窗口初始化 setPosition(); // 设置每个组件位置 addActionListener(); // 添加监听器 } private void panelInit(){ // 窗口初始化 // 设置图标 Toolkit took = Toolkit.getDefaultToolkit(); Image image = took.getImage("src/img/icon.png"); frame.setIconImage(image); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 关闭窗口时关闭进程 frame.setContentPane(rootPanel); // 容器添加到面板 frame.setResizable(false); // 不准改大小 frame.setSize(800, 600); // 设置窗口大小 frame.setVisible(true); // 显示 <SUF> } private void setPosition(){ // 设置每个组件位置 rootPanel.setLayout(null);// 禁用布局器 menuBar.setPosition(); enterTextArea.setPosition(); ipText.setPosition(); portTexts.setPosition(); messageArea.setPosition(); labels.setPosition(); buttons.setPosition(); } private void addActionListener(){ // 添加监听器 menuBar.addActionListener(); buttons.addButtonActionListener(enterTextArea, ipText, portTexts, messageArea, labels, menuBar.ipHistorySet); } }
false
482
5
515
5
541
4
515
5
733
9
false
false
false
false
false
true
24092_10
package com.dyman.opencvtest.utils; import android.graphics.Bitmap; import android.util.Log; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.RotatedRect; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by dyman on 2017/8/12. * * 智能选区帮助类 */ public class Scanner { private static final String TAG = "Scanner"; private static int resizeThreshold = 500; private static float resizeScale = 1.0f; /** 扫描图片,并返回检测到的矩形的四个顶点的坐标 */ public static android.graphics.Point[] scanPoint(Bitmap srcBitmap) { Mat srcMat = new Mat(); Utils.bitmapToMat(srcBitmap, srcMat); // 图像缩放 Mat image = resizeImage(srcMat); // 图像预处理 Mat scanImage = preProcessImage(image); List<MatOfPoint> contours = new ArrayList<>(); // 检测到的轮廓 Mat hierarchy = new Mat(); // 各轮廓的继承关系 // 提取边框 Imgproc.findContours(scanImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); // 按面积排序,最后只取面积最大的那个 Collections.sort(contours, new Comparator<MatOfPoint>() { @Override public int compare(MatOfPoint matOfPoint1, MatOfPoint matOfPoint2) { double oneArea = Math.abs(Imgproc.contourArea(matOfPoint1)); double twoArea = Math.abs(Imgproc.contourArea(matOfPoint2)); return Double.compare(twoArea, oneArea); } }); Point[] resultArr = new Point[4]; if (contours.size() > 0) { Log.i(TAG, "scanPoint: -------------contours.size="+contours.size()); // 取面积最大的 MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(0).toArray()); double arc = Imgproc.arcLength(contour2f, true); MatOfPoint2f outDpMat = new MatOfPoint2f(); Imgproc.approxPolyDP(contour2f, outDpMat, 0.02 * arc, true); // 多边形逼近 // 筛选去除相近的点 MatOfPoint2f selectMat = selectPoint(outDpMat, 1); if (selectMat.toArray().length != 4) { // 不是四边形,使用最小矩形包裹 RotatedRect rotatedRect = Imgproc.minAreaRect(selectMat); rotatedRect.points(resultArr); } else { resultArr = selectMat.toArray(); } // 比例还原 for (Point p : resultArr) { p.x *= resizeScale; p.y *= resizeScale; } } // 对最终检测出的四个点进行排序:左上、右上、右下、坐下 Point[] result = sortPointClockwise(resultArr); android.graphics.Point[] rs = new android.graphics.Point[result.length]; for (int i = 0; i < result.length; i++) { android.graphics.Point p = new android.graphics.Point((int) result[i].x, (int) result[i].y); rs[i] = p; } return rs; } /** * 为避免处理时间过长,先对图片进行压缩 * @param image * @return */ private static Mat resizeImage(Mat image) { int width = image.cols(); int height = image.rows(); int maxSize = width > height ? width : height; if (maxSize > resizeThreshold) { resizeScale = 1.0f * maxSize / resizeThreshold; width = (int) (width / resizeScale); height = (int) (height / resizeScale); Size size = new Size(width, height); Mat resizeMat = new Mat(); Imgproc.resize(image, resizeMat, size); return resizeMat; } return image; } /** * 对图像进行预处理:灰度化、高斯模糊、Canny边缘检测 * @param image * @return */ private static Mat preProcessImage(Mat image) { Mat grayMat = new Mat(); Imgproc.cvtColor(image, grayMat, Imgproc.COLOR_RGB2GRAY); // 注意RGB和BGR,影响很大 Mat blurMat = new Mat(); Imgproc.GaussianBlur(grayMat, blurMat, new Size(5,5), 0); Mat cannyMat = new Mat(); Imgproc.Canny(blurMat, cannyMat, 0, 5); Mat thresholdMat = new Mat(); Imgproc.threshold(cannyMat, thresholdMat, 0, 255, Imgproc.THRESH_OTSU); return cannyMat; } /** 过滤掉距离相近的点 */ private static MatOfPoint2f selectPoint(MatOfPoint2f outDpMat, int selectTimes) { List<Point> pointList = new ArrayList<>(); pointList.addAll(outDpMat.toList()); if (pointList.size() > 4) { double arc = Imgproc.arcLength(outDpMat, true); for (int i = pointList.size() - 1; i >= 0; i--) { if (pointList.size() == 4) { Point[] resultPoints = new Point[pointList.size()]; for (int j = 0; j < pointList.size(); j++) { resultPoints[j] = pointList.get(j); } return new MatOfPoint2f(resultPoints); } if (i != pointList.size() - 1) { Point itor = pointList.get(i); Point lastP = pointList.get(i + 1); double pointLength = Math.sqrt(Math.pow(itor.x-lastP.x, 2) + Math.pow(itor.y - lastP.y, 2)); if (pointLength < arc * 0.01 * selectTimes && pointList.size() > 4) { pointList.remove(i); } } } if (pointList.size() > 4) { // 要手动逐个强转 Point[] againPoints = new Point[pointList.size()]; for (int i = 0; i < pointList.size(); i++) { againPoints[i] = pointList.get(i); } return selectPoint(new MatOfPoint2f(againPoints), selectTimes + 1); } } return outDpMat; } /** 对顶点进行排序 */ private static Point[] sortPointClockwise(Point[] points) { if (points.length != 4) { return points; } Point unFoundPoint = new Point(); Point[] result = {unFoundPoint, unFoundPoint, unFoundPoint, unFoundPoint}; long minDistance = -1; for (Point point : points) { long distance = (long) (point.x * point.x + point.y * point.y); if (minDistance == -1 || distance < minDistance) { result[0] = point; minDistance = distance; } } if (result[0] != unFoundPoint) { Point leftTop = result[0]; Point[] p1 = new Point[3]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; p1[i] = point; i++; } if ((pointSideLine(leftTop, p1[0], p1[1]) * pointSideLine(leftTop, p1[0], p1[2])) < 0) { result[2] = p1[0]; } else if ((pointSideLine(leftTop, p1[1], p1[0]) * pointSideLine(leftTop, p1[1], p1[2])) < 0) { result[2] = p1[1]; } else if ((pointSideLine(leftTop, p1[2], p1[0]) * pointSideLine(leftTop, p1[2], p1[1])) < 0) { result[2] = p1[2]; } } if (result[0] != unFoundPoint && result[2] != unFoundPoint) { Point leftTop = result[0]; Point rightBottom = result[2]; Point[] p1 = new Point[2]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; if (point.x == rightBottom.x && point.y == rightBottom.y) continue; p1[i] = point; i++; } if (pointSideLine(leftTop, rightBottom, p1[0]) > 0) { result[1] = p1[0]; result[3] = p1[1]; } else { result[1] = p1[1]; result[3] = p1[0]; } } if (result[0] != unFoundPoint && result[1] != unFoundPoint && result[2] != unFoundPoint && result[3] != unFoundPoint) { return result; } return points; } private static double pointSideLine(Point lineP1, Point lineP2, Point point) { double x1 = lineP1.x; double y1 = lineP1.y; double x2 = lineP2.x; double y2 = lineP2.y; double x = point.x; double y = point.y; return (x - x1)*(y2 - y1) - (y - y1)*(x2 - x1); } }
DymanZy/OpenCVTest
app/src/main/java/com/dyman/opencvtest/utils/Scanner.java
2,479
// 筛选去除相近的点
line_comment
zh-cn
package com.dyman.opencvtest.utils; import android.graphics.Bitmap; import android.util.Log; import org.opencv.android.Utils; import org.opencv.core.Mat; import org.opencv.core.MatOfPoint; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Point; import org.opencv.core.RotatedRect; import org.opencv.core.Size; import org.opencv.imgproc.Imgproc; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Created by dyman on 2017/8/12. * * 智能选区帮助类 */ public class Scanner { private static final String TAG = "Scanner"; private static int resizeThreshold = 500; private static float resizeScale = 1.0f; /** 扫描图片,并返回检测到的矩形的四个顶点的坐标 */ public static android.graphics.Point[] scanPoint(Bitmap srcBitmap) { Mat srcMat = new Mat(); Utils.bitmapToMat(srcBitmap, srcMat); // 图像缩放 Mat image = resizeImage(srcMat); // 图像预处理 Mat scanImage = preProcessImage(image); List<MatOfPoint> contours = new ArrayList<>(); // 检测到的轮廓 Mat hierarchy = new Mat(); // 各轮廓的继承关系 // 提取边框 Imgproc.findContours(scanImage, contours, hierarchy, Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_NONE); // 按面积排序,最后只取面积最大的那个 Collections.sort(contours, new Comparator<MatOfPoint>() { @Override public int compare(MatOfPoint matOfPoint1, MatOfPoint matOfPoint2) { double oneArea = Math.abs(Imgproc.contourArea(matOfPoint1)); double twoArea = Math.abs(Imgproc.contourArea(matOfPoint2)); return Double.compare(twoArea, oneArea); } }); Point[] resultArr = new Point[4]; if (contours.size() > 0) { Log.i(TAG, "scanPoint: -------------contours.size="+contours.size()); // 取面积最大的 MatOfPoint2f contour2f = new MatOfPoint2f(contours.get(0).toArray()); double arc = Imgproc.arcLength(contour2f, true); MatOfPoint2f outDpMat = new MatOfPoint2f(); Imgproc.approxPolyDP(contour2f, outDpMat, 0.02 * arc, true); // 多边形逼近 // 筛选 <SUF> MatOfPoint2f selectMat = selectPoint(outDpMat, 1); if (selectMat.toArray().length != 4) { // 不是四边形,使用最小矩形包裹 RotatedRect rotatedRect = Imgproc.minAreaRect(selectMat); rotatedRect.points(resultArr); } else { resultArr = selectMat.toArray(); } // 比例还原 for (Point p : resultArr) { p.x *= resizeScale; p.y *= resizeScale; } } // 对最终检测出的四个点进行排序:左上、右上、右下、坐下 Point[] result = sortPointClockwise(resultArr); android.graphics.Point[] rs = new android.graphics.Point[result.length]; for (int i = 0; i < result.length; i++) { android.graphics.Point p = new android.graphics.Point((int) result[i].x, (int) result[i].y); rs[i] = p; } return rs; } /** * 为避免处理时间过长,先对图片进行压缩 * @param image * @return */ private static Mat resizeImage(Mat image) { int width = image.cols(); int height = image.rows(); int maxSize = width > height ? width : height; if (maxSize > resizeThreshold) { resizeScale = 1.0f * maxSize / resizeThreshold; width = (int) (width / resizeScale); height = (int) (height / resizeScale); Size size = new Size(width, height); Mat resizeMat = new Mat(); Imgproc.resize(image, resizeMat, size); return resizeMat; } return image; } /** * 对图像进行预处理:灰度化、高斯模糊、Canny边缘检测 * @param image * @return */ private static Mat preProcessImage(Mat image) { Mat grayMat = new Mat(); Imgproc.cvtColor(image, grayMat, Imgproc.COLOR_RGB2GRAY); // 注意RGB和BGR,影响很大 Mat blurMat = new Mat(); Imgproc.GaussianBlur(grayMat, blurMat, new Size(5,5), 0); Mat cannyMat = new Mat(); Imgproc.Canny(blurMat, cannyMat, 0, 5); Mat thresholdMat = new Mat(); Imgproc.threshold(cannyMat, thresholdMat, 0, 255, Imgproc.THRESH_OTSU); return cannyMat; } /** 过滤掉距离相近的点 */ private static MatOfPoint2f selectPoint(MatOfPoint2f outDpMat, int selectTimes) { List<Point> pointList = new ArrayList<>(); pointList.addAll(outDpMat.toList()); if (pointList.size() > 4) { double arc = Imgproc.arcLength(outDpMat, true); for (int i = pointList.size() - 1; i >= 0; i--) { if (pointList.size() == 4) { Point[] resultPoints = new Point[pointList.size()]; for (int j = 0; j < pointList.size(); j++) { resultPoints[j] = pointList.get(j); } return new MatOfPoint2f(resultPoints); } if (i != pointList.size() - 1) { Point itor = pointList.get(i); Point lastP = pointList.get(i + 1); double pointLength = Math.sqrt(Math.pow(itor.x-lastP.x, 2) + Math.pow(itor.y - lastP.y, 2)); if (pointLength < arc * 0.01 * selectTimes && pointList.size() > 4) { pointList.remove(i); } } } if (pointList.size() > 4) { // 要手动逐个强转 Point[] againPoints = new Point[pointList.size()]; for (int i = 0; i < pointList.size(); i++) { againPoints[i] = pointList.get(i); } return selectPoint(new MatOfPoint2f(againPoints), selectTimes + 1); } } return outDpMat; } /** 对顶点进行排序 */ private static Point[] sortPointClockwise(Point[] points) { if (points.length != 4) { return points; } Point unFoundPoint = new Point(); Point[] result = {unFoundPoint, unFoundPoint, unFoundPoint, unFoundPoint}; long minDistance = -1; for (Point point : points) { long distance = (long) (point.x * point.x + point.y * point.y); if (minDistance == -1 || distance < minDistance) { result[0] = point; minDistance = distance; } } if (result[0] != unFoundPoint) { Point leftTop = result[0]; Point[] p1 = new Point[3]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; p1[i] = point; i++; } if ((pointSideLine(leftTop, p1[0], p1[1]) * pointSideLine(leftTop, p1[0], p1[2])) < 0) { result[2] = p1[0]; } else if ((pointSideLine(leftTop, p1[1], p1[0]) * pointSideLine(leftTop, p1[1], p1[2])) < 0) { result[2] = p1[1]; } else if ((pointSideLine(leftTop, p1[2], p1[0]) * pointSideLine(leftTop, p1[2], p1[1])) < 0) { result[2] = p1[2]; } } if (result[0] != unFoundPoint && result[2] != unFoundPoint) { Point leftTop = result[0]; Point rightBottom = result[2]; Point[] p1 = new Point[2]; int i = 0; for (Point point : points) { if (point.x == leftTop.x && point.y == leftTop.y) continue; if (point.x == rightBottom.x && point.y == rightBottom.y) continue; p1[i] = point; i++; } if (pointSideLine(leftTop, rightBottom, p1[0]) > 0) { result[1] = p1[0]; result[3] = p1[1]; } else { result[1] = p1[1]; result[3] = p1[0]; } } if (result[0] != unFoundPoint && result[1] != unFoundPoint && result[2] != unFoundPoint && result[3] != unFoundPoint) { return result; } return points; } private static double pointSideLine(Point lineP1, Point lineP2, Point point) { double x1 = lineP1.x; double y1 = lineP1.y; double x2 = lineP2.x; double y2 = lineP2.y; double x = point.x; double y = point.y; return (x - x1)*(y2 - y1) - (y - y1)*(x2 - x1); } }
false
2,294
10
2,478
12
2,611
8
2,479
12
2,927
12
false
false
false
false
false
true
29762_1
package Ai; import control.GameControl; import dto.GameInfo; import dto.Grassman; import music.Player; public class Ai { private GameControl gameControl; private GameInfo info; private Grassman aiMan; private int moveDirection; private int offendDirection; public Ai(GameControl gameControl){ this.gameControl = gameControl; } /* * 默认先移动后攻击 */ public void judgeAction(){ //获取游戏信息 this.info=gameControl.getGameInfo(); //获得当前人物 this.aiMan=gameControl.getGrassman(); //随机移动方向 0 1 2 3 上 下 左 右 moveDirection=(int) (Math.random() * 4); doAction(moveDirection); //攻击方向 //随机攻击方向4 5 6 7 上 下 左 右 offendDirection=(int) (Math.random() * 4+4); //判断四个方向是否有敌人 if(isExistUpEnemy(this.gameControl.judgeWeapon())){ offendDirection=4; } if(isExistDownEnemy(this.gameControl.judgeWeapon())){ offendDirection=5; } if(isExistLeftEnemy(this.gameControl.judgeWeapon())){ offendDirection=6; } if(isExistRightEnemy(this.gameControl.judgeWeapon())){ offendDirection=7; } doAction(offendDirection); } /* * 判断攻击范围内是否有敌人 */ private boolean isExistUpEnemy(int weapon){ //向上有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistDownEnemy(int weapon){ //向下有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistLeftEnemy(int weapon){ //向左有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistRightEnemy(int weapon){ //向右有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } public void doAction(int cmd){ Player.playSound("攻击"); switch(cmd){ case 0: if (this.gameControl.canMove()) { this.gameControl.KeyUp(); // System.out.println(0); } break; case 1: if (this.gameControl.canMove()) { this.gameControl.KeyDown(); // System.out.println(1); } break; case 2: if (this.gameControl.canMove()) { this.gameControl.KeyLeft(); // System.out.println(2); } break; case 3: if (this.gameControl.canMove()) { this.gameControl.KeyRight(); // System.out.println(3); } case 4: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendUp(); // System.out.println(4); } break; case 5: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendDown(); // System.out.println(5); } break; case 6: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendLeft(); // System.out.println(6); } break; case 7: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendRight(); // System.out.println(7); } break; default: System.out.println("出错啦! 你这个大笨蛋!"); break; } } }
ELCyber/GrassCraft
src/Ai/Ai.java
2,176
//获取游戏信息
line_comment
zh-cn
package Ai; import control.GameControl; import dto.GameInfo; import dto.Grassman; import music.Player; public class Ai { private GameControl gameControl; private GameInfo info; private Grassman aiMan; private int moveDirection; private int offendDirection; public Ai(GameControl gameControl){ this.gameControl = gameControl; } /* * 默认先移动后攻击 */ public void judgeAction(){ //获取 <SUF> this.info=gameControl.getGameInfo(); //获得当前人物 this.aiMan=gameControl.getGrassman(); //随机移动方向 0 1 2 3 上 下 左 右 moveDirection=(int) (Math.random() * 4); doAction(moveDirection); //攻击方向 //随机攻击方向4 5 6 7 上 下 左 右 offendDirection=(int) (Math.random() * 4+4); //判断四个方向是否有敌人 if(isExistUpEnemy(this.gameControl.judgeWeapon())){ offendDirection=4; } if(isExistDownEnemy(this.gameControl.judgeWeapon())){ offendDirection=5; } if(isExistLeftEnemy(this.gameControl.judgeWeapon())){ offendDirection=6; } if(isExistRightEnemy(this.gameControl.judgeWeapon())){ offendDirection=7; } doAction(offendDirection); } /* * 判断攻击范围内是否有敌人 */ private boolean isExistUpEnemy(int weapon){ //向上有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistDownEnemy(int weapon){ //向下有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOx()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOx()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOy()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOx()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOy()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistLeftEnemy(int weapon){ //向左有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() - aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() -aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() +aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() - this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() + this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } private boolean isExistRightEnemy(int weapon){ //向右有敌人 for (int i = 0; i < 7; i++) { if (aiMan.getOx()[weapon][i] != 0 || aiMan.getOy()[weapon][i] != 0) { // 该判断为攻击范围是否越界 if (this.aiMan.getXPosition() + aiMan.getOy()[weapon][i] < 0 || this.aiMan.getXPosition() +aiMan.getOy()[weapon][i] > 9 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] < 0 || this.aiMan.getYPosition() -aiMan.getOx()[weapon][i] > 9) { continue; } if ((info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] < 4) && (info.map[this.aiMan.getXPosition() + this.aiMan.getOy()[weapon][i]][this.aiMan.getYPosition() - this.aiMan.getOx()[weapon][i]] > 0)) { return true; } else { return false; } } } return false; } public void doAction(int cmd){ Player.playSound("攻击"); switch(cmd){ case 0: if (this.gameControl.canMove()) { this.gameControl.KeyUp(); // System.out.println(0); } break; case 1: if (this.gameControl.canMove()) { this.gameControl.KeyDown(); // System.out.println(1); } break; case 2: if (this.gameControl.canMove()) { this.gameControl.KeyLeft(); // System.out.println(2); } break; case 3: if (this.gameControl.canMove()) { this.gameControl.KeyRight(); // System.out.println(3); } case 4: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendUp(); // System.out.println(4); } break; case 5: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendDown(); // System.out.println(5); } break; case 6: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendLeft(); // System.out.println(6); } break; case 7: if(this.gameControl.canOffend()){ this.gameControl.KeyOffendRight(); // System.out.println(7); } break; default: System.out.println("出错啦! 你这个大笨蛋!"); break; } } }
false
1,880
4
2,176
4
2,196
4
2,176
4
2,911
11
false
false
false
false
false
true
57884_2
package io.github.emanual.app.ui; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.Toast; import com.loopj.android.http.AsyncHttpResponseHandler; import java.io.File; import java.io.IOException; import java.util.List; import butterknife.Bind; import cz.msebera.android.httpclient.Header; import de.greenrobot.event.EventBus; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.api.EmanualAPI; import io.github.emanual.app.entity.FeedsItemEntity; import io.github.emanual.app.ui.adapter.FeedsListAdapter; import io.github.emanual.app.ui.base.activity.SwipeRefreshActivity; import io.github.emanual.app.ui.event.InterviewDownloadEndEvent; import io.github.emanual.app.ui.event.InterviewDownloadFaildEvent; import io.github.emanual.app.ui.event.InterviewDownloadProgressEvent; import io.github.emanual.app.ui.event.InterviewDownloadStartEvent; import io.github.emanual.app.ui.event.UnPackFinishEvent; import io.github.emanual.app.utils.AppPath; import io.github.emanual.app.utils.SwipeRefreshLayoutUtils; import io.github.emanual.app.utils.ZipUtils; import timber.log.Timber; public class InterviewFeedsActivity extends SwipeRefreshActivity { ProgressDialog mProgressDialog; @Bind(R.id.recyclerView) RecyclerView recyclerView; @Override protected void initData(Bundle savedInstanceState) { } @Override protected void initLayout(Bundle savedInstanceState) { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.acty_feeds_list); mProgressDialog = new ProgressDialog(getContext()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); fetchData(); } @Override protected int getContentViewId() { return R.layout.acty_interview_feeds; } @Override public void onRefresh() { // EmanualAPI.getIn fetchData(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadStart(InterviewDownloadStartEvent event) { mProgressDialog.setTitle("正在下载.."); mProgressDialog.setProgress(0); mProgressDialog.setMax(100); mProgressDialog.show(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadProgress(InterviewDownloadProgressEvent event) { Timber.d(event.getBytesWritten() + "/" + event.getTotalSize()); mProgressDialog.setMessage(String.format("大小:%.2f M", 1.0 * event.getTotalSize() / 1024 / 1024)); mProgressDialog.setMax((int) event.getTotalSize()); mProgressDialog.setProgress((int) event.getBytesWritten()); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadFaild(InterviewDownloadFaildEvent event) { Toast.makeText(getContext(), "出错了,错误码:" + event.getStatusCode(), Toast.LENGTH_LONG).show(); mProgressDialog.dismiss(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadEnd2(InterviewDownloadEndEvent event) { mProgressDialog.setTitle("正在解压.."); } /** * 下载完毕 * @param event */ @Subscribe(threadMode = ThreadMode.Async) public void onDownloadEnd(InterviewDownloadEndEvent event) { try { ZipUtils.unZipFiles(event.getFile().getAbsolutePath(), AppPath.getInterviewsPath(getContext()) + File.separator + event.getFeedsItemEntity().getName() + File.separator); //删除压缩包 if (event.getFile().exists()) { event.getFile().delete(); } } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new UnPackFinishEvent(e)); return; } EventBus.getDefault().post(new UnPackFinishEvent(null)); } @Subscribe(threadMode = ThreadMode.MainThread) public void onUnpackFinishEvent(UnPackFinishEvent event) { if (event.getException() != null) { toast(event.getException().getMessage()); return; } toast("下载并解压成功"); mProgressDialog.dismiss(); } private void fetchData() { EmanualAPI.getInterviewFeeds(new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), true); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { List<FeedsItemEntity> feeds = FeedsItemEntity.createByJSONArray(new String(responseBody), FeedsItemEntity.class); Timber.d(feeds.toString()); recyclerView.setAdapter(new FeedsListAdapter(getContext(), feeds, FeedsListAdapter.TYPE_INTERVIEW)); } catch (Exception e) { toast("哎呀,网络异常!"); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } @Override public void onFinish() { super.onFinish(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), false); } @Override public void onProgress(long bytesWritten, long totalSize) { super.onProgress(bytesWritten, totalSize); } }); } }
EManual/EManual-Android
app/src/main/java/io/github/emanual/app/ui/InterviewFeedsActivity.java
1,433
//删除压缩包
line_comment
zh-cn
package io.github.emanual.app.ui; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.Toast; import com.loopj.android.http.AsyncHttpResponseHandler; import java.io.File; import java.io.IOException; import java.util.List; import butterknife.Bind; import cz.msebera.android.httpclient.Header; import de.greenrobot.event.EventBus; import de.greenrobot.event.Subscribe; import de.greenrobot.event.ThreadMode; import io.github.emanual.app.R; import io.github.emanual.app.api.EmanualAPI; import io.github.emanual.app.entity.FeedsItemEntity; import io.github.emanual.app.ui.adapter.FeedsListAdapter; import io.github.emanual.app.ui.base.activity.SwipeRefreshActivity; import io.github.emanual.app.ui.event.InterviewDownloadEndEvent; import io.github.emanual.app.ui.event.InterviewDownloadFaildEvent; import io.github.emanual.app.ui.event.InterviewDownloadProgressEvent; import io.github.emanual.app.ui.event.InterviewDownloadStartEvent; import io.github.emanual.app.ui.event.UnPackFinishEvent; import io.github.emanual.app.utils.AppPath; import io.github.emanual.app.utils.SwipeRefreshLayoutUtils; import io.github.emanual.app.utils.ZipUtils; import timber.log.Timber; public class InterviewFeedsActivity extends SwipeRefreshActivity { ProgressDialog mProgressDialog; @Bind(R.id.recyclerView) RecyclerView recyclerView; @Override protected void initData(Bundle savedInstanceState) { } @Override protected void initLayout(Bundle savedInstanceState) { setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.acty_feeds_list); mProgressDialog = new ProgressDialog(getContext()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); fetchData(); } @Override protected int getContentViewId() { return R.layout.acty_interview_feeds; } @Override public void onRefresh() { // EmanualAPI.getIn fetchData(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadStart(InterviewDownloadStartEvent event) { mProgressDialog.setTitle("正在下载.."); mProgressDialog.setProgress(0); mProgressDialog.setMax(100); mProgressDialog.show(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadProgress(InterviewDownloadProgressEvent event) { Timber.d(event.getBytesWritten() + "/" + event.getTotalSize()); mProgressDialog.setMessage(String.format("大小:%.2f M", 1.0 * event.getTotalSize() / 1024 / 1024)); mProgressDialog.setMax((int) event.getTotalSize()); mProgressDialog.setProgress((int) event.getBytesWritten()); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadFaild(InterviewDownloadFaildEvent event) { Toast.makeText(getContext(), "出错了,错误码:" + event.getStatusCode(), Toast.LENGTH_LONG).show(); mProgressDialog.dismiss(); } @Subscribe(threadMode = ThreadMode.MainThread) public void onDownloadEnd2(InterviewDownloadEndEvent event) { mProgressDialog.setTitle("正在解压.."); } /** * 下载完毕 * @param event */ @Subscribe(threadMode = ThreadMode.Async) public void onDownloadEnd(InterviewDownloadEndEvent event) { try { ZipUtils.unZipFiles(event.getFile().getAbsolutePath(), AppPath.getInterviewsPath(getContext()) + File.separator + event.getFeedsItemEntity().getName() + File.separator); //删除 <SUF> if (event.getFile().exists()) { event.getFile().delete(); } } catch (IOException e) { e.printStackTrace(); EventBus.getDefault().post(new UnPackFinishEvent(e)); return; } EventBus.getDefault().post(new UnPackFinishEvent(null)); } @Subscribe(threadMode = ThreadMode.MainThread) public void onUnpackFinishEvent(UnPackFinishEvent event) { if (event.getException() != null) { toast(event.getException().getMessage()); return; } toast("下载并解压成功"); mProgressDialog.dismiss(); } private void fetchData() { EmanualAPI.getInterviewFeeds(new AsyncHttpResponseHandler() { @Override public void onStart() { super.onStart(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), true); } @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { try { List<FeedsItemEntity> feeds = FeedsItemEntity.createByJSONArray(new String(responseBody), FeedsItemEntity.class); Timber.d(feeds.toString()); recyclerView.setAdapter(new FeedsListAdapter(getContext(), feeds, FeedsListAdapter.TYPE_INTERVIEW)); } catch (Exception e) { toast("哎呀,网络异常!"); } } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { } @Override public void onFinish() { super.onFinish(); SwipeRefreshLayoutUtils.setRefreshing(getSwipeRefreshLayout(), false); } @Override public void onProgress(long bytesWritten, long totalSize) { super.onProgress(bytesWritten, totalSize); } }); } }
false
1,133
4
1,433
4
1,435
4
1,433
4
1,712
10
false
false
false
false
false
true
40957_21
package com.cn.main; import com.cn.util.HttpClientUtil; import org.apache.commons.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class nyaPictureMain { //存放目录 private static String fileSource = "E://nyaManhua//new//"; public static void main(String[] args) throws Exception { List<String> urlList = new ArrayList<String>(); //地址 urlList.add("https://zha.doghentai.com/g/338012/"); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); nyaPictureMain.crawlerNyaUrl(urlList); String exSite = "cmd /c start " + fileSource ; Runtime.getRuntime().exec(exSite); } public static void crawlerNyaPic(int picSum,String fileUrl,String intputFile,String suffix){ try { for (int i = 1; i <= picSum; i++) { // suffix = ".jpg"; //随时替换文件格式 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例 HttpGet httpGet = new HttpGet(fileUrl+i+suffix); // 创建Httpget实例 //设置Http报文头信息 httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"); httpGet.setHeader("accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"); httpGet.setHeader("accept-encoding", "gzip, deflate, br"); httpGet.setHeader("referer", "https://zha.doghentai.com/"); httpGet.setHeader("sec-fetch-dest", "image"); httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8"); HttpHost proxy = new HttpHost("127.0.0.1", 7890); //超时时间单位为毫秒 RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(1000).setSocketTimeout(30000) .setProxy(proxy).build(); httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build(); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); // 执行http get请求 HttpEntity entity = response.getEntity(); // 获取返回实体 if(null != entity){ InputStream inputStream = entity.getContent();//返回一个输入流 //输出图片 FileUtils.copyInputStreamToFile(inputStream, new File(intputFile+i+suffix));//引用org.apache.commons.io.FileUtils System.out.println(i+suffix); } response.close(); // 关闭response httpClient.close(); // 关闭HttpClient实体 } }catch (Exception e){ System.out.println(e); } } public static void crawlerNyaUrl(List<String> urlList) throws Exception { Integer rateDow = 1; for(String url:urlList){ String html = ""; if(url.length() != 0){ html = HttpClientUtil.getSource(url); Document document = Jsoup.parse(html); Element element = document.selectFirst("div.container").selectFirst("a"); String coverImgUrl = element.select("img").attr("data-src"); //获取图片载点 String[] ourStr = coverImgUrl.split("/"); //获取后缀 String[] oursuffix = coverImgUrl.split("\\."); //获取数量 Elements picSum = document.select("div.thumb-container"); //获取本子名字 String benziName = element.select("img").attr("alt"); benziName = benziName.replaceAll("\\?","").replaceAll(":","").replaceAll(" ","").replaceAll("\\*",""); int count = picSum.size(); int benziN = Integer.parseInt(ourStr[ourStr.length-2]); String suffix = "."+oursuffix[oursuffix.length-1]; String fileUrl = "https://i0.nyacdn.com/galleries/"+benziN+"/"; String intputFile = fileSource +benziName +"//"; nyaPictureMain.crawlerNyaPic(count,fileUrl,intputFile,suffix); //缓存完后暂停几秒 Thread.sleep(3000); } } System.out.println("喵变态图片缓存成功!!!!"); } }
ERYhua/nyaHentaiCrawler
src/main/java/com/cn/main/nyaPictureMain.java
1,357
//缓存完后暂停几秒
line_comment
zh-cn
package com.cn.main; import com.cn.util.HttpClientUtil; import org.apache.commons.io.FileUtils; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; public class nyaPictureMain { //存放目录 private static String fileSource = "E://nyaManhua//new//"; public static void main(String[] args) throws Exception { List<String> urlList = new ArrayList<String>(); //地址 urlList.add("https://zha.doghentai.com/g/338012/"); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); urlList.add(""); nyaPictureMain.crawlerNyaUrl(urlList); String exSite = "cmd /c start " + fileSource ; Runtime.getRuntime().exec(exSite); } public static void crawlerNyaPic(int picSum,String fileUrl,String intputFile,String suffix){ try { for (int i = 1; i <= picSum; i++) { // suffix = ".jpg"; //随时替换文件格式 CloseableHttpClient httpClient = HttpClients.createDefault(); // 创建HttpClient实例 HttpGet httpGet = new HttpGet(fileUrl+i+suffix); // 创建Httpget实例 //设置Http报文头信息 httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"); httpGet.setHeader("accept", "image/avif,image/webp,image/apng,image/*,*/*;q=0.8"); httpGet.setHeader("accept-encoding", "gzip, deflate, br"); httpGet.setHeader("referer", "https://zha.doghentai.com/"); httpGet.setHeader("sec-fetch-dest", "image"); httpGet.setHeader("accept-language", "zh-CN,zh;q=0.9,en;q=0.8"); HttpHost proxy = new HttpHost("127.0.0.1", 7890); //超时时间单位为毫秒 RequestConfig defaultRequestConfig = RequestConfig.custom() .setConnectTimeout(1000).setSocketTimeout(30000) .setProxy(proxy).build(); httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build(); CloseableHttpResponse response = null; response = httpClient.execute(httpGet); // 执行http get请求 HttpEntity entity = response.getEntity(); // 获取返回实体 if(null != entity){ InputStream inputStream = entity.getContent();//返回一个输入流 //输出图片 FileUtils.copyInputStreamToFile(inputStream, new File(intputFile+i+suffix));//引用org.apache.commons.io.FileUtils System.out.println(i+suffix); } response.close(); // 关闭response httpClient.close(); // 关闭HttpClient实体 } }catch (Exception e){ System.out.println(e); } } public static void crawlerNyaUrl(List<String> urlList) throws Exception { Integer rateDow = 1; for(String url:urlList){ String html = ""; if(url.length() != 0){ html = HttpClientUtil.getSource(url); Document document = Jsoup.parse(html); Element element = document.selectFirst("div.container").selectFirst("a"); String coverImgUrl = element.select("img").attr("data-src"); //获取图片载点 String[] ourStr = coverImgUrl.split("/"); //获取后缀 String[] oursuffix = coverImgUrl.split("\\."); //获取数量 Elements picSum = document.select("div.thumb-container"); //获取本子名字 String benziName = element.select("img").attr("alt"); benziName = benziName.replaceAll("\\?","").replaceAll(":","").replaceAll(" ","").replaceAll("\\*",""); int count = picSum.size(); int benziN = Integer.parseInt(ourStr[ourStr.length-2]); String suffix = "."+oursuffix[oursuffix.length-1]; String fileUrl = "https://i0.nyacdn.com/galleries/"+benziN+"/"; String intputFile = fileSource +benziName +"//"; nyaPictureMain.crawlerNyaPic(count,fileUrl,intputFile,suffix); //缓存 <SUF> Thread.sleep(3000); } } System.out.println("喵变态图片缓存成功!!!!"); } }
false
1,160
8
1,357
8
1,404
7
1,357
8
1,662
19
false
false
false
false
false
true
50426_10
package exp.libs.ui.cpt.win; import exp.libs.utils.concurrent.ThreadUtils; /** * <PRE> * swing右下角通知窗口 * (使用_show方法显示窗体, 可触发自动渐隐消失) * </PRE> * <br/><B>PROJECT : </B> exp-libs * <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a> * @version 2022-03-06 * @author EXP: [email protected] * @since JDK 1.8+ */ @SuppressWarnings("serial") public abstract class NoticeWindow extends PopChildWindow implements Runnable { private Thread _this; private boolean isRun = false; protected NoticeWindow() { super("NoticeWindow"); } protected NoticeWindow(String name) { super(name); } protected NoticeWindow(String name, int width, int height) { super(name, width, height); } protected NoticeWindow(String name, int width, int height, boolean relative) { super(name, width, height, relative); } protected NoticeWindow(String name, int width, int height, boolean relative, Object... args) { super(name, width, height, relative, args); } @Override protected int LOCATION() { return LOCATION_RB; // 出现坐标为右下角 } @Override protected boolean WIN_ON_TOP() { return true; // 设置窗口置顶 } /** * 以渐隐方式显示通知消息 */ @Override protected final void AfterView() { if(isRun == false) { isRun = true; _this = new Thread(this); _this.start(); // 渐隐窗体 } } @Deprecated @Override protected final void beforeHide() { // Undo } @Override public void run() { ThreadUtils.tSleep(2000); // 悬停2秒 // 透明度渐隐(大约持续3秒) for(float opacity = 100; opacity > 0; opacity -= 2) { this.setOpacity(opacity / 100); // 设置透明度 ThreadUtils.tSleep(60); if(isVisible() == false) { break; // 窗体被提前销毁了(手工点了X) } } _hide(); // 销毁窗体 } /** * 阻塞等待渐隐关闭过程 */ public void _join() { if(_this == null) { return; } try { _this.join(); } catch (Exception e) {} } }
EXP-Codes/exp-libs-refactor
exp-libs-ui/src/main/java/exp/libs/ui/cpt/win/NoticeWindow.java
724
// 销毁窗体
line_comment
zh-cn
package exp.libs.ui.cpt.win; import exp.libs.utils.concurrent.ThreadUtils; /** * <PRE> * swing右下角通知窗口 * (使用_show方法显示窗体, 可触发自动渐隐消失) * </PRE> * <br/><B>PROJECT : </B> exp-libs * <br/><B>SUPPORT : </B> <a href="https://exp-blog.com" target="_blank">https://exp-blog.com</a> * @version 2022-03-06 * @author EXP: [email protected] * @since JDK 1.8+ */ @SuppressWarnings("serial") public abstract class NoticeWindow extends PopChildWindow implements Runnable { private Thread _this; private boolean isRun = false; protected NoticeWindow() { super("NoticeWindow"); } protected NoticeWindow(String name) { super(name); } protected NoticeWindow(String name, int width, int height) { super(name, width, height); } protected NoticeWindow(String name, int width, int height, boolean relative) { super(name, width, height, relative); } protected NoticeWindow(String name, int width, int height, boolean relative, Object... args) { super(name, width, height, relative, args); } @Override protected int LOCATION() { return LOCATION_RB; // 出现坐标为右下角 } @Override protected boolean WIN_ON_TOP() { return true; // 设置窗口置顶 } /** * 以渐隐方式显示通知消息 */ @Override protected final void AfterView() { if(isRun == false) { isRun = true; _this = new Thread(this); _this.start(); // 渐隐窗体 } } @Deprecated @Override protected final void beforeHide() { // Undo } @Override public void run() { ThreadUtils.tSleep(2000); // 悬停2秒 // 透明度渐隐(大约持续3秒) for(float opacity = 100; opacity > 0; opacity -= 2) { this.setOpacity(opacity / 100); // 设置透明度 ThreadUtils.tSleep(60); if(isVisible() == false) { break; // 窗体被提前销毁了(手工点了X) } } _hide(); // 销毁 <SUF> } /** * 阻塞等待渐隐关闭过程 */ public void _join() { if(_this == null) { return; } try { _this.join(); } catch (Exception e) {} } }
false
622
6
724
7
737
5
724
7
921
12
false
false
false
false
false
true
23210_2
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * @author yangda * @description: * @create 2023-05-21-14:53 */ public class MyTomcat { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); int i = 0; while (!serverSocket.isClosed()){ // 如果serverSocket 没有关闭 System.out.println("f服务器等待连接、、、" + ++i); // 等待浏览器/客户端连接,得到socket // 该socket用于通信 Socket socket = serverSocket.accept(); // 拿到 和socket相关的输出流 OutputStream outputStream = socket.getOutputStream(); FileReader fileReader = new FileReader("src/hello.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); String buf = ""; while ((buf = bufferedReader.readLine()) != null){ outputStream.write(buf.getBytes()); } // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); // outputStream.write("hello i am server".getBytes()); System.out.println("信息以打入管道" ); outputStream.close(); socket.close(); } serverSocket.close(); } }
EXsYang/mycode
javaweb/tomcat/src/MyTomcat.java
311
// 等待浏览器/客户端连接,得到socket
line_comment
zh-cn
import java.io.*; import java.net.ServerSocket; import java.net.Socket; /** * @author yangda * @description: * @create 2023-05-21-14:53 */ public class MyTomcat { public static void main(String[] args) throws IOException { ServerSocket serverSocket = new ServerSocket(9999); int i = 0; while (!serverSocket.isClosed()){ // 如果serverSocket 没有关闭 System.out.println("f服务器等待连接、、、" + ++i); // 等待 <SUF> // 该socket用于通信 Socket socket = serverSocket.accept(); // 拿到 和socket相关的输出流 OutputStream outputStream = socket.getOutputStream(); FileReader fileReader = new FileReader("src/hello.html"); BufferedReader bufferedReader = new BufferedReader(fileReader); String buf = ""; while ((buf = bufferedReader.readLine()) != null){ outputStream.write(buf.getBytes()); } // BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream)); // outputStream.write("hello i am server".getBytes()); System.out.println("信息以打入管道" ); outputStream.close(); socket.close(); } serverSocket.close(); } }
false
274
12
311
10
315
10
311
10
390
25
false
false
false
false
false
true
36401_4
package name.ealen.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Set; /** * Created by EalenXie on 2018/10/16 16:13. * 典型的 多层级 分类 * <p> * :@NamedEntityGraph :注解在实体上 , 解决典型的N+1问题 * name表示实体图名, 与 repository中的注解 @EntityGraph的value属性相对应, * attributeNodes 表示被标注要懒加载的属性节点 比如此例中 : 要懒加载的子分类集合children */ @Entity @Table(name = "jpa_category") @NamedEntityGraphs({ @NamedEntityGraph(name = "Category.findAll", attributeNodes = {@NamedAttributeNode("children")}), @NamedEntityGraph(name = "Category.findByParent", attributeNodes = {@NamedAttributeNode(value = "children", subgraph = "son")}, //一级延伸 subgraphs = {@NamedSubgraph(name = "son", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "grandson")), //二级延伸 @NamedSubgraph(name = "grandson", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "greatGrandSon")), //三级延伸 @NamedSubgraph(name = "greatGrandSon", attributeNodes = @NamedAttributeNode(value = "children"))}) //四级延伸 // 有多少次延伸,就有多少个联表关系,自身关联的表设计中,子节点是可以无限延伸的,所以关联数可能查询的..... }) public class Category { /** * Id 使用UUID生成策略 */ @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") private String id; /** * 分类名 */ private String name; /** * 一个商品分类下面可能有多个商品子分类(多级) 比如 分类 : 家用电器 (子)分类 : 电脑 (孙)子分类 : 笔记本电脑 */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") @JsonIgnore private Category parent; //父分类 @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) private Set<Category> children; //子分类集合 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getParent() { return parent; } public void setParent(Category parent) { this.parent = parent; } public Set<Category> getChildren() { return children; } public void setChildren(Set<Category> children) { this.children = children; } }
EalenXie/springboot-jpa-N-plus-One
src/main/java/name/ealen/entity/Category.java
743
//四级延伸
line_comment
zh-cn
package name.ealen.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Set; /** * Created by EalenXie on 2018/10/16 16:13. * 典型的 多层级 分类 * <p> * :@NamedEntityGraph :注解在实体上 , 解决典型的N+1问题 * name表示实体图名, 与 repository中的注解 @EntityGraph的value属性相对应, * attributeNodes 表示被标注要懒加载的属性节点 比如此例中 : 要懒加载的子分类集合children */ @Entity @Table(name = "jpa_category") @NamedEntityGraphs({ @NamedEntityGraph(name = "Category.findAll", attributeNodes = {@NamedAttributeNode("children")}), @NamedEntityGraph(name = "Category.findByParent", attributeNodes = {@NamedAttributeNode(value = "children", subgraph = "son")}, //一级延伸 subgraphs = {@NamedSubgraph(name = "son", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "grandson")), //二级延伸 @NamedSubgraph(name = "grandson", attributeNodes = @NamedAttributeNode(value = "children", subgraph = "greatGrandSon")), //三级延伸 @NamedSubgraph(name = "greatGrandSon", attributeNodes = @NamedAttributeNode(value = "children"))}) //四级 <SUF> // 有多少次延伸,就有多少个联表关系,自身关联的表设计中,子节点是可以无限延伸的,所以关联数可能查询的..... }) public class Category { /** * Id 使用UUID生成策略 */ @Id @GeneratedValue(generator = "UUID") @GenericGenerator(name = "UUID", strategy = "org.hibernate.id.UUIDGenerator") private String id; /** * 分类名 */ private String name; /** * 一个商品分类下面可能有多个商品子分类(多级) 比如 分类 : 家用电器 (子)分类 : 电脑 (孙)子分类 : 笔记本电脑 */ @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "parent_id") @JsonIgnore private Category parent; //父分类 @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY) private Set<Category> children; //子分类集合 public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getParent() { return parent; } public void setParent(Category parent) { this.parent = parent; } public Set<Category> getChildren() { return children; } public void setChildren(Set<Category> children) { this.children = children; } }
false
658
3
743
6
736
4
743
6
949
11
false
false
false
false
false
true
41467_46
package leetcode.One.Thousand.boxDelivering; //你有一辆货运卡车,你需要用这一辆车把一些箱子从仓库运送到码头。这辆卡车每次运输有 箱子数目的限制 和 总重量的限制 。 // // 给你一个箱子数组 boxes 和三个整数 portsCount, maxBoxes 和 maxWeight ,其中 boxes[i] = [portsi, // weighti] 。 // // // portsi 表示第 i 个箱子需要送达的码头, weightsi 是第 i 个箱子的重量。 // portsCount 是码头的数目。 // maxBoxes 和 maxWeight 分别是卡车每趟运输箱子数目和重量的限制。 // // // 箱子需要按照 数组顺序 运输,同时每次运输需要遵循以下步骤: // // // 卡车从 boxes 队列中按顺序取出若干个箱子,但不能违反 maxBoxes 和 maxWeight 限制。 // 对于在卡车上的箱子,我们需要 按顺序 处理它们,卡车会通过 一趟行程 将最前面的箱子送到目的地码头并卸货。如果卡车已经在对应的码头,那么不需要 额外行程 //,箱子也会立马被卸货。 // 卡车上所有箱子都被卸货后,卡车需要 一趟行程 回到仓库,从箱子队列里再取出一些箱子。 // // // 卡车在将所有箱子运输并卸货后,最后必须回到仓库。 // // 请你返回将所有箱子送到相应码头的 最少行程 次数。 // // // // 示例 1: // // 输入:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 //输出:4 //解释:最优策略如下: //- 卡车将所有箱子装上车,到达码头 1 ,然后去码头 2 ,然后再回到码头 1 ,最后回到仓库,总共需要 4 趟行程。 //所以总行程数为 4 。 //注意到第一个和第三个箱子不能同时被卸货,因为箱子需要按顺序处理(也就是第二个箱子需要先被送到码头 2 ,然后才能处理第三个箱子)。 // // // 示例 2: // // 输入:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, //maxWeight = 6 //输出:6 //解释:最优策略如下: //- 卡车首先运输第一个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二、第三、第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五个箱子,到达码头 3 ,回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 3: // // 输入:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = //6, maxWeight = 7 //输出:6 //解释:最优策略如下: //- 卡车运输第一和第二个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五和第六个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 4: // // 输入:boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], //portsCount = 5, maxBoxes = 5, maxWeight = 7 //输出:14 //解释:最优策略如下: //- 卡车运输第一个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第六和第七个箱子,到达码头 3 ,然后去码头 4 ,然后回到仓库,总共 3 趟行程。 //- 卡车运输第八和第九个箱子,到达码头 1 ,然后去码头 5 ,然后回到仓库,总共 3 趟行程。 //总行程数为 2 + 2 + 2 + 2 + 3 + 3 = 14 。 // // // // // 提示: // // // 1 <= boxes.length <= 10⁵ // 1 <= portsCount, maxBoxes, maxWeight <= 10⁵ // 1 <= portsi <= portsCount // 1 <= weightsi <= maxWeight // // Related Topics 线段树 队列 数组 动态规划 单调队列 堆(优先队列) 👍 106 👎 0 import java.util.ArrayDeque; import java.util.Deque; /** * @Desc: * @Author: 泽露 * @Date: 2022/12/5 5:22 PM * @Version: 1.initial version; 2022/12/5 5:22 PM */ public class Solution { public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { int n = boxes.length; int[] p = new int[n + 1]; int[] w = new int[n + 1]; int[] neg = new int[n + 1]; long[] W = new long[n + 1]; for (int i = 1; i <= n; ++i) { p[i] = boxes[i - 1][0]; w[i] = boxes[i - 1][1]; if (i > 1) { neg[i] = neg[i - 1] + (p[i - 1] != p[i] ? 1 : 0); } W[i] = W[i - 1] + w[i]; } Deque<Integer> opt = new ArrayDeque<Integer>(); opt.offerLast(0); int[] f = new int[n + 1]; int[] g = new int[n + 1]; for (int i = 1; i <= n; ++i) { while (i - opt.peekFirst() > maxBoxes || W[i] - W[opt.peekFirst()] > maxWeight) { opt.pollFirst(); } f[i] = g[opt.peekFirst()] + neg[i] + 2; if (i != n) { g[i] = f[i] - neg[i + 1]; while (!opt.isEmpty() && g[i] <= g[opt.peekLast()]) { opt.pollLast(); } opt.offerLast(i); } } return f[n]; } }
EarWheat/LeetCode
src/main/java/leetcode/One/Thousand/boxDelivering/Solution.java
1,965
//- 卡车运输第五个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。
line_comment
zh-cn
package leetcode.One.Thousand.boxDelivering; //你有一辆货运卡车,你需要用这一辆车把一些箱子从仓库运送到码头。这辆卡车每次运输有 箱子数目的限制 和 总重量的限制 。 // // 给你一个箱子数组 boxes 和三个整数 portsCount, maxBoxes 和 maxWeight ,其中 boxes[i] = [portsi, // weighti] 。 // // // portsi 表示第 i 个箱子需要送达的码头, weightsi 是第 i 个箱子的重量。 // portsCount 是码头的数目。 // maxBoxes 和 maxWeight 分别是卡车每趟运输箱子数目和重量的限制。 // // // 箱子需要按照 数组顺序 运输,同时每次运输需要遵循以下步骤: // // // 卡车从 boxes 队列中按顺序取出若干个箱子,但不能违反 maxBoxes 和 maxWeight 限制。 // 对于在卡车上的箱子,我们需要 按顺序 处理它们,卡车会通过 一趟行程 将最前面的箱子送到目的地码头并卸货。如果卡车已经在对应的码头,那么不需要 额外行程 //,箱子也会立马被卸货。 // 卡车上所有箱子都被卸货后,卡车需要 一趟行程 回到仓库,从箱子队列里再取出一些箱子。 // // // 卡车在将所有箱子运输并卸货后,最后必须回到仓库。 // // 请你返回将所有箱子送到相应码头的 最少行程 次数。 // // // // 示例 1: // // 输入:boxes = [[1,1],[2,1],[1,1]], portsCount = 2, maxBoxes = 3, maxWeight = 3 //输出:4 //解释:最优策略如下: //- 卡车将所有箱子装上车,到达码头 1 ,然后去码头 2 ,然后再回到码头 1 ,最后回到仓库,总共需要 4 趟行程。 //所以总行程数为 4 。 //注意到第一个和第三个箱子不能同时被卸货,因为箱子需要按顺序处理(也就是第二个箱子需要先被送到码头 2 ,然后才能处理第三个箱子)。 // // // 示例 2: // // 输入:boxes = [[1,2],[3,3],[3,1],[3,1],[2,4]], portsCount = 3, maxBoxes = 3, //maxWeight = 6 //输出:6 //解释:最优策略如下: //- 卡车首先运输第一个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二、第三、第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五个箱子,到达码头 3 ,回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 3: // // 输入:boxes = [[1,4],[1,2],[2,1],[2,1],[3,2],[3,4]], portsCount = 3, maxBoxes = //6, maxWeight = 7 //输出:6 //解释:最优策略如下: //- 卡车运输第一和第二个箱子,到达码头 1 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第五和第六个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //总行程数为 2 + 2 + 2 = 6 。 // // // 示例 4: // // 输入:boxes = [[2,4],[2,5],[3,1],[3,2],[3,7],[3,1],[4,4],[1,3],[5,2]], //portsCount = 5, maxBoxes = 5, maxWeight = 7 //输出:14 //解释:最优策略如下: //- 卡车运输第一个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第二个箱子,到达码头 2 ,然后回到仓库,总共 2 趟行程。 //- 卡车运输第三和第四个箱子,到达码头 3 ,然后回到仓库,总共 2 趟行程。 //- <SUF> //- 卡车运输第六和第七个箱子,到达码头 3 ,然后去码头 4 ,然后回到仓库,总共 3 趟行程。 //- 卡车运输第八和第九个箱子,到达码头 1 ,然后去码头 5 ,然后回到仓库,总共 3 趟行程。 //总行程数为 2 + 2 + 2 + 2 + 3 + 3 = 14 。 // // // // // 提示: // // // 1 <= boxes.length <= 10⁵ // 1 <= portsCount, maxBoxes, maxWeight <= 10⁵ // 1 <= portsi <= portsCount // 1 <= weightsi <= maxWeight // // Related Topics 线段树 队列 数组 动态规划 单调队列 堆(优先队列) 👍 106 👎 0 import java.util.ArrayDeque; import java.util.Deque; /** * @Desc: * @Author: 泽露 * @Date: 2022/12/5 5:22 PM * @Version: 1.initial version; 2022/12/5 5:22 PM */ public class Solution { public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { int n = boxes.length; int[] p = new int[n + 1]; int[] w = new int[n + 1]; int[] neg = new int[n + 1]; long[] W = new long[n + 1]; for (int i = 1; i <= n; ++i) { p[i] = boxes[i - 1][0]; w[i] = boxes[i - 1][1]; if (i > 1) { neg[i] = neg[i - 1] + (p[i - 1] != p[i] ? 1 : 0); } W[i] = W[i - 1] + w[i]; } Deque<Integer> opt = new ArrayDeque<Integer>(); opt.offerLast(0); int[] f = new int[n + 1]; int[] g = new int[n + 1]; for (int i = 1; i <= n; ++i) { while (i - opt.peekFirst() > maxBoxes || W[i] - W[opt.peekFirst()] > maxWeight) { opt.pollFirst(); } f[i] = g[opt.peekFirst()] + neg[i] + 2; if (i != n) { g[i] = f[i] - neg[i + 1]; while (!opt.isEmpty() && g[i] <= g[opt.peekLast()]) { opt.pollLast(); } opt.offerLast(i); } } return f[n]; } }
false
1,631
26
1,965
35
1,797
27
1,965
35
2,585
49
false
false
false
false
false
true
46861_2
package JavaBasicAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import BrowserDrivers.GetBrowserDriver; //10.27 public class GetWebElementAttributeTesting { public WebDriver driver; @Test public void getWebElementAttributeTest() throws InterruptedException { driver.get("http://www.baidu.com"); String text="比利时遭遇恐怖袭击"; WebElement SearchBox = driver.findElement(By.id("kw")); //将搜索框的id实例化 SearchBox.sendKeys(text); String innerText = SearchBox.getAttribute("value"); //调用attribute方法,并获取搜索框value的值(就是搜索文字的内容) Thread.sleep(3000); Assert.assertEquals(innerText, "比利时遭遇恐怖袭击"); } @BeforeMethod public void beforeMethod() { driver = GetBrowserDriver.GetChromeDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } }
Eason0731/MySeleniumCases
src/JavaBasicAPI/GetWebElementAttributeTesting.java
304
//将搜索框的id实例化
line_comment
zh-cn
package JavaBasicAPI; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.testng.Assert; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import BrowserDrivers.GetBrowserDriver; //10.27 public class GetWebElementAttributeTesting { public WebDriver driver; @Test public void getWebElementAttributeTest() throws InterruptedException { driver.get("http://www.baidu.com"); String text="比利时遭遇恐怖袭击"; WebElement SearchBox = driver.findElement(By.id("kw")); //将搜 <SUF> SearchBox.sendKeys(text); String innerText = SearchBox.getAttribute("value"); //调用attribute方法,并获取搜索框value的值(就是搜索文字的内容) Thread.sleep(3000); Assert.assertEquals(innerText, "比利时遭遇恐怖袭击"); } @BeforeMethod public void beforeMethod() { driver = GetBrowserDriver.GetChromeDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } }
false
238
8
304
8
325
8
304
8
409
14
false
false
false
false
false
true
55510_2
class Solution529 { public char[][] updateBoard(char[][] board, int[] click) { boolean[][] visited = new boolean[board.length][board[0].length]; if (board[click[0]][click[1]] == 'M') { // 规则 1,点到雷改为X退出游戏 board[click[0]][click[1]] = 'X'; } else if (board[click[0]][click[1]] == 'E') { // 只有当点的是未被访问过的格子E才进入递归和判断 dfs(visited, board, click[0], click[1]); } return board; } public void dfs(boolean[][] visited, char[][] board, int x, int y) { // 访问当前结点 visited[x][y] = true; if (count(board, x, y) == 0) { board[x][y] = 'B'; int[] diff = new int[] {-1, 0, 1}; // 访问周围结点 for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length || visited[x + diff[i]][y + diff[j]]) continue; dfs(visited, board, x + diff[i], y + diff[j]); } } else board[x][y] = (char) (count(board, x, y) + '0'); } public int count(char[][] board, int x, int y) { // 确定周围雷的数量 int res = 0; int[] diff = new int[] {-1, 0, 1}; for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length) continue; if (board[x + diff[i]][y + diff[j]] == 'M') res++; } return res; } } /** * 点击的格子是M,直接改为X并退出游戏 * 点击的格子是是B或者数字,什么也不做退出游戏(题解里其实可以加上这个else if的判断) * 点击的格子是E才扩展:计算当前格子周围的雷的数量cnt,决定当前格子从E改为B还是改为数字;若改为数字则终止扩展(这也是为什么示例1还剩一个E),若改为B则继续扩展(遇到E才扩展,遇到B或者数字则终止) */
Echlorine/leetcode-solution
Java/Solution529.java
733
// 访问当前结点
line_comment
zh-cn
class Solution529 { public char[][] updateBoard(char[][] board, int[] click) { boolean[][] visited = new boolean[board.length][board[0].length]; if (board[click[0]][click[1]] == 'M') { // 规则 1,点到雷改为X退出游戏 board[click[0]][click[1]] = 'X'; } else if (board[click[0]][click[1]] == 'E') { // 只有当点的是未被访问过的格子E才进入递归和判断 dfs(visited, board, click[0], click[1]); } return board; } public void dfs(boolean[][] visited, char[][] board, int x, int y) { // 访问 <SUF> visited[x][y] = true; if (count(board, x, y) == 0) { board[x][y] = 'B'; int[] diff = new int[] {-1, 0, 1}; // 访问周围结点 for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length || visited[x + diff[i]][y + diff[j]]) continue; dfs(visited, board, x + diff[i], y + diff[j]); } } else board[x][y] = (char) (count(board, x, y) + '0'); } public int count(char[][] board, int x, int y) { // 确定周围雷的数量 int res = 0; int[] diff = new int[] {-1, 0, 1}; for (int i = 0; i < diff.length; i++) for (int j = 0; j < diff.length; j++) { if (diff[i] == 0 && diff[j] == 0) continue; if (x + diff[i] < 0 || x + diff[i] >= board.length || y + diff[j] < 0 || y + diff[j] >= board[0].length) continue; if (board[x + diff[i]][y + diff[j]] == 'M') res++; } return res; } } /** * 点击的格子是M,直接改为X并退出游戏 * 点击的格子是是B或者数字,什么也不做退出游戏(题解里其实可以加上这个else if的判断) * 点击的格子是E才扩展:计算当前格子周围的雷的数量cnt,决定当前格子从E改为B还是改为数字;若改为数字则终止扩展(这也是为什么示例1还剩一个E),若改为B则继续扩展(遇到E才扩展,遇到B或者数字则终止) */
false
685
7
733
5
739
6
733
5
911
10
false
false
false
false
false
true
66465_14
package alg_02_train_dm._17_day_二叉树二_二刷; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @Author Wuyj * @DateTime 2023-08-10 19:10 * @Version 1.0 */ public class _10_257_binary_tree_paths2 { // KeyPoint 方法二 BFS => 高性能,打败 100 % => 需要掌握 public List<String> binaryTreePaths(TreeNode root) { // 输入: // 1 // / \ // 2 3 // \ // 5 // // 输出: ["1->2->5", "1->3"] List<String> res = new ArrayList<String>(); if (root == null) return res; Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); // 在 BFS 过程中,每遍历一个节点,都会有一个 path 与之对应 // 直到遇到叶子节点,将完整 path 加入到 res 中 Queue<String> pathQueue = new LinkedList<String>(); nodeQueue.offer(root); // KeyPoint 区别:两者 API // 1.Integer.toString() // 2.Integer.parseInt() pathQueue.offer(Integer.toString(root.val)); while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.poll(); String path = pathQueue.poll(); // 叶子节点 if (node.left == null && node.right == null) { res.add(path); // 结束后面循环 continue; } if (node.left != null) { nodeQueue.offer(node.left); // KeyPoint 注意事项 // append(node.left.val),不是 node.left,node.left 表示节点 // 同时,因为对 node.left 已经做了判空,不存在空指针异常 pathQueue.offer(new StringBuilder(path).append("->").append(node.left.val).toString()); } if (node.right != null) { nodeQueue.offer(node.right); pathQueue.offer(new StringBuilder(path).append("->").append(node.right.val).toString()); } } return res; } }
EchoWuyj/LeetCode
LC_douma/src/main/java/alg_02_train_dm/_17_day_二叉树二_二刷/_10_257_binary_tree_paths2.java
565
// 同时,因为对 node.left 已经做了判空,不存在空指针异常
line_comment
zh-cn
package alg_02_train_dm._17_day_二叉树二_二刷; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * @Author Wuyj * @DateTime 2023-08-10 19:10 * @Version 1.0 */ public class _10_257_binary_tree_paths2 { // KeyPoint 方法二 BFS => 高性能,打败 100 % => 需要掌握 public List<String> binaryTreePaths(TreeNode root) { // 输入: // 1 // / \ // 2 3 // \ // 5 // // 输出: ["1->2->5", "1->3"] List<String> res = new ArrayList<String>(); if (root == null) return res; Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>(); // 在 BFS 过程中,每遍历一个节点,都会有一个 path 与之对应 // 直到遇到叶子节点,将完整 path 加入到 res 中 Queue<String> pathQueue = new LinkedList<String>(); nodeQueue.offer(root); // KeyPoint 区别:两者 API // 1.Integer.toString() // 2.Integer.parseInt() pathQueue.offer(Integer.toString(root.val)); while (!nodeQueue.isEmpty()) { TreeNode node = nodeQueue.poll(); String path = pathQueue.poll(); // 叶子节点 if (node.left == null && node.right == null) { res.add(path); // 结束后面循环 continue; } if (node.left != null) { nodeQueue.offer(node.left); // KeyPoint 注意事项 // append(node.left.val),不是 node.left,node.left 表示节点 // 同时 <SUF> pathQueue.offer(new StringBuilder(path).append("->").append(node.left.val).toString()); } if (node.right != null) { nodeQueue.offer(node.right); pathQueue.offer(new StringBuilder(path).append("->").append(node.right.val).toString()); } } return res; } }
false
498
21
565
20
584
19
565
20
706
33
false
false
false
false
false
true
24845_2
package ch12DP; import java.util.Scanner; public class Karma46TakeMaterial { public static void main(String[] args) { int[] weight = {1,3,4}; int[] value = {15,20,30}; int bagSize = 4; testWeightBagProblem2(weight,value,bagSize); } /** * 动态规划获得结果 * @param weight 物品的重量 * @param value 物品的价值 * @param bagSize 背包的容量 */ public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){ // 创建dp数组 int goods = weight.length; // 获取物品的数量 int[][] dp = new int[goods][bagSize + 1]; // 初始化dp数组 // 创建数组后,其中默认的值就是0 /* Arrays.sort(weight); for (int j = weight[0]; j <= bagSize; j++) { dp[0][j] = value[0]; }*/ for (int j = 0; j <= bagSize; j++) { if (j >= weight[0]) { dp[0][j] = value[0]; // 当背包容量大于等于第一个物品的重量时,可以选择装入该物品 } else { dp[0][j] = 0; // 否则,背包内无法装入该物品,价值为0 } } // 填充dp数组 for (int i = 1; i < weight.length; i++) { for (int j = 0; j <= bagSize; j++) { if (j < weight[i]) { /** * 当前背包的容量都没有当前物品i大的时候,是不放物品i的 * 那么前i-1个物品能放下的最大价值就是当前情况的最大价值 */ dp[i][j] = dp[i-1][j]; } else { /** * 当前背包的容量可以放下物品i * 那么此时分两种情况: * 1、不放物品i * 2、放物品i * 比较这两种情况下,哪种背包中物品的最大价值最大 */ dp[i][j] = Math.max(dp[i-1][j] , dp[i-1][j-weight[i]] + value[i]); } } } // 打印dp数组 for (int i = 0; i < goods; i++) { for (int j = 0; j <= bagSize; j++) { System.out.print(dp[i][j] + "\t"); } System.out.println("\n"); } } /* * 不能正序可以这么理解: 虽然是一维数组,但是性质和二维背包差不多。 * 我们先来理解倒序遍历,从最后一个元素往前看,看到的都是“上一层的元素”然后每遍历到一个元素,就把当前元素赋值成“当前层”的。 * 这样得到的背包,因为每个元素加上的都是上一层的对应的物品value,所以不会重复。 * 因为二维数组是根据左上元素来求的,一维数组自然就是靠左边来求的。 * 倒序的时候左边元素再刷新前都是上一层的数据,但正序就不一样了,正序的时候,左边的元素刚刚刷新过,也就是左边的元素已经是本层的了, * 意味着什么 这样会导致一个物品反复加好几次。 * */ public static void testWeightBagProblem2(int[] weight, int[] value, int bagWeight){ int[] dp = new int[bagWeight + 1]; dp[0] = 0; //本来 应该每个值都赋一个 不影响后面比较max的最小值 敲定为0 但是这里不用赋值为0 默认都是0 /* * dp[j] = max(dp[j],dp[j - weight[i]] + value[i]) * */ int len = weight.length; for (int i = 0; i < len; i++) { for (int j = bagWeight; j >= weight[i] ; j--) { dp[j] = Math.max(dp[j],dp[j - weight[i]] + value[i]); } } for (int j = 0; j <= bagWeight; j++){ System.out.print(dp[j] + " "); } } }
EddieAy/Leetcode
ch12DP/Karma46TakeMaterial.java
1,097
// 获取物品的数量
line_comment
zh-cn
package ch12DP; import java.util.Scanner; public class Karma46TakeMaterial { public static void main(String[] args) { int[] weight = {1,3,4}; int[] value = {15,20,30}; int bagSize = 4; testWeightBagProblem2(weight,value,bagSize); } /** * 动态规划获得结果 * @param weight 物品的重量 * @param value 物品的价值 * @param bagSize 背包的容量 */ public static void testWeightBagProblem(int[] weight, int[] value, int bagSize){ // 创建dp数组 int goods = weight.length; // 获取 <SUF> int[][] dp = new int[goods][bagSize + 1]; // 初始化dp数组 // 创建数组后,其中默认的值就是0 /* Arrays.sort(weight); for (int j = weight[0]; j <= bagSize; j++) { dp[0][j] = value[0]; }*/ for (int j = 0; j <= bagSize; j++) { if (j >= weight[0]) { dp[0][j] = value[0]; // 当背包容量大于等于第一个物品的重量时,可以选择装入该物品 } else { dp[0][j] = 0; // 否则,背包内无法装入该物品,价值为0 } } // 填充dp数组 for (int i = 1; i < weight.length; i++) { for (int j = 0; j <= bagSize; j++) { if (j < weight[i]) { /** * 当前背包的容量都没有当前物品i大的时候,是不放物品i的 * 那么前i-1个物品能放下的最大价值就是当前情况的最大价值 */ dp[i][j] = dp[i-1][j]; } else { /** * 当前背包的容量可以放下物品i * 那么此时分两种情况: * 1、不放物品i * 2、放物品i * 比较这两种情况下,哪种背包中物品的最大价值最大 */ dp[i][j] = Math.max(dp[i-1][j] , dp[i-1][j-weight[i]] + value[i]); } } } // 打印dp数组 for (int i = 0; i < goods; i++) { for (int j = 0; j <= bagSize; j++) { System.out.print(dp[i][j] + "\t"); } System.out.println("\n"); } } /* * 不能正序可以这么理解: 虽然是一维数组,但是性质和二维背包差不多。 * 我们先来理解倒序遍历,从最后一个元素往前看,看到的都是“上一层的元素”然后每遍历到一个元素,就把当前元素赋值成“当前层”的。 * 这样得到的背包,因为每个元素加上的都是上一层的对应的物品value,所以不会重复。 * 因为二维数组是根据左上元素来求的,一维数组自然就是靠左边来求的。 * 倒序的时候左边元素再刷新前都是上一层的数据,但正序就不一样了,正序的时候,左边的元素刚刚刷新过,也就是左边的元素已经是本层的了, * 意味着什么 这样会导致一个物品反复加好几次。 * */ public static void testWeightBagProblem2(int[] weight, int[] value, int bagWeight){ int[] dp = new int[bagWeight + 1]; dp[0] = 0; //本来 应该每个值都赋一个 不影响后面比较max的最小值 敲定为0 但是这里不用赋值为0 默认都是0 /* * dp[j] = max(dp[j],dp[j - weight[i]] + value[i]) * */ int len = weight.length; for (int i = 0; i < len; i++) { for (int j = bagWeight; j >= weight[i] ; j--) { dp[j] = Math.max(dp[j],dp[j - weight[i]] + value[i]); } } for (int j = 0; j <= bagWeight; j++){ System.out.print(dp[j] + " "); } } }
false
1,017
4
1,097
6
1,086
4
1,097
6
1,468
9
false
false
false
false
false
true
20918_7
/** * 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法, * 能够支持2个生产者线程以及10个消费者线程的阻塞调用 * * 使用wait和notify/notifyAll来实现 * * @author mashibing */ package yxxy.c_021; import java.util.LinkedList; import java.util.concurrent.TimeUnit; public class MyContainer1<T> { final private LinkedList<T> lists = new LinkedList<>(); final private int MAX = 10; //最多10个元素 private int count = 0; public synchronized void put(T t) { while(lists.size() == MAX) { //想想为什么用while而不是用if? try { this.wait(); //effective java } catch (InterruptedException e) { e.printStackTrace(); } } lists.add(t); ++count; this.notifyAll(); //通知消费者线程进行消费 } public synchronized T get() { T t = null; while(lists.size() == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } t = lists.removeFirst(); count --; this.notifyAll(); //通知生产者进行生产 return t; } public static void main(String[] args) { MyContainer1<String> c = new MyContainer1<>(); //启动消费者线程 for(int i=0; i<10; i++) { new Thread(()->{ for(int j=0; j<5; j++) System.out.println(c.get()); }, "c" + i).start(); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } //启动生产者线程 for(int i=0; i<2; i++) { new Thread(()->{ for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j); }, "p" + i).start(); } } }
EduMoral/edu
concurrent/src/yxxy/c_021/MyContainer1.java
562
//启动生产者线程
line_comment
zh-cn
/** * 面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法, * 能够支持2个生产者线程以及10个消费者线程的阻塞调用 * * 使用wait和notify/notifyAll来实现 * * @author mashibing */ package yxxy.c_021; import java.util.LinkedList; import java.util.concurrent.TimeUnit; public class MyContainer1<T> { final private LinkedList<T> lists = new LinkedList<>(); final private int MAX = 10; //最多10个元素 private int count = 0; public synchronized void put(T t) { while(lists.size() == MAX) { //想想为什么用while而不是用if? try { this.wait(); //effective java } catch (InterruptedException e) { e.printStackTrace(); } } lists.add(t); ++count; this.notifyAll(); //通知消费者线程进行消费 } public synchronized T get() { T t = null; while(lists.size() == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } t = lists.removeFirst(); count --; this.notifyAll(); //通知生产者进行生产 return t; } public static void main(String[] args) { MyContainer1<String> c = new MyContainer1<>(); //启动消费者线程 for(int i=0; i<10; i++) { new Thread(()->{ for(int j=0; j<5; j++) System.out.println(c.get()); }, "c" + i).start(); } try { TimeUnit.SECONDS.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } //启动 <SUF> for(int i=0; i<2; i++) { new Thread(()->{ for(int j=0; j<25; j++) c.put(Thread.currentThread().getName() + " " + j); }, "p" + i).start(); } } }
false
486
7
558
6
561
6
558
6
733
13
false
false
false
false
false
true
17113_2
package tmall.bean; /** * Created by Edward on 2018/7/3 */ /** * 属性表 * 商品详情标签下的产品属性 * 不同的商品可能有相同的属性,如能效等级 */ public class Property { // 属性的唯一识别的 id private int id; // 属性的名称 private String name; // 和分类表的多对一关系 private Category category; // Get, Set public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
EdwardLiu-Aurora/Tmall
src/tmall/bean/Property.java
205
// 属性的唯一识别的 id
line_comment
zh-cn
package tmall.bean; /** * Created by Edward on 2018/7/3 */ /** * 属性表 * 商品详情标签下的产品属性 * 不同的商品可能有相同的属性,如能效等级 */ public class Property { // 属性 <SUF> private int id; // 属性的名称 private String name; // 和分类表的多对一关系 private Category category; // Get, Set public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; } }
false
190
8
205
7
220
7
205
7
279
17
false
false
false
false
false
true
62038_2
package com.dd.entity; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Table; import java.util.Date; /** * Describe:消息Entity * Author:蛋蛋 * Age:Eighteen * Time:2017年4月25日 下午3:10:24 */ @Table("message") public class Message { @Id private int id;//消息id @Column("content") private String content;//消息内容 @Column("uid") private int uid;//我的id @Column(wrap=true,value="from") private Integer from;//发送人,如果此字段为0或者为没有则为系统消息 @Column("from_group") private int from_group;//分组id @Column(wrap=true,value="type") private int type;//1.请求加好友. 2.已拒绝 3.已同意 @Column("remark") private String remark;//留言 @Column("href") private String href; @Column(wrap=true,value="read") private int read;//是否已读.1.已读.0.未读 @Column(wrap=true,value="time") private Date time;//消息日期 private User user;//发送人信息 public final static String ID = "id"; public final static String CONTENT = "content"; public final static String UID = "uid"; public final static String FROM = "`from`"; public final static String FROM_GROUP = "from_group"; public final static String TYPE = "`type`"; public final static String REMARK = "remark"; public final static String HREF = "href"; public final static String READ = "`read`"; public final static String TIME = "time"; public static final String TABLE_NAME = "message"; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public Integer getFrom() { return from; } public void setFrom(Integer from) { this.from = from; } public int getFrom_group() { return from_group; } public void setFrom_group(int from_group) { this.from_group = from_group; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public int getRead() { return read; } public void setRead(int read) { this.read = read; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Message [id=" + id + ", content=" + content + ", uid=" + uid + ", from=" + from + ", from_group=" + from_group + ", type=" + type + ", remark=" + remark + ", href=" + href + ", read=" + read + ", time=" + time + ", user=" + user + "]"; } }
EggsBlue/LuliChat
src/main/java/com/dd/entity/Message.java
998
//消息内容
line_comment
zh-cn
package com.dd.entity; import org.nutz.dao.entity.annotation.Column; import org.nutz.dao.entity.annotation.Id; import org.nutz.dao.entity.annotation.Table; import java.util.Date; /** * Describe:消息Entity * Author:蛋蛋 * Age:Eighteen * Time:2017年4月25日 下午3:10:24 */ @Table("message") public class Message { @Id private int id;//消息id @Column("content") private String content;//消息 <SUF> @Column("uid") private int uid;//我的id @Column(wrap=true,value="from") private Integer from;//发送人,如果此字段为0或者为没有则为系统消息 @Column("from_group") private int from_group;//分组id @Column(wrap=true,value="type") private int type;//1.请求加好友. 2.已拒绝 3.已同意 @Column("remark") private String remark;//留言 @Column("href") private String href; @Column(wrap=true,value="read") private int read;//是否已读.1.已读.0.未读 @Column(wrap=true,value="time") private Date time;//消息日期 private User user;//发送人信息 public final static String ID = "id"; public final static String CONTENT = "content"; public final static String UID = "uid"; public final static String FROM = "`from`"; public final static String FROM_GROUP = "from_group"; public final static String TYPE = "`type`"; public final static String REMARK = "remark"; public final static String HREF = "href"; public final static String READ = "`read`"; public final static String TIME = "time"; public static final String TABLE_NAME = "message"; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public Integer getFrom() { return from; } public void setFrom(Integer from) { this.from = from; } public int getFrom_group() { return from_group; } public void setFrom_group(int from_group) { this.from_group = from_group; } public int getType() { return type; } public void setType(int type) { this.type = type; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public int getRead() { return read; } public void setRead(int read) { this.read = read; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } @Override public String toString() { return "Message [id=" + id + ", content=" + content + ", uid=" + uid + ", from=" + from + ", from_group=" + from_group + ", type=" + type + ", remark=" + remark + ", href=" + href + ", read=" + read + ", time=" + time + ", user=" + user + "]"; } }
false
770
3
998
3
990
3
998
3
1,113
5
false
false
false
false
false
true
20796_7
package com.mychat.controol; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.nutz.dao.Cnd; import org.nutz.dao.Dao; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.json.Json; import org.nutz.lang.Strings; import org.nutz.lang.util.NutMap; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Attr; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.Param; import com.mychat.dao.ChatMessageDao; import com.mychat.dao.UserDao; import com.mychat.entity.InitData; import com.mychat.entity.JsonMsgModel; import com.mychat.entity.Message; import com.mychat.entity.User; import com.mychat.msg.entity.ChatMessage; /** * Describe: User Controll * Author:陆小不离 * Age:Eighteen * Time:2017年4月24日 上午11:34:08 */ @IocBean @At("/user") @Ok("json") public class UserModule { @Inject(value="userDao") private UserDao userDao; @Inject private Dao dao; @Inject private ChatMessageDao chatMessageDao; /** * 登陆 * @param u * @param session * @return */ @At public Object login(@Param("..")User u,HttpSession session){ NutMap re = new NutMap(); User user = userDao.getByNamPwd(u); if(user == null){ re.setv("ok", false).setv("msg", "用户名或密码错误!"); return re; }else{ session.setAttribute("me", user.getId()); session.setAttribute("username", user.getUsername()); re.setv("ok", true).setv("msg", "登陆成功!"); userDao.online(user.getId()); return re; } } /** * 注册 * @param user * @param session * @return */ @At public Object registry(@Param("..") User user,HttpSession session){ NutMap re = new NutMap(); String msg = checkUser(user,true); if(msg != null){ re.setv("ok", false).setv("msg", msg); return re; } user.setAvatar("/mychat/imgs/user.jpg"); User u = userDao.save(user); if(u==null){ re.setv("ok", false).setv("msg", "注册失败!"); return re; }else{ session.setAttribute("me", user.getId()); session.setAttribute("username", user.getUsername()); re.setv("ok", true).setv("msg", "注册成功"); //添加默认分组 userDao.addGroup(u.getId(), "家人"); userDao.addGroup(u.getId(), "朋友"); return re; } } /** * 查找用户 * @param name * @return */ @At public Object seachUser(@Param("name") String name){ List<User> users = userDao.getByLikeName(name); return Json.toJson(users); } /** * 初始化数据 * @param me * @return */ @At @Ok("raw") public String getInitData(@Attr("me") int me){ String data = userDao.getInitData(me); System.out.println(data); return data; } /** * 获取未读消息数量 * @param me * @return */ @At public Object unreadMsgCount(@Attr("me") int me){ List<Message> msgs = userDao.getMessages(me); int count = 0; for(Message msg : msgs){ if(msg.getRead() == 0){//0未读 count++; } } NutMap nm = new NutMap(); nm.setv("ok", true).setv("count",count); return nm; } /** * 获取我的消息 * @param me * @return */ @At public Object getMsg(@Attr("me") int me){ List<Message> msgs = userDao.getMessages(me); JsonMsgModel jmm = new JsonMsgModel(); jmm.setCode(0); jmm.setPages(1); jmm.setData(msgs); return jmm; } /** * 已读我的消息 * @param me */ @At public void markRead(@Attr("me") int me){ userDao.markRead(me); } /** * 申请添加好友 * @param me 我的id * @param uid 对方id * @param from_group 到哪个分组? * @return */ @At public Object applyFriend(@Attr("me") int me,@Param("uid")int uid,@Param("from_group")int from_group ){ NutMap nm = new NutMap(); int i = userDao.applyFriend(uid, me, from_group); if(1>0) nm.setv("ok", 1); else nm.setv("ok", 0); return nm; } /** * 同意添加 * @param me 我的id * @param uid 对方的id * @param group 我要添加到的分组id * @param from_group 对方要添加到的分组id * @return */ @At public Object addFridend(@Attr("me") int me,@Param("uid") int uid,@Param("group") int group,@Param("from_group") int from_group,@Param("msgid")int msgid){ NutMap nm = new NutMap(); //查出我的所有好友,判断是否已经添加过 List<User> list = userDao.getFriends(me); if(list!=null && list.size()>0){ for(User u : list){ if(u.getId() == uid) return nm.setv("code", 1).setv("msg", "不可重复添加!"); } } int id = userDao.addFriend(me, uid, group); int i = userDao.addFriend(uid, me, from_group); System.out.println("加好友成功!"); //更新消息状态 userDao.updateMsg(msgid, 3); //更新状态为已同意 nm.setv("code", 0); return nm; } /** * 拒绝添加 * @param me * @param msgid * @return */ @At public Object declineApply(@Attr("me") int me,@Param("msgid")int msgid){ NutMap nm = new NutMap(); userDao.updateMsg(msgid, 2); nm.setv("code", 0); return nm; } /** * 上线 * @param me */ @At public void online(@Attr("me") int me){ userDao.online(me); } /** * 下线 * @param me */ @At public void hide(@Attr("me") int me){ userDao.hide(me); } /** * 修改签名 * @param me * @param sign */ @At public void updateSign(@Attr("me") int me,@Param("sign") String sign){ userDao.updateSign(me, sign); } /** * 根据id获取用户信息,可用于查看在线状态 * @param id * @return */ @At public Object getUser(@Param("id") int id){ User user = userDao.findbyid(id); return user; } /** * 查询群成员 * @param id * @return */ @At public Object getMembers(@Param("id") int fid){ List<User> members = userDao.getMembers(fid); InitData id = new InitData(); id.setCode(0); id.setMsg(""); Map<String,Object> war = new HashMap<String,Object>(); war.put("list", members); id.setData(war); return id; } /** * 分页查询聊天记录 * @param me * @param pageNo * @param pageSize * @param toid * @param type * @return */ @At @Ok("json") public Object getOldMsgs(@Attr("me") int me,@Param("pageNo") int pageNo,@Param("pageSize") int pageSize,@Param("toid") int toid,@Param("type") int type){ /* username: '纸飞机' ,id: 1 ,avatar: 'http://tva3.sinaimg.cn/crop.0.0.512.512.180/8693225ajw8f2rt20ptykj20e80e8weu.jpg' ,timestamp: 1480897882000 ,content: 'face[抱抱] face[心] 你好啊小美女' */ NutMap nm = chatMessageDao.pageMsg(pageNo, pageSize, me, toid, type); return nm; } /** * Validate Data * @param user * @param create * @return */ protected String checkUser(User user, boolean create) { if (user == null) { return "空对象"; } if (create) { if (Strings.isBlank(user.getUsername()) || Strings.isBlank(user.getPwd())) return "用户名/密码不能为空"; } else { if (Strings.isBlank(user.getPwd())) return "密码不能为空"; } String passwd = user.getPwd().trim(); if (6 > passwd.length() || passwd.length() > 12) { return "密码长度错误"; } user.setPwd(passwd); if (create) { int count = dao.count(User.class, Cnd.where("username", "=", user.getUsername())); if (count != 0) { return "用户名已经存在"; } } else { if (user.getId() < 1) { return "用户Id非法"; } } if (user.getUsername() != null) user.setUsername(user.getUsername().trim()); return null; } }
EggsBlue/MyChat
MyChat/src/com/mychat/controol/UserModule.java
2,702
//0未读
line_comment
zh-cn
package com.mychat.controol; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpSession; import org.nutz.dao.Cnd; import org.nutz.dao.Dao; import org.nutz.ioc.loader.annotation.Inject; import org.nutz.ioc.loader.annotation.IocBean; import org.nutz.json.Json; import org.nutz.lang.Strings; import org.nutz.lang.util.NutMap; import org.nutz.mvc.annotation.At; import org.nutz.mvc.annotation.Attr; import org.nutz.mvc.annotation.Ok; import org.nutz.mvc.annotation.Param; import com.mychat.dao.ChatMessageDao; import com.mychat.dao.UserDao; import com.mychat.entity.InitData; import com.mychat.entity.JsonMsgModel; import com.mychat.entity.Message; import com.mychat.entity.User; import com.mychat.msg.entity.ChatMessage; /** * Describe: User Controll * Author:陆小不离 * Age:Eighteen * Time:2017年4月24日 上午11:34:08 */ @IocBean @At("/user") @Ok("json") public class UserModule { @Inject(value="userDao") private UserDao userDao; @Inject private Dao dao; @Inject private ChatMessageDao chatMessageDao; /** * 登陆 * @param u * @param session * @return */ @At public Object login(@Param("..")User u,HttpSession session){ NutMap re = new NutMap(); User user = userDao.getByNamPwd(u); if(user == null){ re.setv("ok", false).setv("msg", "用户名或密码错误!"); return re; }else{ session.setAttribute("me", user.getId()); session.setAttribute("username", user.getUsername()); re.setv("ok", true).setv("msg", "登陆成功!"); userDao.online(user.getId()); return re; } } /** * 注册 * @param user * @param session * @return */ @At public Object registry(@Param("..") User user,HttpSession session){ NutMap re = new NutMap(); String msg = checkUser(user,true); if(msg != null){ re.setv("ok", false).setv("msg", msg); return re; } user.setAvatar("/mychat/imgs/user.jpg"); User u = userDao.save(user); if(u==null){ re.setv("ok", false).setv("msg", "注册失败!"); return re; }else{ session.setAttribute("me", user.getId()); session.setAttribute("username", user.getUsername()); re.setv("ok", true).setv("msg", "注册成功"); //添加默认分组 userDao.addGroup(u.getId(), "家人"); userDao.addGroup(u.getId(), "朋友"); return re; } } /** * 查找用户 * @param name * @return */ @At public Object seachUser(@Param("name") String name){ List<User> users = userDao.getByLikeName(name); return Json.toJson(users); } /** * 初始化数据 * @param me * @return */ @At @Ok("raw") public String getInitData(@Attr("me") int me){ String data = userDao.getInitData(me); System.out.println(data); return data; } /** * 获取未读消息数量 * @param me * @return */ @At public Object unreadMsgCount(@Attr("me") int me){ List<Message> msgs = userDao.getMessages(me); int count = 0; for(Message msg : msgs){ if(msg.getRead() == 0){//0未 <SUF> count++; } } NutMap nm = new NutMap(); nm.setv("ok", true).setv("count",count); return nm; } /** * 获取我的消息 * @param me * @return */ @At public Object getMsg(@Attr("me") int me){ List<Message> msgs = userDao.getMessages(me); JsonMsgModel jmm = new JsonMsgModel(); jmm.setCode(0); jmm.setPages(1); jmm.setData(msgs); return jmm; } /** * 已读我的消息 * @param me */ @At public void markRead(@Attr("me") int me){ userDao.markRead(me); } /** * 申请添加好友 * @param me 我的id * @param uid 对方id * @param from_group 到哪个分组? * @return */ @At public Object applyFriend(@Attr("me") int me,@Param("uid")int uid,@Param("from_group")int from_group ){ NutMap nm = new NutMap(); int i = userDao.applyFriend(uid, me, from_group); if(1>0) nm.setv("ok", 1); else nm.setv("ok", 0); return nm; } /** * 同意添加 * @param me 我的id * @param uid 对方的id * @param group 我要添加到的分组id * @param from_group 对方要添加到的分组id * @return */ @At public Object addFridend(@Attr("me") int me,@Param("uid") int uid,@Param("group") int group,@Param("from_group") int from_group,@Param("msgid")int msgid){ NutMap nm = new NutMap(); //查出我的所有好友,判断是否已经添加过 List<User> list = userDao.getFriends(me); if(list!=null && list.size()>0){ for(User u : list){ if(u.getId() == uid) return nm.setv("code", 1).setv("msg", "不可重复添加!"); } } int id = userDao.addFriend(me, uid, group); int i = userDao.addFriend(uid, me, from_group); System.out.println("加好友成功!"); //更新消息状态 userDao.updateMsg(msgid, 3); //更新状态为已同意 nm.setv("code", 0); return nm; } /** * 拒绝添加 * @param me * @param msgid * @return */ @At public Object declineApply(@Attr("me") int me,@Param("msgid")int msgid){ NutMap nm = new NutMap(); userDao.updateMsg(msgid, 2); nm.setv("code", 0); return nm; } /** * 上线 * @param me */ @At public void online(@Attr("me") int me){ userDao.online(me); } /** * 下线 * @param me */ @At public void hide(@Attr("me") int me){ userDao.hide(me); } /** * 修改签名 * @param me * @param sign */ @At public void updateSign(@Attr("me") int me,@Param("sign") String sign){ userDao.updateSign(me, sign); } /** * 根据id获取用户信息,可用于查看在线状态 * @param id * @return */ @At public Object getUser(@Param("id") int id){ User user = userDao.findbyid(id); return user; } /** * 查询群成员 * @param id * @return */ @At public Object getMembers(@Param("id") int fid){ List<User> members = userDao.getMembers(fid); InitData id = new InitData(); id.setCode(0); id.setMsg(""); Map<String,Object> war = new HashMap<String,Object>(); war.put("list", members); id.setData(war); return id; } /** * 分页查询聊天记录 * @param me * @param pageNo * @param pageSize * @param toid * @param type * @return */ @At @Ok("json") public Object getOldMsgs(@Attr("me") int me,@Param("pageNo") int pageNo,@Param("pageSize") int pageSize,@Param("toid") int toid,@Param("type") int type){ /* username: '纸飞机' ,id: 1 ,avatar: 'http://tva3.sinaimg.cn/crop.0.0.512.512.180/8693225ajw8f2rt20ptykj20e80e8weu.jpg' ,timestamp: 1480897882000 ,content: 'face[抱抱] face[心] 你好啊小美女' */ NutMap nm = chatMessageDao.pageMsg(pageNo, pageSize, me, toid, type); return nm; } /** * Validate Data * @param user * @param create * @return */ protected String checkUser(User user, boolean create) { if (user == null) { return "空对象"; } if (create) { if (Strings.isBlank(user.getUsername()) || Strings.isBlank(user.getPwd())) return "用户名/密码不能为空"; } else { if (Strings.isBlank(user.getPwd())) return "密码不能为空"; } String passwd = user.getPwd().trim(); if (6 > passwd.length() || passwd.length() > 12) { return "密码长度错误"; } user.setPwd(passwd); if (create) { int count = dao.count(User.class, Cnd.where("username", "=", user.getUsername())); if (count != 0) { return "用户名已经存在"; } } else { if (user.getId() < 1) { return "用户Id非法"; } } if (user.getUsername() != null) user.setUsername(user.getUsername().trim()); return null; } }
false
2,353
4
2,702
4
2,771
4
2,702
4
3,293
6
false
false
false
false
false
true
60092_10
package cn.eiden.hsm.enums; /** * 多职业组 * @author Eiden J.P Zhou * @date 2020/8/5 17:22 */ public enum MultiClassGroup { /**无效*/ INVALID(0), /**污手党*/ GRIMY_GOONS(1), /**玉莲帮*/ JADE_LOTUS(2), /**暗金教*/ KABAL(3), /**骑士-牧师*/ PALADIN_PRIEST(4), /**牧师-术士*/ PRIEST_WARLOCK(5), /**术士-恶魔猎手*/ WARLOCK_DEMONHUNTER(6), /**恶魔猎手-猎人*/ HUNTER_DEMONHUNTER(7), /**猎人-德鲁伊*/ DRUID_HUNTER(8), /**德鲁伊-萨满*/ DRUID_SHAMAN(9), /**萨满-法师*/ MAGE_SHAMAN(10), /**法师-盗贼*/ MAGE_ROGUE(11), /**盗贼-战士*/ ROGUE_WARRIOR(12), /**战士-骑士*/ PALADIN_WARRIOR(13) ; /**代号*/ private int code; MultiClassGroup(int code) { this.code = code; } public int getCode() { return code; } }
EidenRitto/hearthstone
hearth-core/src/main/java/cn/eiden/hsm/enums/MultiClassGroup.java
385
/**德鲁伊-萨满*/
block_comment
zh-cn
package cn.eiden.hsm.enums; /** * 多职业组 * @author Eiden J.P Zhou * @date 2020/8/5 17:22 */ public enum MultiClassGroup { /**无效*/ INVALID(0), /**污手党*/ GRIMY_GOONS(1), /**玉莲帮*/ JADE_LOTUS(2), /**暗金教*/ KABAL(3), /**骑士-牧师*/ PALADIN_PRIEST(4), /**牧师-术士*/ PRIEST_WARLOCK(5), /**术士-恶魔猎手*/ WARLOCK_DEMONHUNTER(6), /**恶魔猎手-猎人*/ HUNTER_DEMONHUNTER(7), /**猎人-德鲁伊*/ DRUID_HUNTER(8), /**德鲁伊 <SUF>*/ DRUID_SHAMAN(9), /**萨满-法师*/ MAGE_SHAMAN(10), /**法师-盗贼*/ MAGE_ROGUE(11), /**盗贼-战士*/ ROGUE_WARRIOR(12), /**战士-骑士*/ PALADIN_WARRIOR(13) ; /**代号*/ private int code; MultiClassGroup(int code) { this.code = code; } public int getCode() { return code; } }
false
322
8
385
11
368
8
385
11
476
14
false
false
false
false
false
true
42778_13
package com.foodClass.model; import java.util.List; public class TestFoodClass { public static void main(String[] args) { I_FoodClassDAO fdclasstest = new FoodClassJDBCDAO(); FoodClassVO fdvo = new FoodClassVO(); // 新增===================================== // fdvo.setFd_class_name("好吃"); // fdvo.setFd_class_state(true); // // fdclasstest.insertFoodClass(fdvo); // // System.out.println("新增成功"); // System.out.println(fdvo); // 修改===================================== // fdvo.setFd_class_no(7); // fdvo.setFd_class_name("很好吃"); // fdvo.setFd_class_state(true); // // fdclasstest.updateFoodClass(fdvo); // System.out.println("修改成功"); // 查詢===================================== fdvo = fdclasstest.getClassPK(1); System.out.println(fdvo.getFd_class_no()); System.out.println(fdvo.getFd_class_name()); System.out.println(fdvo.getFd_class_state()); // 查詢===================================== // List<FoodClassVO> list = fdclasstest.getAllFoodClass(); // for (FoodClassVO fdclass : list) { // System.out.print(fdclass.getFd_class_no() + ","); // System.out.print(fdclass.getFd_class_name() + ","); // System.out.println(fdclass.getFd_class_state()); // } // System.out.println("查詢成功"); } }
EmeryWeng/CFA102G5
src/com/foodClass/model/TestFoodClass.java
463
// 查詢=====================================
line_comment
zh-cn
package com.foodClass.model; import java.util.List; public class TestFoodClass { public static void main(String[] args) { I_FoodClassDAO fdclasstest = new FoodClassJDBCDAO(); FoodClassVO fdvo = new FoodClassVO(); // 新增===================================== // fdvo.setFd_class_name("好吃"); // fdvo.setFd_class_state(true); // // fdclasstest.insertFoodClass(fdvo); // // System.out.println("新增成功"); // System.out.println(fdvo); // 修改===================================== // fdvo.setFd_class_no(7); // fdvo.setFd_class_name("很好吃"); // fdvo.setFd_class_state(true); // // fdclasstest.updateFoodClass(fdvo); // System.out.println("修改成功"); // 查詢===================================== fdvo = fdclasstest.getClassPK(1); System.out.println(fdvo.getFd_class_no()); System.out.println(fdvo.getFd_class_name()); System.out.println(fdvo.getFd_class_state()); // 查詢 <SUF> // List<FoodClassVO> list = fdclasstest.getAllFoodClass(); // for (FoodClassVO fdclass : list) { // System.out.print(fdclass.getFd_class_no() + ","); // System.out.print(fdclass.getFd_class_name() + ","); // System.out.println(fdclass.getFd_class_state()); // } // System.out.println("查詢成功"); } }
false
332
5
463
6
447
6
463
6
561
10
false
false
false
false
false
true
17847_1
package com.zhu56.util; import cn.hutool.core.util.ReflectUtil; import com.zhu56.inter.SerFunction; import lombok.SneakyThrows; import lombok.experimental.UtilityClass; import java.io.Serializable; import java.lang.invoke.SerializedLambda; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * λ表达式工具类 * * @author 朱滔 * @date 2021/10/10 23:42 */ @UtilityClass public class LambdaUtil { /** * 类型λ缓存 */ private final Map<Class<?>, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>(); /** * 返回类型模式 */ private final Pattern RETURN_TYPE_PATTERN = Pattern.compile("\\(.*\\)L(.*);"); /** * 获得一个方法引用的lambda实例 * * @param fun 函数 * @return {@link SerializedLambda} */ public <T, R> SerializedLambda getLambda(SerFunction<T, R> fun) { return getSerializedLambda(fun); } /** * 获取方法的lambda实例 * * @param fun 有趣 * @return {@link SerializedLambda} */ @SneakyThrows public SerializedLambda getSerializedLambda(Serializable fun) { Class<?> funClazz = fun.getClass(); return CLASS_LAMBDA_CACHE.computeIfAbsent(funClazz, c -> { Method method = ReflectUtil.getMethodByName(funClazz, "writeReplace"); return ReflectUtil.invoke(fun, method); }); } /** * 得到返回值的类型 * * @param fun 有趣 * @return {@link Class}<{@link R}> */ @SuppressWarnings("unchecked") public <T, R> Class<R> getReturnClass(SerFunction<T, R> fun) { SerializedLambda serializedLambda = getSerializedLambda(fun); String expr = serializedLambda.getImplMethodSignature(); Matcher matcher = RETURN_TYPE_PATTERN.matcher(expr); if (!matcher.find() || matcher.groupCount() != 1) { return null; } String className = matcher.group(1).replace("/", "."); Class<R> clazz; try { clazz = (Class<R>) Class.forName(className); } catch (ClassNotFoundException e) { return null; } return clazz; } }
EmperorZhu56/ztream
src/main/java/com/zhu56/util/LambdaUtil.java
603
/** * 类型λ缓存 */
block_comment
zh-cn
package com.zhu56.util; import cn.hutool.core.util.ReflectUtil; import com.zhu56.inter.SerFunction; import lombok.SneakyThrows; import lombok.experimental.UtilityClass; import java.io.Serializable; import java.lang.invoke.SerializedLambda; import java.lang.reflect.Method; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * λ表达式工具类 * * @author 朱滔 * @date 2021/10/10 23:42 */ @UtilityClass public class LambdaUtil { /** * 类型λ <SUF>*/ private final Map<Class<?>, SerializedLambda> CLASS_LAMBDA_CACHE = new ConcurrentHashMap<>(); /** * 返回类型模式 */ private final Pattern RETURN_TYPE_PATTERN = Pattern.compile("\\(.*\\)L(.*);"); /** * 获得一个方法引用的lambda实例 * * @param fun 函数 * @return {@link SerializedLambda} */ public <T, R> SerializedLambda getLambda(SerFunction<T, R> fun) { return getSerializedLambda(fun); } /** * 获取方法的lambda实例 * * @param fun 有趣 * @return {@link SerializedLambda} */ @SneakyThrows public SerializedLambda getSerializedLambda(Serializable fun) { Class<?> funClazz = fun.getClass(); return CLASS_LAMBDA_CACHE.computeIfAbsent(funClazz, c -> { Method method = ReflectUtil.getMethodByName(funClazz, "writeReplace"); return ReflectUtil.invoke(fun, method); }); } /** * 得到返回值的类型 * * @param fun 有趣 * @return {@link Class}<{@link R}> */ @SuppressWarnings("unchecked") public <T, R> Class<R> getReturnClass(SerFunction<T, R> fun) { SerializedLambda serializedLambda = getSerializedLambda(fun); String expr = serializedLambda.getImplMethodSignature(); Matcher matcher = RETURN_TYPE_PATTERN.matcher(expr); if (!matcher.find() || matcher.groupCount() != 1) { return null; } String className = matcher.group(1).replace("/", "."); Class<R> clazz; try { clazz = (Class<R>) Class.forName(className); } catch (ClassNotFoundException e) { return null; } return clazz; } }
false
536
11
603
9
642
10
603
9
777
15
false
false
false
false
false
true
53794_6
package com.ezreal.multiselecttreeview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.ezreal.treevieewlib.AndroidTreeView; import com.ezreal.treevieewlib.NodeIDFormat; import com.ezreal.treevieewlib.OnTreeNodeClickListener; import com.ezreal.treevieewlib.TreeNode; import java.util.ArrayList; import java.util.List; public class SingleSelectActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_sel); final TextView result = findViewById(R.id.tv_result); // 通过 findViewById获得控件实例 AndroidTreeView treeView = findViewById(R.id.tree_view); treeView.setNodeIdFormat(NodeIDFormat.LONG); // 声明 bean 中id pid 字段类型,必选 treeView.setMultiSelEnable(false); // 设置关闭多选,默认关闭,可选 // 在单选状态下,通过监听叶子节点单击事件,得到选中的节点 treeView.setTreeNodeClickListener(new OnTreeNodeClickListener() { @Override public void OnLeafNodeClick(TreeNode node, int position) { result.setText(node.getTitle()); } }); // 绑定数据,注意:本行需要写在为 treeView 设置属性之后 // 在本行之后任何 setXXX 都不起作用 treeView.bindData(testData()); } private List<TypeBeanLong> testData(){ // 根据 层级关系,设置好 PID ID 构造测试数据 // 在工作项目中,一般会通过解析 json/xml 来得到个节点数据以及节点间关系 List<TypeBeanLong> list = new ArrayList<>(); list.add(new TypeBeanLong(1,0,"图书")); list.add(new TypeBeanLong(2,0,"服装")); list.add(new TypeBeanLong(11,1,"小说")); list.add(new TypeBeanLong(12,1,"杂志")); list.add(new TypeBeanLong(21,2,"衣服")); list.add(new TypeBeanLong(22,2,"裤子")); list.add(new TypeBeanLong(111,11,"言情小说")); list.add(new TypeBeanLong(112,11,"科幻小说")); list.add(new TypeBeanLong(121,12,"军事杂志")); list.add(new TypeBeanLong(122,12,"娱乐杂志")); list.add(new TypeBeanLong(211,21,"阿迪")); list.add(new TypeBeanLong(212,21,"耐克")); list.add(new TypeBeanLong(221,22,"百斯盾")); list.add(new TypeBeanLong(222,22,"海澜之家")); return list; } }
Enjoylone1y/MutiSelectTreeView
app/src/main/java/com/ezreal/multiselecttreeview/SingleSelectActivity.java
719
// 根据 层级关系,设置好 PID ID 构造测试数据
line_comment
zh-cn
package com.ezreal.multiselecttreeview; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import com.ezreal.treevieewlib.AndroidTreeView; import com.ezreal.treevieewlib.NodeIDFormat; import com.ezreal.treevieewlib.OnTreeNodeClickListener; import com.ezreal.treevieewlib.TreeNode; import java.util.ArrayList; import java.util.List; public class SingleSelectActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_single_sel); final TextView result = findViewById(R.id.tv_result); // 通过 findViewById获得控件实例 AndroidTreeView treeView = findViewById(R.id.tree_view); treeView.setNodeIdFormat(NodeIDFormat.LONG); // 声明 bean 中id pid 字段类型,必选 treeView.setMultiSelEnable(false); // 设置关闭多选,默认关闭,可选 // 在单选状态下,通过监听叶子节点单击事件,得到选中的节点 treeView.setTreeNodeClickListener(new OnTreeNodeClickListener() { @Override public void OnLeafNodeClick(TreeNode node, int position) { result.setText(node.getTitle()); } }); // 绑定数据,注意:本行需要写在为 treeView 设置属性之后 // 在本行之后任何 setXXX 都不起作用 treeView.bindData(testData()); } private List<TypeBeanLong> testData(){ // 根据 <SUF> // 在工作项目中,一般会通过解析 json/xml 来得到个节点数据以及节点间关系 List<TypeBeanLong> list = new ArrayList<>(); list.add(new TypeBeanLong(1,0,"图书")); list.add(new TypeBeanLong(2,0,"服装")); list.add(new TypeBeanLong(11,1,"小说")); list.add(new TypeBeanLong(12,1,"杂志")); list.add(new TypeBeanLong(21,2,"衣服")); list.add(new TypeBeanLong(22,2,"裤子")); list.add(new TypeBeanLong(111,11,"言情小说")); list.add(new TypeBeanLong(112,11,"科幻小说")); list.add(new TypeBeanLong(121,12,"军事杂志")); list.add(new TypeBeanLong(122,12,"娱乐杂志")); list.add(new TypeBeanLong(211,21,"阿迪")); list.add(new TypeBeanLong(212,21,"耐克")); list.add(new TypeBeanLong(221,22,"百斯盾")); list.add(new TypeBeanLong(222,22,"海澜之家")); return list; } }
false
613
18
719
15
727
13
719
15
882
27
false
false
false
false
false
true
55495_24
package rip; import java.util.HashMap; public class Router { private final int routerId; private RouterTable routerTable; private int[] nearRouter; private int[] nearNetwork; public RouterTable getRouterTable() { return routerTable; } public void setRouterTable(RouterTable routerTable) { this.routerTable = routerTable; } public void changeRouterTable(RouterTable otherRouterTable){ // 规则: // 1. 传入的为其临近路由器的路由表 // 2. 解析路由表 // 3. 如果有自己路由表里有的网络,检查跳数是否为15,不为15进行以下操作 // 4. 如果“跳数+1” 小于 本路由表对应条目的跳数,则修改记录 // 5. 修改记录 “网络号(不变)”,“跳数+1”,“下一跳路由(该路由条目的来源路由)” // 6. else如果有本自己路由表里没有的网路,检查跳数是否为15,不为15进行以下操作 // 7. 添加记录 “网络号”,“跳数+1”,“下一跳路由(该路由条目的来源路由)” //将自己的路由表里 所有的网络号建立一个String,所有的跳数建立一个String, //遍历外来路由表的各个网络号,判断是否存在相同的值 //如果存在 判断跳数(1.是否不等于15,2,是否小于自己对应的跳数+1) // 如果满足,修改路由表对应数据 // 如果不满足。do nothing //如果不存在,判断跳数是否不等于15, // 如果满足,添加该路由条目 HashMap<Integer, String[] > otherList = otherRouterTable.getList(); HashMap<Integer, String[] > selfList = routerTable.getList(); String otherNetnum = ""; String otherTiaonum = ""; String selfNetnum = ""; String selfTiaonum = ""; String selfShouldMod = ""; String otherShouldMod = ""; String shouldAdd = ""; for(int i = 0 ; i < otherList.size(); i++){ otherNetnum += otherList.get(i)[0]; otherTiaonum += otherList.get(i)[1]; } for(int i = 0; i < selfList.size(); i++){ selfNetnum += selfList.get(i)[0]; selfTiaonum += selfList.get(i)[1]; } for(int i = 0; i < otherNetnum.length(); i++){ // System.out.println("第"+i+"循环检验========================"); int res = selfNetnum.indexOf(otherNetnum.substring(i,i+1)); int p = Integer.parseInt(otherTiaonum.substring(i, i+1)); if (res != -1) { int q = Integer.parseInt(selfTiaonum.substring(res, res+1)); if (p < 15) { if ((p+1) < q ) { //TODO 修改路由表对应数据 // System.out.println("premod======="+selfNetnum.substring(res, res+1)+"--------"+otherNetnum.substring(i,i+1)); selfShouldMod += String.valueOf(res); otherShouldMod += String.valueOf(i); } } }else if (res == -1) { if (p < 15) { //TODO 添加该条目 // System.out.println("preadd====="+otherNetnum.substring(i,i+1)); shouldAdd += String.valueOf(i); } }else { System.err.println("core change err"); } } if (selfShouldMod.length() > 0) { for(int i = 0; i < selfShouldMod.length(); i++){ // System.out.println("mod"); selfList.remove(selfShouldMod.substring(i,i+1)); String newChange[] = { otherList.get(Integer.parseInt(otherShouldMod.substring(i, i+1)))[0], String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(otherShouldMod.substring(i,i+1)))[1])+1), String.valueOf(otherRouterTable.getRouterID()) }; selfList.put(Integer.parseInt(selfShouldMod.substring(i,i+1)), newChange); } } if (shouldAdd.length() > 0) { // System.out.println("1111111111111self.size================="+selfList.size()); int len = selfList.size(); for(int i = 0; i < shouldAdd.length(); i++){ // System.out.println("add"); String newChange[] = { otherList.get(Integer.parseInt(shouldAdd.substring(i, i+1)))[0], String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(shouldAdd.substring(i,i+1)))[1])+1), String.valueOf(otherRouterTable.getRouterID()) }; selfList.put(len+i, newChange); // System.out.println("self.size================="+selfList.size()); } } routerTable.setList(selfList); setRouterTable(routerTable); } public int[] getNearRouter() { return nearRouter; } public void setNearRouter(int[] nearRouter) { this.nearRouter = nearRouter; } public int[] getNearNetwork() { return nearNetwork; } public void setNearNetwork(int[] nearNetwork) { this.nearNetwork = nearNetwork; } public int getRouterId() { return routerId; } public void echoRoutertable(){ RouterTable rtTables = getRouterTable(); HashMap<Integer, String[]> list = rtTables.getList(); System.out.println("*******路由器 "+getRouterTable().getRouterID()+" 路由表******"); for (int i = 0; i < list.size(); i++) { String[] pStrings = list.get(i); System.out.println("网络:"+pStrings[0]+" | "+"跳数:"+pStrings[1]+" | "+"下一跳路由器: "+pStrings[2]); } } public Router(int routerId, RouterTable routerTable) { super(); this.routerId = routerId; this.routerTable = routerTable; //TODO 记录临近的网络 int[] p = new int[routerTable.getList().size()]; for(int i = 0; i < routerTable.getList().size(); i++){ p[i] = Integer.parseInt(routerTable.getList().get(i)[0]); } this.nearNetwork = p; } }
EricLi404/Java-Demos
Rip-Demo/Router.java
1,763
//TODO 记录临近的网络
line_comment
zh-cn
package rip; import java.util.HashMap; public class Router { private final int routerId; private RouterTable routerTable; private int[] nearRouter; private int[] nearNetwork; public RouterTable getRouterTable() { return routerTable; } public void setRouterTable(RouterTable routerTable) { this.routerTable = routerTable; } public void changeRouterTable(RouterTable otherRouterTable){ // 规则: // 1. 传入的为其临近路由器的路由表 // 2. 解析路由表 // 3. 如果有自己路由表里有的网络,检查跳数是否为15,不为15进行以下操作 // 4. 如果“跳数+1” 小于 本路由表对应条目的跳数,则修改记录 // 5. 修改记录 “网络号(不变)”,“跳数+1”,“下一跳路由(该路由条目的来源路由)” // 6. else如果有本自己路由表里没有的网路,检查跳数是否为15,不为15进行以下操作 // 7. 添加记录 “网络号”,“跳数+1”,“下一跳路由(该路由条目的来源路由)” //将自己的路由表里 所有的网络号建立一个String,所有的跳数建立一个String, //遍历外来路由表的各个网络号,判断是否存在相同的值 //如果存在 判断跳数(1.是否不等于15,2,是否小于自己对应的跳数+1) // 如果满足,修改路由表对应数据 // 如果不满足。do nothing //如果不存在,判断跳数是否不等于15, // 如果满足,添加该路由条目 HashMap<Integer, String[] > otherList = otherRouterTable.getList(); HashMap<Integer, String[] > selfList = routerTable.getList(); String otherNetnum = ""; String otherTiaonum = ""; String selfNetnum = ""; String selfTiaonum = ""; String selfShouldMod = ""; String otherShouldMod = ""; String shouldAdd = ""; for(int i = 0 ; i < otherList.size(); i++){ otherNetnum += otherList.get(i)[0]; otherTiaonum += otherList.get(i)[1]; } for(int i = 0; i < selfList.size(); i++){ selfNetnum += selfList.get(i)[0]; selfTiaonum += selfList.get(i)[1]; } for(int i = 0; i < otherNetnum.length(); i++){ // System.out.println("第"+i+"循环检验========================"); int res = selfNetnum.indexOf(otherNetnum.substring(i,i+1)); int p = Integer.parseInt(otherTiaonum.substring(i, i+1)); if (res != -1) { int q = Integer.parseInt(selfTiaonum.substring(res, res+1)); if (p < 15) { if ((p+1) < q ) { //TODO 修改路由表对应数据 // System.out.println("premod======="+selfNetnum.substring(res, res+1)+"--------"+otherNetnum.substring(i,i+1)); selfShouldMod += String.valueOf(res); otherShouldMod += String.valueOf(i); } } }else if (res == -1) { if (p < 15) { //TODO 添加该条目 // System.out.println("preadd====="+otherNetnum.substring(i,i+1)); shouldAdd += String.valueOf(i); } }else { System.err.println("core change err"); } } if (selfShouldMod.length() > 0) { for(int i = 0; i < selfShouldMod.length(); i++){ // System.out.println("mod"); selfList.remove(selfShouldMod.substring(i,i+1)); String newChange[] = { otherList.get(Integer.parseInt(otherShouldMod.substring(i, i+1)))[0], String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(otherShouldMod.substring(i,i+1)))[1])+1), String.valueOf(otherRouterTable.getRouterID()) }; selfList.put(Integer.parseInt(selfShouldMod.substring(i,i+1)), newChange); } } if (shouldAdd.length() > 0) { // System.out.println("1111111111111self.size================="+selfList.size()); int len = selfList.size(); for(int i = 0; i < shouldAdd.length(); i++){ // System.out.println("add"); String newChange[] = { otherList.get(Integer.parseInt(shouldAdd.substring(i, i+1)))[0], String.valueOf(Integer.parseInt(otherList.get(Integer.parseInt(shouldAdd.substring(i,i+1)))[1])+1), String.valueOf(otherRouterTable.getRouterID()) }; selfList.put(len+i, newChange); // System.out.println("self.size================="+selfList.size()); } } routerTable.setList(selfList); setRouterTable(routerTable); } public int[] getNearRouter() { return nearRouter; } public void setNearRouter(int[] nearRouter) { this.nearRouter = nearRouter; } public int[] getNearNetwork() { return nearNetwork; } public void setNearNetwork(int[] nearNetwork) { this.nearNetwork = nearNetwork; } public int getRouterId() { return routerId; } public void echoRoutertable(){ RouterTable rtTables = getRouterTable(); HashMap<Integer, String[]> list = rtTables.getList(); System.out.println("*******路由器 "+getRouterTable().getRouterID()+" 路由表******"); for (int i = 0; i < list.size(); i++) { String[] pStrings = list.get(i); System.out.println("网络:"+pStrings[0]+" | "+"跳数:"+pStrings[1]+" | "+"下一跳路由器: "+pStrings[2]); } } public Router(int routerId, RouterTable routerTable) { super(); this.routerId = routerId; this.routerTable = routerTable; //TO <SUF> int[] p = new int[routerTable.getList().size()]; for(int i = 0; i < routerTable.getList().size(); i++){ p[i] = Integer.parseInt(routerTable.getList().get(i)[0]); } this.nearNetwork = p; } }
false
1,481
9
1,751
9
1,726
8
1,751
9
2,314
16
false
false
false
false
false
true
22789_44
/** * Copyright(c) Jade Techonologies Co., Ltd. */ package cn.eric.jdktools.data; import java.math.BigDecimal; /** * 格式化数字工具类 */ public class NumUtil { /** * 保留两位小数点 * @param value * @return */ public static double keepTwoPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } public static double keepFourPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } public static double keepSixPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } /** * 从命令行接收一个数,在其中调用 checkNum() 方法对其进行 * 验证,并返回相应的值 * @return 如果输入合法,返回输入的这个数 */ public static String getNum(String loanmoney) { // 判断用户输入是否合法 // 若合法,返回这个值;若非法返回 "0" if(checkNum(loanmoney)) { return loanmoney; } else { return ""; } } /** * 判断用户输入的数据是否合法,用户只能输入大于零的数字,不能输入其它字符 * @param s String * @return 如果用户输入数据合法,返回 true,否则返回 false */ private static boolean checkNum(String loanmoney) { // 如果用户输入的数里有非数字字符,则视为非法数据,返回 false try { float f = Float.valueOf(loanmoney); // 如果这个数小于零则视为非法数据,返回 false if(f < 0) { System.out.println("非法数据,请检查!"); return false; }else { return true; } } catch (NumberFormatException s) { System.out.println("非法数据,请检查!"); return false; } } /** * 把用户输入的数以小数点为界分割开来,并调用 numFormat() 方法 * 进行相应的中文金额大写形式的转换 * 注:传入的这个数应该是经过 roundString() 方法进行了四舍五入操作的 * @param s String * @return 转换好的中文金额大写形式的字符串 */ public static String splitNum(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 以小数点为界分割这个字符串 int index = loanmoney.indexOf("."); // 截取并转换这个数的整数部分 String intOnly = loanmoney.substring(0, index); String part1 = numFormat(1, intOnly); // 截取并转换这个数的小数部分 String smallOnly = loanmoney.substring(index + 1); String part2 = numFormat(2, smallOnly); // 把转换好了的整数部分和小数部分重新拼凑一个新的字符串 String newS = part1 + part2; return newS; } /** * 对传入的数进行四舍五入操作 * @param loanmoney 从命令行输入的那个数 * @return 四舍五入后的新值 */ public static String roundString(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 将这个数转换成 double 类型,并对其进行四舍五入操作 double d = Double.parseDouble(loanmoney); // 此操作作用在小数点后两位上 d = (d * 100 + 0.5) / 100; // 将 d 进行格式化 loanmoney = new java.text.DecimalFormat("##0.000").format(d); // 以小数点为界分割这个字符串 int index = loanmoney.indexOf("."); // 这个数的整数部分 String intOnly = loanmoney.substring(0, index); // 规定数值的最大长度只能到万亿单位,否则返回 "0" if(intOnly.length() > 13) { System.out.println("输入数据过大!(整数部分最多13位!)"); return ""; } // 这个数的小数部分 String smallOnly = loanmoney.substring(index + 1); // 如果小数部分大于两位,只截取小数点后两位 if(smallOnly.length() > 2) { String roundSmall = smallOnly.substring(0, 2); // 把整数部分和新截取的小数部分重新拼凑这个字符串 loanmoney = intOnly + "." + roundSmall; } return loanmoney; } /** * 把传入的数转换为中文金额大写形式 * @param flag int 标志位,1 表示转换整数部分,2 表示转换小数部分 * @param s String 要转换的字符串 * @return 转换好的带单位的中文金额大写形式 */ private static String numFormat(int flag, String loanmoney) { int sLength = loanmoney.length(); // 货币大写形式 String bigLetter[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; // 货币单位 String unit[] = {"元", "拾", "佰", "仟", "万", // 拾万位到仟万位 "拾", "佰", "仟", // 亿位到万亿位 "亿", "拾", "佰", "仟", "万"}; String small[] = {"分", "角"}; // 用来存放转换后的新字符串 String newS = ""; // 逐位替换为中文大写形式 for(int i = 0; i < sLength; i ++) { if(flag == 1) { // 转换整数部分为中文大写形式(带单位) newS = newS + bigLetter[loanmoney.charAt(i) - 48] + unit[sLength - i - 1]; } else if(flag == 2) { // 转换小数部分(带单位) newS = newS + bigLetter[loanmoney.charAt(i) - 48] + small[sLength - i - 1]; } } return newS; } /** * 把已经转换好的中文金额大写形式加以改进,清理这个字 * 符串里面多余的零,让这个字符串变得更加可观 * 注:传入的这个数应该是经过 splitNum() 方法进行处理,这个字 * 符串应该已经是用中文金额大写形式表示的 * @param s String 已经转换好的字符串 * @return 改进后的字符串 */ public static String cleanZero(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 如果用户开始输入了很多 0 去掉字符串前面多余的'零',使其看上去更符合习惯 while(loanmoney.charAt(0) == '零') { // 将字符串中的 "零" 和它对应的单位去掉 loanmoney = loanmoney.substring(2); // 如果用户当初输入的时候只输入了 0,则只返回一个 "零" if(loanmoney.length() == 0) { return "零"; } } // 字符串中存在多个'零'在一起的时候只读出一个'零',并省略多余的单位 /* 由于本人对算法的研究太菜了,只能用4个正则表达式去转换了,各位大虾别介意哈... */ String regex1[] = {"零仟", "零佰", "零拾"}; String regex2[] = {"零亿", "零万", "零元"}; String regex3[] = {"亿", "万", "元"}; String regex4[] = {"零角", "零分"}; // 第一轮转换把 "零仟", 零佰","零拾"等字符串替换成一个"零" for(int i = 0; i < 3; i ++) { loanmoney = loanmoney.replaceAll(regex1[i], "零"); } // 第二轮转换考虑 "零亿","零万","零元"等情况 // "亿","万","元"这些单位有些情况是不能省的,需要保留下来 for(int i = 0; i < 3; i ++) { // 当第一轮转换过后有可能有很多个零叠在一起 // 要把很多个重复的零变成一个零 loanmoney = loanmoney.replaceAll("零零零", "零"); loanmoney = loanmoney.replaceAll("零零", "零"); loanmoney = loanmoney.replaceAll(regex2[i], regex3[i]); } // 第三轮转换把"零角","零分"字符串省略 for(int i = 0; i < 2; i ++) { loanmoney = loanmoney.replaceAll(regex4[i], ""); } // 当"万"到"亿"之间全部是"零"的时候,忽略"亿万"单位,只保留一个"亿" loanmoney = loanmoney.replaceAll("亿万", "亿"); return loanmoney; } /** * 测试程序的可行性 * @param args */ public static void main(String[] args) { System.out.println("\n--------将数字转换成中文金额的大写形式------------\n"); NumUtil t2r = new NumUtil(); String money= getNum("bbb600ttt98726a"); System.out.println(money); String money1= splitNum("17800260026.26"); System.out.println(money1); String money2 = roundString("3027830056.34426"); System.out.println(money2); String money3 = numFormat(1, "37356653"); System.out.println(money3); String money4 = numFormat(2, "34"); System.out.println(money4); String money5 = cleanZero("零零零零零零壹佰柒拾捌万贰仟陆佰贰拾陆元贰角陆分"); System.out.println(money5); } }
EricLoveMia/JavaTools
src/main/java/cn/eric/jdktools/data/NumUtil.java
2,585
// "亿","万","元"这些单位有些情况是不能省的,需要保留下来
line_comment
zh-cn
/** * Copyright(c) Jade Techonologies Co., Ltd. */ package cn.eric.jdktools.data; import java.math.BigDecimal; /** * 格式化数字工具类 */ public class NumUtil { /** * 保留两位小数点 * @param value * @return */ public static double keepTwoPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } public static double keepFourPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(4,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } public static double keepSixPoint(double value) { BigDecimal b = new BigDecimal(value); double result = b.setScale(6,BigDecimal.ROUND_HALF_UP).doubleValue(); return result; } /** * 从命令行接收一个数,在其中调用 checkNum() 方法对其进行 * 验证,并返回相应的值 * @return 如果输入合法,返回输入的这个数 */ public static String getNum(String loanmoney) { // 判断用户输入是否合法 // 若合法,返回这个值;若非法返回 "0" if(checkNum(loanmoney)) { return loanmoney; } else { return ""; } } /** * 判断用户输入的数据是否合法,用户只能输入大于零的数字,不能输入其它字符 * @param s String * @return 如果用户输入数据合法,返回 true,否则返回 false */ private static boolean checkNum(String loanmoney) { // 如果用户输入的数里有非数字字符,则视为非法数据,返回 false try { float f = Float.valueOf(loanmoney); // 如果这个数小于零则视为非法数据,返回 false if(f < 0) { System.out.println("非法数据,请检查!"); return false; }else { return true; } } catch (NumberFormatException s) { System.out.println("非法数据,请检查!"); return false; } } /** * 把用户输入的数以小数点为界分割开来,并调用 numFormat() 方法 * 进行相应的中文金额大写形式的转换 * 注:传入的这个数应该是经过 roundString() 方法进行了四舍五入操作的 * @param s String * @return 转换好的中文金额大写形式的字符串 */ public static String splitNum(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 以小数点为界分割这个字符串 int index = loanmoney.indexOf("."); // 截取并转换这个数的整数部分 String intOnly = loanmoney.substring(0, index); String part1 = numFormat(1, intOnly); // 截取并转换这个数的小数部分 String smallOnly = loanmoney.substring(index + 1); String part2 = numFormat(2, smallOnly); // 把转换好了的整数部分和小数部分重新拼凑一个新的字符串 String newS = part1 + part2; return newS; } /** * 对传入的数进行四舍五入操作 * @param loanmoney 从命令行输入的那个数 * @return 四舍五入后的新值 */ public static String roundString(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 将这个数转换成 double 类型,并对其进行四舍五入操作 double d = Double.parseDouble(loanmoney); // 此操作作用在小数点后两位上 d = (d * 100 + 0.5) / 100; // 将 d 进行格式化 loanmoney = new java.text.DecimalFormat("##0.000").format(d); // 以小数点为界分割这个字符串 int index = loanmoney.indexOf("."); // 这个数的整数部分 String intOnly = loanmoney.substring(0, index); // 规定数值的最大长度只能到万亿单位,否则返回 "0" if(intOnly.length() > 13) { System.out.println("输入数据过大!(整数部分最多13位!)"); return ""; } // 这个数的小数部分 String smallOnly = loanmoney.substring(index + 1); // 如果小数部分大于两位,只截取小数点后两位 if(smallOnly.length() > 2) { String roundSmall = smallOnly.substring(0, 2); // 把整数部分和新截取的小数部分重新拼凑这个字符串 loanmoney = intOnly + "." + roundSmall; } return loanmoney; } /** * 把传入的数转换为中文金额大写形式 * @param flag int 标志位,1 表示转换整数部分,2 表示转换小数部分 * @param s String 要转换的字符串 * @return 转换好的带单位的中文金额大写形式 */ private static String numFormat(int flag, String loanmoney) { int sLength = loanmoney.length(); // 货币大写形式 String bigLetter[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; // 货币单位 String unit[] = {"元", "拾", "佰", "仟", "万", // 拾万位到仟万位 "拾", "佰", "仟", // 亿位到万亿位 "亿", "拾", "佰", "仟", "万"}; String small[] = {"分", "角"}; // 用来存放转换后的新字符串 String newS = ""; // 逐位替换为中文大写形式 for(int i = 0; i < sLength; i ++) { if(flag == 1) { // 转换整数部分为中文大写形式(带单位) newS = newS + bigLetter[loanmoney.charAt(i) - 48] + unit[sLength - i - 1]; } else if(flag == 2) { // 转换小数部分(带单位) newS = newS + bigLetter[loanmoney.charAt(i) - 48] + small[sLength - i - 1]; } } return newS; } /** * 把已经转换好的中文金额大写形式加以改进,清理这个字 * 符串里面多余的零,让这个字符串变得更加可观 * 注:传入的这个数应该是经过 splitNum() 方法进行处理,这个字 * 符串应该已经是用中文金额大写形式表示的 * @param s String 已经转换好的字符串 * @return 改进后的字符串 */ public static String cleanZero(String loanmoney) { // 如果传入的是空串则继续返回空串 if("".equals(loanmoney)) { return ""; } // 如果用户开始输入了很多 0 去掉字符串前面多余的'零',使其看上去更符合习惯 while(loanmoney.charAt(0) == '零') { // 将字符串中的 "零" 和它对应的单位去掉 loanmoney = loanmoney.substring(2); // 如果用户当初输入的时候只输入了 0,则只返回一个 "零" if(loanmoney.length() == 0) { return "零"; } } // 字符串中存在多个'零'在一起的时候只读出一个'零',并省略多余的单位 /* 由于本人对算法的研究太菜了,只能用4个正则表达式去转换了,各位大虾别介意哈... */ String regex1[] = {"零仟", "零佰", "零拾"}; String regex2[] = {"零亿", "零万", "零元"}; String regex3[] = {"亿", "万", "元"}; String regex4[] = {"零角", "零分"}; // 第一轮转换把 "零仟", 零佰","零拾"等字符串替换成一个"零" for(int i = 0; i < 3; i ++) { loanmoney = loanmoney.replaceAll(regex1[i], "零"); } // 第二轮转换考虑 "零亿","零万","零元"等情况 // "亿 <SUF> for(int i = 0; i < 3; i ++) { // 当第一轮转换过后有可能有很多个零叠在一起 // 要把很多个重复的零变成一个零 loanmoney = loanmoney.replaceAll("零零零", "零"); loanmoney = loanmoney.replaceAll("零零", "零"); loanmoney = loanmoney.replaceAll(regex2[i], regex3[i]); } // 第三轮转换把"零角","零分"字符串省略 for(int i = 0; i < 2; i ++) { loanmoney = loanmoney.replaceAll(regex4[i], ""); } // 当"万"到"亿"之间全部是"零"的时候,忽略"亿万"单位,只保留一个"亿" loanmoney = loanmoney.replaceAll("亿万", "亿"); return loanmoney; } /** * 测试程序的可行性 * @param args */ public static void main(String[] args) { System.out.println("\n--------将数字转换成中文金额的大写形式------------\n"); NumUtil t2r = new NumUtil(); String money= getNum("bbb600ttt98726a"); System.out.println(money); String money1= splitNum("17800260026.26"); System.out.println(money1); String money2 = roundString("3027830056.34426"); System.out.println(money2); String money3 = numFormat(1, "37356653"); System.out.println(money3); String money4 = numFormat(2, "34"); System.out.println(money4); String money5 = cleanZero("零零零零零零壹佰柒拾捌万贰仟陆佰贰拾陆元贰角陆分"); System.out.println(money5); } }
false
2,431
20
2,585
23
2,619
20
2,585
23
3,612
34
false
false
false
false
false
true
25178_6
package com.example.guohouxiao.musicalbum.utils; /** * Created by guohouxiao on 2017/9/5. * 表的属性 */ public class Config { public static final String USER_TABLE = "_User";//用户表 public static final String AVATAR = "avatar";//用户头像 public static final String NICKNAME = "nickname";//用户昵称 public static final String DESC = "desc";//简介 public static final String BOOKMARKALBUM = "bookmarkalbum";//收藏的相册 public static final String LIKEALBUM = "likealbum";//喜欢的相册 public static final String MUSICALBUM_TABLE = "MusicAlbum";//音乐相册表 public static final String USERID = "userId";//作者的ID public static final String ALBUMNAME = "albumname";//相册名称 public static final String COVER = "cover";//封面 public static final String PLACE = "place";//地点 public static final String WHERECREATED = "whereCreated";//经纬度 public static final String PLAYMODE = "playmode";//模板 public static final String MUSIC = "music";//音乐 public static final String PHOTOS = "photos";//图片 public static final String SUBTITLES = "subtitles";//字幕 public static final String ISPUBLIC = "ispublic";//是否公开 public static final String LIKENUMBER = "likenumber";//获得的喜欢数 }
ErisRolo/MusicAlbum
app/src/main/java/com/example/guohouxiao/musicalbum/utils/Config.java
358
//音乐相册表
line_comment
zh-cn
package com.example.guohouxiao.musicalbum.utils; /** * Created by guohouxiao on 2017/9/5. * 表的属性 */ public class Config { public static final String USER_TABLE = "_User";//用户表 public static final String AVATAR = "avatar";//用户头像 public static final String NICKNAME = "nickname";//用户昵称 public static final String DESC = "desc";//简介 public static final String BOOKMARKALBUM = "bookmarkalbum";//收藏的相册 public static final String LIKEALBUM = "likealbum";//喜欢的相册 public static final String MUSICALBUM_TABLE = "MusicAlbum";//音乐 <SUF> public static final String USERID = "userId";//作者的ID public static final String ALBUMNAME = "albumname";//相册名称 public static final String COVER = "cover";//封面 public static final String PLACE = "place";//地点 public static final String WHERECREATED = "whereCreated";//经纬度 public static final String PLAYMODE = "playmode";//模板 public static final String MUSIC = "music";//音乐 public static final String PHOTOS = "photos";//图片 public static final String SUBTITLES = "subtitles";//字幕 public static final String ISPUBLIC = "ispublic";//是否公开 public static final String LIKENUMBER = "likenumber";//获得的喜欢数 }
false
322
5
358
6
319
5
358
6
428
8
false
false
false
false
false
true
45050_10
package cn.com.fusio.event.merge; import cn.com.fusio.event.BaseEvent; import cn.com.fusio.event.entity.ArticleInfo; import cn.com.fusio.event.entity.FormInfo; import cn.com.fusio.event.entity.UserInfo; import cn.com.fusio.event.raw.PinganBehaviorData; import org.drools.core.util.StringUtils; /** * @Description: 丰富 PinganBehaviorData 类 * @Author : Ernest * @Date : 2017/8/20 20:07 */ public class PinganEduPVEnrich extends BaseEvent { /** * 用户行为记录 */ private PinganBehaviorData behaviorData ; /** * 用户信息 */ private UserInfo userInfo ; /** * 文章信息,当 bd:contentType=article 时,有值 */ private ArticleInfo articleInfo ; /** * 表单信息,当 bd:contentType=form 时,有值 */ private FormInfo formInfo ; public PinganEduPVEnrich() {} public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, ArticleInfo articleInfo) { this.behaviorData = behaviorData; this.userInfo = userInfo; this.articleInfo = articleInfo; // 指定 DRL 中的 @timestamp this.eventTime = behaviorData.getCollector_tstamp() ; } /** * 判断行为数据是否包含某些标签:PinganEduPVEnrich * @param tags * @return */ public boolean containTags(String... tags){ boolean isValid = false ; // 1.2.过滤标签条件 // 59effffd48b743bbbf9ff148341b32ee:事业;63dd1d21acfd4452bf72130123cf2f3c:职位 String cntTags = "" ; String cntType = behaviorData.getContentType(); if("article".equals(cntType)){ cntTags = articleInfo.getCatg_name() ; }else if("form".equals(cntType)){ // cntTags = formInfo.getForm_tags() ; cntTags = "心理" ; //暂时 表单 标签都作为 心理。 } // 判断是否包含标签, 并集 if(!StringUtils.isEmpty(cntTags)){ for(int i = 0 ; i<tags.length ;i++){ if(cntTags.equals(tags[i])) isValid = true ; } } return isValid ; } /** * 判断用户是否属于某个省份:或 * @param city * @return */ public Boolean isBelongToProvince(String... city){ boolean yesOrNo = false ; String province = null ; if(userInfo != null ){ province = this.userInfo.getAll_province(); } if(province !=null && "".equals(province)){ for(int i = 0 ; i < city.length ;i++){ if(province.equals(city[i])){ yesOrNo = true ; break; } } } return yesOrNo ; } /** * 年龄大于 age * @param age * @return */ public Boolean isAgeGtNum(Integer age){ boolean yesOrNo = false ; Integer userAge = null ; if(userInfo != null ){ userAge = userInfo.getAge(); } if( userAge != null ){ if(userInfo.getAge() > age){ yesOrNo = true ; } } return yesOrNo ; } /** * 年龄小于 age * @param age * @return */ public Boolean isAgeLtNum(Integer age){ boolean yesOrNo = false ; if(userInfo.getAge() != null ){ if(userInfo.getAge() < age){ yesOrNo = true ; } } return yesOrNo ; } public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, FormInfo formInfo) { this.behaviorData = behaviorData; this.userInfo = userInfo; this.formInfo = formInfo; // 指定 DRL 中的 @timestamp this.eventTime = behaviorData.getCollector_tstamp() ; } public PinganBehaviorData getBehaviorData() { return behaviorData; } public void setBehaviorData(PinganBehaviorData behaviorData) { this.behaviorData = behaviorData; } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public ArticleInfo getArticleInfo() { return articleInfo; } public void setArticleInfo(ArticleInfo articleInfo) { this.articleInfo = articleInfo; } public FormInfo getFormInfo() { return formInfo; } public void setFormInfo(FormInfo formInfo) { this.formInfo = formInfo; } @Override public String toString() { return "PinganEduPVEnrich{" + "behaviorData=" + behaviorData + ", userInfo=" + userInfo + ", articleInfo=" + articleInfo + ", formInfo=" + formInfo + '}'; } }
ErnestMing/Drools-CEP-EventFlow
src/main/java/cn/com/fusio/event/merge/PinganEduPVEnrich.java
1,237
//暂时 表单 标签都作为 心理。
line_comment
zh-cn
package cn.com.fusio.event.merge; import cn.com.fusio.event.BaseEvent; import cn.com.fusio.event.entity.ArticleInfo; import cn.com.fusio.event.entity.FormInfo; import cn.com.fusio.event.entity.UserInfo; import cn.com.fusio.event.raw.PinganBehaviorData; import org.drools.core.util.StringUtils; /** * @Description: 丰富 PinganBehaviorData 类 * @Author : Ernest * @Date : 2017/8/20 20:07 */ public class PinganEduPVEnrich extends BaseEvent { /** * 用户行为记录 */ private PinganBehaviorData behaviorData ; /** * 用户信息 */ private UserInfo userInfo ; /** * 文章信息,当 bd:contentType=article 时,有值 */ private ArticleInfo articleInfo ; /** * 表单信息,当 bd:contentType=form 时,有值 */ private FormInfo formInfo ; public PinganEduPVEnrich() {} public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, ArticleInfo articleInfo) { this.behaviorData = behaviorData; this.userInfo = userInfo; this.articleInfo = articleInfo; // 指定 DRL 中的 @timestamp this.eventTime = behaviorData.getCollector_tstamp() ; } /** * 判断行为数据是否包含某些标签:PinganEduPVEnrich * @param tags * @return */ public boolean containTags(String... tags){ boolean isValid = false ; // 1.2.过滤标签条件 // 59effffd48b743bbbf9ff148341b32ee:事业;63dd1d21acfd4452bf72130123cf2f3c:职位 String cntTags = "" ; String cntType = behaviorData.getContentType(); if("article".equals(cntType)){ cntTags = articleInfo.getCatg_name() ; }else if("form".equals(cntType)){ // cntTags = formInfo.getForm_tags() ; cntTags = "心理" ; //暂时 <SUF> } // 判断是否包含标签, 并集 if(!StringUtils.isEmpty(cntTags)){ for(int i = 0 ; i<tags.length ;i++){ if(cntTags.equals(tags[i])) isValid = true ; } } return isValid ; } /** * 判断用户是否属于某个省份:或 * @param city * @return */ public Boolean isBelongToProvince(String... city){ boolean yesOrNo = false ; String province = null ; if(userInfo != null ){ province = this.userInfo.getAll_province(); } if(province !=null && "".equals(province)){ for(int i = 0 ; i < city.length ;i++){ if(province.equals(city[i])){ yesOrNo = true ; break; } } } return yesOrNo ; } /** * 年龄大于 age * @param age * @return */ public Boolean isAgeGtNum(Integer age){ boolean yesOrNo = false ; Integer userAge = null ; if(userInfo != null ){ userAge = userInfo.getAge(); } if( userAge != null ){ if(userInfo.getAge() > age){ yesOrNo = true ; } } return yesOrNo ; } /** * 年龄小于 age * @param age * @return */ public Boolean isAgeLtNum(Integer age){ boolean yesOrNo = false ; if(userInfo.getAge() != null ){ if(userInfo.getAge() < age){ yesOrNo = true ; } } return yesOrNo ; } public PinganEduPVEnrich(PinganBehaviorData behaviorData, UserInfo userInfo, FormInfo formInfo) { this.behaviorData = behaviorData; this.userInfo = userInfo; this.formInfo = formInfo; // 指定 DRL 中的 @timestamp this.eventTime = behaviorData.getCollector_tstamp() ; } public PinganBehaviorData getBehaviorData() { return behaviorData; } public void setBehaviorData(PinganBehaviorData behaviorData) { this.behaviorData = behaviorData; } public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public ArticleInfo getArticleInfo() { return articleInfo; } public void setArticleInfo(ArticleInfo articleInfo) { this.articleInfo = articleInfo; } public FormInfo getFormInfo() { return formInfo; } public void setFormInfo(FormInfo formInfo) { this.formInfo = formInfo; } @Override public String toString() { return "PinganEduPVEnrich{" + "behaviorData=" + behaviorData + ", userInfo=" + userInfo + ", articleInfo=" + articleInfo + ", formInfo=" + formInfo + '}'; } }
false
1,167
14
1,237
13
1,342
10
1,237
13
1,579
20
false
false
false
false
false
true
32949_5
package com.eshel.takeout.permission; import android.app.Activity; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import com.eshel.takeout.utils.UIUtils; /** * 项目名称: GooglePlay * 创建人: Eshel * 创建时间:2017/7/12 19时02分 * 描述: TODO */ public class RequestPermissionUtil { /** * @param permission Manifest.permission.*** * @return */ public static boolean requestPermission(Activity activity,String permission,int requestCode){ //检查权限: 检查用户是不是已经授权 int checkSelfPermission = ContextCompat.checkSelfPermission(UIUtils.getContext(), permission); //拒绝 : 检查到用户之前拒绝授权 if(checkSelfPermission == PackageManager.PERMISSION_DENIED){ //申请权限 ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode); }else if(checkSelfPermission == PackageManager.PERMISSION_GRANTED){ //已经授权 return true; }else { ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode); } return false; } }
EshelGuo/PermissionsUtil
permission/RequestPermissionUtil.java
322
//已经授权
line_comment
zh-cn
package com.eshel.takeout.permission; import android.app.Activity; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import com.eshel.takeout.utils.UIUtils; /** * 项目名称: GooglePlay * 创建人: Eshel * 创建时间:2017/7/12 19时02分 * 描述: TODO */ public class RequestPermissionUtil { /** * @param permission Manifest.permission.*** * @return */ public static boolean requestPermission(Activity activity,String permission,int requestCode){ //检查权限: 检查用户是不是已经授权 int checkSelfPermission = ContextCompat.checkSelfPermission(UIUtils.getContext(), permission); //拒绝 : 检查到用户之前拒绝授权 if(checkSelfPermission == PackageManager.PERMISSION_DENIED){ //申请权限 ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode); }else if(checkSelfPermission == PackageManager.PERMISSION_GRANTED){ //已经 <SUF> return true; }else { ActivityCompat.requestPermissions(activity,new String[]{permission},requestCode); } return false; } }
false
251
3
322
3
299
3
322
3
412
9
false
false
false
false
false
true
61598_4
/** * 创建时间:2016-2-23 */ package cn.aofeng.demo.httpclient; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.FileEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; /** * HttpClient的基本操作。 * * @author <a href="mailto:[email protected]">聂勇</a> */ public class HttpClientBasic { private static Logger _logger = Logger.getLogger(HttpClientBasic.class); private static String _targetHost = "http://127.0.0.1:8888"; private static String _charset = "utf-8"; public void get() throws URISyntaxException, ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(_targetHost+"/get"); CloseableHttpResponse response = client.execute(get); processResponse(response); } public void post() throws ClientProtocolException, IOException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("chinese", "中文")); params.add(new BasicNameValuePair("english", "英文")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, _charset); CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost+"/post"); post.addHeader("Cookie", "character=abcdefghijklmnopqrstuvwxyz; sign=abc-123-jkl-098"); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); processResponse(response); } public void sendFile(String filePath) throws UnsupportedOperationException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost+"/file"); File file = new File(filePath); FileEntity entity = new FileEntity(file, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), _charset)); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); processResponse(response); } private void processResponse(CloseableHttpResponse response) throws UnsupportedOperationException, IOException { try { // 获取响应头 Header[] headers = response.getAllHeaders(); for (Header header : headers) { _logger.info(header.getName() + ":" + header.getValue()); } // 获取状态信息 StatusLine sl =response.getStatusLine(); _logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s", sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) ); // 获取响应内容 HttpEntity entity = response.getEntity(); _logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s", null == entity.getContentType() ? "" : entity.getContentType().getValue(), entity.getContentLength(), null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) ); _logger.info(EntityUtils.toString(entity, _charset)); // _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同 } finally { response.close(); } } /** * @param args */ public static void main(String[] args) throws Exception { HttpClientBasic basic = new HttpClientBasic(); // basic.get(); // basic.post(); basic.sendFile("/devdata/projects/open_source/mine/JavaTutorial/LICENSE"); } }
Estom/notes
Java/Java源代码/codedemo/httpclient/HttpClientBasic.java
1,046
// 获取状态信息
line_comment
zh-cn
/** * 创建时间:2016-2-23 */ package cn.aofeng.demo.httpclient; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.List; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.FileEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.apache.log4j.Logger; /** * HttpClient的基本操作。 * * @author <a href="mailto:[email protected]">聂勇</a> */ public class HttpClientBasic { private static Logger _logger = Logger.getLogger(HttpClientBasic.class); private static String _targetHost = "http://127.0.0.1:8888"; private static String _charset = "utf-8"; public void get() throws URISyntaxException, ClientProtocolException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpGet get = new HttpGet(_targetHost+"/get"); CloseableHttpResponse response = client.execute(get); processResponse(response); } public void post() throws ClientProtocolException, IOException { List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("chinese", "中文")); params.add(new BasicNameValuePair("english", "英文")); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, _charset); CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost+"/post"); post.addHeader("Cookie", "character=abcdefghijklmnopqrstuvwxyz; sign=abc-123-jkl-098"); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); processResponse(response); } public void sendFile(String filePath) throws UnsupportedOperationException, IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPost post = new HttpPost(_targetHost+"/file"); File file = new File(filePath); FileEntity entity = new FileEntity(file, ContentType.create(ContentType.TEXT_PLAIN.getMimeType(), _charset)); post.setEntity(entity); CloseableHttpResponse response = client.execute(post); processResponse(response); } private void processResponse(CloseableHttpResponse response) throws UnsupportedOperationException, IOException { try { // 获取响应头 Header[] headers = response.getAllHeaders(); for (Header header : headers) { _logger.info(header.getName() + ":" + header.getValue()); } // 获取 <SUF> StatusLine sl =response.getStatusLine(); _logger.info( String.format("ProtocolVersion:%s, StatusCode:%d, Desc:%s", sl.getProtocolVersion().toString(), sl.getStatusCode(), sl.getReasonPhrase()) ); // 获取响应内容 HttpEntity entity = response.getEntity(); _logger.info( String.format("ContentType:%s, Length:%d, Encoding:%s", null == entity.getContentType() ? "" : entity.getContentType().getValue(), entity.getContentLength(), null == entity.getContentEncoding() ? "" : entity.getContentEncoding().getValue()) ); _logger.info(EntityUtils.toString(entity, _charset)); // _logger.info( IOUtils.toString(entity.getContent(), _charset) ); // 大部分情况下效果与上行语句等同,但实现上的编码处理不同 } finally { response.close(); } } /** * @param args */ public static void main(String[] args) throws Exception { HttpClientBasic basic = new HttpClientBasic(); // basic.get(); // basic.post(); basic.sendFile("/devdata/projects/open_source/mine/JavaTutorial/LICENSE"); } }
false
881
4
1,046
4
1,110
4
1,046
4
1,284
8
false
false
false
false
false
true
47478_1
package com.dcx.concurrency.dcxTest; //作者:卡巴拉的树 // 链接:https://juejin.im/post/5a38d2046fb9a045076fcb1f // 来源:掘金 // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 //厕所 //种族 import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; class Employee implements Runnable { private String id; private Semaphore semaphore; private static Random random = new Random(47); public Employee(String id, Semaphore semaphore) { this.id = id; this.semaphore = semaphore; } public void run() { try { semaphore.acquire(); System.out.println(this.id + "is using the toilet"); TimeUnit.MILLISECONDS.sleep(random.nextInt(2000)); semaphore.release(); System.out.println(this.id + "is leaving"); } catch (InterruptedException e) { } } } public class ToiletRace { private static final int THREAD_COUNT = 30; private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); // 10个坑位 控制并行度 private static Semaphore semaphore = new Semaphore(10); public static void main(String[] args) { for (int i = 0; i < THREAD_COUNT; i++) { threadPool.execute(new Employee(String.valueOf(i), semaphore)); } threadPool.shutdown(); } }
EthanDCX/High-concurrency
src/main/java/com/dcx/concurrency/dcxTest/ToiletRace.java
424
// 链接:https://juejin.im/post/5a38d2046fb9a045076fcb1f
line_comment
zh-cn
package com.dcx.concurrency.dcxTest; //作者:卡巴拉的树 // 链接 <SUF> // 来源:掘金 // 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 //厕所 //种族 import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; class Employee implements Runnable { private String id; private Semaphore semaphore; private static Random random = new Random(47); public Employee(String id, Semaphore semaphore) { this.id = id; this.semaphore = semaphore; } public void run() { try { semaphore.acquire(); System.out.println(this.id + "is using the toilet"); TimeUnit.MILLISECONDS.sleep(random.nextInt(2000)); semaphore.release(); System.out.println(this.id + "is leaving"); } catch (InterruptedException e) { } } } public class ToiletRace { private static final int THREAD_COUNT = 30; private static ExecutorService threadPool = Executors.newFixedThreadPool(THREAD_COUNT); // 10个坑位 控制并行度 private static Semaphore semaphore = new Semaphore(10); public static void main(String[] args) { for (int i = 0; i < THREAD_COUNT; i++) { threadPool.execute(new Employee(String.valueOf(i), semaphore)); } threadPool.shutdown(); } }
false
352
37
424
34
429
35
424
34
532
39
false
false
false
false
false
true
28574_6
package TanXin; import java.util.*; /** * @description: * @author: wuboyu * @date: 2022-07-21 16:58 */ public class L56 { //56. 合并区间 //以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。 // // // //示例 1: // //输入:intervals = [[1,3],[2,6],[8,10],[15,18]] //输出:[[1,6],[8,10],[15,18]] //解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6]. //示例 2: // //输入:intervals = [[1,4],[4,5]] //输出:[[1,5]] //解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。 // // //提示: // //1 <= intervals.length <= 104 //intervals[i].length == 2 //0 <= starti <= endi <= 104 public int[][] merge(int[][] intervals) { //思路 //首先 按 左排序 //如果此区间的左>上一个的right 不合 //如果当前区间的左<=上一个的right 合并 Comparator<int[]> com=new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o1[0],o2[0]); } }; Arrays.sort(intervals,com); LinkedList<int[]> answer=new LinkedList<>(); answer.add(intervals[0]); int lastright=intervals[0][1]; for(int i=1;i<intervals.length;i++){ if(intervals[i][0]<=lastright){ //合并 //当前区间的左区间 在上一个区间的右区间中 int[] temp=answer.getLast(); answer.removeLast(); temp[1]=Math.max(intervals[i][1],lastright); answer.add(temp); lastright=Math.max(intervals[i][1],lastright); }else { //不合并 answer.add(intervals[i]); lastright=intervals[i][1]; } } return answer.toArray(new int[answer.size()][]); } }
Etherstrings/Algorithm
src/TanXin/L56.java
639
//解释:区间 [1,3] 和 [2,6] 重叠, 将它们合并为 [1,6].
line_comment
zh-cn
package TanXin; import java.util.*; /** * @description: * @author: wuboyu * @date: 2022-07-21 16:58 */ public class L56 { //56. 合并区间 //以数组 intervals 表示若干个区间的集合,其中单个区间为 intervals[i] = [starti, endi] 。请你合并所有重叠的区间,并返回 一个不重叠的区间数组,该数组需恰好覆盖输入中的所有区间 。 // // // //示例 1: // //输入:intervals = [[1,3],[2,6],[8,10],[15,18]] //输出:[[1,6],[8,10],[15,18]] //解释 <SUF> //示例 2: // //输入:intervals = [[1,4],[4,5]] //输出:[[1,5]] //解释:区间 [1,4] 和 [4,5] 可被视为重叠区间。 // // //提示: // //1 <= intervals.length <= 104 //intervals[i].length == 2 //0 <= starti <= endi <= 104 public int[][] merge(int[][] intervals) { //思路 //首先 按 左排序 //如果此区间的左>上一个的right 不合 //如果当前区间的左<=上一个的right 合并 Comparator<int[]> com=new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return Integer.compare(o1[0],o2[0]); } }; Arrays.sort(intervals,com); LinkedList<int[]> answer=new LinkedList<>(); answer.add(intervals[0]); int lastright=intervals[0][1]; for(int i=1;i<intervals.length;i++){ if(intervals[i][0]<=lastright){ //合并 //当前区间的左区间 在上一个区间的右区间中 int[] temp=answer.getLast(); answer.removeLast(); temp[1]=Math.max(intervals[i][1],lastright); answer.add(temp); lastright=Math.max(intervals[i][1],lastright); }else { //不合并 answer.add(intervals[i]); lastright=intervals[i][1]; } } return answer.toArray(new int[answer.size()][]); } }
false
598
29
639
30
657
27
639
30
791
40
false
false
false
false
false
true
46976_0
package web; import my_music.*; import java.util.ArrayList; import java.util.List; public class Constants { public static MusicDemo ErGe = new MusicDemo("快乐儿歌","无","佚名",0,0); public final static MusicDemo Jiangjunling = new MusicDemo("将军令","五月天", "YOUR LEGEND ~燃烧的生命~", 0,0); private static final User u1 = new User("Spark", "12121", "000", 0); private static final User u2 = new User("降临者", "12121", "000", 0); public static List<MusicDemo> musicLists = getMusicLists(); public static List<MusicDemo> getMusicLists(){ ArrayList<MusicDemo> musicDemos = new ArrayList<>(); Comments comments = new Comments(); //一些例子 comments.put(new SingleComment(u1, "太打动我了这首曲子!", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(u2, "一个小评论!", new MyDate(2023,4,30,0,16,52))); comments.put(new SingleComment(u1, "这是一个评论", new MyDate(2023,1,30,14,23,12))); comments.put(new SingleComment(u1, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2022,11,6,13,11,52))); comments.put(new SingleComment(u1, "这是依然一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(u2, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(new User("Knight", "16121", "000", 0), "好听", new MyDate(2023,4,30,0,11,52))); musicDemos.add(ErGe); Jiangjunling.setComments(comments); musicDemos.add(Jiangjunling); MusicDemo demo = new MusicDemo("转眼", "五月天", "自传", 0, 0); demo.setComments(new Comments(new SingleComment(u1, "泪目", new MyDate(2022,10,14,16,29,4)))); musicDemos.add(demo); musicDemos.add(new MusicDemo("兄弟","五月天","自传", 0,0)); musicDemos.add(new MusicDemo("顽固","五月天","自传", 0,0)); musicDemos.add(new MusicDemo("派对动物","五月天","自传",0,0)); musicDemos.add(new MusicDemo("干杯","五月天","第二人生-明日版",0,0)); return musicDemos; } }
Ethylene9160/SUSTC_EE317_Android_applications
musicPlayer/src_server/web/Constants.java
814
//一些例子
line_comment
zh-cn
package web; import my_music.*; import java.util.ArrayList; import java.util.List; public class Constants { public static MusicDemo ErGe = new MusicDemo("快乐儿歌","无","佚名",0,0); public final static MusicDemo Jiangjunling = new MusicDemo("将军令","五月天", "YOUR LEGEND ~燃烧的生命~", 0,0); private static final User u1 = new User("Spark", "12121", "000", 0); private static final User u2 = new User("降临者", "12121", "000", 0); public static List<MusicDemo> musicLists = getMusicLists(); public static List<MusicDemo> getMusicLists(){ ArrayList<MusicDemo> musicDemos = new ArrayList<>(); Comments comments = new Comments(); //一些 <SUF> comments.put(new SingleComment(u1, "太打动我了这首曲子!", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(u2, "一个小评论!", new MyDate(2023,4,30,0,16,52))); comments.put(new SingleComment(u1, "这是一个评论", new MyDate(2023,1,30,14,23,12))); comments.put(new SingleComment(u1, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2022,11,6,13,11,52))); comments.put(new SingleComment(u1, "这是依然一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(u2, "这是一个长长长长长长长长长长长长长长长的评的的的的论", new MyDate(2023,4,30,0,11,52))); comments.put(new SingleComment(new User("Knight", "16121", "000", 0), "好听", new MyDate(2023,4,30,0,11,52))); musicDemos.add(ErGe); Jiangjunling.setComments(comments); musicDemos.add(Jiangjunling); MusicDemo demo = new MusicDemo("转眼", "五月天", "自传", 0, 0); demo.setComments(new Comments(new SingleComment(u1, "泪目", new MyDate(2022,10,14,16,29,4)))); musicDemos.add(demo); musicDemos.add(new MusicDemo("兄弟","五月天","自传", 0,0)); musicDemos.add(new MusicDemo("顽固","五月天","自传", 0,0)); musicDemos.add(new MusicDemo("派对动物","五月天","自传",0,0)); musicDemos.add(new MusicDemo("干杯","五月天","第二人生-明日版",0,0)); return musicDemos; } }
false
705
3
814
3
791
3
814
3
925
5
false
false
false
false
false
true
45491_6
package com.rookie.stack.ai.domain.chat; 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 eumenides * @description * @date 2023/11/28 */ @Data @Builder @Slf4j @JsonInclude(JsonInclude.Include.NON_NULL) @NoArgsConstructor @AllArgsConstructor public class ChatCompletionRequest implements Serializable { /** 默认模型 */ private String model = Model.GPT_3_5_TURBO.getCode(); /** 问题描述 */ private List<Message> messages; /** 控制温度【随机性】;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; /** 频率惩罚;降低模型重复同一行的可能性 */ @JsonProperty("frequency_penalty") private double frequencyPenalty = 0; /** 存在惩罚;增强模型谈论新话题的可能性 */ @JsonProperty("presence_penalty") private double presencePenalty = 0; /** 生成多个调用结果,只显示最佳的。这样会更多的消耗你的 api token */ @JsonProperty("logit_bias") private Map logitBias; /** 调用标识,避免重复调用 */ private String user; @Getter @AllArgsConstructor public enum Model { /** gpt-3.5-turbo */ GPT_3_5_TURBO("gpt-3.5-turbo"), /** GPT4.0 */ GPT_4("gpt-4"), /** GPT4.0 超长上下文 */ GPT_4_32K("gpt-4-32k"), ; private String code; } }
Eumenides1/rookie-gpt-sdk-java
src/main/java/com/rookie/stack/ai/domain/chat/ChatCompletionRequest.java
678
/** 是否为流式输出;就是一蹦一蹦的,出来结果 */
block_comment
zh-cn
package com.rookie.stack.ai.domain.chat; 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 eumenides * @description * @date 2023/11/28 */ @Data @Builder @Slf4j @JsonInclude(JsonInclude.Include.NON_NULL) @NoArgsConstructor @AllArgsConstructor public class ChatCompletionRequest implements Serializable { /** 默认模型 */ private String model = Model.GPT_3_5_TURBO.getCode(); /** 问题描述 */ private List<Message> messages; /** 控制温度【随机性】;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; /** 是否为 <SUF>*/ private boolean stream = false; /** 停止输出标识 */ private List<String> stop; /** 输出字符串限制;0 ~ 4096 */ @JsonProperty("max_tokens") private Integer maxTokens = 2048; /** 频率惩罚;降低模型重复同一行的可能性 */ @JsonProperty("frequency_penalty") private double frequencyPenalty = 0; /** 存在惩罚;增强模型谈论新话题的可能性 */ @JsonProperty("presence_penalty") private double presencePenalty = 0; /** 生成多个调用结果,只显示最佳的。这样会更多的消耗你的 api token */ @JsonProperty("logit_bias") private Map logitBias; /** 调用标识,避免重复调用 */ private String user; @Getter @AllArgsConstructor public enum Model { /** gpt-3.5-turbo */ GPT_3_5_TURBO("gpt-3.5-turbo"), /** GPT4.0 */ GPT_4("gpt-4"), /** GPT4.0 超长上下文 */ GPT_4_32K("gpt-4-32k"), ; private String code; } }
false
595
17
678
21
655
17
678
21
924
27
false
false
false
false
false
true
29042_0
public class RealSubject implements Subject{ @Override public void eat() {//吃饭 System.out.println("eating"); } }
Euraxluo/ProjectPractice
java/DesignPatternInJAVA/Proxy/src/RealSubject.java
36
//吃饭
line_comment
zh-cn
public class RealSubject implements Subject{ @Override public void eat() {//吃饭 <SUF> System.out.println("eating"); } }
false
30
3
35
5
36
3
35
5
44
8
false
false
false
false
false
true
56716_0
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList){ if (beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() == 0 || beginWord.length() != endWord.length()) return 0; // 此题关键是去重,还有去除和beginWord,相同的单词 Set<String> set = new HashSet<String>(wordList); if (set.contains(beginWord)) set.remove(beginWord); Queue<String> wordQueue = new LinkedList<String>(); int level = 1; // the start string already count for 1 int curnum = 1;// the candidate num on current level int nextnum = 0;// counter for next level // 或者使用map记录层数 // Map<String, Integer> map = new HashMap<String, Integer>(); // map.put(beginWord, 1); wordQueue.add(beginWord); while (!wordQueue.isEmpty()) { String word = wordQueue.poll(); curnum--; // int curLevel = map.get(word); for (int i = 0; i < word.length(); i++) { char[] wordunit = word.toCharArray(); for (char j = 'a'; j <= 'z'; j++) { wordunit[i] = j; String temp = new String(wordunit); if (set.contains(temp)) { if (temp.equals(endWord)) // return curLevel + 1; return level + 1; // map.put(temp, curLevel + 1); nextnum++; wordQueue.add(temp); set.remove(temp); } } } if (curnum == 0) { curnum = nextnum; nextnum = 0; level++; } } return 0; } }
Eurus-Holmes/LCED
Word Ladder.java
490
// 此题关键是去重,还有去除和beginWord,相同的单词
line_comment
zh-cn
class Solution { public int ladderLength(String beginWord, String endWord, List<String> wordList){ if (beginWord == null || endWord == null || beginWord.length() == 0 || endWord.length() == 0 || beginWord.length() != endWord.length()) return 0; // 此题 <SUF> Set<String> set = new HashSet<String>(wordList); if (set.contains(beginWord)) set.remove(beginWord); Queue<String> wordQueue = new LinkedList<String>(); int level = 1; // the start string already count for 1 int curnum = 1;// the candidate num on current level int nextnum = 0;// counter for next level // 或者使用map记录层数 // Map<String, Integer> map = new HashMap<String, Integer>(); // map.put(beginWord, 1); wordQueue.add(beginWord); while (!wordQueue.isEmpty()) { String word = wordQueue.poll(); curnum--; // int curLevel = map.get(word); for (int i = 0; i < word.length(); i++) { char[] wordunit = word.toCharArray(); for (char j = 'a'; j <= 'z'; j++) { wordunit[i] = j; String temp = new String(wordunit); if (set.contains(temp)) { if (temp.equals(endWord)) // return curLevel + 1; return level + 1; // map.put(temp, curLevel + 1); nextnum++; wordQueue.add(temp); set.remove(temp); } } } if (curnum == 0) { curnum = nextnum; nextnum = 0; level++; } } return 0; } }
false
426
16
490
19
489
16
490
19
624
27
false
false
false
false
false
true
31939_10
package client.data; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.Scanner; /** * */ public class Txt2Excel { public void txt2excel1() { File file = new File("D:\\学习\\Slime's fighting\\account.txt");// 将读取的txt文件 File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.xls");// 将生成的excel表格 if (file.exists() && file.isFile()) { InputStreamReader read = null; BufferedReader input = null; WritableWorkbook wbook = null; WritableSheet sheet; try { read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); input = new BufferedReader(read); Scanner scanner = new Scanner(read); wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件 sheet = wbook.createSheet("first", 0);// 新标签页 try { Label sName = new Label(0, 0, "");// 如下皆为列名 sheet.addCell(sName); Label account = new Label(0, 0, "用户名");// 如下皆为列名 sheet.addCell(account); Label pass = new Label(1, 0, "密码"); sheet.addCell(pass); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } int m = 1;// excel行数 int n = 0;// excel列数 int count = 0; Label t; while ((scanner.hasNext())) { String word = scanner.next(); t = new Label(n, m, word.trim()); sheet.addCell(t); n++; count++; if (count == 2) { n = 0;// 回到列头部 m++;// 向下移动一行 count = 0; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { wbook.write(); wbook.close(); input.close(); read.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } System.out.println("over!"); } else { System.out.println("file is not exists or not a file"); } } public void txt2excel2() { File file = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.txt");// 将读取的txt文件 File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\game_data.xls");// 将生成的excel表格 if (file.exists() && file.isFile()) { InputStreamReader read = null; BufferedReader input = null; WritableWorkbook wbook = null; WritableSheet sheet; try { read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); input = new BufferedReader(read); Scanner scanner = new Scanner(read); wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件 sheet = wbook.createSheet("first", 0);// 新标签页 try { Label sName = new Label(0, 0, "");// 如下皆为列名 sheet.addCell(sName); Label account = new Label(0, 0, "用户名");// 如下皆为列名 sheet.addCell(account); Label team = new Label(1, 0, "队伍(0绿1蓝)"); sheet.addCell(team); Label blood = new Label(2, 0, "剩余血量"); sheet.addCell(blood); Label time = new Label(3, 0, "在线时长"); sheet.addCell(time); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } int m = 1;// excel行数 int n = 0;// excel列数 int count = 0; Label t; scanner.next(); scanner.next(); scanner.next(); scanner.next(); while ((scanner.hasNext())) { String word = scanner.next(); t = new Label(n, m, word.trim()); sheet.addCell(t); n++; count++; if (count == 4) { n = 0;// 回到列头部 m++;// 向下移动一行 count = 0; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { wbook.write(); wbook.close(); input.close(); read.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } System.out.println("over!"); } else { System.out.println("file is not exists or not a file"); } } }
Evelynn1014/BJTU-cxd-Slime-java-project
client/data/Txt2Excel.java
1,373
// 将读取的txt文件
line_comment
zh-cn
package client.data; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.Scanner; /** * */ public class Txt2Excel { public void txt2excel1() { File file = new File("D:\\学习\\Slime's fighting\\account.txt");// 将读取的txt文件 File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.xls");// 将生成的excel表格 if (file.exists() && file.isFile()) { InputStreamReader read = null; BufferedReader input = null; WritableWorkbook wbook = null; WritableSheet sheet; try { read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); input = new BufferedReader(read); Scanner scanner = new Scanner(read); wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件 sheet = wbook.createSheet("first", 0);// 新标签页 try { Label sName = new Label(0, 0, "");// 如下皆为列名 sheet.addCell(sName); Label account = new Label(0, 0, "用户名");// 如下皆为列名 sheet.addCell(account); Label pass = new Label(1, 0, "密码"); sheet.addCell(pass); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } int m = 1;// excel行数 int n = 0;// excel列数 int count = 0; Label t; while ((scanner.hasNext())) { String word = scanner.next(); t = new Label(n, m, word.trim()); sheet.addCell(t); n++; count++; if (count == 2) { n = 0;// 回到列头部 m++;// 向下移动一行 count = 0; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { wbook.write(); wbook.close(); input.close(); read.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } System.out.println("over!"); } else { System.out.println("file is not exists or not a file"); } } public void txt2excel2() { File file = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\data.txt");// 将读 <SUF> File file2 = new File("D:\\学习\\Slime's fighting\\src\\client\\data\\game_data.xls");// 将生成的excel表格 if (file.exists() && file.isFile()) { InputStreamReader read = null; BufferedReader input = null; WritableWorkbook wbook = null; WritableSheet sheet; try { read = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); input = new BufferedReader(read); Scanner scanner = new Scanner(read); wbook = Workbook.createWorkbook(file2);// 根据路径生成excel文件 sheet = wbook.createSheet("first", 0);// 新标签页 try { Label sName = new Label(0, 0, "");// 如下皆为列名 sheet.addCell(sName); Label account = new Label(0, 0, "用户名");// 如下皆为列名 sheet.addCell(account); Label team = new Label(1, 0, "队伍(0绿1蓝)"); sheet.addCell(team); Label blood = new Label(2, 0, "剩余血量"); sheet.addCell(blood); Label time = new Label(3, 0, "在线时长"); sheet.addCell(time); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } int m = 1;// excel行数 int n = 0;// excel列数 int count = 0; Label t; scanner.next(); scanner.next(); scanner.next(); scanner.next(); while ((scanner.hasNext())) { String word = scanner.next(); t = new Label(n, m, word.trim()); sheet.addCell(t); n++; count++; if (count == 4) { n = 0;// 回到列头部 m++;// 向下移动一行 count = 0; } } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (RowsExceededException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } finally { try { wbook.write(); wbook.close(); input.close(); read.close(); } catch (IOException e) { e.printStackTrace(); } catch (WriteException e) { e.printStackTrace(); } } System.out.println("over!"); } else { System.out.println("file is not exists or not a file"); } } }
false
1,234
9
1,364
7
1,462
7
1,364
7
1,731
12
false
false
false
false
false
true
16451_1
package db.log.sim; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.telephony.TelephonyManager; import lombok.Data; /** * @Author : YangFan * @Date : 2020年11月19日 10:10 * @effect : 获取sim卡、手机号 */ @Data public class Phone { private Context context; private TelephonyManager telephonyManager; public Phone(Context context) { this.context = context; telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); } /** * READ_PHONE_STATE * @return 是否有读取手机状态的权限 * 电话 READ_PHONE_STATE 危险 允许对电话状态进行只读访问,包括设备的电话号码,当前蜂窝网络信息,任何正在进行的呼叫的状态以及设备上注册的任何PhoneAccounts列表 * 电话 CALL_PHONE 危险 允许应用程序在不通过拨号器用户界面的情况下发起电话呼叫,以便用户确认呼叫 * 电话 READ_CALL_LOG 危险 允许应用程序读取用户的通话记录 * 电话 WRITE_CALL_LOG 危险 允许应用程序写入(但不读取)用户的呼叫日志数据 * 电话 ADD_VOICEMAIL 危险 允许应用程序将语音邮件添加到系统中 * 电话 USE_SIP 危险 允许应用程序使用SIP服务 * 电话 PROCESS_OUTGOING_CALLS 危险 允许应用程序查看拨出呼叫期间拨打的号码,并选择将呼叫重定向到其他号码或完全中止呼叫 * 耗时3ms左右 */ //获取SIM卡iccid public String getIccid() { String iccid = "N/A"; iccid = telephonyManager.getSimSerialNumber(); return iccid; } //获取电话号码 public String getNativePhoneNumber() { String nativePhoneNumber = "N/A"; if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return nativePhoneNumber; } nativePhoneNumber = telephonyManager.getLine1Number(); return nativePhoneNumber; } }
EvolvedHumans/EdgeAgent
CPE1/app/src/main/java/db/log/sim/Phone.java
736
/** * READ_PHONE_STATE * @return 是否有读取手机状态的权限 * 电话 READ_PHONE_STATE 危险 允许对电话状态进行只读访问,包括设备的电话号码,当前蜂窝网络信息,任何正在进行的呼叫的状态以及设备上注册的任何PhoneAccounts列表 * 电话 CALL_PHONE 危险 允许应用程序在不通过拨号器用户界面的情况下发起电话呼叫,以便用户确认呼叫 * 电话 READ_CALL_LOG 危险 允许应用程序读取用户的通话记录 * 电话 WRITE_CALL_LOG 危险 允许应用程序写入(但不读取)用户的呼叫日志数据 * 电话 ADD_VOICEMAIL 危险 允许应用程序将语音邮件添加到系统中 * 电话 USE_SIP 危险 允许应用程序使用SIP服务 * 电话 PROCESS_OUTGOING_CALLS 危险 允许应用程序查看拨出呼叫期间拨打的号码,并选择将呼叫重定向到其他号码或完全中止呼叫 * 耗时3ms左右 */
block_comment
zh-cn
package db.log.sim; import android.Manifest; import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.support.v4.app.ActivityCompat; import android.telephony.TelephonyManager; import lombok.Data; /** * @Author : YangFan * @Date : 2020年11月19日 10:10 * @effect : 获取sim卡、手机号 */ @Data public class Phone { private Context context; private TelephonyManager telephonyManager; public Phone(Context context) { this.context = context; telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); } /** * REA <SUF>*/ //获取SIM卡iccid public String getIccid() { String iccid = "N/A"; iccid = telephonyManager.getSimSerialNumber(); return iccid; } //获取电话号码 public String getNativePhoneNumber() { String nativePhoneNumber = "N/A"; if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_SMS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return nativePhoneNumber; } nativePhoneNumber = telephonyManager.getLine1Number(); return nativePhoneNumber; } }
false
601
233
736
284
714
247
736
284
1,036
494
true
true
true
true
true
false
3166_29
package cn.exrick.xboot.common.utils; import cn.exrick.xboot.common.exception.CaptchaException; import cn.hutool.core.util.StrUtil; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.security.SecureRandom; /** * 随机字符验证码生成工具类 * @author Exrickx */ public class CreateVerifyCode { /** * 随机字符 */ public static final String STRING = "ABCDEFGHJKMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz1234567890"; /** * 图片的宽度 */ private int width = 160; /** * 图片的高度 */ private int height = 40; /** * 验证码字符个数 */ private int codeCount = 4; /** * 验证码干扰线数 */ private int lineCount = 20; /** * 验证码 */ private String code = null; /** * 验证码图片Buffer */ private BufferedImage buffImg = null; SecureRandom random = new SecureRandom(); public CreateVerifyCode() { creatImage(); } public CreateVerifyCode(int width, int height) { this.width = width; this.height = height; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount) { this.width = width; this.height = height; this.codeCount = codeCount; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount, int lineCount) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount, int lineCount, String code) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; creatImage(code); } /** * 生成图片 */ private void creatImage() { // 字体的宽度 int fontWidth = width / codeCount; // 字体的高度 int fontHeight = height - 5; int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); //Graphics2D g = buffImg.createGraphics(); // 设置背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设置字体 // Font font1 = getFont(fontHeight); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); // 设置干扰线 for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width); int ye = ys + random.nextInt(height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // 添加噪点 噪声率 float yawpRate = 0.01f; int area = (int) (yawpRate * width * height); for (int i = 0; i < area; i++) { int x = random.nextInt(width); int y = random.nextInt(height); buffImg.setRGB(x, y, random.nextInt(255)); } // 得到随机字符 String str1 = randomStr(codeCount); this.code = str1; for (int i = 0; i < codeCount; i++) { String strRand = str1.substring(i, i + 1); g.setColor(getRandColor(1, 255)); // g.drawString(a,x,y); // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, i * fontWidth + 3, codeY); } } /** * 生成指定字符图片 */ private void creatImage(String code) { if (StrUtil.isBlank(code)) { throw new CaptchaException("验证码为空或已过期,请重新获取"); } // 字体的宽度 int fontWidth = width / codeCount; // 字体的高度 int fontHeight = height - 5; int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); //Graphics2D g = buffImg.createGraphics(); // 设置背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设置字体 //Font font1 = getFont(fontHeight); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); // 设置干扰线 for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width); int ye = ys + random.nextInt(height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // 添加噪点 噪声率 float yawpRate = 0.01f; int area = (int) (yawpRate * width * height); for (int i = 0; i < area; i++) { int x = random.nextInt(width); int y = random.nextInt(height); buffImg.setRGB(x, y, random.nextInt(255)); } this.code = code; for (int i = 0; i < code.length(); i++) { String strRand = code.substring(i, i + 1); g.setColor(getRandColor(1, 255)); // g.drawString(a,x,y); // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, i * fontWidth + 3, codeY); } } /** * 得到随机字符 * @param n * @return */ public String randomStr(int n) { String str = ""; int len = STRING.length() - 1; double r; for (int i = 0; i < n; i++) { r = random.nextDouble() * len; str = str + STRING.charAt((int) r); } return str; } /** * 得到随机颜色 * @param fc * @param bc * @return */ private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色 if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * 产生随机字体 */ private Font getFont(int size) { Font[] font = new Font[5]; font[0] = new Font("Ravie", Font.PLAIN, size); font[1] = new Font("Antique Olive Compact", Font.PLAIN, size); font[2] = new Font("Fixedsys", Font.PLAIN, size); font[3] = new Font("Wide Latin", Font.PLAIN, size); font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size); return font[random.nextInt(5)]; } // 扭曲方法 private void shear(Graphics g, int w1, int h1, Color color) { shearX(g, w1, h1, color); shearY(g, w1, h1, color); } private void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) { g.setColor(color); g.drawLine((int) d, i, 0, i); g.drawLine((int) d + w1, i, w1, i); } } } private void shearY(Graphics g, int w1, int h1, Color color) { // 50 int period = random.nextInt(40) + 10; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } } public void write(OutputStream sos) throws IOException { ImageIO.write(buffImg, "png", sos); sos.close(); } public BufferedImage getBuffImg() { return buffImg; } public String getCode() { return code.toLowerCase(); } }
Exrick/xboot
xboot-fast/src/main/java/cn/exrick/xboot/common/utils/CreateVerifyCode.java
2,567
// 设置干扰线
line_comment
zh-cn
package cn.exrick.xboot.common.utils; import cn.exrick.xboot.common.exception.CaptchaException; import cn.hutool.core.util.StrUtil; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.security.SecureRandom; /** * 随机字符验证码生成工具类 * @author Exrickx */ public class CreateVerifyCode { /** * 随机字符 */ public static final String STRING = "ABCDEFGHJKMNOPQRSTUVWXYZabcdefghjkmnopqrstuvwxyz1234567890"; /** * 图片的宽度 */ private int width = 160; /** * 图片的高度 */ private int height = 40; /** * 验证码字符个数 */ private int codeCount = 4; /** * 验证码干扰线数 */ private int lineCount = 20; /** * 验证码 */ private String code = null; /** * 验证码图片Buffer */ private BufferedImage buffImg = null; SecureRandom random = new SecureRandom(); public CreateVerifyCode() { creatImage(); } public CreateVerifyCode(int width, int height) { this.width = width; this.height = height; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount) { this.width = width; this.height = height; this.codeCount = codeCount; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount, int lineCount) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; creatImage(); } public CreateVerifyCode(int width, int height, int codeCount, int lineCount, String code) { this.width = width; this.height = height; this.codeCount = codeCount; this.lineCount = lineCount; creatImage(code); } /** * 生成图片 */ private void creatImage() { // 字体的宽度 int fontWidth = width / codeCount; // 字体的高度 int fontHeight = height - 5; int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); //Graphics2D g = buffImg.createGraphics(); // 设置背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设置字体 // Font font1 = getFont(fontHeight); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); // 设置干扰线 for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width); int ye = ys + random.nextInt(height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // 添加噪点 噪声率 float yawpRate = 0.01f; int area = (int) (yawpRate * width * height); for (int i = 0; i < area; i++) { int x = random.nextInt(width); int y = random.nextInt(height); buffImg.setRGB(x, y, random.nextInt(255)); } // 得到随机字符 String str1 = randomStr(codeCount); this.code = str1; for (int i = 0; i < codeCount; i++) { String strRand = str1.substring(i, i + 1); g.setColor(getRandColor(1, 255)); // g.drawString(a,x,y); // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, i * fontWidth + 3, codeY); } } /** * 生成指定字符图片 */ private void creatImage(String code) { if (StrUtil.isBlank(code)) { throw new CaptchaException("验证码为空或已过期,请重新获取"); } // 字体的宽度 int fontWidth = width / codeCount; // 字体的高度 int fontHeight = height - 5; int codeY = height - 8; // 图像buffer buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics g = buffImg.getGraphics(); //Graphics2D g = buffImg.createGraphics(); // 设置背景色 g.setColor(getRandColor(200, 250)); g.fillRect(0, 0, width, height); // 设置字体 //Font font1 = getFont(fontHeight); Font font = new Font("Fixedsys", Font.BOLD, fontHeight); g.setFont(font); // 设置 <SUF> for (int i = 0; i < lineCount; i++) { int xs = random.nextInt(width); int ys = random.nextInt(height); int xe = xs + random.nextInt(width); int ye = ys + random.nextInt(height); g.setColor(getRandColor(1, 255)); g.drawLine(xs, ys, xe, ye); } // 添加噪点 噪声率 float yawpRate = 0.01f; int area = (int) (yawpRate * width * height); for (int i = 0; i < area; i++) { int x = random.nextInt(width); int y = random.nextInt(height); buffImg.setRGB(x, y, random.nextInt(255)); } this.code = code; for (int i = 0; i < code.length(); i++) { String strRand = code.substring(i, i + 1); g.setColor(getRandColor(1, 255)); // g.drawString(a,x,y); // a为要画出来的东西,x和y表示要画的东西最左侧字符的基线位于此图形上下文坐标系的 (x, y) 位置处 g.drawString(strRand, i * fontWidth + 3, codeY); } } /** * 得到随机字符 * @param n * @return */ public String randomStr(int n) { String str = ""; int len = STRING.length() - 1; double r; for (int i = 0; i < n; i++) { r = random.nextDouble() * len; str = str + STRING.charAt((int) r); } return str; } /** * 得到随机颜色 * @param fc * @param bc * @return */ private Color getRandColor(int fc, int bc) { // 给定范围获得随机颜色 if (fc > 255) { fc = 255; } if (bc > 255) { bc = 255; } int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } /** * 产生随机字体 */ private Font getFont(int size) { Font[] font = new Font[5]; font[0] = new Font("Ravie", Font.PLAIN, size); font[1] = new Font("Antique Olive Compact", Font.PLAIN, size); font[2] = new Font("Fixedsys", Font.PLAIN, size); font[3] = new Font("Wide Latin", Font.PLAIN, size); font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, size); return font[random.nextInt(5)]; } // 扭曲方法 private void shear(Graphics g, int w1, int h1, Color color) { shearX(g, w1, h1, color); shearY(g, w1, h1, color); } private void shearX(Graphics g, int w1, int h1, Color color) { int period = random.nextInt(2); boolean borderGap = true; int frames = 1; int phase = random.nextInt(2); for (int i = 0; i < h1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(0, i, w1, 1, (int) d, 0); if (borderGap) { g.setColor(color); g.drawLine((int) d, i, 0, i); g.drawLine((int) d + w1, i, w1, i); } } } private void shearY(Graphics g, int w1, int h1, Color color) { // 50 int period = random.nextInt(40) + 10; boolean borderGap = true; int frames = 20; int phase = 7; for (int i = 0; i < w1; i++) { double d = (double) (period >> 1) * Math.sin((double) i / (double) period + (6.2831853071795862D * (double) phase) / (double) frames); g.copyArea(i, 0, 1, h1, 0, (int) d); if (borderGap) { g.setColor(color); g.drawLine(i, (int) d, i, 0); g.drawLine(i, (int) d + h1, i, h1); } } } public void write(OutputStream sos) throws IOException { ImageIO.write(buffImg, "png", sos); sos.close(); } public BufferedImage getBuffImg() { return buffImg; } public String getCode() { return code.toLowerCase(); } }
false
2,359
4
2,567
6
2,720
4
2,567
6
3,185
11
false
false
false
false
false
true
4963_1
package cn.exrick.service.impl; import cn.exrick.bean.Pay; import cn.exrick.bean.dto.Count; import cn.exrick.common.utils.DateUtils; import cn.exrick.common.utils.StringUtils; import cn.exrick.dao.PayDao; import cn.exrick.service.PayService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; /** * @author Exrickx */ @Service public class PayServiceImpl implements PayService { private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class); @Autowired private PayDao payDao; @Override public Page<Pay> getPayListByPage(Integer state, String key, Pageable pageable) { return payDao.findAll(new Specification<Pay>() { @Override public Predicate toPredicate(Root<Pay> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { Path<String> nickNameField = root.get("nickName"); Path<String> infoField = root.get("info"); Path<String> payTypeField=root.get("payType"); Path<Integer> stateField=root.get("state"); List<Predicate> list = new ArrayList<Predicate>(); //模糊搜素 if(StringUtils.isNotBlank(key)){ Predicate p1 = cb.like(nickNameField,'%'+key+'%'); Predicate p3 = cb.like(infoField,'%'+key+'%'); Predicate p4 = cb.like(payTypeField,'%'+key+'%'); list.add(cb.or(p1,p3,p4)); } //状态 if(state!=null){ list.add(cb.equal(stateField, state)); } Predicate[] arr = new Predicate[list.size()]; cq.where(list.toArray(arr)); return null; } }, pageable); } @Override public List<Pay> getPayList(Integer state) { List<Pay> list=payDao.getByStateIs(state); for(Pay pay:list){ //屏蔽隐私数据 pay.setId(""); pay.setEmail(""); pay.setTestEmail(""); pay.setPayNum(null); pay.setMobile(null); pay.setCustom(null); pay.setDevice(null); } return list; } @Override public Pay getPay(String id) { Pay pay=payDao.findOne(id); pay.setTime(StringUtils.getTimeStamp(pay.getCreateTime())); return pay; } @Override public int addPay(Pay pay) { pay.setId(UUID.randomUUID().toString()); pay.setCreateTime(new Date()); pay.setState(0); payDao.save(pay); return 1; } @Override public int updatePay(Pay pay) { pay.setUpdateTime(new Date()); payDao.saveAndFlush(pay); return 1; } @Override public int changePayState(String id, Integer state) { Pay pay=getPay(id); pay.setState(state); pay.setUpdateTime(new Date()); payDao.saveAndFlush(pay); return 1; } @Override public int delPay(String id) { payDao.delete(id); return 1; } @Override public Count statistic(Integer type, String start, String end) { Count count=new Count(); if(type==-1){ // 总 count.setAmount(payDao.countAllMoney()); count.setAlipay(payDao.countAllMoneyByType("Alipay")); count.setWechat(payDao.countAllMoneyByType("Wechat")); count.setQq(payDao.countAllMoneyByType("QQ")); count.setUnion(payDao.countAllMoneyByType("UnionPay")); count.setDiandan(payDao.countAllMoneyByType("Diandan")); return count; } Date startDate=null,endDate=null; if(type==0){ // 今天 startDate = DateUtils.getDayBegin(); endDate = DateUtils.getDayEnd(); }if(type==6){ // 昨天 startDate = DateUtils.getBeginDayOfYesterday(); endDate = DateUtils.getEndDayOfYesterDay(); }else if(type==1){ // 本周 startDate = DateUtils.getBeginDayOfWeek(); endDate = DateUtils.getEndDayOfWeek(); }else if(type==2){ // 本月 startDate = DateUtils.getBeginDayOfMonth(); endDate = DateUtils.getEndDayOfMonth(); }else if(type==3){ // 本年 startDate = DateUtils.getBeginDayOfYear(); endDate = DateUtils.getEndDayOfYear(); }else if(type==4){ // 上周 startDate = DateUtils.getBeginDayOfLastWeek(); endDate = DateUtils.getEndDayOfLastWeek(); }else if(type==5){ // 上个月 startDate = DateUtils.getBeginDayOfLastMonth(); endDate = DateUtils.getEndDayOfLastMonth(); }else if(type==-2){ // 自定义 startDate = DateUtils.parseStartDate(start); endDate = DateUtils.parseEndDate(end); } count.setAmount(payDao.countMoney(startDate, endDate)); count.setAlipay(payDao.countMoneyByType("Alipay", startDate, endDate)); count.setWechat(payDao.countMoneyByType("Wechat", startDate, endDate)); count.setQq(payDao.countMoneyByType("QQ", startDate, endDate)); count.setUnion(payDao.countMoneyByType("UnionPay", startDate, endDate)); count.setDiandan(payDao.countMoneyByType("Diandan", startDate, endDate)); return count; } }
Exrick/xpay
xpay-code/src/main/java/cn/exrick/service/impl/PayServiceImpl.java
1,487
//模糊搜素
line_comment
zh-cn
package cn.exrick.service.impl; import cn.exrick.bean.Pay; import cn.exrick.bean.dto.Count; import cn.exrick.common.utils.DateUtils; import cn.exrick.common.utils.StringUtils; import cn.exrick.dao.PayDao; import cn.exrick.service.PayService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Service; import javax.persistence.criteria.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.UUID; /** * @author Exrickx */ @Service public class PayServiceImpl implements PayService { private static final Logger log = LoggerFactory.getLogger(PayServiceImpl.class); @Autowired private PayDao payDao; @Override public Page<Pay> getPayListByPage(Integer state, String key, Pageable pageable) { return payDao.findAll(new Specification<Pay>() { @Override public Predicate toPredicate(Root<Pay> root, CriteriaQuery<?> cq, CriteriaBuilder cb) { Path<String> nickNameField = root.get("nickName"); Path<String> infoField = root.get("info"); Path<String> payTypeField=root.get("payType"); Path<Integer> stateField=root.get("state"); List<Predicate> list = new ArrayList<Predicate>(); //模糊 <SUF> if(StringUtils.isNotBlank(key)){ Predicate p1 = cb.like(nickNameField,'%'+key+'%'); Predicate p3 = cb.like(infoField,'%'+key+'%'); Predicate p4 = cb.like(payTypeField,'%'+key+'%'); list.add(cb.or(p1,p3,p4)); } //状态 if(state!=null){ list.add(cb.equal(stateField, state)); } Predicate[] arr = new Predicate[list.size()]; cq.where(list.toArray(arr)); return null; } }, pageable); } @Override public List<Pay> getPayList(Integer state) { List<Pay> list=payDao.getByStateIs(state); for(Pay pay:list){ //屏蔽隐私数据 pay.setId(""); pay.setEmail(""); pay.setTestEmail(""); pay.setPayNum(null); pay.setMobile(null); pay.setCustom(null); pay.setDevice(null); } return list; } @Override public Pay getPay(String id) { Pay pay=payDao.findOne(id); pay.setTime(StringUtils.getTimeStamp(pay.getCreateTime())); return pay; } @Override public int addPay(Pay pay) { pay.setId(UUID.randomUUID().toString()); pay.setCreateTime(new Date()); pay.setState(0); payDao.save(pay); return 1; } @Override public int updatePay(Pay pay) { pay.setUpdateTime(new Date()); payDao.saveAndFlush(pay); return 1; } @Override public int changePayState(String id, Integer state) { Pay pay=getPay(id); pay.setState(state); pay.setUpdateTime(new Date()); payDao.saveAndFlush(pay); return 1; } @Override public int delPay(String id) { payDao.delete(id); return 1; } @Override public Count statistic(Integer type, String start, String end) { Count count=new Count(); if(type==-1){ // 总 count.setAmount(payDao.countAllMoney()); count.setAlipay(payDao.countAllMoneyByType("Alipay")); count.setWechat(payDao.countAllMoneyByType("Wechat")); count.setQq(payDao.countAllMoneyByType("QQ")); count.setUnion(payDao.countAllMoneyByType("UnionPay")); count.setDiandan(payDao.countAllMoneyByType("Diandan")); return count; } Date startDate=null,endDate=null; if(type==0){ // 今天 startDate = DateUtils.getDayBegin(); endDate = DateUtils.getDayEnd(); }if(type==6){ // 昨天 startDate = DateUtils.getBeginDayOfYesterday(); endDate = DateUtils.getEndDayOfYesterDay(); }else if(type==1){ // 本周 startDate = DateUtils.getBeginDayOfWeek(); endDate = DateUtils.getEndDayOfWeek(); }else if(type==2){ // 本月 startDate = DateUtils.getBeginDayOfMonth(); endDate = DateUtils.getEndDayOfMonth(); }else if(type==3){ // 本年 startDate = DateUtils.getBeginDayOfYear(); endDate = DateUtils.getEndDayOfYear(); }else if(type==4){ // 上周 startDate = DateUtils.getBeginDayOfLastWeek(); endDate = DateUtils.getEndDayOfLastWeek(); }else if(type==5){ // 上个月 startDate = DateUtils.getBeginDayOfLastMonth(); endDate = DateUtils.getEndDayOfLastMonth(); }else if(type==-2){ // 自定义 startDate = DateUtils.parseStartDate(start); endDate = DateUtils.parseEndDate(end); } count.setAmount(payDao.countMoney(startDate, endDate)); count.setAlipay(payDao.countMoneyByType("Alipay", startDate, endDate)); count.setWechat(payDao.countMoneyByType("Wechat", startDate, endDate)); count.setQq(payDao.countMoneyByType("QQ", startDate, endDate)); count.setUnion(payDao.countMoneyByType("UnionPay", startDate, endDate)); count.setDiandan(payDao.countMoneyByType("Diandan", startDate, endDate)); return count; } }
false
1,252
5
1,467
8
1,559
5
1,467
8
1,814
10
false
false
false
false
false
true
52668_1
package com.atguigu.practiceNo2.juc; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class SemaphoreDemo { public static void main(String[] args) { //6辆汽车停三个停车位 Semaphore semaphore = new Semaphore(3); for (int i = 0; i <= 6; i++) { new Thread(() -> { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "停车"); //随机停车时间 TimeUnit.SECONDS.sleep(new Random().nextInt(5)); System.out.println(Thread.currentThread().getName() + "离开"); } catch (Exception e) { e.printStackTrace(); } finally { //释放 semaphore.release(); } }, "线程" + i).start(); } } }
Ezrabin/juc_atguigu
src/com/atguigu/practiceNo2/juc/SemaphoreDemo.java
217
//随机停车时间
line_comment
zh-cn
package com.atguigu.practiceNo2.juc; import java.util.Random; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; public class SemaphoreDemo { public static void main(String[] args) { //6辆汽车停三个停车位 Semaphore semaphore = new Semaphore(3); for (int i = 0; i <= 6; i++) { new Thread(() -> { try { semaphore.acquire(); System.out.println(Thread.currentThread().getName() + "停车"); //随机 <SUF> TimeUnit.SECONDS.sleep(new Random().nextInt(5)); System.out.println(Thread.currentThread().getName() + "离开"); } catch (Exception e) { e.printStackTrace(); } finally { //释放 semaphore.release(); } }, "线程" + i).start(); } } }
false
179
4
217
5
225
4
217
5
298
13
false
false
false
false
false
true
58892_37
package com.videogo.ui.login; import java.util.ArrayList; import java.util.List; /** * 开放平台服务端在分为海外和国内,海外又分为5个大区 * (北美、南美、新加坡(亚洲)、俄罗斯、欧洲) * 必须根据当前使用的AppKey对应大区切换到所在大区的服务器 * 否则EZOpenSDK的接口调用将会出现异常 */ public enum ServerAreasEnum { /** * 国内 */ ASIA_CHINA(0,"Asia-China", "https://open.ys7.com", "https://openauth.ys7.com", "26810f3acd794862b608b6cfbc32a6b8"), /** * 海外:俄罗斯 */ ASIA_Russia(5, "Asia-Russia", "https://irusopen.ezvizru.com", "https://irusopenauth.ezvizru.com", true), /** * 海外:亚洲 * (服务亚洲的所有国家,但不包括中国和俄罗斯) */ ASIA(10, "Asia", "https://isgpopen.ezvizlife.com", "https://isgpopenauth.ezvizlife.com", true), /** * 海外:北美洲 */ NORTH_AMERICA(15,"North America", "https://iusopen.ezvizlife.com", "https://iusopenauth.ezvizlife.com", true), /** * 海外:南美洲 */ SOUTH_AMERICA(20, "South America", "https://isaopen.ezvizlife.com", "https://isaopenauth.ezvizlife.com", true), /** * 海外:欧洲 */ EUROPE(25, "Europe", "https://ieuopen.ezvizlife.com", "https://ieuopenauth.ezvizlife.com", "5cadedf5478d11e7ae26fa163e8bac01", true), OTHER(26, "Other", "", "", "1111"), OTHER_GLOBAL(27, "Other Global", "", "", "1111", true), /*线上平台的id范围为0到99,测试平台的id范围为100+*/ /** * 测试平台:test12 */ TEST12(110, "test12", "https://test12open.ys7.com", "https://test12openauth.ys7.com", "b22035492c7949bca95286382ed90b01"), /** * 测试平台:testcn */ TEST_CN(115, "testcn", "https://testcnopen.ezvizlife.com", "https://testcnopenauth.ezvizlife.com", true), /** * 测试平台:testus */ TEST_US(120, "testus", "https://testusopen.ezvizlife.com", "https://testusopenauth.ezvizlife.com", true), /** * 测试平台:testeu */ // TEST_EU(125, "testeu", "https://testeuopen.ezvizlife.com", // "https://testeuopenauth.ezvizlife.com", true), TEST_EU(125, "testeu", "https://ys-open.wens.com.cn", "https://test2auth.ys7.com:8643", true), /** * 温氏 */ WENSHI(126, "WenShi", "https://ezcpcloudopen.wens.com.cn", "https://ezcpcloudopenauth.wens.com.cn", false), /** * 华住 */ HUAZHU(127, "HuaZhu", "https://ezcpatctestopen.ys7.com", "https://ezcpatctestopenauth.ys7.com", false); // TEST_NEW(130,"testnew", "https://ys-open.wens.com.cn", // "https://test2auth.ys7.com:8643", true); public int id; public String areaName; public String openApiServer; public String openAuthApiServer; // 预置的用于测试h5登录的appKey(该appKey的bundleId已绑定到ezviz.opensdk) public String defaultOpenAuthAppKey; // 是否正在海外域名,海外域名需要使用GlobalEZOpenSDK,反之使用EZOpenSDK public boolean usingGlobalSDK; ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer){ this(id, areaName, openApiServer, openAuthApiServer, null, false); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey){ this(id, areaName, openApiServer, openAuthApiServer, defaultOpenAuthAppKey, false); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, boolean usingGlobalSDK){ this(id, areaName, openApiServer, openAuthApiServer, null, usingGlobalSDK); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey, boolean usingGlobalSDK){ this.id = id; this.areaName = areaName; this.openApiServer = openApiServer; this.openAuthApiServer = openAuthApiServer; this.defaultOpenAuthAppKey = defaultOpenAuthAppKey; this.usingGlobalSDK = usingGlobalSDK; } public static List<ServerAreasEnum> getAllServers(){ List<ServerAreasEnum> serversList = new ArrayList<>(); for (ServerAreasEnum server : values()) { boolean isTestServer = server.id >= 100; // 线上demo不展示测试平台 if (!com.videogo.openapi.BuildConfig.DEBUG && isTestServer) { continue; } serversList.add(server); } return serversList; } @Override public String toString() { return "id: " + id + ", " + "areaName: " + areaName + ", " + "openApiServer: " + openApiServer + ", " + "openAuthApiServer: " + openAuthApiServer; } }
Ezviz-Open/EzvizSDK-Android
app/src/main/java/com/videogo/ui/login/ServerAreasEnum.java
1,598
/** * 华住 */
block_comment
zh-cn
package com.videogo.ui.login; import java.util.ArrayList; import java.util.List; /** * 开放平台服务端在分为海外和国内,海外又分为5个大区 * (北美、南美、新加坡(亚洲)、俄罗斯、欧洲) * 必须根据当前使用的AppKey对应大区切换到所在大区的服务器 * 否则EZOpenSDK的接口调用将会出现异常 */ public enum ServerAreasEnum { /** * 国内 */ ASIA_CHINA(0,"Asia-China", "https://open.ys7.com", "https://openauth.ys7.com", "26810f3acd794862b608b6cfbc32a6b8"), /** * 海外:俄罗斯 */ ASIA_Russia(5, "Asia-Russia", "https://irusopen.ezvizru.com", "https://irusopenauth.ezvizru.com", true), /** * 海外:亚洲 * (服务亚洲的所有国家,但不包括中国和俄罗斯) */ ASIA(10, "Asia", "https://isgpopen.ezvizlife.com", "https://isgpopenauth.ezvizlife.com", true), /** * 海外:北美洲 */ NORTH_AMERICA(15,"North America", "https://iusopen.ezvizlife.com", "https://iusopenauth.ezvizlife.com", true), /** * 海外:南美洲 */ SOUTH_AMERICA(20, "South America", "https://isaopen.ezvizlife.com", "https://isaopenauth.ezvizlife.com", true), /** * 海外:欧洲 */ EUROPE(25, "Europe", "https://ieuopen.ezvizlife.com", "https://ieuopenauth.ezvizlife.com", "5cadedf5478d11e7ae26fa163e8bac01", true), OTHER(26, "Other", "", "", "1111"), OTHER_GLOBAL(27, "Other Global", "", "", "1111", true), /*线上平台的id范围为0到99,测试平台的id范围为100+*/ /** * 测试平台:test12 */ TEST12(110, "test12", "https://test12open.ys7.com", "https://test12openauth.ys7.com", "b22035492c7949bca95286382ed90b01"), /** * 测试平台:testcn */ TEST_CN(115, "testcn", "https://testcnopen.ezvizlife.com", "https://testcnopenauth.ezvizlife.com", true), /** * 测试平台:testus */ TEST_US(120, "testus", "https://testusopen.ezvizlife.com", "https://testusopenauth.ezvizlife.com", true), /** * 测试平台:testeu */ // TEST_EU(125, "testeu", "https://testeuopen.ezvizlife.com", // "https://testeuopenauth.ezvizlife.com", true), TEST_EU(125, "testeu", "https://ys-open.wens.com.cn", "https://test2auth.ys7.com:8643", true), /** * 温氏 */ WENSHI(126, "WenShi", "https://ezcpcloudopen.wens.com.cn", "https://ezcpcloudopenauth.wens.com.cn", false), /** * 华住 <SUF>*/ HUAZHU(127, "HuaZhu", "https://ezcpatctestopen.ys7.com", "https://ezcpatctestopenauth.ys7.com", false); // TEST_NEW(130,"testnew", "https://ys-open.wens.com.cn", // "https://test2auth.ys7.com:8643", true); public int id; public String areaName; public String openApiServer; public String openAuthApiServer; // 预置的用于测试h5登录的appKey(该appKey的bundleId已绑定到ezviz.opensdk) public String defaultOpenAuthAppKey; // 是否正在海外域名,海外域名需要使用GlobalEZOpenSDK,反之使用EZOpenSDK public boolean usingGlobalSDK; ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer){ this(id, areaName, openApiServer, openAuthApiServer, null, false); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey){ this(id, areaName, openApiServer, openAuthApiServer, defaultOpenAuthAppKey, false); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, boolean usingGlobalSDK){ this(id, areaName, openApiServer, openAuthApiServer, null, usingGlobalSDK); } ServerAreasEnum(int id, String areaName, String openApiServer, String openAuthApiServer, String defaultOpenAuthAppKey, boolean usingGlobalSDK){ this.id = id; this.areaName = areaName; this.openApiServer = openApiServer; this.openAuthApiServer = openAuthApiServer; this.defaultOpenAuthAppKey = defaultOpenAuthAppKey; this.usingGlobalSDK = usingGlobalSDK; } public static List<ServerAreasEnum> getAllServers(){ List<ServerAreasEnum> serversList = new ArrayList<>(); for (ServerAreasEnum server : values()) { boolean isTestServer = server.id >= 100; // 线上demo不展示测试平台 if (!com.videogo.openapi.BuildConfig.DEBUG && isTestServer) { continue; } serversList.add(server); } return serversList; } @Override public String toString() { return "id: " + id + ", " + "areaName: " + areaName + ", " + "openApiServer: " + openApiServer + ", " + "openAuthApiServer: " + openAuthApiServer; } }
false
1,472
9
1,592
8
1,620
9
1,592
8
1,886
12
false
false
false
false
false
true
50744_3
package org.skyer.tags.infra.constant; /** * 基础模块常量 * * @author */ public interface FndConstants { /** * 个性化页面值类型 */ interface AttributeType { /** * 字符串 */ String STRING = "STRING"; /** * 数字 */ String NUMBER = "NUMBER"; /** * boolean */ String BOOLEAN = "BOOLEAN"; } /** * 个性化页面应用层级 */ interface UiDimensionType { /** * 平台级 */ String SITE = "SITE"; /** * 租户级 */ String TENANT = "TENANT"; /** * 公司及 */ String COMPANY = "COMPANY"; /** * 用户级 */ String USER = "USER"; } /** * 缓存Key */ interface CacheKey { /** * 模板配置缓存Key */ String TEMPLATE_CACHE_KEY = Constants.APP_CODE + ":template:"; /** * 模板配置缓存Key */ String DEFAULT_TEMPLATE_CACHE_KEY = Constants.APP_CODE + ":default-template:"; /** * 值集缓存 */ String LOV_KEY = Constants.APP_CODE + ":lov"; /** * 配置维护 */ String PROFILE_KEY = Constants.APP_CODE + ":profile"; /** * 事件 */ String EVENT_KEY = Constants.APP_CODE + ":event"; /** * 个性化表格配置 */ String CUSTOM_TABLE_KEY = Constants.APP_CODE + ":custom_table"; /** * 数据屏蔽 */ String PERMISSION_KEY = Constants.APP_CODE + ":permission"; /** * 系统配置 服务级功能,所以不加fnd */ String CONFIG_KEY = Constants.APP_CODE + ":config"; /** * 多语言描述 */ String PROMPT_KEY = Constants.APP_CODE + ":prompt"; /** * 数据权限数据库关系 */ String DATABASE_KEY = Constants.APP_CODE + ":database"; /** * 数据源服务关系 */ String DATASOURCE_KEY = Constants.APP_CODE + ":datasource"; /** * 静态文本 */ String STATIC_TEXT = Constants.APP_CODE + ":text"; /** * 个性化页面 */ String Ui_PAGE = Constants.APP_CODE + ":page"; /** * 静态文本头 */ String STATIC_TEXT_HEAD = STATIC_TEXT + ":head"; /** * 静态文本行 */ String STATIC_TEXT_LINE = STATIC_TEXT + ":line"; /** * 平台卡片 */ String DASHBOARD_CARD_KEY = Constants.APP_CODE + ":dashboard_card"; /** * 租户卡片分配 */ String DASHBOARD_TENANT_CARD_KEY = Constants.APP_CODE + ":dashboard_tenant_card"; } /** * 值集类型 */ interface LovTypeCode { /** * URL型 */ String URL = "URL"; /** * 自定义SQL型 */ String SQL = "SQL"; /** * 独立值集型 */ String INDEPENDENT = "IDP"; } /** * 事件调用类型 */ interface CallType { /** * 方法 */ String METHOD = "M"; /** * API */ String API = "A"; } /** * 配置维护值应用层级 */ interface ProfileLevelCode { /** * 配置维护值应用层级-角色级 */ String ROLE = "ROLE"; /** * 配置维护值应用层级-用户级 */ String USER = "USER"; /** * 配置维护值应用层级-全局(对应该租户下的所有) */ String GLOBAL = "GLOBAL"; } /** * 编码规则应用层级 */ interface CodeRuleLevelCode { /** * 全局级 */ String GLOBAL = "GLOBAL"; /** * 公司 */ String COMPANY = "COM"; } /** * 应用维度 */ interface Level { /** * 应用维度-租户级 */ String TENANT = "T"; /** * 应用维度-平台级 */ String PLATFORM = "P"; } /** * 编码规则段类型 */ interface FieldType { /** * 序列 */ String SEQUENCE = "SEQUENCE"; /** * 常量 */ String CONSTANT = "CONSTANT"; /** * 日期 */ String DATE = "DATE"; /** * 变量 */ String VARIABLE = "VARIABLE"; /** * uuid */ String UUID = "UUID"; } /** * 重置频率 */ interface ResetFrequency { /** * 从不 */ String NEVER = "NEVER"; /** * 每年 */ String YEAR = "YEAR"; /** * 每季 */ String QUARTER = "QUARTER"; /** * 每月 */ String MONTH = "MONTH"; /** * 每天 */ String DAY = "DAY"; } /** * 序列 */ interface Sequence { /** * 自增步长 */ Long STEP = 1L; /** * 记录频率 */ Long STEP_NUM = 100L; } /** * 数据来源 * * @author */ interface DataSource { String SKYER = "SKYER"; String SRM = "SRM"; String ERP = "ERP"; } /** * 数据屏蔽规则类型代码 */ interface PermissionRuleTypeCode { /** * sql */ String SQL = "SQL"; /** * 数据库前缀 */ String PREFIX = "PREFIX"; } /** * 数据源用户密码返回值 */ interface DatasourcePassword { /** * 返回前端的密码信息 */ String RETURNEDSTRING = "******"; } }
FJ-OMS/oms-erp
skyer-tags/src/main/java/org/skyer/tags/infra/constant/FndConstants.java
1,395
/** * 数字 */
block_comment
zh-cn
package org.skyer.tags.infra.constant; /** * 基础模块常量 * * @author */ public interface FndConstants { /** * 个性化页面值类型 */ interface AttributeType { /** * 字符串 */ String STRING = "STRING"; /** * 数字 <SUF>*/ String NUMBER = "NUMBER"; /** * boolean */ String BOOLEAN = "BOOLEAN"; } /** * 个性化页面应用层级 */ interface UiDimensionType { /** * 平台级 */ String SITE = "SITE"; /** * 租户级 */ String TENANT = "TENANT"; /** * 公司及 */ String COMPANY = "COMPANY"; /** * 用户级 */ String USER = "USER"; } /** * 缓存Key */ interface CacheKey { /** * 模板配置缓存Key */ String TEMPLATE_CACHE_KEY = Constants.APP_CODE + ":template:"; /** * 模板配置缓存Key */ String DEFAULT_TEMPLATE_CACHE_KEY = Constants.APP_CODE + ":default-template:"; /** * 值集缓存 */ String LOV_KEY = Constants.APP_CODE + ":lov"; /** * 配置维护 */ String PROFILE_KEY = Constants.APP_CODE + ":profile"; /** * 事件 */ String EVENT_KEY = Constants.APP_CODE + ":event"; /** * 个性化表格配置 */ String CUSTOM_TABLE_KEY = Constants.APP_CODE + ":custom_table"; /** * 数据屏蔽 */ String PERMISSION_KEY = Constants.APP_CODE + ":permission"; /** * 系统配置 服务级功能,所以不加fnd */ String CONFIG_KEY = Constants.APP_CODE + ":config"; /** * 多语言描述 */ String PROMPT_KEY = Constants.APP_CODE + ":prompt"; /** * 数据权限数据库关系 */ String DATABASE_KEY = Constants.APP_CODE + ":database"; /** * 数据源服务关系 */ String DATASOURCE_KEY = Constants.APP_CODE + ":datasource"; /** * 静态文本 */ String STATIC_TEXT = Constants.APP_CODE + ":text"; /** * 个性化页面 */ String Ui_PAGE = Constants.APP_CODE + ":page"; /** * 静态文本头 */ String STATIC_TEXT_HEAD = STATIC_TEXT + ":head"; /** * 静态文本行 */ String STATIC_TEXT_LINE = STATIC_TEXT + ":line"; /** * 平台卡片 */ String DASHBOARD_CARD_KEY = Constants.APP_CODE + ":dashboard_card"; /** * 租户卡片分配 */ String DASHBOARD_TENANT_CARD_KEY = Constants.APP_CODE + ":dashboard_tenant_card"; } /** * 值集类型 */ interface LovTypeCode { /** * URL型 */ String URL = "URL"; /** * 自定义SQL型 */ String SQL = "SQL"; /** * 独立值集型 */ String INDEPENDENT = "IDP"; } /** * 事件调用类型 */ interface CallType { /** * 方法 */ String METHOD = "M"; /** * API */ String API = "A"; } /** * 配置维护值应用层级 */ interface ProfileLevelCode { /** * 配置维护值应用层级-角色级 */ String ROLE = "ROLE"; /** * 配置维护值应用层级-用户级 */ String USER = "USER"; /** * 配置维护值应用层级-全局(对应该租户下的所有) */ String GLOBAL = "GLOBAL"; } /** * 编码规则应用层级 */ interface CodeRuleLevelCode { /** * 全局级 */ String GLOBAL = "GLOBAL"; /** * 公司 */ String COMPANY = "COM"; } /** * 应用维度 */ interface Level { /** * 应用维度-租户级 */ String TENANT = "T"; /** * 应用维度-平台级 */ String PLATFORM = "P"; } /** * 编码规则段类型 */ interface FieldType { /** * 序列 */ String SEQUENCE = "SEQUENCE"; /** * 常量 */ String CONSTANT = "CONSTANT"; /** * 日期 */ String DATE = "DATE"; /** * 变量 */ String VARIABLE = "VARIABLE"; /** * uuid */ String UUID = "UUID"; } /** * 重置频率 */ interface ResetFrequency { /** * 从不 */ String NEVER = "NEVER"; /** * 每年 */ String YEAR = "YEAR"; /** * 每季 */ String QUARTER = "QUARTER"; /** * 每月 */ String MONTH = "MONTH"; /** * 每天 */ String DAY = "DAY"; } /** * 序列 */ interface Sequence { /** * 自增步长 */ Long STEP = 1L; /** * 记录频率 */ Long STEP_NUM = 100L; } /** * 数据来源 * * @author */ interface DataSource { String SKYER = "SKYER"; String SRM = "SRM"; String ERP = "ERP"; } /** * 数据屏蔽规则类型代码 */ interface PermissionRuleTypeCode { /** * sql */ String SQL = "SQL"; /** * 数据库前缀 */ String PREFIX = "PREFIX"; } /** * 数据源用户密码返回值 */ interface DatasourcePassword { /** * 返回前端的密码信息 */ String RETURNEDSTRING = "******"; } }
false
1,411
8
1,395
7
1,601
8
1,395
7
2,132
10
false
false
false
false
false
true
51602_0
package com.lucky.jacklamb.enums; import com.lucky.jacklamb.utils.base.StaticFile; import com.lucky.jacklamb.utils.file.Resources; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.Reader; public enum Logo { /** * 键盘 */ KEYBOARD("keyboard.txt"), /** * 小老鼠 */ MOUSELET("mouselet.txt"), /** * 电脑 */ COMPUTER("computer.txt"), /** * 吉祥物草泥马 */ GRASS_MUD_HORSE("grass-mud-horse.txt"), /** * 蚂蚁先生 */ ANTS("ants.txt"), /** * 单身汪 */ SINGLE_WANG("single-wang.txt"), /** * 喷火龙 */ DRAGON("dragon.txt"), /** * 佛祖 */ BUDDHA("buddha.txt"), /** * 书本 */ BOOK("book.txt"), /** * 安妮 */ ANNE("anne.txt"), /** * 朱迪 */ JUDY("judy.txt"), /** * 危险信号 */ DANGER_SIGNALS("danger-signals.txt"), /** * Lucky */ LUCKY("lucky.txt"); private String fileName; public String getLogo() { try{ Reader reader = Resources.getReader(StaticFile.LOGO_FOLDER +fileName); return IOUtils.toString(reader); }catch (IOException e){ throw new RuntimeException(e); } } Logo(String fileName) { this.fileName = fileName; } }
FK7075/lucky-noxml
lucky-noxml/src/main/java/com/lucky/jacklamb/enums/Logo.java
479
/** * 键盘 */
block_comment
zh-cn
package com.lucky.jacklamb.enums; import com.lucky.jacklamb.utils.base.StaticFile; import com.lucky.jacklamb.utils.file.Resources; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.Reader; public enum Logo { /** * 键盘 <SUF>*/ KEYBOARD("keyboard.txt"), /** * 小老鼠 */ MOUSELET("mouselet.txt"), /** * 电脑 */ COMPUTER("computer.txt"), /** * 吉祥物草泥马 */ GRASS_MUD_HORSE("grass-mud-horse.txt"), /** * 蚂蚁先生 */ ANTS("ants.txt"), /** * 单身汪 */ SINGLE_WANG("single-wang.txt"), /** * 喷火龙 */ DRAGON("dragon.txt"), /** * 佛祖 */ BUDDHA("buddha.txt"), /** * 书本 */ BOOK("book.txt"), /** * 安妮 */ ANNE("anne.txt"), /** * 朱迪 */ JUDY("judy.txt"), /** * 危险信号 */ DANGER_SIGNALS("danger-signals.txt"), /** * Lucky */ LUCKY("lucky.txt"); private String fileName; public String getLogo() { try{ Reader reader = Resources.getReader(StaticFile.LOGO_FOLDER +fileName); return IOUtils.toString(reader); }catch (IOException e){ throw new RuntimeException(e); } } Logo(String fileName) { this.fileName = fileName; } }
false
386
9
479
8
475
9
479
8
590
14
false
false
false
false
false
true
54975_14
package com.faceunity.app.data.disksource.style; import com.faceunity.core.model.facebeauty.FaceBeautyBlurTypeEnum; import java.io.Serializable; /** * 保存到磁盘的风格对象 * 该例只保存特效demo展示出来的风格功能 */ public class FUDiskStyleData implements Serializable { /* 美肤 */ /*是否开启美肤效果*/ public boolean faceBeautySkinEnable = true; /* 磨皮类型 */ public int blurType = FaceBeautyBlurTypeEnum.FineSkin; /* 磨皮程度 */ public double blurIntensity = 0.0; /* 祛斑痘程度 */ public double delspotIntensity = 0.0; /* 美白程度 */ public double colorIntensity = 0.0; /* 美白皮肤分割 */ public boolean enableSkinSeg = false; /* 红润程度 */ public double redIntensity = 0.0; /* 清晰程度 */ public double clarityIntensity = 0.0; /* 锐化程度 */ public double sharpenIntensity = 0.0; /* 亮眼程度 */ public double eyeBrightIntensity = 0.0; /* 美牙程度 */ public double toothIntensity = 0.0; /* 去黑眼圈强度*/ public double removePouchIntensity = 0.0; /* 去法令纹强度*/ public double removeLawPatternIntensity = 0.0; /*美型*/ /*是否开启美型效果*/ public boolean faceBeautyShapeEnable = true; /* 瘦脸程度 */ public double cheekThinningIntensity = 0.0; /* V脸程度 */ public double cheekVIntensity = 0.0; /* 窄脸程度 */ public double cheekNarrowIntensity = 0.0; /* 短脸程度 */ public double cheekShortIntensity = 0.0; /* 小脸程度 */ public double cheekSmallIntensity = 0.0; /* 瘦颧骨 */ public double cheekBonesIntensity = 0.0; /* 瘦下颌骨 */ public double lowerJawIntensity = 0.0; /* 大眼程度 */ public double eyeEnlargingIntensity = 0.0; /* 圆眼程度 */ public double eyeCircleIntensity = 0.0; /* 下巴调整程度 */ public double chinIntensity = 0.5; /* 额头调整程度 */ public double forHeadIntensity = 0.5; /* 瘦鼻程度 */ public double noseIntensity = 0.0; /* 嘴巴调整程度 */ public double mouthIntensity = 0.5; /* 开眼角强度 */ public double canthusIntensity = 0.0; /* 眼睛间距 */ public double eyeSpaceIntensity = 0.5; /* 眼睛角度 */ public double eyeRotateIntensity = 0.5; /* 鼻子长度 */ public double longNoseIntensity = 0.5; /* 调节人中 */ public double philtrumIntensity = 0.5; /* 微笑嘴角强度 */ public double smileIntensity = 0.0; /* 眉毛上下 */ public double browHeightIntensity = 0.5; /* 眉毛间距 */ public double browSpaceIntensity = 0.5; /* 眼睑 */ public double eyeLidIntensity = 0.0; /* 眼睛高度 */ public double eyeHeightIntensity = 0.5; /* 眉毛粗细 */ public double browThickIntensity = 0.5; /* 嘴巴厚度 */ public double lipThickIntensity = 0.5; /* 五官立体 */ public double faceThreeIntensity = 0.5; /* 风格滤镜程度 */ public double filterIntensity = 0.0f; /*风格美妆道具路径*/ public String makeupPath = ""; /*风格美妆强度*/ public double makeupIntensity = 0.0f; /*选中的风格类型,默认选中原生*/ public boolean isSelect = false; }
Faceunity/FULiveDemoDroid
app/src/main/java/com/faceunity/app/data/disksource/style/FUDiskStyleData.java
1,069
/* 去法令纹强度*/
block_comment
zh-cn
package com.faceunity.app.data.disksource.style; import com.faceunity.core.model.facebeauty.FaceBeautyBlurTypeEnum; import java.io.Serializable; /** * 保存到磁盘的风格对象 * 该例只保存特效demo展示出来的风格功能 */ public class FUDiskStyleData implements Serializable { /* 美肤 */ /*是否开启美肤效果*/ public boolean faceBeautySkinEnable = true; /* 磨皮类型 */ public int blurType = FaceBeautyBlurTypeEnum.FineSkin; /* 磨皮程度 */ public double blurIntensity = 0.0; /* 祛斑痘程度 */ public double delspotIntensity = 0.0; /* 美白程度 */ public double colorIntensity = 0.0; /* 美白皮肤分割 */ public boolean enableSkinSeg = false; /* 红润程度 */ public double redIntensity = 0.0; /* 清晰程度 */ public double clarityIntensity = 0.0; /* 锐化程度 */ public double sharpenIntensity = 0.0; /* 亮眼程度 */ public double eyeBrightIntensity = 0.0; /* 美牙程度 */ public double toothIntensity = 0.0; /* 去黑眼圈强度*/ public double removePouchIntensity = 0.0; /* 去法令 <SUF>*/ public double removeLawPatternIntensity = 0.0; /*美型*/ /*是否开启美型效果*/ public boolean faceBeautyShapeEnable = true; /* 瘦脸程度 */ public double cheekThinningIntensity = 0.0; /* V脸程度 */ public double cheekVIntensity = 0.0; /* 窄脸程度 */ public double cheekNarrowIntensity = 0.0; /* 短脸程度 */ public double cheekShortIntensity = 0.0; /* 小脸程度 */ public double cheekSmallIntensity = 0.0; /* 瘦颧骨 */ public double cheekBonesIntensity = 0.0; /* 瘦下颌骨 */ public double lowerJawIntensity = 0.0; /* 大眼程度 */ public double eyeEnlargingIntensity = 0.0; /* 圆眼程度 */ public double eyeCircleIntensity = 0.0; /* 下巴调整程度 */ public double chinIntensity = 0.5; /* 额头调整程度 */ public double forHeadIntensity = 0.5; /* 瘦鼻程度 */ public double noseIntensity = 0.0; /* 嘴巴调整程度 */ public double mouthIntensity = 0.5; /* 开眼角强度 */ public double canthusIntensity = 0.0; /* 眼睛间距 */ public double eyeSpaceIntensity = 0.5; /* 眼睛角度 */ public double eyeRotateIntensity = 0.5; /* 鼻子长度 */ public double longNoseIntensity = 0.5; /* 调节人中 */ public double philtrumIntensity = 0.5; /* 微笑嘴角强度 */ public double smileIntensity = 0.0; /* 眉毛上下 */ public double browHeightIntensity = 0.5; /* 眉毛间距 */ public double browSpaceIntensity = 0.5; /* 眼睑 */ public double eyeLidIntensity = 0.0; /* 眼睛高度 */ public double eyeHeightIntensity = 0.5; /* 眉毛粗细 */ public double browThickIntensity = 0.5; /* 嘴巴厚度 */ public double lipThickIntensity = 0.5; /* 五官立体 */ public double faceThreeIntensity = 0.5; /* 风格滤镜程度 */ public double filterIntensity = 0.0f; /*风格美妆道具路径*/ public String makeupPath = ""; /*风格美妆强度*/ public double makeupIntensity = 0.0f; /*选中的风格类型,默认选中原生*/ public boolean isSelect = false; }
false
943
8
1,069
10
980
7
1,069
10
1,404
13
false
false
false
false
false
true
44451_4
package com.hl.mvvm; import android.app.Application; import android.content.res.Configuration; import androidx.annotation.NonNull; import com.alibaba.android.arouter.launcher.ARouter; import com.hl.base_module.CommonApi; import com.hl.base_module.util.system.AppUtil; import com.hl.base_module.util.system.LogUtil; public class MainAppication extends Application { @Override public void onCreate() { super.onCreate(); // 防止多次初始化: 当多个进程时,oncreate会多次调用 String pkgName = getPackageName(); if (null != pkgName && pkgName.equals( AppUtil.getProcessName(this, android.os.Process.myPid()))) { // 基础模块相关初始化 CommonApi.init(this); // ARouter路由配置 if (LogUtil.isDebugMode(this)) { ARouter.openLog(); ARouter.openDebug(); } ARouter.init(this); } } /** * onTerminate()会在app关闭的时候调用,但是就像onDestroy()一样,不能保证一定会被调用。所以最好不要依赖这个方法做重要的处理, 这个方法最多可以用来销毁一写对象,清除一下缓存,但是也并不能保证一定会清除掉,其他操作,例如想在程序结束保存数据,用这个方法明显是错误的。 */ @Override public void onTerminate() { super.onTerminate(); ARouter.getInstance().destroy(); } /** * 当应用进程退到后台正在被Cached的时候,可能会接收到从onTrimMemory()中返回的下面的值之一: * <p> * TRIM_MEMORY_BACKGROUND 系统正运行于低内存状态并且你的进程正处于LRU缓存名单中最不容易杀掉的位置。尽管你的应用进程并不是处于被杀掉的高危险状态,系统可能已经开始杀掉LRU缓存中的其他进程了。你应该释放那些容易恢复的资源,以便于你的进程可以保留下来,这样当用户回退到你的应用的时候才能够迅速恢复。 * <p> * TRIM_MEMORY_MODERATE 系统正运行于低内存状态并且你的进程已经已经接近LRU名单的中部位置。如果系统开始变得更加内存紧张,你的进程是有可能被杀死的。 * <p> * TRIM_MEMORY_COMPLETE 系统正运行于低内存的状态并且你的进程正处于LRU名单中最容易被杀掉的位置。你应该释放任何不影响你的应用恢复状态的资源。 * * @param level */ @Override public void onTrimMemory(int level) { super.onTrimMemory(level); } @Override public void onLowMemory() { super.onLowMemory(); } @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); } }
FanChael/MVVM
app/src/main/java/com/hl/mvvm/MainAppication.java
711
/** * 当应用进程退到后台正在被Cached的时候,可能会接收到从onTrimMemory()中返回的下面的值之一: * <p> * TRIM_MEMORY_BACKGROUND 系统正运行于低内存状态并且你的进程正处于LRU缓存名单中最不容易杀掉的位置。尽管你的应用进程并不是处于被杀掉的高危险状态,系统可能已经开始杀掉LRU缓存中的其他进程了。你应该释放那些容易恢复的资源,以便于你的进程可以保留下来,这样当用户回退到你的应用的时候才能够迅速恢复。 * <p> * TRIM_MEMORY_MODERATE 系统正运行于低内存状态并且你的进程已经已经接近LRU名单的中部位置。如果系统开始变得更加内存紧张,你的进程是有可能被杀死的。 * <p> * TRIM_MEMORY_COMPLETE 系统正运行于低内存的状态并且你的进程正处于LRU名单中最容易被杀掉的位置。你应该释放任何不影响你的应用恢复状态的资源。 * * @param level */
block_comment
zh-cn
package com.hl.mvvm; import android.app.Application; import android.content.res.Configuration; import androidx.annotation.NonNull; import com.alibaba.android.arouter.launcher.ARouter; import com.hl.base_module.CommonApi; import com.hl.base_module.util.system.AppUtil; import com.hl.base_module.util.system.LogUtil; public class MainAppication extends Application { @Override public void onCreate() { super.onCreate(); // 防止多次初始化: 当多个进程时,oncreate会多次调用 String pkgName = getPackageName(); if (null != pkgName && pkgName.equals( AppUtil.getProcessName(this, android.os.Process.myPid()))) { // 基础模块相关初始化 CommonApi.init(this); // ARouter路由配置 if (LogUtil.isDebugMode(this)) { ARouter.openLog(); ARouter.openDebug(); } ARouter.init(this); } } /** * onTerminate()会在app关闭的时候调用,但是就像onDestroy()一样,不能保证一定会被调用。所以最好不要依赖这个方法做重要的处理, 这个方法最多可以用来销毁一写对象,清除一下缓存,但是也并不能保证一定会清除掉,其他操作,例如想在程序结束保存数据,用这个方法明显是错误的。 */ @Override public void onTerminate() { super.onTerminate(); ARouter.getInstance().destroy(); } /** * 当应用 <SUF>*/ @Override public void onTrimMemory(int level) { super.onTrimMemory(level); } @Override public void onLowMemory() { super.onLowMemory(); } @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); } }
false
605
227
711
268
692
236
711
268
1,044
451
true
true
true
true
true
false
16797_0
import java.util.List; public class Dispatch { public Dispatch(List<Mission> list) { System.out.println("准备调度作业"); for (Mission m : list) { System.out.println(m.getName() + "-" + m.getServiceStatus()); } //第一个 //开始时间 list.get(0).setStartingTime(list.get(0).getArrivalTime()); //完成时间 list.get(0).setFinishingTime(list.get(0).getArrivalTime() + list.get(0).getServiceTime()); //周转时间 list.get(0).setTurnAroundTime(list.get(0).getFinishingTime() - list.get(0).getArrivalTime()); //带权周转时间 list.get(0).setWeightTurnAroundTime((double) list.get(0).getTurnAroundTime() / (double) list.get(0).getServiceTime()); //状态 list.get(0).setServiceStatus("F"); System.out.println("处理=" + list.get(0).getName() + " 周转时间=" + list.get(0).getTurnAroundTime() + " 带权周转时间=" + list.get(0).getWeightTurnAroundTime()); for (Mission m : list) { System.out.println(m.getName() + "-" + m.getServiceStatus()); } //第二个及以后的 for (int i = 1; i < list.size(); i++) { //开始时间 list.get(i).setStartingTime(list.get(i - 1).getFinishingTime()); //完成时间 list.get(i).setFinishingTime(list.get(i).getStartingTime() + list.get(i).getServiceTime()); //周转时间 list.get(i).setTurnAroundTime(list.get(i).getFinishingTime() - list.get(i).getArrivalTime()); //带权周转时间 list.get(i).setWeightTurnAroundTime((double)list.get(i).getTurnAroundTime() / (double) list.get(i).getServiceTime()); //状态 list.get(i).setServiceStatus("F"); System.out.println("处理=" + list.get(i).getName() + " 周转时间=" + list.get(i).getTurnAroundTime() + " 带权周转时间=" + list.get(i).getWeightTurnAroundTime()); for (Mission m : list) { System.out.println(m.getName() + "-" + m.getServiceStatus()); } } } }
FangWolf/simFCFS-SJF
src/Dispatch.java
612
//第一个
line_comment
zh-cn
import java.util.List; public class Dispatch { public Dispatch(List<Mission> list) { System.out.println("准备调度作业"); for (Mission m : list) { System.out.println(m.getName() + "-" + m.getServiceStatus()); } //第一 <SUF> //开始时间 list.get(0).setStartingTime(list.get(0).getArrivalTime()); //完成时间 list.get(0).setFinishingTime(list.get(0).getArrivalTime() + list.get(0).getServiceTime()); //周转时间 list.get(0).setTurnAroundTime(list.get(0).getFinishingTime() - list.get(0).getArrivalTime()); //带权周转时间 list.get(0).setWeightTurnAroundTime((double) list.get(0).getTurnAroundTime() / (double) list.get(0).getServiceTime()); //状态 list.get(0).setServiceStatus("F"); System.out.println("处理=" + list.get(0).getName() + " 周转时间=" + list.get(0).getTurnAroundTime() + " 带权周转时间=" + list.get(0).getWeightTurnAroundTime()); for (Mission m : list) { System.out.println(m.getName() + "-" + m.getServiceStatus()); } //第二个及以后的 for (int i = 1; i < list.size(); i++) { //开始时间 list.get(i).setStartingTime(list.get(i - 1).getFinishingTime()); //完成时间 list.get(i).setFinishingTime(list.get(i).getStartingTime() + list.get(i).getServiceTime()); //周转时间 list.get(i).setTurnAroundTime(list.get(i).getFinishingTime() - list.get(i).getArrivalTime()); //带权周转时间 list.get(i).setWeightTurnAroundTime((double)list.get(i).getTurnAroundTime() / (double) list.get(i).getServiceTime()); //状态 list.get(i).setServiceStatus("F"); System.out.println("处理=" + list.get(i).getName() + " 周转时间=" + list.get(i).getTurnAroundTime() + " 带权周转时间=" + list.get(i).getWeightTurnAroundTime()); for (Mission m : list) { System.out.println(m.getName() + "-" + m.getServiceStatus()); } } } }
false
543
2
612
2
639
2
612
2
734
4
false
false
false
false
false
true
48126_6
package cc.mrbird.febs.cos.entity; import java.time.LocalDateTime; import java.io.Serializable; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * 岗位管理 * * @author FanK */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class PostInfo implements Serializable { private static final long serialVersionUID = 1L; /** * 主键ID */ @TableId(type = IdType.AUTO) private Integer id; /** * 岗位编号 */ private String code; /** * 岗位名称 */ private String postName; /** * 工作地点 */ private String address; /** * 所需经验 */ private String experience; /** * 岗位职责 */ private String responsibility; /** * 学历要求(1.小学 2.初中 3.高中 4.大专 5.本科 6.研究生) */ private Integer academic; /** * 工作时间 */ private String workTime; /** * 工作时段 */ private String workHour; /** * 工作时段 */ private String workAddress; /** * 工作要求 */ private String workRequire; /** * 所属行业 */ private Integer industryId; /** * 创建时间 */ private String createDate; /** * 上下架(0.下架 1.上架) */ private Integer delFlag; /** * 所属企业 */ private Integer enterpriseId; /** * 薪资 */ private String salary; /** * 福利 */ private String welfare; @TableField(exist = false) private String enterpriseName; }
Fankekeke/job_hunt
backend/src/main/java/cc/mrbird/febs/cos/entity/PostInfo.java
491
/** * 岗位职责 */
block_comment
zh-cn
package cc.mrbird.febs.cos.entity; import java.time.LocalDateTime; import java.io.Serializable; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * 岗位管理 * * @author FanK */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class PostInfo implements Serializable { private static final long serialVersionUID = 1L; /** * 主键ID */ @TableId(type = IdType.AUTO) private Integer id; /** * 岗位编号 */ private String code; /** * 岗位名称 */ private String postName; /** * 工作地点 */ private String address; /** * 所需经验 */ private String experience; /** * 岗位职 <SUF>*/ private String responsibility; /** * 学历要求(1.小学 2.初中 3.高中 4.大专 5.本科 6.研究生) */ private Integer academic; /** * 工作时间 */ private String workTime; /** * 工作时段 */ private String workHour; /** * 工作时段 */ private String workAddress; /** * 工作要求 */ private String workRequire; /** * 所属行业 */ private Integer industryId; /** * 创建时间 */ private String createDate; /** * 上下架(0.下架 1.上架) */ private Integer delFlag; /** * 所属企业 */ private Integer enterpriseId; /** * 薪资 */ private String salary; /** * 福利 */ private String welfare; @TableField(exist = false) private String enterpriseName; }
false
449
11
491
11
521
10
491
11
667
18
false
false
false
false
false
true
59345_4
package cc.mrbird.febs.cos.entity; import java.time.LocalDateTime; import java.io.Serializable; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * 员工信息 * * @author FanK */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class StaffInfo implements Serializable { private static final long serialVersionUID = 1L; /** * 主键ID */ @TableId(type = IdType.AUTO) private Integer id; /** * 员工编号 */ private String code; /** * 员工姓名 */ private String name; /** * 员工类型(1.司机 2.搬运工) */ private Integer type; /** * 性别(1.男 2.女) */ private Integer sex; /** * 在职状态(1.在职 2.离职) */ private Integer status; /** * 员工照片 */ private String images; /** * 创建时间 */ private String createDate; }
Fankekeke/move_cos
backend/src/main/java/cc/mrbird/febs/cos/entity/StaffInfo.java
306
/** * 员工类型(1.司机 2.搬运工) */
block_comment
zh-cn
package cc.mrbird.febs.cos.entity; import java.time.LocalDateTime; import java.io.Serializable; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * 员工信息 * * @author FanK */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) public class StaffInfo implements Serializable { private static final long serialVersionUID = 1L; /** * 主键ID */ @TableId(type = IdType.AUTO) private Integer id; /** * 员工编号 */ private String code; /** * 员工姓名 */ private String name; /** * 员工类 <SUF>*/ private Integer type; /** * 性别(1.男 2.女) */ private Integer sex; /** * 在职状态(1.在职 2.离职) */ private Integer status; /** * 员工照片 */ private String images; /** * 创建时间 */ private String createDate; }
false
265
20
306
22
321
21
306
22
408
26
false
false
false
false
false
true
41360_12
package math; // Source : https://leetcode.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/ // Id : Offer62 // Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode // Date : 2020/7/19 // Topic : math // Level : Easy // Other : // Tips : // Links : // Result : 99.98% 100.00% public class offer62 { /** * 约瑟夫环; * f(n,m) = [f(n-1, m) + m] \% n * 当数到最后一个结点不足m个时,需要跳到第一个结点继续数。 * 每轮都是上一轮被删结点的下一个结点开始数 m 个。 * * n个人删掉的第一个人的编号是(m-1)%n * * f(n,m)=[(m-1)%n+x+1]%n * =[(m-1)%n%n+(x+1)%n]%n * =[(m-1)%n+(x+1)%n]%n * =(m-1+x+1)%n * =(m+x)%n * * @param n * @param m * @return */ public int lastRemaining(int n, int m) { int pos = 0; // 最终活下来那个人的初始位置 for(int i = 2; i <= n; i++){ pos = (pos + m) % i; // 每次循环右移 } return pos; } }
Fanlu91/FanluLeetcode
src/math/offer62.java
422
// 每次循环右移
line_comment
zh-cn
package math; // Source : https://leetcode.com/problems/yuan-quan-zhong-zui-hou-sheng-xia-de-shu-zi-lcof/ // Id : Offer62 // Author : Fanlu Hai | https://github.com/Fanlu91/FanluLeetcode // Date : 2020/7/19 // Topic : math // Level : Easy // Other : // Tips : // Links : // Result : 99.98% 100.00% public class offer62 { /** * 约瑟夫环; * f(n,m) = [f(n-1, m) + m] \% n * 当数到最后一个结点不足m个时,需要跳到第一个结点继续数。 * 每轮都是上一轮被删结点的下一个结点开始数 m 个。 * * n个人删掉的第一个人的编号是(m-1)%n * * f(n,m)=[(m-1)%n+x+1]%n * =[(m-1)%n%n+(x+1)%n]%n * =[(m-1)%n+(x+1)%n]%n * =(m-1+x+1)%n * =(m+x)%n * * @param n * @param m * @return */ public int lastRemaining(int n, int m) { int pos = 0; // 最终活下来那个人的初始位置 for(int i = 2; i <= n; i++){ pos = (pos + m) % i; // 每次 <SUF> } return pos; } }
false
401
8
422
6
427
6
422
6
518
12
false
false
false
false
false
true
32720_0
package com.fh.util; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; /** * 汉字解析拼音处理 * @author: FHQ313596790 * 修改时间:2015年11月24日 */ public class GetPinyin { /** * 得到 全拼 * @param src * @return */ public static String getPingYin(String src) { char[] t1 = null; t1 = src.toCharArray(); String[] t2 = new String[t1.length]; HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat(); t3.setCaseType(HanyuPinyinCaseType.LOWERCASE); t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE); t3.setVCharType(HanyuPinyinVCharType.WITH_V); String t4 = ""; int t0 = t1.length; try { for (int i = 0; i < t0; i++) { // 判断是否为汉字字符 if (java.lang.Character.toString(t1[i]).matches( "[\\u4E00-\\u9FA5]+")) { t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3); t4 += t2[0]; } else { t4 += java.lang.Character.toString(t1[i]); } } return t4; } catch (BadHanyuPinyinOutputFormatCombination e1) { e1.printStackTrace(); } return t4; } /** * 得到中文首字母 * @param str * @return */ public static String getPinYinHeadChar(String str) { String convert = ""; for (int j = 0; j < str.length(); j++) { char word = str.charAt(j); String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); if (pinyinArray != null) { convert += pinyinArray[0].charAt(0); } else { convert += word; } } return convert; } /** * 将字符串转移为ASCII码 * @param cnStr * @return */ public static String getCnASCII(String cnStr) { StringBuffer strBuf = new StringBuffer(); byte[] bGBK = cnStr.getBytes(); for (int i = 0; i < bGBK.length; i++) { // System.out.println(Integer.toHexString(bGBK[i]&0xff)); strBuf.append(Integer.toHexString(bGBK[i] & 0xff)); } return strBuf.toString(); } public static void main(String[] args) { String cnStr = "中国"; System.out.println(getPingYin(cnStr)); System.out.println(getPinYinHeadChar(cnStr)); } }
Feiyu123/hdManager
src/com/fh/util/GetPinyin.java
905
/** * 汉字解析拼音处理 * @author: FHQ313596790 * 修改时间:2015年11月24日 */
block_comment
zh-cn
package com.fh.util; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.pinyin4j.format.HanyuPinyinToneType; import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType; import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination; /** * 汉字解 <SUF>*/ public class GetPinyin { /** * 得到 全拼 * @param src * @return */ public static String getPingYin(String src) { char[] t1 = null; t1 = src.toCharArray(); String[] t2 = new String[t1.length]; HanyuPinyinOutputFormat t3 = new HanyuPinyinOutputFormat(); t3.setCaseType(HanyuPinyinCaseType.LOWERCASE); t3.setToneType(HanyuPinyinToneType.WITHOUT_TONE); t3.setVCharType(HanyuPinyinVCharType.WITH_V); String t4 = ""; int t0 = t1.length; try { for (int i = 0; i < t0; i++) { // 判断是否为汉字字符 if (java.lang.Character.toString(t1[i]).matches( "[\\u4E00-\\u9FA5]+")) { t2 = PinyinHelper.toHanyuPinyinStringArray(t1[i], t3); t4 += t2[0]; } else { t4 += java.lang.Character.toString(t1[i]); } } return t4; } catch (BadHanyuPinyinOutputFormatCombination e1) { e1.printStackTrace(); } return t4; } /** * 得到中文首字母 * @param str * @return */ public static String getPinYinHeadChar(String str) { String convert = ""; for (int j = 0; j < str.length(); j++) { char word = str.charAt(j); String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); if (pinyinArray != null) { convert += pinyinArray[0].charAt(0); } else { convert += word; } } return convert; } /** * 将字符串转移为ASCII码 * @param cnStr * @return */ public static String getCnASCII(String cnStr) { StringBuffer strBuf = new StringBuffer(); byte[] bGBK = cnStr.getBytes(); for (int i = 0; i < bGBK.length; i++) { // System.out.println(Integer.toHexString(bGBK[i]&0xff)); strBuf.append(Integer.toHexString(bGBK[i] & 0xff)); } return strBuf.toString(); } public static void main(String[] args) { String cnStr = "中国"; System.out.println(getPingYin(cnStr)); System.out.println(getPinYinHeadChar(cnStr)); } }
false
752
43
905
46
855
42
905
46
1,074
54
false
false
false
false
false
true
12646_13
package JUnit; import static org.junit.Assert.*; import java.io.IOException; import java.net.UnknownHostException; import org.junit.Before; import org.junit.Test; import protocol.ProtoHead; import protocol.Msg.LoginMsg; import protocol.Msg.LoginMsg.LoginRsp.ResultCode; import server.NetworkPacket; import client.SocketClientTest; /** * 测试第二个人登陆后第一个人被踢下来的情况 * * @author Feng * */ public class TestDoubleLogin { // public SocketClientTest client1, client2; // @Before // public void init() throws UnknownHostException, IOException { // client1 = new SocketClientTest(); // client1.link(); // client2 = new SocketClientTest(); // client2.link(); // } @Test public void test() throws UnknownHostException, IOException { ClientSocket client1, client2; String user = "a"; // 1号客户端登陆 client1 = new ClientSocket(); ResultCode resultCode = client1.login(user, user); assertEquals(resultCode, LoginMsg.LoginRsp.ResultCode.SUCCESS); // 2号客户端登陆 client2 = new ClientSocket(); resultCode = client2.login(user, user); assertEquals(resultCode, LoginMsg.LoginRsp.ResultCode.SUCCESS); // 检测1号客户端的收到的“踢下线”消息 byte[] resultBytes; boolean getResponse = false; for (int i = 0; i < 2; i++) { resultBytes = client1.readFromServerWithoutKeepAlive(); // 其他消息,不管 if (ProtoHead.ENetworkMessage.OFFLINE_SYNC != NetworkPacket.getMessageType(resultBytes)) continue; // System.err.println(NetworkMessage.getMessageType(resultBytes)); // 回复服务器 // client1.writeToServer(NetworkPacket.packMessage(ProtoHead.ENetworkMessage.OFFLINE_SYNC_VALUE, // NetworkPacket.getMessageID(resultBytes), new byte[]{})); // 踢人通知 assertTrue(true); getResponse = true; return; } if (!getResponse) assertFalse(true); } }
Feng14/MiniWeChat-Server
src/JUnit/TestDoubleLogin.java
566
// 回复服务器
line_comment
zh-cn
package JUnit; import static org.junit.Assert.*; import java.io.IOException; import java.net.UnknownHostException; import org.junit.Before; import org.junit.Test; import protocol.ProtoHead; import protocol.Msg.LoginMsg; import protocol.Msg.LoginMsg.LoginRsp.ResultCode; import server.NetworkPacket; import client.SocketClientTest; /** * 测试第二个人登陆后第一个人被踢下来的情况 * * @author Feng * */ public class TestDoubleLogin { // public SocketClientTest client1, client2; // @Before // public void init() throws UnknownHostException, IOException { // client1 = new SocketClientTest(); // client1.link(); // client2 = new SocketClientTest(); // client2.link(); // } @Test public void test() throws UnknownHostException, IOException { ClientSocket client1, client2; String user = "a"; // 1号客户端登陆 client1 = new ClientSocket(); ResultCode resultCode = client1.login(user, user); assertEquals(resultCode, LoginMsg.LoginRsp.ResultCode.SUCCESS); // 2号客户端登陆 client2 = new ClientSocket(); resultCode = client2.login(user, user); assertEquals(resultCode, LoginMsg.LoginRsp.ResultCode.SUCCESS); // 检测1号客户端的收到的“踢下线”消息 byte[] resultBytes; boolean getResponse = false; for (int i = 0; i < 2; i++) { resultBytes = client1.readFromServerWithoutKeepAlive(); // 其他消息,不管 if (ProtoHead.ENetworkMessage.OFFLINE_SYNC != NetworkPacket.getMessageType(resultBytes)) continue; // System.err.println(NetworkMessage.getMessageType(resultBytes)); // 回复 <SUF> // client1.writeToServer(NetworkPacket.packMessage(ProtoHead.ENetworkMessage.OFFLINE_SYNC_VALUE, // NetworkPacket.getMessageID(resultBytes), new byte[]{})); // 踢人通知 assertTrue(true); getResponse = true; return; } if (!getResponse) assertFalse(true); } }
false
464
5
566
4
539
4
566
4
691
7
false
false
false
false
false
true
20695_4
package core; import utils.MyLogger; import server.Servlet; import server.WebApp; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * @author Firefly * @version 1.0 * @date 2020/2/6 14:31 */ public class Dispatcher { private Request req; private Response res; private OutputStream os; static List<String> staticFile; static { staticFile = new ArrayList<>(); staticFile.add("html"); staticFile.add("ico"); staticFile.add("css"); staticFile.add("jpg"); staticFile.add("js"); staticFile.add("png"); } Dispatcher(Request req, OutputStream os) { this.req = req; this.os = os; // 为 response 做准备 } public void dispatch() { boolean isStatic = false; for (String s : staticFile) { if (req.getUrl().endsWith("." + s)) { this.res = new Response(this.os, s); isStatic = true; break; } } if (isStatic) { handleStatic(); } else { this.res = new Response(this.os, "html"); handleServlet(); } } private void handleStatic() { res.responseByte(req.getUrl()); } private void handleServlet() { MyLogger.log("Info", "start run a servlet: " + req.getUrl()); /** * @author Firefly * 反射创建 servlet */ Servlet servlet = null; try { servlet = WebApp.getServlet(req.getUrl()); } catch (Exception e) { MyLogger.log("Exception", "no this servlet"); res.responseByte("noserverror.html"); return; //不能删死循环 后面 } try { servlet.service(req, res); // 空的 话上面会捕获 res.push2clent(); } catch (Exception e) { MyLogger.log("Exception", "no this servlet"); res.responseByte("500.html");// servlet 运行出错在这里 } } }
Fierygit/Jerryrat
core/Dispatcher.java
524
// 空的 话上面会捕获
line_comment
zh-cn
package core; import utils.MyLogger; import server.Servlet; import server.WebApp; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * @author Firefly * @version 1.0 * @date 2020/2/6 14:31 */ public class Dispatcher { private Request req; private Response res; private OutputStream os; static List<String> staticFile; static { staticFile = new ArrayList<>(); staticFile.add("html"); staticFile.add("ico"); staticFile.add("css"); staticFile.add("jpg"); staticFile.add("js"); staticFile.add("png"); } Dispatcher(Request req, OutputStream os) { this.req = req; this.os = os; // 为 response 做准备 } public void dispatch() { boolean isStatic = false; for (String s : staticFile) { if (req.getUrl().endsWith("." + s)) { this.res = new Response(this.os, s); isStatic = true; break; } } if (isStatic) { handleStatic(); } else { this.res = new Response(this.os, "html"); handleServlet(); } } private void handleStatic() { res.responseByte(req.getUrl()); } private void handleServlet() { MyLogger.log("Info", "start run a servlet: " + req.getUrl()); /** * @author Firefly * 反射创建 servlet */ Servlet servlet = null; try { servlet = WebApp.getServlet(req.getUrl()); } catch (Exception e) { MyLogger.log("Exception", "no this servlet"); res.responseByte("noserverror.html"); return; //不能删死循环 后面 } try { servlet.service(req, res); // 空的 <SUF> res.push2clent(); } catch (Exception e) { MyLogger.log("Exception", "no this servlet"); res.responseByte("500.html");// servlet 运行出错在这里 } } }
false
471
11
524
11
564
8
524
11
631
13
false
false
false
false
false
true
63617_0
package com.dh.home; // v2.1 应用类型 public enum AppType { /** Hotseat */ PHONE("PHONE"), CONTACTS("CONTACTS"), BROWSER("BROWSER"), MMS("MMS"), // CLOCK("CLOCK"), /** 日历 */ CALENDAR("CALENDAR"), /** 画廊 */ GALLERY("GALLERY"), /** 邮件 */ EMAIL("EMAIL"), /** 下载 */ DOWNLOADS("DOWNLOADS"), /** 计算器 */ CALCULATOR("CALCULATOR"), SETTING("SETTING"), CAMERA("CAMERA"), /** 地图 */ MAPS("MAPS"), /** 市场 */ MARKET("MARKET"), /** 升级 */ UPDATER("UPDATER"), MUSIC("MUSIC"); private String value; public String getValue() { return value; } AppType(String type) { this.value = type; } }
FightingLarry/Launcher3
src/com/dh/home/AppType.java
230
// v2.1 应用类型
line_comment
zh-cn
package com.dh.home; // v2 <SUF> public enum AppType { /** Hotseat */ PHONE("PHONE"), CONTACTS("CONTACTS"), BROWSER("BROWSER"), MMS("MMS"), // CLOCK("CLOCK"), /** 日历 */ CALENDAR("CALENDAR"), /** 画廊 */ GALLERY("GALLERY"), /** 邮件 */ EMAIL("EMAIL"), /** 下载 */ DOWNLOADS("DOWNLOADS"), /** 计算器 */ CALCULATOR("CALCULATOR"), SETTING("SETTING"), CAMERA("CAMERA"), /** 地图 */ MAPS("MAPS"), /** 市场 */ MARKET("MARKET"), /** 升级 */ UPDATER("UPDATER"), MUSIC("MUSIC"); private String value; public String getValue() { return value; } AppType(String type) { this.value = type; } }
false
214
9
230
8
216
7
230
8
316
10
false
false
false
false
false
true
57099_2
package com.mic.router.api; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import android.util.LruCache; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.mic.router.annotation.model.RouterBean; import com.mic.router.api.core.RouterLoadGroup; import com.mic.router.api.core.RouterLoadPath; import com.mic.router.api.core.Call; /** * 路由加载管理器 */ public final class RouterManager { // 路由组名 private String group; // 路由详细路径 private String path; private static RouterManager instance; // Lru缓存,key:类名, value:路由组Group加载接口 private LruCache<String, RouterLoadGroup> groupCache; // Lru缓存,key:类名, value:路由组Group对应的详细Path加载接口 private LruCache<String, RouterLoadPath> pathCache; // APT生成的路由组Group源文件前缀名 private static final String GROUP_FILE_PREFIX_NAME = ".Router$$Group$$"; // 单例方式,全局唯一 public static RouterManager getInstance() { if (instance == null) { synchronized (RouterManager.class) { if (instance == null) { instance = new RouterManager(); } } } return instance; } private RouterManager() { // 初始化,并赋值缓存中条目的最大值(最多163组) groupCache = new LruCache<>(163); // 每组最多163条路径值 pathCache = new LruCache<>(163); } public BundleManager build(String path) { // @ARouter注解中的path值,必须要以 / 开头(模仿阿里Arouter规范) if (TextUtils.isEmpty(path) || !path.startsWith("/")) { throw new IllegalArgumentException("未按规范配置,如:/app/MainActivity"); } group = subFromPath2Group(path); // 检查后再赋值 this.path = path; return new BundleManager(); } private String subFromPath2Group(String path) { // 比如开发者代码为:path = "/MainActivity",最后一个 / 符号必然在字符串第1位 if (path.lastIndexOf("/") == 0) { // 架构师定义规范,让开发者遵循 throw new IllegalArgumentException("@ARouter注解未按规范配置,如:/app/MainActivity"); } // 从第一个 / 到第二个 / 中间截取,如:/app/MainActivity 截取出 app 作为group String finalGroup = path.substring(1, path.indexOf("/", 1)); if (TextUtils.isEmpty(finalGroup)) { // 架构师定义规范,让开发者遵循 throw new IllegalArgumentException("@ARouter注解未按规范配置,如:/app/MainActivity"); } // 最终组名:app return finalGroup; } /** * 开始跳转 * * @param context 上下文 * @param bundleManager Bundle拼接参数管理类 * @param code 这里的code,可能是requestCode,也可能是resultCode。取决于isResult * @return 普通跳转可以忽略,用于跨模块CALL接口 */ Object navigation(@NonNull Context context, BundleManager bundleManager, int code) { // 精华:阿里的路由path随意写,导致无法找到随意拼接APT生成的源文件,如:ARouter$$Group$$abc // 找不到,就加载私有目录下apk中的所有dex并遍历,获得所有包名为xxx的类。并开启了线程池工作 // 这里的优化是:代码规范写法,准确定位ARouter$$Group$$app String groupClassName = context.getPackageName() + ".apt" + GROUP_FILE_PREFIX_NAME + group; Log.e("netease >>> ", "groupClassName -> " + groupClassName); try { RouterLoadGroup groupLoad = groupCache.get(group); if (groupLoad == null) { Class<?> clazz = Class.forName(groupClassName); groupLoad = (RouterLoadGroup) clazz.newInstance(); groupCache.put(group, groupLoad); } // 获取路由路径类ARouter$$Path$$app if (groupLoad.loadGroup().isEmpty()) { throw new RuntimeException("路由加载失败"); } RouterLoadPath pathLoad = pathCache.get(path); if (pathLoad == null) { Class<? extends RouterLoadPath> clazz = groupLoad.loadGroup().get(group); if (clazz != null) pathLoad = clazz.newInstance(); if (pathLoad != null) pathCache.put(path, pathLoad); } if (pathLoad != null) { // tempMap赋值 pathLoad.loadPath(); if (pathLoad.loadPath().isEmpty()) { throw new RuntimeException("路由路径加载失败"); } RouterBean routerBean = pathLoad.loadPath().get(path); if (routerBean != null) { switch (routerBean.getType()) { case ACTIVITY: Intent intent = new Intent(context, routerBean.getClazz()); intent.putExtras(bundleManager.getBundle()); // startActivityForResult -> setResult if (bundleManager.isResult()) { ((Activity) context).setResult(code, intent); ((Activity) context).finish(); } if (code > 0) { // 跳转时是否回调 ((Activity) context).startActivityForResult(intent, code, bundleManager.getBundle()); } else { context.startActivity(intent, bundleManager.getBundle()); } break; case CALL: Class<?> clazz = routerBean.getClazz(); Call call = (Call) clazz.newInstance(); bundleManager.setCall(call); return bundleManager.getCall(); case FRAGMENT: Class<?> fragmentClazz = routerBean.getClazz(); Fragment fragment = (Fragment) fragmentClazz.newInstance(); return fragment; } } } } catch (Exception e) { e.printStackTrace(); } return null; } }
Fimics/FimicsPlayer
annotation/router_api/src/main/java/com/mic/router/api/RouterManager.java
1,447
// 路由详细路径
line_comment
zh-cn
package com.mic.router.api; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.text.TextUtils; import android.util.Log; import android.util.LruCache; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import com.mic.router.annotation.model.RouterBean; import com.mic.router.api.core.RouterLoadGroup; import com.mic.router.api.core.RouterLoadPath; import com.mic.router.api.core.Call; /** * 路由加载管理器 */ public final class RouterManager { // 路由组名 private String group; // 路由 <SUF> private String path; private static RouterManager instance; // Lru缓存,key:类名, value:路由组Group加载接口 private LruCache<String, RouterLoadGroup> groupCache; // Lru缓存,key:类名, value:路由组Group对应的详细Path加载接口 private LruCache<String, RouterLoadPath> pathCache; // APT生成的路由组Group源文件前缀名 private static final String GROUP_FILE_PREFIX_NAME = ".Router$$Group$$"; // 单例方式,全局唯一 public static RouterManager getInstance() { if (instance == null) { synchronized (RouterManager.class) { if (instance == null) { instance = new RouterManager(); } } } return instance; } private RouterManager() { // 初始化,并赋值缓存中条目的最大值(最多163组) groupCache = new LruCache<>(163); // 每组最多163条路径值 pathCache = new LruCache<>(163); } public BundleManager build(String path) { // @ARouter注解中的path值,必须要以 / 开头(模仿阿里Arouter规范) if (TextUtils.isEmpty(path) || !path.startsWith("/")) { throw new IllegalArgumentException("未按规范配置,如:/app/MainActivity"); } group = subFromPath2Group(path); // 检查后再赋值 this.path = path; return new BundleManager(); } private String subFromPath2Group(String path) { // 比如开发者代码为:path = "/MainActivity",最后一个 / 符号必然在字符串第1位 if (path.lastIndexOf("/") == 0) { // 架构师定义规范,让开发者遵循 throw new IllegalArgumentException("@ARouter注解未按规范配置,如:/app/MainActivity"); } // 从第一个 / 到第二个 / 中间截取,如:/app/MainActivity 截取出 app 作为group String finalGroup = path.substring(1, path.indexOf("/", 1)); if (TextUtils.isEmpty(finalGroup)) { // 架构师定义规范,让开发者遵循 throw new IllegalArgumentException("@ARouter注解未按规范配置,如:/app/MainActivity"); } // 最终组名:app return finalGroup; } /** * 开始跳转 * * @param context 上下文 * @param bundleManager Bundle拼接参数管理类 * @param code 这里的code,可能是requestCode,也可能是resultCode。取决于isResult * @return 普通跳转可以忽略,用于跨模块CALL接口 */ Object navigation(@NonNull Context context, BundleManager bundleManager, int code) { // 精华:阿里的路由path随意写,导致无法找到随意拼接APT生成的源文件,如:ARouter$$Group$$abc // 找不到,就加载私有目录下apk中的所有dex并遍历,获得所有包名为xxx的类。并开启了线程池工作 // 这里的优化是:代码规范写法,准确定位ARouter$$Group$$app String groupClassName = context.getPackageName() + ".apt" + GROUP_FILE_PREFIX_NAME + group; Log.e("netease >>> ", "groupClassName -> " + groupClassName); try { RouterLoadGroup groupLoad = groupCache.get(group); if (groupLoad == null) { Class<?> clazz = Class.forName(groupClassName); groupLoad = (RouterLoadGroup) clazz.newInstance(); groupCache.put(group, groupLoad); } // 获取路由路径类ARouter$$Path$$app if (groupLoad.loadGroup().isEmpty()) { throw new RuntimeException("路由加载失败"); } RouterLoadPath pathLoad = pathCache.get(path); if (pathLoad == null) { Class<? extends RouterLoadPath> clazz = groupLoad.loadGroup().get(group); if (clazz != null) pathLoad = clazz.newInstance(); if (pathLoad != null) pathCache.put(path, pathLoad); } if (pathLoad != null) { // tempMap赋值 pathLoad.loadPath(); if (pathLoad.loadPath().isEmpty()) { throw new RuntimeException("路由路径加载失败"); } RouterBean routerBean = pathLoad.loadPath().get(path); if (routerBean != null) { switch (routerBean.getType()) { case ACTIVITY: Intent intent = new Intent(context, routerBean.getClazz()); intent.putExtras(bundleManager.getBundle()); // startActivityForResult -> setResult if (bundleManager.isResult()) { ((Activity) context).setResult(code, intent); ((Activity) context).finish(); } if (code > 0) { // 跳转时是否回调 ((Activity) context).startActivityForResult(intent, code, bundleManager.getBundle()); } else { context.startActivity(intent, bundleManager.getBundle()); } break; case CALL: Class<?> clazz = routerBean.getClazz(); Call call = (Call) clazz.newInstance(); bundleManager.setCall(call); return bundleManager.getCall(); case FRAGMENT: Class<?> fragmentClazz = routerBean.getClazz(); Fragment fragment = (Fragment) fragmentClazz.newInstance(); return fragment; } } } } catch (Exception e) { e.printStackTrace(); } return null; } }
false
1,344
7
1,447
5
1,509
5
1,447
5
1,941
14
false
false
false
false
false
true
45202_3
package com.ppdai.stargate.service.flink; import com.ppdai.stargate.dao.GroupRepository; import com.ppdai.stargate.job.JobInfo; import com.ppdai.stargate.service.JobService; import com.ppdai.stargate.vi.FlinkJobVO; import com.ppdai.stargate.vo.DeployGroupInfoVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service @Slf4j public class FlinkJobGroupService { @Autowired private GroupRepository groupRepo; @Autowired private FlinkService flinkService; @Autowired private JobService jobService; /** * 获取指定站点的发布组列表 * * @return 返回发布组实体列表 */ public List<DeployGroupInfoVO> listGroupByEnvAndAppId(String env, String appId) { List<DeployGroupInfoVO> deployGroupInfoVOs = new ArrayList<>(); groupRepo.findByEnvAndAppId(env, appId).forEach(group -> { DeployGroupInfoVO groupVO = new DeployGroupInfoVO(); BeanUtils.copyProperties(group, groupVO); // 获取各个发布组的流量状态 Long groupId = group.getId(); FlinkJobVO flinkJobVO = flinkService.getFlinkJobStatusByGroupId(groupId); groupVO.setExpectedCount(flinkJobVO.getRunningTaskTotal()); // 计算实际流量 Integer activeCount = flinkJobVO.getRunningTaskTotal(); // 注:total以发布系统的实例数为准,因为remoteRegistry注册中心的实例总数可能会有延迟,即已下线的实例但还在保留在注册中心里 int total = groupVO.getInstanceCount(); groupVO.setActiveCount(activeCount); if (total <= 0) { groupVO.setInstanceUpPercentage(0); } else { groupVO.setInstanceUpPercentage(100 * activeCount / total); } JobInfo jobInfo = jobService.getCurrentJobByGroupId(groupId); groupVO.setJobInfo(jobInfo); deployGroupInfoVOs.add(groupVO); }); return deployGroupInfoVOs; } }
FinVolution/stargate
gate-server/src/main/java/com/ppdai/stargate/service/flink/FlinkJobGroupService.java
570
// 注:total以发布系统的实例数为准,因为remoteRegistry注册中心的实例总数可能会有延迟,即已下线的实例但还在保留在注册中心里
line_comment
zh-cn
package com.ppdai.stargate.service.flink; import com.ppdai.stargate.dao.GroupRepository; import com.ppdai.stargate.job.JobInfo; import com.ppdai.stargate.service.JobService; import com.ppdai.stargate.vi.FlinkJobVO; import com.ppdai.stargate.vo.DeployGroupInfoVO; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service @Slf4j public class FlinkJobGroupService { @Autowired private GroupRepository groupRepo; @Autowired private FlinkService flinkService; @Autowired private JobService jobService; /** * 获取指定站点的发布组列表 * * @return 返回发布组实体列表 */ public List<DeployGroupInfoVO> listGroupByEnvAndAppId(String env, String appId) { List<DeployGroupInfoVO> deployGroupInfoVOs = new ArrayList<>(); groupRepo.findByEnvAndAppId(env, appId).forEach(group -> { DeployGroupInfoVO groupVO = new DeployGroupInfoVO(); BeanUtils.copyProperties(group, groupVO); // 获取各个发布组的流量状态 Long groupId = group.getId(); FlinkJobVO flinkJobVO = flinkService.getFlinkJobStatusByGroupId(groupId); groupVO.setExpectedCount(flinkJobVO.getRunningTaskTotal()); // 计算实际流量 Integer activeCount = flinkJobVO.getRunningTaskTotal(); // 注: <SUF> int total = groupVO.getInstanceCount(); groupVO.setActiveCount(activeCount); if (total <= 0) { groupVO.setInstanceUpPercentage(0); } else { groupVO.setInstanceUpPercentage(100 * activeCount / total); } JobInfo jobInfo = jobService.getCurrentJobByGroupId(groupId); groupVO.setJobInfo(jobInfo); deployGroupInfoVOs.add(groupVO); }); return deployGroupInfoVOs; } }
false
493
36
570
43
574
35
570
43
712
73
false
false
false
false
false
true
16089_8
import java.io.*; import java.util.LinkedList; import java.util.Queue; import Compression.LZMA.Zipper; /** * 测试类,包含encode和decode函数,此例为将文件分割成块再对每块压缩的示例。 * * @author FindHao * 2017.9.13 */ public class LZMAExample { /** * 测试函数 */ public void work() throws Exception { Zipper zipper = new Zipper(); //读取文件 File infile = new File("/home/find/ddown/aa/aa.pptx"); BufferedInputStream ins = new BufferedInputStream(new FileInputStream(infile)); BufferedOutputStream outs = new BufferedOutputStream(new FileOutputStream(new File("/home/find/ddown/aa/aa.lzma"))); // @todo 设置real_len为int,实际限制了每块的大小不能超过2GB int real_len; // 要将文件分割的文件块的大小 final int blockSize = 1024 << 3; // 用来保存每块压缩大小 Queue<Integer> queue = new LinkedList<>(); for (int i = 0; i < infile.length(); i += real_len) { //由于压缩可能会导致文件块变大,因此预开辟两倍空间存放,默认文件分块大小为8KB,即1024<<3 byte[] inbytes = new byte[blockSize << 1]; // @todo: 如果实际不是读到1024 × 8,除非到文件尾部,否则应该继续读取,直到读完1024*8长度的块。 real_len = ins.read(inbytes, 0, blockSize); // @warning: 一定要注意,要以实际大小建stream!!!否则压缩时,会将实际有效数据后面的部分空数据也认为是有效的。!!! ByteArrayInputStream inputStream = new ByteArrayInputStream(inbytes, 0, real_len); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(blockSize << 1); System.out.print("实际读取的字节数" + real_len); zipper.encode(inputStream, outputStream, (long) real_len); // ByteArrarInputStream.size()是指实际有效数据 queue.offer(outputStream.size()); System.out.println("压缩后大小" + (outputStream.size())); //将压缩好的数据写入压缩文件 outs.write(outputStream.toByteArray()); } System.out.println("encode end\n======================================\n"); // 最后一定不要忘记flush outs.flush(); outs.close(); ins.close(); // decoder part infile = new File("/home/find/ddown/aa/aa.lzma"); BufferedOutputStream o2 = new BufferedOutputStream(new FileOutputStream(new File("/home/find/ddown/aa/aa_extra.pptx"))); BufferedInputStream i2 = new BufferedInputStream(new FileInputStream(infile)); // 每个压缩块的大小都在queue里。一个一个压缩块的进行读取和解压 while (!queue.isEmpty()) { byte[] inbytes = new byte[blockSize << 1]; real_len = i2.read(inbytes, 0, queue.peek()); //@todo: 这里应该throw error if (real_len != queue.peek()) { System.out.println("读取的大小和队列里的大小(要读的大小)不同" + real_len + "\t" + queue.peek()); } ByteArrayInputStream inputStream = new ByteArrayInputStream(inbytes, 0, queue.peek()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(blockSize << 1); zipper.decode(inputStream, outputStream); o2.write(outputStream.toByteArray()); queue.poll(); } o2.flush(); o2.close(); i2.close(); } public static void main(String[] args) { LZMAExample example = new LZMAExample(); try { example.work(); } catch (Exception e) { e.printStackTrace(); } } }
FindHao/LZMAExample
src/LZMAExample.java
942
// @warning: 一定要注意,要以实际大小建stream!!!否则压缩时,会将实际有效数据后面的部分空数据也认为是有效的。!!!
line_comment
zh-cn
import java.io.*; import java.util.LinkedList; import java.util.Queue; import Compression.LZMA.Zipper; /** * 测试类,包含encode和decode函数,此例为将文件分割成块再对每块压缩的示例。 * * @author FindHao * 2017.9.13 */ public class LZMAExample { /** * 测试函数 */ public void work() throws Exception { Zipper zipper = new Zipper(); //读取文件 File infile = new File("/home/find/ddown/aa/aa.pptx"); BufferedInputStream ins = new BufferedInputStream(new FileInputStream(infile)); BufferedOutputStream outs = new BufferedOutputStream(new FileOutputStream(new File("/home/find/ddown/aa/aa.lzma"))); // @todo 设置real_len为int,实际限制了每块的大小不能超过2GB int real_len; // 要将文件分割的文件块的大小 final int blockSize = 1024 << 3; // 用来保存每块压缩大小 Queue<Integer> queue = new LinkedList<>(); for (int i = 0; i < infile.length(); i += real_len) { //由于压缩可能会导致文件块变大,因此预开辟两倍空间存放,默认文件分块大小为8KB,即1024<<3 byte[] inbytes = new byte[blockSize << 1]; // @todo: 如果实际不是读到1024 × 8,除非到文件尾部,否则应该继续读取,直到读完1024*8长度的块。 real_len = ins.read(inbytes, 0, blockSize); // @w <SUF> ByteArrayInputStream inputStream = new ByteArrayInputStream(inbytes, 0, real_len); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(blockSize << 1); System.out.print("实际读取的字节数" + real_len); zipper.encode(inputStream, outputStream, (long) real_len); // ByteArrarInputStream.size()是指实际有效数据 queue.offer(outputStream.size()); System.out.println("压缩后大小" + (outputStream.size())); //将压缩好的数据写入压缩文件 outs.write(outputStream.toByteArray()); } System.out.println("encode end\n======================================\n"); // 最后一定不要忘记flush outs.flush(); outs.close(); ins.close(); // decoder part infile = new File("/home/find/ddown/aa/aa.lzma"); BufferedOutputStream o2 = new BufferedOutputStream(new FileOutputStream(new File("/home/find/ddown/aa/aa_extra.pptx"))); BufferedInputStream i2 = new BufferedInputStream(new FileInputStream(infile)); // 每个压缩块的大小都在queue里。一个一个压缩块的进行读取和解压 while (!queue.isEmpty()) { byte[] inbytes = new byte[blockSize << 1]; real_len = i2.read(inbytes, 0, queue.peek()); //@todo: 这里应该throw error if (real_len != queue.peek()) { System.out.println("读取的大小和队列里的大小(要读的大小)不同" + real_len + "\t" + queue.peek()); } ByteArrayInputStream inputStream = new ByteArrayInputStream(inbytes, 0, queue.peek()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(blockSize << 1); zipper.decode(inputStream, outputStream); o2.write(outputStream.toByteArray()); queue.poll(); } o2.flush(); o2.close(); i2.close(); } public static void main(String[] args) { LZMAExample example = new LZMAExample(); try { example.work(); } catch (Exception e) { e.printStackTrace(); } } }
false
844
36
942
39
969
34
942
39
1,284
63
false
false
false
false
false
true
37570_14
package com.fiona.tiaozao; import android.app.Application; /** * Created by fiona on 16-3-4. */ public class App extends Application { //172.19.201.79 public final static String URL = "http://192.168.43.53:8080/"; //请求地址 /** * 数据请求Servlet */ public final static String GOODS_SERVLET = "Flea/GoodsServlet"; public final static String USER_SERVLET = "Flea/UserServlet"; public final static String CLASSIFY_SERVLET = "Flea/ClassifyServlet"; public final static String GOODS_OPERATE_SERVLET = "Flea/GoodsOperateServlet"; public final static String USER_OPERATE_SERVLET = "Flea/UserOperateServlet"; public final static int GOODS_SALE = 0x01; //消息处理 public final static int GOODS_EMPTION = 0x02; public final static int USER = 0x51; public final static String ACTION_GOODS = "goods"; //意图携带的数据 public final static String ACTION_USER = "user"; public final static int REQUEST_PICK_PICTURE = 0x118; //本地选择图片 public final static int REQUEST_CAPTURE = 0x119; //拍照 public final static String SETTING_WIFI = "setting_wifi"; //wifi设置 public final static String SETTING_STALL = "setting_stall"; //摊位改变设置 public final static String SETTING_GOODS = "setting_goods"; //物品降价通知设置 public final static String DEFAULT_PIC = "http://tp4.sinaimg.cn/5827544395/180/0/1"; //默认头像 public final static String QUERY_SALE = "sale_goods"; // 请求出售的物品 public final static String QUERY_EMPTION = "emption_goods"; // 请求求购的物品 public final static String QUERY_USER = "query_user"; // 请求用户列表 public final static String QUERY_USER_GOODS = "query_user_goods"; // 请求用户的出售物品 public final static String QUERY_FAIL="query_fail"; //请求失败 @Override public void onCreate() { super.onCreate(); } }
Fionaaaa/Flea
src/main/java/com/fiona/tiaozao/App.java
576
// 请求用户的出售物品
line_comment
zh-cn
package com.fiona.tiaozao; import android.app.Application; /** * Created by fiona on 16-3-4. */ public class App extends Application { //172.19.201.79 public final static String URL = "http://192.168.43.53:8080/"; //请求地址 /** * 数据请求Servlet */ public final static String GOODS_SERVLET = "Flea/GoodsServlet"; public final static String USER_SERVLET = "Flea/UserServlet"; public final static String CLASSIFY_SERVLET = "Flea/ClassifyServlet"; public final static String GOODS_OPERATE_SERVLET = "Flea/GoodsOperateServlet"; public final static String USER_OPERATE_SERVLET = "Flea/UserOperateServlet"; public final static int GOODS_SALE = 0x01; //消息处理 public final static int GOODS_EMPTION = 0x02; public final static int USER = 0x51; public final static String ACTION_GOODS = "goods"; //意图携带的数据 public final static String ACTION_USER = "user"; public final static int REQUEST_PICK_PICTURE = 0x118; //本地选择图片 public final static int REQUEST_CAPTURE = 0x119; //拍照 public final static String SETTING_WIFI = "setting_wifi"; //wifi设置 public final static String SETTING_STALL = "setting_stall"; //摊位改变设置 public final static String SETTING_GOODS = "setting_goods"; //物品降价通知设置 public final static String DEFAULT_PIC = "http://tp4.sinaimg.cn/5827544395/180/0/1"; //默认头像 public final static String QUERY_SALE = "sale_goods"; // 请求出售的物品 public final static String QUERY_EMPTION = "emption_goods"; // 请求求购的物品 public final static String QUERY_USER = "query_user"; // 请求用户列表 public final static String QUERY_USER_GOODS = "query_user_goods"; // 请求 <SUF> public final static String QUERY_FAIL="query_fail"; //请求失败 @Override public void onCreate() { super.onCreate(); } }
false
530
6
576
9
575
6
576
9
730
13
false
false
false
false
false
true
63966_2
package com.firefox.musicplayer.bean; /** * Created by FireFox on 2017/4/25. */ public class LyricBean { /** * sgc : true * sfy : false * qfy : false * lrc : {"version":7,"lyric":"[00:29.620]细雨带风湿透黄昏的街道\n[00:35.050]抹去雨水双眼无帮地仰望\n[00:40.240]望向孤单的晚灯是那伤感的记忆\n[00:48.630]再次泛起心里无数的思念\n[00:54.000]以往片刻欢笑仍挂在脸上\n[00:58.770]愿你此刻可会知是我衷心的说声\n[01:06.310]喜欢你\n[01:08.940]那双眼动人笑声更迷人\n[01:14.330]愿再可轻抚你那可爱面容\n[01:22.490]挽手说梦话象昨天你共我\n[01:42.970]满带理想的我曾经多冲动\n[01:48.340]埋怨与她相爱难有自由\n[01:53.040]愿你此刻可会知是我衷心的说声\n[02:00.420]喜欢你\n[02:03.230]那双眼动人笑声更迷人\n[02:08.540]愿再可轻抚你那可爱面容\n[02:16.750]挽手说梦话象昨天你共我\n[02:24.740]每晚夜里自我独行\n[02:27.670]随处荡 多冰冷\n[02:35.070]以往为了自我挣扎从不知她的痛苦\n[02:49.380]喜欢你\n[02:52.020]那双眼动人笑声更迷人\n[02:57.420]愿再可轻抚你那可爱面容\n[03:05.590]挽手说梦话象昨天你共我\n[03:13.870]挽手说梦话象昨天你共我\n"} * code : 200 */ private boolean sgc; private boolean sfy; private boolean qfy; private LrcBean lrc; private int code; public boolean isSgc() { return sgc; } public void setSgc(boolean sgc) { this.sgc = sgc; } public boolean isSfy() { return sfy; } public void setSfy(boolean sfy) { this.sfy = sfy; } public boolean isQfy() { return qfy; } public void setQfy(boolean qfy) { this.qfy = qfy; } public LrcBean getLrc() { return lrc; } public void setLrc(LrcBean lrc) { this.lrc = lrc; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public static class LrcBean { /** * version : 7 * lyric : [00:29.620]细雨带风湿透黄昏的街道 [00:35.050]抹去雨水双眼无帮地仰望 [00:40.240]望向孤单的晚灯是那伤感的记忆 [00:48.630]再次泛起心里无数的思念 [00:54.000]以往片刻欢笑仍挂在脸上 [00:58.770]愿你此刻可会知是我衷心的说声 [01:06.310]喜欢你 [01:08.940]那双眼动人笑声更迷人 [01:14.330]愿再可轻抚你那可爱面容 [01:22.490]挽手说梦话象昨天你共我 [01:42.970]满带理想的我曾经多冲动 [01:48.340]埋怨与她相爱难有自由 [01:53.040]愿你此刻可会知是我衷心的说声 [02:00.420]喜欢你 [02:03.230]那双眼动人笑声更迷人 [02:08.540]愿再可轻抚你那可爱面容 [02:16.750]挽手说梦话象昨天你共我 [02:24.740]每晚夜里自我独行 [02:27.670]随处荡 多冰冷 [02:35.070]以往为了自我挣扎从不知她的痛苦 [02:49.380]喜欢你 [02:52.020]那双眼动人笑声更迷人 [02:57.420]愿再可轻抚你那可爱面容 [03:05.590]挽手说梦话象昨天你共我 [03:13.870]挽手说梦话象昨天你共我 */ private int version; private String lyric; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getLyric() { return lyric; } public void setLyric(String lyric) { this.lyric = lyric; } } }
FireFoxAhri/MusicPlayer
app/src/main/java/com/firefox/musicplayer/bean/LyricBean.java
1,651
/** * version : 7 * lyric : [00:29.620]细雨带风湿透黄昏的街道 [00:35.050]抹去雨水双眼无帮地仰望 [00:40.240]望向孤单的晚灯是那伤感的记忆 [00:48.630]再次泛起心里无数的思念 [00:54.000]以往片刻欢笑仍挂在脸上 [00:58.770]愿你此刻可会知是我衷心的说声 [01:06.310]喜欢你 [01:08.940]那双眼动人笑声更迷人 [01:14.330]愿再可轻抚你那可爱面容 [01:22.490]挽手说梦话象昨天你共我 [01:42.970]满带理想的我曾经多冲动 [01:48.340]埋怨与她相爱难有自由 [01:53.040]愿你此刻可会知是我衷心的说声 [02:00.420]喜欢你 [02:03.230]那双眼动人笑声更迷人 [02:08.540]愿再可轻抚你那可爱面容 [02:16.750]挽手说梦话象昨天你共我 [02:24.740]每晚夜里自我独行 [02:27.670]随处荡 多冰冷 [02:35.070]以往为了自我挣扎从不知她的痛苦 [02:49.380]喜欢你 [02:52.020]那双眼动人笑声更迷人 [02:57.420]愿再可轻抚你那可爱面容 [03:05.590]挽手说梦话象昨天你共我 [03:13.870]挽手说梦话象昨天你共我 */
block_comment
zh-cn
package com.firefox.musicplayer.bean; /** * Created by FireFox on 2017/4/25. */ public class LyricBean { /** * sgc : true * sfy : false * qfy : false * lrc : {"version":7,"lyric":"[00:29.620]细雨带风湿透黄昏的街道\n[00:35.050]抹去雨水双眼无帮地仰望\n[00:40.240]望向孤单的晚灯是那伤感的记忆\n[00:48.630]再次泛起心里无数的思念\n[00:54.000]以往片刻欢笑仍挂在脸上\n[00:58.770]愿你此刻可会知是我衷心的说声\n[01:06.310]喜欢你\n[01:08.940]那双眼动人笑声更迷人\n[01:14.330]愿再可轻抚你那可爱面容\n[01:22.490]挽手说梦话象昨天你共我\n[01:42.970]满带理想的我曾经多冲动\n[01:48.340]埋怨与她相爱难有自由\n[01:53.040]愿你此刻可会知是我衷心的说声\n[02:00.420]喜欢你\n[02:03.230]那双眼动人笑声更迷人\n[02:08.540]愿再可轻抚你那可爱面容\n[02:16.750]挽手说梦话象昨天你共我\n[02:24.740]每晚夜里自我独行\n[02:27.670]随处荡 多冰冷\n[02:35.070]以往为了自我挣扎从不知她的痛苦\n[02:49.380]喜欢你\n[02:52.020]那双眼动人笑声更迷人\n[02:57.420]愿再可轻抚你那可爱面容\n[03:05.590]挽手说梦话象昨天你共我\n[03:13.870]挽手说梦话象昨天你共我\n"} * code : 200 */ private boolean sgc; private boolean sfy; private boolean qfy; private LrcBean lrc; private int code; public boolean isSgc() { return sgc; } public void setSgc(boolean sgc) { this.sgc = sgc; } public boolean isSfy() { return sfy; } public void setSfy(boolean sfy) { this.sfy = sfy; } public boolean isQfy() { return qfy; } public void setQfy(boolean qfy) { this.qfy = qfy; } public LrcBean getLrc() { return lrc; } public void setLrc(LrcBean lrc) { this.lrc = lrc; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public static class LrcBean { /** * ver <SUF>*/ private int version; private String lyric; public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public String getLyric() { return lyric; } public void setLyric(String lyric) { this.lyric = lyric; } } }
false
1,389
527
1,651
619
1,526
548
1,651
619
2,043
784
true
true
true
true
true
false
4894_3
package CVE; /** * 地方:src/main/java/com.lxinet.jeesns/core/utils/XssHttpServletRequestWrapper.java * <svg/onLoad=confirm(1)> * <object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgiSGVsbG8iKTs8L3NjcmlwdD4="> * <img src="x" ONERROR=confirm(0)> */ public class CVE_2018_19178 { public static void main(String[] args) { String xss = "<svg/onLoad=confirm(1)>"; xss= cleanXSS(xss);//就只需要如果就欧克 System.out.println(xss); } private static String cleanXSS(String value) { //first checkpoint //(?i)忽略大小写 value = value.replaceAll("(?i)<style>", "&lt;style&gt;").replaceAll("(?i)</style>", "&lt;&#47;style&gt;"); value = value.replaceAll("(?i)<script>", "&lt;script&gt;").replaceAll("(?i)</script>", "&lt;&#47;script&gt;"); value = value.replaceAll("(?i)<script", "&lt;script"); value = value.replaceAll("(?i)eval\\((.*)\\)", ""); value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); //second checkpoint // 需要过滤的脚本事件关键字 String[] eventKeywords = { "onmouseover", "onmouseout", "onmousedown", "onmouseup", "onmousemove", "onclick", "ondblclick", "onkeypress", "onkeydown", "onkeyup", "ondragstart", "onerrorupdate", "onhelp", "onreadystatechange", "onrowenter", "onrowexit", "onselectstart", "onload", "onunload", "onbeforeunload", "onblur", "onerror", "onfocus", "onresize", "onscroll", "oncontextmenu", "alert" }; // 滤除脚本事件代码 for (int i = 0; i < eventKeywords.length; i++) {//没有处理大写字符 // 添加一个"_", 使事件代码无效 value = value.replaceAll(eventKeywords[i],"_" + eventKeywords[i]); } return value; } }
Firebasky/Java
java小型框架/code/CVE_2018_19178.java
555
//(?i)忽略大小写
line_comment
zh-cn
package CVE; /** * 地方:src/main/java/com.lxinet.jeesns/core/utils/XssHttpServletRequestWrapper.java * <svg/onLoad=confirm(1)> * <object data="data:text/html;base64,PHNjcmlwdD5hbGVydCgiSGVsbG8iKTs8L3NjcmlwdD4="> * <img src="x" ONERROR=confirm(0)> */ public class CVE_2018_19178 { public static void main(String[] args) { String xss = "<svg/onLoad=confirm(1)>"; xss= cleanXSS(xss);//就只需要如果就欧克 System.out.println(xss); } private static String cleanXSS(String value) { //first checkpoint //(? <SUF> value = value.replaceAll("(?i)<style>", "&lt;style&gt;").replaceAll("(?i)</style>", "&lt;&#47;style&gt;"); value = value.replaceAll("(?i)<script>", "&lt;script&gt;").replaceAll("(?i)</script>", "&lt;&#47;script&gt;"); value = value.replaceAll("(?i)<script", "&lt;script"); value = value.replaceAll("(?i)eval\\((.*)\\)", ""); value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); //second checkpoint // 需要过滤的脚本事件关键字 String[] eventKeywords = { "onmouseover", "onmouseout", "onmousedown", "onmouseup", "onmousemove", "onclick", "ondblclick", "onkeypress", "onkeydown", "onkeyup", "ondragstart", "onerrorupdate", "onhelp", "onreadystatechange", "onrowenter", "onrowexit", "onselectstart", "onload", "onunload", "onbeforeunload", "onblur", "onerror", "onfocus", "onresize", "onscroll", "oncontextmenu", "alert" }; // 滤除脚本事件代码 for (int i = 0; i < eventKeywords.length; i++) {//没有处理大写字符 // 添加一个"_", 使事件代码无效 value = value.replaceAll(eventKeywords[i],"_" + eventKeywords[i]); } return value; } }
false
527
7
555
8
575
7
555
8
697
13
false
false
false
false
false
true
25124_17
package com.fish.bin.action; import com.fish.bin.api.GetTranslationTask; import com.fish.bin.bean.DataBean; import com.fish.bin.utils.StringUtils; import com.intellij.notification.impl.NotificationsManagerImpl; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFrame; import com.intellij.psi.PsiFile; import com.intellij.psi.XmlRecursiveElementVisitor; import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.xml.XmlTag; import com.intellij.ui.EditorTextField; import com.intellij.ui.JBColor; import com.intellij.ui.awt.RelativePoint; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * 将xml中字符串到strings中 * * @author liubin */ public class ExtractText extends AnAction { private String layoutName; private List<DataBean> dataBeans; private Editor editor; private Project project; private Document document; @Override public void actionPerformed(AnActionEvent e) { //当前项目 project = e.getData(PlatformDataKeys.PROJECT); //当前文件 PsiFile psiFile = e.getData(PlatformDataKeys.PSI_FILE); //当前光标位置 editor = e.getData(PlatformDataKeys.EDITOR); if (project != null && psiFile != null) { if (psiFile.getParent() != null && psiFile.getParent().getName().equals("layout") && psiFile.getName().contains("xml")) { //选中layout中的布局文件 layoutName = psiFile.getName().split("\\.")[0]; handLayout(layoutName); } else if (editor != null) { //选中java类的布局文件 //可操作的文档文件 document = editor.getDocument(); layoutName = editor.getSelectionModel().getSelectedText(); handLayout(layoutName); } else { showDialog("请选中布局文件", 2); } } else { showDialog("请选中焦点或布局文件", 2); } } /** * 处理布局,获取需要的内容 * * @param layoutName 布局的名字 */ private void handLayout(String layoutName) { System.out.println("需要处理的布局文件为:" + layoutName); //获取布局文件 PsiFile[] filesByName = FilenameIndex.getFilesByName(project, layoutName + ".xml", GlobalSearchScope.projectScope(project)); //如果布局文件有且仅有一个 if (filesByName.length == 1) { try { //文件内容 PsiFile file = filesByName[0]; //打印文件内容 System.out.println(file.getText()); //储存需要的内容 dataBeans = new LinkedList<>(); List<String> soureces = new ArrayList<>(); //xml解析,获取所有标签元素(不处理include标签) file.accept(new XmlRecursiveElementVisitor(true) { @Override public void visitXmlTag(XmlTag tag) { super.visitXmlTag(tag); //获取标签以及value值 String valueText = tag.getAttributeValue("android:text"); String valueHint = tag.getAttributeValue("android:hint"); if (valueText != null && !valueText.isEmpty() && !valueText.contains("@string")) { soureces.add(valueText); String key = layoutName + "_"; dataBeans.add(new DataBean(key, valueText)); } if (valueHint != null && !valueHint.isEmpty() && !valueHint.contains("@string")) { soureces.add(valueHint); String key = layoutName + "_"; dataBeans.add(new DataBean(key, valueHint)); } } }); if (soureces.size() == 0) { showDialog("没有需要替换的字符串", 1); } else { //翻译并处理结果 translate(file, soureces); } } catch (Exception e) { showDialog("全局异常:" + e.getMessage(), 2); } } else { showDialog("请选中layout", 2); } } private void handResult(PsiFile file) { if (dataBeans.size() > 0) { //改文件的值 changeXml(file); //获取内容 String content = getShowContent(dataBeans); //往xml中写内容 writeContentXml(content); //显示文字(弹出框形式) showDialog("success", 2); } else { showDialog("没有需要提取的字符串", 2); } } /** * 翻译 */ private void translate(PsiFile file, List<String> sources) { new GetTranslationTask(project, "翻译中", sources, result -> { if (result != null) { for (int i = 0; i < dataBeans.size(); i++) { DataBean dataBean = dataBeans.get(i); dataBean.setKey(dataBean.getKey() + StringUtils.formatStr(result.get(i))); } handResult(file); } else { showDialog("翻译异常", 2); } }).setCancelText("Translation Has Been Canceled").queue(); } /** * 改布局文件里的映射 */ private void changeXml(PsiFile file) { Runnable runnable = () -> { VirtualFile virtualFile = file.getVirtualFile(); Document document = FileDocumentManager.getInstance().getDocument(virtualFile); if(document!=null){ String text = document.getText(); for (DataBean attributeValue : dataBeans) { text = text.replace("\"" + attributeValue.getValue() + "\"", "\"" + "@string/" + attributeValue.getKey() + "\""); } document.setText(text); } }; WriteCommandAction.runWriteCommandAction(project, runnable); } /** * 往strings.xml中写内容 */ private void writeContentXml(String content) { try { String stringPath = project.getBasePath() + "/app/src/main/res/values/strings.xml"; VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(stringPath); if (virtualFile != null) { Runnable runnable = () -> { Document document = FileDocumentManager.getInstance().getDocument(virtualFile); if(document!=null){ int lineCount = document.getLineCount(); int lineNumber = document.getLineStartOffset(lineCount - 1); document.insertString(lineNumber, content); } }; WriteCommandAction.runWriteCommandAction(project, runnable); } else { showDialog("strings.xml文件没找到", 2); } } catch (Exception e) { e.printStackTrace(); } } /** * 向文件中写入内容 */ private void writeContentCurrent(String content) { int maxOffset = document.getTextLength(); Runnable runnable = () -> document.insertString(maxOffset, content); WriteCommandAction.runWriteCommandAction(project, runnable); } /** * 获取需要显示的内容 */ private String getShowContent(List<DataBean> attributeValues) { StringBuilder block = new StringBuilder(); block.append("<!--################ ").append(layoutName).append(" start ################-->\n"); for (DataBean dataBean : attributeValues) { block.append("<string name=\"") .append(dataBean.getKey()) .append("\">") .append(dataBean.getValue()) .append("</string>\n"); } block.append("<!--################ ").append(layoutName).append(" end ################-->\n"); return block.toString(); } /** * 显示提示框 */ private void showDialog(final String result, final int time) { ApplicationManager.getApplication().invokeLater(() -> { JBPopupFactory factory = JBPopupFactory.getInstance(); Balloon balloon = factory.createHtmlTextBalloonBuilder(result, null, JBColor.GRAY, null) .setFadeoutTime(time * 1000) .createBalloon(); if (editor == null) { RelativePoint pointToShowPopup = null; IdeFrame window = (IdeFrame) NotificationsManagerImpl.findWindowForBalloon(project); if (window != null) pointToShowPopup = RelativePoint.getSouthEastOf(window.getComponent()); balloon.show(pointToShowPopup, Balloon.Position.atLeft); } else { balloon.show(factory.guessBestPopupLocation(editor), Balloon.Position.below); } }); } /** * 显示文本框 */ private void showEditText(String result) { JBPopupFactory instance = JBPopupFactory.getInstance(); instance.createDialogBalloonBuilder(new EditorTextField(EditorFactory.getInstance().createDocument(result), null, FileTypes.PLAIN_TEXT, false, false), "KViewBind-Generate") .setHideOnKeyOutside(true) .setHideOnClickOutside(true) .createBalloon() .show(instance.guessBestPopupLocation(editor), Balloon.Position.below); } }
Fish-Bin/ExtractText
src/com/fish/bin/action/ExtractText.java
2,326
//获取内容
line_comment
zh-cn
package com.fish.bin.action; import com.fish.bin.api.GetTranslationTask; import com.fish.bin.bean.DataBean; import com.fish.bin.utils.StringUtils; import com.intellij.notification.impl.NotificationsManagerImpl; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.PlatformDataKeys; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.fileTypes.FileTypes; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.popup.Balloon; import com.intellij.openapi.ui.popup.JBPopupFactory; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.IdeFrame; import com.intellij.psi.PsiFile; import com.intellij.psi.XmlRecursiveElementVisitor; import com.intellij.psi.search.FilenameIndex; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.psi.xml.XmlTag; import com.intellij.ui.EditorTextField; import com.intellij.ui.JBColor; import com.intellij.ui.awt.RelativePoint; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * 将xml中字符串到strings中 * * @author liubin */ public class ExtractText extends AnAction { private String layoutName; private List<DataBean> dataBeans; private Editor editor; private Project project; private Document document; @Override public void actionPerformed(AnActionEvent e) { //当前项目 project = e.getData(PlatformDataKeys.PROJECT); //当前文件 PsiFile psiFile = e.getData(PlatformDataKeys.PSI_FILE); //当前光标位置 editor = e.getData(PlatformDataKeys.EDITOR); if (project != null && psiFile != null) { if (psiFile.getParent() != null && psiFile.getParent().getName().equals("layout") && psiFile.getName().contains("xml")) { //选中layout中的布局文件 layoutName = psiFile.getName().split("\\.")[0]; handLayout(layoutName); } else if (editor != null) { //选中java类的布局文件 //可操作的文档文件 document = editor.getDocument(); layoutName = editor.getSelectionModel().getSelectedText(); handLayout(layoutName); } else { showDialog("请选中布局文件", 2); } } else { showDialog("请选中焦点或布局文件", 2); } } /** * 处理布局,获取需要的内容 * * @param layoutName 布局的名字 */ private void handLayout(String layoutName) { System.out.println("需要处理的布局文件为:" + layoutName); //获取布局文件 PsiFile[] filesByName = FilenameIndex.getFilesByName(project, layoutName + ".xml", GlobalSearchScope.projectScope(project)); //如果布局文件有且仅有一个 if (filesByName.length == 1) { try { //文件内容 PsiFile file = filesByName[0]; //打印文件内容 System.out.println(file.getText()); //储存需要的内容 dataBeans = new LinkedList<>(); List<String> soureces = new ArrayList<>(); //xml解析,获取所有标签元素(不处理include标签) file.accept(new XmlRecursiveElementVisitor(true) { @Override public void visitXmlTag(XmlTag tag) { super.visitXmlTag(tag); //获取标签以及value值 String valueText = tag.getAttributeValue("android:text"); String valueHint = tag.getAttributeValue("android:hint"); if (valueText != null && !valueText.isEmpty() && !valueText.contains("@string")) { soureces.add(valueText); String key = layoutName + "_"; dataBeans.add(new DataBean(key, valueText)); } if (valueHint != null && !valueHint.isEmpty() && !valueHint.contains("@string")) { soureces.add(valueHint); String key = layoutName + "_"; dataBeans.add(new DataBean(key, valueHint)); } } }); if (soureces.size() == 0) { showDialog("没有需要替换的字符串", 1); } else { //翻译并处理结果 translate(file, soureces); } } catch (Exception e) { showDialog("全局异常:" + e.getMessage(), 2); } } else { showDialog("请选中layout", 2); } } private void handResult(PsiFile file) { if (dataBeans.size() > 0) { //改文件的值 changeXml(file); //获取 <SUF> String content = getShowContent(dataBeans); //往xml中写内容 writeContentXml(content); //显示文字(弹出框形式) showDialog("success", 2); } else { showDialog("没有需要提取的字符串", 2); } } /** * 翻译 */ private void translate(PsiFile file, List<String> sources) { new GetTranslationTask(project, "翻译中", sources, result -> { if (result != null) { for (int i = 0; i < dataBeans.size(); i++) { DataBean dataBean = dataBeans.get(i); dataBean.setKey(dataBean.getKey() + StringUtils.formatStr(result.get(i))); } handResult(file); } else { showDialog("翻译异常", 2); } }).setCancelText("Translation Has Been Canceled").queue(); } /** * 改布局文件里的映射 */ private void changeXml(PsiFile file) { Runnable runnable = () -> { VirtualFile virtualFile = file.getVirtualFile(); Document document = FileDocumentManager.getInstance().getDocument(virtualFile); if(document!=null){ String text = document.getText(); for (DataBean attributeValue : dataBeans) { text = text.replace("\"" + attributeValue.getValue() + "\"", "\"" + "@string/" + attributeValue.getKey() + "\""); } document.setText(text); } }; WriteCommandAction.runWriteCommandAction(project, runnable); } /** * 往strings.xml中写内容 */ private void writeContentXml(String content) { try { String stringPath = project.getBasePath() + "/app/src/main/res/values/strings.xml"; VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(stringPath); if (virtualFile != null) { Runnable runnable = () -> { Document document = FileDocumentManager.getInstance().getDocument(virtualFile); if(document!=null){ int lineCount = document.getLineCount(); int lineNumber = document.getLineStartOffset(lineCount - 1); document.insertString(lineNumber, content); } }; WriteCommandAction.runWriteCommandAction(project, runnable); } else { showDialog("strings.xml文件没找到", 2); } } catch (Exception e) { e.printStackTrace(); } } /** * 向文件中写入内容 */ private void writeContentCurrent(String content) { int maxOffset = document.getTextLength(); Runnable runnable = () -> document.insertString(maxOffset, content); WriteCommandAction.runWriteCommandAction(project, runnable); } /** * 获取需要显示的内容 */ private String getShowContent(List<DataBean> attributeValues) { StringBuilder block = new StringBuilder(); block.append("<!--################ ").append(layoutName).append(" start ################-->\n"); for (DataBean dataBean : attributeValues) { block.append("<string name=\"") .append(dataBean.getKey()) .append("\">") .append(dataBean.getValue()) .append("</string>\n"); } block.append("<!--################ ").append(layoutName).append(" end ################-->\n"); return block.toString(); } /** * 显示提示框 */ private void showDialog(final String result, final int time) { ApplicationManager.getApplication().invokeLater(() -> { JBPopupFactory factory = JBPopupFactory.getInstance(); Balloon balloon = factory.createHtmlTextBalloonBuilder(result, null, JBColor.GRAY, null) .setFadeoutTime(time * 1000) .createBalloon(); if (editor == null) { RelativePoint pointToShowPopup = null; IdeFrame window = (IdeFrame) NotificationsManagerImpl.findWindowForBalloon(project); if (window != null) pointToShowPopup = RelativePoint.getSouthEastOf(window.getComponent()); balloon.show(pointToShowPopup, Balloon.Position.atLeft); } else { balloon.show(factory.guessBestPopupLocation(editor), Balloon.Position.below); } }); } /** * 显示文本框 */ private void showEditText(String result) { JBPopupFactory instance = JBPopupFactory.getInstance(); instance.createDialogBalloonBuilder(new EditorTextField(EditorFactory.getInstance().createDocument(result), null, FileTypes.PLAIN_TEXT, false, false), "KViewBind-Generate") .setHideOnKeyOutside(true) .setHideOnClickOutside(true) .createBalloon() .show(instance.guessBestPopupLocation(editor), Balloon.Position.below); } }
false
2,041
3
2,326
3
2,469
3
2,326
3
2,906
5
false
false
false
false
false
true
21108_10
package com.fitpolo.support.entity; /** * @Date 2017/5/14 0014 * @Author wenzheng.liu * @Description 手环闹钟 * @ClassPath com.fitpolo.support.entity.BandAlarm */ public class BandAlarm { public String time;// 时间,格式:HH:mm // 状态 // bit[7]:0:关闭;1:打开; // bit[6]:1:周日; // bit[5]:1:周六; // bit[4]:1:周五; // bit[3]:1:周四; // bit[2]:1:周三; // bit[1]:1:周二; // bit[0]:1:周一; // ex:每周日打开:11000000;每周一到周五打开10011111; public String state; public int type;// 类型,0:吃药;1:喝水;3:普通;4:睡觉;5:吃药;6:锻炼 @Override public String toString() { return "BandAlarm{" + "time='" + time + '\'' + ", state='" + state + '\'' + ", type='" + type + '\'' + '}'; } }
Fitpolo/FitpoloDemo_H705_Android
fitpolosupport/src/main/java/com/fitpolo/support/entity/BandAlarm.java
326
// ex:每周日打开:11000000;每周一到周五打开10011111;
line_comment
zh-cn
package com.fitpolo.support.entity; /** * @Date 2017/5/14 0014 * @Author wenzheng.liu * @Description 手环闹钟 * @ClassPath com.fitpolo.support.entity.BandAlarm */ public class BandAlarm { public String time;// 时间,格式:HH:mm // 状态 // bit[7]:0:关闭;1:打开; // bit[6]:1:周日; // bit[5]:1:周六; // bit[4]:1:周五; // bit[3]:1:周四; // bit[2]:1:周三; // bit[1]:1:周二; // bit[0]:1:周一; // ex <SUF> public String state; public int type;// 类型,0:吃药;1:喝水;3:普通;4:睡觉;5:吃药;6:锻炼 @Override public String toString() { return "BandAlarm{" + "time='" + time + '\'' + ", state='" + state + '\'' + ", type='" + type + '\'' + '}'; } }
false
296
30
326
33
325
31
326
33
394
35
false
false
false
false
false
true
48517_6
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Random; import java.util.concurrent.TimeUnit; import javax.swing.*; public class RockPaperScissors extends JFrame { private JLabel lb1, lb2, lb3, lb4; // 提示标签 private JTextField ta1, ta2;// 两个文本框 private JButton b1, b2, b3,b4; // 三个按钮 private JPanel p1, p2,p3; // 三个JPanel面板 private int res_flag=1; // 两个JPanel面板 private boolean flag; private String utf_jd = null; //剪刀 private String utf_st = null;// 石头 private String utf_b = null;//布 private FiveChessWindows five; public RockPaperScissors(boolean flag,FiveChessWindows five) { this.flag=flag; this.five=five; // 初始化所有组件 lb1 = new JLabel("猜拳"); lb2 = new JLabel(" 您出拳: "); lb3 = new JLabel("电脑出拳:"); lb4 = new JLabel(" "); ta1 = new JTextField(); ta1.setPreferredSize(new Dimension(60, 60)); // 设置大小 ta1.setFont(new Font(null, Font.BOLD,50)); ta1.setEditable(false);//设置不可编辑 ta2 = new JTextField(); ta2.setPreferredSize(new Dimension(60, 60)); ta2.setFont(new Font(null, Font.BOLD,50)); ta2.setEditable(false);//设置不可编辑 Gbk_Utf(); b1 = new JButton("剪刀"+utf_jd); b2 = new JButton("石头"+utf_st); b3 = new JButton("布"+utf_b); b4 = new JButton("开始下棋⚪"); p1 = new JPanel(); p2 = new JPanel(); p3 = new JPanel(); // 设置第一个面板内容 Box box = Box.createVerticalBox(); Box box1 = Box.createHorizontalBox(); box1.add(lb2); box1.add(ta1); box1.add(new JLabel(" VS ")); box1.add(ta2); box1.add(lb3); box.add(lb1); box.add(Box.createVerticalStrut(30)); box.add(box1); box.add(Box.createVerticalStrut(30)); box.add(lb4); p1.add(box); p3.add(b4); // 设置第二个面板 p2.setLayout(new GridBagLayout()); // 使用GridBagLayout布局管理器 p2.setPreferredSize(new Dimension(0, 60)); GridBagConstraints g2 = new GridBagConstraints(); g2.fill = GridBagConstraints.BOTH; g2.weightx = 1.0; g2.weighty = 1.0; g2.gridx = 0; g2.gridy = 0; p2.add(b1, g2); g2.gridx = 1; p2.add(b2, g2); g2.gridx = 2; p2.add(b3, g2); //为4个按钮添加事件 b1.addActionListener(new buttonAction()); b2.addActionListener(new buttonAction()); b3.addActionListener(new buttonAction()); b4.addActionListener(new buttonAction()); getContentPane().add(p1,BorderLayout.NORTH); getContentPane().add(p3); getContentPane().add(p2, BorderLayout.SOUTH); setTitle("猜拳决定落子顺序"); setLocation(560, 360); setSize(540, 330); setIconImage(this.getToolkit().getImage("./src/favicon.png")); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void Gbk_Utf() { try { utf_jd = new String("✌".getBytes("UTF-8"), "UTF-8"); utf_st = new String("✊".getBytes("UTF-8"), "UTF-8"); utf_b = new String("👋".getBytes("UTF-8"), "UTF-8"); } catch (UnsupportedEncodingException e1) {e1.printStackTrace();} } //事件类 class buttonAction extends AbstractAction{ public void actionPerformed(ActionEvent e) { String res=""; if(e.getSource()==b1){ ta1.setText(utf_jd); res=init(ta1.getText()); }else if(e.getSource()==b2){ ta1.setText(utf_st); res=init(ta1.getText()); }else if(e.getSource()==b3){ ta1.setText(utf_b); res=init(ta1.getText()); }else { new FiveChessWindows().init(flag,res_flag); five.dispose(); dispose(); } if(res.equals("电脑赢了 您后手。")) res_flag=-1; if(res.equals("您赢了 您先手。")) res_flag=1; } // 模拟电脑出拳,产生三个随机数。0代表剪刀,1代表石头,2代表布 public String getQuan(){ String str=""; int num=new Random().nextInt(3) ;//产生随机数 if(num==0)str=utf_jd; else if(num==1)str=utf_st; else str=utf_b; return str; } public String init(String wo){ String sy=""; // 保存输赢结果 String dncq=getQuan(); //电脑出拳 if(wo.equals(dncq))sy="平局,再来一次"; else if(wo.equals(utf_jd)&&dncq.equals(utf_b) || wo.equals(utf_st)&&dncq.equals(utf_jd)||wo.equals(utf_b)&&dncq.equals(utf_st))sy="您赢了 您先手。"; else sy="电脑赢了 您后手。"; ta2.setText(dncq);// 电脑出拳 lb4.setText(sy); return sy; } } }
Five-great/FiveChess
FiveChessV18/src/RockPaperScissors.java
1,645
// 石头
line_comment
zh-cn
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Random; import java.util.concurrent.TimeUnit; import javax.swing.*; public class RockPaperScissors extends JFrame { private JLabel lb1, lb2, lb3, lb4; // 提示标签 private JTextField ta1, ta2;// 两个文本框 private JButton b1, b2, b3,b4; // 三个按钮 private JPanel p1, p2,p3; // 三个JPanel面板 private int res_flag=1; // 两个JPanel面板 private boolean flag; private String utf_jd = null; //剪刀 private String utf_st = null;// 石头 <SUF> private String utf_b = null;//布 private FiveChessWindows five; public RockPaperScissors(boolean flag,FiveChessWindows five) { this.flag=flag; this.five=five; // 初始化所有组件 lb1 = new JLabel("猜拳"); lb2 = new JLabel(" 您出拳: "); lb3 = new JLabel("电脑出拳:"); lb4 = new JLabel(" "); ta1 = new JTextField(); ta1.setPreferredSize(new Dimension(60, 60)); // 设置大小 ta1.setFont(new Font(null, Font.BOLD,50)); ta1.setEditable(false);//设置不可编辑 ta2 = new JTextField(); ta2.setPreferredSize(new Dimension(60, 60)); ta2.setFont(new Font(null, Font.BOLD,50)); ta2.setEditable(false);//设置不可编辑 Gbk_Utf(); b1 = new JButton("剪刀"+utf_jd); b2 = new JButton("石头"+utf_st); b3 = new JButton("布"+utf_b); b4 = new JButton("开始下棋⚪"); p1 = new JPanel(); p2 = new JPanel(); p3 = new JPanel(); // 设置第一个面板内容 Box box = Box.createVerticalBox(); Box box1 = Box.createHorizontalBox(); box1.add(lb2); box1.add(ta1); box1.add(new JLabel(" VS ")); box1.add(ta2); box1.add(lb3); box.add(lb1); box.add(Box.createVerticalStrut(30)); box.add(box1); box.add(Box.createVerticalStrut(30)); box.add(lb4); p1.add(box); p3.add(b4); // 设置第二个面板 p2.setLayout(new GridBagLayout()); // 使用GridBagLayout布局管理器 p2.setPreferredSize(new Dimension(0, 60)); GridBagConstraints g2 = new GridBagConstraints(); g2.fill = GridBagConstraints.BOTH; g2.weightx = 1.0; g2.weighty = 1.0; g2.gridx = 0; g2.gridy = 0; p2.add(b1, g2); g2.gridx = 1; p2.add(b2, g2); g2.gridx = 2; p2.add(b3, g2); //为4个按钮添加事件 b1.addActionListener(new buttonAction()); b2.addActionListener(new buttonAction()); b3.addActionListener(new buttonAction()); b4.addActionListener(new buttonAction()); getContentPane().add(p1,BorderLayout.NORTH); getContentPane().add(p3); getContentPane().add(p2, BorderLayout.SOUTH); setTitle("猜拳决定落子顺序"); setLocation(560, 360); setSize(540, 330); setIconImage(this.getToolkit().getImage("./src/favicon.png")); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void Gbk_Utf() { try { utf_jd = new String("✌".getBytes("UTF-8"), "UTF-8"); utf_st = new String("✊".getBytes("UTF-8"), "UTF-8"); utf_b = new String("👋".getBytes("UTF-8"), "UTF-8"); } catch (UnsupportedEncodingException e1) {e1.printStackTrace();} } //事件类 class buttonAction extends AbstractAction{ public void actionPerformed(ActionEvent e) { String res=""; if(e.getSource()==b1){ ta1.setText(utf_jd); res=init(ta1.getText()); }else if(e.getSource()==b2){ ta1.setText(utf_st); res=init(ta1.getText()); }else if(e.getSource()==b3){ ta1.setText(utf_b); res=init(ta1.getText()); }else { new FiveChessWindows().init(flag,res_flag); five.dispose(); dispose(); } if(res.equals("电脑赢了 您后手。")) res_flag=-1; if(res.equals("您赢了 您先手。")) res_flag=1; } // 模拟电脑出拳,产生三个随机数。0代表剪刀,1代表石头,2代表布 public String getQuan(){ String str=""; int num=new Random().nextInt(3) ;//产生随机数 if(num==0)str=utf_jd; else if(num==1)str=utf_st; else str=utf_b; return str; } public String init(String wo){ String sy=""; // 保存输赢结果 String dncq=getQuan(); //电脑出拳 if(wo.equals(dncq))sy="平局,再来一次"; else if(wo.equals(utf_jd)&&dncq.equals(utf_b) || wo.equals(utf_st)&&dncq.equals(utf_jd)||wo.equals(utf_b)&&dncq.equals(utf_st))sy="您赢了 您先手。"; else sy="电脑赢了 您后手。"; ta2.setText(dncq);// 电脑出拳 lb4.setText(sy); return sy; } } }
false
1,329
5
1,627
5
1,578
4
1,627
5
2,074
5
false
false
false
false
false
true
61881_3
package DesignModel.MediatorPattern; public class Mediator extends AbstractMediator{ @Override /* 为什么动作都交给中介者做: 因为动作需要涉及两类,比如采购多少台电脑需要知道库存的情况,如果让purchase自己决定采购多少电脑,则purchase会 接触到stock,增加了耦合。如果交给中介者做,则purchase和stock之间是解耦的 */ public void execute(String str, Object... objects) { if(str.equals("purchase.buy")){ //采购电脑 this.buyComputer((Integer)objects[0]); }else if(str.equals("sale.sell")){ //销售电脑 this.sellComputer((Integer)objects[0]); }else if(str.equals("sale.offsell")){ //折价销售 this.offSell(); }else if(str.equals("stock.clear")){ //清仓处理 this.clearStock(); } } //采购电脑 private void buyComputer(int number){ int saleStatus = super.sale.getSaleStatus(); if(saleStatus>80){ //销售情况良好 System.out.println("采购IBM电脑:"+number + "台"); super.stock.increase(number); }else{ //销售情况不好 int buyNumber = number/2; //折半采购 System.out.println("采购IBM电脑: "+buyNumber+ "台"); } } //销售电脑 private void sellComputer(int number){ if(super.stock.getStockNumber()<number){ //库存数量不够销售 super.purchase.buyIBMComputer(number); } super.stock.decrease(number); } //折价销售电脑 private void offSell(){ System.out.println("折价销售IBM电脑"+stock.getStockNumber()+"台"); } //清仓处理 private void clearStock(){ //要求清仓销售 super.sale.offSale(); //要求采购人员不要采购 super.purchase.refuseBuyIBM(); } }
Fivehours0/LearnJava
DesignModel/MediatorPattern/Mediator.java
501
//折价销售
line_comment
zh-cn
package DesignModel.MediatorPattern; public class Mediator extends AbstractMediator{ @Override /* 为什么动作都交给中介者做: 因为动作需要涉及两类,比如采购多少台电脑需要知道库存的情况,如果让purchase自己决定采购多少电脑,则purchase会 接触到stock,增加了耦合。如果交给中介者做,则purchase和stock之间是解耦的 */ public void execute(String str, Object... objects) { if(str.equals("purchase.buy")){ //采购电脑 this.buyComputer((Integer)objects[0]); }else if(str.equals("sale.sell")){ //销售电脑 this.sellComputer((Integer)objects[0]); }else if(str.equals("sale.offsell")){ //折价 <SUF> this.offSell(); }else if(str.equals("stock.clear")){ //清仓处理 this.clearStock(); } } //采购电脑 private void buyComputer(int number){ int saleStatus = super.sale.getSaleStatus(); if(saleStatus>80){ //销售情况良好 System.out.println("采购IBM电脑:"+number + "台"); super.stock.increase(number); }else{ //销售情况不好 int buyNumber = number/2; //折半采购 System.out.println("采购IBM电脑: "+buyNumber+ "台"); } } //销售电脑 private void sellComputer(int number){ if(super.stock.getStockNumber()<number){ //库存数量不够销售 super.purchase.buyIBMComputer(number); } super.stock.decrease(number); } //折价销售电脑 private void offSell(){ System.out.println("折价销售IBM电脑"+stock.getStockNumber()+"台"); } //清仓处理 private void clearStock(){ //要求清仓销售 super.sale.offSale(); //要求采购人员不要采购 super.purchase.refuseBuyIBM(); } }
false
426
4
502
6
492
4
501
6
760
13
false
false
false
false
false
true
18781_5
import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class VolatileDemo { public static void main(String[] args) { MyData myData = new MyData(); for(int i = 1; i <= 20; ++i){ new Thread(() -> { for(int j = 1; j <= 1000; ++j){ myData.addPlusPlus(); myData.addAtomic(); } }, String.valueOf(i)).start(); } //等待上方20个线程都执行完 //如果活跃的线程数大于2,主线程就等待 //为什么是2,后台有两个线程,主线程和GC线程 while(Thread.activeCount() > 2){ Thread.yield(); } System.out.println(Thread.currentThread().getName() + "\t get finally number value: " + myData.num); System.out.println(Thread.currentThread().getName() + "\t get finally atomic number value: " + myData.atomicInteger); } //volatile 关键字可以保证可见性 及时通知其他线程主内存的值已经被修改 private static void seeOkByVolatile() { MyData myData = new MyData(); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "\t come in"); try{ TimeUnit.SECONDS.sleep(3); }catch (InterruptedException e){ e.printStackTrace(); } myData.addTo60(); System.out.println(Thread.currentThread().getName() + "\t update number value: " + myData.num); }, "AAA").start(); while(myData.num == 0){} System.out.println("mission is over! Main get number value: " + myData.num); } } class MyData{ volatile int num = 0; public void addTo60(){ this.num = 60; } public void addPlusPlus(){ this.num++; } //解决 i++ 的原子性问题 使用atomicInteger //构造方法默认是0 AtomicInteger atomicInteger = new AtomicInteger(); public void addAtomic(){ //自增 1 atomicInteger.getAndIncrement(); //每次以括号内的数字增加 //atomicInteger.getAndAdd(4); } }
Fiziluuk/JucDemo
src/VolatileDemo.java
539
//构造方法默认是0
line_comment
zh-cn
import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; public class VolatileDemo { public static void main(String[] args) { MyData myData = new MyData(); for(int i = 1; i <= 20; ++i){ new Thread(() -> { for(int j = 1; j <= 1000; ++j){ myData.addPlusPlus(); myData.addAtomic(); } }, String.valueOf(i)).start(); } //等待上方20个线程都执行完 //如果活跃的线程数大于2,主线程就等待 //为什么是2,后台有两个线程,主线程和GC线程 while(Thread.activeCount() > 2){ Thread.yield(); } System.out.println(Thread.currentThread().getName() + "\t get finally number value: " + myData.num); System.out.println(Thread.currentThread().getName() + "\t get finally atomic number value: " + myData.atomicInteger); } //volatile 关键字可以保证可见性 及时通知其他线程主内存的值已经被修改 private static void seeOkByVolatile() { MyData myData = new MyData(); new Thread(() -> { System.out.println(Thread.currentThread().getName() + "\t come in"); try{ TimeUnit.SECONDS.sleep(3); }catch (InterruptedException e){ e.printStackTrace(); } myData.addTo60(); System.out.println(Thread.currentThread().getName() + "\t update number value: " + myData.num); }, "AAA").start(); while(myData.num == 0){} System.out.println("mission is over! Main get number value: " + myData.num); } } class MyData{ volatile int num = 0; public void addTo60(){ this.num = 60; } public void addPlusPlus(){ this.num++; } //解决 i++ 的原子性问题 使用atomicInteger //构造 <SUF> AtomicInteger atomicInteger = new AtomicInteger(); public void addAtomic(){ //自增 1 atomicInteger.getAndIncrement(); //每次以括号内的数字增加 //atomicInteger.getAndAdd(4); } }
false
492
6
539
6
581
6
539
6
679
9
false
false
false
false
false
true
16237_4
package DanmakuUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; //已弃用 public class EmotionAnalysis { public static void main(String[] args) { String url = "http://localhost:5000/"; String text = "{\"type\": \"DANMU_MSG\", \"timestamp\": 1684976117, \"time\": \"2023-05-25 08:55:17\", \"uid\": 669823071, \"color\": 16777215, \"dm_type\": 1, \"font_size\": 25, \"content\": \"开心\", \"recommend_score\": 2}"; try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost post = new HttpPost(url); StringEntity params = new StringEntity("text=" + text,"UTF-8"); post.setEntity(params); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); try (CloseableHttpResponse response = client.execute(post)) { String result = EntityUtils.toString(response.getEntity(),"UTF-8"); System.out.println(result); } } catch (Exception e) { e.printStackTrace(); } } public static String emo(String text) { String url = "http://localhost:5000/"; // 创建HttpPost对象 HttpPost post = new HttpPost(url); try (CloseableHttpClient client = HttpClients.createDefault()) { // 设置请求参数 StringEntity params = new StringEntity("text=" + text,"UTF-8"); // System.out.println(text); post.setEntity(params); // 设置请求头 post.setHeader("Content-Type", "application/x-www-form-urlencoded"); try (CloseableHttpResponse response = client.execute(post)) { // 获取响应结果 // String re = EntityUtils.toString(response.getEntity()); // System.out.println(re); return EntityUtils.toString(response.getEntity(),"UTF-8"); // return EntityUtils.toString(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); } return null; } }
Fluchw/Bilibili_Graduation_Design
flink_word/src/main/java/DanmakuUtils/EmotionAnalysis.java
595
// 设置请求参数
line_comment
zh-cn
package DanmakuUtils; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; //已弃用 public class EmotionAnalysis { public static void main(String[] args) { String url = "http://localhost:5000/"; String text = "{\"type\": \"DANMU_MSG\", \"timestamp\": 1684976117, \"time\": \"2023-05-25 08:55:17\", \"uid\": 669823071, \"color\": 16777215, \"dm_type\": 1, \"font_size\": 25, \"content\": \"开心\", \"recommend_score\": 2}"; try (CloseableHttpClient client = HttpClients.createDefault()) { HttpPost post = new HttpPost(url); StringEntity params = new StringEntity("text=" + text,"UTF-8"); post.setEntity(params); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); try (CloseableHttpResponse response = client.execute(post)) { String result = EntityUtils.toString(response.getEntity(),"UTF-8"); System.out.println(result); } } catch (Exception e) { e.printStackTrace(); } } public static String emo(String text) { String url = "http://localhost:5000/"; // 创建HttpPost对象 HttpPost post = new HttpPost(url); try (CloseableHttpClient client = HttpClients.createDefault()) { // 设置 <SUF> StringEntity params = new StringEntity("text=" + text,"UTF-8"); // System.out.println(text); post.setEntity(params); // 设置请求头 post.setHeader("Content-Type", "application/x-www-form-urlencoded"); try (CloseableHttpResponse response = client.execute(post)) { // 获取响应结果 // String re = EntityUtils.toString(response.getEntity()); // System.out.println(re); return EntityUtils.toString(response.getEntity(),"UTF-8"); // return EntityUtils.toString(response.getEntity()); } } catch (Exception e) { e.printStackTrace(); } return null; } }
false
506
4
595
4
620
4
595
4
694
8
false
false
false
false
false
true
33267_6
package com.leetcode_cn.hard; import java.util.Map; import java.util.Stack; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /*********************原子的数量*******************/ /** * 给定一个化学式formula(作为字符串),返回每种原子的数量。 * * 原子总是以一个大写字母开始,接着跟随0个或任意个小写字母,表示原子的名字。 * * 如果数量大于 1,原子后会跟着数字表示原子的数量。如果数量等于 1 则不会跟数字。例如,H2O 和 H2O2 是可行的,但 H1O2 这个表达是不可行的。 * * 两个化学式连在一起是新的化学式。例如 H2O2He3Mg4 也是化学式。 * * 一个括号中的化学式和数字(可选择性添加)也是化学式。例如 (H2O2) 和 (H2O2)3 是化学式。 * * 给定一个化学式,输出所有原子的数量。格式为:第一个(按字典序)原子的名子,跟着它的数量(如果数量大于 * 1),然后是第二个原子的名字(按字典序),跟着它的数量(如果数量大于 1),以此类推。 * * 示例 1: * * 输入: formula = "H2O" 输出: "H2O" 解释: 原子的数量是 {'H': 2, 'O': 1}。 * * 示例 2: * * 输入: formula = "Mg(OH)2" 输出: "H2MgO2" 解释: 原子的数量是 {'H': 2, 'Mg': 1, 'O': 2}。 * * 示例 3: * * 输入: formula = "K4(ON(SO3)2)2" 输出: "K4N2O14S4" 解释: 原子的数量是 {'K': 4, 'N': 2, * 'O': 14, 'S': 4}。 注意: * * 所有原子的第一个字母为大写,剩余字母都是小写。 formula的长度在[1, 1000]之间。 * formula只包含字母、数字和圆括号,并且题目中给定的是合法的化学式。 * * @author ffj * */ public class NumberOfAtoms { int i; public String countOfAtoms(String formula) { StringBuilder ans = new StringBuilder(); i = 0; Map<String, Integer> count = parse(formula); for (String name : count.keySet()) { ans.append(name); int multiplicity = count.get(name); if (multiplicity > 1) ans.append("" + multiplicity); } return new String(ans); } /** * 计数 存储map中 递归 * * @param formula * @return */ public Map<String, Integer> parse(String formula) { int N = formula.length(); Map<String, Integer> count = new TreeMap<String, Integer>(); while (i < N && formula.charAt(i) != ')') { if (formula.charAt(i) == '(') { // 左括号 i++; for (Map.Entry<String, Integer> entry : parse(formula).entrySet()) { // map中没有key 默认值为0 累加 count.put(entry.getKey(), count.getOrDefault(entry.getKey(), 0) + entry.getValue()); } } else { int iStart = i++; while (i < N && Character.isLowerCase(formula.charAt(i))) // 判断是否是小写字母 i++; String name = formula.substring(iStart, i); // 截取元素 iStart = i; while (i < N && Character.isDigit(formula.charAt(i))) // 是否是数字 i++; int multiplicity = iStart < i ? Integer.parseInt(formula.substring(iStart, i)) : 1; count.put(name, count.getOrDefault(name, 0) + multiplicity); } } int iStart = ++i; while (i < N && Character.isDigit(formula.charAt(i))) i++; if (iStart < i) { int multiplicity = Integer.parseInt(formula.substring(iStart, i)); for (String key : count.keySet()) { count.put(key, count.get(key) * multiplicity); } } return count; } /** * stack * * @param formula * @return */ public String countOfAtoms1(String formula) { int N = formula.length(); Stack<Map<String, Integer>> stack = new Stack<Map<String, Integer>>(); stack.push(new TreeMap<String, Integer>()); for (int i = 0; i < N;) { if (formula.charAt(i) == '(') { stack.push(new TreeMap<String, Integer>()); i++; } else if (formula.charAt(i) == ')') { Map<String, Integer> top = stack.pop(); int iStart = ++i, multiplicity = 1; while (i < N && Character.isDigit(formula.charAt(i))) i++; if (i > iStart) multiplicity = Integer.parseInt(formula.substring(iStart, i)); for (String c : top.keySet()) { int v = top.get(c); stack.peek().put(c, stack.peek().getOrDefault(c, 0) + v * multiplicity); } } else { int iStart = i++; while (i < N && Character.isLowerCase(formula.charAt(i))) i++; String name = formula.substring(iStart, i); iStart = i; while (i < N && Character.isDigit(formula.charAt(i))) i++; int multiplicity = i > iStart ? Integer.parseInt(formula.substring(iStart, i)) : 1; stack.peek().put(name, stack.peek().getOrDefault(name, 0) + multiplicity); } } StringBuilder ans = new StringBuilder(); for (String name : stack.peek().keySet()) { ans.append(name); int multiplicity = stack.peek().get(name); if (multiplicity > 1) ans.append("" + multiplicity); } return new String(ans); } /** * 正则匹配 * * @param formula * @return */ public String countOfAtoms2(String formula) { Matcher matcher = Pattern.compile("([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)").matcher(formula); Stack<Map<String, Integer>> stack = new Stack<Map<String, Integer>>(); stack.push(new TreeMap<String, Integer>()); while (matcher.find()) { String match = matcher.group(); if (match.equals("(")) { stack.push(new TreeMap<String, Integer>()); } else if (match.startsWith(")")) { Map<String, Integer> top = stack.pop(); int multiplicity = match.length() > 1 ? Integer.parseInt(match.substring(1, match.length())) : 1; for (String name : top.keySet()) { stack.peek().put(name, stack.peek().getOrDefault(name, 0) + top.get(name) * multiplicity); } } else { int i = 1; while (i < match.length() && Character.isLowerCase(match.charAt(i))) { i++; } String name = match.substring(0, i); int multiplicity = i < match.length() ? Integer.parseInt(match.substring(i, match.length())) : 1; stack.peek().put(name, stack.peek().getOrDefault(name, 0) + multiplicity); } } StringBuilder ans = new StringBuilder(); for (String name : stack.peek().keySet()) { ans.append(name); final int count = stack.peek().get(name); if (count > 1) ans.append(String.valueOf(count)); } return ans.toString(); } }
Folgerjun/leetcode-cn
src/com/leetcode_cn/hard/NumberOfAtoms.java
2,118
// 截取元素
line_comment
zh-cn
package com.leetcode_cn.hard; import java.util.Map; import java.util.Stack; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; /*********************原子的数量*******************/ /** * 给定一个化学式formula(作为字符串),返回每种原子的数量。 * * 原子总是以一个大写字母开始,接着跟随0个或任意个小写字母,表示原子的名字。 * * 如果数量大于 1,原子后会跟着数字表示原子的数量。如果数量等于 1 则不会跟数字。例如,H2O 和 H2O2 是可行的,但 H1O2 这个表达是不可行的。 * * 两个化学式连在一起是新的化学式。例如 H2O2He3Mg4 也是化学式。 * * 一个括号中的化学式和数字(可选择性添加)也是化学式。例如 (H2O2) 和 (H2O2)3 是化学式。 * * 给定一个化学式,输出所有原子的数量。格式为:第一个(按字典序)原子的名子,跟着它的数量(如果数量大于 * 1),然后是第二个原子的名字(按字典序),跟着它的数量(如果数量大于 1),以此类推。 * * 示例 1: * * 输入: formula = "H2O" 输出: "H2O" 解释: 原子的数量是 {'H': 2, 'O': 1}。 * * 示例 2: * * 输入: formula = "Mg(OH)2" 输出: "H2MgO2" 解释: 原子的数量是 {'H': 2, 'Mg': 1, 'O': 2}。 * * 示例 3: * * 输入: formula = "K4(ON(SO3)2)2" 输出: "K4N2O14S4" 解释: 原子的数量是 {'K': 4, 'N': 2, * 'O': 14, 'S': 4}。 注意: * * 所有原子的第一个字母为大写,剩余字母都是小写。 formula的长度在[1, 1000]之间。 * formula只包含字母、数字和圆括号,并且题目中给定的是合法的化学式。 * * @author ffj * */ public class NumberOfAtoms { int i; public String countOfAtoms(String formula) { StringBuilder ans = new StringBuilder(); i = 0; Map<String, Integer> count = parse(formula); for (String name : count.keySet()) { ans.append(name); int multiplicity = count.get(name); if (multiplicity > 1) ans.append("" + multiplicity); } return new String(ans); } /** * 计数 存储map中 递归 * * @param formula * @return */ public Map<String, Integer> parse(String formula) { int N = formula.length(); Map<String, Integer> count = new TreeMap<String, Integer>(); while (i < N && formula.charAt(i) != ')') { if (formula.charAt(i) == '(') { // 左括号 i++; for (Map.Entry<String, Integer> entry : parse(formula).entrySet()) { // map中没有key 默认值为0 累加 count.put(entry.getKey(), count.getOrDefault(entry.getKey(), 0) + entry.getValue()); } } else { int iStart = i++; while (i < N && Character.isLowerCase(formula.charAt(i))) // 判断是否是小写字母 i++; String name = formula.substring(iStart, i); // 截取 <SUF> iStart = i; while (i < N && Character.isDigit(formula.charAt(i))) // 是否是数字 i++; int multiplicity = iStart < i ? Integer.parseInt(formula.substring(iStart, i)) : 1; count.put(name, count.getOrDefault(name, 0) + multiplicity); } } int iStart = ++i; while (i < N && Character.isDigit(formula.charAt(i))) i++; if (iStart < i) { int multiplicity = Integer.parseInt(formula.substring(iStart, i)); for (String key : count.keySet()) { count.put(key, count.get(key) * multiplicity); } } return count; } /** * stack * * @param formula * @return */ public String countOfAtoms1(String formula) { int N = formula.length(); Stack<Map<String, Integer>> stack = new Stack<Map<String, Integer>>(); stack.push(new TreeMap<String, Integer>()); for (int i = 0; i < N;) { if (formula.charAt(i) == '(') { stack.push(new TreeMap<String, Integer>()); i++; } else if (formula.charAt(i) == ')') { Map<String, Integer> top = stack.pop(); int iStart = ++i, multiplicity = 1; while (i < N && Character.isDigit(formula.charAt(i))) i++; if (i > iStart) multiplicity = Integer.parseInt(formula.substring(iStart, i)); for (String c : top.keySet()) { int v = top.get(c); stack.peek().put(c, stack.peek().getOrDefault(c, 0) + v * multiplicity); } } else { int iStart = i++; while (i < N && Character.isLowerCase(formula.charAt(i))) i++; String name = formula.substring(iStart, i); iStart = i; while (i < N && Character.isDigit(formula.charAt(i))) i++; int multiplicity = i > iStart ? Integer.parseInt(formula.substring(iStart, i)) : 1; stack.peek().put(name, stack.peek().getOrDefault(name, 0) + multiplicity); } } StringBuilder ans = new StringBuilder(); for (String name : stack.peek().keySet()) { ans.append(name); int multiplicity = stack.peek().get(name); if (multiplicity > 1) ans.append("" + multiplicity); } return new String(ans); } /** * 正则匹配 * * @param formula * @return */ public String countOfAtoms2(String formula) { Matcher matcher = Pattern.compile("([A-Z][a-z]*)(\\d*)|(\\()|(\\))(\\d*)").matcher(formula); Stack<Map<String, Integer>> stack = new Stack<Map<String, Integer>>(); stack.push(new TreeMap<String, Integer>()); while (matcher.find()) { String match = matcher.group(); if (match.equals("(")) { stack.push(new TreeMap<String, Integer>()); } else if (match.startsWith(")")) { Map<String, Integer> top = stack.pop(); int multiplicity = match.length() > 1 ? Integer.parseInt(match.substring(1, match.length())) : 1; for (String name : top.keySet()) { stack.peek().put(name, stack.peek().getOrDefault(name, 0) + top.get(name) * multiplicity); } } else { int i = 1; while (i < match.length() && Character.isLowerCase(match.charAt(i))) { i++; } String name = match.substring(0, i); int multiplicity = i < match.length() ? Integer.parseInt(match.substring(i, match.length())) : 1; stack.peek().put(name, stack.peek().getOrDefault(name, 0) + multiplicity); } } StringBuilder ans = new StringBuilder(); for (String name : stack.peek().keySet()) { ans.append(name); final int count = stack.peek().get(name); if (count > 1) ans.append(String.valueOf(count)); } return ans.toString(); } }
false
1,783
5
2,118
5
2,061
4
2,118
5
2,687
8
false
false
false
false
false
true
18891_14
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /* 游戏“地图”为7×7矩阵,实际代码中“地图”存储在in[49]的数组中 如下图 7×7矩阵示例,单数号的DotCom垂直分布 1 2 3 4 5 6 7 a 1 2 3 4 5 6 7 b 8 9 10 11 12 13 14 c 15 16 17 18 19 20 21 d e f g 首先在0~49中随机一个数作为起点,DotCom编号为单数时,location每次加7,达到垂直效果 */ public class GameHelper{ private static final String alphabet = "abcdefg"; private int gridLength = 7; private int gridSize = 49; private int[] grid = new int[gridSize]; private int comCount = 0; public String getUserInput(String prompt){ String inputLine = null; System.out.println(prompt + " "); try{ BufferedReader is = new BufferedReader( new InputStreamReader(System.in)); inputLine = is.readLine(); if(inputLine.length() == 0){ return null; } } catch(IOException e){ System.out.println("IOException " + e); } return inputLine.toLowerCase(); } public ArrayList<String> placeDotCom(int comSize){ ArrayList<String> alphaCells = new ArrayList<String>(); String[] alphacoords = new String[comSize]; String temp = null; int[] coords = new int[comSize]; //用来存储随机结果 int attempts = 0; boolean success = false; int location = 0; //目前起点 comCount++; int incr = 1; //水平增量 if((comCount % 2 ) == 1){ //单数号的DotCom垂直分布 incr = gridLength; } while(!success & attempts++ < 200){ location = (int)(Math.random() * gridSize); //在0~49内随机 System.out.println(" try " + location); int x = 0; success = true; while(success && x <comSize){ if(grid[location] == 0){ //随机出来的坐标是否已被使用 coords[x++] = location; //记录坐标 location += incr; if(location >= gridSize){ //当DC垂直时才有可能超出下边界 success = false; } if(x>0 && (location % gridLength) == 0){ //当DC水平时才能超出右边界 success = false; } }else{ System.out.println(" used " + location); success = false; } } } int x = 0; int row = 0; int column = 0; while(x < comSize){ grid[coords[x]] = 1; row = (int)(coords[x] / gridLength); //计算第几行 column = coords[x] % gridLength; //第几列 temp = String.valueOf(alphabet.charAt(column)); //列用avcdefg表示, //此时temp里只有一个字母 alphaCells.add(temp.concat(Integer.toString(row))); //temp后添加数字(行数) x++; System.out.println(" coord " + x + " = " + alphaCells.get(x-1)); } return alphaCells; } }
For-Elyisa/DotComGame
src/GameHelper.java
885
//temp后添加数字(行数)
line_comment
zh-cn
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; /* 游戏“地图”为7×7矩阵,实际代码中“地图”存储在in[49]的数组中 如下图 7×7矩阵示例,单数号的DotCom垂直分布 1 2 3 4 5 6 7 a 1 2 3 4 5 6 7 b 8 9 10 11 12 13 14 c 15 16 17 18 19 20 21 d e f g 首先在0~49中随机一个数作为起点,DotCom编号为单数时,location每次加7,达到垂直效果 */ public class GameHelper{ private static final String alphabet = "abcdefg"; private int gridLength = 7; private int gridSize = 49; private int[] grid = new int[gridSize]; private int comCount = 0; public String getUserInput(String prompt){ String inputLine = null; System.out.println(prompt + " "); try{ BufferedReader is = new BufferedReader( new InputStreamReader(System.in)); inputLine = is.readLine(); if(inputLine.length() == 0){ return null; } } catch(IOException e){ System.out.println("IOException " + e); } return inputLine.toLowerCase(); } public ArrayList<String> placeDotCom(int comSize){ ArrayList<String> alphaCells = new ArrayList<String>(); String[] alphacoords = new String[comSize]; String temp = null; int[] coords = new int[comSize]; //用来存储随机结果 int attempts = 0; boolean success = false; int location = 0; //目前起点 comCount++; int incr = 1; //水平增量 if((comCount % 2 ) == 1){ //单数号的DotCom垂直分布 incr = gridLength; } while(!success & attempts++ < 200){ location = (int)(Math.random() * gridSize); //在0~49内随机 System.out.println(" try " + location); int x = 0; success = true; while(success && x <comSize){ if(grid[location] == 0){ //随机出来的坐标是否已被使用 coords[x++] = location; //记录坐标 location += incr; if(location >= gridSize){ //当DC垂直时才有可能超出下边界 success = false; } if(x>0 && (location % gridLength) == 0){ //当DC水平时才能超出右边界 success = false; } }else{ System.out.println(" used " + location); success = false; } } } int x = 0; int row = 0; int column = 0; while(x < comSize){ grid[coords[x]] = 1; row = (int)(coords[x] / gridLength); //计算第几行 column = coords[x] % gridLength; //第几列 temp = String.valueOf(alphabet.charAt(column)); //列用avcdefg表示, //此时temp里只有一个字母 alphaCells.add(temp.concat(Integer.toString(row))); //te <SUF> x++; System.out.println(" coord " + x + " = " + alphaCells.get(x-1)); } return alphaCells; } }
false
822
9
885
9
931
9
885
9
1,112
11
false
false
false
false
false
true
47129_1
package com.u9porn.utils; import android.text.TextUtils; /** * @author flymegoc * @date 2018/1/28 */ public class StringUtils { /** * \u3000\u3000 首行缩进 * 空格:&#160; * &#8194;半个中文字更准确点, * &#8195;一个中文字但用起来会比中文字宽一点点。 */ public static String subString(String str, int startIndex, int endIndex) { if (TextUtils.isEmpty(str) || startIndex < 0 || endIndex < 0 || startIndex >= str.length() || endIndex - startIndex < 0) { return ""; } if (endIndex > str.length()) { return str.substring(startIndex, str.length()); } return str.substring(startIndex, endIndex); } }
ForLovelj/v9porn
app/src/main/java/com/u9porn/utils/StringUtils.java
226
/** * \u3000\u3000 首行缩进 * 空格:&#160; * &#8194;半个中文字更准确点, * &#8195;一个中文字但用起来会比中文字宽一点点。 */
block_comment
zh-cn
package com.u9porn.utils; import android.text.TextUtils; /** * @author flymegoc * @date 2018/1/28 */ public class StringUtils { /** * \u3 <SUF>*/ public static String subString(String str, int startIndex, int endIndex) { if (TextUtils.isEmpty(str) || startIndex < 0 || endIndex < 0 || startIndex >= str.length() || endIndex - startIndex < 0) { return ""; } if (endIndex > str.length()) { return str.substring(startIndex, str.length()); } return str.substring(startIndex, endIndex); } }
false
198
71
226
73
226
72
226
73
269
95
false
false
false
false
false
true
15726_7
package com.java.whut.domain; public class Sort { /* * 简单排序:冒泡,选择,插入。 */ //O(N^2)最慢 public static void BubbleSort(int[] arr){ for(int i=0;i<arr.length-1;i++){ for(int j=i+1;j<arr.length;j++){ if(arr[i]>arr[j]){ int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } } //O(N^2)比冒泡略块。 public static void SelectSort(int[] arr){ for(int i=0;i<arr.length-1;i++){ int minIndex=i; for(int j=i+1;j<arr.length-1;j++){ if(arr[j]<arr[minIndex]) minIndex=j; } int temp=arr[i]; arr[i]=arr[minIndex]; arr[minIndex]=temp; } } //O(N^2),比冒泡块一半。 public static void InsertSort(int[] arr){ for(int i=1;i<arr.length;i++){ int temp=arr[i]; int flag=i; while(flag>0&&arr[flag-1]>temp){ arr[flag]=arr[flag-1]; flag--; } arr[flag]=temp; } } //高级排序:希尔排序。基于插入排序,步长为1时等同于插入排序。 public static void ShellSort(int[] arr){ int len=arr.length; int index,flag,temp; //h为步长,每次while循环后步长递减直至为1.各步长之间应满足互质。 int h=1; while(h<len/3) h=3*h+1; while(h>0){ for(flag=h;flag<len;flag++){ temp=arr[flag]; index=flag; //while循环找到标志位arr[flag]的位置index while(index-h>=0&&arr[index-h]>=temp){ //如果index减去步长>=0,且步长数组逆序。 arr[index]=arr[index-h]; index=index-h; } //将arr[flag]插入index处 arr[index]=temp; } h=(h-1)/3; } for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } } //快速排序 public static void FastSort(int[] arr,int left,int right){ int flag; if(left<right){ flag=Parttion(arr,left,right); FastSort(arr, left, flag-1); FastSort(arr, flag+1, right); } } private static int Parttion(int[] arr, int left, int right) { while(left<right){ int flag=arr[left]; while(left<right){ while(left<right&&arr[right]>=flag) right--; arr[left]=arr[right]; while(left<right&&arr[left]<=flag) left++; arr[right]=arr[left]; } arr[left]=flag; } return left; } }
ForeverL/Java
Sort.java
902
//如果index减去步长>=0,且步长数组逆序。
line_comment
zh-cn
package com.java.whut.domain; public class Sort { /* * 简单排序:冒泡,选择,插入。 */ //O(N^2)最慢 public static void BubbleSort(int[] arr){ for(int i=0;i<arr.length-1;i++){ for(int j=i+1;j<arr.length;j++){ if(arr[i]>arr[j]){ int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } } } } //O(N^2)比冒泡略块。 public static void SelectSort(int[] arr){ for(int i=0;i<arr.length-1;i++){ int minIndex=i; for(int j=i+1;j<arr.length-1;j++){ if(arr[j]<arr[minIndex]) minIndex=j; } int temp=arr[i]; arr[i]=arr[minIndex]; arr[minIndex]=temp; } } //O(N^2),比冒泡块一半。 public static void InsertSort(int[] arr){ for(int i=1;i<arr.length;i++){ int temp=arr[i]; int flag=i; while(flag>0&&arr[flag-1]>temp){ arr[flag]=arr[flag-1]; flag--; } arr[flag]=temp; } } //高级排序:希尔排序。基于插入排序,步长为1时等同于插入排序。 public static void ShellSort(int[] arr){ int len=arr.length; int index,flag,temp; //h为步长,每次while循环后步长递减直至为1.各步长之间应满足互质。 int h=1; while(h<len/3) h=3*h+1; while(h>0){ for(flag=h;flag<len;flag++){ temp=arr[flag]; index=flag; //while循环找到标志位arr[flag]的位置index while(index-h>=0&&arr[index-h]>=temp){ //如果 <SUF> arr[index]=arr[index-h]; index=index-h; } //将arr[flag]插入index处 arr[index]=temp; } h=(h-1)/3; } for(int i=0;i<len;i++){ System.out.print(arr[i]+" "); } } //快速排序 public static void FastSort(int[] arr,int left,int right){ int flag; if(left<right){ flag=Parttion(arr,left,right); FastSort(arr, left, flag-1); FastSort(arr, flag+1, right); } } private static int Parttion(int[] arr, int left, int right) { while(left<right){ int flag=arr[left]; while(left<right){ while(left<right&&arr[right]>=flag) right--; arr[left]=arr[right]; while(left<right&&arr[left]<=flag) left++; arr[right]=arr[left]; } arr[left]=flag; } return left; } }
false
718
17
902
18
902
17
902
18
1,197
29
false
false
false
false
false
true
64331_10
package com.example.luo_pc.news.fragment; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.luo_pc.news.R; import com.example.luo_pc.news.activity.NewsActivity; import com.example.luo_pc.news.adapter.NewsListAdapter; import com.example.luo_pc.news.bean.NewsBean; import com.example.luo_pc.news.utils.FileUtils; import com.example.luo_pc.news.utils.HttpUtils; import com.example.luo_pc.news.utils.JsonUtils; import com.example.luo_pc.news.utils.Urls; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; /** * Created by luo-pc on 2016/5/14. */ public class NewsListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener { private String keyword; private String TAG = "NewsListFragment"; private ArrayList<NewsBean> newsList = null; private RecyclerView recycle_news; private NewsListAdapter newsListAdapter; private Context context; //private ArrayList<NewsBean> newsList = null; private LinearLayoutManager layoutManager; //在重新创建fragment时加载缓存数据 private int count = 0; //页数 int pageIndex = 0; private SwipeRefreshLayout sr_refresh; public void setKeyword(String keyword) { this.keyword = keyword; if (count != 0) { new DownloadTask().execute(getUrl()); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_news_list, null); context = getContext(); layoutManager = new LinearLayoutManager(context); newsListAdapter = new NewsListAdapter(context); initView(view); newsListAdapter.setOnItemClickListener(onItemClickListener); recycle_news.setLayoutManager(layoutManager); recycle_news.setAdapter(newsListAdapter); sr_refresh.setColorSchemeResources(R.color.primary, R.color.primary_dark, R.color.primary_light, R.color.accent); sr_refresh.setOnRefreshListener(this); recycle_news.addOnScrollListener(onScrollListener); if (context != null) { File cacheFile = FileUtils.getDisCacheDir(context, "NewsBean" + keyword); if (cacheFile.exists()) { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cacheFile)); ArrayList<NewsBean> list = (ArrayList<NewsBean>) ois.readObject(); newsListAdapter.setData(list); Log.i(TAG, list.size() + " "); } catch (Exception e) { e.printStackTrace(); } } } new DownloadTask().execute(getUrl()); return view; } private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() { private int lastVisibleItem; @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); lastVisibleItem = layoutManager.findLastVisibleItemPosition(); } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); //SCROLL_STATE_IDLE //The RecyclerView is not currently scrolling. if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == newsListAdapter.getItemCount() && newsListAdapter.isShowFooter()) { //加载更多新闻 pageIndex += Urls.PAZE_SIZE; new UpdateTask().execute(getUrl()); } } }; //拼接url private String getUrl() { StringBuilder sb = new StringBuilder(); switch (keyword) { //头条 case Urls.TOP_ID: sb.append(Urls.TOP_URL).append(Urls.TOP_ID); break; //NBA case Urls.NBA_ID: sb.append(Urls.COMMON_URL).append(Urls.NBA_ID); break; //汽车 case Urls.CAR_ID: sb.append(Urls.COMMON_URL).append(Urls.CAR_ID); break; //笑话 case Urls.JOKE_ID: sb.append(Urls.COMMON_URL).append(Urls.JOKE_ID); break; default: sb.append(Urls.TOP_URL).append(Urls.TOP_ID); break; } sb.append("/").append(pageIndex).append(Urls.END_URL); return sb.toString(); } private NewsListAdapter.OnItemClickListener onItemClickListener = new NewsListAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent = new Intent(); intent.setClass(getActivity(), NewsActivity.class); intent.putExtra("url", newsList.get(position).getUrl()); startActivity(intent); } }; private void initView(View view) { recycle_news = (RecyclerView) view.findViewById(R.id.recycle_news); sr_refresh = (SwipeRefreshLayout) view.findViewById(R.id.sr_refresh); } @Override public void onRefresh() { //刷新置pageIndex为0获取最新数据 pageIndex = 0; if (newsList != null) { newsList.clear(); } new DownloadTask().execute(getUrl()); // newsListAdapter.notifyDataSetChanged(); } /** * 请求新闻信息 */ class DownloadTask extends AsyncTask<String, Integer, ArrayList<NewsBean>> { private ObjectOutputStream oos; @Override protected ArrayList<NewsBean> doInBackground(String... params) { try { String infoUrl = params[0]; HttpUtils.getJsonString(infoUrl, new HttpUtils.HttpCallbackListener() { @Override public void onFinish(String response) { newsList = JsonUtils.readJsonNewsBean(response, keyword); if (count == 0) { if (context != null) { File cacheFile = FileUtils.getDisCacheDir(context, "NewsBean" + keyword); try { oos = new ObjectOutputStream(new FileOutputStream(cacheFile)); oos.writeObject(newsList); count++; } catch (IOException e) { e.printStackTrace(); } finally { if (oos != null) { try { oos.close(); }catch (IOException e){ e.printStackTrace(); } } } } } } @Override public void onError(Exception e) { e.printStackTrace(); } }); return newsList; } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(ArrayList<NewsBean> newsList) { if (newsList == null) { return; } else { NewsListFragment.this.newsList = newsList; newsListAdapter.setData(newsList); // recycle_news.setLayoutManager(layoutManager); // recycle_news.setAdapter(newsListAdapter); newsListAdapter.notifyDataSetChanged(); } sr_refresh.setRefreshing(false); } } /** * 加载更多 */ class UpdateTask extends AsyncTask<String, Integer, ArrayList<NewsBean>> { private ArrayList<NewsBean> updateNewsList; @Override protected ArrayList<NewsBean> doInBackground(String... params) { try { String infoUrl = params[0]; HttpUtils.getJsonString(infoUrl, new HttpUtils.HttpCallbackListener() { @Override public void onFinish(String response) { updateNewsList = JsonUtils.readJsonNewsBean(response, keyword); } @Override public void onError(Exception e) { e.printStackTrace(); } }); if (updateNewsList.size() <= 0) { newsListAdapter.isShowFooter(false); } for (NewsBean i : updateNewsList) { newsList.add(i); } return updateNewsList; } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(ArrayList<NewsBean> updateNewsList) { if (updateNewsList == null) { Toast.makeText(getContext(), "请求数据失败", Toast.LENGTH_SHORT).show(); } else { // newsListAdapter.isShowFooter(false); newsListAdapter.setData(NewsListFragment.this.newsList); } } } }
ForgetAll/News
app/src/main/java/com/example/luo_pc/news/fragment/NewsListFragment.java
2,201
/** * 请求新闻信息 */
block_comment
zh-cn
package com.example.luo_pc.news.fragment; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.example.luo_pc.news.R; import com.example.luo_pc.news.activity.NewsActivity; import com.example.luo_pc.news.adapter.NewsListAdapter; import com.example.luo_pc.news.bean.NewsBean; import com.example.luo_pc.news.utils.FileUtils; import com.example.luo_pc.news.utils.HttpUtils; import com.example.luo_pc.news.utils.JsonUtils; import com.example.luo_pc.news.utils.Urls; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; /** * Created by luo-pc on 2016/5/14. */ public class NewsListFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener { private String keyword; private String TAG = "NewsListFragment"; private ArrayList<NewsBean> newsList = null; private RecyclerView recycle_news; private NewsListAdapter newsListAdapter; private Context context; //private ArrayList<NewsBean> newsList = null; private LinearLayoutManager layoutManager; //在重新创建fragment时加载缓存数据 private int count = 0; //页数 int pageIndex = 0; private SwipeRefreshLayout sr_refresh; public void setKeyword(String keyword) { this.keyword = keyword; if (count != 0) { new DownloadTask().execute(getUrl()); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_news_list, null); context = getContext(); layoutManager = new LinearLayoutManager(context); newsListAdapter = new NewsListAdapter(context); initView(view); newsListAdapter.setOnItemClickListener(onItemClickListener); recycle_news.setLayoutManager(layoutManager); recycle_news.setAdapter(newsListAdapter); sr_refresh.setColorSchemeResources(R.color.primary, R.color.primary_dark, R.color.primary_light, R.color.accent); sr_refresh.setOnRefreshListener(this); recycle_news.addOnScrollListener(onScrollListener); if (context != null) { File cacheFile = FileUtils.getDisCacheDir(context, "NewsBean" + keyword); if (cacheFile.exists()) { try { ObjectInputStream ois = new ObjectInputStream(new FileInputStream(cacheFile)); ArrayList<NewsBean> list = (ArrayList<NewsBean>) ois.readObject(); newsListAdapter.setData(list); Log.i(TAG, list.size() + " "); } catch (Exception e) { e.printStackTrace(); } } } new DownloadTask().execute(getUrl()); return view; } private RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() { private int lastVisibleItem; @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); lastVisibleItem = layoutManager.findLastVisibleItemPosition(); } @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); //SCROLL_STATE_IDLE //The RecyclerView is not currently scrolling. if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == newsListAdapter.getItemCount() && newsListAdapter.isShowFooter()) { //加载更多新闻 pageIndex += Urls.PAZE_SIZE; new UpdateTask().execute(getUrl()); } } }; //拼接url private String getUrl() { StringBuilder sb = new StringBuilder(); switch (keyword) { //头条 case Urls.TOP_ID: sb.append(Urls.TOP_URL).append(Urls.TOP_ID); break; //NBA case Urls.NBA_ID: sb.append(Urls.COMMON_URL).append(Urls.NBA_ID); break; //汽车 case Urls.CAR_ID: sb.append(Urls.COMMON_URL).append(Urls.CAR_ID); break; //笑话 case Urls.JOKE_ID: sb.append(Urls.COMMON_URL).append(Urls.JOKE_ID); break; default: sb.append(Urls.TOP_URL).append(Urls.TOP_ID); break; } sb.append("/").append(pageIndex).append(Urls.END_URL); return sb.toString(); } private NewsListAdapter.OnItemClickListener onItemClickListener = new NewsListAdapter.OnItemClickListener() { @Override public void onItemClick(View view, int position) { Intent intent = new Intent(); intent.setClass(getActivity(), NewsActivity.class); intent.putExtra("url", newsList.get(position).getUrl()); startActivity(intent); } }; private void initView(View view) { recycle_news = (RecyclerView) view.findViewById(R.id.recycle_news); sr_refresh = (SwipeRefreshLayout) view.findViewById(R.id.sr_refresh); } @Override public void onRefresh() { //刷新置pageIndex为0获取最新数据 pageIndex = 0; if (newsList != null) { newsList.clear(); } new DownloadTask().execute(getUrl()); // newsListAdapter.notifyDataSetChanged(); } /** * 请求新 <SUF>*/ class DownloadTask extends AsyncTask<String, Integer, ArrayList<NewsBean>> { private ObjectOutputStream oos; @Override protected ArrayList<NewsBean> doInBackground(String... params) { try { String infoUrl = params[0]; HttpUtils.getJsonString(infoUrl, new HttpUtils.HttpCallbackListener() { @Override public void onFinish(String response) { newsList = JsonUtils.readJsonNewsBean(response, keyword); if (count == 0) { if (context != null) { File cacheFile = FileUtils.getDisCacheDir(context, "NewsBean" + keyword); try { oos = new ObjectOutputStream(new FileOutputStream(cacheFile)); oos.writeObject(newsList); count++; } catch (IOException e) { e.printStackTrace(); } finally { if (oos != null) { try { oos.close(); }catch (IOException e){ e.printStackTrace(); } } } } } } @Override public void onError(Exception e) { e.printStackTrace(); } }); return newsList; } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(ArrayList<NewsBean> newsList) { if (newsList == null) { return; } else { NewsListFragment.this.newsList = newsList; newsListAdapter.setData(newsList); // recycle_news.setLayoutManager(layoutManager); // recycle_news.setAdapter(newsListAdapter); newsListAdapter.notifyDataSetChanged(); } sr_refresh.setRefreshing(false); } } /** * 加载更多 */ class UpdateTask extends AsyncTask<String, Integer, ArrayList<NewsBean>> { private ArrayList<NewsBean> updateNewsList; @Override protected ArrayList<NewsBean> doInBackground(String... params) { try { String infoUrl = params[0]; HttpUtils.getJsonString(infoUrl, new HttpUtils.HttpCallbackListener() { @Override public void onFinish(String response) { updateNewsList = JsonUtils.readJsonNewsBean(response, keyword); } @Override public void onError(Exception e) { e.printStackTrace(); } }); if (updateNewsList.size() <= 0) { newsListAdapter.isShowFooter(false); } for (NewsBean i : updateNewsList) { newsList.add(i); } return updateNewsList; } catch (Exception e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(ArrayList<NewsBean> updateNewsList) { if (updateNewsList == null) { Toast.makeText(getContext(), "请求数据失败", Toast.LENGTH_SHORT).show(); } else { // newsListAdapter.isShowFooter(false); newsListAdapter.setData(NewsListFragment.this.newsList); } } } }
false
1,838
9
2,201
9
2,353
10
2,201
9
2,708
16
false
false
false
false
false
true
62235_1
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lyl.shortlink.admin.remote.dto.req; import lombok.Data; /** * 回收站恢复功能 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */ @Data public class RecycleBinRecoverReqDTO { /** * 分组标识 */ private String gid; /** * 全部短链接 */ private String fullShortUrl; }
FouforPast/shortlink
admin/src/main/java/com/lyl/shortlink/admin/remote/dto/req/RecycleBinRecoverReqDTO.java
299
/** * 回收站恢复功能 * 公众号:马丁玩编程,回复:加群,添加马哥微信(备注:link)获取项目资料 */
block_comment
zh-cn
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lyl.shortlink.admin.remote.dto.req; import lombok.Data; /** * 回收站 <SUF>*/ @Data public class RecycleBinRecoverReqDTO { /** * 分组标识 */ private String gid; /** * 全部短链接 */ private String fullShortUrl; }
false
268
38
299
45
295
38
299
45
374
62
false
false
false
false
false
true
16454_5
package com.old.drivers.bean; import java.sql.Date; import java.util.ArrayList; /** * �û��� * * @author Xyu * */ public class User { /** * 用户id */ private Long id; /** * 用户名 */ private String name; /** * 密码 */ private String password; /** * 注册时间 */ private Date date; /** * 昵称 */ private String nick; /** * 邮箱 */ private String email; /** * 状态 0:打开,1:关闭 */ private int state; /** * �绰 */ private String phone; /** * 性别(默认男) */ private int sex; /** *职业 */ private String industry; /** * 危险 */ private String weChat; /** * QQ号 */ private String qq; /** * 头像 */ private String headImg; /** * 用户问题列表 */ private ArrayList<Question> questions = new ArrayList<Question>(); /** * 用户回答列表 */ private ArrayList<Answer> answers = new ArrayList<Answer>(); /** * 用户评论列表 */ private ArrayList<Comment> comments = new ArrayList<Comment>(); /** * 用户粉丝列表 */ private ArrayList<User> fans = new ArrayList<User>(); public User() { } /** * @param name * @param password * @param nick * @param email */ public User(String name, String password, String nick, String email) { super(); this.name = name; this.password = password; this.nick = nick; this.email = email; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the date */ public Date getDate() { return date; } /** * @param date * the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the nick */ public String getNick() { return nick; } /** * @param nick * the nick to set */ public void setNick(String nick) { this.nick = nick; } /** * @return the email */ public String getEmail() { return email; } /** * @param email * the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the state */ public int getState() { return state; } /** * @param state * the state to set */ public void setState(int state) { this.state = state; } /** * @return the phone */ public String getPhone() { return phone; } /** * @param phone * the phone to set */ public void setPhone(String phone) { this.phone = phone; } /** * @return the sex */ public int getSex() { return sex; } /** * @param sex * the sex to set */ public void setSex(int sex) { this.sex = sex; } /** * @return the industry */ public String getIndustry() { return industry; } /** * @param industry * the industry to set */ public void setIndustry(String industry) { this.industry = industry; } /** * @return the weChat */ public String getWeChat() { return weChat; } /** * @param weChat * the weChat to set */ public void setWeChat(String weChat) { this.weChat = weChat; } /** * @return the qq */ public String getQq() { return qq; } /** * @param qq * the qq to set */ public void setQq(String qq) { this.qq = qq; } /** * @return the headImg */ public String getHeadImg() { return headImg; } /** * @param headImg * the headImg to set */ public void setHeadImg(String headImg) { this.headImg = headImg; } /** * @return the questions */ public ArrayList<Question> getQuestions() { return questions; } /** * @param questions * the questions to set */ public void setQuestions(ArrayList<Question> questions) { this.questions = questions; } /** * 增加一个问题 * * @param question */ public void addQuestion(Question question) { questions.add(question); } /** * @return the answers */ public ArrayList<Answer> getAnswers() { return answers; } /** * @param answers * the answers to set */ public void setAnswers(ArrayList<Answer> answers) { this.answers = answers; } /** * ��ӻش� * * @param answer */ public void addAnswer(Answer answer) { answers.add(answer); } /** * @return the comments */ public ArrayList<Comment> getComments() { return comments; } /** * @param comments * the comments to set */ public void setComments(ArrayList<Comment> comments) { this.comments = comments; } /** * ������� * * @param comment */ public void addComment(Comment comment) { comments.add(comment); } /** * @return the fans */ public ArrayList<User> getFans() { return fans; } /** * @param fans * the fans to set */ public void setFans(ArrayList<User> fans) { this.fans = fans; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + ", nick=" + nick + ", email=" + email + ", phone=" + phone + ", sex=" + sex + ", industry=" + industry + ", weChat=" + weChat + ", qq=" + qq + ", headImg=" + headImg + ", questions=" + questions + ", answers=" + answers + ", comments=" + comments + ", fans=" + fans + "]"; } }
FourOldDrivers/wenba
src/main/java/com/old/drivers/bean/User.java
1,817
/** * 昵称 */
block_comment
zh-cn
package com.old.drivers.bean; import java.sql.Date; import java.util.ArrayList; /** * �û��� * * @author Xyu * */ public class User { /** * 用户id */ private Long id; /** * 用户名 */ private String name; /** * 密码 */ private String password; /** * 注册时间 */ private Date date; /** * 昵称 <SUF>*/ private String nick; /** * 邮箱 */ private String email; /** * 状态 0:打开,1:关闭 */ private int state; /** * �绰 */ private String phone; /** * 性别(默认男) */ private int sex; /** *职业 */ private String industry; /** * 危险 */ private String weChat; /** * QQ号 */ private String qq; /** * 头像 */ private String headImg; /** * 用户问题列表 */ private ArrayList<Question> questions = new ArrayList<Question>(); /** * 用户回答列表 */ private ArrayList<Answer> answers = new ArrayList<Answer>(); /** * 用户评论列表 */ private ArrayList<Comment> comments = new ArrayList<Comment>(); /** * 用户粉丝列表 */ private ArrayList<User> fans = new ArrayList<User>(); public User() { } /** * @param name * @param password * @param nick * @param email */ public User(String name, String password, String nick, String email) { super(); this.name = name; this.password = password; this.nick = nick; this.email = email; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @return the password */ public String getPassword() { return password; } /** * @param password * the password to set */ public void setPassword(String password) { this.password = password; } /** * @return the date */ public Date getDate() { return date; } /** * @param date * the date to set */ public void setDate(Date date) { this.date = date; } /** * @return the nick */ public String getNick() { return nick; } /** * @param nick * the nick to set */ public void setNick(String nick) { this.nick = nick; } /** * @return the email */ public String getEmail() { return email; } /** * @param email * the email to set */ public void setEmail(String email) { this.email = email; } /** * @return the state */ public int getState() { return state; } /** * @param state * the state to set */ public void setState(int state) { this.state = state; } /** * @return the phone */ public String getPhone() { return phone; } /** * @param phone * the phone to set */ public void setPhone(String phone) { this.phone = phone; } /** * @return the sex */ public int getSex() { return sex; } /** * @param sex * the sex to set */ public void setSex(int sex) { this.sex = sex; } /** * @return the industry */ public String getIndustry() { return industry; } /** * @param industry * the industry to set */ public void setIndustry(String industry) { this.industry = industry; } /** * @return the weChat */ public String getWeChat() { return weChat; } /** * @param weChat * the weChat to set */ public void setWeChat(String weChat) { this.weChat = weChat; } /** * @return the qq */ public String getQq() { return qq; } /** * @param qq * the qq to set */ public void setQq(String qq) { this.qq = qq; } /** * @return the headImg */ public String getHeadImg() { return headImg; } /** * @param headImg * the headImg to set */ public void setHeadImg(String headImg) { this.headImg = headImg; } /** * @return the questions */ public ArrayList<Question> getQuestions() { return questions; } /** * @param questions * the questions to set */ public void setQuestions(ArrayList<Question> questions) { this.questions = questions; } /** * 增加一个问题 * * @param question */ public void addQuestion(Question question) { questions.add(question); } /** * @return the answers */ public ArrayList<Answer> getAnswers() { return answers; } /** * @param answers * the answers to set */ public void setAnswers(ArrayList<Answer> answers) { this.answers = answers; } /** * ��ӻش� * * @param answer */ public void addAnswer(Answer answer) { answers.add(answer); } /** * @return the comments */ public ArrayList<Comment> getComments() { return comments; } /** * @param comments * the comments to set */ public void setComments(ArrayList<Comment> comments) { this.comments = comments; } /** * ������� * * @param comment */ public void addComment(Comment comment) { comments.add(comment); } /** * @return the fans */ public ArrayList<User> getFans() { return fans; } /** * @param fans * the fans to set */ public void setFans(ArrayList<User> fans) { this.fans = fans; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + ", nick=" + nick + ", email=" + email + ", phone=" + phone + ", sex=" + sex + ", industry=" + industry + ", weChat=" + weChat + ", qq=" + qq + ", headImg=" + headImg + ", questions=" + questions + ", answers=" + answers + ", comments=" + comments + ", fans=" + fans + "]"; } }
false
1,562
9
1,816
9
1,904
9
1,816
9
2,155
12
false
false
false
false
false
true
28882_3
package com.piano.moguyun.act; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.piano.moguyun.R; import com.piano.moguyun.bean.SignBean; import com.piano.moguyun.bean.SignManager; import com.piano.moguyun.bean.UserInfoBean; import com.piano.moguyun.bean.UserInfoManager; import com.piano.moguyun.utils.APIContent; import com.piano.moguyun.utils.DataUt; import com.piano.moguyun.utils.IBaseAct; import com.piano.moguyun.utils.LogUtils; import com.piano.moguyun.utils.TimeUtils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * 记录 */ public class RecordAct extends IBaseAct implements View.OnClickListener { private LinearLayout ivBack; private TextView tvTitle; private TextView tvSign;//签到 private TextView tvDaily;//日报 private TextView tvWeekly;//周报 private TextView tvMonthly;//月报 private UserInfoBean userInfoBean; @Override protected void onCreate(Bundle savedInstanceState) { statusBarBgColorId = R.color.color_F4F5F9; super.onCreate(savedInstanceState); setContentView(R.layout.act_record); userInfoBean = new Gson().fromJson(getIntent().getStringExtra("bean"),UserInfoBean.class); initView(); } private void initView() { tvTitle = findViewById(R.id.tvTitle); ivBack = findViewById(R.id.ivBack); tvSign = findViewById(R.id.tvSign); tvDaily = findViewById(R.id.tvDaily); tvWeekly = findViewById(R.id.tvWeekly); tvMonthly = findViewById(R.id.tvMonthly); tvTitle.setText("记录"); ivBack.setOnClickListener(this::onClick); tvSign.setOnClickListener(this::onClick); tvDaily.setOnClickListener(this::onClick); tvWeekly.setOnClickListener(this::onClick); tvMonthly.setOnClickListener(this::onClick); } @Override public void onClick(View v) { Intent intent; switch (v.getId()){ case R.id.ivBack: finish(); break; case R.id.tvSign://签到 intent = new Intent(this,SignRecordAct.class); intent.putExtra("key",userInfoBean.getUserId()); intent.putExtra("type",1); startActivity(intent); break; case R.id.tvDaily://日报 LogUtils.e(TAG,"日报----->"+new Gson().toJson(SignManager.getInstance().getSignBeanList(DataUt.MMKV_DAILY+userInfoBean.getUserId()))); intent = new Intent(this,SignRecordAct.class); intent.putExtra("key",DataUt.MMKV_DAILY+userInfoBean.getUserId()); intent.putExtra("type",2); startActivity(intent); break; case R.id.tvWeekly://周报 int way = Integer.parseInt(TimeUtils.getWay()); String start = TimeUtils.getStr(2, way == 1 ? 6 : way - 2); String end = TimeUtils.getStr(1, way == 1 ? 0 : 8 - way); LogUtils.e("TAG", "start-------->" + start); LogUtils.e("TAG", "end-------->" + end); intent = new Intent(this,SignRecordAct.class); intent.putExtra("key",DataUt.MMKV_WEEKLY+userInfoBean.getUserId()); intent.putExtra("type",3); startActivity(intent); break; case R.id.tvMonthly://月报 intent = new Intent(this,SignRecordAct.class); intent.putExtra("key",DataUt.MMKV_MOON+userInfoBean.getUserId()); intent.putExtra("type",4); startActivity(intent); break; } } }
Fover01/OkMoGuYun
RecordAct.java
1,002
//周报
line_comment
zh-cn
package com.piano.moguyun.act; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.google.gson.Gson; import com.piano.moguyun.R; import com.piano.moguyun.bean.SignBean; import com.piano.moguyun.bean.SignManager; import com.piano.moguyun.bean.UserInfoBean; import com.piano.moguyun.bean.UserInfoManager; import com.piano.moguyun.utils.APIContent; import com.piano.moguyun.utils.DataUt; import com.piano.moguyun.utils.IBaseAct; import com.piano.moguyun.utils.LogUtils; import com.piano.moguyun.utils.TimeUtils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; /** * 记录 */ public class RecordAct extends IBaseAct implements View.OnClickListener { private LinearLayout ivBack; private TextView tvTitle; private TextView tvSign;//签到 private TextView tvDaily;//日报 private TextView tvWeekly;//周报 <SUF> private TextView tvMonthly;//月报 private UserInfoBean userInfoBean; @Override protected void onCreate(Bundle savedInstanceState) { statusBarBgColorId = R.color.color_F4F5F9; super.onCreate(savedInstanceState); setContentView(R.layout.act_record); userInfoBean = new Gson().fromJson(getIntent().getStringExtra("bean"),UserInfoBean.class); initView(); } private void initView() { tvTitle = findViewById(R.id.tvTitle); ivBack = findViewById(R.id.ivBack); tvSign = findViewById(R.id.tvSign); tvDaily = findViewById(R.id.tvDaily); tvWeekly = findViewById(R.id.tvWeekly); tvMonthly = findViewById(R.id.tvMonthly); tvTitle.setText("记录"); ivBack.setOnClickListener(this::onClick); tvSign.setOnClickListener(this::onClick); tvDaily.setOnClickListener(this::onClick); tvWeekly.setOnClickListener(this::onClick); tvMonthly.setOnClickListener(this::onClick); } @Override public void onClick(View v) { Intent intent; switch (v.getId()){ case R.id.ivBack: finish(); break; case R.id.tvSign://签到 intent = new Intent(this,SignRecordAct.class); intent.putExtra("key",userInfoBean.getUserId()); intent.putExtra("type",1); startActivity(intent); break; case R.id.tvDaily://日报 LogUtils.e(TAG,"日报----->"+new Gson().toJson(SignManager.getInstance().getSignBeanList(DataUt.MMKV_DAILY+userInfoBean.getUserId()))); intent = new Intent(this,SignRecordAct.class); intent.putExtra("key",DataUt.MMKV_DAILY+userInfoBean.getUserId()); intent.putExtra("type",2); startActivity(intent); break; case R.id.tvWeekly://周报 int way = Integer.parseInt(TimeUtils.getWay()); String start = TimeUtils.getStr(2, way == 1 ? 6 : way - 2); String end = TimeUtils.getStr(1, way == 1 ? 0 : 8 - way); LogUtils.e("TAG", "start-------->" + start); LogUtils.e("TAG", "end-------->" + end); intent = new Intent(this,SignRecordAct.class); intent.putExtra("key",DataUt.MMKV_WEEKLY+userInfoBean.getUserId()); intent.putExtra("type",3); startActivity(intent); break; case R.id.tvMonthly://月报 intent = new Intent(this,SignRecordAct.class); intent.putExtra("key",DataUt.MMKV_MOON+userInfoBean.getUserId()); intent.putExtra("type",4); startActivity(intent); break; } } }
false
805
4
983
4
1,017
4
983
4
1,169
6
false
false
false
false
false
true
54909_3
题目描述: 1. 给定一个字符串str,返回统计字符串 2. 在给定一个统计字符串,再给定一个整数,返回所代表的的原始字符串上的字符 举例: str = "aaabbadddffc" a_3_b_2_a_1_d_3_f_2_c_1 a_3_b_100 第0个字符为'a' 第50个位'b' 思路: 先生成统计字符串,遍历一次,用StringBuffer来接收。 1. StringBuffer转String方法。 1. 构造方法 new String(StringBuffer) 2. StringBuffer.toString 2. String转StringBuffer 1. 构造方法 new StringBuffer(String) 2.append sb.append(str) 统计的话: 1. 清楚的知道什么时候开始是数字,因为数字可以有很多位,用flag来显示 定义 一个cur表示当前, num出现了多少次 (当前多少,可以是多位的数字), sum总共多少 public class Soultion { public static String getCountString(String str){ if(str == null || str.equals("")){ return ""; } char[] chars = str.toCharArray(); StringBuffer sb = new StringBuffer(); sb.append(chars[0]); int num = 1; for(int i = 1; i < chars.length; i ++){ if(chars[i] == chars[i - 1]){ num ++; continue; }else { //肯定相等了,那么就开始连接了 sb.append('_'); sb.append(num); sb.append('_'); sb.append(chars[i]); num = 1; } } sb.append('_'); sb.append(num); return sb.toString(); } public static char getCharAt(String str, int index){ if(str == null || str.equals("")) return 0; char[] chars = str.toCharArray(); char cur = 0; int num = 0; int sum = 0; boolean flag = true; //碰到_取反, true说明是字符串,false说明是开始数了 //还要考虑出现的数字是多位数的 for(int i = 0; i < str.length(); i ++){ if(chars[i] == '_'){ flag = !flag; }else if(flag){ //说明就是字符了 sum = sum + num; if(sum >= index){ return cur; } cur = chars[i]; num = 0; }else{ //计入计数出现几次 num = num * 10 + chars[i] - '0'; } } //最后还要加一次 return sum + num >= index ? cur : 0; } public static void main(String[] args) { String str1 = getCountString("aaabbbcccddd"); System.out.println(str1); System.out.println(getCharAt(str1, 9)); String str2 = getCountString("abccffeessssggh"); System.out.println(str2); System.out.println(getCharAt(str2, 5)); String str3 = getCountString("abdc"); System.out.println(str3); System.out.println(getCharAt(str3, 3)); } }
Franciswyyy/New-Coder
String/BASIC-08-getCountString.java
805
//说明就是字符了
line_comment
zh-cn
题目描述: 1. 给定一个字符串str,返回统计字符串 2. 在给定一个统计字符串,再给定一个整数,返回所代表的的原始字符串上的字符 举例: str = "aaabbadddffc" a_3_b_2_a_1_d_3_f_2_c_1 a_3_b_100 第0个字符为'a' 第50个位'b' 思路: 先生成统计字符串,遍历一次,用StringBuffer来接收。 1. StringBuffer转String方法。 1. 构造方法 new String(StringBuffer) 2. StringBuffer.toString 2. String转StringBuffer 1. 构造方法 new StringBuffer(String) 2.append sb.append(str) 统计的话: 1. 清楚的知道什么时候开始是数字,因为数字可以有很多位,用flag来显示 定义 一个cur表示当前, num出现了多少次 (当前多少,可以是多位的数字), sum总共多少 public class Soultion { public static String getCountString(String str){ if(str == null || str.equals("")){ return ""; } char[] chars = str.toCharArray(); StringBuffer sb = new StringBuffer(); sb.append(chars[0]); int num = 1; for(int i = 1; i < chars.length; i ++){ if(chars[i] == chars[i - 1]){ num ++; continue; }else { //肯定相等了,那么就开始连接了 sb.append('_'); sb.append(num); sb.append('_'); sb.append(chars[i]); num = 1; } } sb.append('_'); sb.append(num); return sb.toString(); } public static char getCharAt(String str, int index){ if(str == null || str.equals("")) return 0; char[] chars = str.toCharArray(); char cur = 0; int num = 0; int sum = 0; boolean flag = true; //碰到_取反, true说明是字符串,false说明是开始数了 //还要考虑出现的数字是多位数的 for(int i = 0; i < str.length(); i ++){ if(chars[i] == '_'){ flag = !flag; }else if(flag){ //说明 <SUF> sum = sum + num; if(sum >= index){ return cur; } cur = chars[i]; num = 0; }else{ //计入计数出现几次 num = num * 10 + chars[i] - '0'; } } //最后还要加一次 return sum + num >= index ? cur : 0; } public static void main(String[] args) { String str1 = getCountString("aaabbbcccddd"); System.out.println(str1); System.out.println(getCharAt(str1, 9)); String str2 = getCountString("abccffeessssggh"); System.out.println(str2); System.out.println(getCharAt(str2, 5)); String str3 = getCountString("abdc"); System.out.println(str3); System.out.println(getCharAt(str3, 3)); } }
false
719
5
805
5
840
5
805
5
1,024
8
false
false
false
false
false
true
16356_1
package lessons_01.lesson11_synchronized; import org.openjdk.jol.info.ClassLayout; /** * @program: juc_part * @description: * @author: Mr.Ka * @create: 2023-11-13 17:15 **/ public class Demo01 { public static void main(String[] args) { /** * 1. 谈谈你对于Synchronized的锁优化; * 锁升级, 无锁, 偏量锁, 轻量锁: * synchronized是一个重量型锁, 会导致性能下降; * 如何做到在安全的同时又提高性能? 不要一口气上重量锁: * 无锁, 偏向锁, 轻量锁(CAS), 重量级锁(容易导致阻塞); * 锁的升级和演化: * 1. Java5之前只有无锁和重量级锁; 这个是一个操作系统级别的锁;, 锁的竞争激烈的时候性能会下降; * 2. 牵扯到了用户态的内核态的切换; * * 如果一个对象被锁住, 该Java对象的MW 的 LockWord指向monitor的起始地址; * Monitor的Owner字段会存放拥有相关联的对象锁的线程id */ /** * java.lang.Object object internals: * OFFSET SIZE TYPE DESCRIPTION VALUE 001 无锁状态 * 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1) * 4 4 (object header) 00 00 00 00 (0000000,0 00000000 00000000 00000000,) (0) * 8 4 (object header) 80 0e 00 00 (10000000 00001110 00000000 00000000) (3712) * 12 4 (loss due to the next object alignment) * Instance size: 16 bytes * Space losses: 0 bytes internal + 4 bytes external = 4 bytes total */ Object o = new Object(); // 如果调用了hashcode才会生成; System.out.println("o.hashCode() = " + o.hashCode()); System.out.println("Integer.toBinaryString(o.hashCode()) = " + Integer.toBinaryString(o.hashCode())); System.out.println(ClassLayout.parseInstance(o).toPrintable()); } }
FrandKa/JUC
juc_plus/src/main/java/lessons_01/lesson11_synchronized/Demo01.java
684
/** * 1. 谈谈你对于Synchronized的锁优化; * 锁升级, 无锁, 偏量锁, 轻量锁: * synchronized是一个重量型锁, 会导致性能下降; * 如何做到在安全的同时又提高性能? 不要一口气上重量锁: * 无锁, 偏向锁, 轻量锁(CAS), 重量级锁(容易导致阻塞); * 锁的升级和演化: * 1. Java5之前只有无锁和重量级锁; 这个是一个操作系统级别的锁;, 锁的竞争激烈的时候性能会下降; * 2. 牵扯到了用户态的内核态的切换; * * 如果一个对象被锁住, 该Java对象的MW 的 LockWord指向monitor的起始地址; * Monitor的Owner字段会存放拥有相关联的对象锁的线程id */
block_comment
zh-cn
package lessons_01.lesson11_synchronized; import org.openjdk.jol.info.ClassLayout; /** * @program: juc_part * @description: * @author: Mr.Ka * @create: 2023-11-13 17:15 **/ public class Demo01 { public static void main(String[] args) { /** * 1. <SUF>*/ /** * java.lang.Object object internals: * OFFSET SIZE TYPE DESCRIPTION VALUE 001 无锁状态 * 0 4 (object header) 01 00 00 00 (00000001 00000000 00000000 00000000) (1) * 4 4 (object header) 00 00 00 00 (0000000,0 00000000 00000000 00000000,) (0) * 8 4 (object header) 80 0e 00 00 (10000000 00001110 00000000 00000000) (3712) * 12 4 (loss due to the next object alignment) * Instance size: 16 bytes * Space losses: 0 bytes internal + 4 bytes external = 4 bytes total */ Object o = new Object(); // 如果调用了hashcode才会生成; System.out.println("o.hashCode() = " + o.hashCode()); System.out.println("Integer.toBinaryString(o.hashCode()) = " + Integer.toBinaryString(o.hashCode())); System.out.println(ClassLayout.parseInstance(o).toPrintable()); } }
false
645
209
684
226
667
199
684
226
895
387
true
true
true
true
true
false
41750_0
package haidnor.jvm.instruction.stack; import haidnor.jvm.instruction.Instruction; import haidnor.jvm.runtime.Frame; import haidnor.jvm.runtime.StackValue; import haidnor.jvm.core.CodeStream; import lombok.SneakyThrows; /** * DUP2指令是一条Java虚拟机指令,用于复制栈顶两个元素,并将复制的值插入到栈顶之后。 * <p> * DUP2指令有以下几种形式: * <p> * 栈顶元素为A的情况: * <p> * 执行DUP2指令后,栈的状态变为:A(副本)、A。 * 栈顶元素为A和B的情况: * <p> * 执行DUP2指令后,栈的状态变为:A(副本)、B、A、B。 * 需要注意的是,在执行DUP2指令时,操作数栈必须至少有一个或两个元素,具体取决于栈顶元素的数量。如果栈顶元素只有一个,则只会复制该元素一次;如果栈顶元素有两个,则会分别复制两个元素。 * <p> * 在Java虚拟机规范中,DUP2指令的操作码为0x5C,也属于堆栈管理指令家族(Stack Management Instructions)。 */ public class DUP2 extends Instruction { public DUP2(CodeStream codeStream) { super(codeStream); } @Override @SneakyThrows public void execute(Frame frame) { StackValue stackValue1 = frame.pop(); StackValue stackValue2 = frame.pop(); frame.push(stackValue2); frame.push(stackValue1); frame.push(stackValue2); frame.push(stackValue1); } }
FranzHaidnor/haidnorJVM
src/main/java/haidnor/jvm/instruction/stack/DUP2.java
424
/** * DUP2指令是一条Java虚拟机指令,用于复制栈顶两个元素,并将复制的值插入到栈顶之后。 * <p> * DUP2指令有以下几种形式: * <p> * 栈顶元素为A的情况: * <p> * 执行DUP2指令后,栈的状态变为:A(副本)、A。 * 栈顶元素为A和B的情况: * <p> * 执行DUP2指令后,栈的状态变为:A(副本)、B、A、B。 * 需要注意的是,在执行DUP2指令时,操作数栈必须至少有一个或两个元素,具体取决于栈顶元素的数量。如果栈顶元素只有一个,则只会复制该元素一次;如果栈顶元素有两个,则会分别复制两个元素。 * <p> * 在Java虚拟机规范中,DUP2指令的操作码为0x5C,也属于堆栈管理指令家族(Stack Management Instructions)。 */
block_comment
zh-cn
package haidnor.jvm.instruction.stack; import haidnor.jvm.instruction.Instruction; import haidnor.jvm.runtime.Frame; import haidnor.jvm.runtime.StackValue; import haidnor.jvm.core.CodeStream; import lombok.SneakyThrows; /** * DUP <SUF>*/ public class DUP2 extends Instruction { public DUP2(CodeStream codeStream) { super(codeStream); } @Override @SneakyThrows public void execute(Frame frame) { StackValue stackValue1 = frame.pop(); StackValue stackValue2 = frame.pop(); frame.push(stackValue2); frame.push(stackValue1); frame.push(stackValue2); frame.push(stackValue1); } }
false
360
209
424
240
404
218
424
240
602
388
true
true
true
true
true
false
60648_9
package com.jdbc.demo; import com.jdbc.utils.JdbcUtils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; /** * @projectName: JavaWeb_Workspace * @className: JdbcDemo8 * @link: * @author: AaronLi * @description: <br> * 练习 * <br> * &emsp;需求: * &emsp;<ol type="1" start="1"> * <li>通过键盘录入用户名和密码</li> * <li>判断用户是否登录成功</li> * </ol> * @date: 2022/8/5 下午10:32 * @version: JDK17 */ public class JdbcDemo8 { public static void main(String[] args) { //1、键盘录入,接收用户名和密码 Scanner scanner = new Scanner(System.in); System.out.println("请输入用户名:"); String username = scanner.nextLine(); System.out.println("请输入密码:"); String password = scanner.nextLine(); //2、调用方法 boolean flag = new JdbcDemo8().login(username, password); //3、判断结果,输出不同结果 if (flag) { System.out.println("登录成功"); } else { System.out.println("用户名或密码错误!"); } } /** * @date: 2022/8/5 下午10:45 * @description: 登录方法 */ public boolean login(String username, String password) { if (username == null || password == null) { return false; } Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //1、获取Connection连接 conn = JdbcUtils.getConnection(); //2、定义sql String sql = "SELECT* FROM user WHERE username='" + username + "'and password='" + password + "'"; //3、获取sql对象 stmt = conn.createStatement(); //4、执行查询 rs = stmt.executeQuery(sql); //5、判断 return rs.next(); } catch (SQLException e) { throw new RuntimeException(e); } finally { JdbcUtils.close(rs, stmt, conn); } } }
Free-Aaron-Li/JavaWeb
Jdbc/src/com/jdbc/demo/JdbcDemo8.java
552
//5、判断
line_comment
zh-cn
package com.jdbc.demo; import com.jdbc.utils.JdbcUtils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Scanner; /** * @projectName: JavaWeb_Workspace * @className: JdbcDemo8 * @link: * @author: AaronLi * @description: <br> * 练习 * <br> * &emsp;需求: * &emsp;<ol type="1" start="1"> * <li>通过键盘录入用户名和密码</li> * <li>判断用户是否登录成功</li> * </ol> * @date: 2022/8/5 下午10:32 * @version: JDK17 */ public class JdbcDemo8 { public static void main(String[] args) { //1、键盘录入,接收用户名和密码 Scanner scanner = new Scanner(System.in); System.out.println("请输入用户名:"); String username = scanner.nextLine(); System.out.println("请输入密码:"); String password = scanner.nextLine(); //2、调用方法 boolean flag = new JdbcDemo8().login(username, password); //3、判断结果,输出不同结果 if (flag) { System.out.println("登录成功"); } else { System.out.println("用户名或密码错误!"); } } /** * @date: 2022/8/5 下午10:45 * @description: 登录方法 */ public boolean login(String username, String password) { if (username == null || password == null) { return false; } Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //1、获取Connection连接 conn = JdbcUtils.getConnection(); //2、定义sql String sql = "SELECT* FROM user WHERE username='" + username + "'and password='" + password + "'"; //3、获取sql对象 stmt = conn.createStatement(); //4、执行查询 rs = stmt.executeQuery(sql); //5、 <SUF> return rs.next(); } catch (SQLException e) { throw new RuntimeException(e); } finally { JdbcUtils.close(rs, stmt, conn); } } }
false
502
4
552
4
588
4
552
4
700
5
false
false
false
false
false
true
49850_0
package Facade; //厨房子系统接口 public interface Kitchen { //制作 void Cooking(); }
Freg-x/Design_Pattern2019
src/Restaurant/src/Facade/Kitchen.java
31
//厨房子系统接口
line_comment
zh-cn
package Facade; //厨房 <SUF> public interface Kitchen { //制作 void Cooking(); }
false
23
5
31
7
27
5
31
7
37
10
false
false
false
false
false
true
55304_3
package com.leetcode.Structure; import java.util.HashMap; import java.util.HashSet; /** * @Author: zkcheng * @Date: 2021/07/04/19:14 * @Description: */ public class HashTables { // Two sum public int[] twoSum(int[] nums, int target){ HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums[i]; i++) { if(map.containsKey(target - nums[i])){ return new int[]{map.get(target - nums[i]), i}; }else { map.put(nums[i], i); } } return null; } //返回最长连续序列长度 public int longestConsecutive(int[] nums) { HashSet<Integer> hashSet = new HashSet<>(); for (int i = 0; i < nums.length; i++) { hashSet.add(nums[i]); } int longestStreak = 0; for (int num : hashSet) { if(!hashSet.contains(num - 1)){ //保证 num 是最小的那位 int curNum = num; int curSteak = 0; while (hashSet.contains(curNum++)){ // curNum++; curSteak++; } longestStreak = Math.max(longestStreak, curSteak); } } return longestStreak; } public static void main(String[] args){ HashTables hashTables = new HashTables(); System.out.println(hashTables.longestConsecutive(new int[]{100,4,200,1,3,2})); } }
JuneFire/pro-interview
interview-leetcode/src/main/java/com/leetcode/Structure/HashTables.java
405
//保证 num 是最小的那位
line_comment
zh-cn
package com.leetcode.Structure; import java.util.HashMap; import java.util.HashSet; /** * @Author: zkcheng * @Date: 2021/07/04/19:14 * @Description: */ public class HashTables { // Two sum public int[] twoSum(int[] nums, int target){ HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums[i]; i++) { if(map.containsKey(target - nums[i])){ return new int[]{map.get(target - nums[i]), i}; }else { map.put(nums[i], i); } } return null; } //返回最长连续序列长度 public int longestConsecutive(int[] nums) { HashSet<Integer> hashSet = new HashSet<>(); for (int i = 0; i < nums.length; i++) { hashSet.add(nums[i]); } int longestStreak = 0; for (int num : hashSet) { if(!hashSet.contains(num - 1)){ //保证 <SUF> int curNum = num; int curSteak = 0; while (hashSet.contains(curNum++)){ // curNum++; curSteak++; } longestStreak = Math.max(longestStreak, curSteak); } } return longestStreak; } public static void main(String[] args){ HashTables hashTables = new HashTables(); System.out.println(hashTables.longestConsecutive(new int[]{100,4,200,1,3,2})); } }
false
359
7
405
8
431
7
405
8
483
13
false
false
false
false
false
true
43606_2
package olympic.main.pressconference; import olympic.main.person.PersonFactory; import olympic.main.person.athlete.track.TrackAthlete; import olympic.main.person.interview.Interviewee; import olympic.main.person.interview.Interviewer; import olympic.main.person.interview.Listener; import olympic.main.person.interview.Stopper; import olympic.main.pressconference.questionstrategy.PressConferenceStrategy; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * 安排一场新闻发布会 * 使用的设计模式: * 1. Facade * 2. Strategy */ public abstract class PressConferenceMaker { /** * 安排一场新闻发布会对外暴露的API * 使用了Facade模式 * * @param interviewee 被采访者 * @param interviewers 采访者 * @param audience 听众 * @param maxQuestionNum 最大问题数 */ public static void makePressConference(Interviewee interviewee, List<Interviewer> interviewers, List<? extends Listener> audience, int maxQuestionNum) { System.out.println("classname: (PressConferenceMaker) method: (makePressConference) action: (举办一场新闻发布会,使用了Facade模式、Observer模式与Strategy模式)"); // 添加采访者、听众 for (Interviewer interviewer : interviewers) { interviewee.addListener(interviewer); } for (Listener listener : audience) { interviewee.addListener(listener); } List<String> speech = interviewee.makeSpeech(); // 发言人发表讲话 for (String talk : speech) { System.out.println(interviewee.getName() + "发表" + talk); interviewee.notifyListeners(talk); } // 创建Stopper作为Observer Stopper stopper = new Stopper("宅尘浩", "中国", maxQuestionNum); interviewee.addListener(stopper); // 随机抽取记者轮流提问,直到达到提问数量上限,或者记者无问题可问 int askedNum = 0; while (stopper.shouldContinue() && !notesEmpty(interviewers)) { Random random = new Random(); int randomIndex = random.nextInt(interviewers.size()); while (!interviewers.get(randomIndex).haveQuestion()) { randomIndex = random.nextInt(interviewers.size()); } Interviewer currentInterviewer = interviewers.get(randomIndex); String currentQuestion = currentInterviewer.ask(); currentQuestion = "记者" + currentInterviewer.getName() + "对" + currentQuestion + "发起提问(问题" + (askedNum + 1) + ")"; System.out.println(currentQuestion); String currentAnswer = interviewee.answerQuestion(currentQuestion); interviewee.notifyListeners(interviewee.getName() + "对问题" + (askedNum + 1) + "的回答"); System.out.println(interviewee.getName() + "回答问题:" + currentAnswer); askedNum++; } } /** * 判断采访者笔记是否为空(无问题可问) * * @param interviewers 采访者列表 * @return 采访笔记是否为空 */ private static boolean notesEmpty(List<Interviewer> interviewers) { for (Interviewer interviewer : interviewers) { if (interviewer.haveQuestion()) { return false; } } return true; } }
JunjieLl/Design-Pattern
src/main/java/olympic/main/pressconference/PressConferenceMaker.java
893
// 添加采访者、听众
line_comment
zh-cn
package olympic.main.pressconference; import olympic.main.person.PersonFactory; import olympic.main.person.athlete.track.TrackAthlete; import olympic.main.person.interview.Interviewee; import olympic.main.person.interview.Interviewer; import olympic.main.person.interview.Listener; import olympic.main.person.interview.Stopper; import olympic.main.pressconference.questionstrategy.PressConferenceStrategy; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * 安排一场新闻发布会 * 使用的设计模式: * 1. Facade * 2. Strategy */ public abstract class PressConferenceMaker { /** * 安排一场新闻发布会对外暴露的API * 使用了Facade模式 * * @param interviewee 被采访者 * @param interviewers 采访者 * @param audience 听众 * @param maxQuestionNum 最大问题数 */ public static void makePressConference(Interviewee interviewee, List<Interviewer> interviewers, List<? extends Listener> audience, int maxQuestionNum) { System.out.println("classname: (PressConferenceMaker) method: (makePressConference) action: (举办一场新闻发布会,使用了Facade模式、Observer模式与Strategy模式)"); // 添加 <SUF> for (Interviewer interviewer : interviewers) { interviewee.addListener(interviewer); } for (Listener listener : audience) { interviewee.addListener(listener); } List<String> speech = interviewee.makeSpeech(); // 发言人发表讲话 for (String talk : speech) { System.out.println(interviewee.getName() + "发表" + talk); interviewee.notifyListeners(talk); } // 创建Stopper作为Observer Stopper stopper = new Stopper("宅尘浩", "中国", maxQuestionNum); interviewee.addListener(stopper); // 随机抽取记者轮流提问,直到达到提问数量上限,或者记者无问题可问 int askedNum = 0; while (stopper.shouldContinue() && !notesEmpty(interviewers)) { Random random = new Random(); int randomIndex = random.nextInt(interviewers.size()); while (!interviewers.get(randomIndex).haveQuestion()) { randomIndex = random.nextInt(interviewers.size()); } Interviewer currentInterviewer = interviewers.get(randomIndex); String currentQuestion = currentInterviewer.ask(); currentQuestion = "记者" + currentInterviewer.getName() + "对" + currentQuestion + "发起提问(问题" + (askedNum + 1) + ")"; System.out.println(currentQuestion); String currentAnswer = interviewee.answerQuestion(currentQuestion); interviewee.notifyListeners(interviewee.getName() + "对问题" + (askedNum + 1) + "的回答"); System.out.println(interviewee.getName() + "回答问题:" + currentAnswer); askedNum++; } } /** * 判断采访者笔记是否为空(无问题可问) * * @param interviewers 采访者列表 * @return 采访笔记是否为空 */ private static boolean notesEmpty(List<Interviewer> interviewers) { for (Interviewer interviewer : interviewers) { if (interviewer.haveQuestion()) { return false; } } return true; } }
false
743
6
893
8
824
7
893
8
1,071
18
false
false
false
false
false
true
62543_1
package com.example.findfood.mine; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.example.findfood.R; import com.example.findfood.app.MainActivity; //我的消费记录 public class MineRecordActivity extends AppCompatActivity { private ImageView rb_backew; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_mine_record ); rb_backew=(ImageView)findViewById( R.id.rb_backew); rb_backew.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { showExitDialog(); Log.e( "返回","///////////////////////////////////// -------------点击返回按钮" ); } } ); } // 提示框信息 private void showExitDialog() { new AlertDialog.Builder( this ) .setIcon( R.drawable.logo ) .setTitle( "提示信息" ) .setMessage( "还没有消费记录呢,请阁下消费之后再来查看吧!" ) .setPositiveButton( "我知道了", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getApplicationContext(), "进入商品页面", Toast.LENGTH_SHORT).show(); Intent intent=new Intent(MineRecordActivity.this,MainActivity.class); startActivity(intent); } } ) .setNegativeButton( "取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getApplicationContext(), "取消", Toast.LENGTH_SHORT).show(); } } ) .show(); } }
JunqiFu/Android-FindFood
FindFood/项目源码/FindFood/app/src/main/java/com/example/findfood/mine/MineRecordActivity.java
452
///////////////////////////////////// -------------点击返回按钮" );
line_comment
zh-cn
package com.example.findfood.mine; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.Toast; import com.example.findfood.R; import com.example.findfood.app.MainActivity; //我的消费记录 public class MineRecordActivity extends AppCompatActivity { private ImageView rb_backew; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate( savedInstanceState ); setContentView( R.layout.activity_mine_record ); rb_backew=(ImageView)findViewById( R.id.rb_backew); rb_backew.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { showExitDialog(); Log.e( "返回","///////////////////////////////////// -- <SUF> } } ); } // 提示框信息 private void showExitDialog() { new AlertDialog.Builder( this ) .setIcon( R.drawable.logo ) .setTitle( "提示信息" ) .setMessage( "还没有消费记录呢,请阁下消费之后再来查看吧!" ) .setPositiveButton( "我知道了", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getApplicationContext(), "进入商品页面", Toast.LENGTH_SHORT).show(); Intent intent=new Intent(MineRecordActivity.this,MainActivity.class); startActivity(intent); } } ) .setNegativeButton( "取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { Toast.makeText(getApplicationContext(), "取消", Toast.LENGTH_SHORT).show(); } } ) .show(); } }
false
365
8
452
8
482
9
452
8
578
16
false
false
false
false
false
true
49989_3
package com.lj.Time.page.plan; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import com.lj.Time.R; import com.lj.Time.contract.plan.IEditPlanContract; import com.lj.Time.db.ClockPlan; import com.lj.Time.db.RationPlan; import com.lj.Time.model.plan.EditPlanDataEntity; import com.lj.Time.page.base.BaseActivity; import com.lj.Time.presenter.plan.EditPlanPresenterImpl; import com.lj.Time.util.DateTimePickerHelper; import com.lj.Time.util.DateUtils; import java.text.DecimalFormat; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * 修改计划界面 */ public class EditPlanActivity extends BaseActivity implements IEditPlanContract.View { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.view_toolbar_divider) View viewToolbarDivider; @BindView(R.id.et_name) EditText etName; @BindView(R.id.et_description) EditText etDescription; @BindView(R.id.fl_plan_description) FrameLayout flPlanDescription; @BindView(R.id.et_finish_date) EditText etFinishDate; @BindView(R.id.et_target) EditText etTarget; @BindView(R.id.et_current) EditText etCurrent; @BindView(R.id.et_unit) EditText etUnit; @BindView(R.id.ll_plan_switch) LinearLayout llPlanSwitch; @BindView(R.id.et_period_type) EditText etPeriodType; @BindView(R.id.et_period_target) EditText etPeriodTarget; @BindView(R.id.ll_period) LinearLayout llPeriod; /** * 计划ID */ private long planId; /** * 0-定量计划 * 1-打卡计划 */ private int planType; private IEditPlanContract.Presenter presenter; private DecimalFormat decimalFormat = new DecimalFormat("0.00"); /** * 短期计划类型 * 0-天 * 1-周 * 2-月 */ private int periodType = 0; private RationPlan rationPlan; public static void open(Context context, long planId, int planType) { Intent intent = new Intent(context, EditPlanActivity.class); intent.putExtra(INTENT_ARG_01, planId); intent.putExtra(INTENT_ARG_02, planType); context.startActivity(intent); } @Override protected int getLayoutResId() { return R.layout.activity_edit_plan; } @Override protected void initView(@Nullable Bundle savedInstanceState) { ButterKnife.bind(this); initToolbar(toolbar, "修改计划", true); planId = getIntent().getLongExtra(INTENT_ARG_01, -1L); planType = getIntent().getIntExtra(INTENT_ARG_02, 1); presenter = new EditPlanPresenterImpl(this, this); presenter.initDate(planId, planType); } @OnClick(R.id.btn_edit) public void onEdit() { if (planType == 0 && !checkRationPlan()) { return; } if (planType == 1 && !checkClockPlan()) { return; } EditPlanDataEntity editData = new EditPlanDataEntity(); editData.setName(etName.getText().toString()); editData.setFinishDate(etFinishDate.getText().toString()); editData.setDescription(etDescription.getText().toString()); editData.setTarget(planType == 0 ? Double.valueOf(etTarget.getText().toString()) : 0); editData.setCurrent(planType == 0 ? Double.valueOf(etCurrent.getText().toString()) : 0); editData.setUnit(etUnit.getText().toString()); boolean periodIsOpen = llPeriod.getVisibility() == View.VISIBLE; editData.setPeriodIsOpen(periodIsOpen); if (periodIsOpen) { editData.setPeriodTarget(Double.valueOf(etPeriodTarget.getText().toString())); switch(etPeriodType.getText().toString()){ case "天": editData.setPeriodPlanType(0); break; case "周": editData.setPeriodPlanType(1); break; case "月": editData.setPeriodPlanType(3); break; } } presenter.updatePlan(editData); } private boolean checkRationPlan() { if (TextUtils.isEmpty(etName.getText().toString())) { showNoActionSnackbar("请输入计划名"); return false; } if (TextUtils.isEmpty(etFinishDate.getText().toString())) { showNoActionSnackbar("请输入结束时间"); return false; } if (TextUtils.isEmpty(etTarget.getText().toString())) { showNoActionSnackbar("请输入目标值"); return false; } if (TextUtils.isEmpty(etCurrent.getText().toString())) { showNoActionSnackbar("请输入当前值"); return false; } if (TextUtils.isEmpty(etUnit.getText().toString())) { showNoActionSnackbar("请输入单位"); return false; } if (llPeriod.getVisibility() == View.VISIBLE) { if (TextUtils.isEmpty(etPeriodType.getText().toString())) { showNoActionSnackbar("请选择短期计划类型"); return false; } if (TextUtils.isEmpty(etPeriodTarget.getText().toString())) { showNoActionSnackbar("请输入短期计划目标"); return false; } } return true; } private boolean checkClockPlan() { if (TextUtils.isEmpty(etName.getText().toString())) { showNoActionSnackbar("请输入计划名"); return false; } return true; } @OnClick(R.id.et_finish_date) public void onFinishDateClick() { DateTimePickerHelper.showDateDialog(this, "yyyy-MM-dd", TextUtils.isEmpty(etFinishDate.getText().toString()) ? "" : etFinishDate.getText().toString(), etFinishDate::setText); } @OnClick(R.id.et_period_type) public void onPeriodTypeClick(View view) { PopupMenu popupMenu = new PopupMenu(this, view); popupMenu.getMenu().add(0, 0, 0, "天"); popupMenu.getMenu().add(0, 1, 0, "周"); popupMenu.getMenu().add(0, 2, 0, "月"); popupMenu.setOnMenuItemClickListener(item -> { etPeriodType.setText(item.getTitle()); this.periodType = item.getItemId(); updatePeriodTarget(); return true; }); popupMenu.show(); } @OnClick(R.id.img_delete_period) public void onDeletePeriodPlanClick() { new AlertDialog.Builder(this) .setTitle("真的要删除短期计划?") .setNegativeButton("不", null) .setPositiveButton("对", (DialogInterface dialog, int which) -> { showRoundProgressDialog(); presenter.deletePeriod(); }) .create() .show(); } private void updatePeriodTarget() { if (rationPlan == null) return; double target = !TextUtils.isEmpty(etTarget.getText().toString()) ? Double.valueOf(etTarget.getText().toString()) : rationPlan.getTarget(); double current = !TextUtils.isEmpty(etCurrent.getText().toString()) ? Double.valueOf(etCurrent.getText().toString()) : rationPlan.getCurrent(); String startDate = rationPlan != null ? rationPlan.getStartDate() : ""; String finishDate = !TextUtils.isEmpty(etFinishDate.getText().toString()) ? etFinishDate.getText().toString() : rationPlan.getFinishDate(); if (target != 0 && !TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(finishDate)) { switch (periodType) { case 0: { //天 double value = (target - current) / (DateUtils.getDaySpace("yyyy-MM-dd", startDate, finishDate) + 1); etPeriodTarget.setText(decimalFormat.format(value)); break; } case 1: { //周 double value = (target - current) / (DateUtils.getWeekSpace("yyyy-MM-dd", startDate, finishDate) + 1); etPeriodTarget.setText(decimalFormat.format(value)); break; } case 2: { //月 double value = (target - current) / (DateUtils.getMonthSpace("yyyy-MM-dd", startDate, finishDate) + 1); etPeriodTarget.setText(decimalFormat.format(value)); break; } } } } @Override public void showRationPlan() { flPlanDescription.setVisibility(View.GONE); llPlanSwitch.setVisibility(View.VISIBLE); } @Override public void showClockPlan() { flPlanDescription.setVisibility(View.VISIBLE); llPlanSwitch.setVisibility(View.GONE); } @Override public void fillRationPlanData(RationPlan plan) { this.rationPlan = plan; etName.setText(plan.getName()); etFinishDate.setText(plan.getFinishDate()); etTarget.setText(String.valueOf(plan.getTarget())); etCurrent.setText(String.valueOf(plan.getCurrent())); etUnit.setText(plan.getUnit()); if (plan.getPeriodIsOpen()) { llPeriod.setVisibility(View.VISIBLE); int periodType = plan.getPeriodPlanType(); switch (periodType) { case 0: etPeriodType.setText("日"); break; case 1: etPeriodType.setText("周"); break; case 2: etPeriodType.setText("月"); break; } etPeriodTarget.setText(String.valueOf(plan.getPeriodPlanTarget())); } else { llPeriod.setVisibility(View.GONE); } closeRoundProgressDialog(); } @Override public void fillClockPlanData(ClockPlan plan) { etName.setText(plan.getName()); etDescription.setText(plan.getDescription()); closeRoundProgressDialog(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.edit_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.delete: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("注意了"); builder.setMessage("真的要删除这个计划吗???"); builder.setNegativeButton("不不不", null); builder.setPositiveButton("删吧", (DialogInterface dialog, int which) -> presenter.deletePlan()); builder.create().show(); break; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { presenter.onDestroy(); super.onDestroy(); } }
JusperLee/Time
app/src/main/java/com/lj/Time/page/plan/EditPlanActivity.java
2,766
/** * 短期计划类型 * 0-天 * 1-周 * 2-月 */
block_comment
zh-cn
package com.lj.Time.page.plan; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AlertDialog; import android.support.v7.widget.PopupMenu; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import com.lj.Time.R; import com.lj.Time.contract.plan.IEditPlanContract; import com.lj.Time.db.ClockPlan; import com.lj.Time.db.RationPlan; import com.lj.Time.model.plan.EditPlanDataEntity; import com.lj.Time.page.base.BaseActivity; import com.lj.Time.presenter.plan.EditPlanPresenterImpl; import com.lj.Time.util.DateTimePickerHelper; import com.lj.Time.util.DateUtils; import java.text.DecimalFormat; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * 修改计划界面 */ public class EditPlanActivity extends BaseActivity implements IEditPlanContract.View { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.view_toolbar_divider) View viewToolbarDivider; @BindView(R.id.et_name) EditText etName; @BindView(R.id.et_description) EditText etDescription; @BindView(R.id.fl_plan_description) FrameLayout flPlanDescription; @BindView(R.id.et_finish_date) EditText etFinishDate; @BindView(R.id.et_target) EditText etTarget; @BindView(R.id.et_current) EditText etCurrent; @BindView(R.id.et_unit) EditText etUnit; @BindView(R.id.ll_plan_switch) LinearLayout llPlanSwitch; @BindView(R.id.et_period_type) EditText etPeriodType; @BindView(R.id.et_period_target) EditText etPeriodTarget; @BindView(R.id.ll_period) LinearLayout llPeriod; /** * 计划ID */ private long planId; /** * 0-定量计划 * 1-打卡计划 */ private int planType; private IEditPlanContract.Presenter presenter; private DecimalFormat decimalFormat = new DecimalFormat("0.00"); /** * 短期计 <SUF>*/ private int periodType = 0; private RationPlan rationPlan; public static void open(Context context, long planId, int planType) { Intent intent = new Intent(context, EditPlanActivity.class); intent.putExtra(INTENT_ARG_01, planId); intent.putExtra(INTENT_ARG_02, planType); context.startActivity(intent); } @Override protected int getLayoutResId() { return R.layout.activity_edit_plan; } @Override protected void initView(@Nullable Bundle savedInstanceState) { ButterKnife.bind(this); initToolbar(toolbar, "修改计划", true); planId = getIntent().getLongExtra(INTENT_ARG_01, -1L); planType = getIntent().getIntExtra(INTENT_ARG_02, 1); presenter = new EditPlanPresenterImpl(this, this); presenter.initDate(planId, planType); } @OnClick(R.id.btn_edit) public void onEdit() { if (planType == 0 && !checkRationPlan()) { return; } if (planType == 1 && !checkClockPlan()) { return; } EditPlanDataEntity editData = new EditPlanDataEntity(); editData.setName(etName.getText().toString()); editData.setFinishDate(etFinishDate.getText().toString()); editData.setDescription(etDescription.getText().toString()); editData.setTarget(planType == 0 ? Double.valueOf(etTarget.getText().toString()) : 0); editData.setCurrent(planType == 0 ? Double.valueOf(etCurrent.getText().toString()) : 0); editData.setUnit(etUnit.getText().toString()); boolean periodIsOpen = llPeriod.getVisibility() == View.VISIBLE; editData.setPeriodIsOpen(periodIsOpen); if (periodIsOpen) { editData.setPeriodTarget(Double.valueOf(etPeriodTarget.getText().toString())); switch(etPeriodType.getText().toString()){ case "天": editData.setPeriodPlanType(0); break; case "周": editData.setPeriodPlanType(1); break; case "月": editData.setPeriodPlanType(3); break; } } presenter.updatePlan(editData); } private boolean checkRationPlan() { if (TextUtils.isEmpty(etName.getText().toString())) { showNoActionSnackbar("请输入计划名"); return false; } if (TextUtils.isEmpty(etFinishDate.getText().toString())) { showNoActionSnackbar("请输入结束时间"); return false; } if (TextUtils.isEmpty(etTarget.getText().toString())) { showNoActionSnackbar("请输入目标值"); return false; } if (TextUtils.isEmpty(etCurrent.getText().toString())) { showNoActionSnackbar("请输入当前值"); return false; } if (TextUtils.isEmpty(etUnit.getText().toString())) { showNoActionSnackbar("请输入单位"); return false; } if (llPeriod.getVisibility() == View.VISIBLE) { if (TextUtils.isEmpty(etPeriodType.getText().toString())) { showNoActionSnackbar("请选择短期计划类型"); return false; } if (TextUtils.isEmpty(etPeriodTarget.getText().toString())) { showNoActionSnackbar("请输入短期计划目标"); return false; } } return true; } private boolean checkClockPlan() { if (TextUtils.isEmpty(etName.getText().toString())) { showNoActionSnackbar("请输入计划名"); return false; } return true; } @OnClick(R.id.et_finish_date) public void onFinishDateClick() { DateTimePickerHelper.showDateDialog(this, "yyyy-MM-dd", TextUtils.isEmpty(etFinishDate.getText().toString()) ? "" : etFinishDate.getText().toString(), etFinishDate::setText); } @OnClick(R.id.et_period_type) public void onPeriodTypeClick(View view) { PopupMenu popupMenu = new PopupMenu(this, view); popupMenu.getMenu().add(0, 0, 0, "天"); popupMenu.getMenu().add(0, 1, 0, "周"); popupMenu.getMenu().add(0, 2, 0, "月"); popupMenu.setOnMenuItemClickListener(item -> { etPeriodType.setText(item.getTitle()); this.periodType = item.getItemId(); updatePeriodTarget(); return true; }); popupMenu.show(); } @OnClick(R.id.img_delete_period) public void onDeletePeriodPlanClick() { new AlertDialog.Builder(this) .setTitle("真的要删除短期计划?") .setNegativeButton("不", null) .setPositiveButton("对", (DialogInterface dialog, int which) -> { showRoundProgressDialog(); presenter.deletePeriod(); }) .create() .show(); } private void updatePeriodTarget() { if (rationPlan == null) return; double target = !TextUtils.isEmpty(etTarget.getText().toString()) ? Double.valueOf(etTarget.getText().toString()) : rationPlan.getTarget(); double current = !TextUtils.isEmpty(etCurrent.getText().toString()) ? Double.valueOf(etCurrent.getText().toString()) : rationPlan.getCurrent(); String startDate = rationPlan != null ? rationPlan.getStartDate() : ""; String finishDate = !TextUtils.isEmpty(etFinishDate.getText().toString()) ? etFinishDate.getText().toString() : rationPlan.getFinishDate(); if (target != 0 && !TextUtils.isEmpty(startDate) && !TextUtils.isEmpty(finishDate)) { switch (periodType) { case 0: { //天 double value = (target - current) / (DateUtils.getDaySpace("yyyy-MM-dd", startDate, finishDate) + 1); etPeriodTarget.setText(decimalFormat.format(value)); break; } case 1: { //周 double value = (target - current) / (DateUtils.getWeekSpace("yyyy-MM-dd", startDate, finishDate) + 1); etPeriodTarget.setText(decimalFormat.format(value)); break; } case 2: { //月 double value = (target - current) / (DateUtils.getMonthSpace("yyyy-MM-dd", startDate, finishDate) + 1); etPeriodTarget.setText(decimalFormat.format(value)); break; } } } } @Override public void showRationPlan() { flPlanDescription.setVisibility(View.GONE); llPlanSwitch.setVisibility(View.VISIBLE); } @Override public void showClockPlan() { flPlanDescription.setVisibility(View.VISIBLE); llPlanSwitch.setVisibility(View.GONE); } @Override public void fillRationPlanData(RationPlan plan) { this.rationPlan = plan; etName.setText(plan.getName()); etFinishDate.setText(plan.getFinishDate()); etTarget.setText(String.valueOf(plan.getTarget())); etCurrent.setText(String.valueOf(plan.getCurrent())); etUnit.setText(plan.getUnit()); if (plan.getPeriodIsOpen()) { llPeriod.setVisibility(View.VISIBLE); int periodType = plan.getPeriodPlanType(); switch (periodType) { case 0: etPeriodType.setText("日"); break; case 1: etPeriodType.setText("周"); break; case 2: etPeriodType.setText("月"); break; } etPeriodTarget.setText(String.valueOf(plan.getPeriodPlanTarget())); } else { llPeriod.setVisibility(View.GONE); } closeRoundProgressDialog(); } @Override public void fillClockPlanData(ClockPlan plan) { etName.setText(plan.getName()); etDescription.setText(plan.getDescription()); closeRoundProgressDialog(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.edit_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.delete: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("注意了"); builder.setMessage("真的要删除这个计划吗???"); builder.setNegativeButton("不不不", null); builder.setPositiveButton("删吧", (DialogInterface dialog, int which) -> presenter.deletePlan()); builder.create().show(); break; } return super.onOptionsItemSelected(item); } @Override protected void onDestroy() { presenter.onDestroy(); super.onDestroy(); } }
false
2,314
33
2,766
28
2,968
32
2,766
28
3,385
39
false
false
false
false
false
true
60959_0
package com.aspire.main; /* * 场景说明: * 甲和乙打赌,甲说可以在乙先跑39米的情况下,挥刀仍能伤着乙;乙不信,要比一下速度。于是请来裁判丁。 * * 于是比赛规则(流程)就有了: * 第一步:丁(裁判)倒计时5个数,数到0时,(通知)乙开始跑。 * 第二步:乙开始跑,跑到第39米时,(通知)甲可以挥刀了。 * 第三步:甲挥刀。 */ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Condition简单测试 * * @author JustryDeng * @DATE 2018年9月4日 下午8:42:14 */ public class ConditionTest { /** 获取Lock实例 */ Lock lock = new ReentrantLock(); /** 丁(裁判)倒计时结束后,由false变为true; */ boolean gameStartFlag = false; /** 乙跑了39米后,由false变为true; */ boolean swingFlag = false; /** 对应jia中用到的Condition */ Condition jiaCondition = lock.newCondition(); /** 对应yi中用到的Condition */ Condition yiCondition = lock.newCondition(); /** * 对应 --- 甲 */ public void jia() { lock.lock(); try { if(!swingFlag) {// 如果乙还没跑够39米,那么继续等乙跑够 jiaCondition.await(); } if(swingFlag) { System.out.println(Thread.currentThread().getName() + ":我挥刀了!!!"); } } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } /** * 对应 --- 乙 */ public void yi() { lock.lock(); try { if(!gameStartFlag) { // 如果游戏还没开始,那么继续等 yiCondition.await(); } System.out.println(Thread.currentThread().getName() + ":我开始跑了!!!"); Thread.sleep(2000); System.out.println(Thread.currentThread().getName() + ":我已经跑了39米了!!!"); // 将 挥刀 标识符 状态改为true;这样 甲就知道可以 挥刀了 swingFlag = true; // 由于要 唤醒 甲; 解铃还须系铃人,用jiaCondition.await()的,这里就用jiaCondition来唤醒 jiaCondition.signal(); } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } /** * 对应 --- 丁 */ public void ding() { lock.lock(); try { System.out.println(Thread.currentThread().getName() + "(裁判):倒计时开始!!!"); for (int i = 5; i >= 0; i--) { System.out.println(Thread.currentThread().getName() + "(裁判):" + i); } System.out.println(Thread.currentThread().getName() + "(裁判):比赛开始!!!"); // 将 开始 标识符 状态改为true;这样乙就知道可以开始跑了 gameStartFlag = true; // 由于要 唤醒 乙; 解铃还须系铃人,用yiCondition.await()的,这里就用yiCondition来唤醒 yiCondition.signal(); } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } /** * 入口 */ public static void main(String[] args) { ConditionTest ct = new ConditionTest(); new Thread("甲") { @Override public void run() { ct.jia(); } }.start(); new Thread("乙") { @Override public void run() { ct.yi(); } }.start(); new Thread("丁") { @Override public void run() { ct.ding(); } }.start(); } }
JustryDeng/PublicRepository
Abc_Lock_Test/src/main/java/com/aspire/main/ConditionTest.java
1,160
/* * 场景说明: * 甲和乙打赌,甲说可以在乙先跑39米的情况下,挥刀仍能伤着乙;乙不信,要比一下速度。于是请来裁判丁。 * * 于是比赛规则(流程)就有了: * 第一步:丁(裁判)倒计时5个数,数到0时,(通知)乙开始跑。 * 第二步:乙开始跑,跑到第39米时,(通知)甲可以挥刀了。 * 第三步:甲挥刀。 */
block_comment
zh-cn
package com.aspire.main; /* * 场景说 <SUF>*/ import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Condition简单测试 * * @author JustryDeng * @DATE 2018年9月4日 下午8:42:14 */ public class ConditionTest { /** 获取Lock实例 */ Lock lock = new ReentrantLock(); /** 丁(裁判)倒计时结束后,由false变为true; */ boolean gameStartFlag = false; /** 乙跑了39米后,由false变为true; */ boolean swingFlag = false; /** 对应jia中用到的Condition */ Condition jiaCondition = lock.newCondition(); /** 对应yi中用到的Condition */ Condition yiCondition = lock.newCondition(); /** * 对应 --- 甲 */ public void jia() { lock.lock(); try { if(!swingFlag) {// 如果乙还没跑够39米,那么继续等乙跑够 jiaCondition.await(); } if(swingFlag) { System.out.println(Thread.currentThread().getName() + ":我挥刀了!!!"); } } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } /** * 对应 --- 乙 */ public void yi() { lock.lock(); try { if(!gameStartFlag) { // 如果游戏还没开始,那么继续等 yiCondition.await(); } System.out.println(Thread.currentThread().getName() + ":我开始跑了!!!"); Thread.sleep(2000); System.out.println(Thread.currentThread().getName() + ":我已经跑了39米了!!!"); // 将 挥刀 标识符 状态改为true;这样 甲就知道可以 挥刀了 swingFlag = true; // 由于要 唤醒 甲; 解铃还须系铃人,用jiaCondition.await()的,这里就用jiaCondition来唤醒 jiaCondition.signal(); } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } /** * 对应 --- 丁 */ public void ding() { lock.lock(); try { System.out.println(Thread.currentThread().getName() + "(裁判):倒计时开始!!!"); for (int i = 5; i >= 0; i--) { System.out.println(Thread.currentThread().getName() + "(裁判):" + i); } System.out.println(Thread.currentThread().getName() + "(裁判):比赛开始!!!"); // 将 开始 标识符 状态改为true;这样乙就知道可以开始跑了 gameStartFlag = true; // 由于要 唤醒 乙; 解铃还须系铃人,用yiCondition.await()的,这里就用yiCondition来唤醒 yiCondition.signal(); } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } /** * 入口 */ public static void main(String[] args) { ConditionTest ct = new ConditionTest(); new Thread("甲") { @Override public void run() { ct.jia(); } }.start(); new Thread("乙") { @Override public void run() { ct.yi(); } }.start(); new Thread("丁") { @Override public void run() { ct.ding(); } }.start(); } }
false
944
122
1,160
166
1,075
125
1,160
166
1,492
217
false
false
false
false
false
true
33364_5
import com.stormlin.fpgrowth.FPGrowth; import com.stormlin.kmeans.Point; import java.util.ArrayList; import java.util.List; import static com.stormlin.fpgrowth.ProcessingUtils.*; import static com.stormlin.kmeans.KMeans.Analyze; /** * @Author stormlin * @DATE 2017/5/11 * @TIME 0:12 * @PROJECT DataMining * @PACKAGE PACKAGE_NAME */ public class Main { public static void main(String[] args) { //kmeans(); fpgorwth(); } /** * 数据挖掘算法 K-Means 部分 */ private static void kmeans() { //输入数据 double[][] input = { {0.29, 1, 1}, {0.29, 0.18, 0.58}, {0.12, 0.3, 0.54}, {1, 1, 1}, {0.06, 0.42, 0.6}, {0.53, 0.64, 0.8}, {0.24, 1, 0.8}, {1, 1, 1}, {0.29, 0.8, 0.56}, {0.53, 0.8, 1}, {0.18, 0.8, 1}, {0.53, 0.8, 0.8}, {0.29, 0.8, 0.8}, {0.53, 0.8, 1}, {0.53, 1, 0.8}, {0.53, 1, 0.8} }; String[] names = {"中国", "日本", "韩国", "印尼", "澳大利亚", "朝鲜", "伊拉克", "泰国", "伊朗", "沙特", "阿联酋" , "卡塔尔", "乌兹别克斯坦", "巴林", "阿曼", "约旦"}; List<Point> points = new ArrayList<>(input.length); for (int i = 0; i < input.length; i++) { Point newPoint = new Point(input[i][0], input[i][1], input[i][2]); newPoint.setName(names[i]); newPoint.setClassID(0); points.add(newPoint); } List<List<Point>> result = Analyze(points, 3); for (List<Point> aResult : result) { for (Point anAResult : aResult) { System.out.print(anAResult.getName() + " "); } System.out.println(); } } /** * 数据挖掘算法 FP-Growth 部分 */ private static void fpgorwth() { //当前路径 String workingDictionaryPath = System.getProperty("user.dir"); //默认 CSV 文件输入位置 String csvFilePath = workingDictionaryPath + "\\test\\test.csv"; //默认书名字典位置 String dictionaryFilePath = workingDictionaryPath + "\\test\\dictionary.csv"; //输出文件路径 String outputFilePath = workingDictionaryPath + "\\test\\output.txt"; //分隔符 String inputSeparator = ","; //FP-Growth 输出分隔符 String fpSeparator = ","; //频繁项中间结果 List<List<String>> fpOutput = new ArrayList<>(); //CSV 输入结果 List<List<String>> fpInput; //最终结果 List<List<String>> result; //需要计算的分类 char requiredClass = 'B'; printCurrentTime(); System.out.println(System.getProperty("user.dir")); /* 预处理过程 */ fpInput = preProcess(csvFilePath, inputSeparator, requiredClass); /* FP-Growth 算法处理 */ FPGrowth fpGrowth = new FPGrowth(2); fpGrowth.getFPOutput(fpInput, null, fpOutput); System.out.println("开始再处理"); /* 再处理过程 */ if ((result = reProcess(dictionaryFilePath, fpSeparator, fpOutput)) == null) { System.out.println("无法进行再处理过程,程序退出。"); System.exit(-1); } System.out.println("处理完成,开始输出计算结果"); /* 结果输出 */ getOutput(outputFilePath, result); System.out.println("输出完成,程序结束"); printCurrentTime(); } }
K9A2/DataMining
src/Main.java
1,120
//当前路径
line_comment
zh-cn
import com.stormlin.fpgrowth.FPGrowth; import com.stormlin.kmeans.Point; import java.util.ArrayList; import java.util.List; import static com.stormlin.fpgrowth.ProcessingUtils.*; import static com.stormlin.kmeans.KMeans.Analyze; /** * @Author stormlin * @DATE 2017/5/11 * @TIME 0:12 * @PROJECT DataMining * @PACKAGE PACKAGE_NAME */ public class Main { public static void main(String[] args) { //kmeans(); fpgorwth(); } /** * 数据挖掘算法 K-Means 部分 */ private static void kmeans() { //输入数据 double[][] input = { {0.29, 1, 1}, {0.29, 0.18, 0.58}, {0.12, 0.3, 0.54}, {1, 1, 1}, {0.06, 0.42, 0.6}, {0.53, 0.64, 0.8}, {0.24, 1, 0.8}, {1, 1, 1}, {0.29, 0.8, 0.56}, {0.53, 0.8, 1}, {0.18, 0.8, 1}, {0.53, 0.8, 0.8}, {0.29, 0.8, 0.8}, {0.53, 0.8, 1}, {0.53, 1, 0.8}, {0.53, 1, 0.8} }; String[] names = {"中国", "日本", "韩国", "印尼", "澳大利亚", "朝鲜", "伊拉克", "泰国", "伊朗", "沙特", "阿联酋" , "卡塔尔", "乌兹别克斯坦", "巴林", "阿曼", "约旦"}; List<Point> points = new ArrayList<>(input.length); for (int i = 0; i < input.length; i++) { Point newPoint = new Point(input[i][0], input[i][1], input[i][2]); newPoint.setName(names[i]); newPoint.setClassID(0); points.add(newPoint); } List<List<Point>> result = Analyze(points, 3); for (List<Point> aResult : result) { for (Point anAResult : aResult) { System.out.print(anAResult.getName() + " "); } System.out.println(); } } /** * 数据挖掘算法 FP-Growth 部分 */ private static void fpgorwth() { //当前 <SUF> String workingDictionaryPath = System.getProperty("user.dir"); //默认 CSV 文件输入位置 String csvFilePath = workingDictionaryPath + "\\test\\test.csv"; //默认书名字典位置 String dictionaryFilePath = workingDictionaryPath + "\\test\\dictionary.csv"; //输出文件路径 String outputFilePath = workingDictionaryPath + "\\test\\output.txt"; //分隔符 String inputSeparator = ","; //FP-Growth 输出分隔符 String fpSeparator = ","; //频繁项中间结果 List<List<String>> fpOutput = new ArrayList<>(); //CSV 输入结果 List<List<String>> fpInput; //最终结果 List<List<String>> result; //需要计算的分类 char requiredClass = 'B'; printCurrentTime(); System.out.println(System.getProperty("user.dir")); /* 预处理过程 */ fpInput = preProcess(csvFilePath, inputSeparator, requiredClass); /* FP-Growth 算法处理 */ FPGrowth fpGrowth = new FPGrowth(2); fpGrowth.getFPOutput(fpInput, null, fpOutput); System.out.println("开始再处理"); /* 再处理过程 */ if ((result = reProcess(dictionaryFilePath, fpSeparator, fpOutput)) == null) { System.out.println("无法进行再处理过程,程序退出。"); System.exit(-1); } System.out.println("处理完成,开始输出计算结果"); /* 结果输出 */ getOutput(outputFilePath, result); System.out.println("输出完成,程序结束"); printCurrentTime(); } }
false
1,018
3
1,120
3
1,150
3
1,120
3
1,391
7
false
false
false
false
false
true
49852_0
package dependency_injection; import Utils.Utils; public class Cook { // 依赖注入 public void cook(Dish dish) { Utils.logger.info("(" + this.toString() + "):" +"制作 " + dish.getName()); } }
KHAKhazeus/UnderCooked
src/main/java/dependency_injection/Cook.java
66
// 依赖注入
line_comment
zh-cn
package dependency_injection; import Utils.Utils; public class Cook { // 依赖 <SUF> public void cook(Dish dish) { Utils.logger.info("(" + this.toString() + "):" +"制作 " + dish.getName()); } }
false
51
4
66
5
64
4
66
5
79
10
false
false
false
false
false
true
24917_18
package ZhiHuSpider.bean; import java.util.regex.Matcher; import java.util.regex.Pattern; import ZhiHuSpider.mothed.Util; /** * 知乎用户bean * * @author KKys * */ public class ZhiHuUserBean { String name;// 用户姓名 String location;// 居住地; String business;// 行业 String employment;// 公司 String position;// 职位; String education;// 大学 String major;// 专业 String userInfo;// 个人简介 int answersNum;// 回答数量 Long starsNum;// 被赞同数 Long thxNum;// 被感谢数 // 构造方法初始化数据 public ZhiHuUserBean(String url) { //初始化为空字符串 name = ""; location = ""; business = ""; employment = ""; position = ""; education = ""; major = ""; userInfo = ""; System.out.println("正在抓取用户链接:" + url); // 根据url获取该用户的详细资料 String content = Util.SendGet(url); Pattern pattern; Matcher matcher; // 匹配姓名 pattern = Pattern.compile("class=\"name\">(.+?)</span>"); matcher = pattern.matcher(content); if (matcher.find()) { name = matcher.group(1); } // 匹配居住地 pattern = Pattern.compile("location item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { location = matcher.group(1); } // 匹配行业 pattern = Pattern.compile("business item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { business = matcher.group(1); } // 匹配公司 pattern = Pattern.compile("employment item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { employment = matcher.group(1); } // 匹配职位 pattern = Pattern.compile("position item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { position = matcher.group(1); } // 匹配大学 pattern = Pattern.compile("education item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { education = matcher.group(1); } // 匹配专业 pattern = Pattern.compile("education-extra item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { major = matcher.group(1); } // 匹配个人简介 pattern = Pattern.compile("fold-item.+?content\">(.*?)</span>"); matcher = pattern.matcher(content); if (matcher.find()) { userInfo = matcher.group(1).replaceAll("<.*?>", "");; } // 匹配回答数量 pattern = Pattern.compile("answers\">.+?>(.*?)</span>"); matcher = pattern.matcher(content); if (matcher.find()) { answersNum = Integer.parseInt(matcher.group(1)); } // 匹配被赞数 pattern = Pattern.compile("zm-profile-header-user-agree.+?strong>(.*?)</strong>"); matcher = pattern.matcher(content); if (matcher.find()) { starsNum = Long.parseLong(matcher.group(1)); } // 匹配被感谢数 pattern = Pattern.compile("zm-profile-header-user-thanks.+?strong>(.*?)</strong>"); matcher = pattern.matcher(content); if (matcher.find()) { thxNum = Long.parseLong(matcher.group(1)); } } @Override public String toString() { return "姓名:" + name + "\n" + "居住地:" + location + "\n" + "行业:" + business + "\n公司:" + employment + "\n职位:"+ position + "\n大学:"+ education + "\n专业:"+ major + "\n个人简介:"+ userInfo + "\n回答数:" + answersNum+"\n被点赞数:"+ starsNum+"\n被收藏数:"+ thxNum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getBusiness() { return business; } public void setBusiness(String business) { this.business = business; } public String getEmployment() { return employment; } public void setEmployment(String employment) { this.employment = employment; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getEducation() { return education; } public void setEducation(String education) { this.education = education; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public int getAnswersNum() { return answersNum; } public void setAnswersNum(int answersNum) { this.answersNum = answersNum; } public Long getStarsNum() { return starsNum; } public void setStarsNum(Long starsNum) { this.starsNum = starsNum; } public Long getThxNum() { return thxNum; } public void setThxNum(Long thxNum) { this.thxNum = thxNum; } public String getUserInfo() { return userInfo; } public void setUserInfo(String userInfo) { this.userInfo = userInfo; } }
KKys/ZhiHuSpider
src/main/java/ZhiHuSpider/bean/ZhiHuUserBean.java
1,546
// 匹配个人简介
line_comment
zh-cn
package ZhiHuSpider.bean; import java.util.regex.Matcher; import java.util.regex.Pattern; import ZhiHuSpider.mothed.Util; /** * 知乎用户bean * * @author KKys * */ public class ZhiHuUserBean { String name;// 用户姓名 String location;// 居住地; String business;// 行业 String employment;// 公司 String position;// 职位; String education;// 大学 String major;// 专业 String userInfo;// 个人简介 int answersNum;// 回答数量 Long starsNum;// 被赞同数 Long thxNum;// 被感谢数 // 构造方法初始化数据 public ZhiHuUserBean(String url) { //初始化为空字符串 name = ""; location = ""; business = ""; employment = ""; position = ""; education = ""; major = ""; userInfo = ""; System.out.println("正在抓取用户链接:" + url); // 根据url获取该用户的详细资料 String content = Util.SendGet(url); Pattern pattern; Matcher matcher; // 匹配姓名 pattern = Pattern.compile("class=\"name\">(.+?)</span>"); matcher = pattern.matcher(content); if (matcher.find()) { name = matcher.group(1); } // 匹配居住地 pattern = Pattern.compile("location item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { location = matcher.group(1); } // 匹配行业 pattern = Pattern.compile("business item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { business = matcher.group(1); } // 匹配公司 pattern = Pattern.compile("employment item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { employment = matcher.group(1); } // 匹配职位 pattern = Pattern.compile("position item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { position = matcher.group(1); } // 匹配大学 pattern = Pattern.compile("education item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { education = matcher.group(1); } // 匹配专业 pattern = Pattern.compile("education-extra item.+?title=\"(.+?)\""); matcher = pattern.matcher(content); if (matcher.find()) { major = matcher.group(1); } // 匹配 <SUF> pattern = Pattern.compile("fold-item.+?content\">(.*?)</span>"); matcher = pattern.matcher(content); if (matcher.find()) { userInfo = matcher.group(1).replaceAll("<.*?>", "");; } // 匹配回答数量 pattern = Pattern.compile("answers\">.+?>(.*?)</span>"); matcher = pattern.matcher(content); if (matcher.find()) { answersNum = Integer.parseInt(matcher.group(1)); } // 匹配被赞数 pattern = Pattern.compile("zm-profile-header-user-agree.+?strong>(.*?)</strong>"); matcher = pattern.matcher(content); if (matcher.find()) { starsNum = Long.parseLong(matcher.group(1)); } // 匹配被感谢数 pattern = Pattern.compile("zm-profile-header-user-thanks.+?strong>(.*?)</strong>"); matcher = pattern.matcher(content); if (matcher.find()) { thxNum = Long.parseLong(matcher.group(1)); } } @Override public String toString() { return "姓名:" + name + "\n" + "居住地:" + location + "\n" + "行业:" + business + "\n公司:" + employment + "\n职位:"+ position + "\n大学:"+ education + "\n专业:"+ major + "\n个人简介:"+ userInfo + "\n回答数:" + answersNum+"\n被点赞数:"+ starsNum+"\n被收藏数:"+ thxNum; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getBusiness() { return business; } public void setBusiness(String business) { this.business = business; } public String getEmployment() { return employment; } public void setEmployment(String employment) { this.employment = employment; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getEducation() { return education; } public void setEducation(String education) { this.education = education; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public int getAnswersNum() { return answersNum; } public void setAnswersNum(int answersNum) { this.answersNum = answersNum; } public Long getStarsNum() { return starsNum; } public void setStarsNum(Long starsNum) { this.starsNum = starsNum; } public Long getThxNum() { return thxNum; } public void setThxNum(Long thxNum) { this.thxNum = thxNum; } public String getUserInfo() { return userInfo; } public void setUserInfo(String userInfo) { this.userInfo = userInfo; } }
false
1,296
6
1,546
6
1,503
5
1,546
6
2,029
12
false
false
false
false
false
true
33663_30
package com.wisedu.emap.itpub.bean; /** * @filename ITUser.java * @date 2016年4月21日 上午11:07:42 * @author wjfu 01116035 */ /* { "name": "林争辉", "id": "03048", "userType": "Teacher", "deptName": "大学生心理健康教育中心", "deptCode": "000059", "phone": "13843838438", "birthday": "1933-11-04", "nationCode": "04", "nationName": "藏族", "nativeCode": "542200", "nativeName": "山南地区", "politicalCode": "01", "politicalName": "中国共产党党员", "positionLevelCode": null, "positionLevelName": null, "email": "[email protected]", "position": "老大", "sexCode": "1", "sexName": "男", "academyCode": "000007", "academyName": "学生工作处、学生工作部", "grade": null, "className": null, "classCode": null, "majorName": null, "majorCode": null, "attachToCode": "000007", "clevel": 2 } */ public class ItUser { /** * 用户姓名 */ private String name; /** * 用户id */ private String id; /** * 用户类型 Teacher/Student */ private String userType; /** * 班级 */ private String className; /** * 班级代码 */ private String classCode; /** * 部门 */ private String deptName; /** * 部门代码 */ private String deptCode; /** * 性别代码 */ private String sexCode; /** * 性别 */ private String sexName; /** * 手机号码 */ private String phone; /** * email */ private String email; /** * 专业 */ private String majorName; /** * 专业code */ private String majorCode; /** * 年级 */ private String grade; /** * 职位 */ private String position; /** * 隶属部门代码 (一级部门) */ private String academyCode; /** * 隶属部门名称 (一级部门) */ private String academyName; /** * 生日 */ private String birthday; /** * 民族编码 */ private String nationCode; /** * 民族 */ private String nationName; /** * 籍贯编码 */ private String nativeCode; /** * 籍贯 */ private String nativeName; /** * 政治面貌编码 */ private String politicalCode; /** * 政治面貌 */ private String politicalName; /** * 党政职务级别编码 */ private String positionLevelCode; /** * 党政职务级别编码 */ private String positionLevelName; /** * 上级部门代码 */ private String attachToCode; /** * 所在部门层次 */ private String clevel; /** * 数据类型 */ private String dataType; public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getAcademyCode() { return academyCode; } public void setAcademyCode(String academyCode) { this.academyCode = academyCode; } public String getAcademyName() { return academyName; } public void setAcademyName(String academyName) { this.academyName = academyName; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getNationCode() { return nationCode; } public void setNationCode(String nationCode) { this.nationCode = nationCode; } public String getNationName() { return nationName; } public void setNationName(String nationName) { this.nationName = nationName; } public String getNativeCode() { return nativeCode; } public void setNativeCode(String nativeCode) { this.nativeCode = nativeCode; } public String getNativeName() { return nativeName; } public void setNativeName(String nativeName) { this.nativeName = nativeName; } public String getPoliticalCode() { return politicalCode; } public void setPoliticalCode(String politicalCode) { this.politicalCode = politicalCode; } public String getPoliticalName() { return politicalName; } public void setPoliticalName(String politicalName) { this.politicalName = politicalName; } public String getPositionLevelCode() { return positionLevelCode; } public void setPositionLevelCode(String positionLevelCode) { this.positionLevelCode = positionLevelCode; } public String getPositionLevelName() { return positionLevelName; } public void setPositionLevelName(String positionLevelName) { this.positionLevelName = positionLevelName; } public String getAttachToCode() { return attachToCode; } public void setAttachToCode(String attachToCode) { this.attachToCode = attachToCode; } public String getClevel() { return clevel; } public void setClevel(String clevel) { this.clevel = clevel; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getClassCode() { return classCode; } public void setClassCode(String classCode) { this.classCode = classCode; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getDeptCode() { return deptCode; } public void setDeptCode(String deptCode) { this.deptCode = deptCode; } public String getSexCode() { return sexCode; } public void setSexCode(String sexCode) { this.sexCode = sexCode; } public String getSexName() { return sexName; } public void setSexName(String sexName) { this.sexName = sexName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMajorName() { return majorName; } public void setMajorName(String majorName) { this.majorName = majorName; } public String getMajorCode() { return majorCode; } public void setMajorCode(String majorCode) { this.majorCode = majorCode; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } @Override public String toString() { return "ItUser [name=" + name + ", id=" + id + ", userType=" + userType + ", className=" + className + ", classCode=" + classCode + ", deptName=" + deptName + ", deptCode=" + deptCode + ", sexCode=" + sexCode + ", sexName=" + sexName + ", phone=" + phone + ", email=" + email + ", majorName=" + majorName + ", majorCode=" + majorCode + ", grade=" + grade + ", dataType=" + dataType + "]"; } }
Kaisir/itpub
src/com/wisedu/emap/itpub/bean/ItUser.java
2,077
/** * 数据类型 */
block_comment
zh-cn
package com.wisedu.emap.itpub.bean; /** * @filename ITUser.java * @date 2016年4月21日 上午11:07:42 * @author wjfu 01116035 */ /* { "name": "林争辉", "id": "03048", "userType": "Teacher", "deptName": "大学生心理健康教育中心", "deptCode": "000059", "phone": "13843838438", "birthday": "1933-11-04", "nationCode": "04", "nationName": "藏族", "nativeCode": "542200", "nativeName": "山南地区", "politicalCode": "01", "politicalName": "中国共产党党员", "positionLevelCode": null, "positionLevelName": null, "email": "[email protected]", "position": "老大", "sexCode": "1", "sexName": "男", "academyCode": "000007", "academyName": "学生工作处、学生工作部", "grade": null, "className": null, "classCode": null, "majorName": null, "majorCode": null, "attachToCode": "000007", "clevel": 2 } */ public class ItUser { /** * 用户姓名 */ private String name; /** * 用户id */ private String id; /** * 用户类型 Teacher/Student */ private String userType; /** * 班级 */ private String className; /** * 班级代码 */ private String classCode; /** * 部门 */ private String deptName; /** * 部门代码 */ private String deptCode; /** * 性别代码 */ private String sexCode; /** * 性别 */ private String sexName; /** * 手机号码 */ private String phone; /** * email */ private String email; /** * 专业 */ private String majorName; /** * 专业code */ private String majorCode; /** * 年级 */ private String grade; /** * 职位 */ private String position; /** * 隶属部门代码 (一级部门) */ private String academyCode; /** * 隶属部门名称 (一级部门) */ private String academyName; /** * 生日 */ private String birthday; /** * 民族编码 */ private String nationCode; /** * 民族 */ private String nationName; /** * 籍贯编码 */ private String nativeCode; /** * 籍贯 */ private String nativeName; /** * 政治面貌编码 */ private String politicalCode; /** * 政治面貌 */ private String politicalName; /** * 党政职务级别编码 */ private String positionLevelCode; /** * 党政职务级别编码 */ private String positionLevelName; /** * 上级部门代码 */ private String attachToCode; /** * 所在部门层次 */ private String clevel; /** * 数据类 <SUF>*/ private String dataType; public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getAcademyCode() { return academyCode; } public void setAcademyCode(String academyCode) { this.academyCode = academyCode; } public String getAcademyName() { return academyName; } public void setAcademyName(String academyName) { this.academyName = academyName; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } public String getNationCode() { return nationCode; } public void setNationCode(String nationCode) { this.nationCode = nationCode; } public String getNationName() { return nationName; } public void setNationName(String nationName) { this.nationName = nationName; } public String getNativeCode() { return nativeCode; } public void setNativeCode(String nativeCode) { this.nativeCode = nativeCode; } public String getNativeName() { return nativeName; } public void setNativeName(String nativeName) { this.nativeName = nativeName; } public String getPoliticalCode() { return politicalCode; } public void setPoliticalCode(String politicalCode) { this.politicalCode = politicalCode; } public String getPoliticalName() { return politicalName; } public void setPoliticalName(String politicalName) { this.politicalName = politicalName; } public String getPositionLevelCode() { return positionLevelCode; } public void setPositionLevelCode(String positionLevelCode) { this.positionLevelCode = positionLevelCode; } public String getPositionLevelName() { return positionLevelName; } public void setPositionLevelName(String positionLevelName) { this.positionLevelName = positionLevelName; } public String getAttachToCode() { return attachToCode; } public void setAttachToCode(String attachToCode) { this.attachToCode = attachToCode; } public String getClevel() { return clevel; } public void setClevel(String clevel) { this.clevel = clevel; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserType() { return userType; } public void setUserType(String userType) { this.userType = userType; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getClassCode() { return classCode; } public void setClassCode(String classCode) { this.classCode = classCode; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } public String getDeptCode() { return deptCode; } public void setDeptCode(String deptCode) { this.deptCode = deptCode; } public String getSexCode() { return sexCode; } public void setSexCode(String sexCode) { this.sexCode = sexCode; } public String getSexName() { return sexName; } public void setSexName(String sexName) { this.sexName = sexName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMajorName() { return majorName; } public void setMajorName(String majorName) { this.majorName = majorName; } public String getMajorCode() { return majorCode; } public void setMajorCode(String majorCode) { this.majorCode = majorCode; } public String getGrade() { return grade; } public void setGrade(String grade) { this.grade = grade; } public String getDataType() { return dataType; } public void setDataType(String dataType) { this.dataType = dataType; } @Override public String toString() { return "ItUser [name=" + name + ", id=" + id + ", userType=" + userType + ", className=" + className + ", classCode=" + classCode + ", deptName=" + deptName + ", deptCode=" + deptCode + ", sexCode=" + sexCode + ", sexName=" + sexName + ", phone=" + phone + ", email=" + email + ", majorName=" + majorName + ", majorCode=" + majorCode + ", grade=" + grade + ", dataType=" + dataType + "]"; } }
false
2,008
8
2,077
7
2,358
9
2,077
7
2,692
12
false
false
false
false
false
true
36516_1
package testQ.Mideum; //給定一個句子,請判斷它是不是迴文,即正著讀或反著讀都一樣的句子。例如:【上海自來水來自海上】是迴文。其他例子: //(1) 喜歡的少年是你,你是年少的歡喜 //(2) 小巷殘月凝天空,親人故土鄉情濃,笑聲猶在空懷舊,憔心客愁滿蒼穹,穹蒼滿愁客心憔,舊懷空在猶聲笑,濃情鄉土故人親,空天凝月殘巷小 public class Q3 { public static void main(String[] args) { boolean reverse = true; int count = 0; String test = "小巷殘月凝天空,親人故土鄉情濃,笑聲猶在空懷舊,憔心客愁滿蒼穹,穹蒼滿愁客心憔,舊懷空在猶聲笑,濃情鄉土故人親,空天凝月殘巷小"; for (int i = 0; i < test.length() / 2; i++) { if (test.charAt(i) != test.charAt((test.length() - 1) - count)) { reverse = false; } count++; } if (reverse){ System.out.println(test + " 是回文"); }else { System.out.println(test +" 不是回文"); } } }
Kalvin520/Kalvin_JDBC
JDBC/src/main/java/testQ/Mideum/Q3.java
434
//(1) 喜歡的少年是你,你是年少的歡喜
line_comment
zh-cn
package testQ.Mideum; //給定一個句子,請判斷它是不是迴文,即正著讀或反著讀都一樣的句子。例如:【上海自來水來自海上】是迴文。其他例子: //(1 <SUF> //(2) 小巷殘月凝天空,親人故土鄉情濃,笑聲猶在空懷舊,憔心客愁滿蒼穹,穹蒼滿愁客心憔,舊懷空在猶聲笑,濃情鄉土故人親,空天凝月殘巷小 public class Q3 { public static void main(String[] args) { boolean reverse = true; int count = 0; String test = "小巷殘月凝天空,親人故土鄉情濃,笑聲猶在空懷舊,憔心客愁滿蒼穹,穹蒼滿愁客心憔,舊懷空在猶聲笑,濃情鄉土故人親,空天凝月殘巷小"; for (int i = 0; i < test.length() / 2; i++) { if (test.charAt(i) != test.charAt((test.length() - 1) - count)) { reverse = false; } count++; } if (reverse){ System.out.println(test + " 是回文"); }else { System.out.println(test +" 不是回文"); } } }
false
327
17
434
22
348
13
434
22
539
24
false
false
false
false
false
true
23382_9
/* * @Author: KasperFan && [email protected] * @Date: 2023-04-04 16:46:33 * @LastEditTime: 2023-04-05 09:15:08 * @FilePath: /Java/WFUStudy/P1616_疯狂的采药.java * @describes: This file is created for learning Code. * Copyright (c) 2023 by KasperFan in WFU, All Rights Reserved. */ /* Name : P1616_疯狂的采药.java Time : 2023/02/18 17:44:52 Author : Kasper Fan Group : Weifang University Contact : [email protected] Desc : This file is created for learning Java coding */ import java.util.Scanner; public class P1616_疯狂的采药 { final static int N = 10010, M = (int) (1e7 + 10); static int t, m; static long[] value = new long[N], time = new long[N]; static long[] dp = new long[M]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); t = sc.nextInt(); m = sc.nextInt(); for (int i = 1; i <= m; i++) { time[i] = sc.nextLong(); value[i] = sc.nextLong(); } for (int i = 1; i <= m; i++) { for (int j = (int) time[i]; j <= t; j++) { dp[j] = Math.max(dp[j], dp[(int) (j - time[i])] + value[i]); } } sc.close(); System.out.println(dp[t]); } } // /* // * 从状态转移方程下手:f[i][j] = max(f[i-1][j- k * v[i]]+ k * w[i] (k= 0, 1, 2, 3, 4,…)) // * 方程拆开: // */ // f[i][j]=max(f[i-1][j],f[i-1][j-v[i]]+w[i],f[i-1][j-2*v[i]]+2*w[i],f[i-1][j-3*v[i]]+3*w[i],......); // // 使用代入法,将j= j-v[i]带入上面的方程中得到: // f[i][j-v[i]]=max(f[i-1][j-v[i]],f[i-1][j-2*v[i]]+w[i],f[i-1][j-3*v[i]]+2*w[i],f[i-1][j-3*v[i]]+3*w[i],......) // // 对比第二个和第一个方程,我们发现,方程1可以简化成: // f[i][j]=max(f[i-1][j],f[i][j-v[i]]+w[i]) // /* // * 怎么看起来跟01背包模型的好像啊,我们对比一下: // */ // f[i][j]=max(f[i-1][j],f[i-1][j-v[i]]+w[i]) // 01背包 // f[i][j]=max(f[i-1][j],f[i][j-v[i]]+w[i]) // 完全背包 // /* // * 发现了区别在下标从i-1变为i。为什么呢? // * f[i][j - v[i]] 已经将除去1个物品i时的所有最优解已经求出来了,因此在计算f[i][j]时,无需再重复计算k=2,3,4,5…时的值了。 // */
KasperFan/.Code
ACM/Java/WFUStudy/P1616_疯狂的采药.java
1,017
// * 怎么看起来跟01背包模型的好像啊,我们对比一下:
line_comment
zh-cn
/* * @Author: KasperFan && [email protected] * @Date: 2023-04-04 16:46:33 * @LastEditTime: 2023-04-05 09:15:08 * @FilePath: /Java/WFUStudy/P1616_疯狂的采药.java * @describes: This file is created for learning Code. * Copyright (c) 2023 by KasperFan in WFU, All Rights Reserved. */ /* Name : P1616_疯狂的采药.java Time : 2023/02/18 17:44:52 Author : Kasper Fan Group : Weifang University Contact : [email protected] Desc : This file is created for learning Java coding */ import java.util.Scanner; public class P1616_疯狂的采药 { final static int N = 10010, M = (int) (1e7 + 10); static int t, m; static long[] value = new long[N], time = new long[N]; static long[] dp = new long[M]; public static void main(String[] args) { Scanner sc = new Scanner(System.in); t = sc.nextInt(); m = sc.nextInt(); for (int i = 1; i <= m; i++) { time[i] = sc.nextLong(); value[i] = sc.nextLong(); } for (int i = 1; i <= m; i++) { for (int j = (int) time[i]; j <= t; j++) { dp[j] = Math.max(dp[j], dp[(int) (j - time[i])] + value[i]); } } sc.close(); System.out.println(dp[t]); } } // /* // * 从状态转移方程下手:f[i][j] = max(f[i-1][j- k * v[i]]+ k * w[i] (k= 0, 1, 2, 3, 4,…)) // * 方程拆开: // */ // f[i][j]=max(f[i-1][j],f[i-1][j-v[i]]+w[i],f[i-1][j-2*v[i]]+2*w[i],f[i-1][j-3*v[i]]+3*w[i],......); // // 使用代入法,将j= j-v[i]带入上面的方程中得到: // f[i][j-v[i]]=max(f[i-1][j-v[i]],f[i-1][j-2*v[i]]+w[i],f[i-1][j-3*v[i]]+2*w[i],f[i-1][j-3*v[i]]+3*w[i],......) // // 对比第二个和第一个方程,我们发现,方程1可以简化成: // f[i][j]=max(f[i-1][j],f[i][j-v[i]]+w[i]) // /* // * 怎么 <SUF> // */ // f[i][j]=max(f[i-1][j],f[i-1][j-v[i]]+w[i]) // 01背包 // f[i][j]=max(f[i-1][j],f[i][j-v[i]]+w[i]) // 完全背包 // /* // * 发现了区别在下标从i-1变为i。为什么呢? // * f[i][j - v[i]] 已经将除去1个物品i时的所有最优解已经求出来了,因此在计算f[i][j]时,无需再重复计算k=2,3,4,5…时的值了。 // */
false
860
19
1,017
22
997
17
1,017
22
1,131
35
false
false
false
false
false
true
20145_0
/** * 是抽象方法的集合,接口通常以interface来声明。一个类通过继承接口的方式,从而来继承接口的抽象方法。 * 有时必须从几个类中派生出一个子类,继承它们所有的属性和方法。 * 但是,Java不支持多重继承。有了接口,就可以得到多重继承的效果。 * 不能用于实例化对象。 * 没有构造方法。 * 中所有的方法必须是抽象方法。 * 不能包含成员变量,除了 static 和 final 变量。 * 不是被类继承了,而是要被类实现。 * 支持多继承。 * * 每一个方法也是隐式抽象的,接口中的方法会被隐式的指定为 public abstract * 可以含有变量,但是接口中的变量会被隐式的指定为 public static final 变量 * 接口中的方法是不能在接口中实现的,只能由实现接口的类来实现接口中的方法。 * 一个类只能继承一个抽象类,而一个类却可以实现多个接口。 * * */ public interface Runner { int id = 1; //接口中的变量会被隐式的指定为 public static final 变量 public void start(); public void run(); public void stop(); }
KeepCalmAndKeepCode/javaTest
Interface/src/Runner.java
294
/** * 是抽象方法的集合,接口通常以interface来声明。一个类通过继承接口的方式,从而来继承接口的抽象方法。 * 有时必须从几个类中派生出一个子类,继承它们所有的属性和方法。 * 但是,Java不支持多重继承。有了接口,就可以得到多重继承的效果。 * 不能用于实例化对象。 * 没有构造方法。 * 中所有的方法必须是抽象方法。 * 不能包含成员变量,除了 static 和 final 变量。 * 不是被类继承了,而是要被类实现。 * 支持多继承。 * * 每一个方法也是隐式抽象的,接口中的方法会被隐式的指定为 public abstract * 可以含有变量,但是接口中的变量会被隐式的指定为 public static final 变量 * 接口中的方法是不能在接口中实现的,只能由实现接口的类来实现接口中的方法。 * 一个类只能继承一个抽象类,而一个类却可以实现多个接口。 * * */
block_comment
zh-cn
/** * 是抽象 <SUF>*/ public interface Runner { int id = 1; //接口中的变量会被隐式的指定为 public static final 变量 public void start(); public void run(); public void stop(); }
false
271
227
294
248
271
223
294
248
473
415
true
true
true
true
true
false
37945_7
package upload; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; import communication.CommunicationModel; import database.DBConnection; import json.JsonUtil; import json.UploadInfoModel; import main.InfoPadding; public class Upload { // 定时填充上传函数 public static void upload(DBConnection db) { Calendar calendar = Calendar.getInstance(); // 设置首次执行的时间 // calendar.set(Calendar.HOUR_OF_DAY, 21); // calendar.set(Calendar.MINUTE, 36); // calendar.set(Calendar.SECOND, 0); // 不设置则默认是当前时间 java.util.Date time = calendar.getTime(); System.out.println("首次开始任务的时间是:" + time); Timer timer = new Timer(); // 间隔是1min timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { myTask(db); } }, time, 1000 * 60); } // 上传任务 public static void myTask(DBConnection db) { // 1.填充待上传数据 UploadInfoModel uploadInfoModel = InfoPadding.paddingInfo(db); // 2.生成json(没用) String jsonStr = JsonUtil.transformToJson(uploadInfoModel); // System.out.println("上传 "+jsonStr); System.out.println("上传数据 "); // 3.执行上传函数 CommunicationModel.uploadInfo(uploadInfoModel); // 4.手动更新到区块链 CommunicationModel.updateByman(); // 5.更新后查询(可能会出问题) //CommunicationModel.acquirePoint(); } }
Kevin-miu/InformationGetter
src/upload/Upload.java
440
// 上传任务
line_comment
zh-cn
package upload; import java.util.Calendar; import java.util.Timer; import java.util.TimerTask; import communication.CommunicationModel; import database.DBConnection; import json.JsonUtil; import json.UploadInfoModel; import main.InfoPadding; public class Upload { // 定时填充上传函数 public static void upload(DBConnection db) { Calendar calendar = Calendar.getInstance(); // 设置首次执行的时间 // calendar.set(Calendar.HOUR_OF_DAY, 21); // calendar.set(Calendar.MINUTE, 36); // calendar.set(Calendar.SECOND, 0); // 不设置则默认是当前时间 java.util.Date time = calendar.getTime(); System.out.println("首次开始任务的时间是:" + time); Timer timer = new Timer(); // 间隔是1min timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { myTask(db); } }, time, 1000 * 60); } // 上传 <SUF> public static void myTask(DBConnection db) { // 1.填充待上传数据 UploadInfoModel uploadInfoModel = InfoPadding.paddingInfo(db); // 2.生成json(没用) String jsonStr = JsonUtil.transformToJson(uploadInfoModel); // System.out.println("上传 "+jsonStr); System.out.println("上传数据 "); // 3.执行上传函数 CommunicationModel.uploadInfo(uploadInfoModel); // 4.手动更新到区块链 CommunicationModel.updateByman(); // 5.更新后查询(可能会出问题) //CommunicationModel.acquirePoint(); } }
false
371
4
440
4
426
3
440
4
562
6
false
false
false
false
false
true
25597_2
package com.mbyte.easy.admin.entity; import com.baomidou.mybatisplus.annotation.TableName; import com.mbyte.easy.common.entity.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * 人员信息表 * </p> * * @author 会写代码的怪叔叔 * @since 2019-04-12 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @TableName("t_person") public class Person extends BaseEntity { private static final long serialVersionUID = 1L; /** * 姓名 */ private String name; /** * 编号 */ private String code; /** * 内容 */ private String content; /** * 图片 */ private String filePath; }
Kevinlyz/Byte-Easy
src/main/java/com/mbyte/easy/admin/entity/Person.java
230
/** * 编号 */
block_comment
zh-cn
package com.mbyte.easy.admin.entity; import com.baomidou.mybatisplus.annotation.TableName; import com.mbyte.easy.common.entity.BaseEntity; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * 人员信息表 * </p> * * @author 会写代码的怪叔叔 * @since 2019-04-12 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) @TableName("t_person") public class Person extends BaseEntity { private static final long serialVersionUID = 1L; /** * 姓名 */ private String name; /** * 编号 <SUF>*/ private String code; /** * 内容 */ private String content; /** * 图片 */ private String filePath; }
false
183
9
221
7
225
9
221
7
278
10
false
false
false
false
false
true
57218_7
package vip.zhguo.xier.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.*; import vip.zhguo.xier.pojo.WxSetting; import vip.zhguo.xier.util.JodaTimeUtil; import vip.zhguo.xier.util.NetUtil; import vip.zhguo.xier.pojo.TempValue; import vip.zhguo.xier.pojo.WeatherDTO; import vip.zhguo.xier.util.WxUtil; import java.net.URLEncoder; import java.util.Date; import java.util.HashMap; import java.util.Map; @Api(value = "早安", tags = "早安") @RestController @Slf4j public class Weather { @Autowired TempValue tempValue; @Autowired WxSetting wxSetting; @Scheduled(cron = "0 30 7 * * ?",zone="GMT+8") @ApiOperation(value = "1.默认") @GetMapping("/za") public String za() throws Exception { WeatherDTO weatherDTO = new WeatherDTO(); String res = NetUtil.doGet(tempValue.getHuoqutianqi()); JSONObject json = JSON.parseObject(res); Map map = json.getJSONObject("result"); Object today = map.get("today"); log.info("json======" + json.toString()); log.info("today======" + today.toString()); //获取地理位置 weatherDTO.setArea_3(map.get("area_3").toString()); Map map1 = (Map) today; // /*天气(白天) weatherDTO.setWtNm1(map1.get("wtNm1").toString()); // /*天气(夜间) weatherDTO.setWtNm2(map1.get("wtNm2").toString()); /*温度(白天)*/ weatherDTO.setWtTemp1(map1.get("wtTemp1").toString()); /*温度(夜间)*/ weatherDTO.setWtTemp2(map1.get("wtTemp2").toString()); /*日出时间*/ weatherDTO.setWtSunr(map1.get("wtSunr").toString()); /*日落时间(24小时制)*/ weatherDTO.setWtSuns(map1.get("wtSuns").toString()); log.info("weatherDTO" + weatherDTO.toString()); wxSetting.setFlag("1"); String msg = "(⊙o⊙)…早安~公主殿下\n太阳起了你也起,你是人间小仙女,今天要开心呀~\n"+ "Slogan:目标清晰明了\t" + "毅力超乎想象\t\t" + "温柔而有力量."; String accessToken = WxUtil.getAccessToken(wxSetting.getAppId(), wxSetting.getAppSecret()); //发送消息 String result = WxUtil.sendMsg(accessToken, msg, wxSetting, weatherDTO); // System.out.println(s); return result; } @ApiOperation(value = "2.get带参") @GetMapping("/za-g") public String za(String msg) throws Exception { WeatherDTO weatherDTO = new WeatherDTO(); String res = NetUtil.doGet(tempValue.getHuoqutianqi()); JSONObject json = JSON.parseObject(res); Map map = json.getJSONObject("result"); Object today = map.get("today"); log.info("json======" + json.toString()); log.info("today======" + today.toString()); //获取地理位置 weatherDTO.setArea_3(map.get("area_3").toString()); Map map1 = (Map) today; // /*天气(白天) weatherDTO.setWtNm1(map1.get("wtNm1").toString()); // /*天气(夜间) weatherDTO.setWtNm2(map1.get("wtNm2").toString()); /*温度(白天)*/ weatherDTO.setWtTemp1(map1.get("wtTemp1").toString()); /*温度(夜间)*/ weatherDTO.setWtTemp2(map1.get("wtTemp2").toString()); /*日出时间*/ weatherDTO.setWtSunr(map1.get("wtSunr").toString()); /*日落时间(24小时制)*/ weatherDTO.setWtSuns(map1.get("wtSuns").toString()); log.info("weatherDTO" + weatherDTO.toString()); wxSetting.setFlag("1"); String accessToken = WxUtil.getAccessToken(wxSetting.getAppId(), wxSetting.getAppSecret()); //发送消息 String result = WxUtil.sendMsg(accessToken, msg, wxSetting, weatherDTO); // System.out.println(s); return result; } @ApiOperation(value = "3.post带参") @PostMapping("/za-p") public String zap(@RequestBody Map msg) throws Exception { WeatherDTO weatherDTO = new WeatherDTO(); String res = NetUtil.doGet(tempValue.getHuoqutianqi()); JSONObject json = JSON.parseObject(res); Map map = json.getJSONObject("result"); Object today = map.get("today"); log.info("json======" + json.toString()); log.info("today======" + today.toString()); //获取地理位置 weatherDTO.setArea_3(map.get("area_3").toString()); Map map1 = (Map) today; // /*天气(白天) weatherDTO.setWtNm1(map1.get("wtNm1").toString()); // /*天气(夜间) weatherDTO.setWtNm2(map1.get("wtNm2").toString()); /*温度(白天)*/ weatherDTO.setWtTemp1(map1.get("wtTemp1").toString()); /*温度(夜间)*/ weatherDTO.setWtTemp2(map1.get("wtTemp2").toString()); /*日出时间*/ weatherDTO.setWtSunr(map1.get("wtSunr").toString()); /*日落时间(24小时制)*/ weatherDTO.setWtSuns(map1.get("wtSuns").toString()); log.info("weatherDTO" + weatherDTO.toString()); wxSetting.setFlag("1"); String accessToken = WxUtil.getAccessToken(wxSetting.getAppId(), wxSetting.getAppSecret()); //发送消息 String result = WxUtil.sendMsg(accessToken, msg.get("msg").toString(), wxSetting, weatherDTO); // System.out.println(s); return result; } }
Khada-Jhin8/xier
src/main/java/vip/zhguo/xier/controller/Weather.java
1,683
//发送消息
line_comment
zh-cn
package vip.zhguo.xier.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.web.bind.annotation.*; import vip.zhguo.xier.pojo.WxSetting; import vip.zhguo.xier.util.JodaTimeUtil; import vip.zhguo.xier.util.NetUtil; import vip.zhguo.xier.pojo.TempValue; import vip.zhguo.xier.pojo.WeatherDTO; import vip.zhguo.xier.util.WxUtil; import java.net.URLEncoder; import java.util.Date; import java.util.HashMap; import java.util.Map; @Api(value = "早安", tags = "早安") @RestController @Slf4j public class Weather { @Autowired TempValue tempValue; @Autowired WxSetting wxSetting; @Scheduled(cron = "0 30 7 * * ?",zone="GMT+8") @ApiOperation(value = "1.默认") @GetMapping("/za") public String za() throws Exception { WeatherDTO weatherDTO = new WeatherDTO(); String res = NetUtil.doGet(tempValue.getHuoqutianqi()); JSONObject json = JSON.parseObject(res); Map map = json.getJSONObject("result"); Object today = map.get("today"); log.info("json======" + json.toString()); log.info("today======" + today.toString()); //获取地理位置 weatherDTO.setArea_3(map.get("area_3").toString()); Map map1 = (Map) today; // /*天气(白天) weatherDTO.setWtNm1(map1.get("wtNm1").toString()); // /*天气(夜间) weatherDTO.setWtNm2(map1.get("wtNm2").toString()); /*温度(白天)*/ weatherDTO.setWtTemp1(map1.get("wtTemp1").toString()); /*温度(夜间)*/ weatherDTO.setWtTemp2(map1.get("wtTemp2").toString()); /*日出时间*/ weatherDTO.setWtSunr(map1.get("wtSunr").toString()); /*日落时间(24小时制)*/ weatherDTO.setWtSuns(map1.get("wtSuns").toString()); log.info("weatherDTO" + weatherDTO.toString()); wxSetting.setFlag("1"); String msg = "(⊙o⊙)…早安~公主殿下\n太阳起了你也起,你是人间小仙女,今天要开心呀~\n"+ "Slogan:目标清晰明了\t" + "毅力超乎想象\t\t" + "温柔而有力量."; String accessToken = WxUtil.getAccessToken(wxSetting.getAppId(), wxSetting.getAppSecret()); //发送 <SUF> String result = WxUtil.sendMsg(accessToken, msg, wxSetting, weatherDTO); // System.out.println(s); return result; } @ApiOperation(value = "2.get带参") @GetMapping("/za-g") public String za(String msg) throws Exception { WeatherDTO weatherDTO = new WeatherDTO(); String res = NetUtil.doGet(tempValue.getHuoqutianqi()); JSONObject json = JSON.parseObject(res); Map map = json.getJSONObject("result"); Object today = map.get("today"); log.info("json======" + json.toString()); log.info("today======" + today.toString()); //获取地理位置 weatherDTO.setArea_3(map.get("area_3").toString()); Map map1 = (Map) today; // /*天气(白天) weatherDTO.setWtNm1(map1.get("wtNm1").toString()); // /*天气(夜间) weatherDTO.setWtNm2(map1.get("wtNm2").toString()); /*温度(白天)*/ weatherDTO.setWtTemp1(map1.get("wtTemp1").toString()); /*温度(夜间)*/ weatherDTO.setWtTemp2(map1.get("wtTemp2").toString()); /*日出时间*/ weatherDTO.setWtSunr(map1.get("wtSunr").toString()); /*日落时间(24小时制)*/ weatherDTO.setWtSuns(map1.get("wtSuns").toString()); log.info("weatherDTO" + weatherDTO.toString()); wxSetting.setFlag("1"); String accessToken = WxUtil.getAccessToken(wxSetting.getAppId(), wxSetting.getAppSecret()); //发送消息 String result = WxUtil.sendMsg(accessToken, msg, wxSetting, weatherDTO); // System.out.println(s); return result; } @ApiOperation(value = "3.post带参") @PostMapping("/za-p") public String zap(@RequestBody Map msg) throws Exception { WeatherDTO weatherDTO = new WeatherDTO(); String res = NetUtil.doGet(tempValue.getHuoqutianqi()); JSONObject json = JSON.parseObject(res); Map map = json.getJSONObject("result"); Object today = map.get("today"); log.info("json======" + json.toString()); log.info("today======" + today.toString()); //获取地理位置 weatherDTO.setArea_3(map.get("area_3").toString()); Map map1 = (Map) today; // /*天气(白天) weatherDTO.setWtNm1(map1.get("wtNm1").toString()); // /*天气(夜间) weatherDTO.setWtNm2(map1.get("wtNm2").toString()); /*温度(白天)*/ weatherDTO.setWtTemp1(map1.get("wtTemp1").toString()); /*温度(夜间)*/ weatherDTO.setWtTemp2(map1.get("wtTemp2").toString()); /*日出时间*/ weatherDTO.setWtSunr(map1.get("wtSunr").toString()); /*日落时间(24小时制)*/ weatherDTO.setWtSuns(map1.get("wtSuns").toString()); log.info("weatherDTO" + weatherDTO.toString()); wxSetting.setFlag("1"); String accessToken = WxUtil.getAccessToken(wxSetting.getAppId(), wxSetting.getAppSecret()); //发送消息 String result = WxUtil.sendMsg(accessToken, msg.get("msg").toString(), wxSetting, weatherDTO); // System.out.println(s); return result; } }
false
1,386
3
1,683
3
1,675
3
1,683
3
1,995
5
false
false
false
false
false
true
41898_0
package kimxu.core.net; import kimxu.api.net.HttpManager; public class HttpConfig { /** * 请求链接 */ final static String URL_WEINEWS_URL = "http://api.huceo.com/wxnew/other/"; final static String URL_YIDIAN_HOT_URL = "http://124.243.203.100/Website/channel/news-list-for-hot-channel"; final static String URL_YIDIAN_URL = "http://124.243.203.100/Website/channel/news-list-for-channel"; public final static int MSGCODE_HTTP_ERROR =HttpManager.MSGCODE_HTTP_ERROR; public final static int MSGCODE_HTTP_RESPONSE =HttpManager.MSGCODE_HTTP_RESPONSE; //社会 final static String SITE_SHEHUI = "1655594054"; //科技 final static String SITE_KEJI = "1655594078"; //段子 final static String SITE_DUANZI = "1655594086"; }
Kimxu/NewsAndFm
core/src/main/java/kimxu/core/net/HttpConfig.java
281
/** * 请求链接 */
block_comment
zh-cn
package kimxu.core.net; import kimxu.api.net.HttpManager; public class HttpConfig { /** * 请求链 <SUF>*/ final static String URL_WEINEWS_URL = "http://api.huceo.com/wxnew/other/"; final static String URL_YIDIAN_HOT_URL = "http://124.243.203.100/Website/channel/news-list-for-hot-channel"; final static String URL_YIDIAN_URL = "http://124.243.203.100/Website/channel/news-list-for-channel"; public final static int MSGCODE_HTTP_ERROR =HttpManager.MSGCODE_HTTP_ERROR; public final static int MSGCODE_HTTP_RESPONSE =HttpManager.MSGCODE_HTTP_RESPONSE; //社会 final static String SITE_SHEHUI = "1655594054"; //科技 final static String SITE_KEJI = "1655594078"; //段子 final static String SITE_DUANZI = "1655594086"; }
false
241
8
281
7
291
9
281
7
330
14
false
false
false
false
false
true