file_id
stringlengths 5
9
| content
stringlengths 24
16.1k
| repo
stringlengths 8
84
| path
stringlengths 7
167
| token_length
int64 18
3.48k
| original_comment
stringlengths 5
2.57k
| comment_type
stringclasses 2
values | detected_lang
stringclasses 1
value | masked_comment
stringlengths 11
16.1k
| excluded
bool 1
class | file-tokens-Qwen/Qwen2-7B
int64 14
3.27k
| comment-tokens-Qwen/Qwen2-7B
int64 2
1.74k
| file-tokens-bigcode/starcoder2-7b
int64 18
3.48k
| comment-tokens-bigcode/starcoder2-7b
int64 2
2.11k
| file-tokens-google/codegemma-7b
int64 14
3.57k
| comment-tokens-google/codegemma-7b
int64 2
1.75k
| file-tokens-ibm-granite/granite-8b-code-base
int64 18
3.48k
| comment-tokens-ibm-granite/granite-8b-code-base
int64 2
2.11k
| file-tokens-meta-llama/CodeLlama-7b-hf
int64 31
3.93k
| comment-tokens-meta-llama/CodeLlama-7b-hf
int64 4
2.71k
| excluded-based-on-tokenizer-Qwen/Qwen2-7B
bool 2
classes | excluded-based-on-tokenizer-bigcode/starcoder2-7b
bool 2
classes | excluded-based-on-tokenizer-google/codegemma-7b
bool 2
classes | excluded-based-on-tokenizer-ibm-granite/granite-8b-code-base
bool 2
classes | excluded-based-on-tokenizer-meta-llama/CodeLlama-7b-hf
bool 2
classes | include-for-inference
bool 2
classes |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
23221_5 | package com.company;
import java.awt.*;
public class Bg {
// 关卡数
static int level = 1;
// 目标得分
int goal = (level * 500) + 550;
// 总分
static int count = 0;
// 药水数量
static int waterNum = 3;
// 药水状态
static boolean waterFlag = false;
// 开始时间
long startTime;
// 结束时间
long endTime;
// 药水价格
int price = (int) (Math.random() * 10);
// 是否进入商店 f不购买
boolean shop = false;
// 载入图片
Image bg = Toolkit.getDefaultToolkit().getImage("imgs/bg.jpg");
Image bg1 = Toolkit.getDefaultToolkit().getImage("imgs/bg1.jpg");
Image peo = Toolkit.getDefaultToolkit().getImage("imgs/peo.png");
Image water = Toolkit.getDefaultToolkit().getImage("imgs/water.png");
// 绘制
void paintSelf(Graphics g) {
g.drawImage(bg, 0, 200, null);
g.drawImage(bg1, 0, 0, null);
switch (GameWin.state) {
case 0:
drawWord(g, 80, Color.black, "按鼠标右键开始", 100, 400);
drawWord(g, 60, Color.red, "游戏规则:", 100, 500);
drawWord(g, 30, Color.black, "点击鼠标左键放出抓钩", 100, 560);
drawWord(g, 30, Color.black, "抓住金块或石头可以点击鼠标右键", 100, 620);
drawWord(g, 30, Color.black, "使用“大力神药”快速收回金块或者爆破石头", 100, 680);
break;
case 1:
g.drawImage(peo, 310, 50, null);
drawWord(g, 30, Color.black, "分数:" + count, 30, 150);
g.drawImage(water, 550, 40, null);
drawWord(g, 30, Color.black, "×" + waterNum, 610, 90);
// 关卡数&目标得分
drawWord(g, 20, Color.black, "关卡:" + level, 30, 60);
drawWord(g, 30, Color.black, "目标:" + goal, 30, 115);
// 实时赋值
endTime = System.currentTimeMillis();
long time = 20 - (endTime - startTime) / 1000;
drawWord(g, 30, Color.black, "时间:" + (time > 0 ? time : 0), 520, 150);
break;
case 2:
g.drawImage(water, 330, 380, null);
drawWord(g, 30, Color.black, "价格:" + price, 300, 500);
drawWord(g, 30, Color.black, "是否购买“大力神药”?", 280, 550);
drawWord(g, 30, Color.black, "点击鼠标左键确认购买,右键退出商店", 100, 700);
if (shop) {
count = count - price;
waterNum++;
shop = false;
GameWin.state = 1;
startTime = System.currentTimeMillis();
}
break;
case 3:
drawWord(g, 80, Color.cyan, "失败", 300, 350);
drawWord(g, 80, Color.black, "分数:" + count, 200, 450);
drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550);
break;
case 4:
drawWord(g, 80, Color.red, "恭喜过关", 250, 350);
drawWord(g, 80, Color.black, "分数:" + count, 200, 450);
drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550);
break;
default:
}
}
// t倒计时完成,f未完成倒计时
boolean gameTime() {
long time = (endTime - startTime) / 1000;
if (time >= 20) {
return true;
}
return false;
}
// 重置元素
void reGame() {
// 关卡数
level = 1;
// 目标得分
goal = (level * 500) + 550;
// 总分
count = 0;
// 药水数量
waterNum = 3;
// 药水状态
waterFlag = false;
}
// 绘制字符串
public static void drawWord(Graphics g, int size, Color color, String str, int x, int y) {
g.setColor(color);
g.setFont(new Font("宋体", Font.BOLD, size));
g.drawString(str, x, y);
}
}
| Cikian/GoldMiner | src/com/company/Bg.java | 1,336 | // 开始时间
| line_comment | zh-cn | package com.company;
import java.awt.*;
public class Bg {
// 关卡数
static int level = 1;
// 目标得分
int goal = (level * 500) + 550;
// 总分
static int count = 0;
// 药水数量
static int waterNum = 3;
// 药水状态
static boolean waterFlag = false;
// 开始 <SUF>
long startTime;
// 结束时间
long endTime;
// 药水价格
int price = (int) (Math.random() * 10);
// 是否进入商店 f不购买
boolean shop = false;
// 载入图片
Image bg = Toolkit.getDefaultToolkit().getImage("imgs/bg.jpg");
Image bg1 = Toolkit.getDefaultToolkit().getImage("imgs/bg1.jpg");
Image peo = Toolkit.getDefaultToolkit().getImage("imgs/peo.png");
Image water = Toolkit.getDefaultToolkit().getImage("imgs/water.png");
// 绘制
void paintSelf(Graphics g) {
g.drawImage(bg, 0, 200, null);
g.drawImage(bg1, 0, 0, null);
switch (GameWin.state) {
case 0:
drawWord(g, 80, Color.black, "按鼠标右键开始", 100, 400);
drawWord(g, 60, Color.red, "游戏规则:", 100, 500);
drawWord(g, 30, Color.black, "点击鼠标左键放出抓钩", 100, 560);
drawWord(g, 30, Color.black, "抓住金块或石头可以点击鼠标右键", 100, 620);
drawWord(g, 30, Color.black, "使用“大力神药”快速收回金块或者爆破石头", 100, 680);
break;
case 1:
g.drawImage(peo, 310, 50, null);
drawWord(g, 30, Color.black, "分数:" + count, 30, 150);
g.drawImage(water, 550, 40, null);
drawWord(g, 30, Color.black, "×" + waterNum, 610, 90);
// 关卡数&目标得分
drawWord(g, 20, Color.black, "关卡:" + level, 30, 60);
drawWord(g, 30, Color.black, "目标:" + goal, 30, 115);
// 实时赋值
endTime = System.currentTimeMillis();
long time = 20 - (endTime - startTime) / 1000;
drawWord(g, 30, Color.black, "时间:" + (time > 0 ? time : 0), 520, 150);
break;
case 2:
g.drawImage(water, 330, 380, null);
drawWord(g, 30, Color.black, "价格:" + price, 300, 500);
drawWord(g, 30, Color.black, "是否购买“大力神药”?", 280, 550);
drawWord(g, 30, Color.black, "点击鼠标左键确认购买,右键退出商店", 100, 700);
if (shop) {
count = count - price;
waterNum++;
shop = false;
GameWin.state = 1;
startTime = System.currentTimeMillis();
}
break;
case 3:
drawWord(g, 80, Color.cyan, "失败", 300, 350);
drawWord(g, 80, Color.black, "分数:" + count, 200, 450);
drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550);
break;
case 4:
drawWord(g, 80, Color.red, "恭喜过关", 250, 350);
drawWord(g, 80, Color.black, "分数:" + count, 200, 450);
drawWord(g, 60, Color.black, "点击鼠标左键重新开始", 90, 550);
break;
default:
}
}
// t倒计时完成,f未完成倒计时
boolean gameTime() {
long time = (endTime - startTime) / 1000;
if (time >= 20) {
return true;
}
return false;
}
// 重置元素
void reGame() {
// 关卡数
level = 1;
// 目标得分
goal = (level * 500) + 550;
// 总分
count = 0;
// 药水数量
waterNum = 3;
// 药水状态
waterFlag = false;
}
// 绘制字符串
public static void drawWord(Graphics g, int size, Color color, String str, int x, int y) {
g.setColor(color);
g.setFont(new Font("宋体", Font.BOLD, size));
g.drawString(str, x, y);
}
}
| false | 1,236 | 5 | 1,336 | 5 | 1,370 | 4 | 1,336 | 5 | 1,637 | 7 | false | false | false | false | false | true |
15282_5 | 问题1
class Context {
//保证一个引用
private AbstractStrategy strategy;
public void setStrategy(AbstractStrategy str) {
this.strategy= str;
}
//调用策略类中的算法
public void algorithm() {
strategy.algorithm();
}
}
abstract class AbstractStrategy {
//声明抽象算法
public abstract void algorithm();
}
class ConcreteStrategyA extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
class ConcreteStrategyB extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
class ConcreteStrategyC extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
如果要添加其他算法,继续声明新类继承父类即可
问题2
使用模板方法模式 步骤不同的进行重写
class Context {
private Algorithm algorithm;
public void setAlgorithm(Algorithm algorithm) {
this.algorithm= algorithm;
}
//调用策略类中的算法
public void algorithm() {
algorithm.step1();
algorithm.step2();
algorithm.step3();
}
}
class Algorithm {
public void step1() {
System.out.println("step1的具体内容");
}
public void step2() {
System.out.println("step2的具体内容");
}
public void step3() {
System.out.println("step3的具体内容");
}
class ConcreteAlgorithmA extends Algorithm {
//算法的具体实现
public void step1() {
System.out.println("重写了算法步骤1");//A步骤1有所不同
}
}
class ConcreteAlgorithmB extends Algorithm {
//算法的具体实现
public void step2() {
System.out.println("重写了算法步骤2"); //B步骤2有所不同
}
}
class ConcreteAlgorithmC extends Algorithm {
//算法的具体实现
public void step3() {
System.out.println("重写了算法步骤3");//C步骤3有所不同
}
}
| CirillaQL/DesignPatternsHomework | 7-1.java | 565 | //算法的具体实现 | line_comment | zh-cn | 问题1
class Context {
//保证一个引用
private AbstractStrategy strategy;
public void setStrategy(AbstractStrategy str) {
this.strategy= str;
}
//调用策略类中的算法
public void algorithm() {
strategy.algorithm();
}
}
abstract class AbstractStrategy {
//声明抽象算法
public abstract void algorithm();
}
class ConcreteStrategyA extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
class ConcreteStrategyB extends AbstractStrategy {
//算法的具体实现
public void algorithm() {
System.out.println("重写");
}
}
class ConcreteStrategyC extends AbstractStrategy {
//算法 <SUF>
public void algorithm() {
System.out.println("重写");
}
}
如果要添加其他算法,继续声明新类继承父类即可
问题2
使用模板方法模式 步骤不同的进行重写
class Context {
private Algorithm algorithm;
public void setAlgorithm(Algorithm algorithm) {
this.algorithm= algorithm;
}
//调用策略类中的算法
public void algorithm() {
algorithm.step1();
algorithm.step2();
algorithm.step3();
}
}
class Algorithm {
public void step1() {
System.out.println("step1的具体内容");
}
public void step2() {
System.out.println("step2的具体内容");
}
public void step3() {
System.out.println("step3的具体内容");
}
class ConcreteAlgorithmA extends Algorithm {
//算法的具体实现
public void step1() {
System.out.println("重写了算法步骤1");//A步骤1有所不同
}
}
class ConcreteAlgorithmB extends Algorithm {
//算法的具体实现
public void step2() {
System.out.println("重写了算法步骤2"); //B步骤2有所不同
}
}
class ConcreteAlgorithmC extends Algorithm {
//算法的具体实现
public void step3() {
System.out.println("重写了算法步骤3");//C步骤3有所不同
}
}
| false | 511 | 5 | 565 | 6 | 686 | 6 | 565 | 6 | 856 | 11 | false | false | false | false | false | true |
40721_6 | package com.civitasv.spider.model.bo;
import com.civitasv.spider.model.po.PoiPo;
import com.civitasv.spider.util.BeanUtils;
import com.google.gson.annotations.SerializedName;
import lombok.*;
import lombok.experimental.Accessors;
import java.util.List;
@Getter
@Setter
@Accessors(fluent = true)
@Builder
@ToString
public class POI {
@SerializedName("status")
private final Integer status;
@SerializedName("info")
private String info;
@SerializedName("infocode")
private Integer infoCode;
@SerializedName("count")
private Integer count;
@SerializedName("pois")
private List<Info> details;
@Getter
@Accessors(fluent = true)
@AllArgsConstructor
public enum OutputFields {
ID("id", "id", "唯一ID", false, true),
NAME("name", "name", "名称", false, true),
TYPE("type", "type", "类型", false, true),
TYPE_CODE("typeCode", "typeCode", "类型编码", false, true),
BIZ_TYPE("bizType", "bizType", "行业类型", false, true),
ADDRESS("address", "address", "地址", false, true),
GCJ02_LNG("gcj02_lng", "gcj02_lng", "gcj02 格式经度", false, true),
GCJ02_LAT("gcj02_lat", "gcj02_lat", "gcj02 格式纬度", false, true),
WGS84_LNG("wgs84_lng", "wgs84_lng", "wgs84 格式经度", false, true),
WGS84_LAT("wgs84_lat", "wgs84_lat", "wgs84 格式纬度", false, true),
TEL("tel", "tel", "电话", false, true),
PROVINCE_NAME("provinceName", "province", "省份名称", false, true),
CITY_NAME("cityName", "city", "城市名称", false, true),
AD_NAME("adName", "ad", "区域名称", false, true),
POST_CODE("postCode", "postCode", "邮编", true, false),
WEBSITE("website", "website", "网址", true, false),
EMAIL("email", "email", "邮箱", true, false),
PROVINCE_CODE("provinceCode", "provCode", "省份编码", true, false),
CITY_CODE("cityCode", "cityCode", "城市编码", true, false),
AD_CODE("adCode", "adCode", "区域编码", true, false);
private final String fieldName;
private final String shapeFieldName; // shp 字段长度有限制
private final String description;
private final boolean inExtension;
private boolean checked;
public void checked(boolean checked) {
this.checked = checked;
}
@Override
public String toString() {
return description;
}
}
@Getter
@Setter
@Accessors(fluent = true)
@Builder
@ToString
public static class Info {
private transient Long id; // 对应PoiPo id
@SerializedName("id")
private Object poiId; // 唯一id 对应pid
@SerializedName("name")
private Object name; // 名称
@SerializedName("type")
private Object type; // 兴趣点类型
@SerializedName("typecode")
private Object typeCode; // 兴趣点类型编码
@SerializedName("biz_type")
private Object bizType; // 行业类型
@SerializedName("address")
private Object address; // 地址
@SerializedName("location")
private Object location; // 经纬度
@SerializedName("tel")
private Object tel; // 电话
@SerializedName("pname")
private Object provinceName; // 省份名称
@SerializedName("cityname")
private Object cityName; // 城市名称
@SerializedName("adname")
private Object adName; // 区域名称
@SerializedName("postcode")
private Object postCode; // 邮编,extensions=all时返回
@SerializedName("website")
private Object website; // 网址,extensions=all时返回
@SerializedName("email")
private Object email; // 邮箱,extensions=all时返回
@SerializedName("pcode")
private Object provinceCode; // 省份编码,extensions=all时返回
@SerializedName("citycode")
private Object cityCode; // 城市编码,extensions=all时返回
@SerializedName("adcode")
private Object adCode; // 区域编码,extensions=all时返回
public PoiPo toPoiPo(Long jobId) {
return PoiPo.builder()
.id(id)
.poiId(BeanUtils.obj2String(poiId))
.jobId(jobId)
.name(BeanUtils.obj2String(name))
.type(BeanUtils.obj2String(type))
.typeCode(BeanUtils.obj2String(typeCode))
.bizType(BeanUtils.obj2String(bizType))
.address(BeanUtils.obj2String(address))
.location(BeanUtils.obj2String(location))
.tel(BeanUtils.obj2String(tel))
.provinceName(BeanUtils.obj2String(provinceName))
.cityName(BeanUtils.obj2String(cityName))
.adName(BeanUtils.obj2String(adName))
.build();
}
public PoiPo toPoiPoWithExtensions(Long jobId) {
return PoiPo.builder()
.id(id)
.poiId(BeanUtils.obj2String(poiId))
.jobId(jobId)
.name(BeanUtils.obj2String(name))
.type(BeanUtils.obj2String(type))
.typeCode(BeanUtils.obj2String(typeCode))
.bizType(BeanUtils.obj2String(bizType))
.address(BeanUtils.obj2String(address))
.location(BeanUtils.obj2String(location))
.tel(BeanUtils.obj2String(tel))
.provinceName(BeanUtils.obj2String(provinceName))
.cityName(BeanUtils.obj2String(cityName))
.adName(BeanUtils.obj2String(adName))
.postCode(BeanUtils.obj2String(postCode))
.website(BeanUtils.obj2String(website))
.email(BeanUtils.obj2String(email))
.provinceCode(BeanUtils.obj2String(provinceCode))
.cityCode(BeanUtils.obj2String(cityCode))
.adCode(BeanUtils.obj2String(adCode))
.build();
}
}
}
| Civitasv/AMapPoi | src/main/java/com/civitasv/spider/model/bo/POI.java | 1,565 | // 经纬度 | line_comment | zh-cn | package com.civitasv.spider.model.bo;
import com.civitasv.spider.model.po.PoiPo;
import com.civitasv.spider.util.BeanUtils;
import com.google.gson.annotations.SerializedName;
import lombok.*;
import lombok.experimental.Accessors;
import java.util.List;
@Getter
@Setter
@Accessors(fluent = true)
@Builder
@ToString
public class POI {
@SerializedName("status")
private final Integer status;
@SerializedName("info")
private String info;
@SerializedName("infocode")
private Integer infoCode;
@SerializedName("count")
private Integer count;
@SerializedName("pois")
private List<Info> details;
@Getter
@Accessors(fluent = true)
@AllArgsConstructor
public enum OutputFields {
ID("id", "id", "唯一ID", false, true),
NAME("name", "name", "名称", false, true),
TYPE("type", "type", "类型", false, true),
TYPE_CODE("typeCode", "typeCode", "类型编码", false, true),
BIZ_TYPE("bizType", "bizType", "行业类型", false, true),
ADDRESS("address", "address", "地址", false, true),
GCJ02_LNG("gcj02_lng", "gcj02_lng", "gcj02 格式经度", false, true),
GCJ02_LAT("gcj02_lat", "gcj02_lat", "gcj02 格式纬度", false, true),
WGS84_LNG("wgs84_lng", "wgs84_lng", "wgs84 格式经度", false, true),
WGS84_LAT("wgs84_lat", "wgs84_lat", "wgs84 格式纬度", false, true),
TEL("tel", "tel", "电话", false, true),
PROVINCE_NAME("provinceName", "province", "省份名称", false, true),
CITY_NAME("cityName", "city", "城市名称", false, true),
AD_NAME("adName", "ad", "区域名称", false, true),
POST_CODE("postCode", "postCode", "邮编", true, false),
WEBSITE("website", "website", "网址", true, false),
EMAIL("email", "email", "邮箱", true, false),
PROVINCE_CODE("provinceCode", "provCode", "省份编码", true, false),
CITY_CODE("cityCode", "cityCode", "城市编码", true, false),
AD_CODE("adCode", "adCode", "区域编码", true, false);
private final String fieldName;
private final String shapeFieldName; // shp 字段长度有限制
private final String description;
private final boolean inExtension;
private boolean checked;
public void checked(boolean checked) {
this.checked = checked;
}
@Override
public String toString() {
return description;
}
}
@Getter
@Setter
@Accessors(fluent = true)
@Builder
@ToString
public static class Info {
private transient Long id; // 对应PoiPo id
@SerializedName("id")
private Object poiId; // 唯一id 对应pid
@SerializedName("name")
private Object name; // 名称
@SerializedName("type")
private Object type; // 兴趣点类型
@SerializedName("typecode")
private Object typeCode; // 兴趣点类型编码
@SerializedName("biz_type")
private Object bizType; // 行业类型
@SerializedName("address")
private Object address; // 地址
@SerializedName("location")
private Object location; // 经纬 <SUF>
@SerializedName("tel")
private Object tel; // 电话
@SerializedName("pname")
private Object provinceName; // 省份名称
@SerializedName("cityname")
private Object cityName; // 城市名称
@SerializedName("adname")
private Object adName; // 区域名称
@SerializedName("postcode")
private Object postCode; // 邮编,extensions=all时返回
@SerializedName("website")
private Object website; // 网址,extensions=all时返回
@SerializedName("email")
private Object email; // 邮箱,extensions=all时返回
@SerializedName("pcode")
private Object provinceCode; // 省份编码,extensions=all时返回
@SerializedName("citycode")
private Object cityCode; // 城市编码,extensions=all时返回
@SerializedName("adcode")
private Object adCode; // 区域编码,extensions=all时返回
public PoiPo toPoiPo(Long jobId) {
return PoiPo.builder()
.id(id)
.poiId(BeanUtils.obj2String(poiId))
.jobId(jobId)
.name(BeanUtils.obj2String(name))
.type(BeanUtils.obj2String(type))
.typeCode(BeanUtils.obj2String(typeCode))
.bizType(BeanUtils.obj2String(bizType))
.address(BeanUtils.obj2String(address))
.location(BeanUtils.obj2String(location))
.tel(BeanUtils.obj2String(tel))
.provinceName(BeanUtils.obj2String(provinceName))
.cityName(BeanUtils.obj2String(cityName))
.adName(BeanUtils.obj2String(adName))
.build();
}
public PoiPo toPoiPoWithExtensions(Long jobId) {
return PoiPo.builder()
.id(id)
.poiId(BeanUtils.obj2String(poiId))
.jobId(jobId)
.name(BeanUtils.obj2String(name))
.type(BeanUtils.obj2String(type))
.typeCode(BeanUtils.obj2String(typeCode))
.bizType(BeanUtils.obj2String(bizType))
.address(BeanUtils.obj2String(address))
.location(BeanUtils.obj2String(location))
.tel(BeanUtils.obj2String(tel))
.provinceName(BeanUtils.obj2String(provinceName))
.cityName(BeanUtils.obj2String(cityName))
.adName(BeanUtils.obj2String(adName))
.postCode(BeanUtils.obj2String(postCode))
.website(BeanUtils.obj2String(website))
.email(BeanUtils.obj2String(email))
.provinceCode(BeanUtils.obj2String(provinceCode))
.cityCode(BeanUtils.obj2String(cityCode))
.adCode(BeanUtils.obj2String(adCode))
.build();
}
}
}
| false | 1,482 | 5 | 1,565 | 6 | 1,607 | 4 | 1,565 | 6 | 1,932 | 7 | false | false | false | false | false | true |
34769_11 | package ali;
import java.util.Arrays;
/**
*
* @author Claudius
* 给一个正整数数组,砍掉三个数,分为四个段,查看是否存在着三个数,让这四个段之和相等。如果存在则返回true。
* 阿里的笔试题。
*/
public class NewMain {
/** 请完成下面这个函数,实现题目要求的功能 **/
/** 当然,你也可以不按照这个模板来作答,完全按照自己的想法来 ^-^ **/
static boolean resolve(int[] A) {
int length = A.length;
if (length <= 7) { //数组中数的数量至少有七个
return false;
}
//先对两个和rightSum和leftSum赋值,分别为左端与右端赋值给两段的和
for(int left = 1,right = length - 2,rightSum = A[length - 1],leftSum = A[0];left <= right - 4; ){ //从两端开始遍历,直到左端与右端下标距离
if (leftSum < rightSum) { //哪个大,移动哪个 //(必须保证中间的数还可以分为两段)
leftSum += A[left];
left++;
continue;
}else if (leftSum > rightSum) {
rightSum += A[right];
right--;
continue;
}
if(right - left + 2 <= 2*leftSum ){
return false;
}
//此时leftSum 和rightSum相等,left 和 right 分别对应需要跳过的下标
int middleLeft,middleRight,middleLeftSum;
// middleRight 代表中间最右值的下标
//将左起第一个值赋值给middleLeftSum,累加循环,直到middleLeftSum大于等于leftSum 或者 距离右端只有两个值时
for( middleLeft = left+2,middleRight = right - 1,middleLeftSum = A[left + 1];middleLeft < middleRight-1; middleLeft++){
if (middleLeftSum >= leftSum) { //如果要是相等,或者比leftSum大,则跳出循环
break;
}else if (middleLeftSum < leftSum) { //如果要是小于,则继续循环
middleLeftSum += A[middleLeft];
}
}
if (middleLeftSum < leftSum) { //小于代表着中间值加完了还是小于,所以最外圈循环再加下去会更小,没有必要再继续了
return false;
}else if (middleLeftSum == leftSum) { //相等,判断剩下的值之和是否相等,如果不相等,则继续外圈循环
int middleRightSum = 0;
//因为相等了,所以必然是从middleLeft + 1开始的,因为要空过下一个下标
for(int index = middleLeft + 1;index <= middleRight;index++){
middleRightSum += A[index];
}
//判断是否相等
if (middleRightSum == rightSum) {
return true;
}else {
continue;
}
}else { //大于,给左边继续加,然后继续循环
leftSum += A[left];
left++;
}
}
return false;
}
public static void main(String[] args){
// ArrayList<Integer> inputs = new ArrayList<Integer>();
// Scanner in = new Scanner(System.in);
// String line = in.nextLine();
// while(line != null && !line.isEmpty()) {
// int value = Integer.parseInt(line.trim());
// if(value == 0) break;
// inputs.add(value);
// line = in.nextLine();
// }
// int[] A = new int[inputs.size()];
// for(int i=0; i<inputs.size(); i++) {
// A[i] = inputs.get(i).intValue();
// }
int [] A = {2,2,5,1,2,1,1,3,1,10,1,1,1,1};
Boolean res = resolve(A);
System.out.println(String.valueOf(res));
}
} | ClaudiusJXK/SwordToOffer | java/NewMain.java | 1,056 | //如果要是小于,则继续循环 | line_comment | zh-cn | package ali;
import java.util.Arrays;
/**
*
* @author Claudius
* 给一个正整数数组,砍掉三个数,分为四个段,查看是否存在着三个数,让这四个段之和相等。如果存在则返回true。
* 阿里的笔试题。
*/
public class NewMain {
/** 请完成下面这个函数,实现题目要求的功能 **/
/** 当然,你也可以不按照这个模板来作答,完全按照自己的想法来 ^-^ **/
static boolean resolve(int[] A) {
int length = A.length;
if (length <= 7) { //数组中数的数量至少有七个
return false;
}
//先对两个和rightSum和leftSum赋值,分别为左端与右端赋值给两段的和
for(int left = 1,right = length - 2,rightSum = A[length - 1],leftSum = A[0];left <= right - 4; ){ //从两端开始遍历,直到左端与右端下标距离
if (leftSum < rightSum) { //哪个大,移动哪个 //(必须保证中间的数还可以分为两段)
leftSum += A[left];
left++;
continue;
}else if (leftSum > rightSum) {
rightSum += A[right];
right--;
continue;
}
if(right - left + 2 <= 2*leftSum ){
return false;
}
//此时leftSum 和rightSum相等,left 和 right 分别对应需要跳过的下标
int middleLeft,middleRight,middleLeftSum;
// middleRight 代表中间最右值的下标
//将左起第一个值赋值给middleLeftSum,累加循环,直到middleLeftSum大于等于leftSum 或者 距离右端只有两个值时
for( middleLeft = left+2,middleRight = right - 1,middleLeftSum = A[left + 1];middleLeft < middleRight-1; middleLeft++){
if (middleLeftSum >= leftSum) { //如果要是相等,或者比leftSum大,则跳出循环
break;
}else if (middleLeftSum < leftSum) { //如果 <SUF>
middleLeftSum += A[middleLeft];
}
}
if (middleLeftSum < leftSum) { //小于代表着中间值加完了还是小于,所以最外圈循环再加下去会更小,没有必要再继续了
return false;
}else if (middleLeftSum == leftSum) { //相等,判断剩下的值之和是否相等,如果不相等,则继续外圈循环
int middleRightSum = 0;
//因为相等了,所以必然是从middleLeft + 1开始的,因为要空过下一个下标
for(int index = middleLeft + 1;index <= middleRight;index++){
middleRightSum += A[index];
}
//判断是否相等
if (middleRightSum == rightSum) {
return true;
}else {
continue;
}
}else { //大于,给左边继续加,然后继续循环
leftSum += A[left];
left++;
}
}
return false;
}
public static void main(String[] args){
// ArrayList<Integer> inputs = new ArrayList<Integer>();
// Scanner in = new Scanner(System.in);
// String line = in.nextLine();
// while(line != null && !line.isEmpty()) {
// int value = Integer.parseInt(line.trim());
// if(value == 0) break;
// inputs.add(value);
// line = in.nextLine();
// }
// int[] A = new int[inputs.size()];
// for(int i=0; i<inputs.size(); i++) {
// A[i] = inputs.get(i).intValue();
// }
int [] A = {2,2,5,1,2,1,1,3,1,10,1,1,1,1};
Boolean res = resolve(A);
System.out.println(String.valueOf(res));
}
} | false | 931 | 7 | 1,056 | 10 | 1,047 | 8 | 1,056 | 10 | 1,422 | 21 | false | false | false | false | false | true |
56555_8 | package com.kesar.a;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
/**
*
* ClassName: AStar
* @Description: A星算法
* @author kesar
*/
public class AStar
{
public final static int BAR = 1; // 障碍值
public final static int PATH = 2; // 路径
public final static int DIRECT_VALUE = 10; // 横竖移动代价
public final static int OBLIQUE_VALUE = 14; // 斜移动代价
Queue<Node> openList = new PriorityQueue<Node>(); // 优先队列(升序)
List<Node> closeList = new ArrayList<Node>();
/**
* 开始算法
*/
public void start(MapInfo mapInfo)
{
if(mapInfo==null) return;
// clean
openList.clear();
closeList.clear();
// 开始搜索
openList.add(mapInfo.start);
moveNodes(mapInfo);
}
/**
* 移动当前结点
*/
private void moveNodes(MapInfo mapInfo)
{
while (!openList.isEmpty())
{
Node current = openList.poll();
closeList.add(current);
addNeighborNodeInOpen(mapInfo,current);
if (isCoordInClose(mapInfo.end.coord))
{
drawPath(mapInfo.maps, mapInfo.end);
break;
}
}
}
/**
* 在二维数组中绘制路径
*/
private void drawPath(int[][] maps, Node end)
{
if(end==null||maps==null) return;
System.out.println("总代价:" + end.G);
while (end != null)
{
Coord c = end.coord;
maps[c.y][c.x] = PATH;
end = end.parent;
}
}
/**
* 添加所有邻结点到open表
*/
private void addNeighborNodeInOpen(MapInfo mapInfo,Node current)
{
int x = current.coord.x;
int y = current.coord.y;
// 左
addNeighborNodeInOpen(mapInfo,current, x - 1, y, DIRECT_VALUE);
// 上
addNeighborNodeInOpen(mapInfo,current, x, y - 1, DIRECT_VALUE);
// 右
addNeighborNodeInOpen(mapInfo,current, x + 1, y, DIRECT_VALUE);
// 下
addNeighborNodeInOpen(mapInfo,current, x, y + 1, DIRECT_VALUE);
// 左上
addNeighborNodeInOpen(mapInfo,current, x - 1, y - 1, OBLIQUE_VALUE);
// 右上
addNeighborNodeInOpen(mapInfo,current, x + 1, y - 1, OBLIQUE_VALUE);
// 右下
addNeighborNodeInOpen(mapInfo,current, x + 1, y + 1, OBLIQUE_VALUE);
// 左下
addNeighborNodeInOpen(mapInfo,current, x - 1, y + 1, OBLIQUE_VALUE);
}
/**
* 添加一个邻结点到open表
*/
private void addNeighborNodeInOpen(MapInfo mapInfo,Node current, int x, int y, int value)
{
if (canAddNodeToOpen(mapInfo,x, y))
{
Node end=mapInfo.end;
Coord coord = new Coord(x, y);
int G = current.G + value; // 计算邻结点的G值
Node child = findNodeInOpen(coord);
if (child == null)
{
int H=calcH(end.coord,coord); // 计算H值
if(isEndNode(end.coord,coord))
{
child=end;
child.parent=current;
child.G=G;
child.H=H;
}
else
{
child = new Node(coord, current, G, H);
}
openList.add(child);
}
else if (child.G > G)
{
child.G = G;
child.parent = current;
openList.add(child);
}
}
}
/**
* 从Open列表中查找结点
*/
private Node findNodeInOpen(Coord coord)
{
if (coord == null || openList.isEmpty()) return null;
for (Node node : openList)
{
if (node.coord.equals(coord))
{
return node;
}
}
return null;
}
/**
* 计算H的估值:“曼哈顿”法,坐标分别取差值相加
*/
private int calcH(Coord end,Coord coord)
{
return (Math.abs(end.x - coord.x) + Math.abs(end.y - coord.y)) * DIRECT_VALUE;
}
/**
* 判断结点是否是最终结点
*/
private boolean isEndNode(Coord end,Coord coord)
{
return coord != null && end.equals(coord);
}
/**
* 判断结点能否放入Open列表
*/
private boolean canAddNodeToOpen(MapInfo mapInfo,int x, int y)
{
// 是否在地图中
if (x < 0 || x >= mapInfo.width || y < 0 || y >= mapInfo.hight) return false;
// 判断是否是不可通过的结点
if (mapInfo.maps[y][x] == BAR) return false;
// 判断结点是否存在close表
if (isCoordInClose(x, y)) return false;
return true;
}
/**
* 判断坐标是否在close表中
*/
private boolean isCoordInClose(Coord coord)
{
return coord!=null&&isCoordInClose(coord.x, coord.y);
}
/**
* 判断坐标是否在close表中
*/
private boolean isCoordInClose(int x, int y)
{
if (closeList.isEmpty()) return false;
for (Node node : closeList)
{
if (node.coord.x == x && node.coord.y == y)
{
return true;
}
}
return false;
}
}
| ClaymanTwinkle/astar | src/com/kesar/a/AStar.java | 1,621 | // 开始搜索
| line_comment | zh-cn | package com.kesar.a;
import java.util.ArrayList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
/**
*
* ClassName: AStar
* @Description: A星算法
* @author kesar
*/
public class AStar
{
public final static int BAR = 1; // 障碍值
public final static int PATH = 2; // 路径
public final static int DIRECT_VALUE = 10; // 横竖移动代价
public final static int OBLIQUE_VALUE = 14; // 斜移动代价
Queue<Node> openList = new PriorityQueue<Node>(); // 优先队列(升序)
List<Node> closeList = new ArrayList<Node>();
/**
* 开始算法
*/
public void start(MapInfo mapInfo)
{
if(mapInfo==null) return;
// clean
openList.clear();
closeList.clear();
// 开始 <SUF>
openList.add(mapInfo.start);
moveNodes(mapInfo);
}
/**
* 移动当前结点
*/
private void moveNodes(MapInfo mapInfo)
{
while (!openList.isEmpty())
{
Node current = openList.poll();
closeList.add(current);
addNeighborNodeInOpen(mapInfo,current);
if (isCoordInClose(mapInfo.end.coord))
{
drawPath(mapInfo.maps, mapInfo.end);
break;
}
}
}
/**
* 在二维数组中绘制路径
*/
private void drawPath(int[][] maps, Node end)
{
if(end==null||maps==null) return;
System.out.println("总代价:" + end.G);
while (end != null)
{
Coord c = end.coord;
maps[c.y][c.x] = PATH;
end = end.parent;
}
}
/**
* 添加所有邻结点到open表
*/
private void addNeighborNodeInOpen(MapInfo mapInfo,Node current)
{
int x = current.coord.x;
int y = current.coord.y;
// 左
addNeighborNodeInOpen(mapInfo,current, x - 1, y, DIRECT_VALUE);
// 上
addNeighborNodeInOpen(mapInfo,current, x, y - 1, DIRECT_VALUE);
// 右
addNeighborNodeInOpen(mapInfo,current, x + 1, y, DIRECT_VALUE);
// 下
addNeighborNodeInOpen(mapInfo,current, x, y + 1, DIRECT_VALUE);
// 左上
addNeighborNodeInOpen(mapInfo,current, x - 1, y - 1, OBLIQUE_VALUE);
// 右上
addNeighborNodeInOpen(mapInfo,current, x + 1, y - 1, OBLIQUE_VALUE);
// 右下
addNeighborNodeInOpen(mapInfo,current, x + 1, y + 1, OBLIQUE_VALUE);
// 左下
addNeighborNodeInOpen(mapInfo,current, x - 1, y + 1, OBLIQUE_VALUE);
}
/**
* 添加一个邻结点到open表
*/
private void addNeighborNodeInOpen(MapInfo mapInfo,Node current, int x, int y, int value)
{
if (canAddNodeToOpen(mapInfo,x, y))
{
Node end=mapInfo.end;
Coord coord = new Coord(x, y);
int G = current.G + value; // 计算邻结点的G值
Node child = findNodeInOpen(coord);
if (child == null)
{
int H=calcH(end.coord,coord); // 计算H值
if(isEndNode(end.coord,coord))
{
child=end;
child.parent=current;
child.G=G;
child.H=H;
}
else
{
child = new Node(coord, current, G, H);
}
openList.add(child);
}
else if (child.G > G)
{
child.G = G;
child.parent = current;
openList.add(child);
}
}
}
/**
* 从Open列表中查找结点
*/
private Node findNodeInOpen(Coord coord)
{
if (coord == null || openList.isEmpty()) return null;
for (Node node : openList)
{
if (node.coord.equals(coord))
{
return node;
}
}
return null;
}
/**
* 计算H的估值:“曼哈顿”法,坐标分别取差值相加
*/
private int calcH(Coord end,Coord coord)
{
return (Math.abs(end.x - coord.x) + Math.abs(end.y - coord.y)) * DIRECT_VALUE;
}
/**
* 判断结点是否是最终结点
*/
private boolean isEndNode(Coord end,Coord coord)
{
return coord != null && end.equals(coord);
}
/**
* 判断结点能否放入Open列表
*/
private boolean canAddNodeToOpen(MapInfo mapInfo,int x, int y)
{
// 是否在地图中
if (x < 0 || x >= mapInfo.width || y < 0 || y >= mapInfo.hight) return false;
// 判断是否是不可通过的结点
if (mapInfo.maps[y][x] == BAR) return false;
// 判断结点是否存在close表
if (isCoordInClose(x, y)) return false;
return true;
}
/**
* 判断坐标是否在close表中
*/
private boolean isCoordInClose(Coord coord)
{
return coord!=null&&isCoordInClose(coord.x, coord.y);
}
/**
* 判断坐标是否在close表中
*/
private boolean isCoordInClose(int x, int y)
{
if (closeList.isEmpty()) return false;
for (Node node : closeList)
{
if (node.coord.x == x && node.coord.y == y)
{
return true;
}
}
return false;
}
}
| false | 1,382 | 5 | 1,614 | 5 | 1,610 | 4 | 1,614 | 5 | 2,018 | 9 | false | false | false | false | false | true |
10127_7 | package com.mcylm.coi.realm.tools.npc;
import com.mcylm.coi.realm.model.COINpc;
import com.mcylm.coi.realm.tools.npc.impl.COIEntity;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import java.util.List;
/**
* AI的接口层,AI的基础能力
*/
public interface AI {
// 创建NPC
COIEntity create(COINpc coiNpc);
// 更新NPC
COIEntity update(COINpc coiNpc, boolean respawn);
// AI寻路
void findPath(Location location);
// 说话
void say(String message);
// 捡起地上的东西
void pickItems();
// 吃东西
void eatFood();
// 自动穿衣服
void wearClothes();
// 获取NPC附近的方块
List<Block> getNearbyBlocks(double radius);
// 获取NPC附近的生物
List<Entity> getNearByEntities(double radius);
// 移动
void move();
// 生成NPC
void spawn(Location location);
// 消除NPC
void despawn();
// 彻底清除NPC
void remove();
// 是否还或者
boolean isAlive();
// 是否被清除
boolean isRemoved();
// 获取NPC位置
Location getLocation();
default int delayTick() {
return 20;
}
}
| Clayun/coi-realm | src/main/java/com/mcylm/coi/realm/tools/npc/AI.java | 355 | // 获取NPC附近的方块 | line_comment | zh-cn | package com.mcylm.coi.realm.tools.npc;
import com.mcylm.coi.realm.model.COINpc;
import com.mcylm.coi.realm.tools.npc.impl.COIEntity;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Entity;
import java.util.List;
/**
* AI的接口层,AI的基础能力
*/
public interface AI {
// 创建NPC
COIEntity create(COINpc coiNpc);
// 更新NPC
COIEntity update(COINpc coiNpc, boolean respawn);
// AI寻路
void findPath(Location location);
// 说话
void say(String message);
// 捡起地上的东西
void pickItems();
// 吃东西
void eatFood();
// 自动穿衣服
void wearClothes();
// 获取 <SUF>
List<Block> getNearbyBlocks(double radius);
// 获取NPC附近的生物
List<Entity> getNearByEntities(double radius);
// 移动
void move();
// 生成NPC
void spawn(Location location);
// 消除NPC
void despawn();
// 彻底清除NPC
void remove();
// 是否还或者
boolean isAlive();
// 是否被清除
boolean isRemoved();
// 获取NPC位置
Location getLocation();
default int delayTick() {
return 20;
}
}
| false | 314 | 6 | 355 | 8 | 359 | 6 | 355 | 8 | 489 | 15 | false | false | false | false | false | true |
55734_2 | package com.guhao.learn.chapter6;
import java.util.*;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.*;
/**
* @Author guhao
* @DateTime 2019-12-06 8:58
* @Description
**/
public class Demo04 {
private static final List<Student> list = new ArrayList<>();
static {
//true未毕业,false毕业
list.add(new Student("酱",23,"male",99.0,true));
list.add(new Student("航",23,"male",99.0,true));
list.add(new Student("兔",23,"male",99.0,true));
list.add(new Student("汁",23,"male",99.0,true));
list.add(new Student("彬",23,"male",99.0,true));
list.add(new Student("马",23,"male",99.0,true));
list.add(new Student("虎",23,"male",99.0,true));
list.add(new Student("菜",23,"male",99.0,true));
list.add(new Student("峰",23,"male",99.0,true));
list.add(new Student("猫",23,"male",99.0,true));
list.add(new Student("狗",18,"male",100.0,false));
list.add(new Student("白",23,"male",99.0,true));
list.add(new Student("夜",23,"male",99.0,true));
list.add(new Student("风",23,"male",99.0,true));
}
public static void main(String[] args) {
//毕业,未毕业人数
Map<Boolean, Long> collect = list.stream()
.collect(partitioningBy(Student::getStatus, counting()));
System.out.println(collect);
//毕业,未毕业
Map<Boolean, Map<String, List<Student>>> collect1 = list.stream()
.collect(partitioningBy(Student::getStatus, groupingBy(Student::getName)));
System.out.println(collect1);
//毕业,未毕业
// list.stream().collect(partitioningBy(Student::getStatus, collectingAndThen(maxBy(Student::getAge),Optional::get)));
}
}
| ClearScenery/Java8-Learn | src/com/guhao/learn/chapter6/Demo04.java | 592 | //毕业,未毕业人数 | line_comment | zh-cn | package com.guhao.learn.chapter6;
import java.util.*;
import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.*;
/**
* @Author guhao
* @DateTime 2019-12-06 8:58
* @Description
**/
public class Demo04 {
private static final List<Student> list = new ArrayList<>();
static {
//true未毕业,false毕业
list.add(new Student("酱",23,"male",99.0,true));
list.add(new Student("航",23,"male",99.0,true));
list.add(new Student("兔",23,"male",99.0,true));
list.add(new Student("汁",23,"male",99.0,true));
list.add(new Student("彬",23,"male",99.0,true));
list.add(new Student("马",23,"male",99.0,true));
list.add(new Student("虎",23,"male",99.0,true));
list.add(new Student("菜",23,"male",99.0,true));
list.add(new Student("峰",23,"male",99.0,true));
list.add(new Student("猫",23,"male",99.0,true));
list.add(new Student("狗",18,"male",100.0,false));
list.add(new Student("白",23,"male",99.0,true));
list.add(new Student("夜",23,"male",99.0,true));
list.add(new Student("风",23,"male",99.0,true));
}
public static void main(String[] args) {
//毕业 <SUF>
Map<Boolean, Long> collect = list.stream()
.collect(partitioningBy(Student::getStatus, counting()));
System.out.println(collect);
//毕业,未毕业
Map<Boolean, Map<String, List<Student>>> collect1 = list.stream()
.collect(partitioningBy(Student::getStatus, groupingBy(Student::getName)));
System.out.println(collect1);
//毕业,未毕业
// list.stream().collect(partitioningBy(Student::getStatus, collectingAndThen(maxBy(Student::getAge),Optional::get)));
}
}
| false | 494 | 6 | 592 | 9 | 595 | 6 | 592 | 9 | 660 | 13 | false | false | false | false | false | true |
58142_10 | /*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.rsf.domain;
import java.util.ArrayList;
import java.util.List;
/**
* RSF Request 的化身,是封装 Request 的数据对象。
* @version : 2014年10月25日
* @author 赵永春 (zyc@hasor.net)
*/
public class RequestInfo extends OptionInfo {
private long requestID = 0; //请求ID
private short flags = 0; //标签
private long receiveTime = 0; //接收请求(本地时间戳)
private String serviceName = null; //远程服务名
private String serviceGroup = null; //远程服务分组
private String serviceVersion = null; //远程服务版本
private String targetMethod = null; //远程服务方法名
private String serializeType = null; //序列化策略
private int clientTimeout = 0; //远程调用时最大忍受等待时间
private boolean isMessage = false;//是否为消息请求
private List<String> paramTypes = null; //参数类型
private List<Object> paramValues = null; //参数值
//
//
public RequestInfo() {
this.paramTypes = new ArrayList<String>();
this.paramValues = new ArrayList<Object>();
}
/**获取请求ID。*/
public long getRequestID() {
return this.requestID;
}
/**设置请求ID。*/
public void setRequestID(long requestID) {
this.requestID = requestID;
}
/**获取flag*/
public short getFlags() {
return flags;
}
/**设置flag。*/
public void setFlags(short flags) {
this.flags = flags;
}
/**数据包到达时间*/
public void setReceiveTime(long receiveTime) {
this.receiveTime = receiveTime;
}
/**数据包到达时间*/
public long getReceiveTime() {
return this.receiveTime;
}
/**获取服务名*/
public String getServiceName() {
return this.serviceName;
}
/**设置服务名*/
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
/**获取服务分组*/
public String getServiceGroup() {
return this.serviceGroup;
}
/**设置服务分组*/
public void setServiceGroup(String serviceGroup) {
this.serviceGroup = serviceGroup;
}
/**获取服务版本*/
public String getServiceVersion() {
return this.serviceVersion;
}
/**设置服务版本*/
public void setServiceVersion(String serviceVersion) {
this.serviceVersion = serviceVersion;
}
/**获取调用的方法名*/
public String getTargetMethod() {
return this.targetMethod;
}
/**设置调用的方法名*/
public void setTargetMethod(String targetMethod) {
this.targetMethod = targetMethod;
}
/**获取序列化类型*/
public String getSerializeType() {
return this.serializeType;
}
/**设置序列化类型*/
public void setSerializeType(String serializeType) {
this.serializeType = serializeType;
}
/**获取远程客户端调用超时时间。*/
public int getClientTimeout() {
return this.clientTimeout;
}
/**设置远程客户端调用超时时间。*/
public void setClientTimeout(int clientTimeout) {
this.clientTimeout = clientTimeout;
}
/**是否为消息请求*/
public boolean isMessage() {
return isMessage;
}
/**设置是否为消息请求*/
public void setMessage(boolean message) {
isMessage = message;
}
//
/**添加请求参数。*/
public void addParameter(String paramType, Object paramValue) {
this.paramTypes.add(paramType);
this.paramValues.add(paramValue);
}
/**添加请求参数。*/
public void updateParameter(int index, String paramType, Object paramValue) {
if (index < 0 || index > this.paramTypes.size()) {
throw new IndexOutOfBoundsException("index out of range 0~" + this.paramTypes.size());
}
this.paramTypes.set(index, paramType);
this.paramValues.set(index, paramValue);
}
/**获取请求参数类型列表。*/
public List<String> getParameterTypes() {
return this.paramTypes;
}
/**获取请求参数值列表。*/
public List<Object> getParameterValues() {
return this.paramValues;
}
} | ClouGence/hasor | hasor-rsf/rsf-framework/src/main/java/net/hasor/rsf/domain/RequestInfo.java | 1,186 | //是否为消息请求 | line_comment | zh-cn | /*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.rsf.domain;
import java.util.ArrayList;
import java.util.List;
/**
* RSF Request 的化身,是封装 Request 的数据对象。
* @version : 2014年10月25日
* @author 赵永春 (zyc@hasor.net)
*/
public class RequestInfo extends OptionInfo {
private long requestID = 0; //请求ID
private short flags = 0; //标签
private long receiveTime = 0; //接收请求(本地时间戳)
private String serviceName = null; //远程服务名
private String serviceGroup = null; //远程服务分组
private String serviceVersion = null; //远程服务版本
private String targetMethod = null; //远程服务方法名
private String serializeType = null; //序列化策略
private int clientTimeout = 0; //远程调用时最大忍受等待时间
private boolean isMessage = false;//是否 <SUF>
private List<String> paramTypes = null; //参数类型
private List<Object> paramValues = null; //参数值
//
//
public RequestInfo() {
this.paramTypes = new ArrayList<String>();
this.paramValues = new ArrayList<Object>();
}
/**获取请求ID。*/
public long getRequestID() {
return this.requestID;
}
/**设置请求ID。*/
public void setRequestID(long requestID) {
this.requestID = requestID;
}
/**获取flag*/
public short getFlags() {
return flags;
}
/**设置flag。*/
public void setFlags(short flags) {
this.flags = flags;
}
/**数据包到达时间*/
public void setReceiveTime(long receiveTime) {
this.receiveTime = receiveTime;
}
/**数据包到达时间*/
public long getReceiveTime() {
return this.receiveTime;
}
/**获取服务名*/
public String getServiceName() {
return this.serviceName;
}
/**设置服务名*/
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
/**获取服务分组*/
public String getServiceGroup() {
return this.serviceGroup;
}
/**设置服务分组*/
public void setServiceGroup(String serviceGroup) {
this.serviceGroup = serviceGroup;
}
/**获取服务版本*/
public String getServiceVersion() {
return this.serviceVersion;
}
/**设置服务版本*/
public void setServiceVersion(String serviceVersion) {
this.serviceVersion = serviceVersion;
}
/**获取调用的方法名*/
public String getTargetMethod() {
return this.targetMethod;
}
/**设置调用的方法名*/
public void setTargetMethod(String targetMethod) {
this.targetMethod = targetMethod;
}
/**获取序列化类型*/
public String getSerializeType() {
return this.serializeType;
}
/**设置序列化类型*/
public void setSerializeType(String serializeType) {
this.serializeType = serializeType;
}
/**获取远程客户端调用超时时间。*/
public int getClientTimeout() {
return this.clientTimeout;
}
/**设置远程客户端调用超时时间。*/
public void setClientTimeout(int clientTimeout) {
this.clientTimeout = clientTimeout;
}
/**是否为消息请求*/
public boolean isMessage() {
return isMessage;
}
/**设置是否为消息请求*/
public void setMessage(boolean message) {
isMessage = message;
}
//
/**添加请求参数。*/
public void addParameter(String paramType, Object paramValue) {
this.paramTypes.add(paramType);
this.paramValues.add(paramValue);
}
/**添加请求参数。*/
public void updateParameter(int index, String paramType, Object paramValue) {
if (index < 0 || index > this.paramTypes.size()) {
throw new IndexOutOfBoundsException("index out of range 0~" + this.paramTypes.size());
}
this.paramTypes.set(index, paramType);
this.paramValues.set(index, paramValue);
}
/**获取请求参数类型列表。*/
public List<String> getParameterTypes() {
return this.paramTypes;
}
/**获取请求参数值列表。*/
public List<Object> getParameterValues() {
return this.paramValues;
}
} | false | 1,112 | 5 | 1,186 | 5 | 1,291 | 5 | 1,186 | 5 | 1,516 | 8 | false | false | false | false | false | true |
37126_17 | /*
* Copyright 2022-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.code13.javase.time;
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* @author <a href="https://github.com/Code-13/">code13</a>
* @date 2021/6/15 13:55
*/
class ZoneAndOffsetTest {
@DisplayName("ZoneId: 指定时区标识符并提供 Instant 和 LocalDateTime 之间转换的规则。")
static class ZoneIdTest {
@Test
@DisplayName("ZoneId")
void test1() {
// 获取所有可用的时区
Set<String> allZones = ZoneId.getAvailableZoneIds();
// 按自然顺序排序
// Create a List using the set of zones and sort it.
List<String> zoneList = new ArrayList<>(allZones);
Collections.sort(zoneList);
LocalDateTime dt = LocalDateTime.now();
for (String s : zoneList) {
ZoneId zone = ZoneId.of(s);
ZonedDateTime zonedDateTime = dt.atZone(zone);
ZoneOffset offset = zonedDateTime.getOffset();
int secondsOfHour = offset.getTotalSeconds() % (60 * 60);
String out = String.format("%35s %10s%n", zone, offset);
if (secondsOfHour != 0) {
System.out.printf(out);
}
}
}
}
/**
* 你什么时候使用 OffsetDateTime 而不是 ZonedDateTime? 如果您正在编写复杂的软件,
* 该软件根据地理位置对自己的日期和时间计算规则进行建模,或者将时间戳存储在仅跟踪格林威治/ UTC 时间的绝对偏移量的数据库中, 则可能需要使用 OffsetDateTime。另外,XML
* 和其他网络格式将日期时间传输定义为 OffsetDateTime 或 OffsetTime。
*/
@DisplayName("java.time.ZonedDateTime")
static class ZonedDateTimeTest {
// 实际上,结合了 LocalDateTime 与类 了 zoneid 类。它用于表示具有时区(地区/城市,如欧洲/巴黎)的完整日期(年,月,日)和时间(小时,分钟,秒,纳秒)。
@Test
@DisplayName("ZonedDateTime 示例")
void test1() {
// DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
DateTimeFormatter format = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
// Leaving from San Francisco on July 20, 2013, at 7:30 p.m.
// 2013-07-20 19:30:00
LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneId leavingZone = ZoneId.of("America/Los_Angeles");
ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone);
try {
String out1 = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
// Flight is 10 hours and 50 minutes, or 650 minutes
ZoneId arrivingZone = ZoneId.of("Asia/Tokyo");
// 使用美国洛杉矶出发的时间,然后换算成东京的时区,返回该时区对应的时间
ZonedDateTime arrival =
departure.withZoneSameInstant(arrivingZone).plusMinutes(650); // 在该时区的基础上加650分钟
try {
String out2 = arrival.format(format);
System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", arrival);
throw exc;
}
// 夏令时
if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) {
System.out.printf(" (%s daylight saving time will be in effect.)%n", arrivingZone);
} else {
// 标准时间
System.out.printf(" (%s standard time will be in effect.)%n", arrivingZone);
}
}
}
/**
* 结合了 LocalDateTime 与类 ZoneOffset 类。 它用于表示格林威治/ UTC 时间的偏移量 (+/-小时:分钟,例如 +06:00
* 或-)的整个日期(年,月,日)和时间(小时,分钟,秒,纳秒)08:00)。
*/
@DisplayName("java.time.OffsetDateTime")
static class OffsetDateTimeTest {
@Test
@DisplayName("OffsetDateTime")
void test1() {
LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneOffset offset = ZoneOffset.of("-08:00");
OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset);
OffsetDateTime lastThursday =
offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY));
System.out.printf(
"The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth());
}
}
/**
* 结合 LocalDateTime 与类 ZoneOffset 类。它用于表示格林威治/ UTC 时间偏移 (+/-小时:分钟,例如+06:00或-08:00)的时间(小时,分钟,秒,纳秒)。
*/
@DisplayName("java.time.OffsetTime")
static class OffsetTime {
@Test
@DisplayName("OffsetTime 示例")
void test1() {
// 一个不带任何时区的时间
LocalDateTime date = LocalDateTime.of(2018, 05, 01, 0, 0, 0);
ZonedDateTime d1 = ZonedDateTime.of(date, ZoneId.systemDefault());
ZoneOffset offset = ZoneOffset.of("+08:00");
OffsetDateTime d2 = OffsetDateTime.of(date, offset);
// 2018-05-01T00:00+08:00[GMT+08:00]
// ZoneId 带了具体的ID
System.out.println(d1);
// 2018-05-01T00:00+08:00
// 而偏移没有ID,因为多个ID对应的值有可能是一样的
System.out.println(d2);
// 那么把中国时间变成其他的时间
// 2018-04-30T20:00+04:00[Asia/Yerevan]
// 把该时间转换成指定时区了
d1.withZoneSameInstant(ZoneId.of("Asia/Yerevan"));
// 2018-05-01T00:00+04:00[Asia/Yerevan]
// 只是改变了时区
d1.withZoneSameLocal(ZoneId.of("Asia/Yerevan"));
}
}
}
| Code-13/java-stack-labs | javase/java-time/src/main/java/io/github/code13/javase/time/ZoneAndOffsetTest.java | 2,028 | // 一个不带任何时区的时间 | line_comment | zh-cn | /*
* Copyright 2022-present the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.code13.javase.time;
import java.time.DateTimeException;
import java.time.DayOfWeek;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
/**
* @author <a href="https://github.com/Code-13/">code13</a>
* @date 2021/6/15 13:55
*/
class ZoneAndOffsetTest {
@DisplayName("ZoneId: 指定时区标识符并提供 Instant 和 LocalDateTime 之间转换的规则。")
static class ZoneIdTest {
@Test
@DisplayName("ZoneId")
void test1() {
// 获取所有可用的时区
Set<String> allZones = ZoneId.getAvailableZoneIds();
// 按自然顺序排序
// Create a List using the set of zones and sort it.
List<String> zoneList = new ArrayList<>(allZones);
Collections.sort(zoneList);
LocalDateTime dt = LocalDateTime.now();
for (String s : zoneList) {
ZoneId zone = ZoneId.of(s);
ZonedDateTime zonedDateTime = dt.atZone(zone);
ZoneOffset offset = zonedDateTime.getOffset();
int secondsOfHour = offset.getTotalSeconds() % (60 * 60);
String out = String.format("%35s %10s%n", zone, offset);
if (secondsOfHour != 0) {
System.out.printf(out);
}
}
}
}
/**
* 你什么时候使用 OffsetDateTime 而不是 ZonedDateTime? 如果您正在编写复杂的软件,
* 该软件根据地理位置对自己的日期和时间计算规则进行建模,或者将时间戳存储在仅跟踪格林威治/ UTC 时间的绝对偏移量的数据库中, 则可能需要使用 OffsetDateTime。另外,XML
* 和其他网络格式将日期时间传输定义为 OffsetDateTime 或 OffsetTime。
*/
@DisplayName("java.time.ZonedDateTime")
static class ZonedDateTimeTest {
// 实际上,结合了 LocalDateTime 与类 了 zoneid 类。它用于表示具有时区(地区/城市,如欧洲/巴黎)的完整日期(年,月,日)和时间(小时,分钟,秒,纳秒)。
@Test
@DisplayName("ZonedDateTime 示例")
void test1() {
// DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM d yyyy hh:mm a");
DateTimeFormatter format = DateTimeFormatter.ofPattern("YYYY-MM-dd HH:mm:ss");
// Leaving from San Francisco on July 20, 2013, at 7:30 p.m.
// 2013-07-20 19:30:00
LocalDateTime leaving = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneId leavingZone = ZoneId.of("America/Los_Angeles");
ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone);
try {
String out1 = departure.format(format);
System.out.printf("LEAVING: %s (%s)%n", out1, leavingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", departure);
throw exc;
}
// Flight is 10 hours and 50 minutes, or 650 minutes
ZoneId arrivingZone = ZoneId.of("Asia/Tokyo");
// 使用美国洛杉矶出发的时间,然后换算成东京的时区,返回该时区对应的时间
ZonedDateTime arrival =
departure.withZoneSameInstant(arrivingZone).plusMinutes(650); // 在该时区的基础上加650分钟
try {
String out2 = arrival.format(format);
System.out.printf("ARRIVING: %s (%s)%n", out2, arrivingZone);
} catch (DateTimeException exc) {
System.out.printf("%s can't be formatted!%n", arrival);
throw exc;
}
// 夏令时
if (arrivingZone.getRules().isDaylightSavings(arrival.toInstant())) {
System.out.printf(" (%s daylight saving time will be in effect.)%n", arrivingZone);
} else {
// 标准时间
System.out.printf(" (%s standard time will be in effect.)%n", arrivingZone);
}
}
}
/**
* 结合了 LocalDateTime 与类 ZoneOffset 类。 它用于表示格林威治/ UTC 时间的偏移量 (+/-小时:分钟,例如 +06:00
* 或-)的整个日期(年,月,日)和时间(小时,分钟,秒,纳秒)08:00)。
*/
@DisplayName("java.time.OffsetDateTime")
static class OffsetDateTimeTest {
@Test
@DisplayName("OffsetDateTime")
void test1() {
LocalDateTime localDate = LocalDateTime.of(2013, Month.JULY, 20, 19, 30);
ZoneOffset offset = ZoneOffset.of("-08:00");
OffsetDateTime offsetDate = OffsetDateTime.of(localDate, offset);
OffsetDateTime lastThursday =
offsetDate.with(TemporalAdjusters.lastInMonth(DayOfWeek.THURSDAY));
System.out.printf(
"The last Thursday in July 2013 is the %sth.%n", lastThursday.getDayOfMonth());
}
}
/**
* 结合 LocalDateTime 与类 ZoneOffset 类。它用于表示格林威治/ UTC 时间偏移 (+/-小时:分钟,例如+06:00或-08:00)的时间(小时,分钟,秒,纳秒)。
*/
@DisplayName("java.time.OffsetTime")
static class OffsetTime {
@Test
@DisplayName("OffsetTime 示例")
void test1() {
// 一个 <SUF>
LocalDateTime date = LocalDateTime.of(2018, 05, 01, 0, 0, 0);
ZonedDateTime d1 = ZonedDateTime.of(date, ZoneId.systemDefault());
ZoneOffset offset = ZoneOffset.of("+08:00");
OffsetDateTime d2 = OffsetDateTime.of(date, offset);
// 2018-05-01T00:00+08:00[GMT+08:00]
// ZoneId 带了具体的ID
System.out.println(d1);
// 2018-05-01T00:00+08:00
// 而偏移没有ID,因为多个ID对应的值有可能是一样的
System.out.println(d2);
// 那么把中国时间变成其他的时间
// 2018-04-30T20:00+04:00[Asia/Yerevan]
// 把该时间转换成指定时区了
d1.withZoneSameInstant(ZoneId.of("Asia/Yerevan"));
// 2018-05-01T00:00+04:00[Asia/Yerevan]
// 只是改变了时区
d1.withZoneSameLocal(ZoneId.of("Asia/Yerevan"));
}
}
}
| false | 1,821 | 9 | 2,028 | 9 | 2,029 | 8 | 2,028 | 9 | 2,531 | 15 | false | false | false | false | false | true |
19707_15 | package pic;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
public class BarChart {
ChartPanel frame1;
public BarChart(){
CategoryDataset dataset = getDataSet();
JFreeChart chart = ChartFactory.createBarChart3D(
"水果", // 图表标题
"水果种类", // 目录轴的显示标签
"数量", // 数值轴的显示标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方向:水平、垂直
true, // 是否显示图例(对于简单的柱状图必须是false)
false, // 是否生成工具
false // 是否生成URL链接
);
//从这里开始
CategoryPlot plot=chart.getCategoryPlot();//获取图表区域对象
CategoryAxis domainAxis=plot.getDomainAxis(); //水平底部列表
domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14)); //水平底部标题
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12)); //垂直标题
ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状
rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15));
chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体
//到这里结束,虽然代码有点多,但只为一个目的,解决汉字乱码问题
frame1=new ChartPanel(chart,true); //这里也可以用chartFrame,可以直接生成一个独立的Frame
}
private static CategoryDataset getDataSet() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(100, "北京", "苹果");
dataset.addValue(100, "上海", "苹果");
dataset.addValue(100, "广州", "苹果");
dataset.addValue(200, "北京", "梨子");
dataset.addValue(200, "上海", "梨子");
dataset.addValue(200, "广州", "梨子");
dataset.addValue(300, "北京", "葡萄");
dataset.addValue(300, "上海", "葡萄");
dataset.addValue(300, "广州", "葡萄");
dataset.addValue(400, "北京", "香蕉");
dataset.addValue(400, "上海", "香蕉");
dataset.addValue(400, "广州", "香蕉");
dataset.addValue(500, "北京", "荔枝");
dataset.addValue(500, "上海", "荔枝");
dataset.addValue(500, "广州", "荔枝");
return dataset;
}
public ChartPanel getChartPanel(){
return frame1;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JFrame jframe = new JFrame();
jframe.setSize(1200,600);
jframe.setLocationRelativeTo(null);
jframe.setDefaultCloseOperation(3);
BarChart bar = new BarChart();
ChartPanel panel = bar.getChartPanel();
jframe.add(panel);
jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| CodeAsPoetry/PublicOpinion | src/pic/BarChart.java | 1,050 | //到这里结束,虽然代码有点多,但只为一个目的,解决汉字乱码问题 | line_comment | zh-cn | package pic;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
public class BarChart {
ChartPanel frame1;
public BarChart(){
CategoryDataset dataset = getDataSet();
JFreeChart chart = ChartFactory.createBarChart3D(
"水果", // 图表标题
"水果种类", // 目录轴的显示标签
"数量", // 数值轴的显示标签
dataset, // 数据集
PlotOrientation.VERTICAL, // 图表方向:水平、垂直
true, // 是否显示图例(对于简单的柱状图必须是false)
false, // 是否生成工具
false // 是否生成URL链接
);
//从这里开始
CategoryPlot plot=chart.getCategoryPlot();//获取图表区域对象
CategoryAxis domainAxis=plot.getDomainAxis(); //水平底部列表
domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14)); //水平底部标题
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,12)); //垂直标题
ValueAxis rangeAxis=plot.getRangeAxis();//获取柱状
rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15));
chart.getLegend().setItemFont(new Font("黑体", Font.BOLD, 15));
chart.getTitle().setFont(new Font("宋体",Font.BOLD,20));//设置标题字体
//到这 <SUF>
frame1=new ChartPanel(chart,true); //这里也可以用chartFrame,可以直接生成一个独立的Frame
}
private static CategoryDataset getDataSet() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
dataset.addValue(100, "北京", "苹果");
dataset.addValue(100, "上海", "苹果");
dataset.addValue(100, "广州", "苹果");
dataset.addValue(200, "北京", "梨子");
dataset.addValue(200, "上海", "梨子");
dataset.addValue(200, "广州", "梨子");
dataset.addValue(300, "北京", "葡萄");
dataset.addValue(300, "上海", "葡萄");
dataset.addValue(300, "广州", "葡萄");
dataset.addValue(400, "北京", "香蕉");
dataset.addValue(400, "上海", "香蕉");
dataset.addValue(400, "广州", "香蕉");
dataset.addValue(500, "北京", "荔枝");
dataset.addValue(500, "上海", "荔枝");
dataset.addValue(500, "广州", "荔枝");
return dataset;
}
public ChartPanel getChartPanel(){
return frame1;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
JFrame jframe = new JFrame();
jframe.setSize(1200,600);
jframe.setLocationRelativeTo(null);
jframe.setDefaultCloseOperation(3);
BarChart bar = new BarChart();
ChartPanel panel = bar.getChartPanel();
jframe.add(panel);
jframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| false | 846 | 19 | 1,050 | 23 | 958 | 21 | 1,050 | 23 | 1,340 | 41 | false | false | false | false | false | true |
53514_4 | package HOther;
import jdk.internal.org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
public class xmlDemo {
public static void main(String[] args) {
//创建一个DocumentBuilderFactory的对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//创建一个DocumentBuilder的对象
try {
//创建DocumentBuilder对象
DocumentBuilder db = dbf.newDocumentBuilder();
//通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下
Document document = db.parse("./src/HOther/book.xml");
//获取所有book节点的集合
NodeList bookList = document.getElementsByTagName("book");
//通过nodelist的getLength()方法可以获取bookList的长度
System.out.println("一共有" + bookList.getLength() + "本书");
//遍历每一个book节点
for (int i = 0; i < bookList.getLength(); i++) {
System.out.println("=================下面开始遍历第" + (i + 1) + "本书的内容=================");
//通过 item(i)方法 获取一个book节点,nodelist的索引值从0开始
Node book = bookList.item(i);
//获取book节点的所有属性集合
NamedNodeMap attrs = book.getAttributes();
System.out.println("第 " + (i + 1) + "本书共有" + attrs.getLength() + "个属性");
//遍历book的属性
for (int j = 0; j < attrs.getLength(); j++) {
//通过item(index)方法获取book节点的某一个属性
Node attr = attrs.item(j);
//获取属性名
System.out.print("属性名:" + attr.getNodeName());
//获取属性值
System.out.println("--属性值" + attr.getNodeValue());
}
//解析book节点的子节点
NodeList childNodes = book.getChildNodes();
//遍历childNodes获取每个节点的节点名和节点值
System.out.println("第" + (i+1) + "本书共有" +
childNodes.getLength() + "个子节点");
for (int k = 0; k < childNodes.getLength(); k++) {
//区分出text类型的node以及element类型的node
if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
//获取了element类型节点的节点名
System.out.print("第" + (k + 1) + "个节点的节点名:"
+ childNodes.item(k).getNodeName());
//获取了element类型节点的节点值
System.out.println("--节点值是:" + childNodes.item(k).getFirstChild().getNodeValue());
//System.out.println("--节点值是:" + childNodes.item(k).getTextContent());
}
}
System.out.println("======================结束遍历第" + (i + 1) + "本书的内容=================");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (org.xml.sax.SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| CodeCoderCoding/Java-Demo | src/HOther/xmlDemo.java | 808 | //获取所有book节点的集合 | line_comment | zh-cn | package HOther;
import jdk.internal.org.xml.sax.SAXException;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
public class xmlDemo {
public static void main(String[] args) {
//创建一个DocumentBuilderFactory的对象
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//创建一个DocumentBuilder的对象
try {
//创建DocumentBuilder对象
DocumentBuilder db = dbf.newDocumentBuilder();
//通过DocumentBuilder对象的parser方法加载books.xml文件到当前项目下
Document document = db.parse("./src/HOther/book.xml");
//获取 <SUF>
NodeList bookList = document.getElementsByTagName("book");
//通过nodelist的getLength()方法可以获取bookList的长度
System.out.println("一共有" + bookList.getLength() + "本书");
//遍历每一个book节点
for (int i = 0; i < bookList.getLength(); i++) {
System.out.println("=================下面开始遍历第" + (i + 1) + "本书的内容=================");
//通过 item(i)方法 获取一个book节点,nodelist的索引值从0开始
Node book = bookList.item(i);
//获取book节点的所有属性集合
NamedNodeMap attrs = book.getAttributes();
System.out.println("第 " + (i + 1) + "本书共有" + attrs.getLength() + "个属性");
//遍历book的属性
for (int j = 0; j < attrs.getLength(); j++) {
//通过item(index)方法获取book节点的某一个属性
Node attr = attrs.item(j);
//获取属性名
System.out.print("属性名:" + attr.getNodeName());
//获取属性值
System.out.println("--属性值" + attr.getNodeValue());
}
//解析book节点的子节点
NodeList childNodes = book.getChildNodes();
//遍历childNodes获取每个节点的节点名和节点值
System.out.println("第" + (i+1) + "本书共有" +
childNodes.getLength() + "个子节点");
for (int k = 0; k < childNodes.getLength(); k++) {
//区分出text类型的node以及element类型的node
if (childNodes.item(k).getNodeType() == Node.ELEMENT_NODE) {
//获取了element类型节点的节点名
System.out.print("第" + (k + 1) + "个节点的节点名:"
+ childNodes.item(k).getNodeName());
//获取了element类型节点的节点值
System.out.println("--节点值是:" + childNodes.item(k).getFirstChild().getNodeValue());
//System.out.println("--节点值是:" + childNodes.item(k).getTextContent());
}
}
System.out.println("======================结束遍历第" + (i + 1) + "本书的内容=================");
}
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (org.xml.sax.SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| false | 721 | 7 | 808 | 7 | 848 | 7 | 808 | 7 | 1,056 | 11 | false | false | false | false | false | true |
21911_3 | package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
/**
* @author Administrator
*/
public class Controller {
private Stage primaryStage;
@FXML
private Button startServer;
@FXML
private TextField localPath;
@FXML
private Button selectFilePath;
@FXML
private TextField port;
@FXML
private TextArea dataView;
@FXML
private ProgressBar progress;
@FXML
private Label proValue;
@FXML
private ChoiceBox bufSizeChoice;
@FXML
private Button endServer;
@FXML
private Button cleanTextArea;
private String bufStr = "1024*5";
private long bufSize;
SocketThread socketThread;
@FXML
public void cleanTextArea() {
dataView.clear();
}
@FXML
public void startServe(ActionEvent actionEvent) throws Exception {
if (!valid()) {
return;
}
init();
socketThread = new SocketThread();
socketThread.start();
endServer.setDisable(false);
startServer.setDisable(true);
new Thread(new DataViewTask(dataView, "服务启动成功。。。")).start();
LogService.logInfo("服务启动成功。。。");
}
@FXML
public void endServe(ActionEvent actionEvent) throws Exception {
if (socketThread.isAlive()) {
try {
socketThread.closeServer();
} catch (Exception e) {
LogService.logError(e.getLocalizedMessage());
}
socketThread.interrupt();
}
LogService.logInfo("服务停止。。。");
new Thread(new DataViewTask(dataView, "服务停止...")).start();
endServer.setDisable(true);
port.setEditable(true);
selectFilePath.setDisable(false);
bufSizeChoice.setDisable(false);
startServer.setDisable(false);
}
@FXML
public void selectFilePath(ActionEvent actionEvent) {
DirectoryChooser directoryChooser = new DirectoryChooser();
File file = directoryChooser.showDialog(primaryStage);
String path = file.getPath();
localPath.setText(path);
}
@FXML
public void choiceBoxBuf() {
bufStr = (String) bufSizeChoice.getSelectionModel().getSelectedItem();
}
private void init() {
switch (bufStr) {
case "1024*10":
bufSize = 1024 * 10;
break;
case "1024*100":
bufSize = 1024 * 100;
break;
default:
bufSize = 1024 * 5;
}
System.out.println(bufSize);
port.setEditable(false);
selectFilePath.setDisable(true);
bufSizeChoice.setDisable(true);
}
private boolean valid() {
String path = localPath.getText();
String portStr = port.getText();
if (portStr.length() == 0) {
LogService.logError("端口为空");
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning Dialog");
alert.setHeaderText("端口为空");
alert.setContentText("port is null");
alert.showAndWait();
return false;
}
if (path.length() == 0) {
LogService.logError("保存路径为空");
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning Dialog");
alert.setHeaderText("保存路径为空");
alert.setContentText("savePath is null");
alert.showAndWait();
return false;
}
return true;
}
/**
* 服务端
*
* @throws Exception
*/
class SocketThread extends Thread {
ServerSocket serverSocket;
boolean isClose = false;
int serverPort = Integer.valueOf(port.getText());
public void closeServer() throws IOException {
isClose = true;
new Socket("localhost",serverPort);
// serverSocket.close();
}
@Override
public void run() {
super.run();
try {
serverSocket = new ServerSocket(serverPort);
} catch (Exception e) {
LogService.logError("启动异常。。。" + e.getLocalizedMessage());
new Thread(new AlertTask(Alert.AlertType.ERROR, "启动异常", "start error" + e.getMessage())).start();
return;
}
while (!isClose) {
try {
Socket socket = serverSocket.accept();
if (isClose){
socket.close();
serverSocket.close();
break;
}
int bufferSize = 1024 * 1000;
byte[] buf = new byte[bufferSize];
//传输完成的数据长度
long donelen = 0;
//接入地址
new Thread(new DataViewTask(dataView, socket.getInetAddress().getHostAddress() + "---已连接")).start();
DataInputStream dis = new DataInputStream(socket.getInputStream());
String filePath = localPath.getText() + File.separator;
String remoteFile = dis.readUTF();
String filePathTo = filePath + remoteFile;
File file = new File(filePathTo);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
//文件长度
Long fileLen = dis.readLong();
new Thread(new DataViewTask(dataView, "开始接收文件---" + file.getName())).start();
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
int read = 0;
while (true) {
if (dis != null && socket.isConnected() && !socket.isClosed()) {
read = dis.read(buf);
}
if (read == -1) {
break;
}
donelen += read;
DecimalFormat df = new DecimalFormat("#.00");
String pro = df.format((double) donelen / fileLen);
new Thread(new ProgressTask(progress, Double.valueOf(pro))).start();
dos.write(buf, 0, read);
}
dos.flush();
if (donelen == fileLen) {
new Thread(new DataViewTask(dataView, file.getName() + "---接收完成" + System.lineSeparator())).start();
LogService.logInfo(file.getName() + "---接收完成");
} else {
LogService.logError("来自" + socket.getInetAddress().getHostName() + "的" + file.getName() + "---接收不完整已删除。");
new Thread(new DataViewTask(dataView, "来自" + socket.getInetAddress().getHostName() +
"的" + file.getName() + "---接收不完整已删除。")).start();
file.delete();
}
dis.close();
dos.close();
} catch (Exception e) {
e.printStackTrace();
LogService.logError("接收异常。。。" + e.getLocalizedMessage());
new Thread(new AlertTask(Alert.AlertType.ERROR, "接收异常", "Receive error" + e.getMessage())).start();
}
}
}
}
}
| CodeIsRunning/SocketTransServer | src/sample/Controller.java | 1,665 | //传输完成的数据长度 | line_comment | zh-cn | package sample;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.stage.DirectoryChooser;
import javafx.stage.Stage;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DecimalFormat;
/**
* @author Administrator
*/
public class Controller {
private Stage primaryStage;
@FXML
private Button startServer;
@FXML
private TextField localPath;
@FXML
private Button selectFilePath;
@FXML
private TextField port;
@FXML
private TextArea dataView;
@FXML
private ProgressBar progress;
@FXML
private Label proValue;
@FXML
private ChoiceBox bufSizeChoice;
@FXML
private Button endServer;
@FXML
private Button cleanTextArea;
private String bufStr = "1024*5";
private long bufSize;
SocketThread socketThread;
@FXML
public void cleanTextArea() {
dataView.clear();
}
@FXML
public void startServe(ActionEvent actionEvent) throws Exception {
if (!valid()) {
return;
}
init();
socketThread = new SocketThread();
socketThread.start();
endServer.setDisable(false);
startServer.setDisable(true);
new Thread(new DataViewTask(dataView, "服务启动成功。。。")).start();
LogService.logInfo("服务启动成功。。。");
}
@FXML
public void endServe(ActionEvent actionEvent) throws Exception {
if (socketThread.isAlive()) {
try {
socketThread.closeServer();
} catch (Exception e) {
LogService.logError(e.getLocalizedMessage());
}
socketThread.interrupt();
}
LogService.logInfo("服务停止。。。");
new Thread(new DataViewTask(dataView, "服务停止...")).start();
endServer.setDisable(true);
port.setEditable(true);
selectFilePath.setDisable(false);
bufSizeChoice.setDisable(false);
startServer.setDisable(false);
}
@FXML
public void selectFilePath(ActionEvent actionEvent) {
DirectoryChooser directoryChooser = new DirectoryChooser();
File file = directoryChooser.showDialog(primaryStage);
String path = file.getPath();
localPath.setText(path);
}
@FXML
public void choiceBoxBuf() {
bufStr = (String) bufSizeChoice.getSelectionModel().getSelectedItem();
}
private void init() {
switch (bufStr) {
case "1024*10":
bufSize = 1024 * 10;
break;
case "1024*100":
bufSize = 1024 * 100;
break;
default:
bufSize = 1024 * 5;
}
System.out.println(bufSize);
port.setEditable(false);
selectFilePath.setDisable(true);
bufSizeChoice.setDisable(true);
}
private boolean valid() {
String path = localPath.getText();
String portStr = port.getText();
if (portStr.length() == 0) {
LogService.logError("端口为空");
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning Dialog");
alert.setHeaderText("端口为空");
alert.setContentText("port is null");
alert.showAndWait();
return false;
}
if (path.length() == 0) {
LogService.logError("保存路径为空");
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Warning Dialog");
alert.setHeaderText("保存路径为空");
alert.setContentText("savePath is null");
alert.showAndWait();
return false;
}
return true;
}
/**
* 服务端
*
* @throws Exception
*/
class SocketThread extends Thread {
ServerSocket serverSocket;
boolean isClose = false;
int serverPort = Integer.valueOf(port.getText());
public void closeServer() throws IOException {
isClose = true;
new Socket("localhost",serverPort);
// serverSocket.close();
}
@Override
public void run() {
super.run();
try {
serverSocket = new ServerSocket(serverPort);
} catch (Exception e) {
LogService.logError("启动异常。。。" + e.getLocalizedMessage());
new Thread(new AlertTask(Alert.AlertType.ERROR, "启动异常", "start error" + e.getMessage())).start();
return;
}
while (!isClose) {
try {
Socket socket = serverSocket.accept();
if (isClose){
socket.close();
serverSocket.close();
break;
}
int bufferSize = 1024 * 1000;
byte[] buf = new byte[bufferSize];
//传输 <SUF>
long donelen = 0;
//接入地址
new Thread(new DataViewTask(dataView, socket.getInetAddress().getHostAddress() + "---已连接")).start();
DataInputStream dis = new DataInputStream(socket.getInputStream());
String filePath = localPath.getText() + File.separator;
String remoteFile = dis.readUTF();
String filePathTo = filePath + remoteFile;
File file = new File(filePathTo);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
//文件长度
Long fileLen = dis.readLong();
new Thread(new DataViewTask(dataView, "开始接收文件---" + file.getName())).start();
DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
int read = 0;
while (true) {
if (dis != null && socket.isConnected() && !socket.isClosed()) {
read = dis.read(buf);
}
if (read == -1) {
break;
}
donelen += read;
DecimalFormat df = new DecimalFormat("#.00");
String pro = df.format((double) donelen / fileLen);
new Thread(new ProgressTask(progress, Double.valueOf(pro))).start();
dos.write(buf, 0, read);
}
dos.flush();
if (donelen == fileLen) {
new Thread(new DataViewTask(dataView, file.getName() + "---接收完成" + System.lineSeparator())).start();
LogService.logInfo(file.getName() + "---接收完成");
} else {
LogService.logError("来自" + socket.getInetAddress().getHostName() + "的" + file.getName() + "---接收不完整已删除。");
new Thread(new DataViewTask(dataView, "来自" + socket.getInetAddress().getHostName() +
"的" + file.getName() + "---接收不完整已删除。")).start();
file.delete();
}
dis.close();
dos.close();
} catch (Exception e) {
e.printStackTrace();
LogService.logError("接收异常。。。" + e.getLocalizedMessage());
new Thread(new AlertTask(Alert.AlertType.ERROR, "接收异常", "Receive error" + e.getMessage())).start();
}
}
}
}
}
| false | 1,489 | 5 | 1,665 | 5 | 1,800 | 5 | 1,665 | 5 | 2,213 | 10 | false | false | false | false | false | true |
56326_10 | import java.util.ArrayList;
/**
* @Author: zzStar
* @Date: 11-29-2020 10:50
* <p>
* 树结构本身是一种天然的的组织结构,用树存储数据能更加高效地搜索。
* <p>
* 二叉树:和链表一样,动态数据结构。
* 1)、对于每一个节点,最多能分成2个节点,即左孩子和右孩子。
* 2)、没有孩子的节点称为叶子节点。
* 3)、每一个孩子节点最多只能有一个父亲节点。
* 4)、二叉树具有天然的递归结构,即每个节点的左右子树都是二叉树。
* <p>
* 注意:一个节点也是二叉树、空也是二叉树。
* <p>
* 二叉树的分类:
* 1)、满二叉树:除了叶子节点外,每个节点都有两个子节点。
* <p>
* <p>
* 二分搜索树:
* 1)、二分搜索树是一个二叉树,且其每一颗子树也是二分搜索树。
* 2)、二分搜索树的每个节点的值大于其左子树的所有节点的值,小于其右子树的所有节点的值。
* 3)、存储的元素必须有可比较性。
* 4)、通常来说,二分搜索树不包含重复元素。如果想包含重复元素的话,只需定义:
* 左子树小于等于节点;或者右子树大于等于节点。注意:数组和链表可以有重复元素。
* <p>
* 什么是遍历操作?
* 1)、遍历就是把所有的节点都访问一遍。
* 2)、访问的原因和业务相关。
* 3)、在线性结构下,遍历是极其容易的,但是在树结构中,遍历会稍微有点难度。
* <p>
* 如何对二叉树进行遍历?
* 对于遍历操作,两颗子树都要顾及。
* <p>
* 前序遍历:最自然和常用的遍历方式。规律:根左右
* 中序遍历:规律:左根右
* 后序遍历:中序遍历的结果就是我们在二叉搜索树中所有数据排序后的结果。规律:左右根。应用:为二分搜索树释放内存。
* <p>
* 心算出二叉搜索树的前中后序遍历:每一个二叉树都会被访问三次,从根节点出发,
* 前序遍历:当一个节点被访问第一次就记录它。
* 中序遍历:当一个节点被访问第二次的时候记录它。
* 后序遍历:当一个节点被访问第三次的时候才记录它。
* <p>
* 前序遍历的非递归实现(深度优先遍历):需要使用栈记录下一步被访问的元素。
* 对于二叉搜索树的非递归实现一般有两种写法:
* 1)、经典教科书写法。
* 2)、完全模拟系统调用栈的写法。
* <p>
* 层序遍历(广度优先遍历):需要使用队列记录当前出队元素的左右子节点。
* 广度优先遍历的意义:
* 1)、在于快速地查询要搜索的元素。
* 2)、更快地找到问题的解。
* 3)、常用于算法设计中——无权图最短路径。
* 4)、联想对比图的深度优先遍历与广度优先遍历。
* <p>
* 从二分搜索树中删除最小值与最大值:
* 往左走的最后一个节点即是存有最小值的节点,往右走的最后一个节点即是存有最大值的节点。
* <p>
* 删除二分搜索树种的任意元素:
* 1)、删除只有左孩子的节点。
* 2)、删除只有右孩子的节点。
* 3)、删除具有左右孩子的节点:
* 1、找到 s = min(d->right)
* s 是 d 的后继(successor)节点,也即 d 的右子树中的最小节点。
* s->right = delMin(d->right)
* s->left = d->left
* 删除 d,s 是新的子树的根。
* 2、找到 p = max(d->left)
* p 是 d 的前驱(predecessor)节点。
* <p>
* 如何高效实现 rank(E 是排名第几的元素)?
* 如何高效实现 select(查找排名第10的元素)?
* 最好的方式是实现一个维护 size 的二分搜索树:
* 给 Node 节点添加新的成员变量 size。
* 维护 depth 的二分搜索树。
* 维护 count 支持重复元素的二分搜索树。
*/
public class BSTImpl<K extends Comparable<K>, V> {
private class Node {
public K key;
public V value;
public Node left, right;
public Node(K key, V value) {
this.key = key;
this.value = value;
left = null;
right = null;
}
}
private Node root;
private int size;
public BSTImpl() {
root = null;
size = 0;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
// 向二分搜索树中添加新的元素(key, value)
public void add(K key, V value) {
root = add(root, key, value);
}
// 向以node为根的二分搜索树中插入元素(key, value),递归算法
// 返回插入新节点后二分搜索树的根
private Node add(Node node, K key, V value) {
if (node == null) {
size++;
return new Node(key, value);
}
if (key.compareTo(node.key) < 0)
node.left = add(node.left, key, value);
else if (key.compareTo(node.key) > 0)
node.right = add(node.right, key, value);
else // key.compareTo(node.key) == 0
node.value = value;
return node;
}
// 返回以node为根节点的二分搜索树中,key所在的节点
private Node getNode(Node node, K key) {
if (node == null)
return null;
if (key.equals(node.key))
return node;
else if (key.compareTo(node.key) < 0)
return getNode(node.left, key);
else // if(key.compareTo(node.key) > 0)
return getNode(node.right, key);
}
public boolean contains(K key) {
return getNode(root, key) != null;
}
public V get(K key) {
Node node = getNode(root, key);
return node == null ? null : node.value;
}
public void set(K key, V newValue) {
Node node = getNode(root, key);
if (node == null)
throw new IllegalArgumentException(key + " doesn't exist!");
node.value = newValue;
}
// 返回以node为根的二分搜索树的最小值所在的节点
private Node minimum(Node node) {
if (node.left == null)
return node;
return minimum(node.left);
}
// 删除掉以node为根的二分搜索树中的最小节点
// 返回删除节点后新的二分搜索树的根
private Node removeMin(Node node) {
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
node.left = removeMin(node.left);
return node;
}
// 从二分搜索树中删除键为key的节点
public V remove(K key) {
Node node = getNode(root, key);
if (node != null) {
root = remove(root, key);
return node.value;
}
return null;
}
private Node remove(Node node, K key) {
if (node == null)
return null;
if (key.compareTo(node.key) < 0) {
node.left = remove(node.left, key);
return node;
} else if (key.compareTo(node.key) > 0) {
node.right = remove(node.right, key);
return node;
} else { // key.compareTo(node.key) == 0
// 待删除节点左子树为空的情况
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
// 待删除节点右子树为空的情况
if (node.right == null) {
Node leftNode = node.left;
node.left = null;
size--;
return leftNode;
}
// 待删除节点左右子树均不为空的情况
// 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
Node successor = minimum(node.right);
successor.right = removeMin(node.right);
successor.left = node.left;
node.left = node.right = null;
return successor;
}
}
public static void main(String[] args) {
System.out.println("Pride and Prejudice");
ArrayList<String> words = new ArrayList<>();
if (FileOperation.readFile("pride-and-prejudice.txt", words)) {
System.out.println("Total words: " + words.size());
BSTImpl<String, Integer> map = new BSTImpl<>();
for (String word : words) {
if (map.contains(word))
map.set(word, map.get(word) + 1);
else
map.add(word, 1);
}
System.out.println("Total different words: " + map.getSize());
System.out.println("Frequency of PRIDE: " + map.get("pride"));
System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
}
System.out.println();
}
}
| CodePrometheus/Data-Structures-and-Algorithms | Tree/BSTImpl.java | 2,488 | // 从二分搜索树中删除键为key的节点 | line_comment | zh-cn | import java.util.ArrayList;
/**
* @Author: zzStar
* @Date: 11-29-2020 10:50
* <p>
* 树结构本身是一种天然的的组织结构,用树存储数据能更加高效地搜索。
* <p>
* 二叉树:和链表一样,动态数据结构。
* 1)、对于每一个节点,最多能分成2个节点,即左孩子和右孩子。
* 2)、没有孩子的节点称为叶子节点。
* 3)、每一个孩子节点最多只能有一个父亲节点。
* 4)、二叉树具有天然的递归结构,即每个节点的左右子树都是二叉树。
* <p>
* 注意:一个节点也是二叉树、空也是二叉树。
* <p>
* 二叉树的分类:
* 1)、满二叉树:除了叶子节点外,每个节点都有两个子节点。
* <p>
* <p>
* 二分搜索树:
* 1)、二分搜索树是一个二叉树,且其每一颗子树也是二分搜索树。
* 2)、二分搜索树的每个节点的值大于其左子树的所有节点的值,小于其右子树的所有节点的值。
* 3)、存储的元素必须有可比较性。
* 4)、通常来说,二分搜索树不包含重复元素。如果想包含重复元素的话,只需定义:
* 左子树小于等于节点;或者右子树大于等于节点。注意:数组和链表可以有重复元素。
* <p>
* 什么是遍历操作?
* 1)、遍历就是把所有的节点都访问一遍。
* 2)、访问的原因和业务相关。
* 3)、在线性结构下,遍历是极其容易的,但是在树结构中,遍历会稍微有点难度。
* <p>
* 如何对二叉树进行遍历?
* 对于遍历操作,两颗子树都要顾及。
* <p>
* 前序遍历:最自然和常用的遍历方式。规律:根左右
* 中序遍历:规律:左根右
* 后序遍历:中序遍历的结果就是我们在二叉搜索树中所有数据排序后的结果。规律:左右根。应用:为二分搜索树释放内存。
* <p>
* 心算出二叉搜索树的前中后序遍历:每一个二叉树都会被访问三次,从根节点出发,
* 前序遍历:当一个节点被访问第一次就记录它。
* 中序遍历:当一个节点被访问第二次的时候记录它。
* 后序遍历:当一个节点被访问第三次的时候才记录它。
* <p>
* 前序遍历的非递归实现(深度优先遍历):需要使用栈记录下一步被访问的元素。
* 对于二叉搜索树的非递归实现一般有两种写法:
* 1)、经典教科书写法。
* 2)、完全模拟系统调用栈的写法。
* <p>
* 层序遍历(广度优先遍历):需要使用队列记录当前出队元素的左右子节点。
* 广度优先遍历的意义:
* 1)、在于快速地查询要搜索的元素。
* 2)、更快地找到问题的解。
* 3)、常用于算法设计中——无权图最短路径。
* 4)、联想对比图的深度优先遍历与广度优先遍历。
* <p>
* 从二分搜索树中删除最小值与最大值:
* 往左走的最后一个节点即是存有最小值的节点,往右走的最后一个节点即是存有最大值的节点。
* <p>
* 删除二分搜索树种的任意元素:
* 1)、删除只有左孩子的节点。
* 2)、删除只有右孩子的节点。
* 3)、删除具有左右孩子的节点:
* 1、找到 s = min(d->right)
* s 是 d 的后继(successor)节点,也即 d 的右子树中的最小节点。
* s->right = delMin(d->right)
* s->left = d->left
* 删除 d,s 是新的子树的根。
* 2、找到 p = max(d->left)
* p 是 d 的前驱(predecessor)节点。
* <p>
* 如何高效实现 rank(E 是排名第几的元素)?
* 如何高效实现 select(查找排名第10的元素)?
* 最好的方式是实现一个维护 size 的二分搜索树:
* 给 Node 节点添加新的成员变量 size。
* 维护 depth 的二分搜索树。
* 维护 count 支持重复元素的二分搜索树。
*/
public class BSTImpl<K extends Comparable<K>, V> {
private class Node {
public K key;
public V value;
public Node left, right;
public Node(K key, V value) {
this.key = key;
this.value = value;
left = null;
right = null;
}
}
private Node root;
private int size;
public BSTImpl() {
root = null;
size = 0;
}
public int getSize() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
// 向二分搜索树中添加新的元素(key, value)
public void add(K key, V value) {
root = add(root, key, value);
}
// 向以node为根的二分搜索树中插入元素(key, value),递归算法
// 返回插入新节点后二分搜索树的根
private Node add(Node node, K key, V value) {
if (node == null) {
size++;
return new Node(key, value);
}
if (key.compareTo(node.key) < 0)
node.left = add(node.left, key, value);
else if (key.compareTo(node.key) > 0)
node.right = add(node.right, key, value);
else // key.compareTo(node.key) == 0
node.value = value;
return node;
}
// 返回以node为根节点的二分搜索树中,key所在的节点
private Node getNode(Node node, K key) {
if (node == null)
return null;
if (key.equals(node.key))
return node;
else if (key.compareTo(node.key) < 0)
return getNode(node.left, key);
else // if(key.compareTo(node.key) > 0)
return getNode(node.right, key);
}
public boolean contains(K key) {
return getNode(root, key) != null;
}
public V get(K key) {
Node node = getNode(root, key);
return node == null ? null : node.value;
}
public void set(K key, V newValue) {
Node node = getNode(root, key);
if (node == null)
throw new IllegalArgumentException(key + " doesn't exist!");
node.value = newValue;
}
// 返回以node为根的二分搜索树的最小值所在的节点
private Node minimum(Node node) {
if (node.left == null)
return node;
return minimum(node.left);
}
// 删除掉以node为根的二分搜索树中的最小节点
// 返回删除节点后新的二分搜索树的根
private Node removeMin(Node node) {
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
node.left = removeMin(node.left);
return node;
}
// 从二 <SUF>
public V remove(K key) {
Node node = getNode(root, key);
if (node != null) {
root = remove(root, key);
return node.value;
}
return null;
}
private Node remove(Node node, K key) {
if (node == null)
return null;
if (key.compareTo(node.key) < 0) {
node.left = remove(node.left, key);
return node;
} else if (key.compareTo(node.key) > 0) {
node.right = remove(node.right, key);
return node;
} else { // key.compareTo(node.key) == 0
// 待删除节点左子树为空的情况
if (node.left == null) {
Node rightNode = node.right;
node.right = null;
size--;
return rightNode;
}
// 待删除节点右子树为空的情况
if (node.right == null) {
Node leftNode = node.left;
node.left = null;
size--;
return leftNode;
}
// 待删除节点左右子树均不为空的情况
// 找到比待删除节点大的最小节点, 即待删除节点右子树的最小节点
// 用这个节点顶替待删除节点的位置
Node successor = minimum(node.right);
successor.right = removeMin(node.right);
successor.left = node.left;
node.left = node.right = null;
return successor;
}
}
public static void main(String[] args) {
System.out.println("Pride and Prejudice");
ArrayList<String> words = new ArrayList<>();
if (FileOperation.readFile("pride-and-prejudice.txt", words)) {
System.out.println("Total words: " + words.size());
BSTImpl<String, Integer> map = new BSTImpl<>();
for (String word : words) {
if (map.contains(word))
map.set(word, map.get(word) + 1);
else
map.add(word, 1);
}
System.out.println("Total different words: " + map.getSize());
System.out.println("Frequency of PRIDE: " + map.get("pride"));
System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
}
System.out.println();
}
}
| false | 2,210 | 14 | 2,488 | 13 | 2,470 | 13 | 2,488 | 13 | 3,556 | 23 | false | false | false | false | false | true |
40913_4 | //https://blog.csdn.net/cslbupt/article/details/53965440
动态规划过程是:每次决策依赖于当前状态,又随即引起状态的转移。一个决策序列就是在变化的状态中产生出来的,所以,这种多阶段最优化决策解决问题的过程就称为动态规划。
https://juejin.im/post/5a29d52cf265da43333e4da7
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int length1 = s1.length();
int length2 = s2.length();
int length3 = s3.length();
if (length1 + length2 != length3){
return false;//这种小判断可以大大提高程序速度
}
//声明一个二维数组dp[][];其中dp[i][j]表示s1在第个位置,s2在第j个位置,s3在遍历第i+j个位置。dp[0][0]为s1和s2都为空
boolean[][] dp = new boolean[length1 + 1][length2 + 1];
//当s1不是empty,s2为empty时。只需比较当前遍历的位置s1的字串和s3的字串是否相等
for (int i = 0; i <= length1; i++){
dp[i][0] = s1.substring(0, i).equals(s3.substring(0, i)) ? true : false;
}
//当s2不是empty,s1是empty时
for (int j = 0; j <= length2; j++){//一个一个比较是否完全一致
dp[0][j] = s2.substring(0, j).equals(s3.substring(0, j)) ? true : false;
}
//当s1和s2都不是空时。有两种情况,一种是从(i-1,j)到达(i,j)位置,如果(i-1,j)已经是交叉的了,只需比较s1的第i个位置的元素与s3的第i+j个位置的元素是否相等;另一种情况同理。
for (int i = 1; i <= length1; i++){
for (int j = 1; j <= length2; j++){
dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) ||
(dp[i][j-1] && s2.charAt(j - 1) == s3.charAt(i + j -1));
}
}
return dp[s1.length()][s2.length()];
}
}
| CodeStudyTogether/StudyAlgorithm | LeetCode/0097.java | 652 | //当s1不是empty,s2为empty时。只需比较当前遍历的位置s1的字串和s3的字串是否相等 | line_comment | zh-cn | //https://blog.csdn.net/cslbupt/article/details/53965440
动态规划过程是:每次决策依赖于当前状态,又随即引起状态的转移。一个决策序列就是在变化的状态中产生出来的,所以,这种多阶段最优化决策解决问题的过程就称为动态规划。
https://juejin.im/post/5a29d52cf265da43333e4da7
public class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int length1 = s1.length();
int length2 = s2.length();
int length3 = s3.length();
if (length1 + length2 != length3){
return false;//这种小判断可以大大提高程序速度
}
//声明一个二维数组dp[][];其中dp[i][j]表示s1在第个位置,s2在第j个位置,s3在遍历第i+j个位置。dp[0][0]为s1和s2都为空
boolean[][] dp = new boolean[length1 + 1][length2 + 1];
//当s <SUF>
for (int i = 0; i <= length1; i++){
dp[i][0] = s1.substring(0, i).equals(s3.substring(0, i)) ? true : false;
}
//当s2不是empty,s1是empty时
for (int j = 0; j <= length2; j++){//一个一个比较是否完全一致
dp[0][j] = s2.substring(0, j).equals(s3.substring(0, j)) ? true : false;
}
//当s1和s2都不是空时。有两种情况,一种是从(i-1,j)到达(i,j)位置,如果(i-1,j)已经是交叉的了,只需比较s1的第i个位置的元素与s3的第i+j个位置的元素是否相等;另一种情况同理。
for (int i = 1; i <= length1; i++){
for (int j = 1; j <= length2; j++){
dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) ||
(dp[i][j-1] && s2.charAt(j - 1) == s3.charAt(i + j -1));
}
}
return dp[s1.length()][s2.length()];
}
}
| false | 592 | 33 | 652 | 34 | 651 | 32 | 652 | 34 | 826 | 46 | false | false | false | false | false | true |
60349_4 | package acwing.basic.chapter5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* @author : CodeWater
* @create :2022-06-18-16:27
* @Function Description :285.没有上司的舞会
*/
public class _285ADanceWithoutABoss {
public static int N = 6010;
public static int n , idx ;
// 每个人的快乐指数
public static int[] happy = new int[N];
// 邻接表存储树
public static int[] h = new int[N];
public static int[] e = new int[N];
public static int[] ne = new int[N];
//状态方程,f[u][0/1]:所有从以u为根的子树中选择,并且不选/选u这个点的方案
public static int[][] f = new int[N][2];
// 因为题目没有告知根结点,所以还需要再求一下。也就是没有父结点的点
public static boolean[] has_father = new boolean[N];
public static void main( String[] args ) throws IOException {
BufferedReader br = new BufferedReader( new InputStreamReader(System.in ) );
String[] str = br.readLine().split(" ");
n = Integer.parseInt( str[0] );
// 读取初始的快乐指数 read直接读取的是一个字符
for( int i = 1 ; i <= n ; i++ ){
str = br.readLine().split(" ");
happy[i] = Integer.parseInt( str[0] );
}
//初始化头结点
Arrays.fill( h , -1 );
//读入每一条边
for( int i = 0 ; i < n - 1 ; i++ ){
//b是a的父结点
str = br.readLine().split(" ");
int a = Integer.parseInt( str[0] ), b = Integer.parseInt( str[1] );
has_father[a] = true;
add( b , a );//添加a到b的一条边
}
// //求根结点
int root = 1;
while( has_father[root] == true ) root ++;
dfs(root );
System.out.println( Math.max( f[root][0] , f[root][1] ) );
}
public static void add( int a , int b ){
e[idx] = b ; ne[idx] = h[a] ; h[a] = idx++;
}
//递归求解每个状态
public static void dfs( int u ){
//选择u结点
f[u][1] = happy[u];
for( int i = h[u] ; i != -1 ; i = ne[i] ){
//j表示u的每个儿子
int j = e[i];
dfs(j);
f[u][0] += Math.max( f[j][0] , f[j][1] );
f[u][1] += f[j][0];
}
}
}
| CodeWater404/JavaCode | Algorithm/src/acwing/basic/chapter5/_285ADanceWithoutABoss.java | 733 | // 因为题目没有告知根结点,所以还需要再求一下。也就是没有父结点的点 | line_comment | zh-cn | package acwing.basic.chapter5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* @author : CodeWater
* @create :2022-06-18-16:27
* @Function Description :285.没有上司的舞会
*/
public class _285ADanceWithoutABoss {
public static int N = 6010;
public static int n , idx ;
// 每个人的快乐指数
public static int[] happy = new int[N];
// 邻接表存储树
public static int[] h = new int[N];
public static int[] e = new int[N];
public static int[] ne = new int[N];
//状态方程,f[u][0/1]:所有从以u为根的子树中选择,并且不选/选u这个点的方案
public static int[][] f = new int[N][2];
// 因为 <SUF>
public static boolean[] has_father = new boolean[N];
public static void main( String[] args ) throws IOException {
BufferedReader br = new BufferedReader( new InputStreamReader(System.in ) );
String[] str = br.readLine().split(" ");
n = Integer.parseInt( str[0] );
// 读取初始的快乐指数 read直接读取的是一个字符
for( int i = 1 ; i <= n ; i++ ){
str = br.readLine().split(" ");
happy[i] = Integer.parseInt( str[0] );
}
//初始化头结点
Arrays.fill( h , -1 );
//读入每一条边
for( int i = 0 ; i < n - 1 ; i++ ){
//b是a的父结点
str = br.readLine().split(" ");
int a = Integer.parseInt( str[0] ), b = Integer.parseInt( str[1] );
has_father[a] = true;
add( b , a );//添加a到b的一条边
}
// //求根结点
int root = 1;
while( has_father[root] == true ) root ++;
dfs(root );
System.out.println( Math.max( f[root][0] , f[root][1] ) );
}
public static void add( int a , int b ){
e[idx] = b ; ne[idx] = h[a] ; h[a] = idx++;
}
//递归求解每个状态
public static void dfs( int u ){
//选择u结点
f[u][1] = happy[u];
for( int i = h[u] ; i != -1 ; i = ne[i] ){
//j表示u的每个儿子
int j = e[i];
dfs(j);
f[u][0] += Math.max( f[j][0] , f[j][1] );
f[u][1] += f[j][0];
}
}
}
| false | 679 | 24 | 733 | 24 | 771 | 22 | 733 | 24 | 892 | 36 | false | false | false | false | false | true |
39798_12 | package com.ssm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
/**
* created by viking on 2018/07/17
* 测试邮件发送controller
*/
@RestController
@RequestMapping("mail")
public class SendMailController {
@Autowired
private JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean
@RequestMapping("send")
public Object sendMail03(){
MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象
MimeMessageHelper mMessageHelper;
Properties prop = new Properties();
String from;
try {
//从配置文件中拿到发件人邮箱地址
prop.load(this.getClass().getResourceAsStream("/config/mail.properties"));
from = prop.get("mail.smtp.username")+"";
mMessageHelper=new MimeMessageHelper(mMessage,true);
mMessageHelper.setFrom(from);//发件人邮箱
mMessageHelper.setTo("viking_yan@163.com");//收件人邮箱
mMessageHelper.setSubject("Spring的邮件发送");//邮件的主题
mMessageHelper.setText("<p>这是使用spring的邮件功能发送的一封邮件</p><br/>" +
"<a href='https://blog.csdn.net/Mr__Viking'>打开我的博客主页</a><br/>" +
"<img src='cid:fengye'>",true);//邮件的文本内容,true表示文本以html格式打开
File file=new File("F:/img/枫叶.png");//在邮件中添加一张图片
FileSystemResource resource=new FileSystemResource(file);
mMessageHelper.addInline("fengye", resource);//这里指定一个id,在上面引用
mMessageHelper.addAttachment("枫叶.png", resource);//在邮件中添加一个附件
javaMailSender.send(mMessage);//发送邮件
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "发送成功";
}
public void sendMail(){
SimpleMailMessage smm=new SimpleMailMessage();
smm.setFrom("发件人的邮件地址");//发送人的邮件
smm.setTo("收件人的邮件地址");//接收的邮箱的地址
smm.setSubject("使用了properties,哈哈");//邮件的标题
smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有");//邮件的内容
javaMailSender.send(smm);//发送邮件
System.out.println("发送成功");
}
public void sendMail01(){
/**
* 使用另一种的方式发送邮件,然后在邮件 使html格式生效
*/
MimeMessage mm=javaMailSender.createMimeMessage();
MimeMessageHelper smm=new MimeMessageHelper(mm);
try {
smm.setFrom("发件人的邮件地址");//发送人的邮件
smm.setTo("接收的邮箱的地址");//接收的邮箱的地址
smm.setSubject("使用了properties,哈哈,猜猜我是谁?");//邮件的标题
smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有<br><a href='http://www.baidu.com'>去百度吧!</a>",true);//邮件的内容 true 是代表的html格式生效
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(mm);//发送邮件
System.out.println("发送成功");
}
public void sendMail02(){
/**
* 使用另一种的方式发送邮件,然后在邮件,发送一个照片
*/
MimeMessage mm=javaMailSender.createMimeMessage();
MimeMessageHelper smm=null;
try {
smm=new MimeMessageHelper(mm,true);
smm.setFrom("发送人的邮件");//发送人的邮件
smm.setTo("接收的邮箱的地址");//接收的邮箱的地址
smm.setSubject("你丫的吃了狗屎了,你还不发送成功");//邮件的标题 这里多此测试 有可能会导致报错,说你发送的邮件内容不合法,注意看报错码,然后在去找报错码的意思,我这里也是报错了的,我是在他们官网上面看到的
smm.setText("山东凯撒第三款<a href='http://www.baidu.com'>去百度吧!</a><img src='cid:identifier1234'>",true);//邮件的内容 true 是代表的html格式生效
File file=new File("D:/1.jpg");//发送邮件的图片
FileSystemResource resource=new FileSystemResource(file);
smm.addInline("identifier1234", resource);//这里指定一个id,在上面引用
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(mm);//发送邮件
System.out.println("发送成功");
}
}
| CoderViking/SSMDemo | src/main/java/com/ssm/controller/SendMailController.java | 1,294 | //发送邮件 | line_comment | zh-cn | package com.ssm.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
/**
* created by viking on 2018/07/17
* 测试邮件发送controller
*/
@RestController
@RequestMapping("mail")
public class SendMailController {
@Autowired
private JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean
@RequestMapping("send")
public Object sendMail03(){
MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象
MimeMessageHelper mMessageHelper;
Properties prop = new Properties();
String from;
try {
//从配置文件中拿到发件人邮箱地址
prop.load(this.getClass().getResourceAsStream("/config/mail.properties"));
from = prop.get("mail.smtp.username")+"";
mMessageHelper=new MimeMessageHelper(mMessage,true);
mMessageHelper.setFrom(from);//发件人邮箱
mMessageHelper.setTo("viking_yan@163.com");//收件人邮箱
mMessageHelper.setSubject("Spring的邮件发送");//邮件的主题
mMessageHelper.setText("<p>这是使用spring的邮件功能发送的一封邮件</p><br/>" +
"<a href='https://blog.csdn.net/Mr__Viking'>打开我的博客主页</a><br/>" +
"<img src='cid:fengye'>",true);//邮件的文本内容,true表示文本以html格式打开
File file=new File("F:/img/枫叶.png");//在邮件中添加一张图片
FileSystemResource resource=new FileSystemResource(file);
mMessageHelper.addInline("fengye", resource);//这里指定一个id,在上面引用
mMessageHelper.addAttachment("枫叶.png", resource);//在邮件中添加一个附件
javaMailSender.send(mMessage);//发送 <SUF>
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "发送成功";
}
public void sendMail(){
SimpleMailMessage smm=new SimpleMailMessage();
smm.setFrom("发件人的邮件地址");//发送人的邮件
smm.setTo("收件人的邮件地址");//接收的邮箱的地址
smm.setSubject("使用了properties,哈哈");//邮件的标题
smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有");//邮件的内容
javaMailSender.send(smm);//发送邮件
System.out.println("发送成功");
}
public void sendMail01(){
/**
* 使用另一种的方式发送邮件,然后在邮件 使html格式生效
*/
MimeMessage mm=javaMailSender.createMimeMessage();
MimeMessageHelper smm=new MimeMessageHelper(mm);
try {
smm.setFrom("发件人的邮件地址");//发送人的邮件
smm.setTo("接收的邮箱的地址");//接收的邮箱的地址
smm.setSubject("使用了properties,哈哈,猜猜我是谁?");//邮件的标题
smm.setText("骄傲骄傲骄傲骄傲家居,你收到了没有<br><a href='http://www.baidu.com'>去百度吧!</a>",true);//邮件的内容 true 是代表的html格式生效
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(mm);//发送邮件
System.out.println("发送成功");
}
public void sendMail02(){
/**
* 使用另一种的方式发送邮件,然后在邮件,发送一个照片
*/
MimeMessage mm=javaMailSender.createMimeMessage();
MimeMessageHelper smm=null;
try {
smm=new MimeMessageHelper(mm,true);
smm.setFrom("发送人的邮件");//发送人的邮件
smm.setTo("接收的邮箱的地址");//接收的邮箱的地址
smm.setSubject("你丫的吃了狗屎了,你还不发送成功");//邮件的标题 这里多此测试 有可能会导致报错,说你发送的邮件内容不合法,注意看报错码,然后在去找报错码的意思,我这里也是报错了的,我是在他们官网上面看到的
smm.setText("山东凯撒第三款<a href='http://www.baidu.com'>去百度吧!</a><img src='cid:identifier1234'>",true);//邮件的内容 true 是代表的html格式生效
File file=new File("D:/1.jpg");//发送邮件的图片
FileSystemResource resource=new FileSystemResource(file);
smm.addInline("identifier1234", resource);//这里指定一个id,在上面引用
} catch (MessagingException e) {
e.printStackTrace();
}
javaMailSender.send(mm);//发送邮件
System.out.println("发送成功");
}
}
| false | 1,111 | 3 | 1,294 | 3 | 1,266 | 3 | 1,294 | 3 | 1,795 | 7 | false | false | false | false | false | true |
61479_0 | package src;
import static src.Util.obj2int;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.exadel.flamingo.flex.amf.AMF0Body;
import flex.messaging.io.ASObject;
public class Garden {
public static final int[] MIN_LEVEL = new int[]{1,21,41,51,61,71,81,86,91,96,101,106,111,116,121};
public static final int[] MAX_LEVEL = new int[]{20,40,50,60,70,80,85,90,95,100,105,110,115,120,125};
private static int gradeToIndex(int grade){
if (grade>=1 && grade<=40) {
return (grade-1)/20;
}
if (grade>=41 && grade<=80) {
return (grade-1)/10-2;
}
if (grade>=81 && grade<=125) {
return (grade-1)/5-10;
}
return -1;
}
private static List<Integer> preferGrades = null;
private static String plantFilename = null;
private static int remainBeatCount = 5;
private static int remainToBeat = 5;
public static Document lookGarden(int grade, int pvzid, String name){
Log.logln("查看lv.%d %s(%d)的花园".formatted(grade,name,pvzid));
byte[] response = Request.sendGetRequest("/pvz/index.php/garden/index/id/%d/sig/c3f56017a56ae0e93716fdffbb3ade91?%d".formatted(
pvzid, new Date().getTime()
));
Document document = Util.parseXml(response);
return document;
}
private static int getRemainBeatCount(Document gardenDoc){
Element garden = (Element) gardenDoc.getElementsByTagName("garden").item(0);
return Integer.parseInt(garden.getAttribute("cn"));
}
private static List<Garden.Monster> getMonsters(Document gardenDoc){
Element monster = (Element) gardenDoc.getElementsByTagName("monster").item(0);
NodeList monList = monster.getElementsByTagName("mon");
List<Monster> res = new ArrayList<>();
for (int i = 0; i < monList.getLength(); i++) {
if (monList.item(i).getNodeType()==Node.ELEMENT_NODE){
Monster monst = new Monster((Element)monList.item(i));
res.add(monst);
}
}
return res;
}
static class Monster {
final int ownerId;
final int lx;
final int ly;
final String name;
public Monster(Element ele){
name = ele.getAttribute("name");
ownerId = Integer.parseInt(ele.getAttribute("owid"));
Element position = (Element)ele.getElementsByTagName("position").item(0);
lx = Integer.parseInt(position.getAttribute("lx"));
ly = Integer.parseInt(position.getAttribute("ly"));
}
}
public static boolean beatOnce(Monster monster){
Object[] value = new Object[4];
value[0] = monster.ownerId;
value[1] = monster.lx;
value[2] = monster.ly;
List<Integer> plants = Util.readIntegersFromFile(plantFilename);
if (plantFilename==null || plants==null) {
Log.logln("请先设置好花园战斗的植物!");
return false;
}
value[3] = Util.integerArr2int(plants.toArray());
byte[] req = Util.encodeAMF("api.garden.challenge", "/1", value);
Log.log("挑战%s(%d,%d)".formatted(monster.name,monster.lx,monster.ly));
byte[] response = Request.sendPostAmf(req, true);
AMF0Body body = Util.decodeAMF(response).getBody(0);
if(Response.isOnStatusException(body, true)){
return false;
}
ASObject obj = (ASObject)body.getValue();
boolean is_winning = (Boolean)obj.get("is_winning");
if (is_winning) {
int exp = obj2int(obj.get("exp"));
Log.println(" 成功,获得%d经验".formatted(exp));
String awards_key = obj.get("awards_key").toString();
GeneralBattle.getAward(awards_key);
remainToBeat--;
}else{
Log.println(" 失败");
}
return true;
}
public static boolean checkBeatOneGarden(int grade, int pvzid, String name){
Document gardenDoc = lookGarden(grade,pvzid, name);
return beatOneGarden(gardenDoc);
}
public static boolean beatOneGarden(Document gardenDoc){
List<Monster> monsters = getMonsters(gardenDoc);
int actualCount = Math.min(remainToBeat, monsters.size());
for (int i = 0; i < actualCount; i++) {
if (!beatOnce(monsters.get(i))) {
return false;
}
}
return true;
}
public static boolean gardenBattleRepeat(int count){
User me = User.getUser();
List<Friend> friendList = me.friends;
Document myGarden = lookGarden(me.grade,me.id, me.name);
remainBeatCount = getRemainBeatCount(myGarden);
if (count==-1) remainToBeat=remainBeatCount;
else remainToBeat=Math.min(count, remainBeatCount);
if (preferGrades==null) {
Log.logln("请先设置花园打怪等级优先顺序!");
return false;
}
// 按照设置的等级顺序去打
for (Integer index : preferGrades) {
if (remainToBeat<=0) return true;
if (me.grade >= MIN_LEVEL[index] && me.grade <= MAX_LEVEL[index]) {
if (!beatOneGarden(myGarden)){
return false;
}
}
List<Friend> tofight = friendList.stream().filter(new Predicate<Friend>() {
@Override
public boolean test(Friend t) {
return t.grade>=MIN_LEVEL[index]&& t.grade <= MAX_LEVEL[index];
}
}).toList();
for (Friend friend : tofight) {
if (remainToBeat<=0) return true;
if (!checkBeatOneGarden(friend.grade, friend.id_pvz, friend.name)){
return false;
}
}
}
return true;
}
public static void main(String[] args) {
if (args.length==2&&args[0].equals("battle")) {
int count;
if (args[1].equals("auto")) {
count=-1;
}else{
count=Integer.parseInt(args[1]);
}
gardenBattleRepeat(count);
return;
}
else if (args.length>=1 && args[0].equals("bgrade")){
preferGrades = new ArrayList<>();
for (int i = 1; i < args.length; i++) {
int tmpgrade = Integer.parseInt(args[i]);
preferGrades.add(gradeToIndex(tmpgrade));
}
return;
}
else if (args.length==2 && args[0].equals("bplant")){
plantFilename = args[1];
return;
}
System.out.println("args: battle auto|<count>");
System.out.println("or : bplant <plant_filename>");
System.out.println("or : bgrade <grade_to_beat>...");
}
} | CodingZn/PvzScript | src/Garden.java | 1,936 | // 按照设置的等级顺序去打 | line_comment | zh-cn | package src;
import static src.Util.obj2int;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.exadel.flamingo.flex.amf.AMF0Body;
import flex.messaging.io.ASObject;
public class Garden {
public static final int[] MIN_LEVEL = new int[]{1,21,41,51,61,71,81,86,91,96,101,106,111,116,121};
public static final int[] MAX_LEVEL = new int[]{20,40,50,60,70,80,85,90,95,100,105,110,115,120,125};
private static int gradeToIndex(int grade){
if (grade>=1 && grade<=40) {
return (grade-1)/20;
}
if (grade>=41 && grade<=80) {
return (grade-1)/10-2;
}
if (grade>=81 && grade<=125) {
return (grade-1)/5-10;
}
return -1;
}
private static List<Integer> preferGrades = null;
private static String plantFilename = null;
private static int remainBeatCount = 5;
private static int remainToBeat = 5;
public static Document lookGarden(int grade, int pvzid, String name){
Log.logln("查看lv.%d %s(%d)的花园".formatted(grade,name,pvzid));
byte[] response = Request.sendGetRequest("/pvz/index.php/garden/index/id/%d/sig/c3f56017a56ae0e93716fdffbb3ade91?%d".formatted(
pvzid, new Date().getTime()
));
Document document = Util.parseXml(response);
return document;
}
private static int getRemainBeatCount(Document gardenDoc){
Element garden = (Element) gardenDoc.getElementsByTagName("garden").item(0);
return Integer.parseInt(garden.getAttribute("cn"));
}
private static List<Garden.Monster> getMonsters(Document gardenDoc){
Element monster = (Element) gardenDoc.getElementsByTagName("monster").item(0);
NodeList monList = monster.getElementsByTagName("mon");
List<Monster> res = new ArrayList<>();
for (int i = 0; i < monList.getLength(); i++) {
if (monList.item(i).getNodeType()==Node.ELEMENT_NODE){
Monster monst = new Monster((Element)monList.item(i));
res.add(monst);
}
}
return res;
}
static class Monster {
final int ownerId;
final int lx;
final int ly;
final String name;
public Monster(Element ele){
name = ele.getAttribute("name");
ownerId = Integer.parseInt(ele.getAttribute("owid"));
Element position = (Element)ele.getElementsByTagName("position").item(0);
lx = Integer.parseInt(position.getAttribute("lx"));
ly = Integer.parseInt(position.getAttribute("ly"));
}
}
public static boolean beatOnce(Monster monster){
Object[] value = new Object[4];
value[0] = monster.ownerId;
value[1] = monster.lx;
value[2] = monster.ly;
List<Integer> plants = Util.readIntegersFromFile(plantFilename);
if (plantFilename==null || plants==null) {
Log.logln("请先设置好花园战斗的植物!");
return false;
}
value[3] = Util.integerArr2int(plants.toArray());
byte[] req = Util.encodeAMF("api.garden.challenge", "/1", value);
Log.log("挑战%s(%d,%d)".formatted(monster.name,monster.lx,monster.ly));
byte[] response = Request.sendPostAmf(req, true);
AMF0Body body = Util.decodeAMF(response).getBody(0);
if(Response.isOnStatusException(body, true)){
return false;
}
ASObject obj = (ASObject)body.getValue();
boolean is_winning = (Boolean)obj.get("is_winning");
if (is_winning) {
int exp = obj2int(obj.get("exp"));
Log.println(" 成功,获得%d经验".formatted(exp));
String awards_key = obj.get("awards_key").toString();
GeneralBattle.getAward(awards_key);
remainToBeat--;
}else{
Log.println(" 失败");
}
return true;
}
public static boolean checkBeatOneGarden(int grade, int pvzid, String name){
Document gardenDoc = lookGarden(grade,pvzid, name);
return beatOneGarden(gardenDoc);
}
public static boolean beatOneGarden(Document gardenDoc){
List<Monster> monsters = getMonsters(gardenDoc);
int actualCount = Math.min(remainToBeat, monsters.size());
for (int i = 0; i < actualCount; i++) {
if (!beatOnce(monsters.get(i))) {
return false;
}
}
return true;
}
public static boolean gardenBattleRepeat(int count){
User me = User.getUser();
List<Friend> friendList = me.friends;
Document myGarden = lookGarden(me.grade,me.id, me.name);
remainBeatCount = getRemainBeatCount(myGarden);
if (count==-1) remainToBeat=remainBeatCount;
else remainToBeat=Math.min(count, remainBeatCount);
if (preferGrades==null) {
Log.logln("请先设置花园打怪等级优先顺序!");
return false;
}
// 按照 <SUF>
for (Integer index : preferGrades) {
if (remainToBeat<=0) return true;
if (me.grade >= MIN_LEVEL[index] && me.grade <= MAX_LEVEL[index]) {
if (!beatOneGarden(myGarden)){
return false;
}
}
List<Friend> tofight = friendList.stream().filter(new Predicate<Friend>() {
@Override
public boolean test(Friend t) {
return t.grade>=MIN_LEVEL[index]&& t.grade <= MAX_LEVEL[index];
}
}).toList();
for (Friend friend : tofight) {
if (remainToBeat<=0) return true;
if (!checkBeatOneGarden(friend.grade, friend.id_pvz, friend.name)){
return false;
}
}
}
return true;
}
public static void main(String[] args) {
if (args.length==2&&args[0].equals("battle")) {
int count;
if (args[1].equals("auto")) {
count=-1;
}else{
count=Integer.parseInt(args[1]);
}
gardenBattleRepeat(count);
return;
}
else if (args.length>=1 && args[0].equals("bgrade")){
preferGrades = new ArrayList<>();
for (int i = 1; i < args.length; i++) {
int tmpgrade = Integer.parseInt(args[i]);
preferGrades.add(gradeToIndex(tmpgrade));
}
return;
}
else if (args.length==2 && args[0].equals("bplant")){
plantFilename = args[1];
return;
}
System.out.println("args: battle auto|<count>");
System.out.println("or : bplant <plant_filename>");
System.out.println("or : bgrade <grade_to_beat>...");
}
} | false | 1,711 | 11 | 1,936 | 10 | 2,017 | 9 | 1,936 | 10 | 2,264 | 19 | false | false | false | false | false | true |
23083_3 | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author WuBiao
* @date 2020/4/2 19:51
*/
public class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap<>();
for (String word : words) {
count.put(word, count.getOrDefault(word, 0) + 1);//统计每个单词出现的次数
}
List<String>[] buckets = new List[words.length + 1];
for (String word : count.keySet()) {//把词放在数组根据频率放在数组里
int num = count.get(word);
if (buckets[num] == null) {
buckets[num] = new ArrayList<>();
}
buckets[num].add(word);
}
List<String> res = new ArrayList<>();
for (int i = buckets.length - 1; i >= 0; i--) {
if (buckets[i] == null) {
continue;
}
buckets[i].sort(String::compareTo);//同一个频率按照字母序排序
if (buckets[i].size() <= k - res.size()) {//能放下的话全放下
res.addAll(buckets[i]);
} else {//放不下的话看能放下多少
res.addAll(buckets[i].subList(0, k - res.size()));
}
}
return res;
}
} | ColdPepsi/Leetcode | 692-前K个高频单词/src/main/java/Solution.java | 364 | //同一个频率按照字母序排序 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author WuBiao
* @date 2020/4/2 19:51
*/
public class Solution {
public List<String> topKFrequent(String[] words, int k) {
Map<String, Integer> count = new HashMap<>();
for (String word : words) {
count.put(word, count.getOrDefault(word, 0) + 1);//统计每个单词出现的次数
}
List<String>[] buckets = new List[words.length + 1];
for (String word : count.keySet()) {//把词放在数组根据频率放在数组里
int num = count.get(word);
if (buckets[num] == null) {
buckets[num] = new ArrayList<>();
}
buckets[num].add(word);
}
List<String> res = new ArrayList<>();
for (int i = buckets.length - 1; i >= 0; i--) {
if (buckets[i] == null) {
continue;
}
buckets[i].sort(String::compareTo);//同一 <SUF>
if (buckets[i].size() <= k - res.size()) {//能放下的话全放下
res.addAll(buckets[i]);
} else {//放不下的话看能放下多少
res.addAll(buckets[i].subList(0, k - res.size()));
}
}
return res;
}
} | false | 314 | 7 | 364 | 10 | 378 | 7 | 364 | 10 | 445 | 21 | false | false | false | false | false | true |
32026_11 | package lee.devis.joker;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import java.util.ArrayList;
import lee.devis.joker.MyView.PathView;
import lee.devis.joker.utility.MyToaster;
public class MainActivity extends FragmentActivity implements NewestFragment.OnFragmentInteractionListener,
HotFragment.OnFragmentInteractionListener, PictureFragment.OnFragmentInteractionListener,
lee.devis.joker.MyView.PathView.OnItemClickListener {
// 页面列表
private ArrayList<android.support.v4.app.Fragment> fragmentList;
// 标题列表
ArrayList<String> titleList = new ArrayList<String>();
private PagerTitleStrip pagerTitleStrip;
private long myTime;// 两次返回的间隔
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
/* 通过pagerTabStrip可以设置标题的属性 */
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagertab);
// 设置下划线的颜色
// pagerTabStrip.setTabIndicatorColor(getResources().getColor(android.R.color.holo_green_dark));
pagerTabStrip.setTabIndicatorColor(Color.RED);
pagerTabStrip.setPadding(18, 18, 18, 18);
// 文字颜色
pagerTabStrip.setTextColor(Color.WHITE);
// 设置背景的颜色
pagerTabStrip.setBackgroundColor(Color.BLACK);
// pagerTitleStrip=(PagerTitleStrip) findViewById(R.id.pagertab);
// //设置背景的颜色
// pagerTitleStrip.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
NewestFragment newestFragment = new NewestFragment();
HotFragment hotFragment = new HotFragment();
PictureFragment pictureFragment = new PictureFragment();
fragmentList = new ArrayList<android.support.v4.app.Fragment>();
fragmentList.add(newestFragment);
fragmentList.add(hotFragment);
fragmentList.add(pictureFragment);
titleList.add("最新糗事");
titleList.add("最热段子");
titleList.add("图说真相");
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyViewPagerAdapter(fragmentManager));
viewPager.setOffscreenPageLimit(3);
setupView();
}
@Override
public void onFragmentInteraction(Uri uri) {
}
public class MyViewPagerAdapter extends FragmentStatePagerAdapter {
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
return fragmentList.get(arg0);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
// 双击退出
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if ((System.currentTimeMillis() - myTime) > 2000) {// 两次按下的时间间隔如果小于2秒就退出,大于2秒就再次提示
MyToaster.showToast(this, "再按一次返回键退出程序");
myTime = System.currentTimeMillis();// 获取当前系统时间
} else {
MyToaster.showToast(this, "客观慢走,欢迎再来哟~");
finish();// 退出应用
// System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
// path菜单初始化
private void setupView() {
PathView mPathView = (PathView) findViewById(R.id.mPathView);
ImageButton startMenu = new ImageButton(this);
startMenu.setBackgroundResource(R.drawable.start_menu_btn);
mPathView.setStartMenu(startMenu);
int[] drawableIds = new int[] { R.drawable.menu_contact, R.drawable.menu_background, R.drawable.menu_native,
R.drawable.menu_net };
View[] items = new View[drawableIds.length];
for (int i = 0; i < drawableIds.length; i++) {
ImageButton button = new ImageButton(this);
button.setBackgroundResource(drawableIds[i]);
items[i] = button;
}
mPathView.setItems(items);
mPathView.setOnItemClickListener(this);
}
@Override
public void onItemClick(View view, int position) {
}
}
| ColorfulCat/Joker | src/lee/devis/joker/MainActivity.java | 1,365 | // 双击退出 | line_comment | zh-cn | package lee.devis.joker;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.PagerTitleStrip;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageButton;
import java.util.ArrayList;
import lee.devis.joker.MyView.PathView;
import lee.devis.joker.utility.MyToaster;
public class MainActivity extends FragmentActivity implements NewestFragment.OnFragmentInteractionListener,
HotFragment.OnFragmentInteractionListener, PictureFragment.OnFragmentInteractionListener,
lee.devis.joker.MyView.PathView.OnItemClickListener {
// 页面列表
private ArrayList<android.support.v4.app.Fragment> fragmentList;
// 标题列表
ArrayList<String> titleList = new ArrayList<String>();
private PagerTitleStrip pagerTitleStrip;
private long myTime;// 两次返回的间隔
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
/* 通过pagerTabStrip可以设置标题的属性 */
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagertab);
// 设置下划线的颜色
// pagerTabStrip.setTabIndicatorColor(getResources().getColor(android.R.color.holo_green_dark));
pagerTabStrip.setTabIndicatorColor(Color.RED);
pagerTabStrip.setPadding(18, 18, 18, 18);
// 文字颜色
pagerTabStrip.setTextColor(Color.WHITE);
// 设置背景的颜色
pagerTabStrip.setBackgroundColor(Color.BLACK);
// pagerTitleStrip=(PagerTitleStrip) findViewById(R.id.pagertab);
// //设置背景的颜色
// pagerTitleStrip.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_dark));
NewestFragment newestFragment = new NewestFragment();
HotFragment hotFragment = new HotFragment();
PictureFragment pictureFragment = new PictureFragment();
fragmentList = new ArrayList<android.support.v4.app.Fragment>();
fragmentList.add(newestFragment);
fragmentList.add(hotFragment);
fragmentList.add(pictureFragment);
titleList.add("最新糗事");
titleList.add("最热段子");
titleList.add("图说真相");
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyViewPagerAdapter(fragmentManager));
viewPager.setOffscreenPageLimit(3);
setupView();
}
@Override
public void onFragmentInteraction(Uri uri) {
}
public class MyViewPagerAdapter extends FragmentStatePagerAdapter {
public MyViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int arg0) {
return fragmentList.get(arg0);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return titleList.get(position);
}
}
// 双击 <SUF>
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if ((System.currentTimeMillis() - myTime) > 2000) {// 两次按下的时间间隔如果小于2秒就退出,大于2秒就再次提示
MyToaster.showToast(this, "再按一次返回键退出程序");
myTime = System.currentTimeMillis();// 获取当前系统时间
} else {
MyToaster.showToast(this, "客观慢走,欢迎再来哟~");
finish();// 退出应用
// System.exit(0);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
// path菜单初始化
private void setupView() {
PathView mPathView = (PathView) findViewById(R.id.mPathView);
ImageButton startMenu = new ImageButton(this);
startMenu.setBackgroundResource(R.drawable.start_menu_btn);
mPathView.setStartMenu(startMenu);
int[] drawableIds = new int[] { R.drawable.menu_contact, R.drawable.menu_background, R.drawable.menu_native,
R.drawable.menu_net };
View[] items = new View[drawableIds.length];
for (int i = 0; i < drawableIds.length; i++) {
ImageButton button = new ImageButton(this);
button.setBackgroundResource(drawableIds[i]);
items[i] = button;
}
mPathView.setItems(items);
mPathView.setOnItemClickListener(this);
}
@Override
public void onItemClick(View view, int position) {
}
}
| false | 1,058 | 5 | 1,365 | 5 | 1,309 | 4 | 1,365 | 5 | 1,672 | 8 | false | false | false | false | false | true |
49653_14 | package cn.tencent.DiscuzMob.net;
/**
* Created by cg on 2017/4/10.
*/
public class AppNetConfig {
public static final String BASE_ADDRESS = "https://guanjia.comsenz-service.com/"; //【注意】更改BASE_ADDRESS的时候,要搜索全局替换, 因为JS中也有。
// public static final String BASE_ADDRESS = "https://bbs.comsenz-service.com/"; //正式服务器
public String ChangeUrl=BASE_ADDRESS;
public String getChangeUrl() {
return ChangeUrl;
}
public void setChangeUrl(String changeUrl) {
ChangeUrl = changeUrl;
}
public static final String IMGURL = BASE_ADDRESS;
public static final String IMGURL1 = BASE_ADDRESS;
public static final String BASEURL = BASE_ADDRESS + "api/mobile/";
public static final String LIVEBASEURL = "http://bbs.wsq.comsenz-service.com/newwsq/forum.php";
public static final String LOGOURL = IMGURL1 + "static/image/common/logo.png";
public static final String IMAGES = BASEURL + "?module=iwechat&data=json&version=5&mobiletype=Android";//轮播图
public static final String ALLFORUM = BASEURL + "?module=forumindex&version=5&debug=1&mobiletype=Android";//全部版块
public static final String HOTFORUM = BASEURL + "?module=hotforum&version=5&mobiletype=Android";//热门版块
public static final String HOTPOST = BASEURL + "?module=hotthread&version=4&mobiletype=IOS&ios=1";//热帖
public static final String QUESTION = BASEURL + "?module=secure&version=5&mobiletype=Android&type=";//获取验证码/问题
public static final String LOGIN = BASEURL + "?module=login&version=5&&loginfield=auto&mobiletype=Android";//登录
public static final String LOGIN1 = BASEURL + "?module=login&loginsubmit=yes&version=5&mapifrom=wx&charset=utf-8";//登录
public static final String USERINFO1 = BASEURL + "?module=profile&version=4&loginsubmit=yes&mobiletype=Android";//用户信息
public static final String USERINFO = BASEURL + "?module=profile&version=5&loginsubmit=yes&mobiletype=Android";//用户信息
public static final String MYFRIEND = BASEURL + "?module=friend&checkavatar=1&version=4&uid=";//我的好友
public static final String MYFAV = BASEURL + "?module=myfavforum&version=1&android=1&debug=1";//我收藏的版块
public static final String MYFAVTHREAD = BASEURL + "?module=myfavthread&version=1&android=1&debug=1";//我收藏的帖子
public static final String SYSTEM_MESSAGE = BASEURL + "?module=mypm&filter=announcepm&version=5&mobiletype=Android&page=";//系统消息
public static final String PRIVATE_LETTER = BASEURL + "?module=mypm&touid=2&page=1&version=4&mobiletype=IOS&ios=1&debug=1";//我的消息————>私信
public static final String MESSAGE_REPLIES = BASEURL + "?module=mynoticelist&mapifrom=android";//我的消息--->回复
public static final String THEME = BASEURL + "?module=mythread&version=5&mobiletype=Android&type=thread";//我的主题
// public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复
public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复
public static final String COLLECTION_BANKUAI = BASEURL + "?module=favorite&version=5&type=forum";//点击收藏板块
public static final String HISTHME = BASEURL + "?module=userthread&version=5&android=1&debug=1&mobiletype=Android";//他的回复
public static final String CONVERSATION = BASEURL + "?module=mypm&subop=view&version=5&mobiletype=Android&checkavatar=1&Android=1&smiley=no&convimg=1";//会话详情
public static final String UNCOLLECTION = BASEURL + "?module=favorite&version=5&op=delete&type=forum&mobiletype=Android&id=";//点击取消收藏
public static final String REGISTER = BASEURL + "?version=5®submit=yes&module=register&";//普通注册
public static final String GETREGISTER = BASEURL + "?version=5&module=check";//普通注册
public static final String REGISTERBANGDING = BASEURL + "?version=5&module=weiqqregister";
public static final String COMMENT = BASEURL + "?module=sendreply&version=5&replysubmit=yes&mobiletype=Android&mapifrom=android";//帖子详情跟帖
public static final String SEARCH = BASEURL + "?module=search&version=5&android=1";//搜索
public static final String JURISDICTION = BASEURL + "?module=newthread&submodule=checkpost&debug=1&version=1";//检查权限
public static final String ACTIVITYTHRADF = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//活动帖
public static final String VOTETHREAD = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//投票贴
public static final String THREAD = BASEURL + "?module=newthread&version=5&android=1&debug=1&topicsubmit=yes&fid=";//普通帖
public static final String QUOTE = BASEURL + "?module=sendreply&version=3";//回复引用
public static final String PRAISETHREAD = BASEURL + "?module=recommend&version=4";//帖子点赞
public static final String COLLECTTHEAD = BASEURL + "?module=favorite&version=5&type=thread&id=";//收藏帖子http://10.0.6.58/api/mobile/version=4&android=1&debug=1&module=favthread&id=46&favoritesubmit=true
public static final String UNCOLLECTTHEAD = BASEURL + "?module=favorite&version=5&op=delete&mobiletype=Android&id=";//取消收藏帖子
public static final String JOINACTIVITY = BASEURL + "?module=activityapplies&version=5&activitysubmit=true";//参加活动
public static final String DELETELETTER = BASEURL + "?module=delpm&version=5&deletesubmit=1";//删除我的私信
public static final String DELETEMESSAGE = BASEURL + "?version=5&module=delpmview&deletesubmit=1";//删除聊天记录
public static final String LIVETHREAD = BASEURL + "?module=livethread&version=5&mobiletype=Android";//直播列表
public static final String LIVETOADY = BASEURL + "?module=recommon_livethread&version=5&mobiletype=Android";//直播推荐
public static final String LIVEDETIAL = BASEURL + "?version=5&ppp=10&module=viewthread&ordertype=1&submodule=checkpost&mobiletype=Android";//直播
public static final String INTERACTION = BASEURL + "?module=threadreply&version=5&mobiletype=Android&ppp=10";
public static final String RECOMMEND = BASEURL + "?module=recommon_thread&version=5&mobiletype=Android&android=1";//推荐
public static final String ESSENCE = BASEURL + "?module=forumguide&view=digest&version=5&type=digest&mobiletype=Android&page=";//精华帖
public static final String NEW = BASEURL + "?module=forumguide&view=newthread&version=5&type=digest&mobiletype=Android&page=";//最新帖
public static final String MYTHRED = BASEURL + "?module=mynotelist&view=mypost&type=post&version=5&mobiletype=Android";//我的帖子
public static final String MYCOMMON = BASEURL + "?module=mynotelist&view=mypost&type=pcomment&version=3&mobiletype=Android";//点评
public static final String NEWS = BASEURL + "?module=notes&version=5&mobiletype=Android";//是否有新的消息
public static final String MYACTVITY = BASEURL + "?module=mynotelist&view=mypost&type=activity&version=3&mobiletype=Android";//我的活动
public static final String MYREWARD = BASEURL + "?module=mynotelist&view=mypost&type=reward&version=3&mobiletype=Android";//悬赏
public static final String GOODS = BASEURL + "?module=mynotelist&view=mypost&type=goods&version=3&mobiletype=Android";//商品
public static final String MENTIONME = BASEURL + "?module=mynotelist&view=mypost&type=at&version=3&mobiletype=Android";//提到我的
public static final String MYCALL = BASEURL + "?module=mynotelist&view=interactive&type=post&version=3&mobiletype=Android";//打招呼
public static final String myFriends = BASEURL + "?module=mynotelist&view=interactive&type=friend&version=3&mobiletype=Android";//好友
public static final String LEAVINGMESSAGE = BASEURL + "?module=mynotelist&view=interactive&type=wall&version=3&mobiletype=Android";//留言
public static final String MYCOMMENT = BASEURL + "?module=mynotelist&view=interactive&type=comment&version=3&mobiletype=Android";//评论
public static final String QUITE = BASEURL + "?module=mynotelist&view=interactive&type=click&version=3&mobiletype=Android";//挺你
public static final String SHARE = BASEURL + "?module=mynotelist&view=interactive&type=sharenotice&version=3&mobiletype=Android";//分享
public static final String SYSTEM = BASEURL + "?module=mynotelist&view=system&version=3&mobiletype=Android";//系统提醒
public static final String ADMINISTRATION = BASEURL + "?module=mynotelist&view=manage&version=3&mobiletype=Android";//管理工作
public static final String JOINMANAGER = BASEURL + "?module=forummisc&action=activityapplylist&version=5&mobiletype=Android";//报名管理
public static final String activity_management = BASEURL + "?module=forummisc&action=activityapplylist&applylistsubmit=yes&version=5&tid=";
} | Comsenz/Discuz-Android | app/src/main/java/cn/tencent/DiscuzMob/net/AppNetConfig.java | 2,587 | //我收藏的版块
| line_comment | zh-cn | package cn.tencent.DiscuzMob.net;
/**
* Created by cg on 2017/4/10.
*/
public class AppNetConfig {
public static final String BASE_ADDRESS = "https://guanjia.comsenz-service.com/"; //【注意】更改BASE_ADDRESS的时候,要搜索全局替换, 因为JS中也有。
// public static final String BASE_ADDRESS = "https://bbs.comsenz-service.com/"; //正式服务器
public String ChangeUrl=BASE_ADDRESS;
public String getChangeUrl() {
return ChangeUrl;
}
public void setChangeUrl(String changeUrl) {
ChangeUrl = changeUrl;
}
public static final String IMGURL = BASE_ADDRESS;
public static final String IMGURL1 = BASE_ADDRESS;
public static final String BASEURL = BASE_ADDRESS + "api/mobile/";
public static final String LIVEBASEURL = "http://bbs.wsq.comsenz-service.com/newwsq/forum.php";
public static final String LOGOURL = IMGURL1 + "static/image/common/logo.png";
public static final String IMAGES = BASEURL + "?module=iwechat&data=json&version=5&mobiletype=Android";//轮播图
public static final String ALLFORUM = BASEURL + "?module=forumindex&version=5&debug=1&mobiletype=Android";//全部版块
public static final String HOTFORUM = BASEURL + "?module=hotforum&version=5&mobiletype=Android";//热门版块
public static final String HOTPOST = BASEURL + "?module=hotthread&version=4&mobiletype=IOS&ios=1";//热帖
public static final String QUESTION = BASEURL + "?module=secure&version=5&mobiletype=Android&type=";//获取验证码/问题
public static final String LOGIN = BASEURL + "?module=login&version=5&&loginfield=auto&mobiletype=Android";//登录
public static final String LOGIN1 = BASEURL + "?module=login&loginsubmit=yes&version=5&mapifrom=wx&charset=utf-8";//登录
public static final String USERINFO1 = BASEURL + "?module=profile&version=4&loginsubmit=yes&mobiletype=Android";//用户信息
public static final String USERINFO = BASEURL + "?module=profile&version=5&loginsubmit=yes&mobiletype=Android";//用户信息
public static final String MYFRIEND = BASEURL + "?module=friend&checkavatar=1&version=4&uid=";//我的好友
public static final String MYFAV = BASEURL + "?module=myfavforum&version=1&android=1&debug=1";//我收 <SUF>
public static final String MYFAVTHREAD = BASEURL + "?module=myfavthread&version=1&android=1&debug=1";//我收藏的帖子
public static final String SYSTEM_MESSAGE = BASEURL + "?module=mypm&filter=announcepm&version=5&mobiletype=Android&page=";//系统消息
public static final String PRIVATE_LETTER = BASEURL + "?module=mypm&touid=2&page=1&version=4&mobiletype=IOS&ios=1&debug=1";//我的消息————>私信
public static final String MESSAGE_REPLIES = BASEURL + "?module=mynoticelist&mapifrom=android";//我的消息--->回复
public static final String THEME = BASEURL + "?module=mythread&version=5&mobiletype=Android&type=thread";//我的主题
// public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复
public static final String MYREPLISE = BASEURL + "?module=mythread&version=4&android=1&type=reply";//w我的回复
public static final String COLLECTION_BANKUAI = BASEURL + "?module=favorite&version=5&type=forum";//点击收藏板块
public static final String HISTHME = BASEURL + "?module=userthread&version=5&android=1&debug=1&mobiletype=Android";//他的回复
public static final String CONVERSATION = BASEURL + "?module=mypm&subop=view&version=5&mobiletype=Android&checkavatar=1&Android=1&smiley=no&convimg=1";//会话详情
public static final String UNCOLLECTION = BASEURL + "?module=favorite&version=5&op=delete&type=forum&mobiletype=Android&id=";//点击取消收藏
public static final String REGISTER = BASEURL + "?version=5®submit=yes&module=register&";//普通注册
public static final String GETREGISTER = BASEURL + "?version=5&module=check";//普通注册
public static final String REGISTERBANGDING = BASEURL + "?version=5&module=weiqqregister";
public static final String COMMENT = BASEURL + "?module=sendreply&version=5&replysubmit=yes&mobiletype=Android&mapifrom=android";//帖子详情跟帖
public static final String SEARCH = BASEURL + "?module=search&version=5&android=1";//搜索
public static final String JURISDICTION = BASEURL + "?module=newthread&submodule=checkpost&debug=1&version=1";//检查权限
public static final String ACTIVITYTHRADF = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//活动帖
public static final String VOTETHREAD = BASEURL + "?module=newthread&version=5&android=1&topicsubmit=yes&fid=";//投票贴
public static final String THREAD = BASEURL + "?module=newthread&version=5&android=1&debug=1&topicsubmit=yes&fid=";//普通帖
public static final String QUOTE = BASEURL + "?module=sendreply&version=3";//回复引用
public static final String PRAISETHREAD = BASEURL + "?module=recommend&version=4";//帖子点赞
public static final String COLLECTTHEAD = BASEURL + "?module=favorite&version=5&type=thread&id=";//收藏帖子http://10.0.6.58/api/mobile/version=4&android=1&debug=1&module=favthread&id=46&favoritesubmit=true
public static final String UNCOLLECTTHEAD = BASEURL + "?module=favorite&version=5&op=delete&mobiletype=Android&id=";//取消收藏帖子
public static final String JOINACTIVITY = BASEURL + "?module=activityapplies&version=5&activitysubmit=true";//参加活动
public static final String DELETELETTER = BASEURL + "?module=delpm&version=5&deletesubmit=1";//删除我的私信
public static final String DELETEMESSAGE = BASEURL + "?version=5&module=delpmview&deletesubmit=1";//删除聊天记录
public static final String LIVETHREAD = BASEURL + "?module=livethread&version=5&mobiletype=Android";//直播列表
public static final String LIVETOADY = BASEURL + "?module=recommon_livethread&version=5&mobiletype=Android";//直播推荐
public static final String LIVEDETIAL = BASEURL + "?version=5&ppp=10&module=viewthread&ordertype=1&submodule=checkpost&mobiletype=Android";//直播
public static final String INTERACTION = BASEURL + "?module=threadreply&version=5&mobiletype=Android&ppp=10";
public static final String RECOMMEND = BASEURL + "?module=recommon_thread&version=5&mobiletype=Android&android=1";//推荐
public static final String ESSENCE = BASEURL + "?module=forumguide&view=digest&version=5&type=digest&mobiletype=Android&page=";//精华帖
public static final String NEW = BASEURL + "?module=forumguide&view=newthread&version=5&type=digest&mobiletype=Android&page=";//最新帖
public static final String MYTHRED = BASEURL + "?module=mynotelist&view=mypost&type=post&version=5&mobiletype=Android";//我的帖子
public static final String MYCOMMON = BASEURL + "?module=mynotelist&view=mypost&type=pcomment&version=3&mobiletype=Android";//点评
public static final String NEWS = BASEURL + "?module=notes&version=5&mobiletype=Android";//是否有新的消息
public static final String MYACTVITY = BASEURL + "?module=mynotelist&view=mypost&type=activity&version=3&mobiletype=Android";//我的活动
public static final String MYREWARD = BASEURL + "?module=mynotelist&view=mypost&type=reward&version=3&mobiletype=Android";//悬赏
public static final String GOODS = BASEURL + "?module=mynotelist&view=mypost&type=goods&version=3&mobiletype=Android";//商品
public static final String MENTIONME = BASEURL + "?module=mynotelist&view=mypost&type=at&version=3&mobiletype=Android";//提到我的
public static final String MYCALL = BASEURL + "?module=mynotelist&view=interactive&type=post&version=3&mobiletype=Android";//打招呼
public static final String myFriends = BASEURL + "?module=mynotelist&view=interactive&type=friend&version=3&mobiletype=Android";//好友
public static final String LEAVINGMESSAGE = BASEURL + "?module=mynotelist&view=interactive&type=wall&version=3&mobiletype=Android";//留言
public static final String MYCOMMENT = BASEURL + "?module=mynotelist&view=interactive&type=comment&version=3&mobiletype=Android";//评论
public static final String QUITE = BASEURL + "?module=mynotelist&view=interactive&type=click&version=3&mobiletype=Android";//挺你
public static final String SHARE = BASEURL + "?module=mynotelist&view=interactive&type=sharenotice&version=3&mobiletype=Android";//分享
public static final String SYSTEM = BASEURL + "?module=mynotelist&view=system&version=3&mobiletype=Android";//系统提醒
public static final String ADMINISTRATION = BASEURL + "?module=mynotelist&view=manage&version=3&mobiletype=Android";//管理工作
public static final String JOINMANAGER = BASEURL + "?module=forummisc&action=activityapplylist&version=5&mobiletype=Android";//报名管理
public static final String activity_management = BASEURL + "?module=forummisc&action=activityapplylist&applylistsubmit=yes&version=5&tid=";
} | false | 2,396 | 7 | 2,584 | 8 | 2,484 | 7 | 2,584 | 8 | 3,162 | 10 | false | false | false | false | false | true |
60215_4 |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class A {
public static void main(String[] args) {
// Readwritel
ReadWriteLock lock = new ReentrantReadWriteLock();
// AbstractQueuedSynchronizer
// CountDownLatch
int result = new A().locate(new int[]{1,-2,3,10,9,-6,9,8});
System.out.println(result);
// System.arraycopy(args, result, lock, result, result);
int[] nums = new int[]{};
List<List<Integer>> list = new A().threeSum(nums);
System.out.println(list);
}
public int findGreatestSumOfSubArray(int[] array) {
int x = array[0];
int y = 0;
int maxsum = x;
for(int i = 1; i < array.length; i++){
//状态转移:连续子数组和最大值
y = Math.max(x + array[i], array[i]);
//维护最大值
maxsum = Math.max(maxsum, y);
//更新x的状态
x = y;
}
return maxsum;
}
private int locate(int[] array){
int low = array[0];
int high = low;
int maxAdd = -100;
for (int i = 1; i < array.length; i++) {
high = Math.max(low + array[i], array[i]);
maxAdd = Math.max(high, maxAdd);
low = high;
}
return maxAdd;
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList();
int target = 0;
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++){
int left = i+1;
int right = nums.length - 1;
while(left < right){
int value = nums[i] + nums[left] + nums[right];
if(value == target){
List<Integer> interList = new ArrayList<Integer>();
interList.add(nums[i]);
interList.add(nums[left]);
interList.add(nums[right]);
// if(!checkExists(list, interList)){
list.add(interList);
// }
left ++;
}else if(value < target){
left ++;
}else {
right --;
}
}
}
return list;
}
private boolean checkExists(List<List<Integer>> list, List<Integer> interList){
if(list.size() < 1){
return false;
}
for(int i = 0; i < list.size(); i++){
if(checkExists0(list.get(list.size() - 1 - i), interList)){
return true;
}
}
return false;
}
private boolean checkExists0(List<Integer> listItem, List<Integer> interList){
for(int i = 0; i < listItem.size(); i++){
if(!Objects.equals(listItem.get(i), interList.get(i))){
return false;
}
}
return true;
}
}
| Coner1/leetcode | src/A.java | 892 | //状态转移:连续子数组和最大值 | line_comment | zh-cn |
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class A {
public static void main(String[] args) {
// Readwritel
ReadWriteLock lock = new ReentrantReadWriteLock();
// AbstractQueuedSynchronizer
// CountDownLatch
int result = new A().locate(new int[]{1,-2,3,10,9,-6,9,8});
System.out.println(result);
// System.arraycopy(args, result, lock, result, result);
int[] nums = new int[]{};
List<List<Integer>> list = new A().threeSum(nums);
System.out.println(list);
}
public int findGreatestSumOfSubArray(int[] array) {
int x = array[0];
int y = 0;
int maxsum = x;
for(int i = 1; i < array.length; i++){
//状态 <SUF>
y = Math.max(x + array[i], array[i]);
//维护最大值
maxsum = Math.max(maxsum, y);
//更新x的状态
x = y;
}
return maxsum;
}
private int locate(int[] array){
int low = array[0];
int high = low;
int maxAdd = -100;
for (int i = 1; i < array.length; i++) {
high = Math.max(low + array[i], array[i]);
maxAdd = Math.max(high, maxAdd);
low = high;
}
return maxAdd;
}
public List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> list = new ArrayList();
int target = 0;
Arrays.sort(nums);
for(int i = 0; i < nums.length - 2; i++){
int left = i+1;
int right = nums.length - 1;
while(left < right){
int value = nums[i] + nums[left] + nums[right];
if(value == target){
List<Integer> interList = new ArrayList<Integer>();
interList.add(nums[i]);
interList.add(nums[left]);
interList.add(nums[right]);
// if(!checkExists(list, interList)){
list.add(interList);
// }
left ++;
}else if(value < target){
left ++;
}else {
right --;
}
}
}
return list;
}
private boolean checkExists(List<List<Integer>> list, List<Integer> interList){
if(list.size() < 1){
return false;
}
for(int i = 0; i < list.size(); i++){
if(checkExists0(list.get(list.size() - 1 - i), interList)){
return true;
}
}
return false;
}
private boolean checkExists0(List<Integer> listItem, List<Integer> interList){
for(int i = 0; i < listItem.size(); i++){
if(!Objects.equals(listItem.get(i), interList.get(i))){
return false;
}
}
return true;
}
}
| false | 769 | 10 | 892 | 12 | 977 | 10 | 892 | 12 | 1,074 | 17 | false | false | false | false | false | true |
31204_27 | import java.util.*;
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Vector<Course> clist = new Vector<Course>();
// clist.add(new Course(1, "数学分析", 0,
// new Teacher("韩老师", 1, "教授"), 20));
// clist.add(new Course(2, "高等代数", 0,
// new Teacher("李老师", 2, "教授"), 15));
// clist.add(new Course(3, "Java", 1,
// new Teacher("吴老师", 3, "副教授"), 23));
// clist.add(new Course(4, "深度学习", 0,
// new Teacher("李老师", 4, "教授"), 50));
// User user = new User();
// Courses.addCourses();
// Courses.SortCourseList();
// Courses.showCourses();
// Courses.readCourses();
menu();
// Courses.saveCourse();
// StringBuffer s1 = new StringBuffer("124");
// s1.append(266);
// s1.append("223");
// System.out.println(s1);
}
public static void menu() {
Scanner sc = new Scanner(System.in);
Vector loginInfo = login();
int identity = (int)loginInfo.get(0);
if (identity == -1) {
return;
}
database.init(); // 初始化
if (identity == 0) { // 管理员菜单
MainLoop:
while (true) {
System.out.println("请选择操作:\n1.新建课程\n" +
"2.删除课程\n3.设置课程教师\n" +
"4.查找老师讲课课程 \n5.显示课程列表 \n" +
"6.按照选课人数进行排序\n7.显示学生列表\n" +
"8.显示教师列表\n9.添加学生\n" +
"10.添加老师\n11.删除学生\n" +
"12.删除老师\n13.初始化学生密码\n" +
"14.初始化老师密码\n0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0: //退出系统
database.dbstmt.close(); // 关数据库
break MainLoop;
case 1: // 添加课程
Courses.addCourses();
break;
case 2: // 删除课程
Courses.deleteCourse();
break;
case 3: // 设置课程教师
Courses.setCourseTeacher();
break;
case 4: // 根据授课教师查找课程
Courses.SearchCourseByTeacher();
break;
case 5: // 显示课程信息
Courses.showCourses();
break;
case 6: // 按照选课人数排序
Courses.SortCourseList();
break;
case 7: // 显示所有学生
Users.showStudents();
break;
case 8: // 显示所有教师
Users.showTeachers();
break;
case 9: // 添加学生
Users.addStudents();
break;
case 10: // 添加老师
Users.addTeachers();
break;
case 11: // 删除学生
Users.deleteStudents();
break;
case 12: // 删除老师
Users.deleteTeachers();
break;
case 13: // 初始化学生密码
Users.recoverStudentsPass();
break;
case 14: // 初始化老师密码
Users.recoverTeachersPass();
break;
default: // 非法输入
System.out.println("输入错误!!!");
}
}
}
else if (identity == 1) { // 教师菜单
Teacher loadingTeacher = (Teacher)loginInfo.get(1);
MainLoop:
while (true) {
System.out.println("请选择操作:\n1.修改登录密码\n" +
"2.查看自己所授课程\n3.查看课程学生名单\n" +
"0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统
case 1 -> loadingTeacher.settPassWord(); // 修改登录密码
case 2 -> loadingTeacher.teachingCourse(); // 查看所授课程
case 3 -> loadingTeacher.studentList(); // 查看所授课程学生名单
}
}
}
else {
Student loadingStudent = (Student)loginInfo.get(1);
MainLoop:
while (true) { // 学生菜单
System.out.println("请选择操作:\n1.修改登录密码\n" +
"2.查看自己所上课程\n3.选课\n" +
"0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统
case 1 -> loadingStudent.setstPassWord(); // 修改登录密码
case 2 -> loadingStudent.learningCourse(); // 查看自己所上课程
case 3 -> loadingStudent.choiceCourse(); // 选课
}
}
}
}
public static Vector login() { // 登录用
Vector res = new Vector(); // result
Scanner sc = new Scanner(System.in);
System.out.println("请输入登陆身份:\n0.管理员\n" +
"1.教师\n" +
"2.学生");
int identity = sc.nextInt();
switch (identity) {
case 0 -> System.out.println("请输入管理员密码:");
case 1 -> System.out.println("请输入教师账号、密码:");
case 2 -> System.out.println("请输入学生账号、密码:");
}
if (identity == 0) {
String pass = sc.next();
if (!pass.equals(Users.admin.getPass())) {
System.out.println("密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
return res;
}
else if (identity == 1) {
String name = sc.next();
String pass = sc.next();
StringBuffer queryt = new StringBuffer("Select * \n" +
"From teacher where tname = ");
queryt.append("'").append(name).append("'");
queryt.append(" and pass = ");
queryt.append("'").append(pass).append("'");
String queryst = new String(queryt);
List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst);
if (selectt.size() == 0) { // 姓名或密码错误
System.out.println("用户名或密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
res.add(new Teacher((String)selectt.get(0).get("tname"), (String)selectt.get(0).get("pass"),
(int)selectt.get(0).get("tid"), (String)selectt.get(0).get("tlevel")));
return res;
}
else if (identity == 2){
String name = sc.next();
String pass = sc.next();
StringBuffer queryt = new StringBuffer("Select * \n" +
"From student where sname = ");
queryt.append("'").append(name).append("'");
queryt.append(" and pass = ");
queryt.append("'").append(pass).append("'");
String queryst = new String(queryt);
List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst);
if (selectt.size() == 0) { // 姓名或密码错误
System.out.println("用户名或密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
res.add(new Student((String)selectt.get(0).get("sname"), (String)selectt.get(0).get("pass"),
(int)selectt.get(0).get("sid"), (String)selectt.get(0).get("sclass")));
return res;
}
System.out.println("输入错误!系统退出!");
res.add(-1);
return res;
}
} | Control-derek/NEU_Doka_Java_Experiment1 | src/Main.java | 2,075 | // 设置课程教师 | line_comment | zh-cn | import java.util.*;
// Press Shift twice to open the Search Everywhere dialog and type `show whitespaces`,
// then press Enter. You can now see whitespace characters in your code.
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Vector<Course> clist = new Vector<Course>();
// clist.add(new Course(1, "数学分析", 0,
// new Teacher("韩老师", 1, "教授"), 20));
// clist.add(new Course(2, "高等代数", 0,
// new Teacher("李老师", 2, "教授"), 15));
// clist.add(new Course(3, "Java", 1,
// new Teacher("吴老师", 3, "副教授"), 23));
// clist.add(new Course(4, "深度学习", 0,
// new Teacher("李老师", 4, "教授"), 50));
// User user = new User();
// Courses.addCourses();
// Courses.SortCourseList();
// Courses.showCourses();
// Courses.readCourses();
menu();
// Courses.saveCourse();
// StringBuffer s1 = new StringBuffer("124");
// s1.append(266);
// s1.append("223");
// System.out.println(s1);
}
public static void menu() {
Scanner sc = new Scanner(System.in);
Vector loginInfo = login();
int identity = (int)loginInfo.get(0);
if (identity == -1) {
return;
}
database.init(); // 初始化
if (identity == 0) { // 管理员菜单
MainLoop:
while (true) {
System.out.println("请选择操作:\n1.新建课程\n" +
"2.删除课程\n3.设置课程教师\n" +
"4.查找老师讲课课程 \n5.显示课程列表 \n" +
"6.按照选课人数进行排序\n7.显示学生列表\n" +
"8.显示教师列表\n9.添加学生\n" +
"10.添加老师\n11.删除学生\n" +
"12.删除老师\n13.初始化学生密码\n" +
"14.初始化老师密码\n0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0: //退出系统
database.dbstmt.close(); // 关数据库
break MainLoop;
case 1: // 添加课程
Courses.addCourses();
break;
case 2: // 删除课程
Courses.deleteCourse();
break;
case 3: // 设置 <SUF>
Courses.setCourseTeacher();
break;
case 4: // 根据授课教师查找课程
Courses.SearchCourseByTeacher();
break;
case 5: // 显示课程信息
Courses.showCourses();
break;
case 6: // 按照选课人数排序
Courses.SortCourseList();
break;
case 7: // 显示所有学生
Users.showStudents();
break;
case 8: // 显示所有教师
Users.showTeachers();
break;
case 9: // 添加学生
Users.addStudents();
break;
case 10: // 添加老师
Users.addTeachers();
break;
case 11: // 删除学生
Users.deleteStudents();
break;
case 12: // 删除老师
Users.deleteTeachers();
break;
case 13: // 初始化学生密码
Users.recoverStudentsPass();
break;
case 14: // 初始化老师密码
Users.recoverTeachersPass();
break;
default: // 非法输入
System.out.println("输入错误!!!");
}
}
}
else if (identity == 1) { // 教师菜单
Teacher loadingTeacher = (Teacher)loginInfo.get(1);
MainLoop:
while (true) {
System.out.println("请选择操作:\n1.修改登录密码\n" +
"2.查看自己所授课程\n3.查看课程学生名单\n" +
"0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统
case 1 -> loadingTeacher.settPassWord(); // 修改登录密码
case 2 -> loadingTeacher.teachingCourse(); // 查看所授课程
case 3 -> loadingTeacher.studentList(); // 查看所授课程学生名单
}
}
}
else {
Student loadingStudent = (Student)loginInfo.get(1);
MainLoop:
while (true) { // 学生菜单
System.out.println("请选择操作:\n1.修改登录密码\n" +
"2.查看自己所上课程\n3.选课\n" +
"0.退出");
int choice = sc.nextInt();
switch (choice) {
case 0 -> {database.dbstmt.close(); break MainLoop;} // 退出系统
case 1 -> loadingStudent.setstPassWord(); // 修改登录密码
case 2 -> loadingStudent.learningCourse(); // 查看自己所上课程
case 3 -> loadingStudent.choiceCourse(); // 选课
}
}
}
}
public static Vector login() { // 登录用
Vector res = new Vector(); // result
Scanner sc = new Scanner(System.in);
System.out.println("请输入登陆身份:\n0.管理员\n" +
"1.教师\n" +
"2.学生");
int identity = sc.nextInt();
switch (identity) {
case 0 -> System.out.println("请输入管理员密码:");
case 1 -> System.out.println("请输入教师账号、密码:");
case 2 -> System.out.println("请输入学生账号、密码:");
}
if (identity == 0) {
String pass = sc.next();
if (!pass.equals(Users.admin.getPass())) {
System.out.println("密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
return res;
}
else if (identity == 1) {
String name = sc.next();
String pass = sc.next();
StringBuffer queryt = new StringBuffer("Select * \n" +
"From teacher where tname = ");
queryt.append("'").append(name).append("'");
queryt.append(" and pass = ");
queryt.append("'").append(pass).append("'");
String queryst = new String(queryt);
List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst);
if (selectt.size() == 0) { // 姓名或密码错误
System.out.println("用户名或密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
res.add(new Teacher((String)selectt.get(0).get("tname"), (String)selectt.get(0).get("pass"),
(int)selectt.get(0).get("tid"), (String)selectt.get(0).get("tlevel")));
return res;
}
else if (identity == 2){
String name = sc.next();
String pass = sc.next();
StringBuffer queryt = new StringBuffer("Select * \n" +
"From student where sname = ");
queryt.append("'").append(name).append("'");
queryt.append(" and pass = ");
queryt.append("'").append(pass).append("'");
String queryst = new String(queryt);
List<HashMap<String, Object>> selectt = database.dbstmt.Select(queryst);
if (selectt.size() == 0) { // 姓名或密码错误
System.out.println("用户名或密码错误!系统退出!");
res.add(-1);
return res;
}
res.add(identity);
res.add(new Student((String)selectt.get(0).get("sname"), (String)selectt.get(0).get("pass"),
(int)selectt.get(0).get("sid"), (String)selectt.get(0).get("sclass")));
return res;
}
System.out.println("输入错误!系统退出!");
res.add(-1);
return res;
}
} | false | 1,868 | 4 | 2,075 | 5 | 2,163 | 4 | 2,075 | 5 | 2,749 | 12 | false | false | false | false | false | true |
13778_4 | package com.hotel.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.List;
/**
* @author guangyong.yang
* @date 2019-01-15
* @description 客人
*/
@Getter
@Setter
@Entity
@Table(name = "customer")
public class Customer {
/**
* id
*/
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 姓名
*/
@Column(nullable = false,length = 80)
private String name;
/**
* 身份证号
*/
@Column(nullable = false,length = 18)
private String idCard;
/**
* 手机号
*/
@Column(length = 11)
private String phoneNo;
/**
* 房间
*/
@ManyToMany(cascade = CascadeType.REFRESH,mappedBy = "customers")
private List<Room> rooms;
@Column(length = 100)
private String comment;
}
| Cool-Coding/angular-springboot-demo | hotel-server/src/main/java/com/hotel/entity/Customer.java | 263 | /**
* 手机号
*/ | block_comment | zh-cn | package com.hotel.entity;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.*;
import java.util.List;
/**
* @author guangyong.yang
* @date 2019-01-15
* @description 客人
*/
@Getter
@Setter
@Entity
@Table(name = "customer")
public class Customer {
/**
* id
*/
@Id
@Column
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 姓名
*/
@Column(nullable = false,length = 80)
private String name;
/**
* 身份证号
*/
@Column(nullable = false,length = 18)
private String idCard;
/**
* 手机号 <SUF>*/
@Column(length = 11)
private String phoneNo;
/**
* 房间
*/
@ManyToMany(cascade = CascadeType.REFRESH,mappedBy = "customers")
private List<Room> rooms;
@Column(length = 100)
private String comment;
}
| false | 238 | 10 | 263 | 8 | 279 | 9 | 263 | 8 | 330 | 11 | false | false | false | false | false | true |
34852_9 | package cn.yang.domain;
import java.sql.Blob;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 用户(会员)
* @author <a href="mailto:riguang_2007@163.com">ygy</a>
*2011-4-7
*
*/
@Entity
public class User {
// --- 基本信息
private String loginName;// 登录名(唯一),最长为128个字符
private String password;// 密码,最长为128个字符
private String email;// Email地址,最长为128个字符
// --- 个人信息
private String nickname;// 昵称,最多128个字符,64个汉字
private Gender gender; // 性别
private byte[] avatar;// 头像
private String signature;// 签名,最多127个汉字
private Integer score=0;//积分
private String rank;//等级
// --- 其他
private Date registrationTime;// 注册时间
private Date lastVisitTime; // 最后(上次)访问时间
private String lastVisitIpAddr; // 最后(上次)访问时所使用的ip地址
private int themeCount=0;// 发表的总主题数
private int replyCount=0;// 发表的总回复数
private boolean locked;// 是否被锁定
private String autoLoginAuthKey;// 用于自动登陆的一个认证的字符串
// private String activationKey;// 锁定用户自己激活帐号所用的激活码
private Set<Role> roles = new HashSet<Role>(0);// 所拥有的角色(权限)
public User(){}
public User(String loginName){
this.loginName=loginName;
}
@Id @Column(length=128)
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
@Column(length=128)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(length=128)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(length=128)
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Enumerated(EnumType.STRING)
@Column(length=6)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
@Lob @Basic(fetch=FetchType.LAZY)
public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
@Column(length=255)
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getRegistrationTime() {
return registrationTime;
}
public void setRegistrationTime(Date registrationTime) {
this.registrationTime = registrationTime;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getLastVisitTime() {
return lastVisitTime;
}
public void setLastVisitTime(Date lastVisitTime) {
this.lastVisitTime = lastVisitTime;
}
@Column(length=15)
public String getLastVisitIpAddr() {
return lastVisitIpAddr;
}
public void setLastVisitIpAddr(String lastVisitIpAddr) {
this.lastVisitIpAddr = lastVisitIpAddr;
}
@Column(length=1)
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
@Column(nullable=false)
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Column(length=20)
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
@Column(nullable=false)
public int getThemeCount() {
return themeCount;
}
public void setThemeCount(int themeCount) {
this.themeCount = themeCount;
}
@Column(nullable=false)
public int getReplyCount() {
return replyCount;
}
public void setReplyCount(int replyCount) {
this.replyCount = replyCount;
}
@Column(length=128)
public String getAutoLoginAuthKey() {
return autoLoginAuthKey;
}
public void setAutoLoginAuthKey(String autoLoginAuthKey) {
this.autoLoginAuthKey = autoLoginAuthKey;
}
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(
name="user_role",
joinColumns=@JoinColumn(name="user_loginName", referencedColumnName="loginName"),
inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id")
)
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return new StringBuffer().append("[User: ")//
.append(",loginName=").append(loginName)//
.append(",email=").append(email)//
.append(",registrationTime=").append(registrationTime)//
.append(",nickname=").append(nickname)//
.append(",replyCount=").append(themeCount)//
.append(",replyCount=").append(replyCount)//
.append("]")//
.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((loginName == null) ? 0 : loginName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (loginName == null) {
if (other.loginName != null)
return false;
} else if (!loginName.equals(other.loginName))
return false;
return true;
}
}
| Cool-Coding/bbs | src/cn/yang/domain/User.java | 1,828 | // 注册时间 | line_comment | zh-cn | package cn.yang.domain;
import java.sql.Blob;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* 用户(会员)
* @author <a href="mailto:riguang_2007@163.com">ygy</a>
*2011-4-7
*
*/
@Entity
public class User {
// --- 基本信息
private String loginName;// 登录名(唯一),最长为128个字符
private String password;// 密码,最长为128个字符
private String email;// Email地址,最长为128个字符
// --- 个人信息
private String nickname;// 昵称,最多128个字符,64个汉字
private Gender gender; // 性别
private byte[] avatar;// 头像
private String signature;// 签名,最多127个汉字
private Integer score=0;//积分
private String rank;//等级
// --- 其他
private Date registrationTime;// 注册 <SUF>
private Date lastVisitTime; // 最后(上次)访问时间
private String lastVisitIpAddr; // 最后(上次)访问时所使用的ip地址
private int themeCount=0;// 发表的总主题数
private int replyCount=0;// 发表的总回复数
private boolean locked;// 是否被锁定
private String autoLoginAuthKey;// 用于自动登陆的一个认证的字符串
// private String activationKey;// 锁定用户自己激活帐号所用的激活码
private Set<Role> roles = new HashSet<Role>(0);// 所拥有的角色(权限)
public User(){}
public User(String loginName){
this.loginName=loginName;
}
@Id @Column(length=128)
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
@Column(length=128)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(length=128)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(length=128)
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Enumerated(EnumType.STRING)
@Column(length=6)
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
@Lob @Basic(fetch=FetchType.LAZY)
public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
@Column(length=255)
public String getSignature() {
return signature;
}
public void setSignature(String signature) {
this.signature = signature;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getRegistrationTime() {
return registrationTime;
}
public void setRegistrationTime(Date registrationTime) {
this.registrationTime = registrationTime;
}
@Temporal(TemporalType.TIMESTAMP)
public Date getLastVisitTime() {
return lastVisitTime;
}
public void setLastVisitTime(Date lastVisitTime) {
this.lastVisitTime = lastVisitTime;
}
@Column(length=15)
public String getLastVisitIpAddr() {
return lastVisitIpAddr;
}
public void setLastVisitIpAddr(String lastVisitIpAddr) {
this.lastVisitIpAddr = lastVisitIpAddr;
}
@Column(length=1)
public boolean isLocked() {
return locked;
}
public void setLocked(boolean locked) {
this.locked = locked;
}
@Column(nullable=false)
public Integer getScore() {
return score;
}
public void setScore(Integer score) {
this.score = score;
}
@Column(length=20)
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank = rank;
}
@Column(nullable=false)
public int getThemeCount() {
return themeCount;
}
public void setThemeCount(int themeCount) {
this.themeCount = themeCount;
}
@Column(nullable=false)
public int getReplyCount() {
return replyCount;
}
public void setReplyCount(int replyCount) {
this.replyCount = replyCount;
}
@Column(length=128)
public String getAutoLoginAuthKey() {
return autoLoginAuthKey;
}
public void setAutoLoginAuthKey(String autoLoginAuthKey) {
this.autoLoginAuthKey = autoLoginAuthKey;
}
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(
name="user_role",
joinColumns=@JoinColumn(name="user_loginName", referencedColumnName="loginName"),
inverseJoinColumns=@JoinColumn(name="role_id", referencedColumnName="id")
)
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return new StringBuffer().append("[User: ")//
.append(",loginName=").append(loginName)//
.append(",email=").append(email)//
.append(",registrationTime=").append(registrationTime)//
.append(",nickname=").append(nickname)//
.append(",replyCount=").append(themeCount)//
.append(",replyCount=").append(replyCount)//
.append("]")//
.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((loginName == null) ? 0 : loginName.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (loginName == null) {
if (other.loginName != null)
return false;
} else if (!loginName.equals(other.loginName))
return false;
return true;
}
}
| false | 1,455 | 4 | 1,828 | 4 | 1,804 | 3 | 1,828 | 4 | 2,206 | 8 | false | false | false | false | false | true |
54915_4 | import java.util.Arrays;
public class _76_match {
public boolean match (String str, String pattern) {
char[] strC = str.toCharArray();
char[] patternC = pattern.toCharArray();
boolean[] dp = new boolean[patternC.length + 1];
dp[0] = true;
for (int i = 1; i < patternC.length && patternC[i] == '*'; i += 2) {
dp[i + 1] = true;
}
boolean pre = true;
for (int i = 1; i <= strC.length; i++) {
dp[0] = false;
for (int j = 1; j <= patternC.length; j++) {
boolean temp = dp[j];
if (patternC[j - 1] == '.') {
dp[j] = pre;
} else if (patternC[j - 1] == '*') {
if (patternC[j - 2] == '.' || patternC[j - 2] == strC[i - 1])
dp[j] = dp[j] || dp[j - 2];
else {
dp[j] = dp[j - 2];
}
} else {
if (patternC[j - 1] == strC[i - 1])
dp[j] = pre;
else
dp[j] = false;
}
pre = temp;
}
}
return dp[patternC.length];
}
public boolean match2 (String str, String pattern) {
int n1 = str.length();
int n2 = pattern.length();
//dp[i][j]表示str前i个字符和pattern前j个字符是否匹配
boolean[][] dp = new boolean[n1 + 1][n2 + 1];
//遍历str每个长度
for(int i = 0; i <= n1; i++){
//遍历pattern每个长度
for(int j = 0; j <= n2; j++){
//空正则的情况
if(j == 0){
dp[i][j] = (i == 0 ? true : false);
//非空的情况下 星号、点号、字符
}else{
if(pattern.charAt(j - 1) != '*'){
//当前字符不为*,用.去匹配或者字符直接相同
if(i > 0 && (str.charAt(i - 1) == pattern.charAt(j - 1) || pattern.charAt(j - 1) == '.')){
dp[i][j] = dp[i - 1][j - 1];
}
}else{
//碰到*
if(j >= 2){
dp[i][j] |= dp[i][j - 2];
}
//若是前一位为.或者前一位可以与这个数字匹配
if(i >= 1 && j >= 2 && (str.charAt(i - 1) == pattern.charAt(j - 2) || pattern.charAt(j - 2) == '.')){
dp[i][j] |= dp[i - 1][j];
}
}
}
}
}
return dp[n1][n2];
}
public static void main(String[] args) {
System.out.println(new _76_match().match("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*"));
System.out.println(new _76_match().match2("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*"));
}
}
| Cqupt-Psyduck/my_algorithm | hot_100/_76_match.java | 847 | //非空的情况下 星号、点号、字符 | line_comment | zh-cn | import java.util.Arrays;
public class _76_match {
public boolean match (String str, String pattern) {
char[] strC = str.toCharArray();
char[] patternC = pattern.toCharArray();
boolean[] dp = new boolean[patternC.length + 1];
dp[0] = true;
for (int i = 1; i < patternC.length && patternC[i] == '*'; i += 2) {
dp[i + 1] = true;
}
boolean pre = true;
for (int i = 1; i <= strC.length; i++) {
dp[0] = false;
for (int j = 1; j <= patternC.length; j++) {
boolean temp = dp[j];
if (patternC[j - 1] == '.') {
dp[j] = pre;
} else if (patternC[j - 1] == '*') {
if (patternC[j - 2] == '.' || patternC[j - 2] == strC[i - 1])
dp[j] = dp[j] || dp[j - 2];
else {
dp[j] = dp[j - 2];
}
} else {
if (patternC[j - 1] == strC[i - 1])
dp[j] = pre;
else
dp[j] = false;
}
pre = temp;
}
}
return dp[patternC.length];
}
public boolean match2 (String str, String pattern) {
int n1 = str.length();
int n2 = pattern.length();
//dp[i][j]表示str前i个字符和pattern前j个字符是否匹配
boolean[][] dp = new boolean[n1 + 1][n2 + 1];
//遍历str每个长度
for(int i = 0; i <= n1; i++){
//遍历pattern每个长度
for(int j = 0; j <= n2; j++){
//空正则的情况
if(j == 0){
dp[i][j] = (i == 0 ? true : false);
//非空 <SUF>
}else{
if(pattern.charAt(j - 1) != '*'){
//当前字符不为*,用.去匹配或者字符直接相同
if(i > 0 && (str.charAt(i - 1) == pattern.charAt(j - 1) || pattern.charAt(j - 1) == '.')){
dp[i][j] = dp[i - 1][j - 1];
}
}else{
//碰到*
if(j >= 2){
dp[i][j] |= dp[i][j - 2];
}
//若是前一位为.或者前一位可以与这个数字匹配
if(i >= 1 && j >= 2 && (str.charAt(i - 1) == pattern.charAt(j - 2) || pattern.charAt(j - 2) == '.')){
dp[i][j] |= dp[i - 1][j];
}
}
}
}
}
return dp[n1][n2];
}
public static void main(String[] args) {
System.out.println(new _76_match().match("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*"));
System.out.println(new _76_match().match2("bbabacccbcbbcaaab","a*b*a*a*c*aa*c*bc*"));
}
}
| false | 768 | 12 | 847 | 13 | 909 | 11 | 847 | 13 | 1,042 | 18 | false | false | false | false | false | true |
55481_9 | /*
*
* Copyright 2017 Crab2Died
* All rights reserved.
*
* 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.
*
* Browse for more information :
* 1) https://gitee.com/Crab2Died/Excel4J
* 2) https://github.com/Crab2died/Excel4J
*
*/
package com.github.crab2died.utils;
import com.github.crab2died.annotation.ExcelField;
import com.github.crab2died.converter.DefaultConvertible;
import com.github.crab2died.converter.WriteConvertible;
import com.github.crab2died.exceptions.Excel4JException;
import com.github.crab2died.handler.ExcelHeader;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
/**
* Excel4J工具类
* author : Crab2Died
* date : 2017/5/24 9:43
*/
public class Utils {
/**
* getter或setter枚举
*/
public enum FieldAccessType {
GETTER, SETTER
}
/**
* <p>根据JAVA对象注解获取Excel表头信息</p>
*
* @param clz 类型
* @return 表头信息
*/
public static List<ExcelHeader> getHeaderList(Class<?> clz) throws Excel4JException {
List<ExcelHeader> headers = new ArrayList<>();
List<Field> fields = new ArrayList<>();
for (Class<?> clazz = clz; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
// 是否使用ExcelField注解
if (field.isAnnotationPresent(ExcelField.class)) {
ExcelField er = field.getAnnotation(ExcelField.class);
try {
headers.add(new ExcelHeader(
er.title(),
er.order(),
er.writeConverter().newInstance(),
er.readConverter().newInstance(),
field.getName(),
field.getType()
));
} catch (InstantiationException | IllegalAccessException e) {
throw new Excel4JException(e);
}
}
}
Collections.sort(headers);
return headers;
}
/**
* 获取excel列表头
*
* @param titleRow excel行
* @param clz 类型
* @return ExcelHeader集合
* @throws Excel4JException 异常
*/
public static Map<Integer, ExcelHeader> getHeaderMap(Row titleRow, Class<?> clz)
throws Excel4JException {
List<ExcelHeader> headers = getHeaderList(clz);
Map<Integer, ExcelHeader> maps = new HashMap<>();
for (Cell c : titleRow) {
String title = c.getStringCellValue();
for (ExcelHeader eh : headers) {
if (eh.getTitle().equals(title.trim())) {
maps.put(c.getColumnIndex(), eh);
break;
}
}
}
return maps;
}
/**
* 获取单元格内容
*
* @param c 单元格
* @return 单元格内容
*/
public static String getCellValue(Cell c) {
String o;
switch (c.getCellType()) {
case BLANK:
o = "";
break;
case BOOLEAN:
o = String.valueOf(c.getBooleanCellValue());
break;
case FORMULA:
o = calculationFormula(c);
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(c)) {
o = DateUtils.date2Str(c.getDateCellValue());
} else {
o = String.valueOf(c.getNumericCellValue());
o = matchDoneBigDecimal(o);
o = RegularUtils.converNumByReg(o);
}
break;
case STRING:
o = c.getStringCellValue();
break;
default:
o = null;
break;
}
return o;
}
/**
* 字符串转对象
*
* @param strField 字符串
* @param clazz 待转类型
* @return 转换后数据
*/
public static Object str2TargetClass(String strField, Class<?> clazz) {
if (null == strField || "".equals(strField))
return null;
if ((Long.class == clazz) || (long.class == clazz)) {
strField = matchDoneBigDecimal(strField);
strField = RegularUtils.converNumByReg(strField);
return Long.parseLong(strField);
}
if ((Integer.class == clazz) || (int.class == clazz)) {
strField = matchDoneBigDecimal(strField);
strField = RegularUtils.converNumByReg(strField);
return Integer.parseInt(strField);
}
if ((Float.class == clazz) || (float.class == clazz)) {
strField = matchDoneBigDecimal(strField);
return Float.parseFloat(strField);
}
if ((Double.class == clazz) || (double.class == clazz)) {
strField = matchDoneBigDecimal(strField);
return Double.parseDouble(strField);
}
if ((Character.class == clazz) || (char.class == clazz)) {
return strField.toCharArray()[0];
}
if ((Boolean.class == clazz) || (boolean.class == clazz)) {
return Boolean.parseBoolean(strField);
}
if (Date.class == clazz) {
return DateUtils.str2DateUnmatch2Null(strField);
}
return strField;
}
/**
* 科学计数法数据转换
*
* @param bigDecimal 科学计数法
* @return 数据字符串
*/
private static String matchDoneBigDecimal(String bigDecimal) {
// 对科学计数法进行处理
boolean flg = Pattern.matches("^-?\\d+(\\.\\d+)?(E-?\\d+)?$", bigDecimal);
if (flg) {
BigDecimal bd = new BigDecimal(bigDecimal);
bigDecimal = bd.toPlainString();
}
return bigDecimal;
}
/**
* <p>根据java对象属性{@link Field}获取该属性的getter或setter方法名,
* 另对{@link boolean}及{@link Boolean}做了行管处理</p>
*
* @param clazz 操作对象
* @param fieldName 对象属性
* @param methodType 方法类型,getter或setter枚举
* @return getter或setter方法
* @throws IntrospectionException 异常
* @author Crab2Died
*/
public static Method getterOrSetter(Class clazz, String fieldName, FieldAccessType methodType)
throws IntrospectionException {
if (null == fieldName || "".equals(fieldName))
return null;
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor prop : props) {
if (fieldName.equals(prop.getName())) {
if (FieldAccessType.SETTER == methodType) {
return prop.getWriteMethod();
}
if (FieldAccessType.GETTER == methodType) {
return prop.getReadMethod();
}
}
}
throw new IntrospectionException("Can not get the getter or setter method");
}
/**
* <p>根据对象的属性名{@code fieldName}获取某个java的属性{@link java.lang.reflect.Field}</p>
*
* @param clazz java对象的class属性
* @param fieldName 属性名
* @return {@link java.lang.reflect.Field} java对象的属性
* @author Crab2Died
*/
private static Field matchClassField(Class clazz, String fieldName) {
List<Field> fields = new ArrayList<>();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
return field;
}
}
throw new IllegalArgumentException("[" + clazz.getName() + "] can`t found field with [" + fieldName + "]");
}
/**
* 根据属性名与属性类型获取字段内容
*
* @param bean 对象
* @param fieldName 字段名
* @param writeConvertible 写入转换器
* @return 对象指定字段内容
* @throws Excel4JException 异常
*/
public static String getProperty(Object bean, String fieldName, WriteConvertible writeConvertible)
throws Excel4JException {
if (bean == null || fieldName == null)
throw new IllegalArgumentException("Operating bean or filed class must not be null");
Method method;
Object object;
try {
method = getterOrSetter(bean.getClass(), fieldName, FieldAccessType.GETTER);
object = method.invoke(bean);
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new Excel4JException(e);
}
if (null != writeConvertible && writeConvertible.getClass() != DefaultConvertible.class) {
// 写入转换器
object = writeConvertible.execWrite(object);
}
return object == null ? "" : object.toString();
}
/**
* 根据属性名与属性类型获取字段内容
*
* @param bean 对象
* @param name 字段名
* @param value 字段类型
*/
public static void copyProperty(Object bean, String name, Object value)
throws Excel4JException {
if (null == name || null == value)
return;
Field field = matchClassField(bean.getClass(), name);
if (null == field)
return;
Method method;
try {
method = getterOrSetter(bean.getClass(), name, FieldAccessType.SETTER);
if (value.getClass() == field.getType()) {
method.invoke(bean, value);
} else {
method.invoke(bean, str2TargetClass(value.toString(), field.getType()));
}
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new Excel4JException(e);
}
}
/**
* 计算公式结果
*
* @param cell 单元格类型为公式的单元格
* @return 返回单元格计算后的值 格式化成String
* @author QingMings
* Email:1821063757@qq.com
* date 2018-01-13
*/
public static String calculationFormula(Cell cell) {
CellValue cellValue = cell.getSheet().getWorkbook().getCreationHelper()
.createFormulaEvaluator().evaluate(cell);
return cellValue.formatAsString();
}
}
| Crab2died/Excel4J | src/main/java/com/github/crab2died/utils/Utils.java | 2,754 | // 对科学计数法进行处理 | line_comment | zh-cn | /*
*
* Copyright 2017 Crab2Died
* All rights reserved.
*
* 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.
*
* Browse for more information :
* 1) https://gitee.com/Crab2Died/Excel4J
* 2) https://github.com/Crab2died/Excel4J
*
*/
package com.github.crab2died.utils;
import com.github.crab2died.annotation.ExcelField;
import com.github.crab2died.converter.DefaultConvertible;
import com.github.crab2died.converter.WriteConvertible;
import com.github.crab2died.exceptions.Excel4JException;
import com.github.crab2died.handler.ExcelHeader;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;
import java.util.regex.Pattern;
/**
* Excel4J工具类
* author : Crab2Died
* date : 2017/5/24 9:43
*/
public class Utils {
/**
* getter或setter枚举
*/
public enum FieldAccessType {
GETTER, SETTER
}
/**
* <p>根据JAVA对象注解获取Excel表头信息</p>
*
* @param clz 类型
* @return 表头信息
*/
public static List<ExcelHeader> getHeaderList(Class<?> clz) throws Excel4JException {
List<ExcelHeader> headers = new ArrayList<>();
List<Field> fields = new ArrayList<>();
for (Class<?> clazz = clz; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
// 是否使用ExcelField注解
if (field.isAnnotationPresent(ExcelField.class)) {
ExcelField er = field.getAnnotation(ExcelField.class);
try {
headers.add(new ExcelHeader(
er.title(),
er.order(),
er.writeConverter().newInstance(),
er.readConverter().newInstance(),
field.getName(),
field.getType()
));
} catch (InstantiationException | IllegalAccessException e) {
throw new Excel4JException(e);
}
}
}
Collections.sort(headers);
return headers;
}
/**
* 获取excel列表头
*
* @param titleRow excel行
* @param clz 类型
* @return ExcelHeader集合
* @throws Excel4JException 异常
*/
public static Map<Integer, ExcelHeader> getHeaderMap(Row titleRow, Class<?> clz)
throws Excel4JException {
List<ExcelHeader> headers = getHeaderList(clz);
Map<Integer, ExcelHeader> maps = new HashMap<>();
for (Cell c : titleRow) {
String title = c.getStringCellValue();
for (ExcelHeader eh : headers) {
if (eh.getTitle().equals(title.trim())) {
maps.put(c.getColumnIndex(), eh);
break;
}
}
}
return maps;
}
/**
* 获取单元格内容
*
* @param c 单元格
* @return 单元格内容
*/
public static String getCellValue(Cell c) {
String o;
switch (c.getCellType()) {
case BLANK:
o = "";
break;
case BOOLEAN:
o = String.valueOf(c.getBooleanCellValue());
break;
case FORMULA:
o = calculationFormula(c);
break;
case NUMERIC:
if (DateUtil.isCellDateFormatted(c)) {
o = DateUtils.date2Str(c.getDateCellValue());
} else {
o = String.valueOf(c.getNumericCellValue());
o = matchDoneBigDecimal(o);
o = RegularUtils.converNumByReg(o);
}
break;
case STRING:
o = c.getStringCellValue();
break;
default:
o = null;
break;
}
return o;
}
/**
* 字符串转对象
*
* @param strField 字符串
* @param clazz 待转类型
* @return 转换后数据
*/
public static Object str2TargetClass(String strField, Class<?> clazz) {
if (null == strField || "".equals(strField))
return null;
if ((Long.class == clazz) || (long.class == clazz)) {
strField = matchDoneBigDecimal(strField);
strField = RegularUtils.converNumByReg(strField);
return Long.parseLong(strField);
}
if ((Integer.class == clazz) || (int.class == clazz)) {
strField = matchDoneBigDecimal(strField);
strField = RegularUtils.converNumByReg(strField);
return Integer.parseInt(strField);
}
if ((Float.class == clazz) || (float.class == clazz)) {
strField = matchDoneBigDecimal(strField);
return Float.parseFloat(strField);
}
if ((Double.class == clazz) || (double.class == clazz)) {
strField = matchDoneBigDecimal(strField);
return Double.parseDouble(strField);
}
if ((Character.class == clazz) || (char.class == clazz)) {
return strField.toCharArray()[0];
}
if ((Boolean.class == clazz) || (boolean.class == clazz)) {
return Boolean.parseBoolean(strField);
}
if (Date.class == clazz) {
return DateUtils.str2DateUnmatch2Null(strField);
}
return strField;
}
/**
* 科学计数法数据转换
*
* @param bigDecimal 科学计数法
* @return 数据字符串
*/
private static String matchDoneBigDecimal(String bigDecimal) {
// 对科 <SUF>
boolean flg = Pattern.matches("^-?\\d+(\\.\\d+)?(E-?\\d+)?$", bigDecimal);
if (flg) {
BigDecimal bd = new BigDecimal(bigDecimal);
bigDecimal = bd.toPlainString();
}
return bigDecimal;
}
/**
* <p>根据java对象属性{@link Field}获取该属性的getter或setter方法名,
* 另对{@link boolean}及{@link Boolean}做了行管处理</p>
*
* @param clazz 操作对象
* @param fieldName 对象属性
* @param methodType 方法类型,getter或setter枚举
* @return getter或setter方法
* @throws IntrospectionException 异常
* @author Crab2Died
*/
public static Method getterOrSetter(Class clazz, String fieldName, FieldAccessType methodType)
throws IntrospectionException {
if (null == fieldName || "".equals(fieldName))
return null;
BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
PropertyDescriptor[] props = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor prop : props) {
if (fieldName.equals(prop.getName())) {
if (FieldAccessType.SETTER == methodType) {
return prop.getWriteMethod();
}
if (FieldAccessType.GETTER == methodType) {
return prop.getReadMethod();
}
}
}
throw new IntrospectionException("Can not get the getter or setter method");
}
/**
* <p>根据对象的属性名{@code fieldName}获取某个java的属性{@link java.lang.reflect.Field}</p>
*
* @param clazz java对象的class属性
* @param fieldName 属性名
* @return {@link java.lang.reflect.Field} java对象的属性
* @author Crab2Died
*/
private static Field matchClassField(Class clazz, String fieldName) {
List<Field> fields = new ArrayList<>();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
fields.addAll(Arrays.asList(clazz.getDeclaredFields()));
}
for (Field field : fields) {
if (fieldName.equals(field.getName())) {
return field;
}
}
throw new IllegalArgumentException("[" + clazz.getName() + "] can`t found field with [" + fieldName + "]");
}
/**
* 根据属性名与属性类型获取字段内容
*
* @param bean 对象
* @param fieldName 字段名
* @param writeConvertible 写入转换器
* @return 对象指定字段内容
* @throws Excel4JException 异常
*/
public static String getProperty(Object bean, String fieldName, WriteConvertible writeConvertible)
throws Excel4JException {
if (bean == null || fieldName == null)
throw new IllegalArgumentException("Operating bean or filed class must not be null");
Method method;
Object object;
try {
method = getterOrSetter(bean.getClass(), fieldName, FieldAccessType.GETTER);
object = method.invoke(bean);
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new Excel4JException(e);
}
if (null != writeConvertible && writeConvertible.getClass() != DefaultConvertible.class) {
// 写入转换器
object = writeConvertible.execWrite(object);
}
return object == null ? "" : object.toString();
}
/**
* 根据属性名与属性类型获取字段内容
*
* @param bean 对象
* @param name 字段名
* @param value 字段类型
*/
public static void copyProperty(Object bean, String name, Object value)
throws Excel4JException {
if (null == name || null == value)
return;
Field field = matchClassField(bean.getClass(), name);
if (null == field)
return;
Method method;
try {
method = getterOrSetter(bean.getClass(), name, FieldAccessType.SETTER);
if (value.getClass() == field.getType()) {
method.invoke(bean, value);
} else {
method.invoke(bean, str2TargetClass(value.toString(), field.getType()));
}
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
throw new Excel4JException(e);
}
}
/**
* 计算公式结果
*
* @param cell 单元格类型为公式的单元格
* @return 返回单元格计算后的值 格式化成String
* @author QingMings
* Email:1821063757@qq.com
* date 2018-01-13
*/
public static String calculationFormula(Cell cell) {
CellValue cellValue = cell.getSheet().getWorkbook().getCreationHelper()
.createFormulaEvaluator().evaluate(cell);
return cellValue.formatAsString();
}
}
| false | 2,541 | 8 | 2,754 | 9 | 2,959 | 7 | 2,754 | 9 | 3,444 | 12 | false | false | false | false | false | true |
29822_3 | package com.ab.http;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* © 2012 amsoft.cn
* 名称:EasyX509TrustManager.java
* 描述:SSL自签名的实现类
*
* @author 还如一梦中
* @version v1.0
* @date:2013-11-13 上午9:00:52
*/
public class EasyX509TrustManager implements X509TrustManager {
private X509TrustManager standardTrustManager = null;
/**
* Constructor for EasyX509TrustManager.
*/
public EasyX509TrustManager(KeyStore keystore)
throws NoSuchAlgorithmException, KeyStoreException {
super();
TrustManagerFactory factory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(keystore);
TrustManager[] trustmanagers = factory.getTrustManagers();
if (trustmanagers.length == 0) {
throw new NoSuchAlgorithmException("no trust manager found");
}
this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
/**
* 执行客户端的安全策略
*/
@Override
public void checkClientTrusted(X509Certificate[] certificates,
String authType) throws CertificateException {
standardTrustManager.checkClientTrusted(certificates, authType);
}
/**
* 执行服务器的安全策略
* 检查签名、信任链中证书的有效日期和CRLs
* 清除因证书过期出现的问题
*/
@Override
public void checkServerTrusted(X509Certificate[] certificates,
String authType) throws CertificateException {
// Clean up the certificates chain and build a new one.
// Theoretically, we shouldn't have to do this, but various web servers
// in practice are mis-configured to have out-of-order certificates or
// expired self-issued root certificate.
// int chainLength = certificates.length;
if (certificates.length > 1) {
// 1. we clean the received certificates chain.
// We start from the end-entity certificate, tracing down by
// matching
// the "issuer" field and "subject" field until we can't continue.
// This helps when the certificates are out of order or
// some certificates are not related to the site.
int currIndex;
for (currIndex = 0; currIndex < certificates.length; ++currIndex) {
boolean foundNext = false;
for (int nextIndex = currIndex + 1; nextIndex < certificates.length; ++nextIndex) {
if (certificates[currIndex].getIssuerDN().equals(
certificates[nextIndex].getSubjectDN())) {
foundNext = true;
// Exchange certificates so that 0 through currIndex + 1
// are in proper order
if (nextIndex != currIndex + 1) {
X509Certificate tempCertificate = certificates[nextIndex];
certificates[nextIndex] = certificates[currIndex + 1];
certificates[currIndex + 1] = tempCertificate;
}
break;
}
}
if (!foundNext)
break;
}
// 2. we exam if the last traced certificate is self issued and it
// is expired.
// If so, we drop it and pass the rest to checkServerTrusted(),
// hoping we might
// have a similar but unexpired trusted root.
int chainLength = currIndex + 1;
X509Certificate lastCertificate = certificates[chainLength - 1];
Date now = new Date();
if (lastCertificate.getSubjectDN().equals(
lastCertificate.getIssuerDN())
&& now.after(lastCertificate.getNotAfter())) {
--chainLength;
}
}
// standardTrustManager.checkServerTrusted(certificates, authType);
}
/**
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return this.standardTrustManager.getAcceptedIssuers();
}
} | CraftsmenTech/AndBase | AndBase/src/com/ab/http/EasyX509TrustManager.java | 1,096 | /**
* 执行服务器的安全策略
* 检查签名、信任链中证书的有效日期和CRLs
* 清除因证书过期出现的问题
*/ | block_comment | zh-cn | package com.ab.http;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Date;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
/**
* © 2012 amsoft.cn
* 名称:EasyX509TrustManager.java
* 描述:SSL自签名的实现类
*
* @author 还如一梦中
* @version v1.0
* @date:2013-11-13 上午9:00:52
*/
public class EasyX509TrustManager implements X509TrustManager {
private X509TrustManager standardTrustManager = null;
/**
* Constructor for EasyX509TrustManager.
*/
public EasyX509TrustManager(KeyStore keystore)
throws NoSuchAlgorithmException, KeyStoreException {
super();
TrustManagerFactory factory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init(keystore);
TrustManager[] trustmanagers = factory.getTrustManagers();
if (trustmanagers.length == 0) {
throw new NoSuchAlgorithmException("no trust manager found");
}
this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
/**
* 执行客户端的安全策略
*/
@Override
public void checkClientTrusted(X509Certificate[] certificates,
String authType) throws CertificateException {
standardTrustManager.checkClientTrusted(certificates, authType);
}
/**
* 执行服 <SUF>*/
@Override
public void checkServerTrusted(X509Certificate[] certificates,
String authType) throws CertificateException {
// Clean up the certificates chain and build a new one.
// Theoretically, we shouldn't have to do this, but various web servers
// in practice are mis-configured to have out-of-order certificates or
// expired self-issued root certificate.
// int chainLength = certificates.length;
if (certificates.length > 1) {
// 1. we clean the received certificates chain.
// We start from the end-entity certificate, tracing down by
// matching
// the "issuer" field and "subject" field until we can't continue.
// This helps when the certificates are out of order or
// some certificates are not related to the site.
int currIndex;
for (currIndex = 0; currIndex < certificates.length; ++currIndex) {
boolean foundNext = false;
for (int nextIndex = currIndex + 1; nextIndex < certificates.length; ++nextIndex) {
if (certificates[currIndex].getIssuerDN().equals(
certificates[nextIndex].getSubjectDN())) {
foundNext = true;
// Exchange certificates so that 0 through currIndex + 1
// are in proper order
if (nextIndex != currIndex + 1) {
X509Certificate tempCertificate = certificates[nextIndex];
certificates[nextIndex] = certificates[currIndex + 1];
certificates[currIndex + 1] = tempCertificate;
}
break;
}
}
if (!foundNext)
break;
}
// 2. we exam if the last traced certificate is self issued and it
// is expired.
// If so, we drop it and pass the rest to checkServerTrusted(),
// hoping we might
// have a similar but unexpired trusted root.
int chainLength = currIndex + 1;
X509Certificate lastCertificate = certificates[chainLength - 1];
Date now = new Date();
if (lastCertificate.getSubjectDN().equals(
lastCertificate.getIssuerDN())
&& now.after(lastCertificate.getNotAfter())) {
--chainLength;
}
}
// standardTrustManager.checkServerTrusted(certificates, authType);
}
/**
* @see javax.net.ssl.X509TrustManager#getAcceptedIssuers()
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return this.standardTrustManager.getAcceptedIssuers();
}
} | false | 1,004 | 42 | 1,096 | 40 | 1,094 | 37 | 1,096 | 40 | 1,453 | 74 | false | false | false | false | false | true |
42246_2 | package com.orong.activity;
import org.json.JSONException;
import org.json.JSONObject;
import com.orong.Constant;
import com.orong.R;
import com.orong.entity.HttpDatas;
import com.orong.utils.net.NetUtils;
import com.orong.utils.net.HttpAsyncTask.TaskCallBack;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class TelUsActivity extends BaseActivity {
private TextView tvTelephone;// 客服电话
private ImageView ivCallService;// 呼叫客服
private EditText etOpinion;// 意见信息
private Button btSubmit;// 确认提交
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tel_us);
initivReabck(this);
setTitle(this, R.string.aboutus);
tvTelephone = (TextView) this.findViewById(R.id.tv_telephone);
ivCallService = (ImageView) this.findViewById(R.id.iv_call_service);
ivCallService.setOnClickListener(this);
etOpinion = (EditText) this.findViewById(R.id.et_opinion);
etOpinion.addTextChangedListener(new SuggestTextWatcher());
btSubmit = (Button) this.findViewById(R.id.bt_submit);
btSubmit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_call_service:
callPhone();
break;
case R.id.bt_submit:
submintOpinion();
break;
default:
super.onClick(v);
break;
}
}
/**
* 启动打电话功能
*/
private void callPhone() {
String phone = tvTelephone.getText().toString();
Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phone));
startActivity(intent);
}
private void submintOpinion() {
String opinion = etOpinion.getText().toString().trim();
if ("".equals(opinion)) {
Toast.makeText(this, "意见不能为空", 0).show();
return;
}
if (opinion.length() < 5) {
Toast.makeText(this, getString(R.string.text_less_than_5), 0).show();
return;
}
if (opinion.length() > 100) {
Toast.makeText(this, getString(R.string.text_more_than_100), 0).show();
return;
}
HttpDatas datas = new HttpDatas(Constant.USERAPI);
datas.putParam("method", "ContactUs");
datas.putParam("reason", opinion);
NetUtils.sendRequest(datas, this, getString(R.string.uploading_message), new TaskCallBack() {
@Override
public int excueHttpResponse(String respondsStr) {
int code = 0;
try {
JSONObject jsonObject = new JSONObject(respondsStr);
code = jsonObject.getInt("code");
} catch (JSONException e) {
e.printStackTrace();
}
return code;
}
@Override
public void beforeTask() {
}
@Override
public void afterTask(int result) {
switch (result) {
case Constant.RESPONSE_OK:
Toast.makeText(getApplicationContext(), getString(R.string.thanks_for_opinion), 0).show();
break;
case 3009:
Toast.makeText(getApplicationContext(), getString(R.string.was_resummit), 0).show();
break;
default:
showResulttoast(result, TelUsActivity.this);
break;
}
}
});
}
class SuggestTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
int length = s.length();
if (length > 100) {
s.delete(length - 1, length);
length--;
Toast.makeText(getApplicationContext(), "字数超限", 0).show();
return;
}
}
}
}
| CraftsmenTech/jurongwang | src/com/orong/activity/TelUsActivity.java | 1,211 | // 意见信息
| line_comment | zh-cn | package com.orong.activity;
import org.json.JSONException;
import org.json.JSONObject;
import com.orong.Constant;
import com.orong.R;
import com.orong.entity.HttpDatas;
import com.orong.utils.net.NetUtils;
import com.orong.utils.net.HttpAsyncTask.TaskCallBack;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class TelUsActivity extends BaseActivity {
private TextView tvTelephone;// 客服电话
private ImageView ivCallService;// 呼叫客服
private EditText etOpinion;// 意见 <SUF>
private Button btSubmit;// 确认提交
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tel_us);
initivReabck(this);
setTitle(this, R.string.aboutus);
tvTelephone = (TextView) this.findViewById(R.id.tv_telephone);
ivCallService = (ImageView) this.findViewById(R.id.iv_call_service);
ivCallService.setOnClickListener(this);
etOpinion = (EditText) this.findViewById(R.id.et_opinion);
etOpinion.addTextChangedListener(new SuggestTextWatcher());
btSubmit = (Button) this.findViewById(R.id.bt_submit);
btSubmit.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.iv_call_service:
callPhone();
break;
case R.id.bt_submit:
submintOpinion();
break;
default:
super.onClick(v);
break;
}
}
/**
* 启动打电话功能
*/
private void callPhone() {
String phone = tvTelephone.getText().toString();
Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phone));
startActivity(intent);
}
private void submintOpinion() {
String opinion = etOpinion.getText().toString().trim();
if ("".equals(opinion)) {
Toast.makeText(this, "意见不能为空", 0).show();
return;
}
if (opinion.length() < 5) {
Toast.makeText(this, getString(R.string.text_less_than_5), 0).show();
return;
}
if (opinion.length() > 100) {
Toast.makeText(this, getString(R.string.text_more_than_100), 0).show();
return;
}
HttpDatas datas = new HttpDatas(Constant.USERAPI);
datas.putParam("method", "ContactUs");
datas.putParam("reason", opinion);
NetUtils.sendRequest(datas, this, getString(R.string.uploading_message), new TaskCallBack() {
@Override
public int excueHttpResponse(String respondsStr) {
int code = 0;
try {
JSONObject jsonObject = new JSONObject(respondsStr);
code = jsonObject.getInt("code");
} catch (JSONException e) {
e.printStackTrace();
}
return code;
}
@Override
public void beforeTask() {
}
@Override
public void afterTask(int result) {
switch (result) {
case Constant.RESPONSE_OK:
Toast.makeText(getApplicationContext(), getString(R.string.thanks_for_opinion), 0).show();
break;
case 3009:
Toast.makeText(getApplicationContext(), getString(R.string.was_resummit), 0).show();
break;
default:
showResulttoast(result, TelUsActivity.this);
break;
}
}
});
}
class SuggestTextWatcher implements TextWatcher {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
int length = s.length();
if (length > 100) {
s.delete(length - 1, length);
length--;
Toast.makeText(getApplicationContext(), "字数超限", 0).show();
return;
}
}
}
}
| false | 934 | 7 | 1,195 | 7 | 1,161 | 5 | 1,195 | 7 | 1,484 | 9 | false | false | false | false | false | true |
34722_11 | package ai.zhuanzhi.dl4j.rbm4j;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.ops.transforms.Transforms;
/**
* @author hu
* 该教程由专知(www.zhuanzhi.ai)提供
*/
public class RBM {
protected INDArray w, b, a;
public RBM(int vDim, int hDim){
w = Nd4j.rand(vDim, hDim);
b = Nd4j.rand(new int[]{hDim});
a = Nd4j.rand(new int[]{vDim});
}
//输入可见层v,输出隐藏层为1的概率p(h|v)
protected INDArray computeHProbs(INDArray vSamples){
INDArray hProbs = vSamples.mmul(w).addRowVector(b);
hProbs = Transforms.sigmoid(hProbs);
return hProbs;
}
//输入隐藏层h,输出可见层为1的概率p(v|h)
protected INDArray computeVProbs(INDArray hSamples){
INDArray vProbs = hSamples.mmul(w.transpose()).addRowVector(a);
vProbs = Transforms.sigmoid(vProbs);
return vProbs;
}
//输入可见层,输出RBM重构的结果
public INDArray reconstruct(INDArray vSamples){
INDArray hProbs = computeHProbs(vSamples);
INDArray hSamples = bernoulliSample(hProbs);
INDArray negVSamples = bernoulliSample(computeVProbs(hSamples));
return negVSamples;
}
public double fit(INDArray vSamples, double learningRate){
INDArray hProbs = computeHProbs(vSamples);
INDArray hSamples = bernoulliSample(hProbs);
INDArray negVSamples = bernoulliSample(computeVProbs(hSamples));
INDArray negHProbs = computeHProbs(negVSamples);
INDArray mseTempMatrix = negVSamples.sub(vSamples);
double loss = mseTempMatrix.mul(mseTempMatrix).div(2).mean(0,1).getDouble(0,0);
//正梯度
INDArray posGrad = vSamples.transpose().mmul(hProbs);
//负梯度
INDArray negGrad = negVSamples.transpose().mmul(negHProbs);
//输入样本数量
int numSamples = vSamples.shape()[0];
//计算并更新参数
INDArray dw = posGrad.sub(negGrad).mul(learningRate/numSamples);
INDArray db = hProbs.mean(0).sub(negHProbs.mean(0)).mul(learningRate);
INDArray da = vSamples.mean(0).sub(negVSamples.mean(0)).mul(learningRate);
w.addi(dw);
b.addi(db);
a.addi(da);
return loss;
}
//伯努利采样
protected INDArray bernoulliSample(INDArray probs){
INDArray randArray = Nd4j.rand(probs.shape());
INDArray samples = probs.gt(randArray);
return samples;
}
public static void main(String[] args) {
//手工设置一组数据
double[][] rawVSamples = new double[][]{
{1,1,1,1,0,0,0,0},
{1,1,1,1,0,0,0,0},
{0,0,1,1,1,1,0,0},
{0,0,1,1,1,1,0,0},
{0,0,0,0,1,1,1,1},
{0,0,0,0,1,1,1,1}
};
INDArray vSamples = Nd4j.create(rawVSamples);
//设置RBM(隐藏层大小为2)
RBM rbm = new RBM(vSamples.shape()[1],2);
//训练
for(int i=0;i<20000;i++){
double loss = rbm.fit(vSamples,5e-3);
if(i % 1000 == 0){
System.out.println("batch:"+i+"\tloss:" + loss);
}
}
//显示重构结果
System.out.println("reconstruction:");
System.out.println(rbm.reconstruct(vSamples));
//显示对应的隐藏层激活值(学习到的特征)
System.out.println("features:");
System.out.println(rbm.computeHProbs(vSamples));
}
}
| CrawlScript/RBM4j | src/main/java/ai/zhuanzhi/dl4j/rbm4j/RBM.java | 1,123 | //显示重构结果 | line_comment | zh-cn | package ai.zhuanzhi.dl4j.rbm4j;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.ops.transforms.Transforms;
/**
* @author hu
* 该教程由专知(www.zhuanzhi.ai)提供
*/
public class RBM {
protected INDArray w, b, a;
public RBM(int vDim, int hDim){
w = Nd4j.rand(vDim, hDim);
b = Nd4j.rand(new int[]{hDim});
a = Nd4j.rand(new int[]{vDim});
}
//输入可见层v,输出隐藏层为1的概率p(h|v)
protected INDArray computeHProbs(INDArray vSamples){
INDArray hProbs = vSamples.mmul(w).addRowVector(b);
hProbs = Transforms.sigmoid(hProbs);
return hProbs;
}
//输入隐藏层h,输出可见层为1的概率p(v|h)
protected INDArray computeVProbs(INDArray hSamples){
INDArray vProbs = hSamples.mmul(w.transpose()).addRowVector(a);
vProbs = Transforms.sigmoid(vProbs);
return vProbs;
}
//输入可见层,输出RBM重构的结果
public INDArray reconstruct(INDArray vSamples){
INDArray hProbs = computeHProbs(vSamples);
INDArray hSamples = bernoulliSample(hProbs);
INDArray negVSamples = bernoulliSample(computeVProbs(hSamples));
return negVSamples;
}
public double fit(INDArray vSamples, double learningRate){
INDArray hProbs = computeHProbs(vSamples);
INDArray hSamples = bernoulliSample(hProbs);
INDArray negVSamples = bernoulliSample(computeVProbs(hSamples));
INDArray negHProbs = computeHProbs(negVSamples);
INDArray mseTempMatrix = negVSamples.sub(vSamples);
double loss = mseTempMatrix.mul(mseTempMatrix).div(2).mean(0,1).getDouble(0,0);
//正梯度
INDArray posGrad = vSamples.transpose().mmul(hProbs);
//负梯度
INDArray negGrad = negVSamples.transpose().mmul(negHProbs);
//输入样本数量
int numSamples = vSamples.shape()[0];
//计算并更新参数
INDArray dw = posGrad.sub(negGrad).mul(learningRate/numSamples);
INDArray db = hProbs.mean(0).sub(negHProbs.mean(0)).mul(learningRate);
INDArray da = vSamples.mean(0).sub(negVSamples.mean(0)).mul(learningRate);
w.addi(dw);
b.addi(db);
a.addi(da);
return loss;
}
//伯努利采样
protected INDArray bernoulliSample(INDArray probs){
INDArray randArray = Nd4j.rand(probs.shape());
INDArray samples = probs.gt(randArray);
return samples;
}
public static void main(String[] args) {
//手工设置一组数据
double[][] rawVSamples = new double[][]{
{1,1,1,1,0,0,0,0},
{1,1,1,1,0,0,0,0},
{0,0,1,1,1,1,0,0},
{0,0,1,1,1,1,0,0},
{0,0,0,0,1,1,1,1},
{0,0,0,0,1,1,1,1}
};
INDArray vSamples = Nd4j.create(rawVSamples);
//设置RBM(隐藏层大小为2)
RBM rbm = new RBM(vSamples.shape()[1],2);
//训练
for(int i=0;i<20000;i++){
double loss = rbm.fit(vSamples,5e-3);
if(i % 1000 == 0){
System.out.println("batch:"+i+"\tloss:" + loss);
}
}
//显示 <SUF>
System.out.println("reconstruction:");
System.out.println(rbm.reconstruct(vSamples));
//显示对应的隐藏层激活值(学习到的特征)
System.out.println("features:");
System.out.println(rbm.computeHProbs(vSamples));
}
}
| false | 1,009 | 4 | 1,123 | 5 | 1,169 | 5 | 1,123 | 5 | 1,393 | 7 | false | false | false | false | false | true |
60032_8 | package com.ynyes.lyz.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* 调色包实体类
*
* @author dengxiao
*/
@Entity
public class TdColorPackage {
// id
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// 调色包名称
@Column
private String name;
// 调色包编号
@Column
private String number;
// 调色包图片
@Column
private String imageUri;
// 库存
@Column
private Long inventory;
// 当前销售价格
@Column(scale = 2)
private Double salePrice;
// 当前进货价格
@Column(scale = 2)
private Double stockPrice;
// 购买数量
@Column
private Long quantity;
//总价
@Column
private Double totalPrice;
// 归属: 1 华润商品 2 乐意装商品
@Column
private Long belongTo;
// 排序号
@Column
private Double sortId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getImageUri() {
return imageUri;
}
public void setImageUri(String imageUri) {
this.imageUri = imageUri;
}
public Long getInventory() {
return inventory;
}
public void setInventory(Long inventory) {
this.inventory = inventory;
}
public Double getSalePrice() {
return salePrice;
}
public void setSalePrice(Double salePrice) {
this.salePrice = salePrice;
}
public Double getStockPrice() {
return stockPrice;
}
public void setStockPrice(Double stockPrice) {
this.stockPrice = stockPrice;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public Long getBelongTo() {
return belongTo;
}
public void setBelongTo(Long belongTo) {
this.belongTo = belongTo;
}
public Double getSortId() {
return sortId;
}
public void setSortId(Double sortId) {
this.sortId = sortId;
}
}
| CrazyApeDX/leyizhuang2.0-manager | src/main/java/com/ynyes/lyz/entity/TdColorPackage.java | 768 | // 排序号 | line_comment | zh-cn | package com.ynyes.lyz.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
* 调色包实体类
*
* @author dengxiao
*/
@Entity
public class TdColorPackage {
// id
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
// 调色包名称
@Column
private String name;
// 调色包编号
@Column
private String number;
// 调色包图片
@Column
private String imageUri;
// 库存
@Column
private Long inventory;
// 当前销售价格
@Column(scale = 2)
private Double salePrice;
// 当前进货价格
@Column(scale = 2)
private Double stockPrice;
// 购买数量
@Column
private Long quantity;
//总价
@Column
private Double totalPrice;
// 归属: 1 华润商品 2 乐意装商品
@Column
private Long belongTo;
// 排序 <SUF>
@Column
private Double sortId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getImageUri() {
return imageUri;
}
public void setImageUri(String imageUri) {
this.imageUri = imageUri;
}
public Long getInventory() {
return inventory;
}
public void setInventory(Long inventory) {
this.inventory = inventory;
}
public Double getSalePrice() {
return salePrice;
}
public void setSalePrice(Double salePrice) {
this.salePrice = salePrice;
}
public Double getStockPrice() {
return stockPrice;
}
public void setStockPrice(Double stockPrice) {
this.stockPrice = stockPrice;
}
public Long getQuantity() {
return quantity;
}
public void setQuantity(Long quantity) {
this.quantity = quantity;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public Long getBelongTo() {
return belongTo;
}
public void setBelongTo(Long belongTo) {
this.belongTo = belongTo;
}
public Double getSortId() {
return sortId;
}
public void setSortId(Double sortId) {
this.sortId = sortId;
}
}
| false | 589 | 5 | 768 | 4 | 744 | 3 | 768 | 4 | 888 | 7 | false | false | false | false | false | true |
20931_4 | package com.lou.simhasher;
import java.math.BigInteger;
import java.util.Map;
import java.util.Set;
import com.lou.simhasher.util.FNVHash;
/**
* 文本去重算法的simhash类
* 步骤如下:
* 1,对文本分词,得到N维特征向量(默认为64维)
* 2,为分词设置权重(tf-idf)
* 3,为特征向量计算哈希
* 4,对所有特征向量加权,累加(目前仅进行非加权累加)
* 5,对累加结果,大于零置一,小于零置零
* 6,得到文本指纹(fingerprint)
*
* @author louxuezheng@hotmail.com
*/
public class SimHasher {
private String hash;
private BigInteger signature;
private KeywordExtractor wordExtractor = KeywordExtractor.getInstance();
/**
* 构造函数
*
* @param content 字符串
*/
public SimHasher(String content) {
this.analysis(content);
}
private void analysis(String content) {
Map<String, Double> wordInfos = wordExtractor.extract(content);
double[] featureVector = new double[FNVHash.HASH_BITS];
Set<String> words = wordInfos.keySet();
// System.out.println(words);
for (String word : words) {
BigInteger wordhash = FNVHash.fnv1aHash64(word);
for (int i = 0; i < FNVHash.HASH_BITS; i++) {
BigInteger bitmask = BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1);
if (wordhash.and(bitmask).signum() != 0) {
featureVector[i] += wordInfos.get(word);
} else {
featureVector[i] -= wordInfos.get(word);
}
}
}
BigInteger signature = BigInteger.ZERO;
StringBuffer hashBuffer = new StringBuffer();
for (int i = 0; i < FNVHash.HASH_BITS; i++) {
if (featureVector[i] >= 0) {
signature = signature.add(BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1));
hashBuffer.append("1");
} else {
hashBuffer.append("0");
}
}
this.hash = hashBuffer.toString();
this.signature = signature;
}
/**
* 汉明距离
*
* @param targetSignature 比较签名
* @return
*/
public int getHammingDistance(BigInteger targetSignature) {
BigInteger x = this.getSignature().xor(targetSignature);
int tot = 0;
// 统计x中二进制位数为1的个数
// 我们想想,一个二进制数减去1,那么,从最后那个1(包括那个1)后面的数字全都反了,
// 对吧,然后,n&(n-1)就相当于把后面的数字清0,
// 我们看n能做多少次这样的操作就OK了。
while (x.signum() != 0) {
tot += 1;
x = x.and(x.subtract(new BigInteger("1")));
}
return tot;
}
/**
* hash距离。二进制比较
*
* @param targetHash 比较目标
* @return
*/
public int getHashDistance(String targetHash) {
int distance;
if (this.getHash().length() != targetHash.length()) {
distance = -1;
} else {
distance = 0;
for (int i = 0; i < this.getHash().length(); i++) {
if (this.getHash().charAt(i) != targetHash.charAt(i)) {
distance++;
}
}
}
return distance;
}
public String getHash() {
return this.hash;
}
public BigInteger getSignature() {
return this.signature;
}
}
| CreekLou/simhash | src/main/java/com/lou/simhasher/SimHasher.java | 1,024 | // 统计x中二进制位数为1的个数
| line_comment | zh-cn | package com.lou.simhasher;
import java.math.BigInteger;
import java.util.Map;
import java.util.Set;
import com.lou.simhasher.util.FNVHash;
/**
* 文本去重算法的simhash类
* 步骤如下:
* 1,对文本分词,得到N维特征向量(默认为64维)
* 2,为分词设置权重(tf-idf)
* 3,为特征向量计算哈希
* 4,对所有特征向量加权,累加(目前仅进行非加权累加)
* 5,对累加结果,大于零置一,小于零置零
* 6,得到文本指纹(fingerprint)
*
* @author louxuezheng@hotmail.com
*/
public class SimHasher {
private String hash;
private BigInteger signature;
private KeywordExtractor wordExtractor = KeywordExtractor.getInstance();
/**
* 构造函数
*
* @param content 字符串
*/
public SimHasher(String content) {
this.analysis(content);
}
private void analysis(String content) {
Map<String, Double> wordInfos = wordExtractor.extract(content);
double[] featureVector = new double[FNVHash.HASH_BITS];
Set<String> words = wordInfos.keySet();
// System.out.println(words);
for (String word : words) {
BigInteger wordhash = FNVHash.fnv1aHash64(word);
for (int i = 0; i < FNVHash.HASH_BITS; i++) {
BigInteger bitmask = BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1);
if (wordhash.and(bitmask).signum() != 0) {
featureVector[i] += wordInfos.get(word);
} else {
featureVector[i] -= wordInfos.get(word);
}
}
}
BigInteger signature = BigInteger.ZERO;
StringBuffer hashBuffer = new StringBuffer();
for (int i = 0; i < FNVHash.HASH_BITS; i++) {
if (featureVector[i] >= 0) {
signature = signature.add(BigInteger.ONE.shiftLeft(FNVHash.HASH_BITS - i - 1));
hashBuffer.append("1");
} else {
hashBuffer.append("0");
}
}
this.hash = hashBuffer.toString();
this.signature = signature;
}
/**
* 汉明距离
*
* @param targetSignature 比较签名
* @return
*/
public int getHammingDistance(BigInteger targetSignature) {
BigInteger x = this.getSignature().xor(targetSignature);
int tot = 0;
// 统计 <SUF>
// 我们想想,一个二进制数减去1,那么,从最后那个1(包括那个1)后面的数字全都反了,
// 对吧,然后,n&(n-1)就相当于把后面的数字清0,
// 我们看n能做多少次这样的操作就OK了。
while (x.signum() != 0) {
tot += 1;
x = x.and(x.subtract(new BigInteger("1")));
}
return tot;
}
/**
* hash距离。二进制比较
*
* @param targetHash 比较目标
* @return
*/
public int getHashDistance(String targetHash) {
int distance;
if (this.getHash().length() != targetHash.length()) {
distance = -1;
} else {
distance = 0;
for (int i = 0; i < this.getHash().length(); i++) {
if (this.getHash().charAt(i) != targetHash.charAt(i)) {
distance++;
}
}
}
return distance;
}
public String getHash() {
return this.hash;
}
public BigInteger getSignature() {
return this.signature;
}
}
| false | 878 | 17 | 1,020 | 14 | 1,004 | 14 | 1,020 | 14 | 1,313 | 17 | false | false | false | false | false | true |
18675_4 | package UI;
// 所有的道具包
public class Bag extends FlyObject {
public Bag(int x, int y) {
this.x = x;
this.y = y;
this.height = 50;
this.width = 50;
}
/**
* 根据的类型来获取新的道具包,x和y是被打的砖块的位置,道具在砖块的位置生成
* @param i
* @param x
* @param y
* @return
*/
public static Bag getBag(int i, int x, int y) {
Bag bag = null;
switch (i) {
case 1:
bag = new RocketBag(x, y);
break;
case 2:
bag = new PunchBag(x, y);
break;
case 3:
bag = new BoomBag(x, y);
break;
case 4:
bag = new LengthenBag(x, y);
break;
case 5:
bag = new ShortenBag(x, y);
break;
case 6:
bag = new DieBag(x, y);
break;
case 7:
bag = new BigBallBag(x, y);
break;
case 8:
bag = new SmallBallBag(x, y);
break;
case 9:
bag = new CommonBallBag(x, y);
break;
}
return bag;
}
}
// 导弹球
class RocketBag extends Bag {
public RocketBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/RocketBag.png");
}
}
// 穿刺球
class PunchBag extends Bag {
public PunchBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/PunchBag.png");
}
}
// 炸弹球
class BoomBag extends Bag {
public BoomBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/BoomBag.png");
}
}
// 让挡板变长
class LengthenBag extends Bag {
public LengthenBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/LengthenBag.png");
}
}
// 让挡板变小
class ShortenBag extends Bag {
public ShortenBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/ShortenBag.png");
}
}
// 死亡
class DieBag extends Bag {
public DieBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/DieBag.png");
}
}
// 让球变大
class BigBallBag extends Bag {
public BigBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/BigBallBag.png");
}
}
// 让球变小
class SmallBallBag extends Bag {
public SmallBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/SmallBallBag.png");
}
}
// 普通球道具包
class CommonBallBag extends Bag {
public CommonBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/ball.png");
}
}
| CrispyCandy750/hit_brick | UI/Bag.java | 841 | // 炸弹球 | line_comment | zh-cn | package UI;
// 所有的道具包
public class Bag extends FlyObject {
public Bag(int x, int y) {
this.x = x;
this.y = y;
this.height = 50;
this.width = 50;
}
/**
* 根据的类型来获取新的道具包,x和y是被打的砖块的位置,道具在砖块的位置生成
* @param i
* @param x
* @param y
* @return
*/
public static Bag getBag(int i, int x, int y) {
Bag bag = null;
switch (i) {
case 1:
bag = new RocketBag(x, y);
break;
case 2:
bag = new PunchBag(x, y);
break;
case 3:
bag = new BoomBag(x, y);
break;
case 4:
bag = new LengthenBag(x, y);
break;
case 5:
bag = new ShortenBag(x, y);
break;
case 6:
bag = new DieBag(x, y);
break;
case 7:
bag = new BigBallBag(x, y);
break;
case 8:
bag = new SmallBallBag(x, y);
break;
case 9:
bag = new CommonBallBag(x, y);
break;
}
return bag;
}
}
// 导弹球
class RocketBag extends Bag {
public RocketBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/RocketBag.png");
}
}
// 穿刺球
class PunchBag extends Bag {
public PunchBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/PunchBag.png");
}
}
// 炸弹 <SUF>
class BoomBag extends Bag {
public BoomBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/BoomBag.png");
}
}
// 让挡板变长
class LengthenBag extends Bag {
public LengthenBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/LengthenBag.png");
}
}
// 让挡板变小
class ShortenBag extends Bag {
public ShortenBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/ShortenBag.png");
}
}
// 死亡
class DieBag extends Bag {
public DieBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/DieBag.png");
}
}
// 让球变大
class BigBallBag extends Bag {
public BigBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/BigBallBag.png");
}
}
// 让球变小
class SmallBallBag extends Bag {
public SmallBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/SmallBallBag.png");
}
}
// 普通球道具包
class CommonBallBag extends Bag {
public CommonBallBag(int x, int y) {
super(x, y);
image = ImageManager.getImage("/Image/ball.png");
}
}
| false | 746 | 6 | 841 | 6 | 878 | 4 | 841 | 6 | 999 | 9 | false | false | false | false | false | true |
62978_3 | package org.brewchain.account.function;
import org.apache.felix.ipojo.util.Log;
import org.brewchain.account.core.AccountHelper;
import org.brewchain.account.test.InternalCallTest;
import com.google.protobuf.ByteString;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class InternalFunction {
/**
* 挖矿奖励
*
* @param accountHelper
* @param blackHoleAddress
* @param coinBase
* @param balance
* @throws Exception
*/
public static void MinerReward(AccountHelper accountHelper, String... params) throws Exception {
String blackHoleAddress = "";
String balance = "0";
String coinBase = "";
log.debug(String.format("call MinerReward!"));
accountHelper.addBalance(ByteString.copyFromUtf8(coinBase).toByteArray(), Long.valueOf(balance));
// 黑洞地址
accountHelper.addBalance(ByteString.copyFromUtf8(blackHoleAddress).toByteArray(), 0 - Long.valueOf(balance));
}
/**
* 挖矿惩罚
*
* @param accountHelper
* @param blackHoleAddress
* @param coinBase
* @param balance
* @throws Exception
*/
public static void MinerPunish(AccountHelper accountHelper, byte[] blackHoleAddress, byte[] coinBase, long balance)
throws Exception {
accountHelper.addBalance(coinBase, 0 - balance);
// 黑洞地址
accountHelper.addBalance(blackHoleAddress, balance);
}
}
| CryptoWorldChain/chaincore | account/src/main/java/org/brewchain/account/function/InternalFunction.java | 389 | // 黑洞地址 | line_comment | zh-cn | package org.brewchain.account.function;
import org.apache.felix.ipojo.util.Log;
import org.brewchain.account.core.AccountHelper;
import org.brewchain.account.test.InternalCallTest;
import com.google.protobuf.ByteString;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class InternalFunction {
/**
* 挖矿奖励
*
* @param accountHelper
* @param blackHoleAddress
* @param coinBase
* @param balance
* @throws Exception
*/
public static void MinerReward(AccountHelper accountHelper, String... params) throws Exception {
String blackHoleAddress = "";
String balance = "0";
String coinBase = "";
log.debug(String.format("call MinerReward!"));
accountHelper.addBalance(ByteString.copyFromUtf8(coinBase).toByteArray(), Long.valueOf(balance));
// 黑洞地址
accountHelper.addBalance(ByteString.copyFromUtf8(blackHoleAddress).toByteArray(), 0 - Long.valueOf(balance));
}
/**
* 挖矿惩罚
*
* @param accountHelper
* @param blackHoleAddress
* @param coinBase
* @param balance
* @throws Exception
*/
public static void MinerPunish(AccountHelper accountHelper, byte[] blackHoleAddress, byte[] coinBase, long balance)
throws Exception {
accountHelper.addBalance(coinBase, 0 - balance);
// 黑洞 <SUF>
accountHelper.addBalance(blackHoleAddress, balance);
}
}
| false | 342 | 5 | 389 | 5 | 387 | 4 | 389 | 5 | 479 | 8 | false | false | false | false | false | true |
34755_5 | package com.cui.rectprogress;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by CZH on 2017/6/15.
* RectProgress
*/
public class RectProgress extends View {
private final int VERTICAL = 1;
private final int HORIZONTAL = 2;
private final int defaultBgColor = 0xFf000000;
private final int defaultProgressColor = 0xFFFF4081;
private int bgColor = defaultBgColor;
private int progressColor = defaultProgressColor;
/*圆角弧度*/
private float rectRadius = 20f;
/*画背景使用的Rect*/
private RectF bgRect = new RectF();
/*画进度使用的Rect*/
private RectF progressRect = new RectF();
/*背景画笔*/
private Paint bgPaint;
/*进度画笔*/
private Paint progressPaint;
/*进度方向*/
private int orientation = VERTICAL;
private int max = 100;
private int progress = 15;
private Bitmap bitmap;
/*icon显示区域Rect*/
private Rect srcRect;
/*icon显示位置Rect*/
private Rect dstRect;
private float iconPadding;
/*进度百分比*/
private int percent = 0;
public RectProgress(Context context) {
super(context);
init(context, null);
}
public RectProgress(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public RectProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
//关闭硬件加速,不然setXfermode()可能会不生效
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
if (attrs != null) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RectProgress);
bgColor = typedArray.getColor(R.styleable.RectProgress_bgColor, defaultBgColor);
progressColor = typedArray.getColor(R.styleable.RectProgress_progressColor, defaultProgressColor);
progress = typedArray.getInteger(R.styleable.RectProgress_progressValue, progress);
max = typedArray.getInteger(R.styleable.RectProgress_progressMax, max);
if (max <= 0)
throw new RuntimeException("Max 必须大于 0");
orientation = typedArray.getInteger(R.styleable.RectProgress_progressOrientation, VERTICAL);
int imgSrc = typedArray.getResourceId(R.styleable.RectProgress_iconSrc, 0);
iconPadding = typedArray.getDimensionPixelSize(R.styleable.RectProgress_iconPadding, 10);
rectRadius = typedArray.getDimensionPixelSize(R.styleable.RectProgress_rectRadius, 20);
if (max < progress) {
progress = max;
}
typedArray.recycle();
if (imgSrc != 0) {
bitmap = ((BitmapDrawable) getResources().getDrawable(imgSrc)).getBitmap();
}
}
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setColor(bgColor);
progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
progressPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
progressPaint.setColor(progressColor);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bgRect.set(getPaddingLeft()
, getPaddingTop()
, getWidth() - getPaddingRight()
, getHeight() - getPaddingBottom());
computeProgressRect();
if (bitmap != null) {
srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
int iconSideLength;
if (orientation == VERTICAL) {
iconSideLength = (int) (bgRect.width() - iconPadding * 2);
dstRect = new Rect((int) bgRect.left + (int) iconPadding
, (int) (bgRect.bottom - iconSideLength - iconPadding)
, (int) bgRect.right - (int) iconPadding
, (int) bgRect.bottom - (int) iconPadding);
} else {
iconSideLength = (int) (bgRect.height() - iconPadding * 2);
dstRect = new Rect((int) bgRect.left + (int) iconPadding
, (int) (bgRect.bottom - iconPadding - iconSideLength)
, (int) (bgRect.left + iconPadding + iconSideLength)
, (int) (bgRect.bottom - iconPadding));
}
}
}
@Override
protected void onDraw(Canvas canvas) {
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
int layerId = canvas.saveLayer(0, 0, canvasWidth, canvasHeight, null, Canvas.ALL_SAVE_FLAG);
{
bgPaint.setColor(bgColor);
// draw the background of progress
canvas.drawRoundRect(bgRect, rectRadius, rectRadius, bgPaint);
// draw progress
canvas.drawRect(progressRect, progressPaint);
bgPaint.setXfermode(null);
if (bitmap != null) {
//draw icon
canvas.drawBitmap(bitmap, srcRect, dstRect, bgPaint);
}
}
canvas.restoreToCount(layerId);
// TODO: 弄明白为什么在xml预览中,canvas.restoreToCount
// TODO: 会导致后续的canvas对象为空 但canvas.restore方法则不会导致这个问题
// canvas.restore();
// canvas.save();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//在家进度条内才执行操作
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (bgRect.contains(event.getX(), event.getY())) {
//按下时,在进度内才执行操作
handleTouch(event);
invalidate();
return true;
}
break;
case MotionEvent.ACTION_MOVE:
handleTouch(event);
invalidate();
break;
}
invalidate();
return super.onTouchEvent(event);
}
private void handleTouch(MotionEvent event) {
if (orientation == VERTICAL) {
if (event.getY() < bgRect.top) {
//触点超出Progress顶部
progressRect.top = bgRect.top;
} else if (event.getY() > bgRect.bottom) {
//触点超过Progress底部
progressRect.top = bgRect.bottom;
} else {
progressRect.top = event.getY();
}
int tmp = (int) ((progressRect.height() / bgRect.height()) * 100);
if (percent != tmp) {
percent = tmp;
progress = percent * max / 100;
if (changedListener != null)
changedListener.onProgressChanged(progress, percent);
}
} else {
if (event.getX() > bgRect.right) {
//触点超出Progress右端
progressRect.right = bgRect.right;
} else if (event.getX() < bgRect.left) {
//触点超出Progress左端
progressRect.right = bgRect.left;
} else {
progressRect.right = event.getX();
}
int tmp = (int) ((progressRect.width() / bgRect.width()) * 100);
if (percent != tmp) {
percent = tmp;
progress = percent * max / 100;
if (changedListener != null)
changedListener.onProgressChanged(progress, percent);
}
}
}
private OnProgressChangedListener changedListener;
public void setChangedListener(OnProgressChangedListener changedListener) {
this.changedListener = changedListener;
}
public interface OnProgressChangedListener {
void onProgressChanged(int currentValue, int percent);
}
public void setMax(int m) {
if (max <= 0)
throw new RuntimeException("Max 必须大于 0");
max = m;
}
public void setProgress(int p) {
int oldProgress = progress;
progress = p;
if (max < progress) {
progress = max;
} else if (progress < 0)
progress = 0;
startProgressAnim(oldProgress);
}
private ValueAnimator valueAnimator;
/**/
private void startProgressAnim(int oldProgress) {
if (valueAnimator != null && valueAnimator.isRunning()) {
valueAnimator.cancel();
}
valueAnimator = ValueAnimator.ofInt(oldProgress, progress);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
progress = (int) animation.getAnimatedValue();
computeProgressRect();
invalidate();
}
});
valueAnimator.setDuration(1000);
valueAnimator.start();
}
/**
* 计算进度Progress
*/
private void computeProgressRect() {
if (orientation == VERTICAL) {
progressRect.set(bgRect.left
, bgRect.bottom - progress * bgRect.height() / max
, bgRect.right
, bgRect.bottom);
} else {
progressRect.set(bgRect.left
, bgRect.top
, bgRect.left + progress * bgRect.width() / max
, bgRect.bottom);
}
}
}
| CuiZhaoHui/IOS11RectProgress | rectprogress/src/main/java/com/cui/rectprogress/RectProgress.java | 2,370 | /*进度画笔*/ | block_comment | zh-cn | package com.cui.rectprogress;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by CZH on 2017/6/15.
* RectProgress
*/
public class RectProgress extends View {
private final int VERTICAL = 1;
private final int HORIZONTAL = 2;
private final int defaultBgColor = 0xFf000000;
private final int defaultProgressColor = 0xFFFF4081;
private int bgColor = defaultBgColor;
private int progressColor = defaultProgressColor;
/*圆角弧度*/
private float rectRadius = 20f;
/*画背景使用的Rect*/
private RectF bgRect = new RectF();
/*画进度使用的Rect*/
private RectF progressRect = new RectF();
/*背景画笔*/
private Paint bgPaint;
/*进度画 <SUF>*/
private Paint progressPaint;
/*进度方向*/
private int orientation = VERTICAL;
private int max = 100;
private int progress = 15;
private Bitmap bitmap;
/*icon显示区域Rect*/
private Rect srcRect;
/*icon显示位置Rect*/
private Rect dstRect;
private float iconPadding;
/*进度百分比*/
private int percent = 0;
public RectProgress(Context context) {
super(context);
init(context, null);
}
public RectProgress(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public RectProgress(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
//关闭硬件加速,不然setXfermode()可能会不生效
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
if (attrs != null) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RectProgress);
bgColor = typedArray.getColor(R.styleable.RectProgress_bgColor, defaultBgColor);
progressColor = typedArray.getColor(R.styleable.RectProgress_progressColor, defaultProgressColor);
progress = typedArray.getInteger(R.styleable.RectProgress_progressValue, progress);
max = typedArray.getInteger(R.styleable.RectProgress_progressMax, max);
if (max <= 0)
throw new RuntimeException("Max 必须大于 0");
orientation = typedArray.getInteger(R.styleable.RectProgress_progressOrientation, VERTICAL);
int imgSrc = typedArray.getResourceId(R.styleable.RectProgress_iconSrc, 0);
iconPadding = typedArray.getDimensionPixelSize(R.styleable.RectProgress_iconPadding, 10);
rectRadius = typedArray.getDimensionPixelSize(R.styleable.RectProgress_rectRadius, 20);
if (max < progress) {
progress = max;
}
typedArray.recycle();
if (imgSrc != 0) {
bitmap = ((BitmapDrawable) getResources().getDrawable(imgSrc)).getBitmap();
}
}
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setColor(bgColor);
progressPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
progressPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP));
progressPaint.setColor(progressColor);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bgRect.set(getPaddingLeft()
, getPaddingTop()
, getWidth() - getPaddingRight()
, getHeight() - getPaddingBottom());
computeProgressRect();
if (bitmap != null) {
srcRect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
int iconSideLength;
if (orientation == VERTICAL) {
iconSideLength = (int) (bgRect.width() - iconPadding * 2);
dstRect = new Rect((int) bgRect.left + (int) iconPadding
, (int) (bgRect.bottom - iconSideLength - iconPadding)
, (int) bgRect.right - (int) iconPadding
, (int) bgRect.bottom - (int) iconPadding);
} else {
iconSideLength = (int) (bgRect.height() - iconPadding * 2);
dstRect = new Rect((int) bgRect.left + (int) iconPadding
, (int) (bgRect.bottom - iconPadding - iconSideLength)
, (int) (bgRect.left + iconPadding + iconSideLength)
, (int) (bgRect.bottom - iconPadding));
}
}
}
@Override
protected void onDraw(Canvas canvas) {
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
int layerId = canvas.saveLayer(0, 0, canvasWidth, canvasHeight, null, Canvas.ALL_SAVE_FLAG);
{
bgPaint.setColor(bgColor);
// draw the background of progress
canvas.drawRoundRect(bgRect, rectRadius, rectRadius, bgPaint);
// draw progress
canvas.drawRect(progressRect, progressPaint);
bgPaint.setXfermode(null);
if (bitmap != null) {
//draw icon
canvas.drawBitmap(bitmap, srcRect, dstRect, bgPaint);
}
}
canvas.restoreToCount(layerId);
// TODO: 弄明白为什么在xml预览中,canvas.restoreToCount
// TODO: 会导致后续的canvas对象为空 但canvas.restore方法则不会导致这个问题
// canvas.restore();
// canvas.save();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//在家进度条内才执行操作
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (bgRect.contains(event.getX(), event.getY())) {
//按下时,在进度内才执行操作
handleTouch(event);
invalidate();
return true;
}
break;
case MotionEvent.ACTION_MOVE:
handleTouch(event);
invalidate();
break;
}
invalidate();
return super.onTouchEvent(event);
}
private void handleTouch(MotionEvent event) {
if (orientation == VERTICAL) {
if (event.getY() < bgRect.top) {
//触点超出Progress顶部
progressRect.top = bgRect.top;
} else if (event.getY() > bgRect.bottom) {
//触点超过Progress底部
progressRect.top = bgRect.bottom;
} else {
progressRect.top = event.getY();
}
int tmp = (int) ((progressRect.height() / bgRect.height()) * 100);
if (percent != tmp) {
percent = tmp;
progress = percent * max / 100;
if (changedListener != null)
changedListener.onProgressChanged(progress, percent);
}
} else {
if (event.getX() > bgRect.right) {
//触点超出Progress右端
progressRect.right = bgRect.right;
} else if (event.getX() < bgRect.left) {
//触点超出Progress左端
progressRect.right = bgRect.left;
} else {
progressRect.right = event.getX();
}
int tmp = (int) ((progressRect.width() / bgRect.width()) * 100);
if (percent != tmp) {
percent = tmp;
progress = percent * max / 100;
if (changedListener != null)
changedListener.onProgressChanged(progress, percent);
}
}
}
private OnProgressChangedListener changedListener;
public void setChangedListener(OnProgressChangedListener changedListener) {
this.changedListener = changedListener;
}
public interface OnProgressChangedListener {
void onProgressChanged(int currentValue, int percent);
}
public void setMax(int m) {
if (max <= 0)
throw new RuntimeException("Max 必须大于 0");
max = m;
}
public void setProgress(int p) {
int oldProgress = progress;
progress = p;
if (max < progress) {
progress = max;
} else if (progress < 0)
progress = 0;
startProgressAnim(oldProgress);
}
private ValueAnimator valueAnimator;
/**/
private void startProgressAnim(int oldProgress) {
if (valueAnimator != null && valueAnimator.isRunning()) {
valueAnimator.cancel();
}
valueAnimator = ValueAnimator.ofInt(oldProgress, progress);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
progress = (int) animation.getAnimatedValue();
computeProgressRect();
invalidate();
}
});
valueAnimator.setDuration(1000);
valueAnimator.start();
}
/**
* 计算进度Progress
*/
private void computeProgressRect() {
if (orientation == VERTICAL) {
progressRect.set(bgRect.left
, bgRect.bottom - progress * bgRect.height() / max
, bgRect.right
, bgRect.bottom);
} else {
progressRect.set(bgRect.left
, bgRect.top
, bgRect.left + progress * bgRect.width() / max
, bgRect.bottom);
}
}
}
| false | 2,098 | 5 | 2,370 | 6 | 2,511 | 5 | 2,370 | 6 | 2,877 | 8 | false | false | false | false | false | true |
49287_2 |
//给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。
//
//我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。
//说明: n 的范围为 [1, 10,000]。
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class NotIncreArr {
//n-1
public static boolean checkPossibility(int[] nums) {
int count = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] < nums[i - 1]) {
count++;
if (count > 1) {
return false;
}
int privous = i > 1 ? nums[i - 2] : 0;
int after = i < nums.length - 1 ? nums[i + 1] : 10000;
if (nums[i - 1] > after && nums[i] < privous) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
// String inputStr = in.nextLine();
// StringTokenizer stringTokenizer = new StringTokenizer(inputStr," ",false);
// ArrayList<String> arr = new ArrayList<>();
// while(stringTokenizer.hasMoreElements()){
// arr.add(stringTokenizer.nextToken());
// }
//
int[] arr = {4,2,3};
System.out.println(checkPossibility(arr));
//checkPossibility(arr);
}
} | Currycurrycurry/FDSS_Algorithm | java/src/NotIncreArr.java | 438 | //说明: n 的范围为 [1, 10,000]。 | line_comment | zh-cn |
//给定一个长度为 n 的整数数组,你的任务是判断在最多改变 1 个元素的情况下,该数组能否变成一个非递减数列。
//
//我们是这样定义一个非递减数列的: 对于数组中所有的 i (1 <= i < n),满足 array[i] <= array[i + 1]。
//说明 <SUF>
import java.util.ArrayList;
import java.util.Scanner;
import java.util.StringTokenizer;
public class NotIncreArr {
//n-1
public static boolean checkPossibility(int[] nums) {
int count = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] < nums[i - 1]) {
count++;
if (count > 1) {
return false;
}
int privous = i > 1 ? nums[i - 2] : 0;
int after = i < nums.length - 1 ? nums[i + 1] : 10000;
if (nums[i - 1] > after && nums[i] < privous) {
return false;
}
}
}
return true;
}
public static void main(String[] args) {
// Scanner in = new Scanner(System.in);
// String inputStr = in.nextLine();
// StringTokenizer stringTokenizer = new StringTokenizer(inputStr," ",false);
// ArrayList<String> arr = new ArrayList<>();
// while(stringTokenizer.hasMoreElements()){
// arr.add(stringTokenizer.nextToken());
// }
//
int[] arr = {4,2,3};
System.out.println(checkPossibility(arr));
//checkPossibility(arr);
}
} | false | 380 | 20 | 438 | 20 | 443 | 20 | 438 | 20 | 539 | 27 | false | false | false | false | false | true |
41830_0 | package com.example.lukedict;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class ChatActivity extends AppCompatActivity {
private List<Msg> msgList = new ArrayList<>();
private EditText inputText;
private Button send;
private RecyclerView msgRecyclerView;
private MsgAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
initMsgs();//初始化消息数据
inputText = (EditText)findViewById(R.id.input_text);
send = (Button) findViewById(R.id.send);
msgRecyclerView = (RecyclerView)findViewById(R.id.msg_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
msgRecyclerView.setLayoutManager(layoutManager);
layoutManager.setOrientation(RecyclerView.VERTICAL);
adapter = new MsgAdapter(msgList);
msgRecyclerView.setAdapter(adapter);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String content = inputText.getText().toString();
if(!"".equals(content)){
Msg msg = new Msg(content,Msg.TYPE_SENT);
msgList.add(msg);
adapter.notifyItemInserted(msgList.size() - 1);
//当有新消息时,刷新RecycleView中的显示
msgRecyclerView.scrollToPosition(msgList.size() - 1);
//将RecycleView定位到最后一行
inputText.setText("");//清空输入框中的内容
}
}
});
showActionbar();
}
private void showActionbar() {
ActionBar actionBar = this.getSupportActionBar();//定义actionbar上的返回箭头
actionBar.setTitle("客服");
actionBar.setDisplayHomeAsUpEnabled(true);
}
public boolean onOptionsItemSelected(MenuItem item) {//定义actionbar上的返回箭头
if(item.getItemId() == android.R.id.home)
{
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public class Msg{
public static final int TYPE_RECEIVED = 0;
public static final int TYPE_SENT = 1;
private String content;
private int type;
public Msg(String content, int type){
this.content = content;
this.type = type;
}
public String getContent(){
return content;
}
public int getType(){
return type;
}
}
private void initMsgs(){
Msg msg1 = new Msg("你好!",Msg.TYPE_RECEIVED);
msgList.add(msg1);
Msg msg2 = new Msg("欢迎使用Luke English!",Msg.TYPE_RECEIVED);
msgList.add(msg2);
Msg msg3 = new Msg("我是客服小苏,很高兴为你服务!有事请留言,我会尽快回复",Msg.TYPE_RECEIVED);
msgList.add(msg3);
}
} | Curzsu/LukeDict | app/src/main/java/com/example/lukedict/ChatActivity.java | 794 | //初始化消息数据 | line_comment | zh-cn | package com.example.lukedict;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
public class ChatActivity extends AppCompatActivity {
private List<Msg> msgList = new ArrayList<>();
private EditText inputText;
private Button send;
private RecyclerView msgRecyclerView;
private MsgAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
initMsgs();//初始 <SUF>
inputText = (EditText)findViewById(R.id.input_text);
send = (Button) findViewById(R.id.send);
msgRecyclerView = (RecyclerView)findViewById(R.id.msg_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
msgRecyclerView.setLayoutManager(layoutManager);
layoutManager.setOrientation(RecyclerView.VERTICAL);
adapter = new MsgAdapter(msgList);
msgRecyclerView.setAdapter(adapter);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String content = inputText.getText().toString();
if(!"".equals(content)){
Msg msg = new Msg(content,Msg.TYPE_SENT);
msgList.add(msg);
adapter.notifyItemInserted(msgList.size() - 1);
//当有新消息时,刷新RecycleView中的显示
msgRecyclerView.scrollToPosition(msgList.size() - 1);
//将RecycleView定位到最后一行
inputText.setText("");//清空输入框中的内容
}
}
});
showActionbar();
}
private void showActionbar() {
ActionBar actionBar = this.getSupportActionBar();//定义actionbar上的返回箭头
actionBar.setTitle("客服");
actionBar.setDisplayHomeAsUpEnabled(true);
}
public boolean onOptionsItemSelected(MenuItem item) {//定义actionbar上的返回箭头
if(item.getItemId() == android.R.id.home)
{
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public class Msg{
public static final int TYPE_RECEIVED = 0;
public static final int TYPE_SENT = 1;
private String content;
private int type;
public Msg(String content, int type){
this.content = content;
this.type = type;
}
public String getContent(){
return content;
}
public int getType(){
return type;
}
}
private void initMsgs(){
Msg msg1 = new Msg("你好!",Msg.TYPE_RECEIVED);
msgList.add(msg1);
Msg msg2 = new Msg("欢迎使用Luke English!",Msg.TYPE_RECEIVED);
msgList.add(msg2);
Msg msg3 = new Msg("我是客服小苏,很高兴为你服务!有事请留言,我会尽快回复",Msg.TYPE_RECEIVED);
msgList.add(msg3);
}
} | false | 633 | 4 | 794 | 4 | 825 | 4 | 794 | 4 | 993 | 8 | false | false | false | false | false | true |
18610_1 | package top.strelitzia.service;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.contact.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.angelinaBot.annotation.AngelinaFriend;
import top.angelinaBot.annotation.AngelinaGroup;
import top.angelinaBot.model.MessageInfo;
import top.angelinaBot.model.ReplayInfo;
import top.strelitzia.dao.AdminUserMapper;
import top.strelitzia.dao.GroupAdminInfoMapper;
import top.strelitzia.dao.UserFoundMapper;
import top.strelitzia.model.AdminUserInfo;
import top.strelitzia.model.UserFoundInfo;
import top.strelitzia.util.AdminUtil;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
/**
* @author Cuthbert
* @Date 2022/6/21 22:56
**/
@Service
public class TodayWife {
private static final org.slf4j.Logger log
= org.slf4j.LoggerFactory.getLogger(TodayWife.class);
@Autowired
private UserFoundMapper userFoundMapper;
@Autowired
private AdminUserMapper adminUserMapper;
/*编辑指令用法
* *所有功能都需要在最前面加上bot名今日老婆,且需要有step权限
* 重置:将你的wife以及wife的群号设置为0
* qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号
* 重置+qq号:将指定qq的wife以及wife的群号设置为0
* qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号
* qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号
* */
@AngelinaFriend(keyWords = "老婆")
@AngelinaGroup(keyWords = "今日老婆" , description = "从本群中随机挑选一位幸运群友作为你今日的老婆")
public ReplayInfo todayWife(MessageInfo messageInfo) {
//准备工作
ReplayInfo replayInfo = new ReplayInfo(messageInfo);
StringBuilder reply = new StringBuilder("*警告:请勿用此功能刷屏*\n" + messageInfo.getName() + ",\n");
UserFoundInfo userFoundInfo = userFoundMapper.selectUserFoundByQQ(messageInfo.getQq());
if (userFoundInfo == null) {
userFoundInfo = new UserFoundInfo();
userFoundInfo.setQq(messageInfo.getQq());
userFoundInfo.setFoundCount(0);
userFoundInfo.setTodayCount(0);
userFoundInfo.setTodayWife(0L);
userFoundInfo.setWifeGroup(0L);
}
//判断是否为编辑指令
if (messageInfo.getArgs().size() == 2) {
String str = messageInfo.getArgs().get(1);
if (str.equals("菜单")){
reply = new StringBuilder(
"编辑指令用法\n" +
" *所有功能都需要在最前面加上bot名今日老婆\n" +
" *所有功能仅有群主和管理员,或step权限者才能使用\n" +
" 重置:将你的wife以及wife的群号设置为0\n" +
" qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号\n" +
" 重置+qq号:将指定qq的wife以及wife的群号设置为0\n" +
" qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号\n" +
" qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号\n" +
"eg.稀音今日老婆 重置 11111\n 稀音今日老婆 11111 22222"
);
}else {
List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin();
boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins);
if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) {
if (str.equals("重置") || str.equals("reset")) {
userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), 0L, 0L);
reply.append("你的今日老婆已经重置啦");
} else if (str.equals("重置本群")) {
userFoundMapper.resetGroupWife(messageInfo.getGroupId());
reply = new StringBuilder("已重置本群");
} else {
Long qq = Long.valueOf(str);
userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId());
reply = new StringBuilder("设置完成");
}
} else {
reply = new StringBuilder("您没有权限编辑哦");
}
}
} else if (messageInfo.getArgs().size() == 3) {
List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin();
boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins);
if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) {
String str1 = messageInfo.getArgs().get(1);
String str2 = messageInfo.getArgs().get(2);
if (str1.equals("重置") || str1.equals("reset")){
Long qq = Long.valueOf(str2);
userFoundMapper.updateTodayWifeByQq(qq, 0L, 0L);
reply = new StringBuilder("重置完成");
}else {
Long qq = Long.valueOf(str1);
Long wife = Long.valueOf(str2);
userFoundMapper.updateTodayWifeByQq(qq, wife, messageInfo.getGroupId());
reply = new StringBuilder("设置完成");
}
} else {
reply = new StringBuilder("您没有权限编辑哦");
}
} else if (messageInfo.getArgs().size() == 4) {
List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin();
boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins);
if (b) {
Long qq = Long.valueOf(messageInfo.getArgs().get(1));
Long wife = Long.valueOf(messageInfo.getArgs().get(2));
Long group = Long.valueOf(messageInfo.getArgs().get(3));
userFoundMapper.updateTodayWifeByQq(qq, wife, group);
reply = new StringBuilder("设置完成");
} else {
reply = new StringBuilder("您没有权限编辑哦");
}
}else {
//查询今日是否抽取过老婆
Long today = userFoundInfo.getTodayWife();
Long group = userFoundInfo.getWifeGroup();
if (group.equals(messageInfo.getGroupId()) || group.equals(0L)) {
Long qq = null;
if (group.equals(0L)) {
//今日未抽取
//获取MemberList并通过stream流提取qq,随机抽取一个
ContactList<NormalMember> qqList = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).getMembers();
List<Long> list = qqList.stream().map(Member::getId).collect(Collectors.toList());
list.add(messageInfo.getLoginQq());
Random random = new Random();
int n = random.nextInt(list.size());
qq = list.get(n);
reply.append("你今天的老婆是:");
userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId());
} else if (group.equals(messageInfo.getGroupId())) {
//在本群抽取过了
qq = userFoundInfo.getTodayWife();
reply.append("你今天已经抽取过老婆啦!" + "你的老婆是:");
}
replayInfo.setReplayImg("http://q.qlogo.cn/headimg_dl?dst_uin=" + qq + "&spec=5");
String name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getNameCard();
if (name.isEmpty()) {
name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getRemark();
}
reply.append(name + "(" + qq + ")");
} else {
//在其他群抽取过了
String groupName = Bot.getInstance(messageInfo.getLoginQq()).getGroup(group).getName();
reply.append("你今天已经在别的群(" + groupName + ")抽取过老婆啦");
}
}
replayInfo.setReplayMessage(reply.toString());
return replayInfo;
}
}
| CuthbertTsao/SceneBot | src/main/java/top/strelitzia/service/TodayWife.java | 2,238 | /*编辑指令用法
* *所有功能都需要在最前面加上bot名今日老婆,且需要有step权限
* 重置:将你的wife以及wife的群号设置为0
* qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号
* 重置+qq号:将指定qq的wife以及wife的群号设置为0
* qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号
* qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号
* */ | block_comment | zh-cn | package top.strelitzia.service;
import net.mamoe.mirai.Bot;
import net.mamoe.mirai.contact.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.angelinaBot.annotation.AngelinaFriend;
import top.angelinaBot.annotation.AngelinaGroup;
import top.angelinaBot.model.MessageInfo;
import top.angelinaBot.model.ReplayInfo;
import top.strelitzia.dao.AdminUserMapper;
import top.strelitzia.dao.GroupAdminInfoMapper;
import top.strelitzia.dao.UserFoundMapper;
import top.strelitzia.model.AdminUserInfo;
import top.strelitzia.model.UserFoundInfo;
import top.strelitzia.util.AdminUtil;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
/**
* @author Cuthbert
* @Date 2022/6/21 22:56
**/
@Service
public class TodayWife {
private static final org.slf4j.Logger log
= org.slf4j.LoggerFactory.getLogger(TodayWife.class);
@Autowired
private UserFoundMapper userFoundMapper;
@Autowired
private AdminUserMapper adminUserMapper;
/*编辑指 <SUF>*/
@AngelinaFriend(keyWords = "老婆")
@AngelinaGroup(keyWords = "今日老婆" , description = "从本群中随机挑选一位幸运群友作为你今日的老婆")
public ReplayInfo todayWife(MessageInfo messageInfo) {
//准备工作
ReplayInfo replayInfo = new ReplayInfo(messageInfo);
StringBuilder reply = new StringBuilder("*警告:请勿用此功能刷屏*\n" + messageInfo.getName() + ",\n");
UserFoundInfo userFoundInfo = userFoundMapper.selectUserFoundByQQ(messageInfo.getQq());
if (userFoundInfo == null) {
userFoundInfo = new UserFoundInfo();
userFoundInfo.setQq(messageInfo.getQq());
userFoundInfo.setFoundCount(0);
userFoundInfo.setTodayCount(0);
userFoundInfo.setTodayWife(0L);
userFoundInfo.setWifeGroup(0L);
}
//判断是否为编辑指令
if (messageInfo.getArgs().size() == 2) {
String str = messageInfo.getArgs().get(1);
if (str.equals("菜单")){
reply = new StringBuilder(
"编辑指令用法\n" +
" *所有功能都需要在最前面加上bot名今日老婆\n" +
" *所有功能仅有群主和管理员,或step权限者才能使用\n" +
" 重置:将你的wife以及wife的群号设置为0\n" +
" qq号:将你的wife更改为输入的qq号,wife的群号自动填充当前群号\n" +
" 重置+qq号:将指定qq的wife以及wife的群号设置为0\n" +
" qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号自动填充当前群号\n" +
" qq号+qq号+qq号:指定你输入的第一个qq,将他的wife更改为你输入的第二个qq,wife的群号更改为你输入的第三个q号\n" +
"eg.稀音今日老婆 重置 11111\n 稀音今日老婆 11111 22222"
);
}else {
List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin();
boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins);
if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) {
if (str.equals("重置") || str.equals("reset")) {
userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), 0L, 0L);
reply.append("你的今日老婆已经重置啦");
} else if (str.equals("重置本群")) {
userFoundMapper.resetGroupWife(messageInfo.getGroupId());
reply = new StringBuilder("已重置本群");
} else {
Long qq = Long.valueOf(str);
userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId());
reply = new StringBuilder("设置完成");
}
} else {
reply = new StringBuilder("您没有权限编辑哦");
}
}
} else if (messageInfo.getArgs().size() == 3) {
List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin();
boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins);
if (b || !messageInfo.getUserAdmin().equals(MemberPermission.MEMBER)) {
String str1 = messageInfo.getArgs().get(1);
String str2 = messageInfo.getArgs().get(2);
if (str1.equals("重置") || str1.equals("reset")){
Long qq = Long.valueOf(str2);
userFoundMapper.updateTodayWifeByQq(qq, 0L, 0L);
reply = new StringBuilder("重置完成");
}else {
Long qq = Long.valueOf(str1);
Long wife = Long.valueOf(str2);
userFoundMapper.updateTodayWifeByQq(qq, wife, messageInfo.getGroupId());
reply = new StringBuilder("设置完成");
}
} else {
reply = new StringBuilder("您没有权限编辑哦");
}
} else if (messageInfo.getArgs().size() == 4) {
List<AdminUserInfo> admins = adminUserMapper.selectAllAdmin();
boolean b = AdminUtil.getStepAdmin(messageInfo.getQq(), admins);
if (b) {
Long qq = Long.valueOf(messageInfo.getArgs().get(1));
Long wife = Long.valueOf(messageInfo.getArgs().get(2));
Long group = Long.valueOf(messageInfo.getArgs().get(3));
userFoundMapper.updateTodayWifeByQq(qq, wife, group);
reply = new StringBuilder("设置完成");
} else {
reply = new StringBuilder("您没有权限编辑哦");
}
}else {
//查询今日是否抽取过老婆
Long today = userFoundInfo.getTodayWife();
Long group = userFoundInfo.getWifeGroup();
if (group.equals(messageInfo.getGroupId()) || group.equals(0L)) {
Long qq = null;
if (group.equals(0L)) {
//今日未抽取
//获取MemberList并通过stream流提取qq,随机抽取一个
ContactList<NormalMember> qqList = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).getMembers();
List<Long> list = qqList.stream().map(Member::getId).collect(Collectors.toList());
list.add(messageInfo.getLoginQq());
Random random = new Random();
int n = random.nextInt(list.size());
qq = list.get(n);
reply.append("你今天的老婆是:");
userFoundMapper.updateTodayWifeByQq(messageInfo.getQq(), qq, messageInfo.getGroupId());
} else if (group.equals(messageInfo.getGroupId())) {
//在本群抽取过了
qq = userFoundInfo.getTodayWife();
reply.append("你今天已经抽取过老婆啦!" + "你的老婆是:");
}
replayInfo.setReplayImg("http://q.qlogo.cn/headimg_dl?dst_uin=" + qq + "&spec=5");
String name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getNameCard();
if (name.isEmpty()) {
name = Bot.getInstance(messageInfo.getLoginQq()).getGroup(messageInfo.getGroupId()).get(qq).getRemark();
}
reply.append(name + "(" + qq + ")");
} else {
//在其他群抽取过了
String groupName = Bot.getInstance(messageInfo.getLoginQq()).getGroup(group).getName();
reply.append("你今天已经在别的群(" + groupName + ")抽取过老婆啦");
}
}
replayInfo.setReplayMessage(reply.toString());
return replayInfo;
}
}
| false | 1,940 | 169 | 2,220 | 188 | 2,178 | 167 | 2,220 | 188 | 2,792 | 252 | false | false | false | false | false | true |
29284_0 | /**
* 题目描述
* 给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1,m<=n),每段绳子的长度记为k[1],...,k[m]。请问k[1]x...xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
* 输入描述:
* 输入一个数n,意义见题面。(2 <= n <= 60)
* 返回值描述:
* 输出答案。
* 示例1
* 输入
* 8
* 返回值
* 18
*/
public class Solution {
public int cutRope(int target) {
if (target<2){
return 0;
}if(target==2){
return 1;
}if (target==3){
return 2;
}
int result = 1;
for(int i=0;i<target/3-1;i++){
result *=3;
}
if (target%3==1){
result*=4;
}else if(target%3==2){
result*=6;
}else {
result*=3;
}
return result;
}
} | Cweiping/AlgorithmInterview | codingInterviews/CutRope.java | 338 | /**
* 题目描述
* 给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1,m<=n),每段绳子的长度记为k[1],...,k[m]。请问k[1]x...xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
* 输入描述:
* 输入一个数n,意义见题面。(2 <= n <= 60)
* 返回值描述:
* 输出答案。
* 示例1
* 输入
* 8
* 返回值
* 18
*/ | block_comment | zh-cn | /**
* 题目描 <SUF>*/
public class Solution {
public int cutRope(int target) {
if (target<2){
return 0;
}if(target==2){
return 1;
}if (target==3){
return 2;
}
int result = 1;
for(int i=0;i<target/3-1;i++){
result *=3;
}
if (target%3==1){
result*=4;
}else if(target%3==2){
result*=6;
}else {
result*=3;
}
return result;
}
} | false | 302 | 173 | 338 | 202 | 330 | 173 | 338 | 202 | 439 | 277 | false | false | false | false | false | true |
22898_6 | /**
* Copyright (C), 2018-2019, csust
* FileName: Conn
* Author: Cwolf9
* Date: 2019/06/21 14:54
* Description:
* History:
* <author> <time> <version> <desc>
* Cwolf9 2019/06/21 2018.3
* <p>
* 〈可怕的是比你强的人比你还努力〉
* 〈〉
*
* @author Cwolf9
* @create 2019/06/21
* @since 1.0.0
*/
/**
* 〈可怕的是比你强的人比你还努力〉
* 〈〉
*
* @author Cwolf9
* @create 2019/06/21
* @since 1.0.0
*/
package com.demo.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* 数据库连接 lhroot
*/
public class Conn {
public static void main(String[] args) {
Connection con;
//jdbc驱动
String driver="com.mysql.cj.jdbc.Driver";
//这里我的数据库是bookcity
String url="jdbc:mysql://localhost:3306/bookcity?useSSL=false&serverTimezone=UTC";
String user="root";
String password="lhroot";
try {
//注册JDBC驱动程序
Class.forName(driver);
//建立连接
con = DriverManager.getConnection(url, user, password);
if (!con.isClosed()) {
System.out.println("数据库连接成功");
}
con.close();
} catch (ClassNotFoundException e) {
System.out.println("数据库驱动没有安装");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
}
}
} | Cwolf9/bookcity | src/main/java/com/demo/util/Conn.java | 502 | //注册JDBC驱动程序 | line_comment | zh-cn | /**
* Copyright (C), 2018-2019, csust
* FileName: Conn
* Author: Cwolf9
* Date: 2019/06/21 14:54
* Description:
* History:
* <author> <time> <version> <desc>
* Cwolf9 2019/06/21 2018.3
* <p>
* 〈可怕的是比你强的人比你还努力〉
* 〈〉
*
* @author Cwolf9
* @create 2019/06/21
* @since 1.0.0
*/
/**
* 〈可怕的是比你强的人比你还努力〉
* 〈〉
*
* @author Cwolf9
* @create 2019/06/21
* @since 1.0.0
*/
package com.demo.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/*
* 数据库连接 lhroot
*/
public class Conn {
public static void main(String[] args) {
Connection con;
//jdbc驱动
String driver="com.mysql.cj.jdbc.Driver";
//这里我的数据库是bookcity
String url="jdbc:mysql://localhost:3306/bookcity?useSSL=false&serverTimezone=UTC";
String user="root";
String password="lhroot";
try {
//注册 <SUF>
Class.forName(driver);
//建立连接
con = DriverManager.getConnection(url, user, password);
if (!con.isClosed()) {
System.out.println("数据库连接成功");
}
con.close();
} catch (ClassNotFoundException e) {
System.out.println("数据库驱动没有安装");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("数据库连接失败");
}
}
} | false | 433 | 6 | 502 | 5 | 494 | 5 | 502 | 5 | 596 | 13 | false | false | false | false | false | true |
12341_3 | package com.chad.baserecyclerviewadapterhelper.utils;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Tips {
/**
* 显示 Toast
* @param message 提示信息
*/
public static void show(String message) {
show(message, Toast.LENGTH_SHORT);
}
/**
* 显示 Toast
* @param message 提示信息
* @param duration 显示时间长短
*/
public static void show(String message, int duration) {
Toast toast = new Toast(AppUtils.INSTANCE.getApp());
toast.setDuration(duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(createTextToastView(message));
toast.show();
}
/**
* 创建自定义 Toast View
*
* @param message 文本消息
* @return View
*/
private static View createTextToastView(String message) {
// 画圆角矩形背景
float rc = dp2px(6);
RoundRectShape shape = new RoundRectShape(new float[]{rc, rc, rc, rc, rc, rc, rc, rc}, null, null);
ShapeDrawable drawable = new ShapeDrawable(shape);
drawable.getPaint().setColor(Color.argb(225, 240, 240, 240));
drawable.getPaint().setStyle(Paint.Style.FILL);
drawable.getPaint().setAntiAlias(true);
drawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
// 创建View
FrameLayout layout = new FrameLayout(AppUtils.INSTANCE.getApp());
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layoutParams);
layout.setPadding(dp2px(16), dp2px(12), dp2px(16), dp2px(12));
layout.setBackground(drawable);
TextView textView = new TextView(AppUtils.INSTANCE.getApp());
textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
textView.setTextSize(15);
textView.setText(message);
textView.setLineSpacing(dp2px(4), 1f);
textView.setTextColor(Color.BLACK);
layout.addView(textView);
return layout;
}
private static int dp2px(float dpValue) {
final float scale = AppUtils.INSTANCE.getApp().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
| CymChad/BaseRecyclerViewAdapterHelper | app/src/main/java/com/chad/baserecyclerviewadapterhelper/utils/Tips.java | 680 | // 画圆角矩形背景 | line_comment | zh-cn | package com.chad.baserecyclerviewadapterhelper.utils;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.RoundRectShape;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
public class Tips {
/**
* 显示 Toast
* @param message 提示信息
*/
public static void show(String message) {
show(message, Toast.LENGTH_SHORT);
}
/**
* 显示 Toast
* @param message 提示信息
* @param duration 显示时间长短
*/
public static void show(String message, int duration) {
Toast toast = new Toast(AppUtils.INSTANCE.getApp());
toast.setDuration(duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.setView(createTextToastView(message));
toast.show();
}
/**
* 创建自定义 Toast View
*
* @param message 文本消息
* @return View
*/
private static View createTextToastView(String message) {
// 画圆 <SUF>
float rc = dp2px(6);
RoundRectShape shape = new RoundRectShape(new float[]{rc, rc, rc, rc, rc, rc, rc, rc}, null, null);
ShapeDrawable drawable = new ShapeDrawable(shape);
drawable.getPaint().setColor(Color.argb(225, 240, 240, 240));
drawable.getPaint().setStyle(Paint.Style.FILL);
drawable.getPaint().setAntiAlias(true);
drawable.getPaint().setFlags(Paint.ANTI_ALIAS_FLAG);
// 创建View
FrameLayout layout = new FrameLayout(AppUtils.INSTANCE.getApp());
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
layout.setLayoutParams(layoutParams);
layout.setPadding(dp2px(16), dp2px(12), dp2px(16), dp2px(12));
layout.setBackground(drawable);
TextView textView = new TextView(AppUtils.INSTANCE.getApp());
textView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT));
textView.setTextSize(15);
textView.setText(message);
textView.setLineSpacing(dp2px(4), 1f);
textView.setTextColor(Color.BLACK);
layout.addView(textView);
return layout;
}
private static int dp2px(float dpValue) {
final float scale = AppUtils.INSTANCE.getApp().getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
}
| false | 571 | 8 | 680 | 8 | 708 | 7 | 680 | 8 | 852 | 15 | false | false | false | false | false | true |
41236_3 | package liuyuboo;
import java.util.LinkedList;
public class JZ27 {
class Node {
public int val;
public Node left;
public Node right;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right) {
val = _val;
left = _left;
right = _right;
}
}
//目的:转化成排序的循环双向链表
Node head = new Node();
public Node treeToDoublyList(Node root) {
//结果形式--和中序遍历类似
//结果链表是一个由中序顺序组织的链表
//所谓链表和bst都是节点靠指针维护的,这个结构是一致的,所以存在就地转换的可能
//这个处理工程,只涉及两个点角色之间的指针调整,其他部分不需要===》需要head cur两个小弟
//cur 代表当前节点,而这个当前节点是中序顺序组织的节点;也就是中序遍历框架中间位置,会自然拿到当前节点
//head 这里就要记录前一个节点
//前一个节点与当前节点的互动,只有三部分:两部分指针调整-前一个后指针指向下一个;后一个前指针指向前一个;记得更新head,来保证始终维持root的前一个节点
Node begin = head;
inOrder(root);
Node cur = ret;
while (cur.left != begin) {
cur = cur.left;
}
return cur;
}
Node ret = null;
public void inOrder(Node root) {
if (root == null) {
return;
}
inOrder(root.left);
head.right = root;
root.left = head;
head = head.right;
ret = root;
inOrder(root.right);
}
//分化瓦解--三个部分,每个部分都具有和上级同样的问题实质
/* Node lastNode = null;
convertNode(root,lastNode);
Node headNode = lastNode;
while (headNode != null && headNode.left != null) {
headNode = headNode.left;
}
return headNode;
}
public void convertNode(Node root,Node lastNode) {
if (root == null) {
return;
}
Node current = root;
if (current.left != null) {
convertNode(current.left,lastNode);
}
current.left = lastNode;
if (lastNode != null) {
lastNode.right = current;
}
lastNode = current;
if (current.right != null) {
convertNode(current.right,lastNode);
}
}*/
/* if (root.left == null)
//小问题:左子树
leftTo(root.left).right = root;
//小问题:右子树
rightTo(root.right).left = root;
return root;
}
//返回左子树最大节点
public Node leftTo(Node root) {
if(root.left == null && root.right == null) {
return root;
}
leftTo(root.left).right = root;
rightTo(root.right).left = root;
return findMax(root.right);
}
public Node findMax(Node root) {
if(root.right == null) {
return root;
}
return findMax(root.right);
}
public Node findMin(Node root) {
if (root.left == null) {
return root;
}
return findMin(root.left);
}
//返回右子树最小节点
public Node rightTo(Node root) {
if(root.left == null && root.right == null) {
return root;
}
leftTo(root.left).right = root;
rightTo(root.right).left = root;
return findMin(root.left);
}
*/
}
| DA-MO-WANG/leetcode | java/src/liuyuboo/JZ27.java | 918 | //所谓链表和bst都是节点靠指针维护的,这个结构是一致的,所以存在就地转换的可能 | line_comment | zh-cn | package liuyuboo;
import java.util.LinkedList;
public class JZ27 {
class Node {
public int val;
public Node left;
public Node right;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right) {
val = _val;
left = _left;
right = _right;
}
}
//目的:转化成排序的循环双向链表
Node head = new Node();
public Node treeToDoublyList(Node root) {
//结果形式--和中序遍历类似
//结果链表是一个由中序顺序组织的链表
//所谓 <SUF>
//这个处理工程,只涉及两个点角色之间的指针调整,其他部分不需要===》需要head cur两个小弟
//cur 代表当前节点,而这个当前节点是中序顺序组织的节点;也就是中序遍历框架中间位置,会自然拿到当前节点
//head 这里就要记录前一个节点
//前一个节点与当前节点的互动,只有三部分:两部分指针调整-前一个后指针指向下一个;后一个前指针指向前一个;记得更新head,来保证始终维持root的前一个节点
Node begin = head;
inOrder(root);
Node cur = ret;
while (cur.left != begin) {
cur = cur.left;
}
return cur;
}
Node ret = null;
public void inOrder(Node root) {
if (root == null) {
return;
}
inOrder(root.left);
head.right = root;
root.left = head;
head = head.right;
ret = root;
inOrder(root.right);
}
//分化瓦解--三个部分,每个部分都具有和上级同样的问题实质
/* Node lastNode = null;
convertNode(root,lastNode);
Node headNode = lastNode;
while (headNode != null && headNode.left != null) {
headNode = headNode.left;
}
return headNode;
}
public void convertNode(Node root,Node lastNode) {
if (root == null) {
return;
}
Node current = root;
if (current.left != null) {
convertNode(current.left,lastNode);
}
current.left = lastNode;
if (lastNode != null) {
lastNode.right = current;
}
lastNode = current;
if (current.right != null) {
convertNode(current.right,lastNode);
}
}*/
/* if (root.left == null)
//小问题:左子树
leftTo(root.left).right = root;
//小问题:右子树
rightTo(root.right).left = root;
return root;
}
//返回左子树最大节点
public Node leftTo(Node root) {
if(root.left == null && root.right == null) {
return root;
}
leftTo(root.left).right = root;
rightTo(root.right).left = root;
return findMax(root.right);
}
public Node findMax(Node root) {
if(root.right == null) {
return root;
}
return findMax(root.right);
}
public Node findMin(Node root) {
if (root.left == null) {
return root;
}
return findMin(root.left);
}
//返回右子树最小节点
public Node rightTo(Node root) {
if(root.left == null && root.right == null) {
return root;
}
leftTo(root.left).right = root;
rightTo(root.right).left = root;
return findMin(root.left);
}
*/
}
| false | 850 | 27 | 918 | 28 | 999 | 25 | 918 | 28 | 1,235 | 52 | false | false | false | false | false | true |
26029_36 | package compile;
import entity.MultiComment;
import entity.SingleComment;
import entity.TokenList;
import frame.OutText;
import frame.ReadText;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* @description 这是词法分析的具体实现
*/
@SuppressWarnings("all")
public class Lexer extends MainComplier{
//词法分析解释规则,定义字符数组
String[] keyWords = {"if", "else", "while", "read", "write", "int", "double","for"}; //关键字数组
String[] operator = {"+", "-", "*", "/"};//运算符数组
String[] roperator = {">", "<", "==", "<>"};//关系运算符数组
String[] sepretor = {";", "{", "}", "(", ")", "."};//分隔符数组
String RegexToId = "^[a-zA-Z]([a-zA-Z_0-9])*[a-zA-Z0-9]$||[a-zA-Z]";//标识符的正则表达式
String RegexToNumber = "^^-?\\d+$";//整数的正则表达式
String RegexToFloat = "^(-?\\d+)(\\.\\d+)?$";//浮点数的正则表达式
String RegexToArray = "[a-zA-Z]+(\\[[0-9][1-9]*\\])+";//数组变量的正则表达式
//将父类的readText, outText继承过来
public Lexer(ReadText readText, OutText outText) throws HeadlessException {
super(readText, outText);
}
//分析过程,此处为语法分析和词法分析提供已经修饰过的源程序
public List<TokenList> getTokens() {
List<TokenList> tokenLists = new ArrayList<>();//用于记录Token的信息
String inputText = readText.getText();
StringTokenizer totalStrt = new StringTokenizer(inputText, "\r\n");
int row = 0;//行号
//获取所有的记号以及记号的信息
while (totalStrt.hasMoreTokens()) {
List<String> Tokens = new ArrayList<>();//行记号
StringTokenizer rowOfStrt = new StringTokenizer(totalStrt.nextToken(), " \n\r\t;(){}\"\'+-<>/=*", true);
//所有可能的界符,初步得到所有的Token,但需要进一步的合并
while (rowOfStrt.hasMoreTokens()) {
Tokens.add(rowOfStrt.nextToken());
}
TokenList tokenList = new TokenList(row, Tokens);
tokenLists.add(tokenList);
row++;
}
//对于初步得到的记号集合的进一步判断与整合,用于区别注释和*,/;以及=与==,以及<与<>
for (int i = 0; i < tokenLists.size(); i++) {
List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组
for (int j = 0; j < tokenList.size() - 1; j++) {
if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("/")) {
//单行注释记号的识别
tokenList.set(j, "//");
tokenList.remove(j + 1);
} else if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("*")) {
//多行注释的识别
tokenList.set(j, "/*");
tokenList.remove(j + 1);
} else if (tokenList.get(j).equals("*") && tokenList.get(j + 1).equals("/")) {
//多行注释的识别
tokenList.set(j, "*/");
tokenList.remove(j + 1);
} else if (tokenList.get(j).equals("=") && tokenList.get(j + 1).equals("=")) {
tokenList.set(j, "==");
tokenList.remove(j + 1);
} else if (tokenList.get(j).equals("<") && tokenList.get(j + 1).equals(">")) {
tokenList.set(j, "<>");
tokenList.remove(j + 1);//判断不等于符号
}
}
}
//第二次对记号进行判断整合,主要用于去除各种分隔符
for (int i = 0; i < tokenLists.size(); i++) {
List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组
String Pattern = "\\s+|\t|\r\n";
int j = 0;
while(j<tokenList.size())
{
if(tokenList.get(j).matches(Pattern))
{
tokenList.remove(j);
}
else
{
j++;
}
}
}
//第三次对记号进行去除注释,得到真正的完整的记号
List<MultiComment> multiComments = new ArrayList<>();//存放多行注释的位置信息
List<SingleComment> singleComments = new ArrayList<>();//存放单行注释的位置信息
for (int i = 0; i < tokenLists.size(); i++)//多行注释的记号获取
{
List<String> TokenOfrow = tokenLists.get(i).getTokenList();
int rowCount = tokenLists.get(i).getRow();//多行注释行号
for (int j = 0; j < TokenOfrow.size(); j++) {
if (TokenOfrow.get(j).equals("//")) {
SingleComment singleComment = new SingleComment(rowCount, j);
singleComments.add(singleComment);//记录单行注释位置
}
if (TokenOfrow.get(j).equals("/*")) {
MultiComment multiComment = new MultiComment(rowCount, j, "/*");//j为列号
multiComments.add(multiComment);
} else if (TokenOfrow.get(j).equals("*/")) {
MultiComment multiComment = new MultiComment(rowCount, j, "*/");
multiComments.add(multiComment);
}
}
}
for (int i = 0; i < multiComments.size(); i = i + 2)//去除多行注释中的整行注释
{
if ((multiComments.size() % 2) == 0 && i <= multiComments.size() - 2)//判断注释是否未闭合
{
if (multiComments.get(i).getComment().equals("/*") && multiComments.get(i + 1).getComment().equals("*/")) {
for (int j = multiComments.get(i).getRow() + 1; j < multiComments.get(i + 1).getRow(); j++) {
tokenLists.remove(j);
}
List<String> StartLine = tokenLists.get(multiComments.get(i).getRow()).getTokenList();//注释行起始
List<String> EndLine = tokenLists.get(multiComments.get(i + 1).getRow()).getTokenList();//注释行结束
for (int j = multiComments.get(i).getColumn(); j < StartLine.size(); )//因为随着元素的删除减少,size大小也会发生改变
{
StartLine.remove(j);
}
int position = multiComments.get(i).getColumn();//位置指针
for (int j = 0; j <= position; )//同理,元素的数量的减少导致size改变
{
EndLine.remove(j);
position--;
}
}
} else {
outText.append("无法继续分析");
outText.append("第" + multiComments.get(i).getRow() + "行第" + multiComments.get(i).getColumn() + "处的注释未闭合");
break;
}
}
for (int i = 0; i < singleComments.size(); i++) {
List<String> SignleLine = tokenLists.get(singleComments.get(i).getRow()).getTokenList();
for (int j = singleComments.get(i).getColumn(); j < SignleLine.size(); ) {
SignleLine.remove(j);//去除单行注释
}
}
return tokenLists;
}
//所有的记号处理都做好,此处纯分析记号
public void Analysis() {
List<TokenList> tokenLists = getTokens();
for (int i = 0; i < tokenLists.size(); i++) {
List<String> tokenList = tokenLists.get(i).getTokenList();
outText.append("--------------------------------------------------分析第" + (i + 1) + "行--------------------------------------------------" + "\r\n");
for (int j = 0; j < tokenList.size(); j++) {
int Count = 0;
for (int k = 0; k < keyWords.length; k++) {
if (tokenList.get(j).equals(keyWords[k])) {
outText.append(tokenList.get(j) + " 是关键字" + "\r\n");
Count++;
}
}
for (int k = 0; k < operator.length; k++) {
if (tokenList.get(j).equals(operator[k])) {
outText.append(tokenList.get(j) + " 是运算符" + "\r\n");
Count++;
}
}
for (int k = 0; k < roperator.length; k++) {
if (tokenList.get(j).equals(roperator[k])) {
outText.append(tokenList.get(j) + " 是关系运算符" + "\r\n");
Count++;
}
}
for (int k = 0; k < sepretor.length; k++) {
if (tokenList.get(j).equals(sepretor[k])) {
outText.append(tokenList.get(j) + " 是分隔符" + "\r\n");
Count++;
}
}
if (tokenList.get(j).matches(RegexToId) && (Count == 0)) {
outText.append(tokenList.get(j) + " 是标识符" + "\r\n");
} else if (tokenList.get(j).matches(RegexToNumber)) {
outText.append(tokenList.get(j) + " 是整数" + "\r\n");
} else if (tokenList.get(j).matches(RegexToFloat)) {
outText.append(tokenList.get(j) + " 是浮点数" + "\r\n");
} else if (tokenList.get(j).matches(RegexToArray)) {
outText.append(tokenList.get(j) + " 是数组变量" + "\r\n");
} else if (tokenList.get(j).equals("=")) {
outText.append(tokenList.get(j) + " 是等于号" + "\r\n");
} else if (Count == 0) {
outText.append(tokenList.get(j) + " 标识符命名错误" + "\r\n");
}
}
}
}
}
| DAQ121/Lexer-Parser | src/compile/Lexer.java | 2,586 | //注释行起始 | line_comment | zh-cn | package compile;
import entity.MultiComment;
import entity.SingleComment;
import entity.TokenList;
import frame.OutText;
import frame.ReadText;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* @description 这是词法分析的具体实现
*/
@SuppressWarnings("all")
public class Lexer extends MainComplier{
//词法分析解释规则,定义字符数组
String[] keyWords = {"if", "else", "while", "read", "write", "int", "double","for"}; //关键字数组
String[] operator = {"+", "-", "*", "/"};//运算符数组
String[] roperator = {">", "<", "==", "<>"};//关系运算符数组
String[] sepretor = {";", "{", "}", "(", ")", "."};//分隔符数组
String RegexToId = "^[a-zA-Z]([a-zA-Z_0-9])*[a-zA-Z0-9]$||[a-zA-Z]";//标识符的正则表达式
String RegexToNumber = "^^-?\\d+$";//整数的正则表达式
String RegexToFloat = "^(-?\\d+)(\\.\\d+)?$";//浮点数的正则表达式
String RegexToArray = "[a-zA-Z]+(\\[[0-9][1-9]*\\])+";//数组变量的正则表达式
//将父类的readText, outText继承过来
public Lexer(ReadText readText, OutText outText) throws HeadlessException {
super(readText, outText);
}
//分析过程,此处为语法分析和词法分析提供已经修饰过的源程序
public List<TokenList> getTokens() {
List<TokenList> tokenLists = new ArrayList<>();//用于记录Token的信息
String inputText = readText.getText();
StringTokenizer totalStrt = new StringTokenizer(inputText, "\r\n");
int row = 0;//行号
//获取所有的记号以及记号的信息
while (totalStrt.hasMoreTokens()) {
List<String> Tokens = new ArrayList<>();//行记号
StringTokenizer rowOfStrt = new StringTokenizer(totalStrt.nextToken(), " \n\r\t;(){}\"\'+-<>/=*", true);
//所有可能的界符,初步得到所有的Token,但需要进一步的合并
while (rowOfStrt.hasMoreTokens()) {
Tokens.add(rowOfStrt.nextToken());
}
TokenList tokenList = new TokenList(row, Tokens);
tokenLists.add(tokenList);
row++;
}
//对于初步得到的记号集合的进一步判断与整合,用于区别注释和*,/;以及=与==,以及<与<>
for (int i = 0; i < tokenLists.size(); i++) {
List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组
for (int j = 0; j < tokenList.size() - 1; j++) {
if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("/")) {
//单行注释记号的识别
tokenList.set(j, "//");
tokenList.remove(j + 1);
} else if (tokenList.get(j).equals("/") && tokenList.get(j + 1).equals("*")) {
//多行注释的识别
tokenList.set(j, "/*");
tokenList.remove(j + 1);
} else if (tokenList.get(j).equals("*") && tokenList.get(j + 1).equals("/")) {
//多行注释的识别
tokenList.set(j, "*/");
tokenList.remove(j + 1);
} else if (tokenList.get(j).equals("=") && tokenList.get(j + 1).equals("=")) {
tokenList.set(j, "==");
tokenList.remove(j + 1);
} else if (tokenList.get(j).equals("<") && tokenList.get(j + 1).equals(">")) {
tokenList.set(j, "<>");
tokenList.remove(j + 1);//判断不等于符号
}
}
}
//第二次对记号进行判断整合,主要用于去除各种分隔符
for (int i = 0; i < tokenLists.size(); i++) {
List<String> tokenList = tokenLists.get(i).getTokenList();//获取行记号组
String Pattern = "\\s+|\t|\r\n";
int j = 0;
while(j<tokenList.size())
{
if(tokenList.get(j).matches(Pattern))
{
tokenList.remove(j);
}
else
{
j++;
}
}
}
//第三次对记号进行去除注释,得到真正的完整的记号
List<MultiComment> multiComments = new ArrayList<>();//存放多行注释的位置信息
List<SingleComment> singleComments = new ArrayList<>();//存放单行注释的位置信息
for (int i = 0; i < tokenLists.size(); i++)//多行注释的记号获取
{
List<String> TokenOfrow = tokenLists.get(i).getTokenList();
int rowCount = tokenLists.get(i).getRow();//多行注释行号
for (int j = 0; j < TokenOfrow.size(); j++) {
if (TokenOfrow.get(j).equals("//")) {
SingleComment singleComment = new SingleComment(rowCount, j);
singleComments.add(singleComment);//记录单行注释位置
}
if (TokenOfrow.get(j).equals("/*")) {
MultiComment multiComment = new MultiComment(rowCount, j, "/*");//j为列号
multiComments.add(multiComment);
} else if (TokenOfrow.get(j).equals("*/")) {
MultiComment multiComment = new MultiComment(rowCount, j, "*/");
multiComments.add(multiComment);
}
}
}
for (int i = 0; i < multiComments.size(); i = i + 2)//去除多行注释中的整行注释
{
if ((multiComments.size() % 2) == 0 && i <= multiComments.size() - 2)//判断注释是否未闭合
{
if (multiComments.get(i).getComment().equals("/*") && multiComments.get(i + 1).getComment().equals("*/")) {
for (int j = multiComments.get(i).getRow() + 1; j < multiComments.get(i + 1).getRow(); j++) {
tokenLists.remove(j);
}
List<String> StartLine = tokenLists.get(multiComments.get(i).getRow()).getTokenList();//注释 <SUF>
List<String> EndLine = tokenLists.get(multiComments.get(i + 1).getRow()).getTokenList();//注释行结束
for (int j = multiComments.get(i).getColumn(); j < StartLine.size(); )//因为随着元素的删除减少,size大小也会发生改变
{
StartLine.remove(j);
}
int position = multiComments.get(i).getColumn();//位置指针
for (int j = 0; j <= position; )//同理,元素的数量的减少导致size改变
{
EndLine.remove(j);
position--;
}
}
} else {
outText.append("无法继续分析");
outText.append("第" + multiComments.get(i).getRow() + "行第" + multiComments.get(i).getColumn() + "处的注释未闭合");
break;
}
}
for (int i = 0; i < singleComments.size(); i++) {
List<String> SignleLine = tokenLists.get(singleComments.get(i).getRow()).getTokenList();
for (int j = singleComments.get(i).getColumn(); j < SignleLine.size(); ) {
SignleLine.remove(j);//去除单行注释
}
}
return tokenLists;
}
//所有的记号处理都做好,此处纯分析记号
public void Analysis() {
List<TokenList> tokenLists = getTokens();
for (int i = 0; i < tokenLists.size(); i++) {
List<String> tokenList = tokenLists.get(i).getTokenList();
outText.append("--------------------------------------------------分析第" + (i + 1) + "行--------------------------------------------------" + "\r\n");
for (int j = 0; j < tokenList.size(); j++) {
int Count = 0;
for (int k = 0; k < keyWords.length; k++) {
if (tokenList.get(j).equals(keyWords[k])) {
outText.append(tokenList.get(j) + " 是关键字" + "\r\n");
Count++;
}
}
for (int k = 0; k < operator.length; k++) {
if (tokenList.get(j).equals(operator[k])) {
outText.append(tokenList.get(j) + " 是运算符" + "\r\n");
Count++;
}
}
for (int k = 0; k < roperator.length; k++) {
if (tokenList.get(j).equals(roperator[k])) {
outText.append(tokenList.get(j) + " 是关系运算符" + "\r\n");
Count++;
}
}
for (int k = 0; k < sepretor.length; k++) {
if (tokenList.get(j).equals(sepretor[k])) {
outText.append(tokenList.get(j) + " 是分隔符" + "\r\n");
Count++;
}
}
if (tokenList.get(j).matches(RegexToId) && (Count == 0)) {
outText.append(tokenList.get(j) + " 是标识符" + "\r\n");
} else if (tokenList.get(j).matches(RegexToNumber)) {
outText.append(tokenList.get(j) + " 是整数" + "\r\n");
} else if (tokenList.get(j).matches(RegexToFloat)) {
outText.append(tokenList.get(j) + " 是浮点数" + "\r\n");
} else if (tokenList.get(j).matches(RegexToArray)) {
outText.append(tokenList.get(j) + " 是数组变量" + "\r\n");
} else if (tokenList.get(j).equals("=")) {
outText.append(tokenList.get(j) + " 是等于号" + "\r\n");
} else if (Count == 0) {
outText.append(tokenList.get(j) + " 标识符命名错误" + "\r\n");
}
}
}
}
}
| false | 2,335 | 6 | 2,584 | 5 | 2,711 | 4 | 2,586 | 5 | 3,266 | 8 | false | false | false | false | false | true |
41648_11 | package tk.dcmmc.sorting.Algorithms;
import tk.dcmmc.fundamentals.Algorithms.DoubleLinkedList;
/**
* 希尔排序法
* Created on 2017/8/5
* @author DCMMC
* @since 1.5
*/
class ShellSort extends Sort {
/**
* 在最糟糕的情况下时间复杂度为O(N^1.5), 一个小小的改进就能从InsertionSort的O(N^2)降低到O(N^1.5)(而且是最坏情况)
* 平均下的时间复杂度不确定, 取决于increment sequence的选取.
*
* InsertionSort在每一轮插入的时候需要跟相邻的元素一个一个交换, 这样很消耗资源, 希尔排序作为插入排序的扩展,
* 每次比较并交换的间隔不再是1(h=1这一特殊情况下h-sorting就是InsertionSort), 而是大于1的不同的步长.
* 定义(Def.): h-sorting
* 如果数组中的元素任意间隔h都是有序的, 那就称为h-sorting array, e.g., 1 2 3 4 5 6 7,
* 取h为2, 则子序列1 3 5 7和子序列2 4 6分别都是有序的(即有h个互相独立有序的子序列交错组合在一起), 则该数组是h-sorted array
* h-sorting即以h为间隔对子序列进行排序, e.g., 对序列 1 5 8 2 3 4 6 7 6 8 9 (共11个元素), 以h = 3进行h-sorting,
* 首先这个序列拆分为一下3个子序列: 1 2 6 7和5 3 7 9和8 6 4, 然后依次对这三个子序列进行InsertionSort, 得到1 2 6 7, 3 5 7 9
* 和4 6 8这三个子序列, 合并之后为: 1 3 4 2 5 6 6 7 8 7 9, 这个序列就被称为原序列以h=3的h-sorted array
* 一个更好的理解就是把序列放在一个h列的表中, 然后对其形成的二维表的每一列进行InsertionSort:
* 1 5 8 2 3 4 6 7 6 8 9以h=3
* 1 5 8
* 2 3 4
* 6 7 6
* 8 9
* 然后依次对第一第二第三第四列进行InsertionSort:
* 1 3 4
* 2 5 6
* 6 7 8
* 7 9
*
*
* ShellSort大体的原理是以一系列值(increment sequence)作为h(又叫步长), 由大的h到小的h来对序列进行h-sorting, 只要该h序列最后的h是1,
* 就一定能得出排序好的序列, 比如 5 3 1就是一个h序列, 先以h=5对原序列进行h-sorting, 然后再以h=3进行h-sorting, 最后以h=1进行h-sorting.
* 不过从1开始然后不断乘以2这样的序列的效率很低,因为1后面都是偶数,彼此h-sorting排序都是错开的的.
*
* 而公认的最好步长序列是由Sedgewick(本书作者)提出的(1, 5, 19, 41, 109,...),该序列的项来自9x4^i-9x2^i+1和2^(i+2)x(2^(i+2)-3)+1
* 这两个算式.用这样步长序列的希尔排序比插入排序要快,甚至在小数组中比快速排序和堆排序还快,但是在涉及大量数据时希尔排序还是比快速排序慢。
*
* 另一个在大数组中表现优异的步长序列是(斐波那契数列除去0和1将剩余的数以黄金分区比的两倍的幂进行运算得到的数列)
*
* 不过一般使用的序列是Knuth提出的由递推公式h = h*3 + 1确定的数列(转成通项公式即为1/2(3^k-1)), 这个序列在元素数量比较大的时候,
* 相比于SelectionSort和InsertionSort, 性能按照数组大小以2的次幂递增.
* 使用Knuth提出序列的比较次数大概为N的若干倍再乘以这个序列的长度(差不多约为N^1.5, 由大量N很大的实验可以估算出)
*
* 虽然使用最优的序列的时候, 在对小数组排序性能有时候可以超过heapsort和quicksort, 不过在大量数据的时候还是慢于后两个, 不过相比于
* 后两者复杂一些的实现, ShellSort只需少量代码而且对资源的消耗也比较小, 所以适合用在嵌入式系统这些比较重视资源的场景中.
*/
public static void shellSort(Comparable[] a) {
//先确定一个不大于a.length/3的一个数作为h序列的最大项
int h = 1;
while (h < a.length/3)
h = h*3 + 1;//by Knuth
//Ex 2.1.11
//还可以把上述生成的increment sequence 保存在数组中
//DoubleLinkedList<Integer> list = new DoubleLinkedList<>();
//list.addLast(1);
//while (h < a.length / 3)
// list.addLast(list.get(list.getSize() - 1) * 3 + 1);
//int[] incrementSeq = list.toArray();
//以这个h构成一个后项是前项的1/3(约)的序列
while (h >= 1) {
//以当前h做h-sorting
for (int i = h; i < a.length; i++) {
for (int j = i; j >= h && less(a[j], a[j - h]); j -= h)
exch(a, j, j - h);
}
h /= 3;
}
}
}///~ | DCMMC/Java-Algorithms-Learning | Algorithms/tk/dcmmc/sorting/Algorithms/ShellSort.java | 1,626 | //以这个h构成一个后项是前项的1/3(约)的序列 | line_comment | zh-cn | package tk.dcmmc.sorting.Algorithms;
import tk.dcmmc.fundamentals.Algorithms.DoubleLinkedList;
/**
* 希尔排序法
* Created on 2017/8/5
* @author DCMMC
* @since 1.5
*/
class ShellSort extends Sort {
/**
* 在最糟糕的情况下时间复杂度为O(N^1.5), 一个小小的改进就能从InsertionSort的O(N^2)降低到O(N^1.5)(而且是最坏情况)
* 平均下的时间复杂度不确定, 取决于increment sequence的选取.
*
* InsertionSort在每一轮插入的时候需要跟相邻的元素一个一个交换, 这样很消耗资源, 希尔排序作为插入排序的扩展,
* 每次比较并交换的间隔不再是1(h=1这一特殊情况下h-sorting就是InsertionSort), 而是大于1的不同的步长.
* 定义(Def.): h-sorting
* 如果数组中的元素任意间隔h都是有序的, 那就称为h-sorting array, e.g., 1 2 3 4 5 6 7,
* 取h为2, 则子序列1 3 5 7和子序列2 4 6分别都是有序的(即有h个互相独立有序的子序列交错组合在一起), 则该数组是h-sorted array
* h-sorting即以h为间隔对子序列进行排序, e.g., 对序列 1 5 8 2 3 4 6 7 6 8 9 (共11个元素), 以h = 3进行h-sorting,
* 首先这个序列拆分为一下3个子序列: 1 2 6 7和5 3 7 9和8 6 4, 然后依次对这三个子序列进行InsertionSort, 得到1 2 6 7, 3 5 7 9
* 和4 6 8这三个子序列, 合并之后为: 1 3 4 2 5 6 6 7 8 7 9, 这个序列就被称为原序列以h=3的h-sorted array
* 一个更好的理解就是把序列放在一个h列的表中, 然后对其形成的二维表的每一列进行InsertionSort:
* 1 5 8 2 3 4 6 7 6 8 9以h=3
* 1 5 8
* 2 3 4
* 6 7 6
* 8 9
* 然后依次对第一第二第三第四列进行InsertionSort:
* 1 3 4
* 2 5 6
* 6 7 8
* 7 9
*
*
* ShellSort大体的原理是以一系列值(increment sequence)作为h(又叫步长), 由大的h到小的h来对序列进行h-sorting, 只要该h序列最后的h是1,
* 就一定能得出排序好的序列, 比如 5 3 1就是一个h序列, 先以h=5对原序列进行h-sorting, 然后再以h=3进行h-sorting, 最后以h=1进行h-sorting.
* 不过从1开始然后不断乘以2这样的序列的效率很低,因为1后面都是偶数,彼此h-sorting排序都是错开的的.
*
* 而公认的最好步长序列是由Sedgewick(本书作者)提出的(1, 5, 19, 41, 109,...),该序列的项来自9x4^i-9x2^i+1和2^(i+2)x(2^(i+2)-3)+1
* 这两个算式.用这样步长序列的希尔排序比插入排序要快,甚至在小数组中比快速排序和堆排序还快,但是在涉及大量数据时希尔排序还是比快速排序慢。
*
* 另一个在大数组中表现优异的步长序列是(斐波那契数列除去0和1将剩余的数以黄金分区比的两倍的幂进行运算得到的数列)
*
* 不过一般使用的序列是Knuth提出的由递推公式h = h*3 + 1确定的数列(转成通项公式即为1/2(3^k-1)), 这个序列在元素数量比较大的时候,
* 相比于SelectionSort和InsertionSort, 性能按照数组大小以2的次幂递增.
* 使用Knuth提出序列的比较次数大概为N的若干倍再乘以这个序列的长度(差不多约为N^1.5, 由大量N很大的实验可以估算出)
*
* 虽然使用最优的序列的时候, 在对小数组排序性能有时候可以超过heapsort和quicksort, 不过在大量数据的时候还是慢于后两个, 不过相比于
* 后两者复杂一些的实现, ShellSort只需少量代码而且对资源的消耗也比较小, 所以适合用在嵌入式系统这些比较重视资源的场景中.
*/
public static void shellSort(Comparable[] a) {
//先确定一个不大于a.length/3的一个数作为h序列的最大项
int h = 1;
while (h < a.length/3)
h = h*3 + 1;//by Knuth
//Ex 2.1.11
//还可以把上述生成的increment sequence 保存在数组中
//DoubleLinkedList<Integer> list = new DoubleLinkedList<>();
//list.addLast(1);
//while (h < a.length / 3)
// list.addLast(list.get(list.getSize() - 1) * 3 + 1);
//int[] incrementSeq = list.toArray();
//以这 <SUF>
while (h >= 1) {
//以当前h做h-sorting
for (int i = h; i < a.length; i++) {
for (int j = i; j >= h && less(a[j], a[j - h]); j -= h)
exch(a, j, j - h);
}
h /= 3;
}
}
}///~ | false | 1,481 | 20 | 1,626 | 21 | 1,489 | 20 | 1,626 | 21 | 2,152 | 26 | false | false | false | false | false | true |
53256_12 | //请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi,
//numberOfUnitsPerBoxi] :
//
//
// numberOfBoxesi 是类型 i 的箱子的数量。
// numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。
//
//
// 整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。
//
// 返回卡车可以装载 单元 的 最大 总数。
//
//
//
// 示例 1:
//
//
//输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
//输出:8
//解释:箱子的情况如下:
//- 1 个第一类的箱子,里面含 3 个单元。
//- 2 个第二类的箱子,每个里面含 2 个单元。
//- 3 个第三类的箱子,每个里面含 1 个单元。
//可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。
//单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8
//
// 示例 2:
//
//
//输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
//输出:91
//
//
//
//
// 提示:
//
//
// 1 <= boxTypes.length <= 1000
// 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
// 1 <= truckSize <= 10⁶
//
//
// Related Topics 贪心 数组 排序 👍 78 👎 0
import java.util.Arrays;
import java.util.Comparator;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
int len = boxTypes.length;
Integer[][] arr = new Integer[len][2];
for (int i = 0; i < len; i++) {
arr[i][0] = boxTypes[i][0];
arr[i][1] = boxTypes[i][1];
}
Arrays.sort(arr, new Comparator<Integer[]>() {
@Override
public int compare(Integer[] o1, Integer[] o2) {
return -o1[1] + o2[1];
}
});
int sum = 0;
int i = 0;
while (truckSize > 0 && i < len) {
if (truckSize - arr[i][0] >= 0) {
truckSize -= arr[i][0];
sum += arr[i][0] * arr[i][1];
} else {
sum += truckSize * arr[i][1];
truckSize = 0;
}
i++;
}
return sum;
}
}
//leetcode submit region end(Prohibit modification and deletion)
| DEAiFISH/LeetCode | editor/cn/[1710]卡车上的最大单元数.java | 781 | //- 3 个第三类的箱子,每个里面含 1 个单元。 | line_comment | zh-cn | //请你将一些箱子装在 一辆卡车 上。给你一个二维数组 boxTypes ,其中 boxTypes[i] = [numberOfBoxesi,
//numberOfUnitsPerBoxi] :
//
//
// numberOfBoxesi 是类型 i 的箱子的数量。
// numberOfUnitsPerBoxi 是类型 i 每个箱子可以装载的单元数量。
//
//
// 整数 truckSize 表示卡车上可以装载 箱子 的 最大数量 。只要箱子数量不超过 truckSize ,你就可以选择任意箱子装到卡车上。
//
// 返回卡车可以装载 单元 的 最大 总数。
//
//
//
// 示例 1:
//
//
//输入:boxTypes = [[1,3],[2,2],[3,1]], truckSize = 4
//输出:8
//解释:箱子的情况如下:
//- 1 个第一类的箱子,里面含 3 个单元。
//- 2 个第二类的箱子,每个里面含 2 个单元。
//- <SUF>
//可以选择第一类和第二类的所有箱子,以及第三类的一个箱子。
//单元总数 = (1 * 3) + (2 * 2) + (1 * 1) = 8
//
// 示例 2:
//
//
//输入:boxTypes = [[5,10],[2,5],[4,7],[3,9]], truckSize = 10
//输出:91
//
//
//
//
// 提示:
//
//
// 1 <= boxTypes.length <= 1000
// 1 <= numberOfBoxesi, numberOfUnitsPerBoxi <= 1000
// 1 <= truckSize <= 10⁶
//
//
// Related Topics 贪心 数组 排序 👍 78 👎 0
import java.util.Arrays;
import java.util.Comparator;
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public int maximumUnits(int[][] boxTypes, int truckSize) {
int len = boxTypes.length;
Integer[][] arr = new Integer[len][2];
for (int i = 0; i < len; i++) {
arr[i][0] = boxTypes[i][0];
arr[i][1] = boxTypes[i][1];
}
Arrays.sort(arr, new Comparator<Integer[]>() {
@Override
public int compare(Integer[] o1, Integer[] o2) {
return -o1[1] + o2[1];
}
});
int sum = 0;
int i = 0;
while (truckSize > 0 && i < len) {
if (truckSize - arr[i][0] >= 0) {
truckSize -= arr[i][0];
sum += arr[i][0] * arr[i][1];
} else {
sum += truckSize * arr[i][1];
truckSize = 0;
}
i++;
}
return sum;
}
}
//leetcode submit region end(Prohibit modification and deletion)
| false | 685 | 19 | 781 | 18 | 770 | 17 | 781 | 18 | 989 | 29 | false | false | false | false | false | true |
58548_7 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GoListener extends MouseAdapter implements ActionListener, GoData{
JRadioButton[] modelForm;
String gameModel = "pvp";// 人机 人人
int chessFlag;// 0 不能下棋 1 黑棋 2 白棋
Graphics g;
@Override
public void actionPerformed(ActionEvent e){
if(modelForm[0].isSelected ()){
gameModel = "pve";
} else if(modelForm[1].isSelected ()){
gameModel = "pvp";
}
String btnStr = e.getActionCommand ();
JButton btn = (JButton) e.getSource ();
if(btnStr.equals ("开始游戏")){
btn.setText ("结束对局");
chessFlag = 1;
} else if(btnStr.equals ("悔棋")){
// 悔棋
} else if(btnStr.equals ("退出")){
System.exit (0);
} else if(btnStr.equals ("结束对局")){
btn.setText ("开始游戏");
chessFlag = 0;
}
}
@Override
public void mousePressed(MouseEvent e){
int x = e.getX ();
int y = e.getY ();
if(chessFlag == 0){
JOptionPane.showConfirmDialog
(null, "请先开始游戏", "提示", JOptionPane.DEFAULT_OPTION);
return;
}
// System.out.println("x:" + x + " y:" + y);
// 求行列值
int r = (y - Y + SIZE / 2) / SIZE; // 行
int c = (x - X + SIZE / 2) / SIZE; // 列
// System.out.println (r + " " + c);
if(x < 25 || y < 25 || r < 0 || r >= ROWS || c < 0 || c >= COLS){
JOptionPane.showMessageDialog (null, "请下在棋盘内", "提示", JOptionPane.DEFAULT_OPTION);
return;
}
if(chessArr[r][c]!=0){
JOptionPane.showMessageDialog (null, "此处已有棋子", "提示", JOptionPane.DEFAULT_OPTION);
return;
}
if(gameModel.equals ("pvp")){
// 存储棋子
chessArr[r][c] = chessFlag;
boolean ifwin = ChessJudge.checkWin(r, c, chessFlag);
System.out.println("ifwin:" + ifwin);
if(chessFlag == 1){
g.setColor (Color.BLACK);
chessFlag = 2;
} else{
g.setColor (Color.WHITE);
chessFlag = 1;
}
// 还原坐标
int chessX = X + c * SIZE - SIZE / 2;
int chessY = Y + r * SIZE - SIZE / 2;
g.fillOval (chessX, chessY, SIZE, SIZE);
// 判断输赢
} else{
}
}
}
| DHUAVY/AIGo | GoListener.java | 713 | // 判断输赢 | line_comment | zh-cn | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GoListener extends MouseAdapter implements ActionListener, GoData{
JRadioButton[] modelForm;
String gameModel = "pvp";// 人机 人人
int chessFlag;// 0 不能下棋 1 黑棋 2 白棋
Graphics g;
@Override
public void actionPerformed(ActionEvent e){
if(modelForm[0].isSelected ()){
gameModel = "pve";
} else if(modelForm[1].isSelected ()){
gameModel = "pvp";
}
String btnStr = e.getActionCommand ();
JButton btn = (JButton) e.getSource ();
if(btnStr.equals ("开始游戏")){
btn.setText ("结束对局");
chessFlag = 1;
} else if(btnStr.equals ("悔棋")){
// 悔棋
} else if(btnStr.equals ("退出")){
System.exit (0);
} else if(btnStr.equals ("结束对局")){
btn.setText ("开始游戏");
chessFlag = 0;
}
}
@Override
public void mousePressed(MouseEvent e){
int x = e.getX ();
int y = e.getY ();
if(chessFlag == 0){
JOptionPane.showConfirmDialog
(null, "请先开始游戏", "提示", JOptionPane.DEFAULT_OPTION);
return;
}
// System.out.println("x:" + x + " y:" + y);
// 求行列值
int r = (y - Y + SIZE / 2) / SIZE; // 行
int c = (x - X + SIZE / 2) / SIZE; // 列
// System.out.println (r + " " + c);
if(x < 25 || y < 25 || r < 0 || r >= ROWS || c < 0 || c >= COLS){
JOptionPane.showMessageDialog (null, "请下在棋盘内", "提示", JOptionPane.DEFAULT_OPTION);
return;
}
if(chessArr[r][c]!=0){
JOptionPane.showMessageDialog (null, "此处已有棋子", "提示", JOptionPane.DEFAULT_OPTION);
return;
}
if(gameModel.equals ("pvp")){
// 存储棋子
chessArr[r][c] = chessFlag;
boolean ifwin = ChessJudge.checkWin(r, c, chessFlag);
System.out.println("ifwin:" + ifwin);
if(chessFlag == 1){
g.setColor (Color.BLACK);
chessFlag = 2;
} else{
g.setColor (Color.WHITE);
chessFlag = 1;
}
// 还原坐标
int chessX = X + c * SIZE - SIZE / 2;
int chessY = Y + r * SIZE - SIZE / 2;
g.fillOval (chessX, chessY, SIZE, SIZE);
// 判断 <SUF>
} else{
}
}
}
| false | 643 | 5 | 713 | 5 | 737 | 4 | 713 | 5 | 911 | 8 | false | false | false | false | false | true |
17596_3 | package code.DrawPad.src;
import javax.swing.*;
import java.awt.*;
public class ImagePro extends JFrame{
ImageListen imageListen = new ImageListen ();
public ImagePro(){
JFrame jf = new JFrame ();
jf.setTitle ("图片处理");
jf.setSize (1000, 900);
jf.setDefaultCloseOperation (EXIT_ON_CLOSE);
jf.setVisible (true);
ShowPanel showPanel = new ShowPanel ();// 显示图片的面板
// 初始化图层
showPanel.setBuffImgList (imageListen.buffImgList);
imageListen.setShowPanel (showPanel);
showPanel.addMouseListener (imageListen);//鼠标监听
showPanel.addMouseMotionListener (imageListen);// 鼠标移动监听
JPanel imgPanel = new JPanel ();// 图片选择的面板
ControlPanel controlPanel = new ControlPanel (imageListen);// 滤镜操作面板
jf.add (showPanel, BorderLayout.CENTER);
jf.add (controlPanel, BorderLayout.SOUTH);
JMenuBar jmb = new JMenuBar ();// 菜单栏
JMenu jm = new JMenu ("文件");// 菜单
JMenuItem jmiOpen = new JMenuItem ("打开");// 菜单项
JMenuItem jmiSave = new JMenuItem ("保存");// 菜单项
jmiOpen.addActionListener (imageListen);
jmiSave.addActionListener (imageListen);
jmiOpen.setActionCommand ("FileOP");
jmiSave.setActionCommand ("FileOP");
jm.add (jmiOpen);
jm.add (jmiSave);
jmb.add (jm);
jf.setJMenuBar (jmb);
jf.setVisible (true);
}
public static void main(String[] args){
new ImagePro ();
}
}
| DHUAVY/DrawPad | src/ImagePro.java | 421 | // 鼠标移动监听 | line_comment | zh-cn | package code.DrawPad.src;
import javax.swing.*;
import java.awt.*;
public class ImagePro extends JFrame{
ImageListen imageListen = new ImageListen ();
public ImagePro(){
JFrame jf = new JFrame ();
jf.setTitle ("图片处理");
jf.setSize (1000, 900);
jf.setDefaultCloseOperation (EXIT_ON_CLOSE);
jf.setVisible (true);
ShowPanel showPanel = new ShowPanel ();// 显示图片的面板
// 初始化图层
showPanel.setBuffImgList (imageListen.buffImgList);
imageListen.setShowPanel (showPanel);
showPanel.addMouseListener (imageListen);//鼠标监听
showPanel.addMouseMotionListener (imageListen);// 鼠标 <SUF>
JPanel imgPanel = new JPanel ();// 图片选择的面板
ControlPanel controlPanel = new ControlPanel (imageListen);// 滤镜操作面板
jf.add (showPanel, BorderLayout.CENTER);
jf.add (controlPanel, BorderLayout.SOUTH);
JMenuBar jmb = new JMenuBar ();// 菜单栏
JMenu jm = new JMenu ("文件");// 菜单
JMenuItem jmiOpen = new JMenuItem ("打开");// 菜单项
JMenuItem jmiSave = new JMenuItem ("保存");// 菜单项
jmiOpen.addActionListener (imageListen);
jmiSave.addActionListener (imageListen);
jmiOpen.setActionCommand ("FileOP");
jmiSave.setActionCommand ("FileOP");
jm.add (jmiOpen);
jm.add (jmiSave);
jmb.add (jm);
jf.setJMenuBar (jmb);
jf.setVisible (true);
}
public static void main(String[] args){
new ImagePro ();
}
}
| false | 381 | 7 | 421 | 7 | 411 | 5 | 421 | 7 | 552 | 14 | false | false | false | false | false | true |
55587_1 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtstack.chunjun.cdc;
import com.dtstack.chunjun.cdc.ddl.definition.TableIdentifier;
import com.dtstack.chunjun.cdc.handler.CacheHandler;
import com.dtstack.chunjun.cdc.handler.DDLHandler;
import com.dtstack.chunjun.cdc.worker.WorkerManager;
import com.dtstack.chunjun.element.ColumnRowData;
import com.dtstack.chunjun.throwable.ChunJunRuntimeException;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.util.Collector;
import java.util.Objects;
/**
* 数据(不论ddl还是dml数据)下发到对应表名下的unblock队列中,worker在轮询过程中,处理unblock数据队列中的数据,在遇到ddl数据之后,将数据队列置为block状态,并将队
* 列引用交给store处理,store在拿到队列引用之后,将队列头部的ddl数据下发到外部存储中, 并监听外部存储对ddl的反馈情况(监听工作由store中额外的线程来执行),
* 此时,队列仍然处于block状态;在收到外部存储的反馈之后,将数据队列头部的ddl数据移除,同时将队列状 态回归为unblock状态,队列引用还给worker。
*/
public class RestorationFlatMap extends RichFlatMapFunction<RowData, RowData> {
private static final long serialVersionUID = -1936334572949200754L;
private final QueuesChamberlain chamberlain;
private final WorkerManager workerManager;
public RestorationFlatMap(DDLHandler ddlHandler, CacheHandler cacheHandler, CdcConfig conf) {
this.chamberlain = new QueuesChamberlain(ddlHandler, cacheHandler);
this.workerManager = new WorkerManager(chamberlain, conf);
}
@Override
public void open(Configuration parameters) throws Exception {
workerManager.open();
chamberlain.open();
}
@Override
public void close() throws Exception {
workerManager.close();
chamberlain.close();
}
@Override
public void flatMap(RowData value, Collector<RowData> out) {
if (workerManager.getCollector() == null) {
WrapCollector<RowData> wrapCollector = new WrapCollector<>(out);
chamberlain.setCollector(wrapCollector);
workerManager.setCollector(out);
}
if (!workerManager.isAlive()) {
throw new ChunJunRuntimeException(workerManager.getException());
}
put(value);
}
private void put(RowData rowData) {
TableIdentifier tableIdentifier = getTableIdentifierFromColumnData(rowData);
chamberlain.add(rowData, tableIdentifier);
}
/**
* 从 RowData 获取对应的tableIdentifier
*
* @param data column row data.
* @return table identifier.
*/
private TableIdentifier getTableIdentifierFromColumnData(RowData data) {
String[] headers;
if (data instanceof DdlRowData) {
headers = ((DdlRowData) data).getHeaders();
} else {
headers = ((ColumnRowData) data).getHeaders();
}
int databaseIndex = -1;
int schemaIndex = -1;
int tableIndex = -1;
for (int i = 0; i < Objects.requireNonNull(headers).length; i++) {
if ("database".equalsIgnoreCase(headers[i])) {
databaseIndex = i;
continue;
}
if ("schema".equalsIgnoreCase(headers[i])) {
schemaIndex = i;
continue;
}
if ("table".equalsIgnoreCase(headers[i])) {
tableIndex = i;
}
}
String database = getDataFromIndex(databaseIndex, data);
String schema = getDataFromIndex(schemaIndex, data);
String table = getDataFromIndex(tableIndex, data);
return new TableIdentifier(database, schema, table);
}
private String getDataFromIndex(int index, RowData data) {
if (index >= 0) {
StringData stringData = data.getString(index);
if (null != stringData) {
return stringData.toString();
}
}
return null;
}
}
| DTStack/chunjun | chunjun-core/src/main/java/com/dtstack/chunjun/cdc/RestorationFlatMap.java | 1,219 | /**
* 数据(不论ddl还是dml数据)下发到对应表名下的unblock队列中,worker在轮询过程中,处理unblock数据队列中的数据,在遇到ddl数据之后,将数据队列置为block状态,并将队
* 列引用交给store处理,store在拿到队列引用之后,将队列头部的ddl数据下发到外部存储中, 并监听外部存储对ddl的反馈情况(监听工作由store中额外的线程来执行),
* 此时,队列仍然处于block状态;在收到外部存储的反馈之后,将数据队列头部的ddl数据移除,同时将队列状 态回归为unblock状态,队列引用还给worker。
*/ | block_comment | zh-cn | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtstack.chunjun.cdc;
import com.dtstack.chunjun.cdc.ddl.definition.TableIdentifier;
import com.dtstack.chunjun.cdc.handler.CacheHandler;
import com.dtstack.chunjun.cdc.handler.DDLHandler;
import com.dtstack.chunjun.cdc.worker.WorkerManager;
import com.dtstack.chunjun.element.ColumnRowData;
import com.dtstack.chunjun.throwable.ChunJunRuntimeException;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.table.data.RowData;
import org.apache.flink.table.data.StringData;
import org.apache.flink.util.Collector;
import java.util.Objects;
/**
* 数据( <SUF>*/
public class RestorationFlatMap extends RichFlatMapFunction<RowData, RowData> {
private static final long serialVersionUID = -1936334572949200754L;
private final QueuesChamberlain chamberlain;
private final WorkerManager workerManager;
public RestorationFlatMap(DDLHandler ddlHandler, CacheHandler cacheHandler, CdcConfig conf) {
this.chamberlain = new QueuesChamberlain(ddlHandler, cacheHandler);
this.workerManager = new WorkerManager(chamberlain, conf);
}
@Override
public void open(Configuration parameters) throws Exception {
workerManager.open();
chamberlain.open();
}
@Override
public void close() throws Exception {
workerManager.close();
chamberlain.close();
}
@Override
public void flatMap(RowData value, Collector<RowData> out) {
if (workerManager.getCollector() == null) {
WrapCollector<RowData> wrapCollector = new WrapCollector<>(out);
chamberlain.setCollector(wrapCollector);
workerManager.setCollector(out);
}
if (!workerManager.isAlive()) {
throw new ChunJunRuntimeException(workerManager.getException());
}
put(value);
}
private void put(RowData rowData) {
TableIdentifier tableIdentifier = getTableIdentifierFromColumnData(rowData);
chamberlain.add(rowData, tableIdentifier);
}
/**
* 从 RowData 获取对应的tableIdentifier
*
* @param data column row data.
* @return table identifier.
*/
private TableIdentifier getTableIdentifierFromColumnData(RowData data) {
String[] headers;
if (data instanceof DdlRowData) {
headers = ((DdlRowData) data).getHeaders();
} else {
headers = ((ColumnRowData) data).getHeaders();
}
int databaseIndex = -1;
int schemaIndex = -1;
int tableIndex = -1;
for (int i = 0; i < Objects.requireNonNull(headers).length; i++) {
if ("database".equalsIgnoreCase(headers[i])) {
databaseIndex = i;
continue;
}
if ("schema".equalsIgnoreCase(headers[i])) {
schemaIndex = i;
continue;
}
if ("table".equalsIgnoreCase(headers[i])) {
tableIndex = i;
}
}
String database = getDataFromIndex(databaseIndex, data);
String schema = getDataFromIndex(schemaIndex, data);
String table = getDataFromIndex(tableIndex, data);
return new TableIdentifier(database, schema, table);
}
private String getDataFromIndex(int index, RowData data) {
if (index >= 0) {
StringData stringData = data.getString(index);
if (null != stringData) {
return stringData.toString();
}
}
return null;
}
}
| false | 1,094 | 160 | 1,219 | 169 | 1,256 | 151 | 1,219 | 169 | 1,518 | 282 | false | false | false | false | false | true |
9593_5 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtstack.flink.sql.localTest;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.alibaba.fastjson.JSONObject;
import com.dtstack.flink.sql.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
/**
* @author tiezhu
* @Date 2020/7/8 Wed
* Company dtstack
*/
public class LocalTest {
private static final Logger LOG = LoggerFactory.getLogger(LocalTest.class);
public static void main(String[] args) throws Exception {
setLogLevel("INFO");
List<String> propertiesList = new ArrayList<>();
String sqlPath = "/Users/wtz/dtstack/sql/test/FileDemoOne.sql";
Map<String, Object> conf = new HashMap<>();
JSONObject properties = new JSONObject();
//其他参数配置
properties.put("time.characteristic", "eventTime");
properties.put("timezone", TimeZone.getDefault());
properties.put("early.trigger", "1");
// 任务配置参数
conf.put("-sql", URLEncoder.encode(readSQL(sqlPath), StandardCharsets.UTF_8.name()));
conf.put("-mode", "local");
conf.put("-name", "flinkStreamSQLLocalTest");
conf.put("-confProp", properties.toString());
conf.put("-pluginLoadMode", "LocalTest");
// conf.put("-checkResource", "true");
conf.put("-dirtyProperties", buildDirtyStr());
for (Map.Entry<String, Object> keyValue : conf.entrySet()) {
propertiesList.add(keyValue.getKey());
propertiesList.add(keyValue.getValue().toString());
}
Main.main(propertiesList.toArray(new String[0]));
}
private static String buildDirtyStr() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", "console");
// 多少条数据打印一次
jsonObject.put("printLimit", "100");
jsonObject.put("url", "jdbc:mysql://localhost:3306/tiezhu");
jsonObject.put("userName", "root");
jsonObject.put("password", "abc123");
jsonObject.put("isCreateTable", "false");
// 多少条数据写入一次
jsonObject.put("batchSize", "1");
jsonObject.put("tableName", "dirtyData");
return jsonObject.toJSONString();
}
private static String readSQL(String sqlPath) {
try {
byte[] array = Files.readAllBytes(Paths.get(sqlPath));
return new String(array, StandardCharsets.UTF_8);
} catch (IOException ioe) {
LOG.error("Can not get the job info !!!", ioe);
throw new RuntimeException(ioe);
}
}
private static void setLogLevel(String level) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
ch.qos.logback.classic.Logger logger = loggerContext.getLogger("root");
logger.setLevel(Level.toLevel(level));
}
}
| DTStack/flinkStreamSQL | localTest/src/main/java/com/dtstack/flink/sql/localTest/LocalTest.java | 985 | // 多少条数据打印一次 | line_comment | zh-cn | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.dtstack.flink.sql.localTest;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.LoggerContext;
import com.alibaba.fastjson.JSONObject;
import com.dtstack.flink.sql.Main;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
/**
* @author tiezhu
* @Date 2020/7/8 Wed
* Company dtstack
*/
public class LocalTest {
private static final Logger LOG = LoggerFactory.getLogger(LocalTest.class);
public static void main(String[] args) throws Exception {
setLogLevel("INFO");
List<String> propertiesList = new ArrayList<>();
String sqlPath = "/Users/wtz/dtstack/sql/test/FileDemoOne.sql";
Map<String, Object> conf = new HashMap<>();
JSONObject properties = new JSONObject();
//其他参数配置
properties.put("time.characteristic", "eventTime");
properties.put("timezone", TimeZone.getDefault());
properties.put("early.trigger", "1");
// 任务配置参数
conf.put("-sql", URLEncoder.encode(readSQL(sqlPath), StandardCharsets.UTF_8.name()));
conf.put("-mode", "local");
conf.put("-name", "flinkStreamSQLLocalTest");
conf.put("-confProp", properties.toString());
conf.put("-pluginLoadMode", "LocalTest");
// conf.put("-checkResource", "true");
conf.put("-dirtyProperties", buildDirtyStr());
for (Map.Entry<String, Object> keyValue : conf.entrySet()) {
propertiesList.add(keyValue.getKey());
propertiesList.add(keyValue.getValue().toString());
}
Main.main(propertiesList.toArray(new String[0]));
}
private static String buildDirtyStr() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("type", "console");
// 多少 <SUF>
jsonObject.put("printLimit", "100");
jsonObject.put("url", "jdbc:mysql://localhost:3306/tiezhu");
jsonObject.put("userName", "root");
jsonObject.put("password", "abc123");
jsonObject.put("isCreateTable", "false");
// 多少条数据写入一次
jsonObject.put("batchSize", "1");
jsonObject.put("tableName", "dirtyData");
return jsonObject.toJSONString();
}
private static String readSQL(String sqlPath) {
try {
byte[] array = Files.readAllBytes(Paths.get(sqlPath));
return new String(array, StandardCharsets.UTF_8);
} catch (IOException ioe) {
LOG.error("Can not get the job info !!!", ioe);
throw new RuntimeException(ioe);
}
}
private static void setLogLevel(String level) {
LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
ch.qos.logback.classic.Logger logger = loggerContext.getLogger("root");
logger.setLevel(Level.toLevel(level));
}
}
| false | 843 | 8 | 985 | 7 | 1,022 | 6 | 985 | 7 | 1,173 | 13 | false | false | false | false | false | true |
54132_2 | package com.njfu.model;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import com.njfu.entity.Player;
import com.njfu.service.PlayerService;
public class PlayerModel extends AbstractTableModel{
/**
*
*/
private static final long serialVersionUID = 1L;
//定义两个集合,一个用于装表头,一个用于装数据
ArrayList rowData,columnNames;
PlayerService playerService = new PlayerService();
public PlayerModel(){
columnNames = new ArrayList<>();
columnNames.add("id");
columnNames.add("账号");
columnNames.add("密码");
columnNames.add("手机");
columnNames.add("状态");
columnNames.add("金币");
columnNames.add("钻石");
columnNames.add("等级");
columnNames.add("经验");
//装数据
List <Player> list = PlayerService.showDatabase();
rowData = new ArrayList();
for(int i = 0; i< list.size();i++){
//新建一个集合---排序
ArrayList array = new ArrayList();
array.add(list.get(i).getId());
array.add(list.get(i).getAccount());
array.add(list.get(i).getPassword());
array.add(list.get(i).getPhonenum());
array.add(list.get(i).getStation());
array.add(list.get(i).getGoldnum());
array.add(list.get(i).getDiamondnum());
array.add(list.get(i).getLv());
array.add(list.get(i).getEpx());
//将集合可添加到集合
rowData.add(array);
}
}
@Override
public int getRowCount() {
return this.rowData.size();
}
@Override
public int getColumnCount() {
return this.columnNames.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return ((ArrayList)this.rowData.get(rowIndex)).get(columnIndex);
}
@Override
public String getColumnName(int column) {
return (String) this.columnNames.get(column);
}
}
| DVKunion/Knight | src/com/njfu/model/PlayerModel.java | 576 | //新建一个集合---排序 | line_comment | zh-cn | package com.njfu.model;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import com.njfu.entity.Player;
import com.njfu.service.PlayerService;
public class PlayerModel extends AbstractTableModel{
/**
*
*/
private static final long serialVersionUID = 1L;
//定义两个集合,一个用于装表头,一个用于装数据
ArrayList rowData,columnNames;
PlayerService playerService = new PlayerService();
public PlayerModel(){
columnNames = new ArrayList<>();
columnNames.add("id");
columnNames.add("账号");
columnNames.add("密码");
columnNames.add("手机");
columnNames.add("状态");
columnNames.add("金币");
columnNames.add("钻石");
columnNames.add("等级");
columnNames.add("经验");
//装数据
List <Player> list = PlayerService.showDatabase();
rowData = new ArrayList();
for(int i = 0; i< list.size();i++){
//新建 <SUF>
ArrayList array = new ArrayList();
array.add(list.get(i).getId());
array.add(list.get(i).getAccount());
array.add(list.get(i).getPassword());
array.add(list.get(i).getPhonenum());
array.add(list.get(i).getStation());
array.add(list.get(i).getGoldnum());
array.add(list.get(i).getDiamondnum());
array.add(list.get(i).getLv());
array.add(list.get(i).getEpx());
//将集合可添加到集合
rowData.add(array);
}
}
@Override
public int getRowCount() {
return this.rowData.size();
}
@Override
public int getColumnCount() {
return this.columnNames.size();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return ((ArrayList)this.rowData.get(rowIndex)).get(columnIndex);
}
@Override
public String getColumnName(int column) {
return (String) this.columnNames.get(column);
}
}
| false | 454 | 6 | 576 | 6 | 569 | 6 | 576 | 6 | 736 | 12 | false | false | false | false | false | true |
13527_2 | package com.dengzhou.sms;
import com.dengzhou.utils.ESClient;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Map;
public class create_sms_index {
String index = "sms_logs_index";
String type = "sms_logs_type";
@Test
public void create_index() throws IOException {
Settings.Builder settings = Settings.builder()
.put("number_of_shards", 3)
.put("number_of_replicas", 1);
XContentBuilder mappings = JsonXContent.contentBuilder()
.startObject()
.startObject("properties")
.startObject("createDate")
.field("type", "date")
.field("format","yyyy-MM-dd")
.endObject()
.startObject("sendDate")
.field("type", "date")
.field("format", "yyyy-MM-dd")
.endObject()
.startObject("longCode")
.field("type", "keyword")
.endObject()
.startObject("mobile")
.field("type", "keyword")
.endObject()
.startObject("corpName")
.field("type", "keyword")
.endObject()
.startObject("smsContent")
.field("type", "text")
.field("analyzer", "ik_max_word")
.endObject()
.startObject("state")
.field("type", "integer")
.endObject()
.startObject("operatorid")
.field("type", "integer")
.endObject()
.startObject("province")
.field("type", "keyword")
.endObject()
.startObject("ipAddr")
.field("type", "ip")
.endObject()
.startObject("replyTotal")
.field("type", "integer")
.endObject()
.startObject("fee")
.field("type", "long")
.endObject()
.endObject()
.endObject();
CreateIndexRequest request = new CreateIndexRequest(index)
.settings(settings)
.mapping(type,mappings);
RestHighLevelClient client = ESClient.getClient();
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response.toString());
}
@Test
public void exists() throws IOException {
GetIndexRequest request = new GetIndexRequest();
request.indices(index);
RestHighLevelClient client = ESClient.getClient();
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
@Test
public void testQuery() throws IOException {
// 1 创建Request对象
SearchRequest request = new SearchRequest(index);
request.types(type);
// 2 指定查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.from(0);
builder.size(5);
builder.query(QueryBuilders.termQuery("province", "河北"));
request.source(builder);
// 3 执行查询
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 4 获取到_source中的数据
for (SearchHit hit : response.getHits().getHits()) {
Map<String, Object> result = hit.getSourceAsMap();
System.out.println(result);
}
}
@Test
public void test_terms() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.termsQuery("province","河北","河南"));
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : resp.getHits().getHits()){
System.out.println(hit);
}
}
@Test
public void test_match_all() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchAllQuery());
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits().getHits()){
System.out.println(hit);
}
}
@Test
public void test_match_field() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchQuery("smsContext","打车"));
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits().getHits()){
System.out.println(hit);
}
}
@Test
public void test_match_boolean() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND));
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits().getHits()){
System.out.println(hit);
}
}
@Test
public void test_multi_match() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
//builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND));
builder.query(QueryBuilders.multiMatchQuery("河北", "province", "smsContext"));
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits().getHits()) {
System.out.println(hit);
}
}
}
| DW-Zhou/ES-6.5.4 | src/main/java/com/dengzhou/sms/create_sms_index.java | 1,647 | // 3 执行查询 | line_comment | zh-cn | package com.dengzhou.sms;
import com.dengzhou.utils.ESClient;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.util.Map;
public class create_sms_index {
String index = "sms_logs_index";
String type = "sms_logs_type";
@Test
public void create_index() throws IOException {
Settings.Builder settings = Settings.builder()
.put("number_of_shards", 3)
.put("number_of_replicas", 1);
XContentBuilder mappings = JsonXContent.contentBuilder()
.startObject()
.startObject("properties")
.startObject("createDate")
.field("type", "date")
.field("format","yyyy-MM-dd")
.endObject()
.startObject("sendDate")
.field("type", "date")
.field("format", "yyyy-MM-dd")
.endObject()
.startObject("longCode")
.field("type", "keyword")
.endObject()
.startObject("mobile")
.field("type", "keyword")
.endObject()
.startObject("corpName")
.field("type", "keyword")
.endObject()
.startObject("smsContent")
.field("type", "text")
.field("analyzer", "ik_max_word")
.endObject()
.startObject("state")
.field("type", "integer")
.endObject()
.startObject("operatorid")
.field("type", "integer")
.endObject()
.startObject("province")
.field("type", "keyword")
.endObject()
.startObject("ipAddr")
.field("type", "ip")
.endObject()
.startObject("replyTotal")
.field("type", "integer")
.endObject()
.startObject("fee")
.field("type", "long")
.endObject()
.endObject()
.endObject();
CreateIndexRequest request = new CreateIndexRequest(index)
.settings(settings)
.mapping(type,mappings);
RestHighLevelClient client = ESClient.getClient();
CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);
System.out.println(response.toString());
}
@Test
public void exists() throws IOException {
GetIndexRequest request = new GetIndexRequest();
request.indices(index);
RestHighLevelClient client = ESClient.getClient();
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
@Test
public void testQuery() throws IOException {
// 1 创建Request对象
SearchRequest request = new SearchRequest(index);
request.types(type);
// 2 指定查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.from(0);
builder.size(5);
builder.query(QueryBuilders.termQuery("province", "河北"));
request.source(builder);
// 3 <SUF>
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
// 4 获取到_source中的数据
for (SearchHit hit : response.getHits().getHits()) {
Map<String, Object> result = hit.getSourceAsMap();
System.out.println(result);
}
}
@Test
public void test_terms() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.termsQuery("province","河北","河南"));
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : resp.getHits().getHits()){
System.out.println(hit);
}
}
@Test
public void test_match_all() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchAllQuery());
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits().getHits()){
System.out.println(hit);
}
}
@Test
public void test_match_field() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchQuery("smsContext","打车"));
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits().getHits()){
System.out.println(hit);
}
}
@Test
public void test_match_boolean() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND));
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits().getHits()){
System.out.println(hit);
}
}
@Test
public void test_multi_match() throws IOException {
SearchRequest request = new SearchRequest(index);
request.types(type);
SearchSourceBuilder builder = new SearchSourceBuilder();
//builder.query(QueryBuilders.matchQuery("smsContext","打车 女士").operator(Operator.AND));
builder.query(QueryBuilders.multiMatchQuery("河北", "province", "smsContext"));
request.source(builder);
RestHighLevelClient client = ESClient.getClient();
SearchResponse response = client.search(request, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits().getHits()) {
System.out.println(hit);
}
}
}
| false | 1,406 | 7 | 1,647 | 5 | 1,780 | 5 | 1,647 | 5 | 1,972 | 12 | false | false | false | false | false | true |
15907_2 | import java.util.LinkedList;
public class P641 {
public static void main(String[] args) {
}
}
class MyCircularDeque {
private int size = 0;
private LinkedList<Integer> list = new LinkedList();
//初始化大小
public MyCircularDeque(int k) {
this.size = k;
}
public boolean insertFront(int value) {
//首先查看大小是否核算
if (list.size() == size){
return false;
}
list.addFirst(value);
return true;
}
public boolean insertLast(int value) {
//首先查看大小是否核算
if (list.size() == size){
return false;
}
list.addLast(value);
return true;
}
public boolean deleteFront() {
//判断大小是否为0,如果为0直接返回false
if (list.size() == 0){
return false;
}
list.removeFirst();
return true;
}
public boolean deleteLast() {
//判断大小是否为0,如果为0直接返回false
if (list.size() == 0){
return false;
}
list.removeLast();
return true;
}
public int getFront() {
//判断大小是否为0,如果为0直接返回-1
if (list.size() == 0){
return -1;
}
return list.getFirst();
}
public int getRear() {
if (list.size() == 0){
return -1;
}
return list.getLast();
}
public boolean isEmpty() {
return list.isEmpty();
}
public boolean isFull() {
return list.size() == size;
}
}
/**
* Your MyCircularDeque object will be instantiated and called as such:
* MyCircularDeque obj = new MyCircularDeque(k);
* boolean param_1 = obj.insertFront(value);
* boolean param_2 = obj.insertLast(value);
* boolean param_3 = obj.deleteFront();
* boolean param_4 = obj.deleteLast();
* int param_5 = obj.getFront();
* int param_6 = obj.getRear();
* boolean param_7 = obj.isEmpty();
* boolean param_8 = obj.isFull();
*/ | DaZuiZui/leetcode | P641.java | 529 | //首先查看大小是否核算 | line_comment | zh-cn | import java.util.LinkedList;
public class P641 {
public static void main(String[] args) {
}
}
class MyCircularDeque {
private int size = 0;
private LinkedList<Integer> list = new LinkedList();
//初始化大小
public MyCircularDeque(int k) {
this.size = k;
}
public boolean insertFront(int value) {
//首先查看大小是否核算
if (list.size() == size){
return false;
}
list.addFirst(value);
return true;
}
public boolean insertLast(int value) {
//首先 <SUF>
if (list.size() == size){
return false;
}
list.addLast(value);
return true;
}
public boolean deleteFront() {
//判断大小是否为0,如果为0直接返回false
if (list.size() == 0){
return false;
}
list.removeFirst();
return true;
}
public boolean deleteLast() {
//判断大小是否为0,如果为0直接返回false
if (list.size() == 0){
return false;
}
list.removeLast();
return true;
}
public int getFront() {
//判断大小是否为0,如果为0直接返回-1
if (list.size() == 0){
return -1;
}
return list.getFirst();
}
public int getRear() {
if (list.size() == 0){
return -1;
}
return list.getLast();
}
public boolean isEmpty() {
return list.isEmpty();
}
public boolean isFull() {
return list.size() == size;
}
}
/**
* Your MyCircularDeque object will be instantiated and called as such:
* MyCircularDeque obj = new MyCircularDeque(k);
* boolean param_1 = obj.insertFront(value);
* boolean param_2 = obj.insertLast(value);
* boolean param_3 = obj.deleteFront();
* boolean param_4 = obj.deleteLast();
* int param_5 = obj.getFront();
* int param_6 = obj.getRear();
* boolean param_7 = obj.isEmpty();
* boolean param_8 = obj.isFull();
*/ | false | 479 | 6 | 529 | 7 | 581 | 7 | 529 | 7 | 655 | 13 | false | false | false | false | false | true |
49972_6 | package com.daemon.pas.presenter.player;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.support.v4.content.LocalBroadcastManager;
import com.daemon.framework.dutils.DLog;
import com.daemon.pas.common.AppRunCache;
import java.io.IOException;
import java.util.List;
/**
* Created by Daemon on 2015/12/25.
*/
public class MusicPlayer implements BaseMusicPlayer, MediaPlayer.OnPreparedListener {
public static final int State_Play = 0;
public static final int State_Pasue = 1;
public static final int State_Stop = 2;
private Intent intent_update;
private MediaPlayer mediaPlayer;
//播放的music index 初始状态
private int play_index = 0;
//当前音乐状态
private int Music_State;
private List<String> musicList;
private String path;
private LocalBroadcastManager mLocalBroadcastManager;
private IntentFilter intentFilter;
private MusicPlayBroadReceiver myReceiver;
private boolean isDestroy=false;
public MusicPlayer(Context context) {
Music_State = State_Stop;
mediaPlayer = new MediaPlayer();
musicList = AppRunCache.musicList;
intentFilter = new IntentFilter();
intentFilter.addAction(IntentFilterUtils.Music_Pause);
intentFilter.addAction(IntentFilterUtils.Music_Resume);
intentFilter.addAction(IntentFilterUtils.Music_Next);
intentFilter.addAction(IntentFilterUtils.Music_Previous);
intentFilter.addAction(IntentFilterUtils.Music_Play_Pause_Onlcik);
intentFilter.addAction(IntentFilterUtils.Progress);
intentFilter.addAction(IntentFilterUtils.Music_Reset);
mLocalBroadcastManager = LocalBroadcastManager.getInstance(context);
myReceiver = new MusicPlayBroadReceiver();
mLocalBroadcastManager.registerReceiver(myReceiver, intentFilter);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
//自动播放结束后 下一首 先通知
DLog.e("setOnCompletionListener");
next();
}
});
DLog.e("onCreate");
mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
@Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
DLog.e("setOnSeekCompleteListener ");
if (Music_State == State_Play) {
mediaPlayer.start();
}
}
});
intent_update = new Intent(IntentFilterUtils.Progress_Update);
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
intent_update.putExtra(IntentFilterUtils.Progress_Update, mediaPlayer.getCurrentPosition());
//DLog.e("setOnBufferingUpdateListener " + mediaPlayer.getCurrentPosition() + " " + i);
mLocalBroadcastManager.sendBroadcast(intent_update);
}
});
play();
}
/**
* 对外点击播放按钮提供的方法
*/
public void actionPlay() {
switch (Music_State) {
case State_Play:
pause();
break;
case State_Pasue:
resume();
break;
case State_Stop:
Music_State = State_Play;
if(mediaPlayer.getCurrentPosition()!=0){
//说明是拖拽过的
mediaPlayer.start();
sendUIAnimatorPlay();
}else {
play();
}
break;
}
}
@Override
public void play() {
if(musicList==null || musicList.size()==0){
return;
}
path = musicList.get(play_index);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(this);
} catch (IOException e) {
e.printStackTrace();
}
DLog.e("play " + play_index);
}
@Override
public void pause() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
Music_State = State_Pasue;
mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Pause));
}
DLog.e("pause " + musicList.size() + " -> " + play_index);
}
@Override
public void resume() {
if (Music_State == State_Pasue) {
mediaPlayer.start();
Music_State = State_Play;
mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Resume));
}
DLog.e("resume " + musicList.size() + " -> " + play_index);
}
@Override
public void seekTo(int progress) {
DLog.e("接受 " + progress);
mediaPlayer.seekTo(progress * mediaPlayer.getDuration() / 100);
}
/**
* 上一首
*/
public void previous() {
if (play_index == 0) {
sendNoPrevious();
return;
} else {
play_index--;
}
Music_State=State_Play;
play();
sendCurrentPosition();
DLog.e("previous " + musicList.size() + " -> " + play_index);
}
/**
* 下一首
*/
public void next() {
Music_State=State_Play;
if (play_index == musicList.size() - 1) {
play_index = 0;
} else {
play_index++;
}
play();
sendCurrentPosition();
DLog.e("next " + musicList.size() + " -> " + play_index);
}
/**
* 当前显示的数据 停止上一个动画
*/
private void sendCurrentPosition() {
Intent intent = new Intent(IntentFilterUtils.Position);
intent.putExtra(IntentFilterUtils.Index, play_index);
mLocalBroadcastManager.sendBroadcast(intent);
}
private void reset() {
play_index = 0;
musicList = AppRunCache.musicList;
sendCurrentPosition();
play();
}
@Override
public void destory() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
mLocalBroadcastManager.unregisterReceiver(myReceiver);
}
/**
* 通知没有上一首了
*/
private void sendNoPrevious() {
Intent intent = new Intent(IntentFilterUtils.Music_Previous_NO);
mLocalBroadcastManager.sendBroadcast(intent);
}
/**
* 通知 ui 改变 动画开始 显示当前歌曲信息
*/
private void sendUIAnimatorPlay() {
//缓存完毕 发送通知 动画 做出改变
Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK);
intent.putExtra(IntentFilterUtils.Index, play_index);
intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration());
mLocalBroadcastManager.sendBroadcast(intent);
}
@Override
public void onPrepared(MediaPlayer mp) {
if (Music_State != State_Stop) {
//只要缓存完毕 就开始放歌 不不管现在是暂停还是播放 只要下一首就继续播放
mediaPlayer.start();
sendUIAnimatorPlay();
Music_State = State_Play;
DLog.e("onPrepared pay" + musicList.size() + " -> " + play_index);
}else {
//只要缓冲完了 就将真个音乐的size传送
sendMusicSize();
Music_State=State_Pasue;
DLog.e("onPrepared stop" + musicList.size() + " -> " + play_index);
}
}
private void sendMusicSize() {
//有位置就播放 没有就显示大小
Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK);
intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration());
mLocalBroadcastManager.sendBroadcast(intent);
}
class MusicPlayBroadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case IntentFilterUtils.Music_Play_Pause_Onlcik:
DLog.e("Music_Play_Pause_Onlcik");
actionPlay();
break;
case IntentFilterUtils.Music_Next:
DLog.e("Music_Next");
next();
break;
case IntentFilterUtils.Music_Previous:
DLog.e("Music_Previous");
previous();
break;
case IntentFilterUtils.Music_Reset:
reset();
break;
case IntentFilterUtils.Progress:
int progress = intent.getIntExtra(IntentFilterUtils.Progress, -1);
seekTo(progress);
break;
}
}
}
}
| Daemon1993/Pas | app/src/main/java/com/daemon/pas/presenter/player/MusicPlayer.java | 2,096 | //说明是拖拽过的 | line_comment | zh-cn | package com.daemon.pas.presenter.player;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.support.v4.content.LocalBroadcastManager;
import com.daemon.framework.dutils.DLog;
import com.daemon.pas.common.AppRunCache;
import java.io.IOException;
import java.util.List;
/**
* Created by Daemon on 2015/12/25.
*/
public class MusicPlayer implements BaseMusicPlayer, MediaPlayer.OnPreparedListener {
public static final int State_Play = 0;
public static final int State_Pasue = 1;
public static final int State_Stop = 2;
private Intent intent_update;
private MediaPlayer mediaPlayer;
//播放的music index 初始状态
private int play_index = 0;
//当前音乐状态
private int Music_State;
private List<String> musicList;
private String path;
private LocalBroadcastManager mLocalBroadcastManager;
private IntentFilter intentFilter;
private MusicPlayBroadReceiver myReceiver;
private boolean isDestroy=false;
public MusicPlayer(Context context) {
Music_State = State_Stop;
mediaPlayer = new MediaPlayer();
musicList = AppRunCache.musicList;
intentFilter = new IntentFilter();
intentFilter.addAction(IntentFilterUtils.Music_Pause);
intentFilter.addAction(IntentFilterUtils.Music_Resume);
intentFilter.addAction(IntentFilterUtils.Music_Next);
intentFilter.addAction(IntentFilterUtils.Music_Previous);
intentFilter.addAction(IntentFilterUtils.Music_Play_Pause_Onlcik);
intentFilter.addAction(IntentFilterUtils.Progress);
intentFilter.addAction(IntentFilterUtils.Music_Reset);
mLocalBroadcastManager = LocalBroadcastManager.getInstance(context);
myReceiver = new MusicPlayBroadReceiver();
mLocalBroadcastManager.registerReceiver(myReceiver, intentFilter);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
//自动播放结束后 下一首 先通知
DLog.e("setOnCompletionListener");
next();
}
});
DLog.e("onCreate");
mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
@Override
public void onSeekComplete(MediaPlayer mediaPlayer) {
DLog.e("setOnSeekCompleteListener ");
if (Music_State == State_Play) {
mediaPlayer.start();
}
}
});
intent_update = new Intent(IntentFilterUtils.Progress_Update);
mediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() {
@Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int i) {
intent_update.putExtra(IntentFilterUtils.Progress_Update, mediaPlayer.getCurrentPosition());
//DLog.e("setOnBufferingUpdateListener " + mediaPlayer.getCurrentPosition() + " " + i);
mLocalBroadcastManager.sendBroadcast(intent_update);
}
});
play();
}
/**
* 对外点击播放按钮提供的方法
*/
public void actionPlay() {
switch (Music_State) {
case State_Play:
pause();
break;
case State_Pasue:
resume();
break;
case State_Stop:
Music_State = State_Play;
if(mediaPlayer.getCurrentPosition()!=0){
//说明 <SUF>
mediaPlayer.start();
sendUIAnimatorPlay();
}else {
play();
}
break;
}
}
@Override
public void play() {
if(musicList==null || musicList.size()==0){
return;
}
path = musicList.get(play_index);
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(path);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(this);
} catch (IOException e) {
e.printStackTrace();
}
DLog.e("play " + play_index);
}
@Override
public void pause() {
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.pause();
Music_State = State_Pasue;
mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Pause));
}
DLog.e("pause " + musicList.size() + " -> " + play_index);
}
@Override
public void resume() {
if (Music_State == State_Pasue) {
mediaPlayer.start();
Music_State = State_Play;
mLocalBroadcastManager.sendBroadcast(new Intent(IntentFilterUtils.Music_Resume));
}
DLog.e("resume " + musicList.size() + " -> " + play_index);
}
@Override
public void seekTo(int progress) {
DLog.e("接受 " + progress);
mediaPlayer.seekTo(progress * mediaPlayer.getDuration() / 100);
}
/**
* 上一首
*/
public void previous() {
if (play_index == 0) {
sendNoPrevious();
return;
} else {
play_index--;
}
Music_State=State_Play;
play();
sendCurrentPosition();
DLog.e("previous " + musicList.size() + " -> " + play_index);
}
/**
* 下一首
*/
public void next() {
Music_State=State_Play;
if (play_index == musicList.size() - 1) {
play_index = 0;
} else {
play_index++;
}
play();
sendCurrentPosition();
DLog.e("next " + musicList.size() + " -> " + play_index);
}
/**
* 当前显示的数据 停止上一个动画
*/
private void sendCurrentPosition() {
Intent intent = new Intent(IntentFilterUtils.Position);
intent.putExtra(IntentFilterUtils.Index, play_index);
mLocalBroadcastManager.sendBroadcast(intent);
}
private void reset() {
play_index = 0;
musicList = AppRunCache.musicList;
sendCurrentPosition();
play();
}
@Override
public void destory() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
mLocalBroadcastManager.unregisterReceiver(myReceiver);
}
/**
* 通知没有上一首了
*/
private void sendNoPrevious() {
Intent intent = new Intent(IntentFilterUtils.Music_Previous_NO);
mLocalBroadcastManager.sendBroadcast(intent);
}
/**
* 通知 ui 改变 动画开始 显示当前歌曲信息
*/
private void sendUIAnimatorPlay() {
//缓存完毕 发送通知 动画 做出改变
Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK);
intent.putExtra(IntentFilterUtils.Index, play_index);
intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration());
mLocalBroadcastManager.sendBroadcast(intent);
}
@Override
public void onPrepared(MediaPlayer mp) {
if (Music_State != State_Stop) {
//只要缓存完毕 就开始放歌 不不管现在是暂停还是播放 只要下一首就继续播放
mediaPlayer.start();
sendUIAnimatorPlay();
Music_State = State_Play;
DLog.e("onPrepared pay" + musicList.size() + " -> " + play_index);
}else {
//只要缓冲完了 就将真个音乐的size传送
sendMusicSize();
Music_State=State_Pasue;
DLog.e("onPrepared stop" + musicList.size() + " -> " + play_index);
}
}
private void sendMusicSize() {
//有位置就播放 没有就显示大小
Intent intent = new Intent(IntentFilterUtils.Music_Prepared_OK);
intent.putExtra(IntentFilterUtils.Music_Size, mediaPlayer.getDuration());
mLocalBroadcastManager.sendBroadcast(intent);
}
class MusicPlayBroadReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case IntentFilterUtils.Music_Play_Pause_Onlcik:
DLog.e("Music_Play_Pause_Onlcik");
actionPlay();
break;
case IntentFilterUtils.Music_Next:
DLog.e("Music_Next");
next();
break;
case IntentFilterUtils.Music_Previous:
DLog.e("Music_Previous");
previous();
break;
case IntentFilterUtils.Music_Reset:
reset();
break;
case IntentFilterUtils.Progress:
int progress = intent.getIntExtra(IntentFilterUtils.Progress, -1);
seekTo(progress);
break;
}
}
}
}
| false | 1,845 | 6 | 2,096 | 9 | 2,241 | 6 | 2,096 | 9 | 2,664 | 12 | false | false | false | false | false | true |
44720_0 | package main.Array;
public interface Array {
//查找对付
public int find(String element);
//插入
public void insert(String element);
//删除
public void delete(String element);
//列出所有元素
public void display();
}
| Daemonxiao/DataStructures | src/main/Array/Array.java | 60 | //查找对付 | line_comment | zh-cn | package main.Array;
public interface Array {
//查找 <SUF>
public int find(String element);
//插入
public void insert(String element);
//删除
public void delete(String element);
//列出所有元素
public void display();
}
| false | 54 | 3 | 60 | 4 | 66 | 3 | 60 | 4 | 81 | 7 | false | false | false | false | false | true |
49387_3 | package com.dai.entity;
import java.util.Date;
/**
* 店铺
* @author 18491
*
*/
public class Shop {
private Long shopId;
private String shopName;
private String shopDesc;
//店铺地址
private String shopAddr;
//店铺联系方式
private String phone;
//店铺缩略图的地址
private String shopImg;
private Integer priority;
private Date createTime;
private Date lastEditTime;
//-1:不可用 0:审核中 1:可用
private Integer enableStatus;
//超级管理员给店家的提醒
private String advice;
//店铺的位置
private Area area;
//店铺所属人
private PersonInfo owner;
//店铺的类别
private ShopCategory shopCategory;
public Long getShopId() {
return shopId;
}
public void setShopId(Long shopId) {
this.shopId = shopId;
}
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public String getShopDesc() {
return shopDesc;
}
public void setShopDesc(String shopDesc) {
this.shopDesc = shopDesc;
}
public String getShopAddr() {
return shopAddr;
}
public void setShopAddr(String shopAddr) {
this.shopAddr = shopAddr;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getShopImg() {
return shopImg;
}
public void setShopImg(String shopImg) {
this.shopImg = shopImg;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastEditTime() {
return lastEditTime;
}
public void setLastEditTime(Date lastEditTime) {
this.lastEditTime = lastEditTime;
}
public Integer getEnableStatus() {
return enableStatus;
}
public void setEnableStatus(Integer enableStatus) {
this.enableStatus = enableStatus;
}
public String getAdvice() {
return advice;
}
public void setAdvice(String advice) {
this.advice = advice;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
public PersonInfo getOwner() {
return owner;
}
public void setOwner(PersonInfo owner) {
this.owner = owner;
}
public ShopCategory getShopCategory() {
return shopCategory;
}
public void setShopCategory(ShopCategory shopCategory) {
this.shopCategory = shopCategory;
}
}
| DaiOwen/DeskMate | src/main/java/com/dai/entity/Shop.java | 819 | //店铺缩略图的地址 | line_comment | zh-cn | package com.dai.entity;
import java.util.Date;
/**
* 店铺
* @author 18491
*
*/
public class Shop {
private Long shopId;
private String shopName;
private String shopDesc;
//店铺地址
private String shopAddr;
//店铺联系方式
private String phone;
//店铺 <SUF>
private String shopImg;
private Integer priority;
private Date createTime;
private Date lastEditTime;
//-1:不可用 0:审核中 1:可用
private Integer enableStatus;
//超级管理员给店家的提醒
private String advice;
//店铺的位置
private Area area;
//店铺所属人
private PersonInfo owner;
//店铺的类别
private ShopCategory shopCategory;
public Long getShopId() {
return shopId;
}
public void setShopId(Long shopId) {
this.shopId = shopId;
}
public String getShopName() {
return shopName;
}
public void setShopName(String shopName) {
this.shopName = shopName;
}
public String getShopDesc() {
return shopDesc;
}
public void setShopDesc(String shopDesc) {
this.shopDesc = shopDesc;
}
public String getShopAddr() {
return shopAddr;
}
public void setShopAddr(String shopAddr) {
this.shopAddr = shopAddr;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getShopImg() {
return shopImg;
}
public void setShopImg(String shopImg) {
this.shopImg = shopImg;
}
public Integer getPriority() {
return priority;
}
public void setPriority(Integer priority) {
this.priority = priority;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getLastEditTime() {
return lastEditTime;
}
public void setLastEditTime(Date lastEditTime) {
this.lastEditTime = lastEditTime;
}
public Integer getEnableStatus() {
return enableStatus;
}
public void setEnableStatus(Integer enableStatus) {
this.enableStatus = enableStatus;
}
public String getAdvice() {
return advice;
}
public void setAdvice(String advice) {
this.advice = advice;
}
public Area getArea() {
return area;
}
public void setArea(Area area) {
this.area = area;
}
public PersonInfo getOwner() {
return owner;
}
public void setOwner(PersonInfo owner) {
this.owner = owner;
}
public ShopCategory getShopCategory() {
return shopCategory;
}
public void setShopCategory(ShopCategory shopCategory) {
this.shopCategory = shopCategory;
}
}
| false | 620 | 7 | 819 | 9 | 795 | 7 | 819 | 9 | 916 | 15 | false | false | false | false | false | true |
39416_2 | package com.damon.chain.travel2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 功能:链管理者,链上所有节点都在此管理
*
* @author Damon
* @since 2018-12-23 21:54
*/
@Slf4j
public class HandlerChain {
private List<Handler> handlerList = new ArrayList<>();
/**
* 维护当前链上位置
*/
private int pos;
/**
* 链的长度
*/
private int handlerLength;
public void addHandler(Handler handler) {
handlerList.add(handler);
handlerLength = handlerList.size();
}
public void handle(String name, double wallet) {
if (CollectionUtils.isEmpty(handlerList)) {
log.error("有钱,但没提供服务,{}也估计就只能步行了。", name);
return;
}
if (pos >= handlerLength) {
log.error("身上钱不够,{}也估计就只能步行了。", name);
reuse();
return;
}
Handler handler = handlerList.get(pos++);
if (Objects.isNull(handler)) {
log.error("假服务,{}也估计就只能步行了。", name);
reuse();
return;
}
handler.handleRequest(name, wallet, this);
}
/**
* 链重新使用
*/
public void reuse() {
pos = 0;
}
}
| DamonChow/design_pattern | chain/src/main/java/com/damon/chain/travel2/HandlerChain.java | 388 | /**
* 链的长度
*/ | block_comment | zh-cn | package com.damon.chain.travel2;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* 功能:链管理者,链上所有节点都在此管理
*
* @author Damon
* @since 2018-12-23 21:54
*/
@Slf4j
public class HandlerChain {
private List<Handler> handlerList = new ArrayList<>();
/**
* 维护当前链上位置
*/
private int pos;
/**
* 链的长 <SUF>*/
private int handlerLength;
public void addHandler(Handler handler) {
handlerList.add(handler);
handlerLength = handlerList.size();
}
public void handle(String name, double wallet) {
if (CollectionUtils.isEmpty(handlerList)) {
log.error("有钱,但没提供服务,{}也估计就只能步行了。", name);
return;
}
if (pos >= handlerLength) {
log.error("身上钱不够,{}也估计就只能步行了。", name);
reuse();
return;
}
Handler handler = handlerList.get(pos++);
if (Objects.isNull(handler)) {
log.error("假服务,{}也估计就只能步行了。", name);
reuse();
return;
}
handler.handleRequest(name, wallet, this);
}
/**
* 链重新使用
*/
public void reuse() {
pos = 0;
}
}
| false | 336 | 11 | 388 | 9 | 405 | 10 | 388 | 9 | 500 | 14 | false | false | false | false | false | true |
54611_4 | package com.sensor.entity;
import com.sensor.Generate.*;
import java.util.List;
/**
* Created by DanLongChen on 2018/11/26
* 网络节点类
**/
public class GANode extends Nodes {
private int id; //唯一标示节点
private String data;//节点的数据
private Point point;//节点位置信息
private List<GANode> neibor;//邻居
private boolean state;//是否损坏
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
public List<GANode> getNeibor() {
return neibor;
}
public void setNeibor(List<GANode> neibor) {
this.neibor = neibor;
}
public boolean isState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
}
| DanLongChen/SensorSys | src/main/java/com/sensor/entity/GANode.java | 292 | //是否损坏 | line_comment | zh-cn | package com.sensor.entity;
import com.sensor.Generate.*;
import java.util.List;
/**
* Created by DanLongChen on 2018/11/26
* 网络节点类
**/
public class GANode extends Nodes {
private int id; //唯一标示节点
private String data;//节点的数据
private Point point;//节点位置信息
private List<GANode> neibor;//邻居
private boolean state;//是否 <SUF>
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
public List<GANode> getNeibor() {
return neibor;
}
public void setNeibor(List<GANode> neibor) {
this.neibor = neibor;
}
public boolean isState() {
return state;
}
public void setState(boolean state) {
this.state = state;
}
}
| false | 268 | 3 | 292 | 6 | 316 | 3 | 292 | 6 | 373 | 9 | false | false | false | false | false | true |
36674_17 | package com.real.simhotel.presenter;
import com.real.simhotel.events.BaseStatus;
import com.real.simhotel.events.EventCode;
import com.real.simhotel.events.TrainStatus;
import com.real.simhotel.events.StatusManager;
import com.real.simhotel.presenter.base.BasePresenter;
import com.real.simhotel.utils.log.KLog;
import com.real.simhotel.view.adapter.DynamicListAdapter;
import com.real.simhotel.view.adapter.DynamicListModel;
import com.real.simhotel.view.adapter.DynamicListModelFactory;
import com.real.simhotel.view.fragment.student.CeoNormalFragment;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liudan on 2016/12/19.
*/
public class CeoNormalPresenter extends BasePresenter{
private CeoNormalFragment mView;
private List<DynamicListModel> list;
public static final int CEO_DECISION_HIRE = 1;
public static final int CEO_DECISION_LOAN = 2;
public CeoNormalPresenter(CeoNormalFragment view){
mView = view;
}
public DynamicListAdapter.NormalChooseInterface getChooseInterface() {
return mChooseInterface;
}
@Override
public void handleStatus(BaseStatus event) {
switch (event.getStatus()){
case EventCode.GroupCode.GROUP_CEO_HIRE_ING:
//开始 增加 雇员 信息 TODO 招聘会的时间
if (list == null){
list = new ArrayList<>();
}
list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?",
application.training.getCurrentCycle() + "", CEO_DECISION_HIRE));
//加载列表
mView.loadList(list);
application.traingingStatusManager.consumeStatus(event);
break;
}
}
@Override
public void destroy() {
super.destroy();
EventBus.getDefault().unregister(this);
}
@Override
public void requestData(Object... o) {
super.requestData(o);
// KLog.d("id = " + application.mHotel.getId());
// list = new ArrayList();
// if (application.group.getGroupStatus() == EventCode.GroupCode.GROUP_CEO_HIRE_ING){
// //增加一条招聘信息
//
// list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?",
// application.training.getCurrentCycle()+"",
// CEO_DECISION_HIRE));
//
// }
// list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 80 玩 ,支出 10 玩","2016年6月"));
// list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 90 玩 ,支出 30 玩","2016年6月"));
// list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 100 玩 ,支出 30 玩","2016年7月"));
// list.add(DynamicListModelFactory.modelForCeoDecisionMessage("大哥你要破产了,贷款不?","2016年9月",2));
//加载列表
// mView.loadList(list);
}
/**
* 监听list中的选项
*/
private DynamicListAdapter.NormalChooseInterface mChooseInterface = new DynamicListAdapter.NormalChooseInterface() {
@Override
public void onChoose(DynamicListModel model, Boolean hasConfirm) {
//修改状态
mView.showLoading();
int eventCode = 0;
if ( (int)model.ext == CEO_DECISION_HIRE) {
eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_REJECT;
if (hasConfirm)
eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_CONFIRM;
}else if ((int)model.ext == CEO_DECISION_LOAN){
eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_REJECT;
if (hasConfirm)
eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_CONFIRM;
}
application.traingingStatusManager.changeGroupStatus(
eventCode,
new StatusManager.StatusChangeListener() {
@Override
public void OnChangedSuccess() {
mView.disMissLoading();
if (hasConfirm){
model.butonChooseInfo = "已开始";
mView.showToast("已确认");
}else {
model.butonChooseInfo = "已放弃";
mView.showToast("已放弃");
}
model.hasChoose = true;
mView.reload();
}
@Override
public void OnChangedFailed(String erro) {
mView.disMissLoading();
mView.showToast("请求失败请稍后再试");
}
});
}
};
}
| Danny1451/Simhotel | app/src/main/java/com/real/simhotel/presenter/CeoNormalPresenter.java | 1,267 | //修改状态 | line_comment | zh-cn | package com.real.simhotel.presenter;
import com.real.simhotel.events.BaseStatus;
import com.real.simhotel.events.EventCode;
import com.real.simhotel.events.TrainStatus;
import com.real.simhotel.events.StatusManager;
import com.real.simhotel.presenter.base.BasePresenter;
import com.real.simhotel.utils.log.KLog;
import com.real.simhotel.view.adapter.DynamicListAdapter;
import com.real.simhotel.view.adapter.DynamicListModel;
import com.real.simhotel.view.adapter.DynamicListModelFactory;
import com.real.simhotel.view.fragment.student.CeoNormalFragment;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
/**
* Created by liudan on 2016/12/19.
*/
public class CeoNormalPresenter extends BasePresenter{
private CeoNormalFragment mView;
private List<DynamicListModel> list;
public static final int CEO_DECISION_HIRE = 1;
public static final int CEO_DECISION_LOAN = 2;
public CeoNormalPresenter(CeoNormalFragment view){
mView = view;
}
public DynamicListAdapter.NormalChooseInterface getChooseInterface() {
return mChooseInterface;
}
@Override
public void handleStatus(BaseStatus event) {
switch (event.getStatus()){
case EventCode.GroupCode.GROUP_CEO_HIRE_ING:
//开始 增加 雇员 信息 TODO 招聘会的时间
if (list == null){
list = new ArrayList<>();
}
list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?",
application.training.getCurrentCycle() + "", CEO_DECISION_HIRE));
//加载列表
mView.loadList(list);
application.traingingStatusManager.consumeStatus(event);
break;
}
}
@Override
public void destroy() {
super.destroy();
EventBus.getDefault().unregister(this);
}
@Override
public void requestData(Object... o) {
super.requestData(o);
// KLog.d("id = " + application.mHotel.getId());
// list = new ArrayList();
// if (application.group.getGroupStatus() == EventCode.GroupCode.GROUP_CEO_HIRE_ING){
// //增加一条招聘信息
//
// list.add(DynamicListModelFactory.modelForCeoDecisionMessage("本季度招聘会即将开始是否招聘?",
// application.training.getCurrentCycle()+"",
// CEO_DECISION_HIRE));
//
// }
// list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 80 玩 ,支出 10 玩","2016年6月"));
// list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 90 玩 ,支出 30 玩","2016年6月"));
// list.add(DynamicListModelFactory.modelForCeoNormalMessage("本月的收入 100 玩 ,支出 30 玩","2016年7月"));
// list.add(DynamicListModelFactory.modelForCeoDecisionMessage("大哥你要破产了,贷款不?","2016年9月",2));
//加载列表
// mView.loadList(list);
}
/**
* 监听list中的选项
*/
private DynamicListAdapter.NormalChooseInterface mChooseInterface = new DynamicListAdapter.NormalChooseInterface() {
@Override
public void onChoose(DynamicListModel model, Boolean hasConfirm) {
//修改 <SUF>
mView.showLoading();
int eventCode = 0;
if ( (int)model.ext == CEO_DECISION_HIRE) {
eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_REJECT;
if (hasConfirm)
eventCode = EventCode.GroupCode.GROUP_CEO_HIRE_CONFIRM;
}else if ((int)model.ext == CEO_DECISION_LOAN){
eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_REJECT;
if (hasConfirm)
eventCode = EventCode.GroupCode.GROUP_CEO_LOAN_CONFIRM;
}
application.traingingStatusManager.changeGroupStatus(
eventCode,
new StatusManager.StatusChangeListener() {
@Override
public void OnChangedSuccess() {
mView.disMissLoading();
if (hasConfirm){
model.butonChooseInfo = "已开始";
mView.showToast("已确认");
}else {
model.butonChooseInfo = "已放弃";
mView.showToast("已放弃");
}
model.hasChoose = true;
mView.reload();
}
@Override
public void OnChangedFailed(String erro) {
mView.disMissLoading();
mView.showToast("请求失败请稍后再试");
}
});
}
};
}
| false | 1,029 | 3 | 1,267 | 3 | 1,235 | 3 | 1,267 | 3 | 1,591 | 5 | false | false | false | false | false | true |
40713_1 | package com.dl.officialsite.member;
import com.dl.officialsite.common.privacy.PrivacyEncrypt;
import com.dl.officialsite.common.privacy.PrivacyTypeEnum;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@EntityListeners(AuditingEntityListener.class)
@Entity
@DynamicUpdate
@Table(name = "member", schema = "dl", uniqueConstraints = {
@UniqueConstraint(name = "address", columnNames = {"address"}),
@UniqueConstraint(name = "tweetId", columnNames = {"tweetId"}),
@UniqueConstraint(name = "githubId", columnNames = {"githubId"}),
@UniqueConstraint(name = "nickName", columnNames = {"nickName"})})
public class Member implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 42)
@NotNull
private String address;
@Column(unique = true, length = 40)
@NotNull
@PrivacyEncrypt(type = PrivacyTypeEnum.EMAIL)
private String email;
@Column(unique = true, length = 20)
@NotNull
private String nickName;
private int role; // 0开发者,1 设计师 2产品 3运营 4 测试 5 运维 6项目经理 7 研究员 8 投资人 9 市场 10 数据分析师 11 其他
@Column(unique = true, length = 38)
private String githubId;
@Column(length = 20)
private String tweetId;
@Column(unique = true, length = 64)
private String tweetScreenName;
@Column(length = 20)
private String telegramId;
@Column(length = 20)
private String wechatId;
private String avatar;
private String techStack; //前端 ,后端 , 全栈, 运维,DBA, UI/UX, AI, 密码学,智能合约,数据分析, 共识算法,金融,数学, 网络安全, 英语, 其他
private String programing;
// optional
private String interests; //兴趣
private String city;
private int shareCount;
private int rewardCount;
@CreatedDate
@Column(updatable = false)
private Long createTime;
@LastModifiedDate
@Column(updatable = false, nullable = false)
private Long updateTime;
//todo
private Long workStatus;
private int githubStatus;
private int twitterStatus;
//@PrivacyEncrypt(type= CUSTOMER)
@JsonIgnore
private String resume;
/**
* 1 forbidden 0 normal
*/
@Column(columnDefinition = "tinyint default 0")
private Integer status = 0;
}
| Dapp-Learning-DAO/Official-website-backend | src/main/java/com/dl/officialsite/member/Member.java | 857 | //前端 ,后端 , 全栈, 运维,DBA, UI/UX, AI, 密码学,智能合约,数据分析, 共识算法,金融,数学, 网络安全, 英语, 其他 | line_comment | zh-cn | package com.dl.officialsite.member;
import com.dl.officialsite.common.privacy.PrivacyEncrypt;
import com.dl.officialsite.common.privacy.PrivacyTypeEnum;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@EntityListeners(AuditingEntityListener.class)
@Entity
@DynamicUpdate
@Table(name = "member", schema = "dl", uniqueConstraints = {
@UniqueConstraint(name = "address", columnNames = {"address"}),
@UniqueConstraint(name = "tweetId", columnNames = {"tweetId"}),
@UniqueConstraint(name = "githubId", columnNames = {"githubId"}),
@UniqueConstraint(name = "nickName", columnNames = {"nickName"})})
public class Member implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(length = 42)
@NotNull
private String address;
@Column(unique = true, length = 40)
@NotNull
@PrivacyEncrypt(type = PrivacyTypeEnum.EMAIL)
private String email;
@Column(unique = true, length = 20)
@NotNull
private String nickName;
private int role; // 0开发者,1 设计师 2产品 3运营 4 测试 5 运维 6项目经理 7 研究员 8 投资人 9 市场 10 数据分析师 11 其他
@Column(unique = true, length = 38)
private String githubId;
@Column(length = 20)
private String tweetId;
@Column(unique = true, length = 64)
private String tweetScreenName;
@Column(length = 20)
private String telegramId;
@Column(length = 20)
private String wechatId;
private String avatar;
private String techStack; //前端 <SUF>
private String programing;
// optional
private String interests; //兴趣
private String city;
private int shareCount;
private int rewardCount;
@CreatedDate
@Column(updatable = false)
private Long createTime;
@LastModifiedDate
@Column(updatable = false, nullable = false)
private Long updateTime;
//todo
private Long workStatus;
private int githubStatus;
private int twitterStatus;
//@PrivacyEncrypt(type= CUSTOMER)
@JsonIgnore
private String resume;
/**
* 1 forbidden 0 normal
*/
@Column(columnDefinition = "tinyint default 0")
private Integer status = 0;
}
| false | 752 | 58 | 857 | 60 | 871 | 47 | 857 | 60 | 1,087 | 87 | false | false | false | false | false | true |
31252_1 | package org.datasays.wes.demo.fetch;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import org.datasays.util.JsonObjGetter;
import org.datasays.util.WCfg;
import org.datasays.util.WPage;
import org.datasays.util.WPageIterator;
import org.datasays.wes.EsBaseService;
import org.datasays.wes.core.HttpException;
import org.datasays.wes.core.JsonObj;
import org.datasays.wes.core.RequestInfo;
import org.datasays.wes.core.WHttpClient;
import org.datasays.wes.toolkit.WGsonConvert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by watano on 2016/12/5.
*/
public class BaiduFetcher {
private static Logger LOG = LoggerFactory.getLogger(BaiduFetcher.class);
private final int FetchInterval = 1;//间隔时间,单位s
public final String index = "fetchdata";
public final String type = "BaiduMap";
private WHttpClient baiduClient;
private EsBaseService esHelper;
public String appKey;
public String appSecret;
public BaiduFetcher(String appKey, String appSecret) {
this.appKey = appKey;
this.appSecret = appSecret;
}
public void init() {
OkHttpClient.Builder cBuilder = new OkHttpClient.Builder();
cBuilder.cache(new Cache(new File("./build/baidu"), 10000));
baiduClient = new WHttpClient(cBuilder.build(), new WGsonConvert());
baiduClient.setLogFlag(false, false, true);
esHelper = new EsBaseService();
esHelper.init(WCfg.getValue("ES.server"), null, null);
}
private RequestInfo create() {
RequestInfo action = new RequestInfo("http://api.map.baidu.com/place/v2/");
action.addParams("ak", appKey);
return action;
}
public JsonObjGetter searchPOIByRegion(WPage page, String query, String region) throws HttpException {
RequestInfo action = create();
action.setUrl("search");
action.addParams("scope", 2);
action.addParams("output", "json");
action.addParams("query", query);
action.addParams("region", region);
action.addParams("page_size", page.getSize());
if (page.getPageNo() > 0) {
action.addParams("page_num", page.getPageNo()-1);
}
LOG.info(page.toText());
JsonObjGetter result = new JsonObjGetter(baiduClient.get(action, Object.class));
if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) {
if (result.num("total") != null && result.num("total").intValue() > 0) {
page.setTotal(result.num("total").intValue());
}
}
return result;
}
public void fetchALLPOIByRegion(String query, String region){
WPage page = new WPage();
WPageIterator<Object> pageIterator = new WPageIterator<Object>(page) {
@Override
public void doSearch() {
try {
JsonObjGetter result = searchPOIByRegion(getPage(), query, region);
if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) {
int total = 0;
if (result.num("total") != null && result.num("total").intValue() > 0) {
total = result.num("total").intValue();
}
List<Object> items = new ArrayList<>();
if (result.list("results") != null) {
items.addAll(result.list("results"));
}
update(items, total);
Thread.sleep(FetchInterval*1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
while (pageIterator.hasNext()) {
Object item = pageIterator.next();
save(item);
}
}
public void save(Object item) {
try {
esHelper.index(index, type, null, item);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
public static void main(String[] args) {
JsonObj allIndustry = new JsonObj();
allIndustry.lstAdd("美食", "中餐厅", "外国餐厅", "小吃快餐店", "蛋糕甜品店", "咖啡厅", "茶座", "酒吧");
allIndustry.lstAdd("酒店", "星级酒店", "快捷酒店", "公寓式酒店");
allIndustry.lstAdd("购物", "购物中心", "超市", "便利店", "家居建材", "家电数码", "商铺", "集市");
allIndustry.lstAdd("生活服务", "通讯营业厅", "邮局", "物流公司", "售票处", "洗衣店", "图文快印店", "照相馆", "房产中介机构", "公用事业", "维修点", "家政服务", "殡葬服务", "彩票销售点", "宠物服务", "报刊亭", "公共厕所");
allIndustry.lstAdd("丽人", "美容", "美发", "美甲", "美体");
allIndustry.lstAdd("旅游景点", "公园", "动物园", "植物园", "游乐园", "博物馆", "水族馆", "海滨浴场", "文物古迹", "教堂", "风景区");
allIndustry.lstAdd("休闲娱乐", "度假村", "农家院", "电影院", "KTV", "剧院", "歌舞厅", "网吧", "游戏场所", "洗浴按摩", "休闲广场");
allIndustry.lstAdd("运动健身", "体育场馆", "极限运动场所", "健身中心");
allIndustry.lstAdd("教育培训", "高等院校", "中学", "小学", "幼儿园", "成人教育", "亲子教育", "特殊教育学校", "留学中介机构", "科研机构", "培训机构", "图书馆", "科技馆");
allIndustry.lstAdd("文化传媒", "新闻出版", "广播电视", "艺术团体", "美术馆", "展览馆", "文化宫");
allIndustry.lstAdd("医疗", "综合医院", "专科医院", "诊所", "药店", "体检机构", "疗养院", "急救中心", "疾控中心");
allIndustry.lstAdd("汽车服务", "汽车销售", "汽车维修", "汽车美容", "汽车配件", "汽车租赁", "汽车检测场");
allIndustry.lstAdd("交通设施", "飞机场", "火车站", "地铁站", "长途汽车站", "公交车站", "港口", "停车场", "加油加气站", "服务区", "收费站", "桥");
allIndustry.lstAdd("金融", "银行", "ATM", "信用社", "投资理财", "典当行");
allIndustry.lstAdd("房地产", "写字楼", "住宅区", "宿舍");
allIndustry.lstAdd("公司企业", "公司", "园区", "农林园艺", "厂矿");
allIndustry.lstAdd("政府机构", "中央机构", "各级政府", "行政单位", "公检法机构", "涉外机构", "党派团体", "福利机构", "政治教育机构");
BaiduFetcher fetcher = new BaiduFetcher(args[0], args[1]);
fetcher.init();
String region = "玉溪";
for(String mainIndustry: new String[]{"美食", "酒店", "购物", "丽人", "休闲娱乐"}){
for(Object industry: (Object[]) allIndustry.get(mainIndustry)){
fetcher.fetchALLPOIByRegion(industry.toString(), region);
}
}
}
}
| DataSays/wES | wES-demo/src/main/java/org/datasays/wes/demo/fetch/BaiduFetcher.java | 2,281 | //间隔时间,单位s | line_comment | zh-cn | package org.datasays.wes.demo.fetch;
import okhttp3.Cache;
import okhttp3.OkHttpClient;
import org.datasays.util.JsonObjGetter;
import org.datasays.util.WCfg;
import org.datasays.util.WPage;
import org.datasays.util.WPageIterator;
import org.datasays.wes.EsBaseService;
import org.datasays.wes.core.HttpException;
import org.datasays.wes.core.JsonObj;
import org.datasays.wes.core.RequestInfo;
import org.datasays.wes.core.WHttpClient;
import org.datasays.wes.toolkit.WGsonConvert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by watano on 2016/12/5.
*/
public class BaiduFetcher {
private static Logger LOG = LoggerFactory.getLogger(BaiduFetcher.class);
private final int FetchInterval = 1;//间隔 <SUF>
public final String index = "fetchdata";
public final String type = "BaiduMap";
private WHttpClient baiduClient;
private EsBaseService esHelper;
public String appKey;
public String appSecret;
public BaiduFetcher(String appKey, String appSecret) {
this.appKey = appKey;
this.appSecret = appSecret;
}
public void init() {
OkHttpClient.Builder cBuilder = new OkHttpClient.Builder();
cBuilder.cache(new Cache(new File("./build/baidu"), 10000));
baiduClient = new WHttpClient(cBuilder.build(), new WGsonConvert());
baiduClient.setLogFlag(false, false, true);
esHelper = new EsBaseService();
esHelper.init(WCfg.getValue("ES.server"), null, null);
}
private RequestInfo create() {
RequestInfo action = new RequestInfo("http://api.map.baidu.com/place/v2/");
action.addParams("ak", appKey);
return action;
}
public JsonObjGetter searchPOIByRegion(WPage page, String query, String region) throws HttpException {
RequestInfo action = create();
action.setUrl("search");
action.addParams("scope", 2);
action.addParams("output", "json");
action.addParams("query", query);
action.addParams("region", region);
action.addParams("page_size", page.getSize());
if (page.getPageNo() > 0) {
action.addParams("page_num", page.getPageNo()-1);
}
LOG.info(page.toText());
JsonObjGetter result = new JsonObjGetter(baiduClient.get(action, Object.class));
if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) {
if (result.num("total") != null && result.num("total").intValue() > 0) {
page.setTotal(result.num("total").intValue());
}
}
return result;
}
public void fetchALLPOIByRegion(String query, String region){
WPage page = new WPage();
WPageIterator<Object> pageIterator = new WPageIterator<Object>(page) {
@Override
public void doSearch() {
try {
JsonObjGetter result = searchPOIByRegion(getPage(), query, region);
if ((result.num("status") != null && result.num("status").intValue() == 0) || "ok".equalsIgnoreCase(result.str("message"))) {
int total = 0;
if (result.num("total") != null && result.num("total").intValue() > 0) {
total = result.num("total").intValue();
}
List<Object> items = new ArrayList<>();
if (result.list("results") != null) {
items.addAll(result.list("results"));
}
update(items, total);
Thread.sleep(FetchInterval*1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
while (pageIterator.hasNext()) {
Object item = pageIterator.next();
save(item);
}
}
public void save(Object item) {
try {
esHelper.index(index, type, null, item);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
public static void main(String[] args) {
JsonObj allIndustry = new JsonObj();
allIndustry.lstAdd("美食", "中餐厅", "外国餐厅", "小吃快餐店", "蛋糕甜品店", "咖啡厅", "茶座", "酒吧");
allIndustry.lstAdd("酒店", "星级酒店", "快捷酒店", "公寓式酒店");
allIndustry.lstAdd("购物", "购物中心", "超市", "便利店", "家居建材", "家电数码", "商铺", "集市");
allIndustry.lstAdd("生活服务", "通讯营业厅", "邮局", "物流公司", "售票处", "洗衣店", "图文快印店", "照相馆", "房产中介机构", "公用事业", "维修点", "家政服务", "殡葬服务", "彩票销售点", "宠物服务", "报刊亭", "公共厕所");
allIndustry.lstAdd("丽人", "美容", "美发", "美甲", "美体");
allIndustry.lstAdd("旅游景点", "公园", "动物园", "植物园", "游乐园", "博物馆", "水族馆", "海滨浴场", "文物古迹", "教堂", "风景区");
allIndustry.lstAdd("休闲娱乐", "度假村", "农家院", "电影院", "KTV", "剧院", "歌舞厅", "网吧", "游戏场所", "洗浴按摩", "休闲广场");
allIndustry.lstAdd("运动健身", "体育场馆", "极限运动场所", "健身中心");
allIndustry.lstAdd("教育培训", "高等院校", "中学", "小学", "幼儿园", "成人教育", "亲子教育", "特殊教育学校", "留学中介机构", "科研机构", "培训机构", "图书馆", "科技馆");
allIndustry.lstAdd("文化传媒", "新闻出版", "广播电视", "艺术团体", "美术馆", "展览馆", "文化宫");
allIndustry.lstAdd("医疗", "综合医院", "专科医院", "诊所", "药店", "体检机构", "疗养院", "急救中心", "疾控中心");
allIndustry.lstAdd("汽车服务", "汽车销售", "汽车维修", "汽车美容", "汽车配件", "汽车租赁", "汽车检测场");
allIndustry.lstAdd("交通设施", "飞机场", "火车站", "地铁站", "长途汽车站", "公交车站", "港口", "停车场", "加油加气站", "服务区", "收费站", "桥");
allIndustry.lstAdd("金融", "银行", "ATM", "信用社", "投资理财", "典当行");
allIndustry.lstAdd("房地产", "写字楼", "住宅区", "宿舍");
allIndustry.lstAdd("公司企业", "公司", "园区", "农林园艺", "厂矿");
allIndustry.lstAdd("政府机构", "中央机构", "各级政府", "行政单位", "公检法机构", "涉外机构", "党派团体", "福利机构", "政治教育机构");
BaiduFetcher fetcher = new BaiduFetcher(args[0], args[1]);
fetcher.init();
String region = "玉溪";
for(String mainIndustry: new String[]{"美食", "酒店", "购物", "丽人", "休闲娱乐"}){
for(Object industry: (Object[]) allIndustry.get(mainIndustry)){
fetcher.fetchALLPOIByRegion(industry.toString(), region);
}
}
}
}
| false | 1,667 | 6 | 2,281 | 7 | 1,983 | 6 | 2,281 | 7 | 2,831 | 11 | false | false | false | false | false | true |
22451_0 |
import java.util.Date;
public class UserInfo {
private String userid;
private String username;
private String userpwd;
private int userStatus;//默认为0,正常。1为注销
private Date userTime;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
public int getUserStatus() {
return userStatus;
}
public void setUserStatus(int userStatus) {
this.userStatus = userStatus;
}
public Date getUserTime() {
return userTime;
}
public void setUserTime(Date userTime) {
this.userTime = userTime;
}
}
| DaturaH/demo-struts2-mybatis | src/UserInfo.java | 257 | //默认为0,正常。1为注销 | line_comment | zh-cn |
import java.util.Date;
public class UserInfo {
private String userid;
private String username;
private String userpwd;
private int userStatus;//默认 <SUF>
private Date userTime;
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpwd() {
return userpwd;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
public int getUserStatus() {
return userStatus;
}
public void setUserStatus(int userStatus) {
this.userStatus = userStatus;
}
public Date getUserTime() {
return userTime;
}
public void setUserTime(Date userTime) {
this.userTime = userTime;
}
}
| false | 200 | 10 | 257 | 10 | 264 | 10 | 257 | 10 | 305 | 15 | false | false | false | false | false | true |
3203_5 | package google.architecture.universal;
import android.content.Context;
import android.util.Log;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Interceptor;
import com.alibaba.android.arouter.facade.callback.InterceptorCallback;
import com.alibaba.android.arouter.facade.template.IInterceptor;
import google.architecture.common.base.ARouterPath;
/**
* Created by danxx on 2017/11/27.
*
* 比较经典的应用就是在跳转过程中处理登陆事件,这样就不需要在目标页重复做登陆检查
* 拦截器会在跳转之前执行,多个拦截器会按优先级顺序依次执行
*
* priority就是优先级 可以设置多个级别的拦截器都活一次执行
* 创建一个实现IInterceptor接口的类就是一个拦截器,不用做额外的配置了
*/
@Interceptor(priority = 8, name = "测试用拦截器")
public class RouterInterceptor implements IInterceptor {
@Override
public void process(Postcard postcard, InterceptorCallback callback) {
if(postcard.getPath().contains(ARouterPath.GirlsListAty)){
Log.d("danxx", "拦截到向ActivityGirls跳转");
//自定义处理
}else {
Log.d("danxx", "非拦截跳转执行path: "+postcard.getPath());
}
callback.onContinue(postcard); // 处理完成,交还控制权
// callback.onInterrupt(new RuntimeException("我觉得有点异常")); // 觉得有问题,中断路由流程
// 以上两种至少需要调用其中一种,否则不会继续路由
}
@Override
public void init(Context context) {
// 拦截器的初始化,会在sdk初始化的时候调用该方法,仅会调用一次
Log.d("danxx", "RouterInterceptor init");
}
}
| Dawish/GoogleArchitectureDemo | app_universal/src/main/java/google/architecture/universal/RouterInterceptor.java | 474 | // 拦截器的初始化,会在sdk初始化的时候调用该方法,仅会调用一次 | line_comment | zh-cn | package google.architecture.universal;
import android.content.Context;
import android.util.Log;
import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Interceptor;
import com.alibaba.android.arouter.facade.callback.InterceptorCallback;
import com.alibaba.android.arouter.facade.template.IInterceptor;
import google.architecture.common.base.ARouterPath;
/**
* Created by danxx on 2017/11/27.
*
* 比较经典的应用就是在跳转过程中处理登陆事件,这样就不需要在目标页重复做登陆检查
* 拦截器会在跳转之前执行,多个拦截器会按优先级顺序依次执行
*
* priority就是优先级 可以设置多个级别的拦截器都活一次执行
* 创建一个实现IInterceptor接口的类就是一个拦截器,不用做额外的配置了
*/
@Interceptor(priority = 8, name = "测试用拦截器")
public class RouterInterceptor implements IInterceptor {
@Override
public void process(Postcard postcard, InterceptorCallback callback) {
if(postcard.getPath().contains(ARouterPath.GirlsListAty)){
Log.d("danxx", "拦截到向ActivityGirls跳转");
//自定义处理
}else {
Log.d("danxx", "非拦截跳转执行path: "+postcard.getPath());
}
callback.onContinue(postcard); // 处理完成,交还控制权
// callback.onInterrupt(new RuntimeException("我觉得有点异常")); // 觉得有问题,中断路由流程
// 以上两种至少需要调用其中一种,否则不会继续路由
}
@Override
public void init(Context context) {
// 拦截 <SUF>
Log.d("danxx", "RouterInterceptor init");
}
}
| false | 405 | 23 | 474 | 21 | 448 | 18 | 474 | 21 | 672 | 37 | false | false | false | false | false | true |
44559_6 | package com.danxx.mdplayer.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
/**
*
* 类描述:网络链接类型判断
*/
public class NetUtils {
/**
* 判断当前网络类型-1为未知网络0为没有网络连接1网络断开或关闭2为以太网3为WiFi4为2G5为3G6为4G
*/
public static int getNetworkType(Context context) {
ConnectivityManager connectMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo();
if (networkInfo == null) {
/** 没有任何网络 */
return 0;
}
if (!networkInfo.isConnected()) {
/** 网络断开或关闭 */
return 1;
}
if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
/** 以太网网络 */
return 2;
} else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
/** wifi网络,当激活时,默认情况下,所有的数据流量将使用此连接 */
return 3;
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
/** 移动数据连接,不能与连接共存,如果wifi打开,则自动关闭 */
switch (networkInfo.getSubtype()) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
/** 2G网络 */
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
/** 3G网络 */
case TelephonyManager.NETWORK_TYPE_LTE:
/** 4G网络 */
return 4;
}
}
/** 未知网络 */
return -1;
}
}
| Dawish/MDPlayer | app/src/main/java/com/danxx/mdplayer/utils/NetUtils.java | 646 | /** 移动数据连接,不能与连接共存,如果wifi打开,则自动关闭 */ | block_comment | zh-cn | package com.danxx.mdplayer.utils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
/**
*
* 类描述:网络链接类型判断
*/
public class NetUtils {
/**
* 判断当前网络类型-1为未知网络0为没有网络连接1网络断开或关闭2为以太网3为WiFi4为2G5为3G6为4G
*/
public static int getNetworkType(Context context) {
ConnectivityManager connectMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectMgr.getActiveNetworkInfo();
if (networkInfo == null) {
/** 没有任何网络 */
return 0;
}
if (!networkInfo.isConnected()) {
/** 网络断开或关闭 */
return 1;
}
if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET) {
/** 以太网网络 */
return 2;
} else if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
/** wifi网络,当激活时,默认情况下,所有的数据流量将使用此连接 */
return 3;
} else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
/** 移动数 <SUF>*/
switch (networkInfo.getSubtype()) {
case TelephonyManager.NETWORK_TYPE_GPRS:
case TelephonyManager.NETWORK_TYPE_EDGE:
case TelephonyManager.NETWORK_TYPE_CDMA:
case TelephonyManager.NETWORK_TYPE_1xRTT:
case TelephonyManager.NETWORK_TYPE_IDEN:
/** 2G网络 */
case TelephonyManager.NETWORK_TYPE_UMTS:
case TelephonyManager.NETWORK_TYPE_EVDO_0:
case TelephonyManager.NETWORK_TYPE_EVDO_A:
case TelephonyManager.NETWORK_TYPE_HSDPA:
case TelephonyManager.NETWORK_TYPE_HSUPA:
case TelephonyManager.NETWORK_TYPE_HSPA:
case TelephonyManager.NETWORK_TYPE_EVDO_B:
case TelephonyManager.NETWORK_TYPE_EHRPD:
case TelephonyManager.NETWORK_TYPE_HSPAP:
/** 3G网络 */
case TelephonyManager.NETWORK_TYPE_LTE:
/** 4G网络 */
return 4;
}
}
/** 未知网络 */
return -1;
}
}
| false | 545 | 20 | 646 | 20 | 625 | 19 | 646 | 20 | 873 | 32 | false | false | false | false | false | true |
25646_1 | import java.util.HashSet;
/**
* 最长没有重复数字的子串
* 滑动窗口法
*/
public class Pro_003 {
public int lengthOfLongestSubstring(String s) {
int start = 0;
int end = 0;
int res = 0;
HashSet<Character> set = new HashSet<>();
while (start < s.length() && end < s.length()) {
if (set.contains(s.charAt(end))) {
// 窗口前边后移
set.remove(s.charAt(start++));
} else {
// 加入,并且后移
set.add(s.charAt(end++));
res = Math.max(res, end - start);
}
}
return res;
}
}
| DawnChau/leetcode | src/Pro_003.java | 185 | // 窗口前边后移 | line_comment | zh-cn | import java.util.HashSet;
/**
* 最长没有重复数字的子串
* 滑动窗口法
*/
public class Pro_003 {
public int lengthOfLongestSubstring(String s) {
int start = 0;
int end = 0;
int res = 0;
HashSet<Character> set = new HashSet<>();
while (start < s.length() && end < s.length()) {
if (set.contains(s.charAt(end))) {
// 窗口 <SUF>
set.remove(s.charAt(start++));
} else {
// 加入,并且后移
set.add(s.charAt(end++));
res = Math.max(res, end - start);
}
}
return res;
}
}
| false | 162 | 9 | 185 | 7 | 196 | 7 | 185 | 7 | 223 | 10 | false | false | false | false | false | true |
17958_1 | package Top200;
class NumSquares {
public int numSquares(int n) {
int[] dp = new int[n + 1];
for (int i = 0; i < n + 1; i++) {
dp[i] = Integer.MAX_VALUE;
}
// base case
dp[0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; i-j*j >= 0; j++) { // 这边等于号要注意,需要加上去,比如组成 4 的这个平方数个数只有 1 个。
dp[i] = Math.min(dp[i], dp[i - j*j] + 1);
}
}
return dp[n];
}
public static void main(String[] args) {
NumSquares ns = new NumSquares();
System.out.println(ns.numSquares(4));
System.out.println(ns.numSquares(5));
System.out.println(ns.numSquares(6));
System.out.println(ns.numSquares(7));
System.out.println(ns.numSquares(12));
}
} | DawnGuoDev/Algorithm | Top200/279-NumSquares.java | 292 | // 这边等于号要注意,需要加上去,比如组成 4 的这个平方数个数只有 1 个。 | line_comment | zh-cn | package Top200;
class NumSquares {
public int numSquares(int n) {
int[] dp = new int[n + 1];
for (int i = 0; i < n + 1; i++) {
dp[i] = Integer.MAX_VALUE;
}
// base case
dp[0] = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; i-j*j >= 0; j++) { // 这边 <SUF>
dp[i] = Math.min(dp[i], dp[i - j*j] + 1);
}
}
return dp[n];
}
public static void main(String[] args) {
NumSquares ns = new NumSquares();
System.out.println(ns.numSquares(4));
System.out.println(ns.numSquares(5));
System.out.println(ns.numSquares(6));
System.out.println(ns.numSquares(7));
System.out.println(ns.numSquares(12));
}
} | false | 253 | 28 | 292 | 30 | 299 | 25 | 292 | 30 | 343 | 39 | false | false | false | false | false | true |
38569_25 | package blcs.lwb.lwbtool.utils.camera;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import blcs.lwb.lwbtool.utils.MyUtils;
import blcs.lwb.lwbtool.utils.RxTool.RxVibrateTool;
/**
* @author vondear
* @date 2016/1/24
* RxTools的常用工具类
* <p>
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
* <p>
* 致终于来到这里的勇敢的人:
* 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。
* 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己,
* 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。
*/
public class RxTool {
@SuppressLint("StaticFieldLeak")
private static Context context;
private static long lastClickTime;
/**
* 初始化工具类
*
* @param context 上下文
*/
public static void init(Context context) {
RxTool.context = context.getApplicationContext();
RxCrashTool.init(context);
}
/**
* 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context
* <p>
* 获取ApplicationContext
*
* @return ApplicationContext
*/
public static Context getContext() {
if (context != null) {
return context;
}
throw new NullPointerException("请先调用init()方法");
}
//==============================================================================================延时任务封装 end
//----------------------------------------------------------------------------------------------延时任务封装 start
public static void delayToDo(long delayTime, final OnSimpleListener onSimpleListener) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//execute the task
onSimpleListener.doSomething();
}
}, delayTime);
}
/**
* 倒计时
*
* @param textView 控件
* @param waitTime 倒计时总时长
* @param interval 倒计时的间隔时间
* @param hint 倒计时完毕时显示的文字
*/
public static void countDown(final TextView textView, long waitTime, long interval, final String hint) {
textView.setEnabled(false);
android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) {
@SuppressLint("DefaultLocale")
@Override
public void onTick(long millisUntilFinished) {
textView.setText(String.format("剩下 %d S", millisUntilFinished / 1000));
}
@Override
public void onFinish() {
textView.setEnabled(true);
textView.setText(hint);
}
};
timer.start();
}
/**
* 手动计算出listView的高度,但是不再具有滚动效果
*
* @param listView
*/
public static void fixListViewHeight(ListView listView) {
// 如果没有设置数据适配器,则ListView没有子项,返回。
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
View listViewItem = listAdapter.getView(index, null, listView);
// 计算子项View 的宽高
listViewItem.measure(0, 0);
// 计算所有子项的高度
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()获取子项间分隔符的高度
// params.height设置ListView完全显示需要的高度
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
//---------------------------------------------MD5加密-------------------------------------------
/**
* 生成MD5加密32位字符串
*
* @param MStr :需要加密的字符串
* @return
*/
public static String Md5(String MStr) {
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(MStr.getBytes());
return bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
return String.valueOf(MStr.hashCode());
}
}
// MD5内部算法---------------不能修改!
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
//============================================MD5加密============================================
/**
* 根据资源名称获取资源 id
* <p>
* 不提倡使用这个方法获取资源,比其直接获取ID效率慢
* <p>
* 例如
* getResources().getIdentifier("ic_launcher", "drawable", getPackageName());
*
* @param context
* @param name
* @param defType
* @return
*/
public final static int getResIdByName(Context context, String name, String defType) {
return context.getResources().getIdentifier(name, defType, context.getPackageName());
}
public static boolean isFastClick(int millisecond) {
long curClickTime = System.currentTimeMillis();
long interval = (curClickTime - lastClickTime);
if (0 < interval && interval < millisecond) {
// 超过点击间隔后再将lastClickTime重置为当前点击时间
return true;
}
lastClickTime = curClickTime;
return false;
}
/**
* Edittext 首位小数点自动加零,最多两位小数
*
* @param editText
*/
public static void setEdTwoDecimal(EditText editText) {
setEdDecimal(editText, 2);
}
/**
* 只允许数字和汉字
* @param editText
*/
public static void setEdType(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void
beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void
onTextChanged(CharSequence s, int start, int before, int count) {
String editable = editText.getText().toString();
String str = stringFilter(editable);
if (!editable.equals(str)) {
editText.setText(str);
//设置新的光标所在位置
editText.setSelection(str.length());
}
}
@Override
public void
afterTextChanged(Editable s) {
}
});
}
/**
* // 只允许数字和汉字
*
* @param str
* @return
* @throws PatternSyntaxException
*/
public static String stringFilter(String str) throws PatternSyntaxException {
String regEx = "[^0-9\u4E00-\u9FA5]";//正则表达式
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
public static void setEdDecimal(EditText editText, int count) {
if (count < 0) {
count = 0;
}
count += 1;
editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
//设置字符过滤
final int finalCount = count;
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (".".contentEquals(source) && dest.toString().length() == 0) {
return "0.";
}
if (dest.toString().contains(".")) {
int index = dest.toString().indexOf(".");
int mlength = dest.toString().substring(index).length();
if (mlength == finalCount) {
return "";
}
}
if (dest.toString().equals("0") && source.equals("0")) {
return "";
}
return null;
}
}});
}
/**
* @param editText 输入框控件
* @param number 位数
* 1 -> 1
* 2 -> 01
* 3 -> 001
* 4 -> 0001
* @param isStartForZero 是否从000开始
* true -> 从 000 开始
* false -> 从 001 开始
*/
public static void setEditNumberAuto(final EditText editText, final int number, final boolean isStartForZero) {
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
setEditNumber(editText, number, isStartForZero);
}
}
});
}
/**
* @param editText 输入框控件
* @param number 位数
* 1 -> 1
* 2 -> 01
* 3 -> 001
* 4 -> 0001
* @param isStartForZero 是否从000开始
* true -> 从 000 开始
* false -> 从 001 开始
*/
public static void setEditNumber(EditText editText, int number, boolean isStartForZero) {
StringBuilder s = new StringBuilder(editText.getText().toString());
StringBuilder temp = new StringBuilder();
int i;
for (i = s.length(); i < number; ++i) {
s.insert(0, "0");
}
if (!isStartForZero) {
for (i = 0; i < number; ++i) {
temp.append("0");
}
if (s.toString().equals(temp.toString())) {
s = new StringBuilder(temp.substring(1) + "1");
}
}
editText.setText(s.toString());
}
/**
* 获取
* @return
*/
public static Handler getBackgroundHandler() {
HandlerThread thread = new HandlerThread("background");
thread.start();
return new Handler(thread.getLooper());
}
public static void initFastClickAndVibrate(Context mContext, OnDoListener onRxSimple) {
if (RxTool.isFastClick(FAST_CLICK_TIME)) {
MyUtils.toast(context,"请不要重复点击");
return;
} else {
RxVibrateTool.vibrateOnce(mContext, VIBRATE_TIME);
onRxSimple.doSomething();
}
}
public final static int FAST_CLICK_TIME = 100;
public final static int VIBRATE_TIME = 100;
}
| DayorNight/BLCS | LwbTool/src/main/java/blcs/lwb/lwbtool/utils/camera/RxTool.java | 2,868 | //设置字符过滤 | line_comment | zh-cn | package blcs.lwb.lwbtool.utils.camera;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import blcs.lwb.lwbtool.utils.MyUtils;
import blcs.lwb.lwbtool.utils.RxTool.RxVibrateTool;
/**
* @author vondear
* @date 2016/1/24
* RxTools的常用工具类
* <p>
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
* <p>
* 致终于来到这里的勇敢的人:
* 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。
* 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己,
* 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。
*/
public class RxTool {
@SuppressLint("StaticFieldLeak")
private static Context context;
private static long lastClickTime;
/**
* 初始化工具类
*
* @param context 上下文
*/
public static void init(Context context) {
RxTool.context = context.getApplicationContext();
RxCrashTool.init(context);
}
/**
* 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context
* <p>
* 获取ApplicationContext
*
* @return ApplicationContext
*/
public static Context getContext() {
if (context != null) {
return context;
}
throw new NullPointerException("请先调用init()方法");
}
//==============================================================================================延时任务封装 end
//----------------------------------------------------------------------------------------------延时任务封装 start
public static void delayToDo(long delayTime, final OnSimpleListener onSimpleListener) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//execute the task
onSimpleListener.doSomething();
}
}, delayTime);
}
/**
* 倒计时
*
* @param textView 控件
* @param waitTime 倒计时总时长
* @param interval 倒计时的间隔时间
* @param hint 倒计时完毕时显示的文字
*/
public static void countDown(final TextView textView, long waitTime, long interval, final String hint) {
textView.setEnabled(false);
android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) {
@SuppressLint("DefaultLocale")
@Override
public void onTick(long millisUntilFinished) {
textView.setText(String.format("剩下 %d S", millisUntilFinished / 1000));
}
@Override
public void onFinish() {
textView.setEnabled(true);
textView.setText(hint);
}
};
timer.start();
}
/**
* 手动计算出listView的高度,但是不再具有滚动效果
*
* @param listView
*/
public static void fixListViewHeight(ListView listView) {
// 如果没有设置数据适配器,则ListView没有子项,返回。
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
View listViewItem = listAdapter.getView(index, null, listView);
// 计算子项View 的宽高
listViewItem.measure(0, 0);
// 计算所有子项的高度
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()获取子项间分隔符的高度
// params.height设置ListView完全显示需要的高度
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
//---------------------------------------------MD5加密-------------------------------------------
/**
* 生成MD5加密32位字符串
*
* @param MStr :需要加密的字符串
* @return
*/
public static String Md5(String MStr) {
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(MStr.getBytes());
return bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
return String.valueOf(MStr.hashCode());
}
}
// MD5内部算法---------------不能修改!
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
//============================================MD5加密============================================
/**
* 根据资源名称获取资源 id
* <p>
* 不提倡使用这个方法获取资源,比其直接获取ID效率慢
* <p>
* 例如
* getResources().getIdentifier("ic_launcher", "drawable", getPackageName());
*
* @param context
* @param name
* @param defType
* @return
*/
public final static int getResIdByName(Context context, String name, String defType) {
return context.getResources().getIdentifier(name, defType, context.getPackageName());
}
public static boolean isFastClick(int millisecond) {
long curClickTime = System.currentTimeMillis();
long interval = (curClickTime - lastClickTime);
if (0 < interval && interval < millisecond) {
// 超过点击间隔后再将lastClickTime重置为当前点击时间
return true;
}
lastClickTime = curClickTime;
return false;
}
/**
* Edittext 首位小数点自动加零,最多两位小数
*
* @param editText
*/
public static void setEdTwoDecimal(EditText editText) {
setEdDecimal(editText, 2);
}
/**
* 只允许数字和汉字
* @param editText
*/
public static void setEdType(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void
beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void
onTextChanged(CharSequence s, int start, int before, int count) {
String editable = editText.getText().toString();
String str = stringFilter(editable);
if (!editable.equals(str)) {
editText.setText(str);
//设置新的光标所在位置
editText.setSelection(str.length());
}
}
@Override
public void
afterTextChanged(Editable s) {
}
});
}
/**
* // 只允许数字和汉字
*
* @param str
* @return
* @throws PatternSyntaxException
*/
public static String stringFilter(String str) throws PatternSyntaxException {
String regEx = "[^0-9\u4E00-\u9FA5]";//正则表达式
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
public static void setEdDecimal(EditText editText, int count) {
if (count < 0) {
count = 0;
}
count += 1;
editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
//设置 <SUF>
final int finalCount = count;
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (".".contentEquals(source) && dest.toString().length() == 0) {
return "0.";
}
if (dest.toString().contains(".")) {
int index = dest.toString().indexOf(".");
int mlength = dest.toString().substring(index).length();
if (mlength == finalCount) {
return "";
}
}
if (dest.toString().equals("0") && source.equals("0")) {
return "";
}
return null;
}
}});
}
/**
* @param editText 输入框控件
* @param number 位数
* 1 -> 1
* 2 -> 01
* 3 -> 001
* 4 -> 0001
* @param isStartForZero 是否从000开始
* true -> 从 000 开始
* false -> 从 001 开始
*/
public static void setEditNumberAuto(final EditText editText, final int number, final boolean isStartForZero) {
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
setEditNumber(editText, number, isStartForZero);
}
}
});
}
/**
* @param editText 输入框控件
* @param number 位数
* 1 -> 1
* 2 -> 01
* 3 -> 001
* 4 -> 0001
* @param isStartForZero 是否从000开始
* true -> 从 000 开始
* false -> 从 001 开始
*/
public static void setEditNumber(EditText editText, int number, boolean isStartForZero) {
StringBuilder s = new StringBuilder(editText.getText().toString());
StringBuilder temp = new StringBuilder();
int i;
for (i = s.length(); i < number; ++i) {
s.insert(0, "0");
}
if (!isStartForZero) {
for (i = 0; i < number; ++i) {
temp.append("0");
}
if (s.toString().equals(temp.toString())) {
s = new StringBuilder(temp.substring(1) + "1");
}
}
editText.setText(s.toString());
}
/**
* 获取
* @return
*/
public static Handler getBackgroundHandler() {
HandlerThread thread = new HandlerThread("background");
thread.start();
return new Handler(thread.getLooper());
}
public static void initFastClickAndVibrate(Context mContext, OnDoListener onRxSimple) {
if (RxTool.isFastClick(FAST_CLICK_TIME)) {
MyUtils.toast(context,"请不要重复点击");
return;
} else {
RxVibrateTool.vibrateOnce(mContext, VIBRATE_TIME);
onRxSimple.doSomething();
}
}
public final static int FAST_CLICK_TIME = 100;
public final static int VIBRATE_TIME = 100;
}
| false | 2,637 | 4 | 2,869 | 4 | 3,023 | 4 | 2,868 | 4 | 3,660 | 9 | false | false | false | false | false | true |
18997_2 | public class Solution {
// O(n * 2^n) time:
// n为nums的length, subsets问题就是对于其中任意一个元素, 选或者不选入subset中
// 那么, 解的个数就是2^n
//
// 我们知道, subsets I的running time:
// T(n) = n*2^(n-1) = θ(n*2^(n-1)) = O(n*2^n)
// 但是我们知道在ret.contains()去重时, 每个解无论重复与否, 都有O(n)的时间, 所以
// 此题中, θ(n*2^(n-1))不再成立
//
// contains()到底花了多少时间?
// 我们知道list的大小是从1逐渐增加到2^m的, m为去重后解的个数, 那么其实就是
// 1 + 2 + 3 + ... + 2^m ~ 2^(m-1) + 2^(2m-1)
// 这个时间是由重复元素个数决定的, 但我们可以用hashSet优化, 见subsetsWithDupOp
// 那么最后running time还是O(n * 2^n)
// O(n) space:
// one n is the recursion stack
// another n is the longest subset which is exactly the same as input
// nums when used this in creating new linked list to store
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> ret = new LinkedList<List<Integer>>();
ret.add(new LinkedList<Integer>());
if(nums == null || nums.length == 0) return ret;
Arrays.sort(nums);
List<Integer> path = new LinkedList<Integer>();
doDFS(0, nums, path, ret);
return ret;
}
private void doDFS(int start, int[] nums, List<Integer> path, List<List<Integer>> ret){
for(int i = start; i < nums.length; i++){
path.add(nums[i]);
if(!ret.contains(path)){
ret.add(new LinkedList<Integer>(path));
doDFS(i + 1, nums, path, ret);
}
path.remove(path.size() - 1);
}
}
// HashSet优化掉contains(), 实践证明可以省掉客观时间, 尤其是对于
// nums = {1, 1, ...... 1}这样的input
public static List<List<Integer>> subsetsWithDupOp(int[] nums) {
List<List<Integer>> ret = new LinkedList<List<Integer>>();
ret.add(new LinkedList<Integer>());
if(nums == null || nums.length == 0) return ret;
Arrays.sort(nums);
List<Integer> path = new LinkedList<Integer>();
HashSet<List<Integer>> set = new HashSet<List<Integer>>();
doDFS(0, nums, path, set);
for(List<Integer> entry: set){
ret.add(entry);
}
return ret;
}
private static void doDFS(int start, int[] nums, List<Integer> path, HashSet<List<Integer>> set){
for(int i = start; i < nums.length; i++){
path.add(nums[i]);
if(!set.contains(path)){
set.add(new LinkedList<Integer>(path));
doDFS(i + 1, nums, path, set);
}
path.remove(path.size() - 1);
}
}
} | Deadbeef-ECE/Interview | Leetcode/All/090_Subsets_II.java | 835 | // 那么, 解的个数就是2^n | line_comment | zh-cn | public class Solution {
// O(n * 2^n) time:
// n为nums的length, subsets问题就是对于其中任意一个元素, 选或者不选入subset中
// 那么 <SUF>
//
// 我们知道, subsets I的running time:
// T(n) = n*2^(n-1) = θ(n*2^(n-1)) = O(n*2^n)
// 但是我们知道在ret.contains()去重时, 每个解无论重复与否, 都有O(n)的时间, 所以
// 此题中, θ(n*2^(n-1))不再成立
//
// contains()到底花了多少时间?
// 我们知道list的大小是从1逐渐增加到2^m的, m为去重后解的个数, 那么其实就是
// 1 + 2 + 3 + ... + 2^m ~ 2^(m-1) + 2^(2m-1)
// 这个时间是由重复元素个数决定的, 但我们可以用hashSet优化, 见subsetsWithDupOp
// 那么最后running time还是O(n * 2^n)
// O(n) space:
// one n is the recursion stack
// another n is the longest subset which is exactly the same as input
// nums when used this in creating new linked list to store
public List<List<Integer>> subsetsWithDup(int[] nums) {
List<List<Integer>> ret = new LinkedList<List<Integer>>();
ret.add(new LinkedList<Integer>());
if(nums == null || nums.length == 0) return ret;
Arrays.sort(nums);
List<Integer> path = new LinkedList<Integer>();
doDFS(0, nums, path, ret);
return ret;
}
private void doDFS(int start, int[] nums, List<Integer> path, List<List<Integer>> ret){
for(int i = start; i < nums.length; i++){
path.add(nums[i]);
if(!ret.contains(path)){
ret.add(new LinkedList<Integer>(path));
doDFS(i + 1, nums, path, ret);
}
path.remove(path.size() - 1);
}
}
// HashSet优化掉contains(), 实践证明可以省掉客观时间, 尤其是对于
// nums = {1, 1, ...... 1}这样的input
public static List<List<Integer>> subsetsWithDupOp(int[] nums) {
List<List<Integer>> ret = new LinkedList<List<Integer>>();
ret.add(new LinkedList<Integer>());
if(nums == null || nums.length == 0) return ret;
Arrays.sort(nums);
List<Integer> path = new LinkedList<Integer>();
HashSet<List<Integer>> set = new HashSet<List<Integer>>();
doDFS(0, nums, path, set);
for(List<Integer> entry: set){
ret.add(entry);
}
return ret;
}
private static void doDFS(int start, int[] nums, List<Integer> path, HashSet<List<Integer>> set){
for(int i = start; i < nums.length; i++){
path.add(nums[i]);
if(!set.contains(path)){
set.add(new LinkedList<Integer>(path));
doDFS(i + 1, nums, path, set);
}
path.remove(path.size() - 1);
}
}
} | false | 749 | 13 | 835 | 12 | 865 | 11 | 835 | 12 | 1,031 | 15 | false | false | false | false | false | true |
56204_4 | /*编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。
如果是有效的 IPv4 地址,返回 "IPv4" ;
如果是有效的 IPv6 地址,返回 "IPv6" ;
如果不是上述类型的 IP 地址,返回 "Neither" 。
IPv4 地址由十进制数和点来表示,每个地址包含 4 个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1;
同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。
IPv6 地址由 8 组 16 进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如, 2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。
然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。
同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。
:示例 1:
输入:IP = "172.16.254.1"
输出:"IPv4"
解释:有效的 IPv4 地址,返回 "IPv4"
示例 2:
输入:IP = "2001:0db8:85a3:0:08A2E:0370:7334"
输出:"IPv6"
解释:有效的 IPv6 地址,返回 "IPv6"
示例 3:
输入:IP = "256.256.256.256"
输出:"Neither"
解释:既不是 IPv4 地址,又不是 IPv6 地址
示例 4:
输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:"
输出:"Neither"
示例 5:
输入:IP = "1e1.4.5.6"
输出:"Neither"
提示:
IP 仅由英文字母,数字,字符 '.' 和 ':' 组成。
*/
public class Q468 {
public static void main(String[] args) {
System.out.print(validIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));
}
public static String validIPAddress(String IP) {
String[] IP4Arr = IP.split("\\.",-1); // -1 表示尽可能用最多的次数
if(IP4Arr.length == 4){
return isIP4Arr(IP4Arr);
}
String[] IP6Arr = IP.split(":",-1);
if(IP6Arr.length == 8){
return isIP6Arr(IP6Arr);
}
return "Neither";
}
public static String isIP4Arr(String[] IP4Arr){
for(String ip : IP4Arr){
if(ip.length() > 3 || ip.length() <= 0){
return "Neither";
}
for(int i = 0 ;i < ip.length();++i){
if(!Character.isDigit(ip.charAt(i))){
return "Neither";
}
}
int num = Integer.parseInt(ip); // String 转int --> Integer.parseInt()
if(num > 255 || String.valueOf(num).length() != ip.length()){ // 判断是否是0开头, int转String --> String.valueOf()
return "Neither";
}
}
return "IPv4";
}
public static String isIP6Arr(String[] IP6Arr){
for(String ip : IP6Arr){
if(ip.length() > 4 || ip.length() <= 0){
return "Neither";
}
for(int i = 0 ;i < ip.length();++i){
char c = ip.charAt(i);
if(!Character.isDigit(c) && !( 'a' <= c && c <= 'f') && !('A' <= c && c <= 'F')){ // 判断字符串是否为数字
return "Neither";
}
}
}
return "IPv6";
}
}
| DeadpanZiao/LEETCODE_comp | src/Q468.java | 1,258 | // 判断字符串是否为数字 | line_comment | zh-cn | /*编写一个函数来验证输入的字符串是否是有效的 IPv4 或 IPv6 地址。
如果是有效的 IPv4 地址,返回 "IPv4" ;
如果是有效的 IPv6 地址,返回 "IPv6" ;
如果不是上述类型的 IP 地址,返回 "Neither" 。
IPv4 地址由十进制数和点来表示,每个地址包含 4 个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1;
同时,IPv4 地址内的数不会以 0 开头。比如,地址 172.16.254.01 是不合法的。
IPv6 地址由 8 组 16 进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如, 2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。而且,我们可以加入一些以 0 开头的数字,字母可以使用大写,也可以是小写。所以, 2001:db8:85a3:0:0:8A2E:0370:7334 也是一个有效的 IPv6 address地址 (即,忽略 0 开头,忽略大小写)。
然而,我们不能因为某个组的值为 0,而使用一个空的组,以至于出现 (::) 的情况。 比如, 2001:0db8:85a3::8A2E:0370:7334 是无效的 IPv6 地址。
同时,在 IPv6 地址中,多余的 0 也是不被允许的。比如, 02001:0db8:85a3:0000:0000:8a2e:0370:7334 是无效的。
:示例 1:
输入:IP = "172.16.254.1"
输出:"IPv4"
解释:有效的 IPv4 地址,返回 "IPv4"
示例 2:
输入:IP = "2001:0db8:85a3:0:08A2E:0370:7334"
输出:"IPv6"
解释:有效的 IPv6 地址,返回 "IPv6"
示例 3:
输入:IP = "256.256.256.256"
输出:"Neither"
解释:既不是 IPv4 地址,又不是 IPv6 地址
示例 4:
输入:IP = "2001:0db8:85a3:0:0:8A2E:0370:7334:"
输出:"Neither"
示例 5:
输入:IP = "1e1.4.5.6"
输出:"Neither"
提示:
IP 仅由英文字母,数字,字符 '.' 和 ':' 组成。
*/
public class Q468 {
public static void main(String[] args) {
System.out.print(validIPAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334"));
}
public static String validIPAddress(String IP) {
String[] IP4Arr = IP.split("\\.",-1); // -1 表示尽可能用最多的次数
if(IP4Arr.length == 4){
return isIP4Arr(IP4Arr);
}
String[] IP6Arr = IP.split(":",-1);
if(IP6Arr.length == 8){
return isIP6Arr(IP6Arr);
}
return "Neither";
}
public static String isIP4Arr(String[] IP4Arr){
for(String ip : IP4Arr){
if(ip.length() > 3 || ip.length() <= 0){
return "Neither";
}
for(int i = 0 ;i < ip.length();++i){
if(!Character.isDigit(ip.charAt(i))){
return "Neither";
}
}
int num = Integer.parseInt(ip); // String 转int --> Integer.parseInt()
if(num > 255 || String.valueOf(num).length() != ip.length()){ // 判断是否是0开头, int转String --> String.valueOf()
return "Neither";
}
}
return "IPv4";
}
public static String isIP6Arr(String[] IP6Arr){
for(String ip : IP6Arr){
if(ip.length() > 4 || ip.length() <= 0){
return "Neither";
}
for(int i = 0 ;i < ip.length();++i){
char c = ip.charAt(i);
if(!Character.isDigit(c) && !( 'a' <= c && c <= 'f') && !('A' <= c && c <= 'F')){ // 判断 <SUF>
return "Neither";
}
}
}
return "IPv6";
}
}
| false | 1,159 | 7 | 1,258 | 6 | 1,225 | 6 | 1,258 | 6 | 1,547 | 12 | false | false | false | false | false | true |
58790_0 | package game.Object;
import game.Engine.Base.BaseModel;
import game.Engine.Enum.ObjectStatus;
import game.Engine.GameObject;
import game.Game;
import game.Object.Model.Alpha;
import game.Object.Model.ScoreIndicator;
import java.util.concurrent.ThreadLocalRandom;
@game.Engine.Annotation.GameObject
public class Generator extends GameObject {
private long lastTime = 0;
private long interval = 1000; // 发射字母的时间间隔
private int maxAlphaCount = 8;
private int currentAlphaCount = 0;
@Override
public void update() {
if (status != ObjectStatus.ANIMATION)
return;
// 判断是否到达发射时间
if (System.currentTimeMillis() - lastTime < interval)
return;
// 判断是否达到最大限制
if (getAnimationAlphaCount() >= maxAlphaCount)
return;
ScoreIndicator scoreIndicator = ((ScoreIndicator) Game.getInstance().getModelManager().get("ScoreIndicator"));
interval -= scoreIndicator.getScore() / 10;
String rndAlpha = getRandomAlpha();
if (Game.getInstance().getModelManager().contains(rndAlpha)) {
BaseModel alpha = Game.getInstance().getModelManager().get(rndAlpha);
if (alpha.getStatus() != ObjectStatus.ANIMATION)
alpha.start();
} else {
Game.getInstance().getModelManager().register(new Alpha(rndAlpha), rndAlpha);
}
lastTime = System.currentTimeMillis();
}
@Override
public void start() {
status = ObjectStatus.ANIMATION;
}
@Override
public void stop() {
status = ObjectStatus.STOP;
}
/**
* 获取随机字母
*
* @return
*/
private String getRandomAlpha() {
int rnd = ThreadLocalRandom.current().nextInt(65, 90);
return String.valueOf((char) rnd);
}
/**
* 获取当前正在屏幕上运动的字母数量
*
* @return 数量
*/
private int getAnimationAlphaCount() {
int result = 0;
for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) {
if (model instanceof Alpha) {
if (model.getStatus() == ObjectStatus.ANIMATION)
result++;
}
}
return result;
}
/**
* 重置字母生成器
*/
public void reset() {
lastTime = 0;
interval = 1000;
currentAlphaCount = 0;
for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) {
if (model instanceof Alpha)
((Alpha) model).stop(false);
}
}
}
| Deali-Axy/CrazyAlpha | src/main/java/game/Object/Generator.java | 615 | // 发射字母的时间间隔 | line_comment | zh-cn | package game.Object;
import game.Engine.Base.BaseModel;
import game.Engine.Enum.ObjectStatus;
import game.Engine.GameObject;
import game.Game;
import game.Object.Model.Alpha;
import game.Object.Model.ScoreIndicator;
import java.util.concurrent.ThreadLocalRandom;
@game.Engine.Annotation.GameObject
public class Generator extends GameObject {
private long lastTime = 0;
private long interval = 1000; // 发射 <SUF>
private int maxAlphaCount = 8;
private int currentAlphaCount = 0;
@Override
public void update() {
if (status != ObjectStatus.ANIMATION)
return;
// 判断是否到达发射时间
if (System.currentTimeMillis() - lastTime < interval)
return;
// 判断是否达到最大限制
if (getAnimationAlphaCount() >= maxAlphaCount)
return;
ScoreIndicator scoreIndicator = ((ScoreIndicator) Game.getInstance().getModelManager().get("ScoreIndicator"));
interval -= scoreIndicator.getScore() / 10;
String rndAlpha = getRandomAlpha();
if (Game.getInstance().getModelManager().contains(rndAlpha)) {
BaseModel alpha = Game.getInstance().getModelManager().get(rndAlpha);
if (alpha.getStatus() != ObjectStatus.ANIMATION)
alpha.start();
} else {
Game.getInstance().getModelManager().register(new Alpha(rndAlpha), rndAlpha);
}
lastTime = System.currentTimeMillis();
}
@Override
public void start() {
status = ObjectStatus.ANIMATION;
}
@Override
public void stop() {
status = ObjectStatus.STOP;
}
/**
* 获取随机字母
*
* @return
*/
private String getRandomAlpha() {
int rnd = ThreadLocalRandom.current().nextInt(65, 90);
return String.valueOf((char) rnd);
}
/**
* 获取当前正在屏幕上运动的字母数量
*
* @return 数量
*/
private int getAnimationAlphaCount() {
int result = 0;
for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) {
if (model instanceof Alpha) {
if (model.getStatus() == ObjectStatus.ANIMATION)
result++;
}
}
return result;
}
/**
* 重置字母生成器
*/
public void reset() {
lastTime = 0;
interval = 1000;
currentAlphaCount = 0;
for (BaseModel model : Game.getInstance().getModelManager().getAllModels()) {
if (model instanceof Alpha)
((Alpha) model).stop(false);
}
}
}
| false | 570 | 6 | 615 | 8 | 669 | 6 | 615 | 8 | 773 | 15 | false | false | false | false | false | true |
19954_0 | package cn.deali.minimalpoem.task;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import cn.deali.minimalpoem.MainApp;
import cn.deali.minimalpoem.R;
import cn.deali.minimalpoem.utils.http.HttpRequestUtil;
import cn.deali.minimalpoem.utils.http.tool.HttpRequestData;
import cn.deali.minimalpoem.utils.http.tool.HttpResponseData;
// 检查更新任务
public class CheckUpdateTask extends AsyncTask<Void, Integer, HttpResponseData> {
private static final String TAG = "CheckUpdateTask";
private Context mContext;
private boolean toast = false;
/**
* @param context Activity对象
* @param toast 是否显示 toast 提示最新版本
*/
public CheckUpdateTask(Context context, boolean toast) {
this.mContext = context;
this.toast = toast;
}
@Override
protected HttpResponseData doInBackground(Void... voids) {
HttpRequestData request = new HttpRequestData(MainApp.getInstance().config.getHost() + "/qapp/get");
JSONObject json = new JSONObject();
try {
json.put("id", MainApp.getInstance().config.getAppId());
} catch (JSONException ex) {
Log.e(TAG, ex.getMessage());
this.cancel(true);
}
request.params = new StringBuffer(json.toString());
return HttpRequestUtil.postData(request);
}
@Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(mContext, "检查更新时发生错误!", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(HttpResponseData data) {
super.onPostExecute(data);
if (data.success) {
try {
JSONObject json = new JSONObject(data.content);
if (json.getString("status").equals("ok")) {
JSONObject app = json.getJSONObject("app");
if (app.getInt("version") > MainApp.getInstance().config.getVersionCode()) {
showUpdateAlert(app);
} else {
if (toast)
Toast.makeText(mContext, "你已经使用最新版本啦~", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException ex) {
Log.e(TAG, ex.getMessage());
if (toast)
Toast.makeText(mContext, "哦豁,完蛋,解析服务器数据失败~", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
if (toast)
Toast.makeText(mContext, "糟糕,在检查更新的时候遇到奇奇怪怪的异常了~", Toast.LENGTH_SHORT).show();
}
}
}
private void showUpdateAlert(JSONObject app) throws JSONException {
final String download_link = app.getString("download_link");
final String detail_link = app.getString("detail_link");
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("发现新版本咯~");
builder.setMessage(String.format(
"版本:%s\n更新说明:\n%s\n",
app.getString("version_str"), app.getString("update_description")));
builder.setPositiveButton("下载", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse(download_link);
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(uri);
mContext.startActivity(intent);
}
});
builder.setNeutralButton("了解详情", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse(detail_link);
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(uri);
mContext.startActivity(intent);
}
});
AlertDialog dialog = builder.create();
// 适配夜间模式和白天模式
if (MainApp.getInstance().getNightMode())
dialog.setOnShowListener(dialogInterface -> {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.white));
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.white));
});
else
dialog.setOnShowListener(dialogInterface -> {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.black));
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.black));
});
dialog.show();
}
} | Deali-Axy/MinimalPoem | app/src/main/java/cn/deali/minimalpoem/task/CheckUpdateTask.java | 1,177 | // 检查更新任务 | line_comment | zh-cn | package cn.deali.minimalpoem.task;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import cn.deali.minimalpoem.MainApp;
import cn.deali.minimalpoem.R;
import cn.deali.minimalpoem.utils.http.HttpRequestUtil;
import cn.deali.minimalpoem.utils.http.tool.HttpRequestData;
import cn.deali.minimalpoem.utils.http.tool.HttpResponseData;
// 检查 <SUF>
public class CheckUpdateTask extends AsyncTask<Void, Integer, HttpResponseData> {
private static final String TAG = "CheckUpdateTask";
private Context mContext;
private boolean toast = false;
/**
* @param context Activity对象
* @param toast 是否显示 toast 提示最新版本
*/
public CheckUpdateTask(Context context, boolean toast) {
this.mContext = context;
this.toast = toast;
}
@Override
protected HttpResponseData doInBackground(Void... voids) {
HttpRequestData request = new HttpRequestData(MainApp.getInstance().config.getHost() + "/qapp/get");
JSONObject json = new JSONObject();
try {
json.put("id", MainApp.getInstance().config.getAppId());
} catch (JSONException ex) {
Log.e(TAG, ex.getMessage());
this.cancel(true);
}
request.params = new StringBuffer(json.toString());
return HttpRequestUtil.postData(request);
}
@Override
protected void onCancelled() {
super.onCancelled();
Toast.makeText(mContext, "检查更新时发生错误!", Toast.LENGTH_SHORT).show();
}
@Override
protected void onPostExecute(HttpResponseData data) {
super.onPostExecute(data);
if (data.success) {
try {
JSONObject json = new JSONObject(data.content);
if (json.getString("status").equals("ok")) {
JSONObject app = json.getJSONObject("app");
if (app.getInt("version") > MainApp.getInstance().config.getVersionCode()) {
showUpdateAlert(app);
} else {
if (toast)
Toast.makeText(mContext, "你已经使用最新版本啦~", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException ex) {
Log.e(TAG, ex.getMessage());
if (toast)
Toast.makeText(mContext, "哦豁,完蛋,解析服务器数据失败~", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Log.e(TAG, ex.getMessage());
if (toast)
Toast.makeText(mContext, "糟糕,在检查更新的时候遇到奇奇怪怪的异常了~", Toast.LENGTH_SHORT).show();
}
}
}
private void showUpdateAlert(JSONObject app) throws JSONException {
final String download_link = app.getString("download_link");
final String detail_link = app.getString("detail_link");
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("发现新版本咯~");
builder.setMessage(String.format(
"版本:%s\n更新说明:\n%s\n",
app.getString("version_str"), app.getString("update_description")));
builder.setPositiveButton("下载", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse(download_link);
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(uri);
mContext.startActivity(intent);
}
});
builder.setNeutralButton("了解详情", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Uri uri = Uri.parse(detail_link);
Intent intent = new Intent();
intent.setAction("android.intent.action.VIEW");
intent.setData(uri);
mContext.startActivity(intent);
}
});
AlertDialog dialog = builder.create();
// 适配夜间模式和白天模式
if (MainApp.getInstance().getNightMode())
dialog.setOnShowListener(dialogInterface -> {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.white));
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.white));
});
else
dialog.setOnShowListener(dialogInterface -> {
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(mContext, R.color.black));
dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(ContextCompat.getColor(mContext, R.color.black));
});
dialog.show();
}
} | false | 956 | 7 | 1,177 | 5 | 1,225 | 4 | 1,177 | 5 | 1,475 | 10 | false | false | false | false | false | true |
66588_1 | package com.hanyi.thread.common.component;
import com.hanyi.thread.domain.ScheduledTask;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* cron任务注册器
*
* @author wcwei@iflytek.com
* @since 2021-08-03 10:29
*/
@Component
@RequiredArgsConstructor
public class CronTaskRegistrar {
/**
* 计划任务
*/
private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
/**
* 任务调度器
*/
private final TaskScheduler taskScheduler;
/**
* 添加cron任务
*
* @param task 任务
* @param cronExpression cron表达式
*/
public void addCronTask(Runnable task, String cronExpression) {
this.addCronTask(new CronTask(task, cronExpression));
}
/**
* 添加cron任务
*
* @param cronTask cron任务
*/
public void addCronTask(CronTask cronTask) {
if (cronTask != null) {
Runnable task = cronTask.getRunnable();
this.removeCronTask(task);
this.scheduledTasks.computeIfAbsent(task, k -> this.scheduledTasks.put(k, this.scheduleCronTask(cronTask)));
}
}
/**
* 删除cron任务
*
* @param task 任务
*/
public void removeCronTask(Runnable task) {
ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
if (scheduledTask != null) {
scheduledTask.cancel();
}
}
/**
* 安排cron任务
*
* @param cronTask cron任务
* @return {@link ScheduledTask}
*/
public ScheduledTask scheduleCronTask(CronTask cronTask) {
ScheduledTask scheduledTask = new ScheduledTask();
scheduledTask.setFuture(this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger()));
return scheduledTask;
}
/**
* 摧毁
*/
@PreDestroy
public void destroy() {
this.scheduledTasks.values().forEach(ScheduledTask::cancel);
this.scheduledTasks.clear();
}
}
| Dearker/middleground | hanyi-dynamic-threadpool/src/main/java/com/hanyi/thread/common/component/CronTaskRegistrar.java | 564 | /**
* 计划任务
*/ | block_comment | zh-cn | package com.hanyi.thread.common.component;
import com.hanyi.thread.domain.ScheduledTask;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* cron任务注册器
*
* @author wcwei@iflytek.com
* @since 2021-08-03 10:29
*/
@Component
@RequiredArgsConstructor
public class CronTaskRegistrar {
/**
* 计划任 <SUF>*/
private final Map<Runnable, ScheduledTask> scheduledTasks = new ConcurrentHashMap<>(16);
/**
* 任务调度器
*/
private final TaskScheduler taskScheduler;
/**
* 添加cron任务
*
* @param task 任务
* @param cronExpression cron表达式
*/
public void addCronTask(Runnable task, String cronExpression) {
this.addCronTask(new CronTask(task, cronExpression));
}
/**
* 添加cron任务
*
* @param cronTask cron任务
*/
public void addCronTask(CronTask cronTask) {
if (cronTask != null) {
Runnable task = cronTask.getRunnable();
this.removeCronTask(task);
this.scheduledTasks.computeIfAbsent(task, k -> this.scheduledTasks.put(k, this.scheduleCronTask(cronTask)));
}
}
/**
* 删除cron任务
*
* @param task 任务
*/
public void removeCronTask(Runnable task) {
ScheduledTask scheduledTask = this.scheduledTasks.remove(task);
if (scheduledTask != null) {
scheduledTask.cancel();
}
}
/**
* 安排cron任务
*
* @param cronTask cron任务
* @return {@link ScheduledTask}
*/
public ScheduledTask scheduleCronTask(CronTask cronTask) {
ScheduledTask scheduledTask = new ScheduledTask();
scheduledTask.setFuture(this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger()));
return scheduledTask;
}
/**
* 摧毁
*/
@PreDestroy
public void destroy() {
this.scheduledTasks.values().forEach(ScheduledTask::cancel);
this.scheduledTasks.clear();
}
}
| false | 517 | 10 | 564 | 8 | 608 | 9 | 564 | 8 | 720 | 14 | false | false | false | false | false | true |
24957_1 | package com.mooctest;
import io.appium.java_client.AndroidKeyCode;
import io.appium.java_client.AppiumDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class Main {
/**
* 所有和AppiumDriver相关的操作都必须写在该函数中
*
* @param driver
*/
public void test(AppiumDriver driver) {
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); //设置尝试定位控件的最长时间为8s,也就是最多尝试8s
/*
* 余下的测试逻辑请按照题目要求进行编写
*/
waitForActivity(driver, "MainActivity");
driver.findElementById("com.sankuai.meituan:id/city_button").click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.findElementsByXPath("//android.widget.TextView[@text='南京']").get(1).click();
driver.findElementByXPath("//android.view.View[@content-desc='附近']").click();
driver.findElementByXPath("//android.view.View[@content-desc='发现']").click();
driver.findElementByXPath("//android.view.View[@content-desc='订单']").click();
driver.findElementByXPath("//android.view.View[@content-desc='我的']").click();
driver.findElementByXPath("//android.view.View[@content-desc='首页']").click();
driver.findElementByXPath("//android.view.View[@content-desc='美食']").click();
driver.findElementByXPath("//android.widget.TextView[@text='优惠团购']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='附近好券']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='预约订座']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='外卖']").click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='新店特惠']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='自助餐']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='火锅']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='江浙菜']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementById("com.sankuai.meituan:id/food_list_map_menu_img").click();
driver.findElementById("com.sankuai.meituan:id/food_search_header_search").click();
driver.findElementByXPath("//android.widget.TextView[@text='新街口地区']").click();
driver.findElementById("com.sankuai.meituan:id/food_map_location_button").click();
driver.findElementById("com.sankuai.meituan:id/food_search_header_back").click();
driver.findElementById("com.sankuai.meituan:id/tv_search_text").click();
driver.findElementById("com.sankuai.meituan:id/search_edit").sendKeys("小龙虾");
driver.findElementById("com.sankuai.meituan:id/search").click();
driver.findElementById("com.sankuai.meituan:id/category").click();
driver.findElementByXPath("//android.widget.TextView[@text='美食']").click();
driver.findElementById("com.sankuai.meituan:id/category").click();
driver.swipe(800, 600, 800, 200, 500);
driver.swipe(800, 600, 800, 200, 500);
driver.swipe(800, 600, 800, 200, 500);
driver.swipe(800, 600, 800, 200, 500);
driver.swipe(800, 600, 800, 200, 500);
driver.findElementByXPath("//android.widget.TextView[@text='海鲜']").click();
driver.findElementById("com.sankuai.meituan:id/area").click();
driver.findElementByXPath("//android.widget.TextView[@text='鼓楼区']").click();
driver.findElementByXPath("//android.widget.TextView[@text='新街口/金轮/五台山体育中心']").click();
driver.findElementById("com.sankuai.meituan:id/sort").click();
driver.findElementByXPath("//android.widget.TextView[@text='好评优先']").click();
driver.findElementById("com.sankuai.meituan:id/senior_filter").click();
driver.findElementByXPath("//android.widget.TextView[@text='5~10人餐']").click();
driver.findElementById("com.sankuai.meituan:id/bottom_confirm").click();
driver.findElementsById("com.sankuai.meituan:id/image").get(0).click();
driver.findElementById("com.sankuai.meituan:id/favor").click();
driver.findElementById("com.sankuai.meituan:id/share").click();
driver.findElementById("com.sankuai.meituan:id/share_cancel").click();
driver.findElementById("com.sankuai.meituan:id/share").click();
driver.findElementByXPath("//android.widget.TextView[@text='微信好友']"); //.click();
// driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='朋友圈']"); //.click();
// driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='复制']").click();
driver.findElementById("com.sankuai.meituan:id/share").click();
driver.findElementByXPath("//android.widget.TextView[@text='更多']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementById("com.sankuai.meituan:id/food_poi_top_image").click();
driver.findElementByXPath("//android.widget.ImageButton[@content-desc='转到上一层级']").click();
driver.findElementById("com.sankuai.meituan:id/food_poi_address_container").click();
driver.findElementById("com.sankuai.meituan:id/food_header_back").click();
driver.findElementById("com.sankuai.meituan:id/food_poi_taxi_img").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementById("com.sankuai.meituan:id/food_poi_telephone_img").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='优惠信息']").click();
driver.findElementByXPath("//android.widget.TextView[@text='用户评论']").click();
driver.findElementByXPath("//android.widget.TextView[@text='商家信息']").click();
driver.quit();
}
private void waitForActivity(AppiumDriver driver, String activity) {
activity = "." + activity;
while (!driver.currentActivity().contains(activity)) {
System.out.println("- Waiting for " + activity);
Thread.yield();
}
System.out.println(">> Begin " + activity);
}
/**
* AppiumDriver的初始化逻辑必须写在该函数中
*
* @return
*/
public AppiumDriver initAppiumTest() {
AppiumDriver driver = null;
File classpathRoot = new File(System.getProperty("user.dir"));
File appDir = new File(classpathRoot, "apk");
File app = new File(appDir, "Meituan.apk");
//设置自动化相关参数
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("automationName", "UiAutomator2");
capabilities.setCapability("browserName", "");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("deviceName", "Android Emulator");
//设置apk路径
capabilities.setCapability("app", app.getAbsolutePath());
capabilities.setCapability("appPackage", "com.sankuai.meituan");
capabilities.setCapability("appActivity", "com.meituan.android.pt.homepage.activity.Welcome");
//设置使用unicode键盘,支持输入中文和特殊字符
capabilities.setCapability("unicodeKeyboard", "true");
//设置用例执行完成后重置键盘
capabilities.setCapability("resetKeyboard", "true");
capabilities.setCapability("noSign", "true");
//初始化
try {
driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return driver;
}
public void start() {
test(initAppiumTest());
}
public static void main(String[] args) {
Main main = new Main();
main.start();
}
} | DeepAQ/SoftwareTesting | Appium/Meituan/src/com/mooctest/Main.java | 2,349 | //设置尝试定位控件的最长时间为8s,也就是最多尝试8s | line_comment | zh-cn | package com.mooctest;
import io.appium.java_client.AndroidKeyCode;
import io.appium.java_client.AppiumDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
public class Main {
/**
* 所有和AppiumDriver相关的操作都必须写在该函数中
*
* @param driver
*/
public void test(AppiumDriver driver) {
driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); //设置 <SUF>
/*
* 余下的测试逻辑请按照题目要求进行编写
*/
waitForActivity(driver, "MainActivity");
driver.findElementById("com.sankuai.meituan:id/city_button").click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.findElementsByXPath("//android.widget.TextView[@text='南京']").get(1).click();
driver.findElementByXPath("//android.view.View[@content-desc='附近']").click();
driver.findElementByXPath("//android.view.View[@content-desc='发现']").click();
driver.findElementByXPath("//android.view.View[@content-desc='订单']").click();
driver.findElementByXPath("//android.view.View[@content-desc='我的']").click();
driver.findElementByXPath("//android.view.View[@content-desc='首页']").click();
driver.findElementByXPath("//android.view.View[@content-desc='美食']").click();
driver.findElementByXPath("//android.widget.TextView[@text='优惠团购']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='附近好券']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='预约订座']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='外卖']").click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='新店特惠']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='自助餐']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='火锅']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='江浙菜']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementById("com.sankuai.meituan:id/food_list_map_menu_img").click();
driver.findElementById("com.sankuai.meituan:id/food_search_header_search").click();
driver.findElementByXPath("//android.widget.TextView[@text='新街口地区']").click();
driver.findElementById("com.sankuai.meituan:id/food_map_location_button").click();
driver.findElementById("com.sankuai.meituan:id/food_search_header_back").click();
driver.findElementById("com.sankuai.meituan:id/tv_search_text").click();
driver.findElementById("com.sankuai.meituan:id/search_edit").sendKeys("小龙虾");
driver.findElementById("com.sankuai.meituan:id/search").click();
driver.findElementById("com.sankuai.meituan:id/category").click();
driver.findElementByXPath("//android.widget.TextView[@text='美食']").click();
driver.findElementById("com.sankuai.meituan:id/category").click();
driver.swipe(800, 600, 800, 200, 500);
driver.swipe(800, 600, 800, 200, 500);
driver.swipe(800, 600, 800, 200, 500);
driver.swipe(800, 600, 800, 200, 500);
driver.swipe(800, 600, 800, 200, 500);
driver.findElementByXPath("//android.widget.TextView[@text='海鲜']").click();
driver.findElementById("com.sankuai.meituan:id/area").click();
driver.findElementByXPath("//android.widget.TextView[@text='鼓楼区']").click();
driver.findElementByXPath("//android.widget.TextView[@text='新街口/金轮/五台山体育中心']").click();
driver.findElementById("com.sankuai.meituan:id/sort").click();
driver.findElementByXPath("//android.widget.TextView[@text='好评优先']").click();
driver.findElementById("com.sankuai.meituan:id/senior_filter").click();
driver.findElementByXPath("//android.widget.TextView[@text='5~10人餐']").click();
driver.findElementById("com.sankuai.meituan:id/bottom_confirm").click();
driver.findElementsById("com.sankuai.meituan:id/image").get(0).click();
driver.findElementById("com.sankuai.meituan:id/favor").click();
driver.findElementById("com.sankuai.meituan:id/share").click();
driver.findElementById("com.sankuai.meituan:id/share_cancel").click();
driver.findElementById("com.sankuai.meituan:id/share").click();
driver.findElementByXPath("//android.widget.TextView[@text='微信好友']"); //.click();
// driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='朋友圈']"); //.click();
// driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='复制']").click();
driver.findElementById("com.sankuai.meituan:id/share").click();
driver.findElementByXPath("//android.widget.TextView[@text='更多']").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementById("com.sankuai.meituan:id/food_poi_top_image").click();
driver.findElementByXPath("//android.widget.ImageButton[@content-desc='转到上一层级']").click();
driver.findElementById("com.sankuai.meituan:id/food_poi_address_container").click();
driver.findElementById("com.sankuai.meituan:id/food_header_back").click();
driver.findElementById("com.sankuai.meituan:id/food_poi_taxi_img").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementById("com.sankuai.meituan:id/food_poi_telephone_img").click();
driver.sendKeyEvent(AndroidKeyCode.BACK);
driver.findElementByXPath("//android.widget.TextView[@text='优惠信息']").click();
driver.findElementByXPath("//android.widget.TextView[@text='用户评论']").click();
driver.findElementByXPath("//android.widget.TextView[@text='商家信息']").click();
driver.quit();
}
private void waitForActivity(AppiumDriver driver, String activity) {
activity = "." + activity;
while (!driver.currentActivity().contains(activity)) {
System.out.println("- Waiting for " + activity);
Thread.yield();
}
System.out.println(">> Begin " + activity);
}
/**
* AppiumDriver的初始化逻辑必须写在该函数中
*
* @return
*/
public AppiumDriver initAppiumTest() {
AppiumDriver driver = null;
File classpathRoot = new File(System.getProperty("user.dir"));
File appDir = new File(classpathRoot, "apk");
File app = new File(appDir, "Meituan.apk");
//设置自动化相关参数
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("automationName", "UiAutomator2");
capabilities.setCapability("browserName", "");
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("deviceName", "Android Emulator");
//设置apk路径
capabilities.setCapability("app", app.getAbsolutePath());
capabilities.setCapability("appPackage", "com.sankuai.meituan");
capabilities.setCapability("appActivity", "com.meituan.android.pt.homepage.activity.Welcome");
//设置使用unicode键盘,支持输入中文和特殊字符
capabilities.setCapability("unicodeKeyboard", "true");
//设置用例执行完成后重置键盘
capabilities.setCapability("resetKeyboard", "true");
capabilities.setCapability("noSign", "true");
//初始化
try {
driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return driver;
}
public void start() {
test(initAppiumTest());
}
public static void main(String[] args) {
Main main = new Main();
main.start();
}
} | false | 1,932 | 18 | 2,349 | 19 | 2,403 | 16 | 2,349 | 19 | 2,901 | 31 | false | false | false | false | false | true |
34717_5 | package info.hb.ccn.main;
import info.hb.cnn.core.CNN;
import info.hb.cnn.core.CNN.LayerBuilder;
import info.hb.cnn.core.Layer;
import info.hb.cnn.core.Layer.Size;
import info.hb.cnn.data.DataSet;
import info.hb.cnn.utils.ConcurentRunner;
public class CNNMnist {
private static final String MODEL_NAME = "mnist/model/model.cnn";
private static final String TRAIN_DATA = "mnist/train.format";
private static final String TEST_DATA = "mnist/test.format";
private static final String TEST_PREDICT = "mnist/test.predict";
public static void main(String[] args) {
System.err.println("训练阶段:");
runTrain();
System.err.println("测试阶段:");
runTest();
ConcurentRunner.stop();
}
public static void runTrain() {
// 构建网络层次结构
LayerBuilder builder = new LayerBuilder();
builder.addLayer(Layer.buildInputLayer(new Size(28, 28))); // 输入层输出map大小为28×28
builder.addLayer(Layer.buildConvLayer(6, new Size(5, 5))); // 卷积层输出map大小为24×24,24=28+1-5
builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样层输出map大小为12×12,12=24/2
builder.addLayer(Layer.buildConvLayer(12, new Size(5, 5))); // 卷积层输出map大小为8×8,8=12+1-5
builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样层输出map大小为4×4,4=8/2
builder.addLayer(Layer.buildOutputLayer(10));
CNN cnn = new CNN(builder, 10);
// 加载训练数据
DataSet dataset = DataSet.load(TRAIN_DATA, ",", 784);
// 开始训练模型
cnn.train(dataset, 5);
// 保存训练好的模型
cnn.saveModel(MODEL_NAME);
dataset.clear();
}
public static void runTest() {
// 加载训练好的模型
CNN cnn = CNN.loadModel(MODEL_NAME);
// 加载测试数据
DataSet testSet = DataSet.load(TEST_DATA, ",", -1);
// 预测结果
cnn.predict(testSet, TEST_PREDICT);
testSet.clear();
}
}
| DeepCompute/cnn | src/main/java/info/hb/ccn/main/CNNMnist.java | 664 | // 采样层输出map大小为4×4,4=8/2 | line_comment | zh-cn | package info.hb.ccn.main;
import info.hb.cnn.core.CNN;
import info.hb.cnn.core.CNN.LayerBuilder;
import info.hb.cnn.core.Layer;
import info.hb.cnn.core.Layer.Size;
import info.hb.cnn.data.DataSet;
import info.hb.cnn.utils.ConcurentRunner;
public class CNNMnist {
private static final String MODEL_NAME = "mnist/model/model.cnn";
private static final String TRAIN_DATA = "mnist/train.format";
private static final String TEST_DATA = "mnist/test.format";
private static final String TEST_PREDICT = "mnist/test.predict";
public static void main(String[] args) {
System.err.println("训练阶段:");
runTrain();
System.err.println("测试阶段:");
runTest();
ConcurentRunner.stop();
}
public static void runTrain() {
// 构建网络层次结构
LayerBuilder builder = new LayerBuilder();
builder.addLayer(Layer.buildInputLayer(new Size(28, 28))); // 输入层输出map大小为28×28
builder.addLayer(Layer.buildConvLayer(6, new Size(5, 5))); // 卷积层输出map大小为24×24,24=28+1-5
builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样层输出map大小为12×12,12=24/2
builder.addLayer(Layer.buildConvLayer(12, new Size(5, 5))); // 卷积层输出map大小为8×8,8=12+1-5
builder.addLayer(Layer.buildSampLayer(new Size(2, 2))); // 采样 <SUF>
builder.addLayer(Layer.buildOutputLayer(10));
CNN cnn = new CNN(builder, 10);
// 加载训练数据
DataSet dataset = DataSet.load(TRAIN_DATA, ",", 784);
// 开始训练模型
cnn.train(dataset, 5);
// 保存训练好的模型
cnn.saveModel(MODEL_NAME);
dataset.clear();
}
public static void runTest() {
// 加载训练好的模型
CNN cnn = CNN.loadModel(MODEL_NAME);
// 加载测试数据
DataSet testSet = DataSet.load(TEST_DATA, ",", -1);
// 预测结果
cnn.predict(testSet, TEST_PREDICT);
testSet.clear();
}
}
| false | 575 | 18 | 664 | 18 | 641 | 18 | 664 | 18 | 836 | 24 | false | false | false | false | false | true |
58221_15 | package bakacraft;
import bakacraft.WeaponSkills.Random;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.List;
public class CraftLimit extends BAKAPlugin implements Listener {
public final static String CRAFT = Random.Colorilize("&2制造");
public final static String USE = Random.Colorilize("&3使用");
public final static String BREAK = Random.Colorilize("&c破坏");
public CraftLimit(JavaPlugin instance) {
super(instance);
getInstance().getServer().getPluginManager().registerEvents(this, instance);
}
@Override
public void onDisable() {
super.onDisable();
}
//制造限制插件
//必须学习技能之后才有制造某件东西的权限
//限制下列工具:
//木、石、铁、金、钻石 稿、斧、剑
//铲和锄不限制
//工作台、熔炉、打火机、剪刀、箱子
//合成除了原始合成之外,还需要旧的一件工具合成
//正常合成铁镐之后,会有无法使用标志
//需要使用一个石稿进行解锁
//熔炉需要打火机解锁才能使用。(消耗1点打火机耐久)
//工作台、打火机、剪刀、箱子无需前置解锁即可使用()
//挖掘限制:
//木头可以手撸
//要挖石头必须木镐及以上
//要挖铁必须石镐及以上
//依次类推
//烧制相关矿石需要相关前置解锁
public boolean breakable(Material mat) {
switch (mat) {
case GOLD_ORE:
case IRON_ORE:
case DIAMOND_ORE:
return true;
default:
return false;
}
}
public boolean craftable(Material mat) {
switch (mat) {
case WOOD_AXE:
case GOLD_AXE:
case IRON_AXE:
case STONE_AXE:
case DIAMOND_AXE:
case WOOD_PICKAXE:
case GOLD_PICKAXE:
case IRON_PICKAXE:
case STONE_PICKAXE:
case DIAMOND_PICKAXE:
case GOLD_SWORD:
case STONE_SWORD:
case IRON_SWORD:
case WOOD_SWORD:
case DIAMOND_SWORD:
case WORKBENCH:
case FURNACE:
case SHEARS:
case CHEST:
return true;
default:
return false;
}
}
public boolean usable(Material mat) {
switch (mat) {
case WOOD_AXE:
case GOLD_AXE:
case IRON_AXE:
case STONE_AXE:
case DIAMOND_AXE:
case WOOD_PICKAXE:
case GOLD_PICKAXE:
case IRON_PICKAXE:
case STONE_PICKAXE:
case DIAMOND_PICKAXE:
case GOLD_SWORD:
case STONE_SWORD:
case IRON_SWORD:
case WOOD_SWORD:
case DIAMOND_SWORD:
return true;
default:
return false;
}
}
@EventHandler
public void onPlayerCraft(CraftItemEvent e) {
if (!craftable(e.getRecipe().getResult().getType())) return;
if (e.getWhoClicked() instanceof Player) {
Player p = (Player) e.getWhoClicked();
if (p.isOp()) return;
if (!p.hasPermission(CRAFT + e.getCurrentItem().getItemMeta().getDisplayName())) {
e.setCancelled(true);
} else {
List<String> lores = new ArrayList<>();
lores.add(Random.Colorilize("&e需要权限:"));
lores.add(USE + e.getCurrentItem().getItemMeta().getDisplayName());
ItemMeta meta = e.getCurrentItem().getItemMeta();
meta.setLore(lores);
e.getCurrentItem().setItemMeta(meta);
}
}
}
@EventHandler
public void onPlayerFurnaceOpen(InventoryOpenEvent e) {
if (e.getPlayer().isOp()) return;
if (e.getInventory().getType() == InventoryType.FURNACE) {
if (!e.getPlayer().getItemInHand().getType().equals(Material.FLINT_AND_STEEL)) {
((Player) e.getPlayer()).sendRawMessage("你需要一个打火石来点燃熔炉");
e.setCancelled(true);
}
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent e) {
if (e.getPlayer().isOp()) return;
if (!usable(e.getPlayer().getItemInHand().getType())) return;
if (e.getPlayer().hasPermission(CRAFT + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) {
e.setCancelled(true);
}
}
@EventHandler
public void onPlayerBreak(BlockBreakEvent e) {
if (e.getPlayer().isOp()) return;
if (!breakable(e.getBlock().getType())) return;
if (e.getPlayer().hasPermission(BREAK + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) {
e.setCancelled(true);
}
}
@EventHandler
public void onPlayerSwitchHeld(PlayerItemHeldEvent e) {
if (e.getPlayer().isOp()) return;
ItemStack newItem = e.getPlayer().getInventory().getItem(e.getNewSlot());
if (newItem == null || !usable(newItem.getType())) return;
if (e.getPlayer().hasPermission(USE + newItem.getItemMeta().getDisplayName())) {
e.getPlayer().sendRawMessage("你需要解锁之后才能使用这件装备");
e.setCancelled(true);
}
}
}
| Deliay/BAKACraft | src/main/java/bakacraft/CraftLimit.java | 1,568 | //依次类推 | line_comment | zh-cn | package bakacraft;
import bakacraft.WeaponSkills.Random;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryType;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemHeldEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.List;
public class CraftLimit extends BAKAPlugin implements Listener {
public final static String CRAFT = Random.Colorilize("&2制造");
public final static String USE = Random.Colorilize("&3使用");
public final static String BREAK = Random.Colorilize("&c破坏");
public CraftLimit(JavaPlugin instance) {
super(instance);
getInstance().getServer().getPluginManager().registerEvents(this, instance);
}
@Override
public void onDisable() {
super.onDisable();
}
//制造限制插件
//必须学习技能之后才有制造某件东西的权限
//限制下列工具:
//木、石、铁、金、钻石 稿、斧、剑
//铲和锄不限制
//工作台、熔炉、打火机、剪刀、箱子
//合成除了原始合成之外,还需要旧的一件工具合成
//正常合成铁镐之后,会有无法使用标志
//需要使用一个石稿进行解锁
//熔炉需要打火机解锁才能使用。(消耗1点打火机耐久)
//工作台、打火机、剪刀、箱子无需前置解锁即可使用()
//挖掘限制:
//木头可以手撸
//要挖石头必须木镐及以上
//要挖铁必须石镐及以上
//依次 <SUF>
//烧制相关矿石需要相关前置解锁
public boolean breakable(Material mat) {
switch (mat) {
case GOLD_ORE:
case IRON_ORE:
case DIAMOND_ORE:
return true;
default:
return false;
}
}
public boolean craftable(Material mat) {
switch (mat) {
case WOOD_AXE:
case GOLD_AXE:
case IRON_AXE:
case STONE_AXE:
case DIAMOND_AXE:
case WOOD_PICKAXE:
case GOLD_PICKAXE:
case IRON_PICKAXE:
case STONE_PICKAXE:
case DIAMOND_PICKAXE:
case GOLD_SWORD:
case STONE_SWORD:
case IRON_SWORD:
case WOOD_SWORD:
case DIAMOND_SWORD:
case WORKBENCH:
case FURNACE:
case SHEARS:
case CHEST:
return true;
default:
return false;
}
}
public boolean usable(Material mat) {
switch (mat) {
case WOOD_AXE:
case GOLD_AXE:
case IRON_AXE:
case STONE_AXE:
case DIAMOND_AXE:
case WOOD_PICKAXE:
case GOLD_PICKAXE:
case IRON_PICKAXE:
case STONE_PICKAXE:
case DIAMOND_PICKAXE:
case GOLD_SWORD:
case STONE_SWORD:
case IRON_SWORD:
case WOOD_SWORD:
case DIAMOND_SWORD:
return true;
default:
return false;
}
}
@EventHandler
public void onPlayerCraft(CraftItemEvent e) {
if (!craftable(e.getRecipe().getResult().getType())) return;
if (e.getWhoClicked() instanceof Player) {
Player p = (Player) e.getWhoClicked();
if (p.isOp()) return;
if (!p.hasPermission(CRAFT + e.getCurrentItem().getItemMeta().getDisplayName())) {
e.setCancelled(true);
} else {
List<String> lores = new ArrayList<>();
lores.add(Random.Colorilize("&e需要权限:"));
lores.add(USE + e.getCurrentItem().getItemMeta().getDisplayName());
ItemMeta meta = e.getCurrentItem().getItemMeta();
meta.setLore(lores);
e.getCurrentItem().setItemMeta(meta);
}
}
}
@EventHandler
public void onPlayerFurnaceOpen(InventoryOpenEvent e) {
if (e.getPlayer().isOp()) return;
if (e.getInventory().getType() == InventoryType.FURNACE) {
if (!e.getPlayer().getItemInHand().getType().equals(Material.FLINT_AND_STEEL)) {
((Player) e.getPlayer()).sendRawMessage("你需要一个打火石来点燃熔炉");
e.setCancelled(true);
}
}
}
@EventHandler
public void onPlayerInteract(PlayerInteractEvent e) {
if (e.getPlayer().isOp()) return;
if (!usable(e.getPlayer().getItemInHand().getType())) return;
if (e.getPlayer().hasPermission(CRAFT + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) {
e.setCancelled(true);
}
}
@EventHandler
public void onPlayerBreak(BlockBreakEvent e) {
if (e.getPlayer().isOp()) return;
if (!breakable(e.getBlock().getType())) return;
if (e.getPlayer().hasPermission(BREAK + e.getPlayer().getItemInHand().getItemMeta().getDisplayName())) {
e.setCancelled(true);
}
}
@EventHandler
public void onPlayerSwitchHeld(PlayerItemHeldEvent e) {
if (e.getPlayer().isOp()) return;
ItemStack newItem = e.getPlayer().getInventory().getItem(e.getNewSlot());
if (newItem == null || !usable(newItem.getType())) return;
if (e.getPlayer().hasPermission(USE + newItem.getItemMeta().getDisplayName())) {
e.getPlayer().sendRawMessage("你需要解锁之后才能使用这件装备");
e.setCancelled(true);
}
}
}
| false | 1,324 | 4 | 1,568 | 5 | 1,559 | 5 | 1,568 | 5 | 2,013 | 9 | false | false | false | false | false | true |
55286_3 | package com.xd.demi.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
/**
* Created by demi on 17/4/24.
*/
public class MyFlowLayout extends LinearLayout {
private int verticalSpacing = 20;
private int horizontalSpacing = 20;
public MyFlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
int widthUsed = paddingLeft + paddingRight; //已经占用的宽度
int heightUsed = paddingTop + paddingBottom; //已经占用的高度
int childMaxHeightOfThisLine = 0; //孩子中最高的那位,其实都一样高
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
int childUsedWidth = 0; //某个孩子的宽度
int childUsedHeight = 0; //某个孩子的高度
measureChild(child, widthMeasureSpec, heightMeasureSpec);
childUsedWidth += child.getMeasuredWidth();
childUsedHeight += child.getMeasuredHeight();
LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams();
MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams;
childUsedWidth += marginLayoutParams.leftMargin + marginLayoutParams.rightMargin + horizontalSpacing;
childUsedHeight += marginLayoutParams.topMargin + marginLayoutParams.bottomMargin;
if (widthUsed + childUsedWidth < widthSpecSize) {
widthUsed += childUsedWidth;
if (childUsedHeight > childMaxHeightOfThisLine) {
childMaxHeightOfThisLine = childUsedHeight;
}
} else {
heightUsed += childMaxHeightOfThisLine + verticalSpacing;
widthUsed = paddingLeft + paddingRight + childUsedWidth;
childMaxHeightOfThisLine = childUsedHeight;
}
}
}
heightUsed += childMaxHeightOfThisLine;
setMeasuredDimension(widthSpecSize, heightUsed);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
int childStartLayoutX = paddingLeft;
int childStartLayoutY = paddingTop;
int widthUsed = paddingLeft + paddingRight;
int childMaxHeight = 0;
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
int childNeededWidth, childNeedHeight;
int left, top, right, bottom;
int childMeasuredWidth = child.getMeasuredWidth();
int childMeasuredHeight = child.getMeasuredHeight();
LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams();
MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams;
int childLeftMargin = marginLayoutParams.leftMargin;
int childTopMargin = marginLayoutParams.topMargin;
int childRightMargin = marginLayoutParams.rightMargin;
int childBottomMargin = marginLayoutParams.bottomMargin;
childNeededWidth = childLeftMargin + childRightMargin + childMeasuredWidth + horizontalSpacing;
childNeedHeight = childTopMargin + childBottomMargin + childMeasuredHeight;
if (widthUsed + childNeededWidth <= r - l) {
if (childNeedHeight > childMaxHeight) {
childMaxHeight = childNeedHeight;
}
left = childStartLayoutX + childLeftMargin;
top = childStartLayoutY + childTopMargin;
right = left + childMeasuredWidth;
bottom = top + childMeasuredHeight;
widthUsed += childNeededWidth;
childStartLayoutX += childNeededWidth;
} else {
childStartLayoutY += childMaxHeight + verticalSpacing;
childStartLayoutX = paddingLeft;
widthUsed = paddingLeft + paddingRight;
left = childStartLayoutX + childLeftMargin;
top = childStartLayoutY + childTopMargin;
right = left + childMeasuredWidth;
bottom = top + childMeasuredHeight;
widthUsed += childNeededWidth;
childStartLayoutX += childNeededWidth;
childMaxHeight = childNeedHeight;
}
child.layout(left, top, right, bottom);
}
}
}
}
| Demidong/ClockView | app/src/main/java/com/xd/demi/view/MyFlowLayout.java | 1,135 | //孩子中最高的那位,其实都一样高 | line_comment | zh-cn | package com.xd.demi.view;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.LinearLayout;
/**
* Created by demi on 17/4/24.
*/
public class MyFlowLayout extends LinearLayout {
private int verticalSpacing = 20;
private int horizontalSpacing = 20;
public MyFlowLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
int widthUsed = paddingLeft + paddingRight; //已经占用的宽度
int heightUsed = paddingTop + paddingBottom; //已经占用的高度
int childMaxHeightOfThisLine = 0; //孩子 <SUF>
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
int childUsedWidth = 0; //某个孩子的宽度
int childUsedHeight = 0; //某个孩子的高度
measureChild(child, widthMeasureSpec, heightMeasureSpec);
childUsedWidth += child.getMeasuredWidth();
childUsedHeight += child.getMeasuredHeight();
LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams();
MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams;
childUsedWidth += marginLayoutParams.leftMargin + marginLayoutParams.rightMargin + horizontalSpacing;
childUsedHeight += marginLayoutParams.topMargin + marginLayoutParams.bottomMargin;
if (widthUsed + childUsedWidth < widthSpecSize) {
widthUsed += childUsedWidth;
if (childUsedHeight > childMaxHeightOfThisLine) {
childMaxHeightOfThisLine = childUsedHeight;
}
} else {
heightUsed += childMaxHeightOfThisLine + verticalSpacing;
widthUsed = paddingLeft + paddingRight + childUsedWidth;
childMaxHeightOfThisLine = childUsedHeight;
}
}
}
heightUsed += childMaxHeightOfThisLine;
setMeasuredDimension(widthSpecSize, heightUsed);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int paddingBottom = getPaddingBottom();
int childStartLayoutX = paddingLeft;
int childStartLayoutY = paddingTop;
int widthUsed = paddingLeft + paddingRight;
int childMaxHeight = 0;
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
int childNeededWidth, childNeedHeight;
int left, top, right, bottom;
int childMeasuredWidth = child.getMeasuredWidth();
int childMeasuredHeight = child.getMeasuredHeight();
LayoutParams childLayoutParams = (LayoutParams) child.getLayoutParams();
MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childLayoutParams;
int childLeftMargin = marginLayoutParams.leftMargin;
int childTopMargin = marginLayoutParams.topMargin;
int childRightMargin = marginLayoutParams.rightMargin;
int childBottomMargin = marginLayoutParams.bottomMargin;
childNeededWidth = childLeftMargin + childRightMargin + childMeasuredWidth + horizontalSpacing;
childNeedHeight = childTopMargin + childBottomMargin + childMeasuredHeight;
if (widthUsed + childNeededWidth <= r - l) {
if (childNeedHeight > childMaxHeight) {
childMaxHeight = childNeedHeight;
}
left = childStartLayoutX + childLeftMargin;
top = childStartLayoutY + childTopMargin;
right = left + childMeasuredWidth;
bottom = top + childMeasuredHeight;
widthUsed += childNeededWidth;
childStartLayoutX += childNeededWidth;
} else {
childStartLayoutY += childMaxHeight + verticalSpacing;
childStartLayoutX = paddingLeft;
widthUsed = paddingLeft + paddingRight;
left = childStartLayoutX + childLeftMargin;
top = childStartLayoutY + childTopMargin;
right = left + childMeasuredWidth;
bottom = top + childMeasuredHeight;
widthUsed += childNeededWidth;
childStartLayoutX += childNeededWidth;
childMaxHeight = childNeedHeight;
}
child.layout(left, top, right, bottom);
}
}
}
}
| false | 1,040 | 10 | 1,148 | 14 | 1,203 | 11 | 1,135 | 14 | 1,433 | 18 | false | false | false | false | false | true |
64372_3 | package com.dxj.util;
import lombok.extern.slf4j.Slf4j;
/**
* 原作者 zzxadi https://github.com/zzxadi/Snowflake-IdWorker
*
* @author Sinkiang
*/
@Slf4j
public class SnowFlakeUtil {
private final long id;
/**
* 机器标识位数
*/
private final long workerIdBits = 10L;
/**
* 0,并发控制
*/
private long sequence = 0L;
private long lastTimestamp = -1L;
private SnowFlakeUtil(long id) {
// 机器ID最大值: 1023
long maxWorkerId = ~(-1L << this.workerIdBits);
if (id > maxWorkerId || id < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
this.id = id;
}
public synchronized long nextId() {
long timestamp = timeGen();
// 毫秒内自增位
long sequenceBits = 12L;
if (this.lastTimestamp == timestamp) {
//如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始
// 4095,111111111111,12位
long sequenceMask = ~(-1L << sequenceBits);
this.sequence = this.sequence + 1 & sequenceMask;
if (this.sequence == 0) {
// 重新生成timestamp
timestamp = this.tilNextMillis(this.lastTimestamp);
}
} else {
this.sequence = 0;
}
if (timestamp < this.lastTimestamp) {
log.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp)));
return -1;
}
this.lastTimestamp = timestamp;
// 22
long timestampLeftShift = sequenceBits + this.workerIdBits;
// 时间起始标记点,作为基准,一般取系统的最近时间
long epoch = 1524291141010L;
// 12
return timestamp - epoch << timestampLeftShift | this.id << sequenceBits | this.sequence;
}
private static SnowFlakeUtil flowIdWorker = new SnowFlakeUtil(1);
public static SnowFlakeUtil getFlowIdInstance() {
return flowIdWorker;
}
/**
* 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 获得系统当前毫秒数
*/
private static long timeGen() {
return System.currentTimeMillis();
}
}
| DengSinkiang/sk-admin | sk-common/src/main/java/com/dxj/util/SnowFlakeUtil.java | 697 | // 机器ID最大值: 1023 | line_comment | zh-cn | package com.dxj.util;
import lombok.extern.slf4j.Slf4j;
/**
* 原作者 zzxadi https://github.com/zzxadi/Snowflake-IdWorker
*
* @author Sinkiang
*/
@Slf4j
public class SnowFlakeUtil {
private final long id;
/**
* 机器标识位数
*/
private final long workerIdBits = 10L;
/**
* 0,并发控制
*/
private long sequence = 0L;
private long lastTimestamp = -1L;
private SnowFlakeUtil(long id) {
// 机器 <SUF>
long maxWorkerId = ~(-1L << this.workerIdBits);
if (id > maxWorkerId || id < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
this.id = id;
}
public synchronized long nextId() {
long timestamp = timeGen();
// 毫秒内自增位
long sequenceBits = 12L;
if (this.lastTimestamp == timestamp) {
//如果上一个timestamp与新产生的相等,则sequence加一(0-4095循环); 对新的timestamp,sequence从0开始
// 4095,111111111111,12位
long sequenceMask = ~(-1L << sequenceBits);
this.sequence = this.sequence + 1 & sequenceMask;
if (this.sequence == 0) {
// 重新生成timestamp
timestamp = this.tilNextMillis(this.lastTimestamp);
}
} else {
this.sequence = 0;
}
if (timestamp < this.lastTimestamp) {
log.error(String.format("clock moved backwards.Refusing to generate id for %d milliseconds", (this.lastTimestamp - timestamp)));
return -1;
}
this.lastTimestamp = timestamp;
// 22
long timestampLeftShift = sequenceBits + this.workerIdBits;
// 时间起始标记点,作为基准,一般取系统的最近时间
long epoch = 1524291141010L;
// 12
return timestamp - epoch << timestampLeftShift | this.id << sequenceBits | this.sequence;
}
private static SnowFlakeUtil flowIdWorker = new SnowFlakeUtil(1);
public static SnowFlakeUtil getFlowIdInstance() {
return flowIdWorker;
}
/**
* 等待下一个毫秒的到来, 保证返回的毫秒数在参数lastTimestamp之后
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
/**
* 获得系统当前毫秒数
*/
private static long timeGen() {
return System.currentTimeMillis();
}
}
| false | 660 | 12 | 697 | 12 | 749 | 11 | 697 | 12 | 877 | 14 | false | false | false | false | false | true |
51482_14 | /*
* www.msxf.com Inc.
* Copyright (c) 2017 All Rights Reserved
*/
package com.falcon.suitagent.util;
// ,%%%%%%%%,
// ,%%/\%%%%/\%%
// ,%%%\c "" J/%%%
// %. %%%%/ o o \%%%
// `%%. %%%% _ |%%%
// `%% `%%%%(__Y__)%%'
// // ;%%%%`\-/%%%'
// (( / `%%%%%%%'
// \\ .' |
// \\ / \ | |
// \\/攻城狮保佑) | |
// \ /_ | |__
// (___________))))))) `\/'
/*
* 修订记录:
* long.qian@msxf.com 2017-08-04 14:08 创建
*/
/**
* @author long.qian@msxf.com
*/
public class HexUtil {
private static boolean isCnSymbol(char ch) {
if (0x3004 <= ch && ch <= 0x301C) return true;
if (0x3020 <= ch && ch <= 0x303F) return true;
return false;
}
private static boolean isEnSymbol(char ch){
if (ch == 0x40) return true;
if (ch == 0x2D || ch == 0x2F) return true;
if (0x23 <= ch && ch <= 0x26) return true;
if (0x28 <= ch && ch <= 0x2B) return true;
if (0x3C <= ch && ch <= 0x3E) return true;
if (0x5B <= ch && ch <= 0x60) return true;
if (0x7B <= ch && ch <= 0x7E) return true;
return false;
}
private static boolean isPunctuation(char ch){
if(isCjkPunc(ch)) return true;
if(isEnPunc(ch)) return true;
if(0x2018 <= ch && ch <= 0x201F) return true;
if(ch == 0xFF01 || ch == 0xFF02) return true;
if(ch == 0xFF07 || ch == 0xFF0C) return true;
if(ch == 0xFF1A || ch == 0xFF1B) return true;
if(ch == 0xFF1F || ch == 0xFF61) return true;
if(ch == 0xFF0E) return true;
if(ch == 0xFF65) return true;
return false;
}
private static boolean isEnPunc(char ch){
if (0x21 <= ch && ch <= 0x22) return true;
if (ch == 0x27 || ch == 0x2C) return true;
if (ch == 0x2E || ch == 0x3A) return true;
if (ch == 0x3B || ch == 0x3F) return true;
return false;
}
private static boolean isCjkPunc(char ch){
if (0x3001 <= ch && ch <= 0x3003) return true;
if (0x301D <= ch && ch <= 0x301F) return true;
return false;
}
private static boolean isSymbol(char ch)
{
if(isCnSymbol(ch)) return true;
if(isEnSymbol(ch))return true;
if(0x2010 <= ch && ch <= 0x2017) return true;
if(0x2020 <= ch && ch <= 0x2027) return true;
if(0x2B00 <= ch && ch <= 0x2BFF) return true;
if(0xFF03 <= ch && ch <= 0xFF06) return true;
if(0xFF08 <= ch && ch <= 0xFF0B) return true;
if(ch == 0xFF0D || ch == 0xFF0F) return true;
if(0xFF1C <= ch && ch <= 0xFF1E) return true;
if(ch == 0xFF20 || ch == 0xFF65) return true;
if(0xFF3B <= ch && ch <= 0xFF40) return true;
if(0xFF5B <= ch && ch <= 0xFF60) return true;
if(ch == 0xFF62 || ch == 0xFF63) return true;
if(ch == 0x0020 || ch == 0x3000) return true;
return false;
}
/**
* 过滤字符串,返回可见字符形式(数字、字母、符号等)
* @param str
* @return
*/
public static String filter(String str){
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") ||
isSymbol(c) ||
isPunctuation(c)){
sb.append(c);
}
}
return sb.toString();
}
/**
* 过滤字符串,将不可见字符串替换为指定的字符串
* @param str
* @param replace
* @return
*/
public static String filter(String str,String replace){
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") ||
isSymbol(c) ||
isPunctuation(c)){
sb.append(c);
}else {
sb.append(replace);
}
}
return sb.toString();
}
}
| DevopsJK/SuitAgent | src/main/java/com/falcon/suitagent/util/HexUtil.java | 1,432 | /*
* 修订记录:
* long.qian@msxf.com 2017-08-04 14:08 创建
*/ | block_comment | zh-cn | /*
* www.msxf.com Inc.
* Copyright (c) 2017 All Rights Reserved
*/
package com.falcon.suitagent.util;
// ,%%%%%%%%,
// ,%%/\%%%%/\%%
// ,%%%\c "" J/%%%
// %. %%%%/ o o \%%%
// `%%. %%%% _ |%%%
// `%% `%%%%(__Y__)%%'
// // ;%%%%`\-/%%%'
// (( / `%%%%%%%'
// \\ .' |
// \\ / \ | |
// \\/攻城狮保佑) | |
// \ /_ | |__
// (___________))))))) `\/'
/*
* 修订记 <SUF>*/
/**
* @author long.qian@msxf.com
*/
public class HexUtil {
private static boolean isCnSymbol(char ch) {
if (0x3004 <= ch && ch <= 0x301C) return true;
if (0x3020 <= ch && ch <= 0x303F) return true;
return false;
}
private static boolean isEnSymbol(char ch){
if (ch == 0x40) return true;
if (ch == 0x2D || ch == 0x2F) return true;
if (0x23 <= ch && ch <= 0x26) return true;
if (0x28 <= ch && ch <= 0x2B) return true;
if (0x3C <= ch && ch <= 0x3E) return true;
if (0x5B <= ch && ch <= 0x60) return true;
if (0x7B <= ch && ch <= 0x7E) return true;
return false;
}
private static boolean isPunctuation(char ch){
if(isCjkPunc(ch)) return true;
if(isEnPunc(ch)) return true;
if(0x2018 <= ch && ch <= 0x201F) return true;
if(ch == 0xFF01 || ch == 0xFF02) return true;
if(ch == 0xFF07 || ch == 0xFF0C) return true;
if(ch == 0xFF1A || ch == 0xFF1B) return true;
if(ch == 0xFF1F || ch == 0xFF61) return true;
if(ch == 0xFF0E) return true;
if(ch == 0xFF65) return true;
return false;
}
private static boolean isEnPunc(char ch){
if (0x21 <= ch && ch <= 0x22) return true;
if (ch == 0x27 || ch == 0x2C) return true;
if (ch == 0x2E || ch == 0x3A) return true;
if (ch == 0x3B || ch == 0x3F) return true;
return false;
}
private static boolean isCjkPunc(char ch){
if (0x3001 <= ch && ch <= 0x3003) return true;
if (0x301D <= ch && ch <= 0x301F) return true;
return false;
}
private static boolean isSymbol(char ch)
{
if(isCnSymbol(ch)) return true;
if(isEnSymbol(ch))return true;
if(0x2010 <= ch && ch <= 0x2017) return true;
if(0x2020 <= ch && ch <= 0x2027) return true;
if(0x2B00 <= ch && ch <= 0x2BFF) return true;
if(0xFF03 <= ch && ch <= 0xFF06) return true;
if(0xFF08 <= ch && ch <= 0xFF0B) return true;
if(ch == 0xFF0D || ch == 0xFF0F) return true;
if(0xFF1C <= ch && ch <= 0xFF1E) return true;
if(ch == 0xFF20 || ch == 0xFF65) return true;
if(0xFF3B <= ch && ch <= 0xFF40) return true;
if(0xFF5B <= ch && ch <= 0xFF60) return true;
if(ch == 0xFF62 || ch == 0xFF63) return true;
if(ch == 0x0020 || ch == 0x3000) return true;
return false;
}
/**
* 过滤字符串,返回可见字符形式(数字、字母、符号等)
* @param str
* @return
*/
public static String filter(String str){
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") ||
isSymbol(c) ||
isPunctuation(c)){
sb.append(c);
}
}
return sb.toString();
}
/**
* 过滤字符串,将不可见字符串替换为指定的字符串
* @param str
* @param replace
* @return
*/
public static String filter(String str,String replace){
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (String.valueOf(c).matches("([a-z]|[A-Z]|\\d|\\s|[\\u4e00-\\u9fa5])+") ||
isSymbol(c) ||
isPunctuation(c)){
sb.append(c);
}else {
sb.append(replace);
}
}
return sb.toString();
}
}
| false | 1,355 | 34 | 1,432 | 39 | 1,504 | 37 | 1,432 | 39 | 1,635 | 44 | false | false | false | false | false | true |
13819_1 |
/**
* @author liuhuanhuan
* @version 1.0
* @date 2022/2/21 22:33
* @describe Twitter推出的分布式唯一id算法
*/
public class UUIDUtil {
//因为二进制里第一个 bit 为如果是 1,那么都是负数,但是我们生成的 id 都是正数,所以第一个 bit 统一都是 0。
//机器ID 2进制5位 32位减掉1位 31个
private long workerId;
//机房ID 2进制5位 32位减掉1位 31个
private long datacenterId;
//代表一毫秒内生成的多个id的最新序号 12位 4096 -1 = 4095 个
private long sequence;
//设置一个时间初始值 2^41 - 1 差不多可以用69年
private long twepoch = 1585644268888L;
//5位的机器id
private long workerIdBits = 5L;
//5位的机房id;。‘
private long datacenterIdBits = 5L;
//每毫秒内产生的id数 2 的 12次方
private long sequenceBits = 12L;
// 这个是二进制运算,就是5 bit最多只能有31个数字,也就是说机器id最多只能是32以内
private long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 这个是一个意思,就是5 bit最多只能有31个数字,机房id最多只能是32以内
private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private long workerIdShift = sequenceBits;
private long datacenterIdShift = sequenceBits + workerIdBits;
private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
// -1L 二进制就是1111 1111 为什么?
// -1 左移12位就是 1111 1111 0000 0000 0000 0000
// 异或 相同为0 ,不同为1
// 1111 1111 0000 0000 0000 0000
// ^
// 1111 1111 1111 1111 1111 1111
// 0000 0000 1111 1111 1111 1111 换算成10进制就是4095
private long sequenceMask = -1L ^ (-1L << sequenceBits);
//记录产生时间毫秒数,判断是否是同1毫秒
private long lastTimestamp = -1L;
public long getWorkerId(){
return workerId;
}
public long getDatacenterId() {
return datacenterId;
}
public long getTimestamp() {
return System.currentTimeMillis();
}
public UUIDUtil() {
}
public UUIDUtil(long workerId, long datacenterId, long sequence) {
// 检查机房id和机器id是否超过31 不能小于0
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(
String.format("worker Id can't be greater than %d or less than 0",maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(
String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = sequence;
}
// 这个是核心方法,通过调用nextId()方法,
// 让当前这台机器上的snowflake算法程序生成一个全局唯一的id
public synchronized long nextId() {
// 这儿就是获取当前时间戳,单位是毫秒
long timestamp = timeGen();
// 判断是否小于上次时间戳,如果小于的话,就抛出异常
if (timestamp < lastTimestamp) {
System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
lastTimestamp - timestamp));
}
// 下面是说假设在同一个毫秒内,又发送了一个请求生成一个id
// 这个时候就得把seqence序号给递增1,最多就是4096
if (timestamp == lastTimestamp) {
// 这个意思是说一个毫秒内最多只能有4096个数字,无论你传递多少进来,
//这个位运算保证始终就是在4096这个范围内,避免你自己传递个sequence超过了4096这个范围
sequence = (sequence + 1) & sequenceMask;
//当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
// 这儿记录一下最近一次生成id的时间戳,单位是毫秒
lastTimestamp = timestamp;
// 这儿就是最核心的二进制位运算操作,生成一个64bit的id
// 先将当前时间戳左移,放到41 bit那儿;将机房id左移放到5 bit那儿;将机器id左移放到5 bit那儿;将序号放最后12 bit
// 最后拼接起来成一个64 bit的二进制数字,转换成10进制就是个long型
return ((timestamp - twepoch) << timestampLeftShift) |
(datacenterId << datacenterIdShift) |
(workerId << workerIdShift) | sequence;
}
/**
* 当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID
* @param lastTimestamp
* @return
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
//获取当前时间戳
private long timeGen(){
return System.currentTimeMillis();
}
/**
* main 测试类
* @param args
*/
public static void main(String[] args) {
// System.out.println(1&4596);
// System.out.println(2&4596);
// System.out.println(6&4596);
// System.out.println(6&4596);
// System.out.println(6&4596);
// System.out.println(6&4596);
UUIDUtil snowFlow = new UUIDUtil(1, 1, 1);
for (int i = 0; i < 22; i++) {
System.out.println(snowFlow.nextId());
// }
}
}
}
| Dexter-Huang/mycode | Algorithm/src/main/java/UUIDUtil.java | 1,738 | //因为二进制里第一个 bit 为如果是 1,那么都是负数,但是我们生成的 id 都是正数,所以第一个 bit 统一都是 0。 | line_comment | zh-cn |
/**
* @author liuhuanhuan
* @version 1.0
* @date 2022/2/21 22:33
* @describe Twitter推出的分布式唯一id算法
*/
public class UUIDUtil {
//因为 <SUF>
//机器ID 2进制5位 32位减掉1位 31个
private long workerId;
//机房ID 2进制5位 32位减掉1位 31个
private long datacenterId;
//代表一毫秒内生成的多个id的最新序号 12位 4096 -1 = 4095 个
private long sequence;
//设置一个时间初始值 2^41 - 1 差不多可以用69年
private long twepoch = 1585644268888L;
//5位的机器id
private long workerIdBits = 5L;
//5位的机房id;。‘
private long datacenterIdBits = 5L;
//每毫秒内产生的id数 2 的 12次方
private long sequenceBits = 12L;
// 这个是二进制运算,就是5 bit最多只能有31个数字,也就是说机器id最多只能是32以内
private long maxWorkerId = -1L ^ (-1L << workerIdBits);
// 这个是一个意思,就是5 bit最多只能有31个数字,机房id最多只能是32以内
private long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private long workerIdShift = sequenceBits;
private long datacenterIdShift = sequenceBits + workerIdBits;
private long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
// -1L 二进制就是1111 1111 为什么?
// -1 左移12位就是 1111 1111 0000 0000 0000 0000
// 异或 相同为0 ,不同为1
// 1111 1111 0000 0000 0000 0000
// ^
// 1111 1111 1111 1111 1111 1111
// 0000 0000 1111 1111 1111 1111 换算成10进制就是4095
private long sequenceMask = -1L ^ (-1L << sequenceBits);
//记录产生时间毫秒数,判断是否是同1毫秒
private long lastTimestamp = -1L;
public long getWorkerId(){
return workerId;
}
public long getDatacenterId() {
return datacenterId;
}
public long getTimestamp() {
return System.currentTimeMillis();
}
public UUIDUtil() {
}
public UUIDUtil(long workerId, long datacenterId, long sequence) {
// 检查机房id和机器id是否超过31 不能小于0
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(
String.format("worker Id can't be greater than %d or less than 0",maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(
String.format("datacenter Id can't be greater than %d or less than 0",maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = sequence;
}
// 这个是核心方法,通过调用nextId()方法,
// 让当前这台机器上的snowflake算法程序生成一个全局唯一的id
public synchronized long nextId() {
// 这儿就是获取当前时间戳,单位是毫秒
long timestamp = timeGen();
// 判断是否小于上次时间戳,如果小于的话,就抛出异常
if (timestamp < lastTimestamp) {
System.err.printf("clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
throw new RuntimeException(
String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
lastTimestamp - timestamp));
}
// 下面是说假设在同一个毫秒内,又发送了一个请求生成一个id
// 这个时候就得把seqence序号给递增1,最多就是4096
if (timestamp == lastTimestamp) {
// 这个意思是说一个毫秒内最多只能有4096个数字,无论你传递多少进来,
//这个位运算保证始终就是在4096这个范围内,避免你自己传递个sequence超过了4096这个范围
sequence = (sequence + 1) & sequenceMask;
//当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
// 这儿记录一下最近一次生成id的时间戳,单位是毫秒
lastTimestamp = timestamp;
// 这儿就是最核心的二进制位运算操作,生成一个64bit的id
// 先将当前时间戳左移,放到41 bit那儿;将机房id左移放到5 bit那儿;将机器id左移放到5 bit那儿;将序号放最后12 bit
// 最后拼接起来成一个64 bit的二进制数字,转换成10进制就是个long型
return ((timestamp - twepoch) << timestampLeftShift) |
(datacenterId << datacenterIdShift) |
(workerId << workerIdShift) | sequence;
}
/**
* 当某一毫秒的时间,产生的id数 超过4095,系统会进入等待,直到下一毫秒,系统继续产生ID
* @param lastTimestamp
* @return
*/
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
//获取当前时间戳
private long timeGen(){
return System.currentTimeMillis();
}
/**
* main 测试类
* @param args
*/
public static void main(String[] args) {
// System.out.println(1&4596);
// System.out.println(2&4596);
// System.out.println(6&4596);
// System.out.println(6&4596);
// System.out.println(6&4596);
// System.out.println(6&4596);
UUIDUtil snowFlow = new UUIDUtil(1, 1, 1);
for (int i = 0; i < 22; i++) {
System.out.println(snowFlow.nextId());
// }
}
}
}
| false | 1,704 | 40 | 1,738 | 37 | 1,770 | 35 | 1,738 | 37 | 2,252 | 58 | false | false | false | false | false | true |
34427_19 | package util;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.UUID;
import android.util.Log;
public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 1000; // 超时时间
private static final String CHARSET = "utf-8"; // 设置编码
/**
* Android上传文件到服务端
*
* @param file
* 需要上传的文件
* @param RequestURL
* 请求的rul
* @return 返回响应的内容
*/
public static String uploadFile(File file, String RequestURL) {
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY);
if (file != null) {
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(
conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
+ file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
// if(res==200)
// {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
// }
// else{
// Log.e(TAG, "request error");
// }
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
*
* @param url
* Service net address
* @param params
* text content
* @param files
* pictures
* @return String result of Service response
* @throws IOException
*/
public static String post(String url, Map<String, String> params,
Map<String, File> files) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(10 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(
conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 发送文件数据
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
+ file.getValue().getName() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
Log.i("http", LINEND);
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
InputStream in = conn.getInputStream();
StringBuilder sb2 = new StringBuilder();
if (res == 200) {
int ch;
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
return sb2.toString();
}
}
| DickyQie/android-picture-upload | src/util/UploadUtil.java | 1,933 | // 允许输出 | line_comment | zh-cn | package util;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.UUID;
import android.util.Log;
public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 1000; // 超时时间
private static final String CHARSET = "utf-8"; // 设置编码
/**
* Android上传文件到服务端
*
* @param file
* 需要上传的文件
* @param RequestURL
* 请求的rul
* @return 返回响应的内容
*/
public static String uploadFile(File file, String RequestURL) {
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
+ BOUNDARY);
if (file != null) {
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(
conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意: name里面的值为服务端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
+ file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
// if(res==200)
// {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
// }
// else{
// Log.e(TAG, "request error");
// }
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* 通过拼接的方式构造请求内容,实现参数传输以及文件传输
*
* @param url
* Service net address
* @param params
* text content
* @param files
* pictures
* @return String result of Service response
* @throws IOException
*/
public static String post(String url, Map<String, String> params,
Map<String, File> files) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(url);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(10 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许 <SUF>
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
+ ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\""
+ entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(
conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 发送文件数据
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"uploadfile\"; filename=\""
+ file.getValue().getName() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
Log.i("http", LINEND);
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
// 得到响应码
int res = conn.getResponseCode();
InputStream in = conn.getInputStream();
StringBuilder sb2 = new StringBuilder();
if (res == 200) {
int ch;
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
return sb2.toString();
}
}
| false | 1,667 | 5 | 1,933 | 4 | 1,929 | 4 | 1,933 | 4 | 2,609 | 10 | false | false | false | false | false | true |
28596_3 | package com.zhangqie.videosummary.widget;
import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.IOException;
/**
* Created by zhangqie on 2019/8/29
* Describe:
*/
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener {
private SurfaceHolder holder;
private MediaPlayer mediaPlayer;
public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}//快进
public void setprogress(int progress) {
int currentPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(currentPosition + progress);
Toast.makeText(getContext(), "快进" + progress, Toast.LENGTH_SHORT).show();
}
//暂停/播放方法
public void stopVideo() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
}
//播放视频方法
public void playVideo(String path) {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();//设置surfaceview不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前
mediaPlayer.setOnCompletionListener(this);
}
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(path);
mediaPlayer.setDisplay(holder);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
private void init() {
holder = this.getHolder();
//重写SurfaceHolder.Callback方法
holder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}//缓冲完成播放
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
}
| DickyQie/android-video | app/src/main/java/com/zhangqie/videosummary/widget/MySurfaceView.java | 537 | //设置surfaceview不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到用户面前 | line_comment | zh-cn | package com.zhangqie.videosummary.widget;
import android.content.Context;
import android.media.MediaPlayer;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.Toast;
import java.io.IOException;
/**
* Created by zhangqie on 2019/8/29
* Describe:
*/
public class MySurfaceView extends SurfaceView implements SurfaceHolder.Callback, MediaPlayer.OnCompletionListener {
private SurfaceHolder holder;
private MediaPlayer mediaPlayer;
public MySurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}//快进
public void setprogress(int progress) {
int currentPosition = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(currentPosition + progress);
Toast.makeText(getContext(), "快进" + progress, Toast.LENGTH_SHORT).show();
}
//暂停/播放方法
public void stopVideo() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
}
//播放视频方法
public void playVideo(String path) {
if (mediaPlayer == null) {
mediaPlayer = new MediaPlayer();//设置 <SUF>
mediaPlayer.setOnCompletionListener(this);
}
try {
mediaPlayer.reset();
mediaPlayer.setDataSource(path);
mediaPlayer.setDisplay(holder);
mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
private void init() {
holder = this.getHolder();
//重写SurfaceHolder.Callback方法
holder.addCallback(this);
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}//缓冲完成播放
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
}
| false | 454 | 22 | 537 | 29 | 553 | 22 | 537 | 29 | 692 | 61 | false | false | false | false | false | true |
30972_0 | package MeaT;
import JDBC.JDBCUtils;
import blockchain.Block;
import blockchain.Transaction;
import dataset.DataProcessing;
import functions.MeaTUtils;
import graph.Edge;
import graph.Node;
import merkletree.Leaf;
import merkletree.MerkleTree;
import javax.xml.crypto.dsig.TransformService;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
public class CreateMeaT {
public Random ran=new Random();
public ArrayList<Transaction> txs=new ArrayList<>();
public ArrayList<Block> blocks=new ArrayList<>();
public String[] types={"food","electronic","face","furniture"};
public ArrayList<Node> all_nodes=new ArrayList<>();
public void create_nodes(){
int i=0;
for (i=0;i<15;i++)
{
String id=String.valueOf(i);
String type=types[ran.nextInt(4)];
Node node=new Node(id,type);
all_nodes.add(node);
System.out.println(node.getNode_id());
}
}
public void create_txs_blocks(ArrayList<Node> nodes){
int block_id=1;
String[] types={"Electronic","Food","Furniture"};
for (int i=0;i<5;i++)
{
String blockid=String.valueOf(block_id);
Block b=new Block(blockid);
for(int j=0;j<20;j++)
{
String tx_id_string=String.valueOf(j);
String tx_id=tx_id_string;
String tx_time_cost=String.valueOf(ran.nextDouble()*150);
String tx_repu=String.valueOf(ran.nextDouble()*100);
int firstNumber = ran.nextInt(15); // 生成0到3之间的随机数
int secondNumber;
do {
secondNumber = ran.nextInt(15);
} while (secondNumber == firstNumber);
Node node1=nodes.get(firstNumber);
Node node2=nodes.get(secondNumber);
String tx_timestamp=String.valueOf(block_id);
int type=ran.nextInt(3);
Transaction tx=new Transaction(tx_id,tx_timestamp,tx_time_cost,tx_repu,node1,node2,types[type]);
tx.setBlock(b);
txs.add(tx);
System.out.println("TX:"+tx.getType());
b.getTxs().add(tx);
}
block_id+=1;
blocks.add(b);
System.out.println("Block:"+b.getId());
System.out.println("Amounts:"+b.getTxs().size());
}
}
public Block query_block(String id, ArrayList<Block> blocks)
{
for (Block block:blocks)
{
if (block.getId().equals(id))
{
return block;
}
}
return null;
}
public boolean exist_block(String id, ArrayList<Block> blocks)
{
for (Block block:blocks)
{
if (block.getId().equals(id))
{
return true;
}
}
return false;
}
public Node query_node(String id, ArrayList<Node> nodes)
{
for (Node node:nodes)
{
if (node.getNode_id().equals(id))
{
return node;
}
}
return null;
}
public static void main(String[] args) throws NoSuchAlgorithmException, SQLException {
String file="./Dataset/100000.csv";
HashMap<Node,ArrayList<Transaction>> node_txs=new HashMap<>();
JDBCUtils jdbcUtils=new JDBCUtils();
DataProcessing dp=new DataProcessing();
CreateMeaT cmt=new CreateMeaT();
//将交易、节点、区块写入数据库并暂存至内存
node_txs=dp.test_dataset_to_txs(file);
for(Node node:node_txs.keySet())
{
dp.insert_transaction_database(node_txs.get(node));
cmt.all_nodes.add(node);
cmt.txs.addAll(node_txs.get(node));
}
// //miniminitest的操作,一个区块,将所有交易加到这个区块中
// cmt.blocks.add(cmt.txs.get(0).getBlock());
// for (Transaction tx: cmt.txs){
// cmt.blocks.get(0).getTxs().add(tx);
// }
//交易、节点存完了,直接读就可以
//将数据库中的交易和节点读出来
ResultSet rs = dp.select_transaction();
ResultSet rs2=dp.select_node();
ResultSet rs3=dp.select_block();
while(rs2.next())
{
Node node=new Node(rs2.getString("node_id"));
cmt.all_nodes.add(node);
}
while(rs3.next())
{
Block block=new Block(rs3.getString("block_id"));
cmt.blocks.add(block);
}
System.out.println("All blocks: "+cmt.blocks.size());
System.out.println("All nodes: "+cmt.all_nodes.size());
Node start_node=null;
Node end_node = new Node(""); // 创建一个空的Node对象,用于重复使用
while (rs.next()) {
Transaction tx=null;
start_node = cmt.query_node(rs.getString("start_node"), cmt.all_nodes);
// 重复使用end_node对象,而不是在每次迭代中创建新对象
end_node.setNode_id(rs.getString("end_node"));
Block b=cmt.query_block(rs.getString("block"),cmt.blocks);
// 重复使用tx对象,而不是在每次迭代中创建新对象
if (tx == null) {
tx = new Transaction("", "", "", "", null, null, "");
}
// 更新tx对象的属性
tx.setId(rs.getString("id"));
tx.setTimestamp(rs.getString("timestamp"));
tx.setTime_cost(rs.getString("time_cost"));
tx.setReputation(rs.getString("reputation"));
tx.setStart_node(start_node);
tx.setEnd_node(end_node);
tx.setType(rs.getString("type"));
tx.setBlock(b);
cmt.txs.add(tx);
System.out.println("Pre tx: " + rs.getString("id"));
b.getTxs().add(tx);
}
System.out.println("Total blocks: "+cmt.blocks.size());
//Merkle树的
int leafcount=0;
for (Block block: cmt.blocks)
{
ArrayList<Transaction> transactions=block.getTxs();
ArrayList<Leaf> leaves=new ArrayList<>();
for(Transaction tx: transactions)
{
Leaf leaf=Leaf.tx_to_leaf(tx);
leaf.setId(String.valueOf(leafcount));
leaves.add(leaf);
leafcount+=1;
}
System.out.println("Block "+block.getId()+" has "+leaves.size()+" leaves");
MerkleTree mt=MerkleTree.create_Merkletree(leaves);
}
//开始创建整体的graphmerkle树架构
System.out.println("------------------------------ Stage 1----------------------------");
System.out.println("------------------------------Lower MGT----------------------------");
//首先,按照起始节点的不同,将交易过滤为edge并分类(在MeaTUtils类中)
int gnlItemcount=0;
//MerkleGraphTree的
for (Block block: cmt.blocks)
{
HashMap<Node,ArrayList<Edge>> all_transactions=new HashMap<>();
all_transactions=MeaTUtils.start_node_filter(block.getTxs());
System.out.println("This block has "+block.getTxs().size()+" transactions");
//之后,对不同的节点构建多个下层MGT树
GraphNodeLink gnl=new GraphNodeLink();
int mgtleafcount=0;
for(Node node: all_transactions.keySet())
{
System.out.println("Pre Node id: "+node.getNode_id());
GraphNodeLinkItem gnlItem=new GraphNodeLinkItem();
ArrayList<Edge> edges=all_transactions.get(node);
ArrayList<GraphLeaf> leaves=new ArrayList<>();
for(Edge e: edges){
GraphLeaf graphLeaf=GraphLeaf.edge_to_leaf(e);
graphLeaf.setId(String.valueOf(mgtleafcount));
leaves.add(graphLeaf);
mgtleafcount+=1;
}
MerkleGraphTree lower_mgt=MerkleGraphTree.create_Merkletree(leaves);
gnlItem.addMGTs(lower_mgt);
gnlItem.setPre_node(node);
gnlItem.setId(String.valueOf(gnlItemcount));
gnlItemcount+=1;
//将gnlItem写入数据库
Connection gnlCoon= jdbcUtils.connect_database();
String gnlSql="insert into graphnodelink (start_node,mgtroot_hashvalue,gnlitem_id) value (?,?,?)";
PreparedStatement ps=gnlCoon.prepareStatement(gnlSql);
ps.setString(1,gnlItem.getPre_node().getNode_id());
ps.setString(2,lower_mgt.getHash_value().toString());
ps.setString(3,String.valueOf(gnlItemcount));
ps.executeUpdate();
try {
if (null != ps) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (null != gnlCoon) {
gnlCoon.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
//GNL中加入item
gnl.addLink(lower_mgt);
}
System.out.println("GNL also has been created. It has "+gnl.getItems().size()+" items now.");
System.out.println("------------------------------ Stage 2- -----------------------");
System.out.println("------------------------------Upper MGT--------------------------");
//接着,构建上层的MGT树
MerkleGraphTree upper_mgt=gnl.create_upper_MGT(gnl,block);
System.out.println("Now the upper MGT has been created, the root is "+block.getRoot()+", and the hash is "+block.getHashroot());
System.out.println("-------------------------------Stage 3---------------------------");
System.out.println("------------------------------PST Tree---------------------------");
//最后,构建PST树
PropertySemanticTrie pst=new PropertySemanticTrie();
String[] filter={"type","time_cost","reputation"};
pst.create_PST(block.getRoot(),cmt.txs, filter, 3);
}
}
}
| Dignity556/MerkleTree0111 | src/MeaT/CreateMeaT.java | 2,606 | // 生成0到3之间的随机数 | line_comment | zh-cn | package MeaT;
import JDBC.JDBCUtils;
import blockchain.Block;
import blockchain.Transaction;
import dataset.DataProcessing;
import functions.MeaTUtils;
import graph.Edge;
import graph.Node;
import merkletree.Leaf;
import merkletree.MerkleTree;
import javax.xml.crypto.dsig.TransformService;
import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
public class CreateMeaT {
public Random ran=new Random();
public ArrayList<Transaction> txs=new ArrayList<>();
public ArrayList<Block> blocks=new ArrayList<>();
public String[] types={"food","electronic","face","furniture"};
public ArrayList<Node> all_nodes=new ArrayList<>();
public void create_nodes(){
int i=0;
for (i=0;i<15;i++)
{
String id=String.valueOf(i);
String type=types[ran.nextInt(4)];
Node node=new Node(id,type);
all_nodes.add(node);
System.out.println(node.getNode_id());
}
}
public void create_txs_blocks(ArrayList<Node> nodes){
int block_id=1;
String[] types={"Electronic","Food","Furniture"};
for (int i=0;i<5;i++)
{
String blockid=String.valueOf(block_id);
Block b=new Block(blockid);
for(int j=0;j<20;j++)
{
String tx_id_string=String.valueOf(j);
String tx_id=tx_id_string;
String tx_time_cost=String.valueOf(ran.nextDouble()*150);
String tx_repu=String.valueOf(ran.nextDouble()*100);
int firstNumber = ran.nextInt(15); // 生成 <SUF>
int secondNumber;
do {
secondNumber = ran.nextInt(15);
} while (secondNumber == firstNumber);
Node node1=nodes.get(firstNumber);
Node node2=nodes.get(secondNumber);
String tx_timestamp=String.valueOf(block_id);
int type=ran.nextInt(3);
Transaction tx=new Transaction(tx_id,tx_timestamp,tx_time_cost,tx_repu,node1,node2,types[type]);
tx.setBlock(b);
txs.add(tx);
System.out.println("TX:"+tx.getType());
b.getTxs().add(tx);
}
block_id+=1;
blocks.add(b);
System.out.println("Block:"+b.getId());
System.out.println("Amounts:"+b.getTxs().size());
}
}
public Block query_block(String id, ArrayList<Block> blocks)
{
for (Block block:blocks)
{
if (block.getId().equals(id))
{
return block;
}
}
return null;
}
public boolean exist_block(String id, ArrayList<Block> blocks)
{
for (Block block:blocks)
{
if (block.getId().equals(id))
{
return true;
}
}
return false;
}
public Node query_node(String id, ArrayList<Node> nodes)
{
for (Node node:nodes)
{
if (node.getNode_id().equals(id))
{
return node;
}
}
return null;
}
public static void main(String[] args) throws NoSuchAlgorithmException, SQLException {
String file="./Dataset/100000.csv";
HashMap<Node,ArrayList<Transaction>> node_txs=new HashMap<>();
JDBCUtils jdbcUtils=new JDBCUtils();
DataProcessing dp=new DataProcessing();
CreateMeaT cmt=new CreateMeaT();
//将交易、节点、区块写入数据库并暂存至内存
node_txs=dp.test_dataset_to_txs(file);
for(Node node:node_txs.keySet())
{
dp.insert_transaction_database(node_txs.get(node));
cmt.all_nodes.add(node);
cmt.txs.addAll(node_txs.get(node));
}
// //miniminitest的操作,一个区块,将所有交易加到这个区块中
// cmt.blocks.add(cmt.txs.get(0).getBlock());
// for (Transaction tx: cmt.txs){
// cmt.blocks.get(0).getTxs().add(tx);
// }
//交易、节点存完了,直接读就可以
//将数据库中的交易和节点读出来
ResultSet rs = dp.select_transaction();
ResultSet rs2=dp.select_node();
ResultSet rs3=dp.select_block();
while(rs2.next())
{
Node node=new Node(rs2.getString("node_id"));
cmt.all_nodes.add(node);
}
while(rs3.next())
{
Block block=new Block(rs3.getString("block_id"));
cmt.blocks.add(block);
}
System.out.println("All blocks: "+cmt.blocks.size());
System.out.println("All nodes: "+cmt.all_nodes.size());
Node start_node=null;
Node end_node = new Node(""); // 创建一个空的Node对象,用于重复使用
while (rs.next()) {
Transaction tx=null;
start_node = cmt.query_node(rs.getString("start_node"), cmt.all_nodes);
// 重复使用end_node对象,而不是在每次迭代中创建新对象
end_node.setNode_id(rs.getString("end_node"));
Block b=cmt.query_block(rs.getString("block"),cmt.blocks);
// 重复使用tx对象,而不是在每次迭代中创建新对象
if (tx == null) {
tx = new Transaction("", "", "", "", null, null, "");
}
// 更新tx对象的属性
tx.setId(rs.getString("id"));
tx.setTimestamp(rs.getString("timestamp"));
tx.setTime_cost(rs.getString("time_cost"));
tx.setReputation(rs.getString("reputation"));
tx.setStart_node(start_node);
tx.setEnd_node(end_node);
tx.setType(rs.getString("type"));
tx.setBlock(b);
cmt.txs.add(tx);
System.out.println("Pre tx: " + rs.getString("id"));
b.getTxs().add(tx);
}
System.out.println("Total blocks: "+cmt.blocks.size());
//Merkle树的
int leafcount=0;
for (Block block: cmt.blocks)
{
ArrayList<Transaction> transactions=block.getTxs();
ArrayList<Leaf> leaves=new ArrayList<>();
for(Transaction tx: transactions)
{
Leaf leaf=Leaf.tx_to_leaf(tx);
leaf.setId(String.valueOf(leafcount));
leaves.add(leaf);
leafcount+=1;
}
System.out.println("Block "+block.getId()+" has "+leaves.size()+" leaves");
MerkleTree mt=MerkleTree.create_Merkletree(leaves);
}
//开始创建整体的graphmerkle树架构
System.out.println("------------------------------ Stage 1----------------------------");
System.out.println("------------------------------Lower MGT----------------------------");
//首先,按照起始节点的不同,将交易过滤为edge并分类(在MeaTUtils类中)
int gnlItemcount=0;
//MerkleGraphTree的
for (Block block: cmt.blocks)
{
HashMap<Node,ArrayList<Edge>> all_transactions=new HashMap<>();
all_transactions=MeaTUtils.start_node_filter(block.getTxs());
System.out.println("This block has "+block.getTxs().size()+" transactions");
//之后,对不同的节点构建多个下层MGT树
GraphNodeLink gnl=new GraphNodeLink();
int mgtleafcount=0;
for(Node node: all_transactions.keySet())
{
System.out.println("Pre Node id: "+node.getNode_id());
GraphNodeLinkItem gnlItem=new GraphNodeLinkItem();
ArrayList<Edge> edges=all_transactions.get(node);
ArrayList<GraphLeaf> leaves=new ArrayList<>();
for(Edge e: edges){
GraphLeaf graphLeaf=GraphLeaf.edge_to_leaf(e);
graphLeaf.setId(String.valueOf(mgtleafcount));
leaves.add(graphLeaf);
mgtleafcount+=1;
}
MerkleGraphTree lower_mgt=MerkleGraphTree.create_Merkletree(leaves);
gnlItem.addMGTs(lower_mgt);
gnlItem.setPre_node(node);
gnlItem.setId(String.valueOf(gnlItemcount));
gnlItemcount+=1;
//将gnlItem写入数据库
Connection gnlCoon= jdbcUtils.connect_database();
String gnlSql="insert into graphnodelink (start_node,mgtroot_hashvalue,gnlitem_id) value (?,?,?)";
PreparedStatement ps=gnlCoon.prepareStatement(gnlSql);
ps.setString(1,gnlItem.getPre_node().getNode_id());
ps.setString(2,lower_mgt.getHash_value().toString());
ps.setString(3,String.valueOf(gnlItemcount));
ps.executeUpdate();
try {
if (null != ps) {
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (null != gnlCoon) {
gnlCoon.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
//GNL中加入item
gnl.addLink(lower_mgt);
}
System.out.println("GNL also has been created. It has "+gnl.getItems().size()+" items now.");
System.out.println("------------------------------ Stage 2- -----------------------");
System.out.println("------------------------------Upper MGT--------------------------");
//接着,构建上层的MGT树
MerkleGraphTree upper_mgt=gnl.create_upper_MGT(gnl,block);
System.out.println("Now the upper MGT has been created, the root is "+block.getRoot()+", and the hash is "+block.getHashroot());
System.out.println("-------------------------------Stage 3---------------------------");
System.out.println("------------------------------PST Tree---------------------------");
//最后,构建PST树
PropertySemanticTrie pst=new PropertySemanticTrie();
String[] filter={"type","time_cost","reputation"};
pst.create_PST(block.getRoot(),cmt.txs, filter, 3);
}
}
}
| false | 2,193 | 9 | 2,606 | 8 | 2,790 | 8 | 2,606 | 8 | 3,166 | 15 | false | false | false | false | false | true |
21688_2 | package design20_备忘录模式.sample_2;
//相当于Originator,
public class Game {
private int checkPoint = 1;//游戏第一关
private int lifeValue = 100;//刚开始血量满满
private String weapon = "匕首";//武器
//开始游戏
public void play(){
System.out.println("开始游戏:"+String.format("第%d关",checkPoint)+" fighting!! ︻$▅▆▇◤");
lifeValue -= 10;
System.out.println("闯关成功");
checkPoint++;
System.out.println("到达"+String.format("第%d关",checkPoint));
}
//退出游戏
public void quit(){
System.out.println(". . . . . .");
System.out.println(this.toString()+"\n退出游戏");
}
//创建备忘录
public Memoto createMemoto(){
Memoto memoto = new Memoto();
memoto.setCheckPoint(this.checkPoint);
memoto.setLifeValue(lifeValue);
memoto.setWeapon(weapon);
return memoto;
}
//恢复游戏
public void restore(Memoto memoto){
this.checkPoint = memoto.getCheckPoint();
this.lifeValue = memoto.getLifeValue();
this.weapon = memoto.getWeapon();
System.out.println("恢复后的游戏状态:"+this.toString());
}
@Override
public String toString() {
return "当前游戏关数:"+checkPoint+" 血量:"+lifeValue+" 武器:"+weapon;
}
}
| DingMouRen/DesignPattern | src/design20_备忘录模式/sample_2/Game.java | 387 | //刚开始血量满满 | line_comment | zh-cn | package design20_备忘录模式.sample_2;
//相当于Originator,
public class Game {
private int checkPoint = 1;//游戏第一关
private int lifeValue = 100;//刚开 <SUF>
private String weapon = "匕首";//武器
//开始游戏
public void play(){
System.out.println("开始游戏:"+String.format("第%d关",checkPoint)+" fighting!! ︻$▅▆▇◤");
lifeValue -= 10;
System.out.println("闯关成功");
checkPoint++;
System.out.println("到达"+String.format("第%d关",checkPoint));
}
//退出游戏
public void quit(){
System.out.println(". . . . . .");
System.out.println(this.toString()+"\n退出游戏");
}
//创建备忘录
public Memoto createMemoto(){
Memoto memoto = new Memoto();
memoto.setCheckPoint(this.checkPoint);
memoto.setLifeValue(lifeValue);
memoto.setWeapon(weapon);
return memoto;
}
//恢复游戏
public void restore(Memoto memoto){
this.checkPoint = memoto.getCheckPoint();
this.lifeValue = memoto.getLifeValue();
this.weapon = memoto.getWeapon();
System.out.println("恢复后的游戏状态:"+this.toString());
}
@Override
public String toString() {
return "当前游戏关数:"+checkPoint+" 血量:"+lifeValue+" 武器:"+weapon;
}
}
| false | 337 | 5 | 387 | 8 | 402 | 6 | 387 | 8 | 520 | 16 | false | false | false | false | false | true |
15017_3 | package com.ding.makeup.beauty;
import android.graphics.Bitmap;
import android.graphics.Point;
import com.ding.makeup.utils.TimeAopUtils;
/**
* @author by dingdegao
* time 2017/9/29 16:03
* function: 眼睛放大
*/
public class MagnifyEyeUtils {
/**
* 眼睛放大算法
* @param bitmap 原来的bitmap
* @param centerPoint 放大中心点
* @param radius 放大半径
* @param sizeLevel 放大力度 [0,4]
* @return 放大眼睛后的图片
*/
public static Bitmap magnifyEye(Bitmap bitmap, Point centerPoint, int radius, float sizeLevel) {
TimeAopUtils.start();
Bitmap dstBitmap = bitmap.copy(Bitmap.Config.RGB_565, true);
int left = centerPoint.x - radius < 0 ? 0 : centerPoint.x - radius;
int top = centerPoint.y - radius < 0 ? 0 : centerPoint.y - radius;
int right = centerPoint.x + radius > bitmap.getWidth() ? bitmap.getWidth() - 1 : centerPoint.x + radius;
int bottom = centerPoint.y + radius > bitmap.getHeight() ? bitmap.getHeight() - 1 : centerPoint.y + radius;
int powRadius = radius * radius;
int offsetX, offsetY, powDistance, powOffsetX, powOffsetY;
int disX, disY;
//当为负数时,为缩小
float strength = (5 + sizeLevel * 2) / 10;
for (int i = top; i <= bottom; i++) {
offsetY = i - centerPoint.y;
for (int j = left; j <= right; j++) {
offsetX = j - centerPoint.x;
powOffsetX = offsetX * offsetX;
powOffsetY = offsetY * offsetY;
powDistance = powOffsetX + powOffsetY;
if (powDistance <= powRadius) {
double distance = Math.sqrt(powDistance);
double sinA = offsetX / distance;
double cosA = offsetY / distance;
double scaleFactor = distance / radius - 1;
scaleFactor = (1 - scaleFactor * scaleFactor * (distance / radius) * strength);
distance = distance * scaleFactor;
disY = (int) (distance * cosA + centerPoint.y + 0.5);
disY = checkY(disY, bitmap);
disX = (int) (distance * sinA + centerPoint.x + 0.5);
disX = checkX(disX, bitmap);
//中心点不做处理
if (!(j == centerPoint.x && i == centerPoint.y)) {
dstBitmap.setPixel(j, i, bitmap.getPixel(disX, disY));
}
}
}
}
TimeAopUtils.end("eye","magnifyEye");
return dstBitmap;
}
private static int checkY(int disY, Bitmap bitmap) {
if (disY < 0) {
disY = 0;
} else if (disY >= bitmap.getHeight()) {
disY = bitmap.getHeight() - 1;
}
return disY;
}
private static int checkX(int disX, Bitmap bitmap) {
if (disX < 0) {
disX = 0;
} else if (disX >= bitmap.getWidth()) {
disX = bitmap.getWidth() - 1;
}
return disX;
}
}
| DingProg/Makeup | app/src/main/java/com/ding/makeup/beauty/MagnifyEyeUtils.java | 853 | //中心点不做处理 | line_comment | zh-cn | package com.ding.makeup.beauty;
import android.graphics.Bitmap;
import android.graphics.Point;
import com.ding.makeup.utils.TimeAopUtils;
/**
* @author by dingdegao
* time 2017/9/29 16:03
* function: 眼睛放大
*/
public class MagnifyEyeUtils {
/**
* 眼睛放大算法
* @param bitmap 原来的bitmap
* @param centerPoint 放大中心点
* @param radius 放大半径
* @param sizeLevel 放大力度 [0,4]
* @return 放大眼睛后的图片
*/
public static Bitmap magnifyEye(Bitmap bitmap, Point centerPoint, int radius, float sizeLevel) {
TimeAopUtils.start();
Bitmap dstBitmap = bitmap.copy(Bitmap.Config.RGB_565, true);
int left = centerPoint.x - radius < 0 ? 0 : centerPoint.x - radius;
int top = centerPoint.y - radius < 0 ? 0 : centerPoint.y - radius;
int right = centerPoint.x + radius > bitmap.getWidth() ? bitmap.getWidth() - 1 : centerPoint.x + radius;
int bottom = centerPoint.y + radius > bitmap.getHeight() ? bitmap.getHeight() - 1 : centerPoint.y + radius;
int powRadius = radius * radius;
int offsetX, offsetY, powDistance, powOffsetX, powOffsetY;
int disX, disY;
//当为负数时,为缩小
float strength = (5 + sizeLevel * 2) / 10;
for (int i = top; i <= bottom; i++) {
offsetY = i - centerPoint.y;
for (int j = left; j <= right; j++) {
offsetX = j - centerPoint.x;
powOffsetX = offsetX * offsetX;
powOffsetY = offsetY * offsetY;
powDistance = powOffsetX + powOffsetY;
if (powDistance <= powRadius) {
double distance = Math.sqrt(powDistance);
double sinA = offsetX / distance;
double cosA = offsetY / distance;
double scaleFactor = distance / radius - 1;
scaleFactor = (1 - scaleFactor * scaleFactor * (distance / radius) * strength);
distance = distance * scaleFactor;
disY = (int) (distance * cosA + centerPoint.y + 0.5);
disY = checkY(disY, bitmap);
disX = (int) (distance * sinA + centerPoint.x + 0.5);
disX = checkX(disX, bitmap);
//中心 <SUF>
if (!(j == centerPoint.x && i == centerPoint.y)) {
dstBitmap.setPixel(j, i, bitmap.getPixel(disX, disY));
}
}
}
}
TimeAopUtils.end("eye","magnifyEye");
return dstBitmap;
}
private static int checkY(int disY, Bitmap bitmap) {
if (disY < 0) {
disY = 0;
} else if (disY >= bitmap.getHeight()) {
disY = bitmap.getHeight() - 1;
}
return disY;
}
private static int checkX(int disX, Bitmap bitmap) {
if (disX < 0) {
disX = 0;
} else if (disX >= bitmap.getWidth()) {
disX = bitmap.getWidth() - 1;
}
return disX;
}
}
| false | 777 | 5 | 853 | 6 | 877 | 5 | 853 | 6 | 983 | 10 | false | false | false | false | false | true |
36265_0 | package com.parkingwang.keyboard.engine;
import static com.parkingwang.keyboard.engine.NumberType.AVIATION;
import static com.parkingwang.keyboard.engine.NumberType.CIVIL;
import static com.parkingwang.keyboard.engine.NumberType.LING2012;
import static com.parkingwang.keyboard.engine.NumberType.LING2018;
import static com.parkingwang.keyboard.engine.NumberType.NEW_ENERGY;
import static com.parkingwang.keyboard.engine.NumberType.PLA2012;
import static com.parkingwang.keyboard.engine.NumberType.SHI2012;
import static com.parkingwang.keyboard.engine.NumberType.WJ2012;
/**
* 禁用更多键的逻辑:
* 1. 第1位,民用、新能源、新旧领事馆
* 2. 第3位,武警类型;
* 3. 第7位,新能源、武警、军队、旧式2012大使馆、民航类型;
* 4. 第8位;
*
*/
public class MoreKeyTransformer extends LayoutMixer.AbstractTypedKeyTransformer {
public MoreKeyTransformer() {
super(KeyType.FUNC_MORE);
}
@Override
protected KeyEntry transform(Context ctx, KeyEntry key) {
if (0 == ctx.selectIndex && ctx.numberType.isAnyOf(CIVIL, NEW_ENERGY, LING2012, LING2018)) {
return KeyEntry.newOfSetEnable(key, false);
} else if (2 == ctx.selectIndex && WJ2012.equals(ctx.numberType)) {
return KeyEntry.newOfSetEnable(key, false);
} else if (6 == ctx.selectIndex && ctx.numberType.isAnyOf(NEW_ENERGY, WJ2012, PLA2012, SHI2012, AVIATION)) {
return KeyEntry.newOfSetEnable(key, false);
} else if (7 == ctx.selectIndex) {
return KeyEntry.newOfSetEnable(key, false);
} else {
return key;
}
}
}
| DingXianSen/ProDemo | keyboard/src/main/java/com/parkingwang/keyboard/engine/MoreKeyTransformer.java | 539 | /**
* 禁用更多键的逻辑:
* 1. 第1位,民用、新能源、新旧领事馆
* 2. 第3位,武警类型;
* 3. 第7位,新能源、武警、军队、旧式2012大使馆、民航类型;
* 4. 第8位;
*
*/ | block_comment | zh-cn | package com.parkingwang.keyboard.engine;
import static com.parkingwang.keyboard.engine.NumberType.AVIATION;
import static com.parkingwang.keyboard.engine.NumberType.CIVIL;
import static com.parkingwang.keyboard.engine.NumberType.LING2012;
import static com.parkingwang.keyboard.engine.NumberType.LING2018;
import static com.parkingwang.keyboard.engine.NumberType.NEW_ENERGY;
import static com.parkingwang.keyboard.engine.NumberType.PLA2012;
import static com.parkingwang.keyboard.engine.NumberType.SHI2012;
import static com.parkingwang.keyboard.engine.NumberType.WJ2012;
/**
* 禁用更 <SUF>*/
public class MoreKeyTransformer extends LayoutMixer.AbstractTypedKeyTransformer {
public MoreKeyTransformer() {
super(KeyType.FUNC_MORE);
}
@Override
protected KeyEntry transform(Context ctx, KeyEntry key) {
if (0 == ctx.selectIndex && ctx.numberType.isAnyOf(CIVIL, NEW_ENERGY, LING2012, LING2018)) {
return KeyEntry.newOfSetEnable(key, false);
} else if (2 == ctx.selectIndex && WJ2012.equals(ctx.numberType)) {
return KeyEntry.newOfSetEnable(key, false);
} else if (6 == ctx.selectIndex && ctx.numberType.isAnyOf(NEW_ENERGY, WJ2012, PLA2012, SHI2012, AVIATION)) {
return KeyEntry.newOfSetEnable(key, false);
} else if (7 == ctx.selectIndex) {
return KeyEntry.newOfSetEnable(key, false);
} else {
return key;
}
}
}
| false | 440 | 76 | 539 | 97 | 519 | 84 | 539 | 97 | 623 | 123 | false | false | false | false | false | true |
8274_8 | package com.mori.domain;
import java.util.ArrayList;
import java.util.List;
public class Lesson {
private String pk_LId;// 每门课都有那本书的ID +课程者TPhone 组合成ID 由课程建设者设定 Len 32
private String LName;//Len 20
private String LInfo;//Len 50
private String LIcon;//Len 100
private String fk_L_TPhone;//Len 11
private int LCount;//Len 255(数据库每个int 4字节 255=8字节 就32字节 没错)
//考虑到有的课程课程号一样 老师不一样 所以老师在建设课程的时候输入的只是课程ID 而主键还是要老师PHONE+课程ID组合成唯一辨识 我了个去劳资又要改表又要
//从最里面改 = = ==== = = == = == = =所以就在逻辑上偷偷这样定义 自己手动添加PHONE 和ID组合再存入PK 在APP中JSON也有PK 不显示 隐藏起来
//点击课程显示章什么的再通过这个隐藏字段去FIND 显示详细章 节
private String fk_DId;//系ID
private List<Section> sd=new ArrayList<Section>();//非字段
public List<Section> getSd() {
return sd;
}
public void setSd(List<Section> sd) {
this.sd = sd;
}
public String getFk_DId() {
return fk_DId;
}
public void setFk_DId(String fk_DId) {
this.fk_DId = fk_DId;
}
public int getLCount() {
return LCount;
}
public void setLCount(int lCount) {
LCount = lCount;
}
public String getFk_L_TPhone() {
return fk_L_TPhone;
}
public void setFk_L_TPhone(String fk_L_TPhone) {
this.fk_L_TPhone = fk_L_TPhone;
}
@Override
public String toString() {
return "Lesson [pk_LId=" + pk_LId + ", LName=" + LName + ", LInfo="
+ LInfo + ", LIcon=" + LIcon + ", fk_L_TPhone=" + fk_L_TPhone
+ ", LCount=" + LCount + ", fk_DId=" + fk_DId + "]";
}
public String getPk_LId() {
return pk_LId;
}
public void setPk_LId(String pk_LId) {
this.pk_LId = pk_LId;
}
public String getLName() {
return LName;
}
public void setLName(String lName) {
LName = lName;
}
public String getLInfo() {
return LInfo;
}
public void setLInfo(String lInfo) {
LInfo = lInfo;
}
public String getLIcon() {
return LIcon;
}
public void setLIcon(String lIcon) {
LIcon = lIcon;
}
}
| DingYonghui/OnlineClass | web端源码/OnlineClass/src/com/mori/domain/Lesson.java | 816 | //点击课程显示章什么的再通过这个隐藏字段去FIND 显示详细章 节 | line_comment | zh-cn | package com.mori.domain;
import java.util.ArrayList;
import java.util.List;
public class Lesson {
private String pk_LId;// 每门课都有那本书的ID +课程者TPhone 组合成ID 由课程建设者设定 Len 32
private String LName;//Len 20
private String LInfo;//Len 50
private String LIcon;//Len 100
private String fk_L_TPhone;//Len 11
private int LCount;//Len 255(数据库每个int 4字节 255=8字节 就32字节 没错)
//考虑到有的课程课程号一样 老师不一样 所以老师在建设课程的时候输入的只是课程ID 而主键还是要老师PHONE+课程ID组合成唯一辨识 我了个去劳资又要改表又要
//从最里面改 = = ==== = = == = == = =所以就在逻辑上偷偷这样定义 自己手动添加PHONE 和ID组合再存入PK 在APP中JSON也有PK 不显示 隐藏起来
//点击 <SUF>
private String fk_DId;//系ID
private List<Section> sd=new ArrayList<Section>();//非字段
public List<Section> getSd() {
return sd;
}
public void setSd(List<Section> sd) {
this.sd = sd;
}
public String getFk_DId() {
return fk_DId;
}
public void setFk_DId(String fk_DId) {
this.fk_DId = fk_DId;
}
public int getLCount() {
return LCount;
}
public void setLCount(int lCount) {
LCount = lCount;
}
public String getFk_L_TPhone() {
return fk_L_TPhone;
}
public void setFk_L_TPhone(String fk_L_TPhone) {
this.fk_L_TPhone = fk_L_TPhone;
}
@Override
public String toString() {
return "Lesson [pk_LId=" + pk_LId + ", LName=" + LName + ", LInfo="
+ LInfo + ", LIcon=" + LIcon + ", fk_L_TPhone=" + fk_L_TPhone
+ ", LCount=" + LCount + ", fk_DId=" + fk_DId + "]";
}
public String getPk_LId() {
return pk_LId;
}
public void setPk_LId(String pk_LId) {
this.pk_LId = pk_LId;
}
public String getLName() {
return LName;
}
public void setLName(String lName) {
LName = lName;
}
public String getLInfo() {
return LInfo;
}
public void setLInfo(String lInfo) {
LInfo = lInfo;
}
public String getLIcon() {
return LIcon;
}
public void setLIcon(String lIcon) {
LIcon = lIcon;
}
}
| false | 675 | 22 | 816 | 20 | 783 | 17 | 816 | 20 | 1,021 | 41 | false | false | false | false | false | true |
50094_0 | import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public interface Utility {
static boolean isSpace(char c) {
return c == ' ';
}
static boolean isNewLine(char c) {
return c == '\n';
}
static boolean isTab(char c) {
return c == '\t';
}
static long filesCompareByLine(Path path1, Path path2)
throws IOException {
try (BufferedReader bf1 = Files.newBufferedReader(path1);
BufferedReader bf2 = Files.newBufferedReader(path2)) {
// 用于标识两文件是否相同,-1是完全相同,
// 否则是不同的行的行号,某种条件下也是较小文件的最大行号
long lineNumber = 1;
String line1 = "", line2 = "";
while ((line1 = bf1.readLine()) != null) {
line2 = bf2.readLine();
if (!line1.equals(line2)) {
return lineNumber;
}
lineNumber++;
}
if (bf2.readLine() == null) {
return -1;
}
else {
return lineNumber;
}
}
}
} | Dludora/BUAA_Compiler | syntactic_analysis/src/Utility.java | 282 | // 用于标识两文件是否相同,-1是完全相同, | line_comment | zh-cn | import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public interface Utility {
static boolean isSpace(char c) {
return c == ' ';
}
static boolean isNewLine(char c) {
return c == '\n';
}
static boolean isTab(char c) {
return c == '\t';
}
static long filesCompareByLine(Path path1, Path path2)
throws IOException {
try (BufferedReader bf1 = Files.newBufferedReader(path1);
BufferedReader bf2 = Files.newBufferedReader(path2)) {
// 用于 <SUF>
// 否则是不同的行的行号,某种条件下也是较小文件的最大行号
long lineNumber = 1;
String line1 = "", line2 = "";
while ((line1 = bf1.readLine()) != null) {
line2 = bf2.readLine();
if (!line1.equals(line2)) {
return lineNumber;
}
lineNumber++;
}
if (bf2.readLine() == null) {
return -1;
}
else {
return lineNumber;
}
}
}
} | false | 254 | 15 | 282 | 15 | 313 | 14 | 282 | 15 | 363 | 24 | false | false | false | false | false | true |
18212_1 | package cn.nuaa.dmrfcoder.androidexceldemo;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import cn.nuaa.dmrfcoder.androidexceldemo.Bean.DemoBean;
import cn.nuaa.dmrfcoder.androidexceldemo.Utils.ExcelUtil;
public class MainActivity extends Activity implements View.OnClickListener {
private Button exportButton;
private Button openButton;
private TextView textView;
private AlertDialog alertDialog;
private AlertDialog mDialog;
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private int REQUEST_PERMISSION_CODE = 1000;
private String filePath = "/sdcard/AndroidExcelDemo";
private void requestPermission() {
if (Build.VERSION.SDK_INT > 23) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
permissions[0])
== PackageManager.PERMISSION_GRANTED) {
//授予权限
Log.i("requestPermission:", "用户之前已经授予了权限!");
} else {
//未获得权限
Log.i("requestPermission:", "未获得权限,现在申请!");
requestPermissions(permissions
, REQUEST_PERMISSION_CODE);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
exportButton = findViewById(R.id.export_button);
exportButton.setOnClickListener(this);
openButton = findViewById(R.id.open_button);
openButton.setOnClickListener(this);
textView = findViewById(R.id.textView);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("onPermissionsResult:", "权限" + permissions[0] + "申请成功");
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
Log.i("onPermissionsResult:", "用户拒绝了权限申请");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("permission")
.setMessage("点击允许才可以使用我们的app哦")
.setPositiveButton("去允许", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
});
alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
}
}
private void showDialogTipUserRequestPermission() {
ActivityCompat.requestPermissions(this, permissions, 321);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.export_button:
exportExcel(this);
break;
case R.id.open_button:
openDir();
default:
break;
}
}
private void openDir() {
File file = new File(filePath);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setDataAndType(Uri.fromFile(file), "file/*");
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(this, "没有正确打开文件管理器", Toast.LENGTH_SHORT).show();
}
}
private void exportExcel(Context context) {
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
String excelFileName = "/demo.xls";
String[] title = {"姓名", "年龄", "男孩"};
String sheetName = "demoSheetName";
List<DemoBean> demoBeanList = new ArrayList<>();
DemoBean demoBean1 = new DemoBean("张三", 10, true);
DemoBean demoBean2 = new DemoBean("小红", 12, false);
DemoBean demoBean3 = new DemoBean("李四", 18, true);
DemoBean demoBean4 = new DemoBean("王香", 13, false);
demoBeanList.add(demoBean1);
demoBeanList.add(demoBean2);
demoBeanList.add(demoBean3);
demoBeanList.add(demoBean4);
filePath = filePath + excelFileName;
ExcelUtil.initExcel(filePath, sheetName, title);
ExcelUtil.writeObjListToExcel(demoBeanList, filePath, context);
textView.setText("excel已导出至:" + filePath);
}
}
| DmrfCoder/AndroidExcelDemo | app/src/main/java/cn/nuaa/dmrfcoder/androidexceldemo/MainActivity.java | 1,433 | //未获得权限 | line_comment | zh-cn | package cn.nuaa.dmrfcoder.androidexceldemo;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import cn.nuaa.dmrfcoder.androidexceldemo.Bean.DemoBean;
import cn.nuaa.dmrfcoder.androidexceldemo.Utils.ExcelUtil;
public class MainActivity extends Activity implements View.OnClickListener {
private Button exportButton;
private Button openButton;
private TextView textView;
private AlertDialog alertDialog;
private AlertDialog mDialog;
String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
private int REQUEST_PERMISSION_CODE = 1000;
private String filePath = "/sdcard/AndroidExcelDemo";
private void requestPermission() {
if (Build.VERSION.SDK_INT > 23) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
permissions[0])
== PackageManager.PERMISSION_GRANTED) {
//授予权限
Log.i("requestPermission:", "用户之前已经授予了权限!");
} else {
//未获 <SUF>
Log.i("requestPermission:", "未获得权限,现在申请!");
requestPermissions(permissions
, REQUEST_PERMISSION_CODE);
}
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
requestPermission();
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
builder.detectFileUriExposure();
exportButton = findViewById(R.id.export_button);
exportButton.setOnClickListener(this);
openButton = findViewById(R.id.open_button);
openButton.setOnClickListener(this);
textView = findViewById(R.id.textView);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_PERMISSION_CODE) {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("onPermissionsResult:", "权限" + permissions[0] + "申请成功");
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
Log.i("onPermissionsResult:", "用户拒绝了权限申请");
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("permission")
.setMessage("点击允许才可以使用我们的app哦")
.setPositiveButton("去允许", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
}
});
alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
}
}
private void showDialogTipUserRequestPermission() {
ActivityCompat.requestPermissions(this, permissions, 321);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.export_button:
exportExcel(this);
break;
case R.id.open_button:
openDir();
default:
break;
}
}
private void openDir() {
File file = new File(filePath);
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setDataAndType(Uri.fromFile(file), "file/*");
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(this, "没有正确打开文件管理器", Toast.LENGTH_SHORT).show();
}
}
private void exportExcel(Context context) {
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
String excelFileName = "/demo.xls";
String[] title = {"姓名", "年龄", "男孩"};
String sheetName = "demoSheetName";
List<DemoBean> demoBeanList = new ArrayList<>();
DemoBean demoBean1 = new DemoBean("张三", 10, true);
DemoBean demoBean2 = new DemoBean("小红", 12, false);
DemoBean demoBean3 = new DemoBean("李四", 18, true);
DemoBean demoBean4 = new DemoBean("王香", 13, false);
demoBeanList.add(demoBean1);
demoBeanList.add(demoBean2);
demoBeanList.add(demoBean3);
demoBeanList.add(demoBean4);
filePath = filePath + excelFileName;
ExcelUtil.initExcel(filePath, sheetName, title);
ExcelUtil.writeObjListToExcel(demoBeanList, filePath, context);
textView.setText("excel已导出至:" + filePath);
}
}
| false | 1,177 | 4 | 1,433 | 4 | 1,510 | 4 | 1,433 | 4 | 1,811 | 8 | false | false | false | false | false | true |
56954_1 | package View;
import Configure.ViewConfigure;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* @author dmrfcoder
* @date 2019-04-17
*/
public class SwichButton extends JLabel {
//0代表开始/绿色(停止中),1代表结束/红色(运行中)
private int curState;
private int D;
interface StateChangeListener {
void changeToRunning();
void changeToStop();
}
private StateChangeListener stateChangeListener;
public void setStateChangeListener(StateChangeListener stateChangeListener) {
this.stateChangeListener = stateChangeListener;
}
public SwichButton(int D) {
curState = 0;
this.D = D;
initListener();
}
private void initListener() {
addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (curState == 0) {
curState = 1;
stateChangeListener.changeToRunning();
} else {
curState = 0;
stateChangeListener.changeToStop();
}
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (curState == 0) {
g.setColor(ViewConfigure.defaultTextColor);
} else {
g.setColor(Color.red);
}
g.fillOval((getWidth() - D) / 2, (getHeight() - D) / 2, D, D);
String text = "";
g.setColor(Color.BLACK);
if (curState == 0) {
text = "开始";
} else {
text = "结束";
}
g.drawString(text, (getWidth() - 25) / 2, 5 + getHeight() / 2);
}
}
| DmrfCoder/SimulationRouter | src/View/SwichButton.java | 524 | //0代表开始/绿色(停止中),1代表结束/红色(运行中) | line_comment | zh-cn | package View;
import Configure.ViewConfigure;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
/**
* @author dmrfcoder
* @date 2019-04-17
*/
public class SwichButton extends JLabel {
//0代 <SUF>
private int curState;
private int D;
interface StateChangeListener {
void changeToRunning();
void changeToStop();
}
private StateChangeListener stateChangeListener;
public void setStateChangeListener(StateChangeListener stateChangeListener) {
this.stateChangeListener = stateChangeListener;
}
public SwichButton(int D) {
curState = 0;
this.D = D;
initListener();
}
private void initListener() {
addMouseListener(new MouseListener() {
@Override
public void mouseClicked(MouseEvent e) {
if (curState == 0) {
curState = 1;
stateChangeListener.changeToRunning();
} else {
curState = 0;
stateChangeListener.changeToStop();
}
repaint();
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
});
}
@Override
public void paint(Graphics g) {
super.paint(g);
if (curState == 0) {
g.setColor(ViewConfigure.defaultTextColor);
} else {
g.setColor(Color.red);
}
g.fillOval((getWidth() - D) / 2, (getHeight() - D) / 2, D, D);
String text = "";
g.setColor(Color.BLACK);
if (curState == 0) {
text = "开始";
} else {
text = "结束";
}
g.drawString(text, (getWidth() - 25) / 2, 5 + getHeight() / 2);
}
}
| false | 463 | 19 | 524 | 22 | 569 | 19 | 524 | 22 | 669 | 34 | false | false | false | false | false | true |
56936_1 | package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class GameFrame extends JFrame implements ActionListener{
static boolean judge = true;
static String name;
public GameFrame() {
setSize(288, 512);//设置窗口大小(288,512);
setLocationRelativeTo(null);//窗口位于电脑的正中间;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按键
setResizable(false);
setTitle("Flappy Bird终极豪华版");
init();
}
public static void main(String[] args){
GameFrame frame = new GameFrame();
GamePanel panel = new GamePanel();
frame.add(panel);//添加到界面
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {}
void init() {
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("菜单");
JMenu birdcolor = new JMenu("小鸟颜色");
JMenu bgcolor = new JMenu("背景主题");
JMenu column = new JMenu("柱子颜色");
menubar.add(menu);
JMenuItem itembc1 = new JMenuItem("黄色");
JMenuItem itembc2 = new JMenuItem("蓝色");
JMenuItem itembc3 = new JMenuItem("红色");
menu.add(birdcolor);
birdcolor.add(itembc1);
birdcolor.add(itembc2);
birdcolor.add(itembc3);
JMenuItem itembg1 = new JMenuItem("白天");
JMenuItem itembg2 = new JMenuItem("黑夜");
menu.add(bgcolor);
bgcolor.add(itembg1);
bgcolor.add(itembg2);
JMenuItem itemc1 = new JMenuItem("绿色");
JMenuItem itemc2 = new JMenuItem("橙色");
menu.add(column);
column.add(itemc1);
column.add(itemc2);
setJMenuBar(menubar);
itembc1.addActionListener(this);
itembc2.addActionListener(this);
itembc3.addActionListener(this);
itembg1.addActionListener(this);
itembg2.addActionListener(this);
itemc1.addActionListener(this);
itemc2.addActionListener(this);
itembc1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 0;
}
});
itembc2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 1;
}
});
itembc3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 2;
}
});
itemc1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Column.j = 0;
}
});
itemc2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Column.j = 1;
}
});
itembg1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GamePanel.j = 1;
}
});
itembg2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GamePanel.j = 0;
}
});
}
}
| DmuFreeCoding/DMU-cs-course | Java/MrLeea/src/game/GameFrame.java | 884 | //窗口位于电脑的正中间; | line_comment | zh-cn | package game;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class GameFrame extends JFrame implements ActionListener{
static boolean judge = true;
static String name;
public GameFrame() {
setSize(288, 512);//设置窗口大小(288,512);
setLocationRelativeTo(null);//窗口 <SUF>
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭按键
setResizable(false);
setTitle("Flappy Bird终极豪华版");
init();
}
public static void main(String[] args){
GameFrame frame = new GameFrame();
GamePanel panel = new GamePanel();
frame.add(panel);//添加到界面
frame.setVisible(true);
}
public void actionPerformed(ActionEvent e) {}
void init() {
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("菜单");
JMenu birdcolor = new JMenu("小鸟颜色");
JMenu bgcolor = new JMenu("背景主题");
JMenu column = new JMenu("柱子颜色");
menubar.add(menu);
JMenuItem itembc1 = new JMenuItem("黄色");
JMenuItem itembc2 = new JMenuItem("蓝色");
JMenuItem itembc3 = new JMenuItem("红色");
menu.add(birdcolor);
birdcolor.add(itembc1);
birdcolor.add(itembc2);
birdcolor.add(itembc3);
JMenuItem itembg1 = new JMenuItem("白天");
JMenuItem itembg2 = new JMenuItem("黑夜");
menu.add(bgcolor);
bgcolor.add(itembg1);
bgcolor.add(itembg2);
JMenuItem itemc1 = new JMenuItem("绿色");
JMenuItem itemc2 = new JMenuItem("橙色");
menu.add(column);
column.add(itemc1);
column.add(itemc2);
setJMenuBar(menubar);
itembc1.addActionListener(this);
itembc2.addActionListener(this);
itembc3.addActionListener(this);
itembg1.addActionListener(this);
itembg2.addActionListener(this);
itemc1.addActionListener(this);
itemc2.addActionListener(this);
itembc1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 0;
}
});
itembc2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 1;
}
});
itembc3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Bird.i = 2;
}
});
itemc1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Column.j = 0;
}
});
itemc2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Column.j = 1;
}
});
itembg1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GamePanel.j = 1;
}
});
itembg2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GamePanel.j = 0;
}
});
}
}
| false | 688 | 8 | 884 | 10 | 843 | 8 | 884 | 10 | 1,132 | 16 | false | false | false | false | false | true |
45653_7 | package com.dnake.panel;
import com.dnake.misc.SysTalk;
import com.dnake.misc.sCaller;
import com.dnake.misc.Sound;
import com.dnake.v700.dmsg;
import com.dnake.v700.dxml;
import com.dnake.v700.sys;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
@SuppressLint({ "DefaultLocale", "SetJavaScriptEnabled", "NewApi" })
public class TalkLabel extends BaseLabel {
public static Intent mIntent = null;
public static TalkLabel mContext = null;
public static int build = 0;
public static int unit = 0;
public static int id;
public static int OUT = 0;
public static int IN = 1;
public static int mMode = 0; // 0:呼出, 1:呼入
private MediaPlayer mPlayer = null;
private TextView mText;
private long mAutoTs = 0;
private long mEndTs = 0;
private String mPstnDtmf = null; // 语音网关拨号DTMF
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.talk);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility();
if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
mContext = this;
mPeriod = 300;
mText = (TextView) this.findViewById(R.id.prompt_text);
if (mMode == OUT) {
mText.setText(R.string.sCaller_call);
} else if (mMode == IN) {
mText.setText(R.string.sCaller_monitor);
}
}
@Override
public void onStart() {
super.onStart();
mContext = this;
this.onStart2();
}
public void onStart2() {
sCaller.refresh();
if (mMode == OUT) {
String s;
if (id == 0) { // 呼叫管理机,使用固定ID
id = 10001;
s = "10001";
} else {
s = String.format("%d%02d%04d", build, unit, id);
}
sCaller.query(s);
OnCompletionListener listener = new OnCompletionListener() {
public void onCompletion(MediaPlayer p) {
p.stop();
p.reset();
p.release();
mPlayer = null;
}
};
mPlayer = Sound.play(Sound.ringback, true, listener);
} else {
mAutoTs = System.currentTimeMillis();
}
}
@Override
public void onStop() {
super.onStop();
if (sCaller.running != sCaller.NONE)
this.stop(true);
mIntent = null;
mAutoTs = 0;
mContext = null;
}
@Override
public void onTimer() {
super.onTimer();
WakeTask.acquire();
int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility();
if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
if (mMode == OUT) {// 呼叫
if (sCaller.running == sCaller.QUERY) {
if (sys.qResult.sip.url != null) {
sCaller.start(sys.qResult.sip.url);
sCaller.logger(sCaller.logger.CALL);
sys.qResult.sip.url = null;
} else if (sys.qResult.d600.ip != null) {
System.out.println("ip: " + sys.qResult.d600.ip);
sCaller.s600(sys.qResult.d600.host, sys.qResult.d600.ip);
} else if (sCaller.timeout() >= sCaller.Time.QUERY)
this.forward();
} else if (sCaller.running == sCaller.CALL) {
if (sCaller.timeout() >= sCaller.Time.CALL || sys.qResult.result >= 400)
this.forward();
} else if (sCaller.running == sCaller.RINGING) {
// 有转呼25秒超时,其他按系统设置
int timeout = sys.panel.ringing * 1000;
if (sCaller.timeout() >= timeout) { // 振铃超时
if (!this.forward()) { // 转呼失败
mText.setText(R.string.sCaller_no_answer);
}
}
} else if (sCaller.running == sCaller.TALK) {
if (sCaller.timeout() >= sys.talk.timeout * 1000) {// 对讲结束
mText.setText(R.string.sCaller_finish);
this.stop(true);
}
if (mPstnDtmf != null && sCaller.timeout() > 1000) {
char d = mPstnDtmf.charAt(0);
mPstnDtmf = mPstnDtmf.substring(1);
if (mPstnDtmf.length() <= 0)
mPstnDtmf = null;
dxml p = new dxml();
dmsg req = new dmsg();
p.setText("/params/dtmf", String.valueOf(d));
req.to("/talk/send_dtmf", p.toString());
}
}
} else if (mMode == IN) {// 监视
if (mAutoTs != 0 && Math.abs(System.currentTimeMillis() - mAutoTs) > 500) {
mAutoTs = 0;
sCaller.running = sCaller.TALK;
dmsg req = new dmsg();
req.to("/talk/start", null);
}
if (sCaller.timeout() >= sCaller.Time.MONITOR) {// 监视超时
this.stop(true);
if (!this.isFinishing())
this.finish();
}
}
if (mEndTs != 0) {
if (Math.abs(System.currentTimeMillis() - mEndTs) >= 1000) {
if (!this.isFinishing())
this.finish();
mEndTs = 0;
}
} else {
if (sCaller.bStop) { // 挂断
this.stop(true);
mText.setText(R.string.sCaller_finish);
}
}
}
@Override
public void onKey(String key) {
super.onKey(key);
if (key.charAt(0) == '*' || key.charAt(0) == 'X') {
if (!this.isFinishing()) {
this.finish();
this.stop(true);
}
}
}
private Boolean forward() {
mText.setText(R.string.sCaller_call_err);
Sound.play(Sound.call_err, false);
this.stop(true);
return false;
}
public void play() {
if (mPlayer != null) {
Sound.stop(mPlayer);
mPlayer = null;
}
mText.setText(R.string.sCaller_talk);
sCaller.logger(sCaller.logger.ANSWER);
}
public void stop(Boolean mode) {
if (mMode == OUT) {
if (sCaller.running == sCaller.RINGING)
sCaller.logger(sCaller.logger.FAILED);
else if (sCaller.running == sCaller.TALK)
sCaller.logger(sCaller.logger.END);
}
dmsg req = new dmsg();
req.to("/talk/stop", null);
sCaller.reset();
if (mode) {
if (mPlayer != null) {
Sound.stop(mPlayer);
mPlayer = null;
}
mEndTs = System.currentTimeMillis();
} else {
mEndTs = 0;
}
}
public static void start(int b, int u, int r) {
build = b;
unit = u;
id = r;
mMode = OUT;
SysTalk.start();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
return true;
return super.onKeyDown(keyCode, event);
}
}
| DnakeFace/Face | ui/talk/src/com/dnake/panel/TalkLabel.java | 2,408 | // 对讲结束
| line_comment | zh-cn | package com.dnake.panel;
import com.dnake.misc.SysTalk;
import com.dnake.misc.sCaller;
import com.dnake.misc.Sound;
import com.dnake.v700.dmsg;
import com.dnake.v700.dxml;
import com.dnake.v700.sys;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
@SuppressLint({ "DefaultLocale", "SetJavaScriptEnabled", "NewApi" })
public class TalkLabel extends BaseLabel {
public static Intent mIntent = null;
public static TalkLabel mContext = null;
public static int build = 0;
public static int unit = 0;
public static int id;
public static int OUT = 0;
public static int IN = 1;
public static int mMode = 0; // 0:呼出, 1:呼入
private MediaPlayer mPlayer = null;
private TextView mText;
private long mAutoTs = 0;
private long mEndTs = 0;
private String mPstnDtmf = null; // 语音网关拨号DTMF
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.talk);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility();
if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
mContext = this;
mPeriod = 300;
mText = (TextView) this.findViewById(R.id.prompt_text);
if (mMode == OUT) {
mText.setText(R.string.sCaller_call);
} else if (mMode == IN) {
mText.setText(R.string.sCaller_monitor);
}
}
@Override
public void onStart() {
super.onStart();
mContext = this;
this.onStart2();
}
public void onStart2() {
sCaller.refresh();
if (mMode == OUT) {
String s;
if (id == 0) { // 呼叫管理机,使用固定ID
id = 10001;
s = "10001";
} else {
s = String.format("%d%02d%04d", build, unit, id);
}
sCaller.query(s);
OnCompletionListener listener = new OnCompletionListener() {
public void onCompletion(MediaPlayer p) {
p.stop();
p.reset();
p.release();
mPlayer = null;
}
};
mPlayer = Sound.play(Sound.ringback, true, listener);
} else {
mAutoTs = System.currentTimeMillis();
}
}
@Override
public void onStop() {
super.onStop();
if (sCaller.running != sCaller.NONE)
this.stop(true);
mIntent = null;
mAutoTs = 0;
mContext = null;
}
@Override
public void onTimer() {
super.onTimer();
WakeTask.acquire();
int ui_visibility = this.getWindow().getDecorView().getSystemUiVisibility();
if ((ui_visibility & View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) == 0) {
this.getWindow().getDecorView().setSystemUiVisibility(ui_visibility | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
if (mMode == OUT) {// 呼叫
if (sCaller.running == sCaller.QUERY) {
if (sys.qResult.sip.url != null) {
sCaller.start(sys.qResult.sip.url);
sCaller.logger(sCaller.logger.CALL);
sys.qResult.sip.url = null;
} else if (sys.qResult.d600.ip != null) {
System.out.println("ip: " + sys.qResult.d600.ip);
sCaller.s600(sys.qResult.d600.host, sys.qResult.d600.ip);
} else if (sCaller.timeout() >= sCaller.Time.QUERY)
this.forward();
} else if (sCaller.running == sCaller.CALL) {
if (sCaller.timeout() >= sCaller.Time.CALL || sys.qResult.result >= 400)
this.forward();
} else if (sCaller.running == sCaller.RINGING) {
// 有转呼25秒超时,其他按系统设置
int timeout = sys.panel.ringing * 1000;
if (sCaller.timeout() >= timeout) { // 振铃超时
if (!this.forward()) { // 转呼失败
mText.setText(R.string.sCaller_no_answer);
}
}
} else if (sCaller.running == sCaller.TALK) {
if (sCaller.timeout() >= sys.talk.timeout * 1000) {// 对讲 <SUF>
mText.setText(R.string.sCaller_finish);
this.stop(true);
}
if (mPstnDtmf != null && sCaller.timeout() > 1000) {
char d = mPstnDtmf.charAt(0);
mPstnDtmf = mPstnDtmf.substring(1);
if (mPstnDtmf.length() <= 0)
mPstnDtmf = null;
dxml p = new dxml();
dmsg req = new dmsg();
p.setText("/params/dtmf", String.valueOf(d));
req.to("/talk/send_dtmf", p.toString());
}
}
} else if (mMode == IN) {// 监视
if (mAutoTs != 0 && Math.abs(System.currentTimeMillis() - mAutoTs) > 500) {
mAutoTs = 0;
sCaller.running = sCaller.TALK;
dmsg req = new dmsg();
req.to("/talk/start", null);
}
if (sCaller.timeout() >= sCaller.Time.MONITOR) {// 监视超时
this.stop(true);
if (!this.isFinishing())
this.finish();
}
}
if (mEndTs != 0) {
if (Math.abs(System.currentTimeMillis() - mEndTs) >= 1000) {
if (!this.isFinishing())
this.finish();
mEndTs = 0;
}
} else {
if (sCaller.bStop) { // 挂断
this.stop(true);
mText.setText(R.string.sCaller_finish);
}
}
}
@Override
public void onKey(String key) {
super.onKey(key);
if (key.charAt(0) == '*' || key.charAt(0) == 'X') {
if (!this.isFinishing()) {
this.finish();
this.stop(true);
}
}
}
private Boolean forward() {
mText.setText(R.string.sCaller_call_err);
Sound.play(Sound.call_err, false);
this.stop(true);
return false;
}
public void play() {
if (mPlayer != null) {
Sound.stop(mPlayer);
mPlayer = null;
}
mText.setText(R.string.sCaller_talk);
sCaller.logger(sCaller.logger.ANSWER);
}
public void stop(Boolean mode) {
if (mMode == OUT) {
if (sCaller.running == sCaller.RINGING)
sCaller.logger(sCaller.logger.FAILED);
else if (sCaller.running == sCaller.TALK)
sCaller.logger(sCaller.logger.END);
}
dmsg req = new dmsg();
req.to("/talk/stop", null);
sCaller.reset();
if (mode) {
if (mPlayer != null) {
Sound.stop(mPlayer);
mPlayer = null;
}
mEndTs = System.currentTimeMillis();
} else {
mEndTs = 0;
}
}
public static void start(int b, int u, int r) {
build = b;
unit = u;
id = r;
mMode = OUT;
SysTalk.start();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
return true;
return super.onKeyDown(keyCode, event);
}
}
| false | 1,925 | 5 | 2,393 | 5 | 2,344 | 5 | 2,393 | 5 | 3,012 | 11 | false | false | false | false | false | true |
53010_2 | package com.randian.win.model;
import java.io.Serializable;
import java.util.List;
/**
* Created by lily on 15-6-24.
*/
public class Coach implements Serializable {
private int id;
private int level;//等级 1:中级 2:高级 3:特级 4:专家
private int distance;
private int order_num;
private int comment_num;
private int reputation_num;
private float score;
private float coach_price;
private String sex;
private String name;
private String city;
private String location;
private String verified;
private String created_at;
private String updated_at;
private String description;
private String hours_class;
private String available_areas;
private String profile_image_url;
private String positive_reputation;
private String categoriesStr;
private List<Sport> sports;//教练对应的课程列表
private List<Category> categories; //category的结构 [{"name":"瑜伽"},{"name":"健身"}]
public class Category implements Serializable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public List<Category> getCategoriesList() {
return categories;
}
public void setCategoriesList(List<Category> categories) {
this.categories = categories;
}
public String getCategories() {
return categoriesStr;
}
public void setCategories(String categoriesStr) {
this.categoriesStr = categoriesStr;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOrder_num() {
return order_num;
}
public void setOrder_num(int order_num) {
this.order_num = order_num;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public int getReputation_num() {
return reputation_num;
}
public void setReputation_num(int reputation_num) {
this.reputation_num = reputation_num;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPositive_reputation() {
return positive_reputation;
}
public void setPositive_reputation(String positive_reputation) {
this.positive_reputation = positive_reputation;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVerified() {
return verified;
}
public void setVerified(String verified) {
this.verified = verified;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHours_class() {
return hours_class;
}
public void setHours_class(String hours_class) {
this.hours_class = hours_class;
}
public String getAvailable_areas() {
return available_areas;
}
public void setAvailable_areas(String available_areas) {
this.available_areas = available_areas;
}
public List<Sport> getSports() {
return sports;
}
public void setSports(List<Sport> sports) {
this.sports = sports;
}
public int getComment_num() {
return comment_num;
}
public void setComment_num(int comment_num) {
this.comment_num = comment_num;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public float getCoach_price() {
return coach_price;
}
public void setCoach_price(float coach_price) {
this.coach_price = coach_price;
}
}
| DoTalkLily/AppKit | app/src/main/java/com/randian/win/model/Coach.java | 1,205 | //教练对应的课程列表 | line_comment | zh-cn | package com.randian.win.model;
import java.io.Serializable;
import java.util.List;
/**
* Created by lily on 15-6-24.
*/
public class Coach implements Serializable {
private int id;
private int level;//等级 1:中级 2:高级 3:特级 4:专家
private int distance;
private int order_num;
private int comment_num;
private int reputation_num;
private float score;
private float coach_price;
private String sex;
private String name;
private String city;
private String location;
private String verified;
private String created_at;
private String updated_at;
private String description;
private String hours_class;
private String available_areas;
private String profile_image_url;
private String positive_reputation;
private String categoriesStr;
private List<Sport> sports;//教练 <SUF>
private List<Category> categories; //category的结构 [{"name":"瑜伽"},{"name":"健身"}]
public class Category implements Serializable{
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public List<Category> getCategoriesList() {
return categories;
}
public void setCategoriesList(List<Category> categories) {
this.categories = categories;
}
public String getCategories() {
return categoriesStr;
}
public void setCategories(String categoriesStr) {
this.categoriesStr = categoriesStr;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getOrder_num() {
return order_num;
}
public void setOrder_num(int order_num) {
this.order_num = order_num;
}
public int getDistance() {
return distance;
}
public void setDistance(int distance) {
this.distance = distance;
}
public int getReputation_num() {
return reputation_num;
}
public void setReputation_num(int reputation_num) {
this.reputation_num = reputation_num;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPositive_reputation() {
return positive_reputation;
}
public void setPositive_reputation(String positive_reputation) {
this.positive_reputation = positive_reputation;
}
public String getProfile_image_url() {
return profile_image_url;
}
public void setProfile_image_url(String profile_image_url) {
this.profile_image_url = profile_image_url;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVerified() {
return verified;
}
public void setVerified(String verified) {
this.verified = verified;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHours_class() {
return hours_class;
}
public void setHours_class(String hours_class) {
this.hours_class = hours_class;
}
public String getAvailable_areas() {
return available_areas;
}
public void setAvailable_areas(String available_areas) {
this.available_areas = available_areas;
}
public List<Sport> getSports() {
return sports;
}
public void setSports(List<Sport> sports) {
this.sports = sports;
}
public int getComment_num() {
return comment_num;
}
public void setComment_num(int comment_num) {
this.comment_num = comment_num;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public int getLevel() {
return level;
}
public void setLevel(int level) {
this.level = level;
}
public float getCoach_price() {
return coach_price;
}
public void setCoach_price(float coach_price) {
this.coach_price = coach_price;
}
}
| false | 1,033 | 5 | 1,205 | 6 | 1,338 | 5 | 1,205 | 6 | 1,473 | 14 | false | false | false | false | false | true |
11898_0 | package xyz.doikki.dkplayer.widget.component;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import xyz.doikki.dkplayer.R;
import xyz.doikki.videoplayer.controller.IControlComponent;
import xyz.doikki.videoplayer.controller.ControlWrapper;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.PlayerUtils;
public class AdControlView extends FrameLayout implements IControlComponent, View.OnClickListener {
protected TextView mAdTime, mAdDetail;
protected ImageView mBack, mVolume, mFullScreen, mPlayButton;
protected AdControlListener mListener;
private ControlWrapper mControlWrapper;
public AdControlView(@NonNull Context context) {
super(context);
}
public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
{
LayoutInflater.from(getContext()).inflate(R.layout.layout_ad_control_view, this, true);
mAdTime = findViewById(R.id.ad_time);
mAdDetail = findViewById(R.id.ad_detail);
mAdDetail.setText("了解详情>");
mBack = findViewById(R.id.back);
mBack.setVisibility(GONE);
mVolume = findViewById(R.id.iv_volume);
mFullScreen = findViewById(R.id.fullscreen);
mPlayButton = findViewById(R.id.iv_play);
mPlayButton.setOnClickListener(this);
mAdTime.setOnClickListener(this);
mAdDetail.setOnClickListener(this);
mBack.setOnClickListener(this);
mVolume.setOnClickListener(this);
mFullScreen.setOnClickListener(this);
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) mListener.onAdClick();
}
});
}
@Override
public void attach(@NonNull ControlWrapper controlWrapper) {
mControlWrapper = controlWrapper;
}
@Override
public View getView() {
return this;
}
@Override
public void onVisibilityChanged(boolean isVisible, Animation anim) {
}
@Override
public void onPlayStateChanged(int playState) {
switch (playState) {
case VideoView.STATE_PLAYING:
mControlWrapper.startProgress();
mPlayButton.setSelected(true);
break;
case VideoView.STATE_PAUSED:
mPlayButton.setSelected(false);
break;
}
}
@Override
public void onPlayerStateChanged(int playerState) {
switch (playerState) {
case VideoView.PLAYER_NORMAL:
mBack.setVisibility(GONE);
mFullScreen.setSelected(false);
break;
case VideoView.PLAYER_FULL_SCREEN:
mBack.setVisibility(VISIBLE);
mFullScreen.setSelected(true);
break;
}
//暂未实现全面屏适配逻辑,需要你自己补全
}
@Override
public void setProgress(int duration, int position) {
if (mAdTime != null)
mAdTime.setText(String.format("%s | 跳过", (duration - position) / 1000));
}
@Override
public void onLockStateChanged(boolean isLocked) {
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.back | id == R.id.fullscreen) {
toggleFullScreen();
} else if (id == R.id.iv_volume) {
doMute();
} else if (id == R.id.ad_detail) {
if (mListener != null) mListener.onAdClick();
} else if (id == R.id.ad_time) {
if (mListener != null) mListener.onSkipAd();
} else if (id == R.id.iv_play) {
mControlWrapper.togglePlay();
}
}
private void doMute() {
mControlWrapper.setMute(!mControlWrapper.isMute());
mVolume.setImageResource(mControlWrapper.isMute() ? R.drawable.dkplayer_ic_action_volume_up : R.drawable.dkplayer_ic_action_volume_off);
}
/**
* 横竖屏切换
*/
private void toggleFullScreen() {
Activity activity = PlayerUtils.scanForActivity(getContext());
mControlWrapper.toggleFullScreen(activity);
}
public void setListener(AdControlListener listener) {
this.mListener = listener;
}
public interface AdControlListener {
void onAdClick();
void onSkipAd();
}
}
| Doikki/DKVideoPlayer | dkplayer-sample/src/main/java/xyz/doikki/dkplayer/widget/component/AdControlView.java | 1,178 | //暂未实现全面屏适配逻辑,需要你自己补全 | line_comment | zh-cn | package xyz.doikki.dkplayer.widget.component;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import xyz.doikki.dkplayer.R;
import xyz.doikki.videoplayer.controller.IControlComponent;
import xyz.doikki.videoplayer.controller.ControlWrapper;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.PlayerUtils;
public class AdControlView extends FrameLayout implements IControlComponent, View.OnClickListener {
protected TextView mAdTime, mAdDetail;
protected ImageView mBack, mVolume, mFullScreen, mPlayButton;
protected AdControlListener mListener;
private ControlWrapper mControlWrapper;
public AdControlView(@NonNull Context context) {
super(context);
}
public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public AdControlView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
{
LayoutInflater.from(getContext()).inflate(R.layout.layout_ad_control_view, this, true);
mAdTime = findViewById(R.id.ad_time);
mAdDetail = findViewById(R.id.ad_detail);
mAdDetail.setText("了解详情>");
mBack = findViewById(R.id.back);
mBack.setVisibility(GONE);
mVolume = findViewById(R.id.iv_volume);
mFullScreen = findViewById(R.id.fullscreen);
mPlayButton = findViewById(R.id.iv_play);
mPlayButton.setOnClickListener(this);
mAdTime.setOnClickListener(this);
mAdDetail.setOnClickListener(this);
mBack.setOnClickListener(this);
mVolume.setOnClickListener(this);
mFullScreen.setOnClickListener(this);
this.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mListener != null) mListener.onAdClick();
}
});
}
@Override
public void attach(@NonNull ControlWrapper controlWrapper) {
mControlWrapper = controlWrapper;
}
@Override
public View getView() {
return this;
}
@Override
public void onVisibilityChanged(boolean isVisible, Animation anim) {
}
@Override
public void onPlayStateChanged(int playState) {
switch (playState) {
case VideoView.STATE_PLAYING:
mControlWrapper.startProgress();
mPlayButton.setSelected(true);
break;
case VideoView.STATE_PAUSED:
mPlayButton.setSelected(false);
break;
}
}
@Override
public void onPlayerStateChanged(int playerState) {
switch (playerState) {
case VideoView.PLAYER_NORMAL:
mBack.setVisibility(GONE);
mFullScreen.setSelected(false);
break;
case VideoView.PLAYER_FULL_SCREEN:
mBack.setVisibility(VISIBLE);
mFullScreen.setSelected(true);
break;
}
//暂未 <SUF>
}
@Override
public void setProgress(int duration, int position) {
if (mAdTime != null)
mAdTime.setText(String.format("%s | 跳过", (duration - position) / 1000));
}
@Override
public void onLockStateChanged(boolean isLocked) {
}
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.back | id == R.id.fullscreen) {
toggleFullScreen();
} else if (id == R.id.iv_volume) {
doMute();
} else if (id == R.id.ad_detail) {
if (mListener != null) mListener.onAdClick();
} else if (id == R.id.ad_time) {
if (mListener != null) mListener.onSkipAd();
} else if (id == R.id.iv_play) {
mControlWrapper.togglePlay();
}
}
private void doMute() {
mControlWrapper.setMute(!mControlWrapper.isMute());
mVolume.setImageResource(mControlWrapper.isMute() ? R.drawable.dkplayer_ic_action_volume_up : R.drawable.dkplayer_ic_action_volume_off);
}
/**
* 横竖屏切换
*/
private void toggleFullScreen() {
Activity activity = PlayerUtils.scanForActivity(getContext());
mControlWrapper.toggleFullScreen(activity);
}
public void setListener(AdControlListener listener) {
this.mListener = listener;
}
public interface AdControlListener {
void onAdClick();
void onSkipAd();
}
}
| false | 986 | 14 | 1,178 | 16 | 1,264 | 13 | 1,178 | 16 | 1,430 | 34 | false | false | false | false | false | true |
43668_5 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* 显示帮助信息的对话框
*/
public class HelpDialog extends JDialog implements ActionListener {
// 确认按钮
private JButton okay;
// 取消按钮
private JButton cancel;
public HelpDialog(Frame parent,String title) {
super(parent,title,true); //不可缺少true
addText();
okay.addActionListener(this);
cancel.addActionListener(this);
pack();
show();
}
// 显示面板
public void addText() {
setLocation(300, 210);
okay = new JButton("确认");
cancel = new JButton("取消");
Panel button = new Panel();
button.setLayout(new FlowLayout());
button.add(okay);
button.add(cancel);
setLayout(new GridLayout(5,1));
add(new Label("传教士野人过河问题是一个经典的人工智能问题,问题描述如下:"));
add(new Label("有N个传教士和N个野人过河,只有一条能装下K个人(包括野人)的船,K<N,"));
add(new Label("在河的任何一方或者船上,如果有野人和传教士在一起,必须要求传教士的人数多于或等于野人的人数。"));
add(new Label("本程序使用A*搜索算法实现求解传教士野人过河问题,对任意N、K有解时给出其解决方案。"));
add(button);
}
// 监听事件
public void actionPerformed(ActionEvent ae) {
//隐藏对话框
dispose();
}
}; | DolphinHome/java-mc-astar | src/HelpDialog.java | 397 | // 监听事件 | line_comment | zh-cn | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
/**
* 显示帮助信息的对话框
*/
public class HelpDialog extends JDialog implements ActionListener {
// 确认按钮
private JButton okay;
// 取消按钮
private JButton cancel;
public HelpDialog(Frame parent,String title) {
super(parent,title,true); //不可缺少true
addText();
okay.addActionListener(this);
cancel.addActionListener(this);
pack();
show();
}
// 显示面板
public void addText() {
setLocation(300, 210);
okay = new JButton("确认");
cancel = new JButton("取消");
Panel button = new Panel();
button.setLayout(new FlowLayout());
button.add(okay);
button.add(cancel);
setLayout(new GridLayout(5,1));
add(new Label("传教士野人过河问题是一个经典的人工智能问题,问题描述如下:"));
add(new Label("有N个传教士和N个野人过河,只有一条能装下K个人(包括野人)的船,K<N,"));
add(new Label("在河的任何一方或者船上,如果有野人和传教士在一起,必须要求传教士的人数多于或等于野人的人数。"));
add(new Label("本程序使用A*搜索算法实现求解传教士野人过河问题,对任意N、K有解时给出其解决方案。"));
add(button);
}
// 监听 <SUF>
public void actionPerformed(ActionEvent ae) {
//隐藏对话框
dispose();
}
}; | false | 350 | 5 | 397 | 4 | 400 | 4 | 397 | 4 | 525 | 10 | false | false | false | false | false | true |
38345_5 | import java.util.HashMap;
/**
* LRU算法 最近最常使用算法,内存加载
*/
public class LRU {
public static class Node<V> {
public Node<V> pre;
public Node<V> next;
public V value;
public Node(V value) {
this.value = value;
}
}
public static class MyCache<K, V> {
//map可保证为(1)的查询对应关系
private HashMap<K, Node<V>> keyNodeMap;
private NodeDoubleLinkedList<V> nodeList;
private int capacity;
public MyCache(int capacity) {
if (capacity < 1) {
new RuntimeException("should be more than 1 ");
}
this.capacity = capacity;
this.keyNodeMap = new HashMap<>();
this.nodeList = new NodeDoubleLinkedList<>();
}
public V get(K key) {
if (this.keyNodeMap.containsKey(key)) {
Node<V> res = this.keyNodeMap.get(key);
this.nodeList.moveNodeToTail(res);
return res.value;
}
return null;
}
public void set(K key, V value) {
if (keyNodeMap.containsKey(key)) {
Node<V> res = this.keyNodeMap.get(key);
res.value = value;
this.nodeList.moveNodeToTail(res);
} else {
Node<V> res = new Node<>(value);
this.nodeList.addNode(res);
this.keyNodeMap.put(key, res);
//大于指定容量移除掉头部,为最不经常使用的节点,同时移除掉map集合中的元素
if (this.keyNodeMap.size() == capacity + 1) {
Node<V> removeNode = this.nodeList.removeHead();
keyNodeMap.remove(removeNode.value);
}
}
}
}
/**
* 双向链表 ,有头尾指针,头指针为最不经常使用的节点,尾指针为刚使用完的节点
*
* @param <V>
*/
public static class NodeDoubleLinkedList<V> {
private Node<V> head;
private Node<V> tail;
public NodeDoubleLinkedList() {
this.head = null;
this.tail = null;
}
public void addNode(Node<V> newNode) {
if (newNode == null) {
return;
}
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
//双向链表
this.tail.next = newNode;
newNode.pre = this.tail;
this.tail = newNode;
}
}
public void moveNodeToTail(Node<V> node) {
if (this.tail == null) {
return;
}
//先断开之前的位置
if (this.head == node) {
head = node.next;
this.head.pre = null;
} else {
node.pre.next = node.next;
node.next.pre = node.pre;
}
//移动到最后的位置
node.pre = this.tail;
node.next = null;
this.tail.next = node;
this.tail = node;
}
public Node<V> removeHead() {
if (head == null) {
return null;
}
Node removeNode = this.head;
if (this.head == this.tail) {
this.head = null;
this.tail = null;
} else {
this.head = removeNode.next;
this.head.pre = null;
removeNode.next = null;
}
return removeNode;
}
}
}
| Dongyang666/leetcode | src/LRU.java | 967 | //先断开之前的位置 | line_comment | zh-cn | import java.util.HashMap;
/**
* LRU算法 最近最常使用算法,内存加载
*/
public class LRU {
public static class Node<V> {
public Node<V> pre;
public Node<V> next;
public V value;
public Node(V value) {
this.value = value;
}
}
public static class MyCache<K, V> {
//map可保证为(1)的查询对应关系
private HashMap<K, Node<V>> keyNodeMap;
private NodeDoubleLinkedList<V> nodeList;
private int capacity;
public MyCache(int capacity) {
if (capacity < 1) {
new RuntimeException("should be more than 1 ");
}
this.capacity = capacity;
this.keyNodeMap = new HashMap<>();
this.nodeList = new NodeDoubleLinkedList<>();
}
public V get(K key) {
if (this.keyNodeMap.containsKey(key)) {
Node<V> res = this.keyNodeMap.get(key);
this.nodeList.moveNodeToTail(res);
return res.value;
}
return null;
}
public void set(K key, V value) {
if (keyNodeMap.containsKey(key)) {
Node<V> res = this.keyNodeMap.get(key);
res.value = value;
this.nodeList.moveNodeToTail(res);
} else {
Node<V> res = new Node<>(value);
this.nodeList.addNode(res);
this.keyNodeMap.put(key, res);
//大于指定容量移除掉头部,为最不经常使用的节点,同时移除掉map集合中的元素
if (this.keyNodeMap.size() == capacity + 1) {
Node<V> removeNode = this.nodeList.removeHead();
keyNodeMap.remove(removeNode.value);
}
}
}
}
/**
* 双向链表 ,有头尾指针,头指针为最不经常使用的节点,尾指针为刚使用完的节点
*
* @param <V>
*/
public static class NodeDoubleLinkedList<V> {
private Node<V> head;
private Node<V> tail;
public NodeDoubleLinkedList() {
this.head = null;
this.tail = null;
}
public void addNode(Node<V> newNode) {
if (newNode == null) {
return;
}
if (this.head == null) {
this.head = newNode;
this.tail = newNode;
} else {
//双向链表
this.tail.next = newNode;
newNode.pre = this.tail;
this.tail = newNode;
}
}
public void moveNodeToTail(Node<V> node) {
if (this.tail == null) {
return;
}
//先断 <SUF>
if (this.head == node) {
head = node.next;
this.head.pre = null;
} else {
node.pre.next = node.next;
node.next.pre = node.pre;
}
//移动到最后的位置
node.pre = this.tail;
node.next = null;
this.tail.next = node;
this.tail = node;
}
public Node<V> removeHead() {
if (head == null) {
return null;
}
Node removeNode = this.head;
if (this.head == this.tail) {
this.head = null;
this.tail = null;
} else {
this.head = removeNode.next;
this.head.pre = null;
removeNode.next = null;
}
return removeNode;
}
}
}
| false | 788 | 6 | 967 | 7 | 956 | 6 | 967 | 7 | 1,264 | 9 | false | false | false | false | false | true |
53109_2 | /**
* MIT License
*
* Copyright (c) 2017 CaiDongyu
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.axe.helper.aop;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.axe.annotation.aop.Aspect;
import org.axe.helper.ioc.BeanHelper;
import org.axe.helper.ioc.ClassHelper;
import org.axe.interface_.base.Helper;
import org.axe.interface_.proxy.Proxy;
import org.axe.proxy.base.ProxyManger;
import org.axe.util.ReflectionUtil;
/**
* 方法拦截助手类
* @author CaiDongyu on 2016/4/14.
*/
public final class AopHelper implements Helper{
@Override
public void init() throws Exception{
synchronized (this) {
Map<Class<?>,Set<Class<?>>> proxyMap = createProxyMap();
Map<Class<?>,List<Proxy>> targetMap = createTargetMap(proxyMap);
for (Map.Entry<Class<?>,List<Proxy>> targetEntry:targetMap.entrySet()){
Class<?> targetClass = targetEntry.getKey();
List<Proxy> proxyList = targetEntry.getValue();
//真正的创建目标类的代理对象
Object proxy = ProxyManger.createProxy(targetClass,proxyList);
BeanHelper.setBean(targetClass,proxy);
}
}
}
/**
* 返回代理类与目标类集合的映射
* 比如代理类A,代理了B、C、D三个类
* 通过A类上的注解Aspect指定一个目标注解比如叫M
* B、C、D类都拥有这个注解M,就可以了。
*/
private static Map<Class<?>,Set<Class<?>>> createProxyMap() throws Exception {
Map<Class<?>,Set<Class<?>>> proxyMap = new HashMap<>();
//找到切面抽象类的实现类,就是说,都是切面类
Set<Class<?>> proxyClassSet = ClassHelper.getClassSetBySuper(Proxy.class);
for(Class<?> proxyClass : proxyClassSet){
//继承了 AspectProxy 不算,还得是有指定了切面目标类
if(proxyClass.isAnnotationPresent(Aspect.class)){
Aspect aspect = proxyClass.getAnnotation(Aspect.class);
//TODO:目前AOP实现,还只是针对有目标注解的类做切面,不能细化到方法,这样一旦拦截,会拦截所有方法
//比如事务切面,实际上是切了整个Server类所有方法,但是在切面加强的时候会判断,判断这个方法开不开事务。
Set<Class<?>> targetClassSet = createTargetClassSet(aspect);
proxyMap.put(proxyClass,targetClassSet);
}
}
return proxyMap;
}
private static Set<Class<?>> createTargetClassSet(Aspect aspect) throws Exception{
Set<Class<?>> targetClassSet = new HashSet<>();
//切面目标的指定,依然是通过注解来匹配
Class<? extends Annotation>[] annotations = aspect.value();
//排除Aspect注解本身,因为Aspect注解就是用来指定目标切面注解的
if(annotations != null){
for(Class<? extends Annotation> annotation:annotations){
if(!annotation.equals(Aspect.class)){
//取出含有目标注解的类,作为目标类
targetClassSet.addAll(ClassHelper.getClassSetByAnnotation(annotation));
}
}
}
return targetClassSet;
}
/**
* 将proxy -> targetClassSet 映射关系逆转
* 变成 targetClass -> proxyList 关系
* 也就是说现在是 一个类,对应有多少个proxy去处理
*/
private static Map<Class<?>,List<Proxy>> createTargetMap(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception{
Map<Class<?>,List<Proxy>> targetMap = new HashMap<>();
for (Map.Entry<Class<?>,Set<Class<?>>> proxyEntry:proxyMap.entrySet()){
Class<?> proxyClass = proxyEntry.getKey();
Set<Class<?>> targetClassSet = proxyEntry.getValue();
Proxy proxy = ReflectionUtil.newInstance(proxyClass);
for (Class<?> targetClass : targetClassSet){
if (targetMap.containsKey(targetClass)){
targetMap.get(targetClass).add(proxy);
} else {
List<Proxy> proxyList = new ArrayList<Proxy>();
proxyList.add(proxy);
targetMap.put(targetClass,proxyList);
}
}
}
return targetMap;
}
@Override
public void onStartUp() throws Exception {}
}
| DongyuCai/Axe | axe/src/main/java/org/axe/helper/aop/AopHelper.java | 1,335 | //真正的创建目标类的代理对象 | line_comment | zh-cn | /**
* MIT License
*
* Copyright (c) 2017 CaiDongyu
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.axe.helper.aop;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.axe.annotation.aop.Aspect;
import org.axe.helper.ioc.BeanHelper;
import org.axe.helper.ioc.ClassHelper;
import org.axe.interface_.base.Helper;
import org.axe.interface_.proxy.Proxy;
import org.axe.proxy.base.ProxyManger;
import org.axe.util.ReflectionUtil;
/**
* 方法拦截助手类
* @author CaiDongyu on 2016/4/14.
*/
public final class AopHelper implements Helper{
@Override
public void init() throws Exception{
synchronized (this) {
Map<Class<?>,Set<Class<?>>> proxyMap = createProxyMap();
Map<Class<?>,List<Proxy>> targetMap = createTargetMap(proxyMap);
for (Map.Entry<Class<?>,List<Proxy>> targetEntry:targetMap.entrySet()){
Class<?> targetClass = targetEntry.getKey();
List<Proxy> proxyList = targetEntry.getValue();
//真正 <SUF>
Object proxy = ProxyManger.createProxy(targetClass,proxyList);
BeanHelper.setBean(targetClass,proxy);
}
}
}
/**
* 返回代理类与目标类集合的映射
* 比如代理类A,代理了B、C、D三个类
* 通过A类上的注解Aspect指定一个目标注解比如叫M
* B、C、D类都拥有这个注解M,就可以了。
*/
private static Map<Class<?>,Set<Class<?>>> createProxyMap() throws Exception {
Map<Class<?>,Set<Class<?>>> proxyMap = new HashMap<>();
//找到切面抽象类的实现类,就是说,都是切面类
Set<Class<?>> proxyClassSet = ClassHelper.getClassSetBySuper(Proxy.class);
for(Class<?> proxyClass : proxyClassSet){
//继承了 AspectProxy 不算,还得是有指定了切面目标类
if(proxyClass.isAnnotationPresent(Aspect.class)){
Aspect aspect = proxyClass.getAnnotation(Aspect.class);
//TODO:目前AOP实现,还只是针对有目标注解的类做切面,不能细化到方法,这样一旦拦截,会拦截所有方法
//比如事务切面,实际上是切了整个Server类所有方法,但是在切面加强的时候会判断,判断这个方法开不开事务。
Set<Class<?>> targetClassSet = createTargetClassSet(aspect);
proxyMap.put(proxyClass,targetClassSet);
}
}
return proxyMap;
}
private static Set<Class<?>> createTargetClassSet(Aspect aspect) throws Exception{
Set<Class<?>> targetClassSet = new HashSet<>();
//切面目标的指定,依然是通过注解来匹配
Class<? extends Annotation>[] annotations = aspect.value();
//排除Aspect注解本身,因为Aspect注解就是用来指定目标切面注解的
if(annotations != null){
for(Class<? extends Annotation> annotation:annotations){
if(!annotation.equals(Aspect.class)){
//取出含有目标注解的类,作为目标类
targetClassSet.addAll(ClassHelper.getClassSetByAnnotation(annotation));
}
}
}
return targetClassSet;
}
/**
* 将proxy -> targetClassSet 映射关系逆转
* 变成 targetClass -> proxyList 关系
* 也就是说现在是 一个类,对应有多少个proxy去处理
*/
private static Map<Class<?>,List<Proxy>> createTargetMap(Map<Class<?>, Set<Class<?>>> proxyMap) throws Exception{
Map<Class<?>,List<Proxy>> targetMap = new HashMap<>();
for (Map.Entry<Class<?>,Set<Class<?>>> proxyEntry:proxyMap.entrySet()){
Class<?> proxyClass = proxyEntry.getKey();
Set<Class<?>> targetClassSet = proxyEntry.getValue();
Proxy proxy = ReflectionUtil.newInstance(proxyClass);
for (Class<?> targetClass : targetClassSet){
if (targetMap.containsKey(targetClass)){
targetMap.get(targetClass).add(proxy);
} else {
List<Proxy> proxyList = new ArrayList<Proxy>();
proxyList.add(proxy);
targetMap.put(targetClass,proxyList);
}
}
}
return targetMap;
}
@Override
public void onStartUp() throws Exception {}
}
| false | 1,204 | 8 | 1,335 | 9 | 1,381 | 7 | 1,335 | 9 | 1,749 | 14 | false | false | false | false | false | true |
22120_2 | package com.software.job.vo;
import java.sql.Date;
import com.software.job.po.Users;
/*
* 此javaBean为了方便展示页面数据,故和数据库类型不一样
*/
public class UserInfo {
private int id;
private String uname;
private String pwd;
private String email;
private String phone;
private int age;
private String gender;//数据类型改变
private String address;
private String degree;//数据类型改变
private Date joinTime;
private String ip;
public UserInfo() {
}
public UserInfo(Users users) {
super();
this.id = users.getId();
this.uname = users.getUname();
this.pwd = users.getPwd();
this.email = users.getEmail();
this.phone = users.getPhone();
this.age = users.getAge();
setGender(users.getGender());
this.address = users.getAddress();
setDegree(users.getDegree());
this.joinTime = users.getJoinTime();
this.ip = users.getIp();
}
public UserInfo(int id, String uname, String pwd, String email, String phone, int age, int gender, String address,
int degree, Date joinTime, String ip) {
super();
this.id = id;
this.uname = uname;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.age = age;
setGender(gender);
this.address = address;
setDegree(degree);
this.joinTime = joinTime;
this.ip = ip;
}
public UserInfo(String uname, String pwd, String email, String phone, int age, int gender, String address, int degree,
Date joinTime, String ip) {
super();
this.uname = uname;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.age = age;
setGender(gender);
this.address = address;
setDegree(degree);
this.joinTime = joinTime;
this.ip = ip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(int gender) {
if(gender==0) {
this.gender = "男";
}else {
this.gender="女";
}
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDegree() {
return degree;
}
public void setDegree(int degree) {
switch (degree) {
case 0:
this.degree = "高中";
break;
case 1:
this.degree = "专科";
break;
case 2:
this.degree = "本科";
break;
case 3:
this.degree = "硕士";
break;
case 4:
this.degree = "博士";
break;
}
}
public Date getJoinTime() {
return joinTime;
}
public void setJoinTime(Date joinTime) {
this.joinTime = joinTime;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
| DonkeyHu/TypicalWebProject | src/com/software/job/vo/UserInfo.java | 1,100 | //数据类型改变 | line_comment | zh-cn | package com.software.job.vo;
import java.sql.Date;
import com.software.job.po.Users;
/*
* 此javaBean为了方便展示页面数据,故和数据库类型不一样
*/
public class UserInfo {
private int id;
private String uname;
private String pwd;
private String email;
private String phone;
private int age;
private String gender;//数据类型改变
private String address;
private String degree;//数据 <SUF>
private Date joinTime;
private String ip;
public UserInfo() {
}
public UserInfo(Users users) {
super();
this.id = users.getId();
this.uname = users.getUname();
this.pwd = users.getPwd();
this.email = users.getEmail();
this.phone = users.getPhone();
this.age = users.getAge();
setGender(users.getGender());
this.address = users.getAddress();
setDegree(users.getDegree());
this.joinTime = users.getJoinTime();
this.ip = users.getIp();
}
public UserInfo(int id, String uname, String pwd, String email, String phone, int age, int gender, String address,
int degree, Date joinTime, String ip) {
super();
this.id = id;
this.uname = uname;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.age = age;
setGender(gender);
this.address = address;
setDegree(degree);
this.joinTime = joinTime;
this.ip = ip;
}
public UserInfo(String uname, String pwd, String email, String phone, int age, int gender, String address, int degree,
Date joinTime, String ip) {
super();
this.uname = uname;
this.pwd = pwd;
this.email = email;
this.phone = phone;
this.age = age;
setGender(gender);
this.address = address;
setDegree(degree);
this.joinTime = joinTime;
this.ip = ip;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(int gender) {
if(gender==0) {
this.gender = "男";
}else {
this.gender="女";
}
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDegree() {
return degree;
}
public void setDegree(int degree) {
switch (degree) {
case 0:
this.degree = "高中";
break;
case 1:
this.degree = "专科";
break;
case 2:
this.degree = "本科";
break;
case 3:
this.degree = "硕士";
break;
case 4:
this.degree = "博士";
break;
}
}
public Date getJoinTime() {
return joinTime;
}
public void setJoinTime(Date joinTime) {
this.joinTime = joinTime;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
}
| false | 835 | 4 | 1,100 | 4 | 1,090 | 4 | 1,100 | 4 | 1,283 | 7 | false | false | false | false | false | true |
63609_7 | package priv.fruits.controller.web;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import priv.fruits.pojo.ResultMessage;
import priv.fruits.pojo.User;
import priv.fruits.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @Author 冶生华
* @Description 果蔬超市
*/
@Controller
@RequestMapping("email")
public class EmailController {
// 创建配置好的邮箱对象
@Autowired
private MailAccount mailAccount;
@Autowired
private UserService userService;
/**
* 发送邮箱验证码
* @param userEmail 邮件接收人
* @return
*/
@GetMapping("sendVerifyCode")
@ResponseBody
public ResultMessage sendVerifyCode(String userEmail, String type, HttpServletRequest request) {
try {
// 查询该邮箱是否已注册
User user = userService.getUserInfoByEmail(userEmail);
if("register".equals(type) && user != null && user.getId() != null) {
return new ResultMessage(207, "该邮箱已被注册!");
}
// 生成验证码(随机10000 - 99999的数字)
String code = RandomUtil.randomInt(10000, 99999)+"";
// 将生成的验证码保存到session中, 用于后期验证
HttpSession session = request.getSession();
// 保存前将之前保存过的记录删除一遍, 防止之前有记录
session.removeAttribute("webEditPassVerifyCode");
session.removeAttribute("webRegisterVerifyCode");
// 判断是注册还是修改密码, 保存不同的名字
if("register".equals(type)) {
session.setAttribute("webRegisterVerifyCode", code);
} else if("editPassword".equals(type)) {
session.setAttribute("webEditPassVerifyCode", code);
}
// 利用Hutool封装的邮箱工具类发送邮件
String send = MailUtil.send(mailAccount, CollectionUtil.newArrayList(userEmail),
"您正在注册果蔬超市账户……", "打死都不要告诉别人!!验证码是:" +
"<span style='color:#1E9FFF;font-size:16px;font-weight:800;'>" +
code + "</span>", true);
System.out.println("邮件发送结果:" + send);
return new ResultMessage(0, "邮件已发送!请查收");
} catch (Exception e) {
e.printStackTrace();
return new ResultMessage(500, "出现异常:" + e.getMessage());
}
}
}
| DouFoUncle/daily-fruits | src/main/java/priv/fruits/controller/web/EmailController.java | 733 | // 判断是注册还是修改密码, 保存不同的名字 | line_comment | zh-cn | package priv.fruits.controller.web;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import priv.fruits.pojo.ResultMessage;
import priv.fruits.pojo.User;
import priv.fruits.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* @Author 冶生华
* @Description 果蔬超市
*/
@Controller
@RequestMapping("email")
public class EmailController {
// 创建配置好的邮箱对象
@Autowired
private MailAccount mailAccount;
@Autowired
private UserService userService;
/**
* 发送邮箱验证码
* @param userEmail 邮件接收人
* @return
*/
@GetMapping("sendVerifyCode")
@ResponseBody
public ResultMessage sendVerifyCode(String userEmail, String type, HttpServletRequest request) {
try {
// 查询该邮箱是否已注册
User user = userService.getUserInfoByEmail(userEmail);
if("register".equals(type) && user != null && user.getId() != null) {
return new ResultMessage(207, "该邮箱已被注册!");
}
// 生成验证码(随机10000 - 99999的数字)
String code = RandomUtil.randomInt(10000, 99999)+"";
// 将生成的验证码保存到session中, 用于后期验证
HttpSession session = request.getSession();
// 保存前将之前保存过的记录删除一遍, 防止之前有记录
session.removeAttribute("webEditPassVerifyCode");
session.removeAttribute("webRegisterVerifyCode");
// 判断 <SUF>
if("register".equals(type)) {
session.setAttribute("webRegisterVerifyCode", code);
} else if("editPassword".equals(type)) {
session.setAttribute("webEditPassVerifyCode", code);
}
// 利用Hutool封装的邮箱工具类发送邮件
String send = MailUtil.send(mailAccount, CollectionUtil.newArrayList(userEmail),
"您正在注册果蔬超市账户……", "打死都不要告诉别人!!验证码是:" +
"<span style='color:#1E9FFF;font-size:16px;font-weight:800;'>" +
code + "</span>", true);
System.out.println("邮件发送结果:" + send);
return new ResultMessage(0, "邮件已发送!请查收");
} catch (Exception e) {
e.printStackTrace();
return new ResultMessage(500, "出现异常:" + e.getMessage());
}
}
}
| false | 625 | 13 | 733 | 12 | 740 | 11 | 733 | 12 | 984 | 24 | false | false | false | false | false | true |
43767_3 | package controllers.admin;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import models.mag_article;
import models.mag_banner;
import models.mag_works;
import models.mag_worksclass;
import play.Play;
import play.libs.Files;
import play.mvc.Controller;
import com.alibaba.fastjson.JSON;
public class Banner extends Controller{
public static void allBanner(){
mag_banner banner = new mag_banner();
renderJSON("{\"data\":"+banner.allBanner()+"}");
}
public static void addBanner(String title,String remark,File image,String artclass ,String ardid){
System.out.println(title);
System.out.println(remark);
System.out.println(image);
System.out.println(artclass);
System.out.println(ardid);
//文件保存目录路径
String savePath = Play.applicationPath.toString()+Play.configuration.getProperty("newsImg.savePath", "/public/upload/");
//文件保存目录URL
String saveUrl = Play.configuration.getProperty("newsImg.savePath", "/public/upload/");
if (image != null) {
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
renderJSON("{\"state\":\"上传目录不存在。\"}");
return;
}
//检查目录写权限
if(!uploadDir.canWrite()){
renderJSON("{\"state\":\"上传目录没有写权限。\"}");
return;
}
String ymd = "banner";
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
//检查扩展名
String fileExt = image.getName().substring(image.getName().lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
File f = new File(savePath,newFileName);
try {
Files.copy(image,f);
System.out.println(saveUrl + newFileName);
java.text.DateFormat format1 = new java.text.SimpleDateFormat(
"yyyy-MM-dd hh:mm");
String timeStr = format1.format(new Date()).toString();
if(artclass == "作品"){
mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "作品");
banner.save();
}else{
mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "文章");
banner.save();
}
renderJSON("{\"state\":\"操作成功\"}");
} catch (Exception e) {
e.printStackTrace();
renderJSON("{\"state\":\"上传失败\"}");
}
}else{
renderJSON("{\"state\":\"请选择文件。\"}");
}
renderJSON("{\"status\":\"操作成功\"}");
}
public static void getBanner(){
}
public static void delBanner(){
}
public static void allBannerList(){
List<mag_article> artlist = mag_article.find("order by id desc").fetch();
List<mag_works> worklist = mag_works.find("order by id desc").fetch();
String artStr = JSON.toJSONString(artlist);
String worksStr = JSON.toJSONString(worklist);
renderJSON("{\"artlist\":"+artStr+",\"worklist\":"+worksStr+"}");
}
}
| DreamCoord/DreamCMS | app/controllers/admin/Banner.java | 959 | //检查目录写权限 | line_comment | zh-cn | package controllers.admin;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import models.mag_article;
import models.mag_banner;
import models.mag_works;
import models.mag_worksclass;
import play.Play;
import play.libs.Files;
import play.mvc.Controller;
import com.alibaba.fastjson.JSON;
public class Banner extends Controller{
public static void allBanner(){
mag_banner banner = new mag_banner();
renderJSON("{\"data\":"+banner.allBanner()+"}");
}
public static void addBanner(String title,String remark,File image,String artclass ,String ardid){
System.out.println(title);
System.out.println(remark);
System.out.println(image);
System.out.println(artclass);
System.out.println(ardid);
//文件保存目录路径
String savePath = Play.applicationPath.toString()+Play.configuration.getProperty("newsImg.savePath", "/public/upload/");
//文件保存目录URL
String saveUrl = Play.configuration.getProperty("newsImg.savePath", "/public/upload/");
if (image != null) {
//检查目录
File uploadDir = new File(savePath);
if(!uploadDir.isDirectory()){
renderJSON("{\"state\":\"上传目录不存在。\"}");
return;
}
//检查 <SUF>
if(!uploadDir.canWrite()){
renderJSON("{\"state\":\"上传目录没有写权限。\"}");
return;
}
String ymd = "banner";
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
//检查扩展名
String fileExt = image.getName().substring(image.getName().lastIndexOf(".") + 1).toLowerCase();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
File f = new File(savePath,newFileName);
try {
Files.copy(image,f);
System.out.println(saveUrl + newFileName);
java.text.DateFormat format1 = new java.text.SimpleDateFormat(
"yyyy-MM-dd hh:mm");
String timeStr = format1.format(new Date()).toString();
if(artclass == "作品"){
mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "作品");
banner.save();
}else{
mag_banner banner = new mag_banner( title, remark, saveUrl + newFileName, timeStr,"", ardid, "文章");
banner.save();
}
renderJSON("{\"state\":\"操作成功\"}");
} catch (Exception e) {
e.printStackTrace();
renderJSON("{\"state\":\"上传失败\"}");
}
}else{
renderJSON("{\"state\":\"请选择文件。\"}");
}
renderJSON("{\"status\":\"操作成功\"}");
}
public static void getBanner(){
}
public static void delBanner(){
}
public static void allBannerList(){
List<mag_article> artlist = mag_article.find("order by id desc").fetch();
List<mag_works> worklist = mag_works.find("order by id desc").fetch();
String artStr = JSON.toJSONString(artlist);
String worksStr = JSON.toJSONString(worklist);
renderJSON("{\"artlist\":"+artStr+",\"worklist\":"+worksStr+"}");
}
}
| false | 773 | 5 | 959 | 5 | 970 | 5 | 959 | 5 | 1,252 | 12 | false | false | false | false | false | true |
36160_53 | package cwp.moneycharge.dao;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.cwp.cmoneycharge.R;
import java.util.ArrayList;
import java.util.List;
import cwp.moneycharge.model.Tb_ptype;
//收入类型的数据库
public class PtypeDAO {
// (_id INTEGER NOT NULL PRIMARY KEY,no not null integer ,typename
// varchar(50)
private DBOpenHelper helper;// 创建DBOpenHelper对象
private SQLiteDatabase db;// 创建SQLiteDatabase对象
int[] imageId = new int[] { R.drawable.icon_spjs_zwwc,
R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc,
R.drawable.icon_spjs_zwwc, R.drawable.icon_jjwy_rcyp,
R.drawable.icon_xxyl_wg, R.drawable.icon_yfsp,
R.drawable.icon_rqwl_slqk, R.drawable.icon_jltx_sjf,
R.drawable.icon_spjs, R.drawable.icon_jrbx_ajhk,
R.drawable.icon_jrbx, R.drawable.icon_xcjt_dczc,
R.drawable.icon_qtzx, R.drawable.icon_jrbx_lxzc, R.drawable.yysb };
public PtypeDAO(Context context) {
// TODO Auto-generated constructor stub
helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象
}
/**
* 新增收入类型
*
* @param tb_ptype
*/
public void add(Tb_ptype tb_ptype) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL(
"insert into tb_ptype (_id,no,typename) values (?,?,?)",
new Object[] { tb_ptype.get_id(), tb_ptype.getNo(),
tb_ptype.getTypename() });// 执行添加支出类型操作
}
/**
* 修改收入类型
*
* @param tb_ptype
*/
public void modify(Tb_ptype tb_ptype) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL(
"update Tb_ptype set typename = ? where _id = ? and no=?",
new Object[] { tb_ptype.get_id(), tb_ptype.getNo(),
tb_ptype.getTypename() });// 执行修改支出类型操作
}
public void modifyByName(int id, String old, String now) {
db = helper.getWritableDatabase();
db.execSQL(
"update Tb_ptype set typename = ? where _id = ? and typename=?",
new Object[] { id, now, old });// 执行修改收入类型操作
}
/**
* 删除收入类型
*
* @param ids
*/
public void delete(Integer... ids) {
if (ids.length > 0)// 判断是否存在要删除的id
{
StringBuffer sb = new StringBuffer();// 创建StringBuffer对象
for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合
{
sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中
}
sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id in (?) and no in (" + sb
+ ")", (Object[]) ids);
}
}
public void deleteByName(int id, String typename) {
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id =? and typename=?",
new Object[] { id, typename });
}
public void deleteById(int id) {
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id =? ", new Object[] { id });
}
/**
* 获取收入类型信息
*
* @param start
* 起始位置
* @param count
* 每页显示数量
* @return
*/
public List<Tb_ptype> getScrollData(int id, int start, int count) {
List<Tb_ptype> lisTb_ptype = new ArrayList<Tb_ptype>();// 创建集合对象
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
// 获取所有便签信息
Cursor cursor = db.rawQuery(
"select * from tb_ptype where _id=? order by no limit ?,?",
new String[] { String.valueOf(id), String.valueOf(start),
String.valueOf(count) });
while (cursor.moveToNext())// 遍历所有的便签信息
{
// 将遍历到的便签信息添加到集合中
lisTb_ptype.add(new Tb_ptype(cursor.getInt(cursor
.getColumnIndex("_id")), cursor.getInt(cursor
.getColumnIndex("no")), cursor.getString(cursor
.getColumnIndex("typename"))));
}
return lisTb_ptype;// 返回集合
}
/**
* 获取总记录数
*
* @return
*/
public long getCount() {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery("select count(no) from tb_ptype", null);// 获取支出类型的记录数
if (cursor.moveToNext())// 判断Cursor中是否有数据
{
return cursor.getLong(0);// 返回总记录数
}
return 0;// 如果没有数据,则返回0
}
public long getCount(int id) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select count(no) from tb_ptype where _id=?",
new String[] { String.valueOf(id) });// 获取收入信息的记录数
if (cursor.moveToNext())// 判断Cursor中是否有数据
{
return cursor.getLong(0);// 返回总记录数
}
return 0;// 如果没有数据,则返回0
}
/**
* 获取便签最大编号
*
* @return
*/
public int getMaxId() {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery("select max(no) from tb_ptype", null);// 获取收入类型表中的最大编号
while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据
return cursor.getInt(0);// 获取访问到的数据,即最大编号
}
return 0;// 如果没有数据,则返回0
}
/**
* 获取类型名数组 param id
*
* @return
* */
public List<String> getPtypeName(int id) {
List<String> lisCharSequence = new ArrayList<String>();// 创建集合对象
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select typename from tb_ptype where _id=?",
new String[] { String.valueOf(id) });// 获取收入类型表中的最大编号
while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据
lisCharSequence.add(cursor.getString(cursor
.getColumnIndex("typename")));
}
return lisCharSequence;// 如果没有数据,则返回0
}
public String getOneName(int id, int no) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select typename from tb_ptype where _id=? and no=?",
new String[] { String.valueOf(id), String.valueOf(no) });
if (cursor.moveToNext()) {
return cursor.getString(cursor.getColumnIndex("typename"));
}
return "";
}
public int getOneImg(int id, int no) {
if (imageId.length < no) {
return imageId[14];
}
return imageId[no - 1];
}
public void initData(int id) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL("delete from tb_ptype where _id=?",
new String[] { String.valueOf(id) }); // 确保无该id
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "1", "早餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "2", "午餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "3", "晚餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "4", "夜宵" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "5", "生活用品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "6", "工作用品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "7", "衣服" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "8", "应酬" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "9", "电子产品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "10", "食品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "11", "租金" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "12", "股票" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "13", "打的" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "14", "基金" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "15", "其他" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "16", "语音识别" });
}
}
| Dreamer206602/QuickMoney | app/src/main/java/cwp/moneycharge/dao/PtypeDAO.java | 2,796 | // 获取收入类型表中的最大编号 | line_comment | zh-cn | package cwp.moneycharge.dao;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.cwp.cmoneycharge.R;
import java.util.ArrayList;
import java.util.List;
import cwp.moneycharge.model.Tb_ptype;
//收入类型的数据库
public class PtypeDAO {
// (_id INTEGER NOT NULL PRIMARY KEY,no not null integer ,typename
// varchar(50)
private DBOpenHelper helper;// 创建DBOpenHelper对象
private SQLiteDatabase db;// 创建SQLiteDatabase对象
int[] imageId = new int[] { R.drawable.icon_spjs_zwwc,
R.drawable.icon_spjs_zwwc, R.drawable.icon_spjs_zwwc,
R.drawable.icon_spjs_zwwc, R.drawable.icon_jjwy_rcyp,
R.drawable.icon_xxyl_wg, R.drawable.icon_yfsp,
R.drawable.icon_rqwl_slqk, R.drawable.icon_jltx_sjf,
R.drawable.icon_spjs, R.drawable.icon_jrbx_ajhk,
R.drawable.icon_jrbx, R.drawable.icon_xcjt_dczc,
R.drawable.icon_qtzx, R.drawable.icon_jrbx_lxzc, R.drawable.yysb };
public PtypeDAO(Context context) {
// TODO Auto-generated constructor stub
helper = new DBOpenHelper(context);// 初始化DBOpenHelper对象
}
/**
* 新增收入类型
*
* @param tb_ptype
*/
public void add(Tb_ptype tb_ptype) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL(
"insert into tb_ptype (_id,no,typename) values (?,?,?)",
new Object[] { tb_ptype.get_id(), tb_ptype.getNo(),
tb_ptype.getTypename() });// 执行添加支出类型操作
}
/**
* 修改收入类型
*
* @param tb_ptype
*/
public void modify(Tb_ptype tb_ptype) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL(
"update Tb_ptype set typename = ? where _id = ? and no=?",
new Object[] { tb_ptype.get_id(), tb_ptype.getNo(),
tb_ptype.getTypename() });// 执行修改支出类型操作
}
public void modifyByName(int id, String old, String now) {
db = helper.getWritableDatabase();
db.execSQL(
"update Tb_ptype set typename = ? where _id = ? and typename=?",
new Object[] { id, now, old });// 执行修改收入类型操作
}
/**
* 删除收入类型
*
* @param ids
*/
public void delete(Integer... ids) {
if (ids.length > 0)// 判断是否存在要删除的id
{
StringBuffer sb = new StringBuffer();// 创建StringBuffer对象
for (int i = 0; i < ids.length - 1; i++)// 遍历要删除的id集合
{
sb.append('?').append(',');// 将删除条件添加到StringBuffer对象中
}
sb.deleteCharAt(sb.length() - 1);// 去掉最后一个“,“字符
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id in (?) and no in (" + sb
+ ")", (Object[]) ids);
}
}
public void deleteByName(int id, String typename) {
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id =? and typename=?",
new Object[] { id, typename });
}
public void deleteById(int id) {
db = helper.getWritableDatabase();// 创建SQLiteDatabase对象
// 执行删除便签信息操作
db.execSQL("delete from tb_ptype where _id =? ", new Object[] { id });
}
/**
* 获取收入类型信息
*
* @param start
* 起始位置
* @param count
* 每页显示数量
* @return
*/
public List<Tb_ptype> getScrollData(int id, int start, int count) {
List<Tb_ptype> lisTb_ptype = new ArrayList<Tb_ptype>();// 创建集合对象
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
// 获取所有便签信息
Cursor cursor = db.rawQuery(
"select * from tb_ptype where _id=? order by no limit ?,?",
new String[] { String.valueOf(id), String.valueOf(start),
String.valueOf(count) });
while (cursor.moveToNext())// 遍历所有的便签信息
{
// 将遍历到的便签信息添加到集合中
lisTb_ptype.add(new Tb_ptype(cursor.getInt(cursor
.getColumnIndex("_id")), cursor.getInt(cursor
.getColumnIndex("no")), cursor.getString(cursor
.getColumnIndex("typename"))));
}
return lisTb_ptype;// 返回集合
}
/**
* 获取总记录数
*
* @return
*/
public long getCount() {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery("select count(no) from tb_ptype", null);// 获取支出类型的记录数
if (cursor.moveToNext())// 判断Cursor中是否有数据
{
return cursor.getLong(0);// 返回总记录数
}
return 0;// 如果没有数据,则返回0
}
public long getCount(int id) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select count(no) from tb_ptype where _id=?",
new String[] { String.valueOf(id) });// 获取收入信息的记录数
if (cursor.moveToNext())// 判断Cursor中是否有数据
{
return cursor.getLong(0);// 返回总记录数
}
return 0;// 如果没有数据,则返回0
}
/**
* 获取便签最大编号
*
* @return
*/
public int getMaxId() {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery("select max(no) from tb_ptype", null);// 获取收入类型表中的最大编号
while (cursor.moveToLast()) {// 访问Cursor中的最后一条数据
return cursor.getInt(0);// 获取访问到的数据,即最大编号
}
return 0;// 如果没有数据,则返回0
}
/**
* 获取类型名数组 param id
*
* @return
* */
public List<String> getPtypeName(int id) {
List<String> lisCharSequence = new ArrayList<String>();// 创建集合对象
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select typename from tb_ptype where _id=?",
new String[] { String.valueOf(id) });// 获取 <SUF>
while (cursor.moveToNext()) {// 访问Cursor中的最后一条数据
lisCharSequence.add(cursor.getString(cursor
.getColumnIndex("typename")));
}
return lisCharSequence;// 如果没有数据,则返回0
}
public String getOneName(int id, int no) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
Cursor cursor = db.rawQuery(
"select typename from tb_ptype where _id=? and no=?",
new String[] { String.valueOf(id), String.valueOf(no) });
if (cursor.moveToNext()) {
return cursor.getString(cursor.getColumnIndex("typename"));
}
return "";
}
public int getOneImg(int id, int no) {
if (imageId.length < no) {
return imageId[14];
}
return imageId[no - 1];
}
public void initData(int id) {
db = helper.getWritableDatabase();// 初始化SQLiteDatabase对象
db.execSQL("delete from tb_ptype where _id=?",
new String[] { String.valueOf(id) }); // 确保无该id
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "1", "早餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "2", "午餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "3", "晚餐" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "4", "夜宵" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "5", "生活用品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "6", "工作用品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "7", "衣服" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "8", "应酬" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "9", "电子产品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "10", "食品" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "11", "租金" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "12", "股票" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "13", "打的" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "14", "基金" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "15", "其他" });
db.execSQL("insert into tb_ptype(_id,no,typename) values(?,?,?)",
new String[] { String.valueOf(id), "16", "语音识别" });
}
}
| false | 2,374 | 8 | 2,796 | 9 | 2,756 | 8 | 2,796 | 9 | 3,683 | 15 | false | false | false | false | false | true |
34101_19 |
package net.paoding.analysis;
import java.io.StringReader;
import junit.framework.TestCase;
import net.paoding.analysis.analyzer.PaodingAnalyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
public class AnalyzerTest extends TestCase {
protected PaodingAnalyzer analyzer = new PaodingAnalyzer();
protected StringBuilder sb = new StringBuilder();
protected String dissect(String input) {
try {
TokenStream ts = analyzer.tokenStream("", new StringReader(input));
Token token;
sb.setLength(0);
while ((token = ts.next()) != null) {
sb.append(token.termText()).append('/');
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
/**
*
*/
public void test000() {
String result = dissect("a");
assertEquals("", result);
}
/**
*
*/
public void test001() {
String result = dissect("空格 a 空格");
assertEquals("空格/空格", result);
}
/**
*
*/
public void test002() {
String result = dissect("A座");
assertEquals("a座", result);
}
/**
*
*/
public void test003() {
String result = dissect("u盘");
assertEquals("u盘", result);
}
public void test004() {
String result = dissect("刚买的u盘的容量");
assertEquals("刚/买的/u盘/容量", result);
}
public void test005() {
String result = dissect("K歌之王很好听");
assertEquals("k歌之王/很好/好听", result);
}
// --------------------------------------------------------------
// 仅包含词语的句子分词策略
// --------------------------------------------------------------
/**
* 句子全由词典词语组成,但词语之间没有包含、交叉关系
*/
public void test100() {
String result = dissect("台北中文国际");
assertEquals("台北/中文/国际", result);
}
/**
* 句子全由词典词语组成,但词语之间有包含关系
*/
public void test101() {
String result = dissect("北京首都机场");
assertEquals("北京/首都/机场", result);
}
/**
* 句子全由词典词语组成,但词语之间有交叉关系
*/
public void test102() {
String result = dissect("东西已经拍卖了");
assertEquals("东西/已经/拍卖/卖了", result);
}
/**
* 句子全由词典词语组成,但词语之间有包含、交叉等复杂关系
*/
public void test103() {
String result = dissect("羽毛球拍");
assertEquals("羽毛/羽毛球/球拍", result);
}
// --------------------------------------------------------------
// noise词汇和单字的分词策略
// --------------------------------------------------------------
/**
* 词语之间有一个noise字(的)
*/
public void test200() {
String result = dissect("足球的魅力");
assertEquals("足球/魅力", result);
}
/**
* 词语之间有一个noise词语(因之)
*/
public void test201() {
String result = dissect("主人因之生气");
assertEquals("主人/生气", result);
}
/**
* 词语前后分别有单字和双字的noise词语(与,有关)
*/
public void test202() {
String result = dissect("与谋杀有关");
assertEquals("谋杀", result);
}
/**
* 前有noise词语(哪怕),后面跟随了连续的noise单字(了,你)
*/
public void test203() {
String result = dissect("哪怕朋友背叛了你");
assertEquals("朋友/背叛", result);
}
/**
* 前后连续的noise词汇(虽然,某些),词语中有noise单字(很)
*/
public void test204() {
String result = dissect("虽然某些动物很凶恶");
assertEquals("动物/凶恶", result);
}
// --------------------------------------------------------------
// 词典没有收录的字符串的分词策略
// --------------------------------------------------------------
/**
* 仅1个字的非词汇串(东,西,南,北)
*/
public void test300() {
String result = dissect("东&&西&&南&&北");
assertEquals("东/西/南/北", result);
}
/**
* 仅两个字的非词汇串(古哥,谷歌,收狗,搜狗)
*/
public void test302() {
String result = dissect("古哥&&谷歌&&收狗&&搜狗");
assertEquals("古哥/谷歌/收狗/搜狗", result);
}
/**
* 多个字的非词汇串
*/
public void test303() {
String result = dissect("这是鸟语:玉鱼遇欲雨");
assertEquals("这是/鸟语/玉鱼/鱼遇/遇欲/欲雨", result);
}
/**
* 两个词语之间有一个非词汇的字(真)
*/
public void test304() {
String result = dissect("朋友真背叛了你了!");
assertEquals("朋友/真/背叛", result);
}
/**
* 两个词语之间有一个非词汇的字符串(盒蟹)
*/
public void test305() {
String result = dissect("建设盒蟹社会");
assertEquals("建设/盒蟹/社会", result);
}
/**
* 两个词语之间有多个非词汇的字符串(盒少蟹)
*/
public void test306() {
String result = dissect("建设盒少蟹社会");
assertEquals("建设/盒少/少蟹/社会", result);
}
// --------------------------------------------------------------
// 不包含小数点的汉字数字
// --------------------------------------------------------------
/**
* 单个汉字数字
*/
public void test400() {
String result = dissect("二");
assertEquals("2", result);
}
/**
* 两个汉字数字
*/
public void test61() {
String result = dissect("五六");
assertEquals("56", result);
}
/**
* 多个汉字数字
*/
public void test62() {
String result = dissect("三四五六");
assertEquals("3456", result);
}
/**
* 十三
*/
public void test63() {
String result = dissect("十三");
assertEquals("13", result);
}
/**
* 二千
*/
public void test65() {
String result = dissect("二千");
assertEquals("2000", result);
}
/**
* 两千
*/
public void test651() {
String result = dissect("两千");
assertEquals("2000", result);
}
/**
* 两千
*/
public void test6511() {
String result = dissect("两千个");
assertEquals("2000/个", result);
}
/**
* 2千
*/
public void test652() {
String result = dissect("2千");
assertEquals("2000", result);
}
/**
*
*/
public void test653() {
String result = dissect("3千万");
assertEquals("30000000", result);
}
/**
*
*/
public void test654() {
String result = dissect("3千万个案例");
assertEquals("30000000/个/案例", result);
}
/**
*
*/
public void test64() {
String result = dissect("千万");
assertEquals("千万", result);
}
public void test66() {
String result = dissect("两两");
assertEquals("两两", result);
}
public void test67() {
String result = dissect("二二");
assertEquals("22", result);
}
public void test68() {
String result = dissect("2.2两");
assertEquals("2.2/两", result);
}
public void test69() {
String result = dissect("二两");
assertEquals("2/两", result);
}
public void test690() {
String result = dissect("2两");
assertEquals("2/两", result);
}
public void test691() {
String result = dissect("2千克");
assertEquals("2000/克", result);
}
public void test692() {
String result = dissect("2公斤");
assertEquals("2/公斤", result);
}
public void test693() {
String result = dissect("2世纪");
assertEquals("2/世纪", result);
}
public void test7() {
String result = dissect("哪怕二");
assertEquals("2", result);
}
} | DrizztLei/code | work/java/ROBOT/src/net/paoding/analysis/AnalyzerTest.java | 2,518 | /**
* 仅两个字的非词汇串(古哥,谷歌,收狗,搜狗)
*/ | block_comment | zh-cn |
package net.paoding.analysis;
import java.io.StringReader;
import junit.framework.TestCase;
import net.paoding.analysis.analyzer.PaodingAnalyzer;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
public class AnalyzerTest extends TestCase {
protected PaodingAnalyzer analyzer = new PaodingAnalyzer();
protected StringBuilder sb = new StringBuilder();
protected String dissect(String input) {
try {
TokenStream ts = analyzer.tokenStream("", new StringReader(input));
Token token;
sb.setLength(0);
while ((token = ts.next()) != null) {
sb.append(token.termText()).append('/');
}
if (sb.length() > 0) {
sb.setLength(sb.length() - 1);
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
/**
*
*/
public void test000() {
String result = dissect("a");
assertEquals("", result);
}
/**
*
*/
public void test001() {
String result = dissect("空格 a 空格");
assertEquals("空格/空格", result);
}
/**
*
*/
public void test002() {
String result = dissect("A座");
assertEquals("a座", result);
}
/**
*
*/
public void test003() {
String result = dissect("u盘");
assertEquals("u盘", result);
}
public void test004() {
String result = dissect("刚买的u盘的容量");
assertEquals("刚/买的/u盘/容量", result);
}
public void test005() {
String result = dissect("K歌之王很好听");
assertEquals("k歌之王/很好/好听", result);
}
// --------------------------------------------------------------
// 仅包含词语的句子分词策略
// --------------------------------------------------------------
/**
* 句子全由词典词语组成,但词语之间没有包含、交叉关系
*/
public void test100() {
String result = dissect("台北中文国际");
assertEquals("台北/中文/国际", result);
}
/**
* 句子全由词典词语组成,但词语之间有包含关系
*/
public void test101() {
String result = dissect("北京首都机场");
assertEquals("北京/首都/机场", result);
}
/**
* 句子全由词典词语组成,但词语之间有交叉关系
*/
public void test102() {
String result = dissect("东西已经拍卖了");
assertEquals("东西/已经/拍卖/卖了", result);
}
/**
* 句子全由词典词语组成,但词语之间有包含、交叉等复杂关系
*/
public void test103() {
String result = dissect("羽毛球拍");
assertEquals("羽毛/羽毛球/球拍", result);
}
// --------------------------------------------------------------
// noise词汇和单字的分词策略
// --------------------------------------------------------------
/**
* 词语之间有一个noise字(的)
*/
public void test200() {
String result = dissect("足球的魅力");
assertEquals("足球/魅力", result);
}
/**
* 词语之间有一个noise词语(因之)
*/
public void test201() {
String result = dissect("主人因之生气");
assertEquals("主人/生气", result);
}
/**
* 词语前后分别有单字和双字的noise词语(与,有关)
*/
public void test202() {
String result = dissect("与谋杀有关");
assertEquals("谋杀", result);
}
/**
* 前有noise词语(哪怕),后面跟随了连续的noise单字(了,你)
*/
public void test203() {
String result = dissect("哪怕朋友背叛了你");
assertEquals("朋友/背叛", result);
}
/**
* 前后连续的noise词汇(虽然,某些),词语中有noise单字(很)
*/
public void test204() {
String result = dissect("虽然某些动物很凶恶");
assertEquals("动物/凶恶", result);
}
// --------------------------------------------------------------
// 词典没有收录的字符串的分词策略
// --------------------------------------------------------------
/**
* 仅1个字的非词汇串(东,西,南,北)
*/
public void test300() {
String result = dissect("东&&西&&南&&北");
assertEquals("东/西/南/北", result);
}
/**
* 仅两个 <SUF>*/
public void test302() {
String result = dissect("古哥&&谷歌&&收狗&&搜狗");
assertEquals("古哥/谷歌/收狗/搜狗", result);
}
/**
* 多个字的非词汇串
*/
public void test303() {
String result = dissect("这是鸟语:玉鱼遇欲雨");
assertEquals("这是/鸟语/玉鱼/鱼遇/遇欲/欲雨", result);
}
/**
* 两个词语之间有一个非词汇的字(真)
*/
public void test304() {
String result = dissect("朋友真背叛了你了!");
assertEquals("朋友/真/背叛", result);
}
/**
* 两个词语之间有一个非词汇的字符串(盒蟹)
*/
public void test305() {
String result = dissect("建设盒蟹社会");
assertEquals("建设/盒蟹/社会", result);
}
/**
* 两个词语之间有多个非词汇的字符串(盒少蟹)
*/
public void test306() {
String result = dissect("建设盒少蟹社会");
assertEquals("建设/盒少/少蟹/社会", result);
}
// --------------------------------------------------------------
// 不包含小数点的汉字数字
// --------------------------------------------------------------
/**
* 单个汉字数字
*/
public void test400() {
String result = dissect("二");
assertEquals("2", result);
}
/**
* 两个汉字数字
*/
public void test61() {
String result = dissect("五六");
assertEquals("56", result);
}
/**
* 多个汉字数字
*/
public void test62() {
String result = dissect("三四五六");
assertEquals("3456", result);
}
/**
* 十三
*/
public void test63() {
String result = dissect("十三");
assertEquals("13", result);
}
/**
* 二千
*/
public void test65() {
String result = dissect("二千");
assertEquals("2000", result);
}
/**
* 两千
*/
public void test651() {
String result = dissect("两千");
assertEquals("2000", result);
}
/**
* 两千
*/
public void test6511() {
String result = dissect("两千个");
assertEquals("2000/个", result);
}
/**
* 2千
*/
public void test652() {
String result = dissect("2千");
assertEquals("2000", result);
}
/**
*
*/
public void test653() {
String result = dissect("3千万");
assertEquals("30000000", result);
}
/**
*
*/
public void test654() {
String result = dissect("3千万个案例");
assertEquals("30000000/个/案例", result);
}
/**
*
*/
public void test64() {
String result = dissect("千万");
assertEquals("千万", result);
}
public void test66() {
String result = dissect("两两");
assertEquals("两两", result);
}
public void test67() {
String result = dissect("二二");
assertEquals("22", result);
}
public void test68() {
String result = dissect("2.2两");
assertEquals("2.2/两", result);
}
public void test69() {
String result = dissect("二两");
assertEquals("2/两", result);
}
public void test690() {
String result = dissect("2两");
assertEquals("2/两", result);
}
public void test691() {
String result = dissect("2千克");
assertEquals("2000/克", result);
}
public void test692() {
String result = dissect("2公斤");
assertEquals("2/公斤", result);
}
public void test693() {
String result = dissect("2世纪");
assertEquals("2/世纪", result);
}
public void test7() {
String result = dissect("哪怕二");
assertEquals("2", result);
}
} | false | 1,982 | 25 | 2,515 | 33 | 2,355 | 27 | 2,515 | 33 | 3,181 | 44 | false | false | false | false | false | true |
13765_40 | package com.d.greendao;
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;
/**
* GreenDaoGenerator
* Created by D on 2017/4/27.
*/
public class GreenDaoGenerator {
public static void main(String[] args) throws Exception {
// 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。
// 两个参数分别代表:数据库版本号与自动生成代码的包路径。
// Schema schema = new Schema(1, "com.d.music.data.database.greendao.music");
// 当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示:
Schema schema = new Schema(1, "com.d.music.data.database.greendao.bean");
schema.setDefaultJavaPackageDao("com.d.music.data.database.greendao.dao");
// 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。
// schema2.enableActiveEntitiesByDefault();
// schema2.enableKeepSectionsByDefault();
// 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。
addMusic(schema);
addLocalAllMusic(schema);
addCollectionMusic(schema);
addCustomList(schema);
addCustomMusics(schema);
addTransferModel(schema);
// 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录。
// 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。
// 重新运行GreenDaoGenerator时,将此路径更改为本地src路径
new DaoGenerator().generateAll(schema, "D:\\AndroidStudioProjects\\DMusic\\app\\src\\main\\java");
}
/**
* Music - 歌曲
*/
private static void addMusic(Schema schema) {
Entity entity = schema.addEntity("MusicModel"); // 表名
addProperty(entity);
}
/**
* LocalAllMusic - 本地歌曲
*/
private static void addLocalAllMusic(Schema schema) {
Entity entity = schema.addEntity("LocalAllMusic"); // 表名
addProperty(entity);
}
/**
* CollectionMusic - 收藏歌曲
*/
private static void addCollectionMusic(Schema schema) {
Entity entity = schema.addEntity("CollectionMusic"); // 表名
addProperty(entity);
}
/**
* CustomList - 自定义列表
*/
private static void addCustomList(Schema schema) {
Entity entity = schema.addEntity("CustomListModel"); // 表名
entity.addIdProperty().autoincrement(); // id主键自增
entity.addStringProperty("name"); // 歌曲列表名
entity.addLongProperty("count"); // 包含歌曲数
entity.addIntProperty("seq"); // 排序显示序号
entity.addIntProperty("sortType"); // 排序方式(1:按名称排序,2:按时间排序,3:自定义排序)
entity.addIntProperty("pointer"); // 指针:指向数据库相应表
}
/**
* CustomMusic - 自定义歌曲(创建20张)
*/
private static void addCustomMusics(Schema schema) {
for (int i = 0; i < 20; i++) {
Entity entity = schema.addEntity("CustomMusic" + i); // 表名
addProperty(entity);
}
}
/**
* TransferModel - 传输
*/
private static void addTransferModel(Schema schema) {
Entity entity = schema.addEntity("TransferModel"); // 表名
entity.addStringProperty("transferId").primaryKey(); // 文件完整路径---主键
entity.addIntProperty("transferType");
entity.addIntProperty("transferState");
entity.addLongProperty("transferCurrentLength");
entity.addLongProperty("transferTotalLength");
entity.addStringProperty("id"); // 文件完整路径
entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等
entity.addIntProperty("seq"); // 自定义序号
entity.addStringProperty("songId"); // 歌曲ID
entity.addStringProperty("songName"); // 歌曲名
entity.addStringProperty("songUrl"); // 歌曲url
entity.addStringProperty("artistId"); // 艺术家ID
entity.addStringProperty("artistName"); // 歌手名
entity.addStringProperty("albumId"); // 专辑ID
entity.addStringProperty("albumName"); // 专辑
entity.addStringProperty("albumUrl"); // 专辑url
entity.addStringProperty("lrcName"); // 歌词名称
entity.addStringProperty("lrcUrl"); // 歌词路径
entity.addLongProperty("fileDuration"); // 歌曲时长
entity.addLongProperty("fileSize"); // 文件大小
entity.addStringProperty("filePostfix"); // 文件后缀类型
entity.addStringProperty("fileFolder"); // 父文件夹绝对路径
entity.addBooleanProperty("isCollected"); // 是否收藏
entity.addLongProperty("timeStamp"); // 时间戳,插入时间
}
/**
* 添加公共字段
*/
private static void addProperty(Entity entity) {
entity.addStringProperty("id").primaryKey(); // 文件完整路径---主键
entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等
entity.addIntProperty("seq"); // 自定义序号
entity.addStringProperty("songId"); // 歌曲ID
entity.addStringProperty("songName"); // 歌曲名
entity.addStringProperty("songUrl"); // 歌曲url
entity.addStringProperty("artistId"); // 艺术家ID
entity.addStringProperty("artistName"); // 歌手名
entity.addStringProperty("albumId"); // 专辑ID
entity.addStringProperty("albumName"); // 专辑
entity.addStringProperty("albumUrl"); // 专辑url
entity.addStringProperty("lrcName"); // 歌词名称
entity.addStringProperty("lrcUrl"); // 歌词路径
entity.addLongProperty("fileDuration"); // 歌曲时长
entity.addLongProperty("fileSize"); // 文件大小
entity.addStringProperty("filePostfix"); // 文件后缀类型
entity.addStringProperty("fileFolder"); // 父文件夹绝对路径
entity.addBooleanProperty("isCollected"); // 是否收藏
entity.addLongProperty("timeStamp"); // 时间戳,插入时间
}
}
| Dsiner/DMusic | lib_greendao_generator/src/main/java/com/d/greendao/GreenDaoGenerator.java | 1,588 | // 父文件夹绝对路径 | line_comment | zh-cn | package com.d.greendao;
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;
/**
* GreenDaoGenerator
* Created by D on 2017/4/27.
*/
public class GreenDaoGenerator {
public static void main(String[] args) throws Exception {
// 正如你所见的,你创建了一个用于添加实体(Entity)的模式(Schema)对象。
// 两个参数分别代表:数据库版本号与自动生成代码的包路径。
// Schema schema = new Schema(1, "com.d.music.data.database.greendao.music");
// 当然,如果你愿意,你也可以分别指定生成的 Bean 与 DAO 类所在的目录,只要如下所示:
Schema schema = new Schema(1, "com.d.music.data.database.greendao.bean");
schema.setDefaultJavaPackageDao("com.d.music.data.database.greendao.dao");
// 模式(Schema)同时也拥有两个默认的 flags,分别用来标示 entity 是否是 activie 以及是否使用 keep sections。
// schema2.enableActiveEntitiesByDefault();
// schema2.enableKeepSectionsByDefault();
// 一旦你拥有了一个 Schema 对象后,你便可以使用它添加实体(Entities)了。
addMusic(schema);
addLocalAllMusic(schema);
addCollectionMusic(schema);
addCustomList(schema);
addCustomMusics(schema);
addTransferModel(schema);
// 最后我们将使用 DAOGenerator 类的 generateAll() 方法自动生成代码,此处你需要根据自己的情况更改输出目录。
// 其实,输出目录的路径可以在 build.gradle 中设置,有兴趣的朋友可以自行搜索,这里就不再详解。
// 重新运行GreenDaoGenerator时,将此路径更改为本地src路径
new DaoGenerator().generateAll(schema, "D:\\AndroidStudioProjects\\DMusic\\app\\src\\main\\java");
}
/**
* Music - 歌曲
*/
private static void addMusic(Schema schema) {
Entity entity = schema.addEntity("MusicModel"); // 表名
addProperty(entity);
}
/**
* LocalAllMusic - 本地歌曲
*/
private static void addLocalAllMusic(Schema schema) {
Entity entity = schema.addEntity("LocalAllMusic"); // 表名
addProperty(entity);
}
/**
* CollectionMusic - 收藏歌曲
*/
private static void addCollectionMusic(Schema schema) {
Entity entity = schema.addEntity("CollectionMusic"); // 表名
addProperty(entity);
}
/**
* CustomList - 自定义列表
*/
private static void addCustomList(Schema schema) {
Entity entity = schema.addEntity("CustomListModel"); // 表名
entity.addIdProperty().autoincrement(); // id主键自增
entity.addStringProperty("name"); // 歌曲列表名
entity.addLongProperty("count"); // 包含歌曲数
entity.addIntProperty("seq"); // 排序显示序号
entity.addIntProperty("sortType"); // 排序方式(1:按名称排序,2:按时间排序,3:自定义排序)
entity.addIntProperty("pointer"); // 指针:指向数据库相应表
}
/**
* CustomMusic - 自定义歌曲(创建20张)
*/
private static void addCustomMusics(Schema schema) {
for (int i = 0; i < 20; i++) {
Entity entity = schema.addEntity("CustomMusic" + i); // 表名
addProperty(entity);
}
}
/**
* TransferModel - 传输
*/
private static void addTransferModel(Schema schema) {
Entity entity = schema.addEntity("TransferModel"); // 表名
entity.addStringProperty("transferId").primaryKey(); // 文件完整路径---主键
entity.addIntProperty("transferType");
entity.addIntProperty("transferState");
entity.addLongProperty("transferCurrentLength");
entity.addLongProperty("transferTotalLength");
entity.addStringProperty("id"); // 文件完整路径
entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等
entity.addIntProperty("seq"); // 自定义序号
entity.addStringProperty("songId"); // 歌曲ID
entity.addStringProperty("songName"); // 歌曲名
entity.addStringProperty("songUrl"); // 歌曲url
entity.addStringProperty("artistId"); // 艺术家ID
entity.addStringProperty("artistName"); // 歌手名
entity.addStringProperty("albumId"); // 专辑ID
entity.addStringProperty("albumName"); // 专辑
entity.addStringProperty("albumUrl"); // 专辑url
entity.addStringProperty("lrcName"); // 歌词名称
entity.addStringProperty("lrcUrl"); // 歌词路径
entity.addLongProperty("fileDuration"); // 歌曲时长
entity.addLongProperty("fileSize"); // 文件大小
entity.addStringProperty("filePostfix"); // 文件后缀类型
entity.addStringProperty("fileFolder"); // 父文 <SUF>
entity.addBooleanProperty("isCollected"); // 是否收藏
entity.addLongProperty("timeStamp"); // 时间戳,插入时间
}
/**
* 添加公共字段
*/
private static void addProperty(Entity entity) {
entity.addStringProperty("id").primaryKey(); // 文件完整路径---主键
entity.addIntProperty("type"); // 类型:本地、百度、网易、QQ等
entity.addIntProperty("seq"); // 自定义序号
entity.addStringProperty("songId"); // 歌曲ID
entity.addStringProperty("songName"); // 歌曲名
entity.addStringProperty("songUrl"); // 歌曲url
entity.addStringProperty("artistId"); // 艺术家ID
entity.addStringProperty("artistName"); // 歌手名
entity.addStringProperty("albumId"); // 专辑ID
entity.addStringProperty("albumName"); // 专辑
entity.addStringProperty("albumUrl"); // 专辑url
entity.addStringProperty("lrcName"); // 歌词名称
entity.addStringProperty("lrcUrl"); // 歌词路径
entity.addLongProperty("fileDuration"); // 歌曲时长
entity.addLongProperty("fileSize"); // 文件大小
entity.addStringProperty("filePostfix"); // 文件后缀类型
entity.addStringProperty("fileFolder"); // 父文件夹绝对路径
entity.addBooleanProperty("isCollected"); // 是否收藏
entity.addLongProperty("timeStamp"); // 时间戳,插入时间
}
}
| false | 1,513 | 8 | 1,588 | 7 | 1,572 | 5 | 1,588 | 7 | 2,073 | 18 | false | false | false | false | false | true |