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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
28512_7 | /*
Copyright [2020] [https://www.xiaonuo.vip]
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.
Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处,作者声明等。
4.分发源码时候,请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点,可申请商业授权,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip
*/
package vip.xiaonuo.modular.lightup.entity;
import com.baomidou.mybatisplus.annotation.*;
import vip.xiaonuo.core.pojo.base.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import cn.afterturn.easypoi.excel.annotation.Excel;
/**
* 课程设置表
*
* @author leiw
* @date 2022-03-03 13:21:35
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("lightup_course")
public class LightupCourse extends BaseEntity {
/**
* 主键id
*/
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/**
* 课程名称
*/
@Excel(name = "课程名称")
private String courseName;
/**
* 授课教师id
*/
@Excel(name = "授课教师用户")
private String teacherAccount;
/**
* 授课班级id
*/
@Excel(name = "授课班级名称")
private String className;
/**
* 授课星期
*/
@Excel(name = "授课星期")
private String weakday;
/**
* 授课节数数组,每天哪几节课
*/
@Excel(name = "授课节数数组,每天哪几节课")
private String beginTime;
/**
*
*/
@Excel(name = "")
private String endTime;
/**
* 状态(字典 0正常 1停用 2删除)
*/
@Excel(name = "状态(字典 0正常 1停用 2删除)")
private Integer delStat;
/**
* 默认打卡状态,1,允许打卡;2,禁止打卡
*/
@Excel(name = "默认打卡状态,1,允许打卡;2,禁止打卡")
private Integer clockInStatus;
/**
* 备注
*/
@Excel(name = "备注")
private String remark;
}
| cckmit/lightup_public | lightup-main/src/main/java/vip/xiaonuo/modular/lightup/entity/LightupCourse.java | 820 | /**
* 授课节数数组,每天哪几节课
*/ | block_comment | zh-cn | /*
Copyright [2020] [https://www.xiaonuo.vip]
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.
Snowy采用APACHE LICENSE 2.0开源协议,您在使用过程中,需要注意以下几点:
1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处,作者声明等。
4.分发源码时候,请注明软件出处 https://gitee.com/xiaonuobase/snowy
5.在修改包名,模块名称,项目代码等时,请注明软件出处 https://gitee.com/xiaonuobase/snowy
6.若您的项目无法满足以上几点,可申请商业授权,获取Snowy商业授权许可,请在官网购买授权,地址为 https://www.xiaonuo.vip
*/
package vip.xiaonuo.modular.lightup.entity;
import com.baomidou.mybatisplus.annotation.*;
import vip.xiaonuo.core.pojo.base.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import cn.afterturn.easypoi.excel.annotation.Excel;
/**
* 课程设置表
*
* @author leiw
* @date 2022-03-03 13:21:35
*/
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("lightup_course")
public class LightupCourse extends BaseEntity {
/**
* 主键id
*/
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/**
* 课程名称
*/
@Excel(name = "课程名称")
private String courseName;
/**
* 授课教师id
*/
@Excel(name = "授课教师用户")
private String teacherAccount;
/**
* 授课班级id
*/
@Excel(name = "授课班级名称")
private String className;
/**
* 授课星期
*/
@Excel(name = "授课星期")
private String weakday;
/**
* 授课节 <SUF>*/
@Excel(name = "授课节数数组,每天哪几节课")
private String beginTime;
/**
*
*/
@Excel(name = "")
private String endTime;
/**
* 状态(字典 0正常 1停用 2删除)
*/
@Excel(name = "状态(字典 0正常 1停用 2删除)")
private Integer delStat;
/**
* 默认打卡状态,1,允许打卡;2,禁止打卡
*/
@Excel(name = "默认打卡状态,1,允许打卡;2,禁止打卡")
private Integer clockInStatus;
/**
* 备注
*/
@Excel(name = "备注")
private String remark;
}
| false | 726 | 17 | 820 | 18 | 820 | 19 | 820 | 18 | 1,179 | 31 | false | false | false | false | false | true |
60111_3 | package com.pangu.logic.module.battle.model;
import com.pangu.framework.protocol.annotation.Transable;
/**
* 英雄职业类型
*/
@Transable
public enum HeroJobType {
/**
* 坦克
*/
TK,
/**
* 战士
*/
ZS,
/**
* 游侠
*/
YX,
/**
* 刺客
*/
CK,
/**
* 法师
*/
FS,
/**
* 术士
*/
SS,
/**
* 牧师
*/
MS,
/**
* 巫师
*/
WS
}
| cckmit/pangu | logic/src/main/java/com/pangu/logic/module/battle/model/HeroJobType.java | 163 | /**
* 游侠
*/ | block_comment | zh-cn | package com.pangu.logic.module.battle.model;
import com.pangu.framework.protocol.annotation.Transable;
/**
* 英雄职业类型
*/
@Transable
public enum HeroJobType {
/**
* 坦克
*/
TK,
/**
* 战士
*/
ZS,
/**
* 游侠
<SUF>*/
YX,
/**
* 刺客
*/
CK,
/**
* 法师
*/
FS,
/**
* 术士
*/
SS,
/**
* 牧师
*/
MS,
/**
* 巫师
*/
WS
}
| false | 147 | 9 | 163 | 9 | 174 | 9 | 163 | 9 | 217 | 14 | false | false | false | false | false | true |
46694_14 | package com.ater.common.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**有关预产期计算的算法
* @author 大师♂罗莊
*
*/
public class PregnancyHelp {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// 请输入您的最后一次来月经的时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdf.parse("2018-6-18");
Calendar d = Calendar.getInstance();
d.setTime(d1);
setValue(d);
getbornmanual(d);
getBorn("2018-6-21");
getCurrent("2018-6-21");
}
/**
* @param localCalendar1
* 末次月经时间
* @throws ParseException
*/
private static void setValue(Calendar localCalendar1) throws ParseException {
// 取今天时间
Calendar Calendartoday = Calendar.getInstance();
// 克隆一个保存下
Calendar Calendarborn = (Calendar) localCalendar1.clone();
// 取今天和末次月经时间相差多少天
long daysBetweennumber = daysBetween(localCalendar1.getTime(),
Calendartoday.getTime());
// 算出多少周
int WeekBetweennumber = (int) daysBetweennumber / 7;
// 零多少天
long i1 = (daysBetweennumber + 1) % 7;
// 电脑计算预产期,只需在末次月经第一天加上9个月零1周(280天)即可
Calendarborn.add(Calendar.DAY_OF_MONTH, 280);
// 计算预产期距离今天还有几天
long borndayBetween = -1
+ daysBetween(Calendartoday.getTime(), Calendarborn.getTime());
// 为输出年月日做准备
int bornyear = Calendarborn.get(Calendar.YEAR);
int bornmonth = 1 + Calendarborn.get(Calendar.MONTH);
// MONTH加1的原因: public static final int MONTH 指示月份的 get 和 set
// 的字段数字。这是一个特定于日历的值。在格里高利历和罗马儒略历中一年中的第一个月是 JANUARY,它为 0;
// 最后一个月取决于一年中的月份数。 简单来说,因为这个值的初始值是0,因此我们要用它来表示正确的月份时就需要加1。
int bornday = Calendarborn.get(Calendar.DAY_OF_MONTH);
System.out.println("您已经怀孕" + daysBetweennumber + "天");
String current = (WeekBetweennumber + "周" + i1 + "天");
System.out.println("怀孕周数" + current);
getMediMonthSpace(WeekBetweennumber);
System.out.println("怀孕月数(直接减去法)"
+ getMonthSpace(localCalendar1, Calendartoday) + "个月");
String born = (borndayBetween + "天");
System.out.println("距离宝宝出生还有" + born);
String borndayString = (String.valueOf(bornyear) + "年"
+ String.valueOf(bornmonth) + "月" + String.valueOf(bornday) + "日");
System.out.println("预产期为" + borndayString);
Calendarbornmanual(localCalendar1);
}
/**
* 计算方法:从末次月经第一天算起,月份减3,如不够时则加9,日数加7。
*
* @param cal
* 从末次月经
*/
static void Calendarbornmanual(Calendar cal) {
Calendar temp = (Calendar) cal.clone();
int month1 = temp.get(Calendar.MONTH) + 1;
if (month1 < 3) {
temp.add(Calendar.MONTH, 9);
} else {
temp.add(Calendar.MONTH, -3);
temp.add(Calendar.YEAR, 1);
}
temp.add(Calendar.DAY_OF_MONTH, 7);
System.out.println("人手工计算的预产期为");
outprint(temp);
}
//计算方法计算预产期
public static Date getbornmanual(Calendar cal) {
Calendar temp = (Calendar) cal.clone();
int month1 = temp.get(Calendar.MONTH) + 1;
if (month1 < 3) {
temp.add(Calendar.MONTH, 9);
} else {
temp.add(Calendar.MONTH, -3);
temp.add(Calendar.YEAR, 1);
}
temp.add(Calendar.DAY_OF_MONTH, 7);
System.out.println("人手工计算的预产期为");
outprint(temp);
return temp.getTime();
}
//获取怀孕周数
public static String getCurrent(String pregnancyDate) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(df.parse(pregnancyDate));
calendar.add(Calendar.MONTH, -9);// 月份减9
calendar.add(Calendar.DATE, -7);// 日期减15
calendar.getTime();
// 取今天时间
Calendar Calendartoday = Calendar.getInstance();
// 克隆一个保存下
Calendar Calendarborn = (Calendar) calendar.clone();
long daysBetweennumber = daysBetween( calendar.getTime(),Calendartoday.getTime());
// 算出多少周
int weekBetweennumber = (int) daysBetweennumber / 7;
int i1=(int) daysBetweennumber % 7;
System.out.println("您已经怀孕" + daysBetweennumber + "天");
String current = ("孕"+weekBetweennumber + "周" + i1 + "天");
System.out.println("怀孕周数" + current);
return current;
}
//获取预产期距离今天还有几天
public static long getBorn(String pregnancyDate ) throws ParseException {
// 取今天时间
Calendar Calendartoday = Calendar.getInstance();
// 克隆一个保存下
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(df.parse(pregnancyDate));
Calendar Calendarborn = (Calendar) calendar.clone();
// 计算预产期距离今天还有几天
long borndayBetween =
daysBetween(Calendartoday.getTime(), calendar.getTime());
return borndayBetween;
}
/**
* @param pregnancyDate
* 怀孕多少周
* 预产期减9个月15天 得到怀孕期
和当前日期相减
得到怀孕天数
除7 得到周数
* @throws ParseException
*/
public static int getWeek(String pregnancyDate ) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(df.parse(pregnancyDate));
calendar.add(Calendar.MONTH, -9);// 月份减1
calendar.add(Calendar.DATE, -7);// 日期减1
calendar.getTime();
// 取今天时间
Calendar Calendartoday = Calendar.getInstance();
// 克隆一个保存下
Calendar Calendarborn = (Calendar) calendar.clone();
long daysBetweennumber = daysBetween( calendar.getTime(),Calendartoday.getTime());
// 算出多少周
int weekBetweennumber = (int) daysBetweennumber / 7;
System.out.println("周" + weekBetweennumber);
return weekBetweennumber;
}
/**
* 计算两个日期之间相差的天数 需要用calendar,因为Date返回的永远是UTC时间,也就是时区永远比我们晚8个小时。
*
* @param smdate
* 较小的时间
* @param bdate
* 较大的时间
* @return 相差天数
* @throws ParseException
*/
public static long daysBetween(Date smdate, Date bdate)
throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
smdate = sdf.parse(sdf.format(smdate));
bdate = sdf.parse(sdf.format(bdate));
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return between_days;
}
static void outprint(Calendar cal) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// 打印
System.out.println(dateFormat.format(cal.getTime()));
}
/**
* 有人问我32w+(32周)怀孕几个月
*
* @param week
* 输入周数
*/
public static void getMediMonthSpace(int week) {
// 此算法同原昆明某三甲医院产科主任算法一致,所以为什么我的算法和她医生算出来的一致
int month = week * 7 / 30;// 周数算出月数,可以按28天或者30天算
int weekleave = week * 7 % 30;// 周数算出剩下的天数
// 也可以通过/7算出周数,大家自己去补充了
System.out.print("怀孕月数(计算法)" + month + "个月");
System.out.println(weekleave + "天");
}
/**
* 算两个日期差几个月,不能用Calendar.MONTH直接相减,否则2012年11月和2013年11月就是0
*
* @param scalendar
* 日期1
* @param calendar
* 日期2
* @return 两个日期差几个月
*/
public static int getMonthSpace(Calendar scalendar, Calendar calendar) {
int year1 = calendar.get(Calendar.YEAR);
int year2 = scalendar.get(Calendar.YEAR);
int month1 = calendar.get(Calendar.MONTH);
int month2 = scalendar.get(Calendar.MONTH);
int count = 0;
if (year1 == year2 && month1 > month2) {
count = month1 - month2;
} else if (year1 == year2 && month1 < month2) {
count = month2 - month1;
} else if (year1 > year2 && month1 > month2) {
count = (year1 - year2) * 12 + (month1 - month2);
} else if (year1 > year2 && month1 < month2) {
count = (year1 - year1) * 12 + (month2 - month1);
} else if (year1 < year2 && month1 > month2) {
count = (year2 - year1) * 12 + month1 - month2;
} else if (year1 < year2 && month1 < month2) {
count = (year2 - year1) * 12 + month2 - month1;
}
if (count < 0) {
count = Math.abs(count);
}
return count;
}
}
| cckmit/yangle-java | src/main/java/com/ater/common/utils/PregnancyHelp.java | 2,748 | // 最后一个月取决于一年中的月份数。 简单来说,因为这个值的初始值是0,因此我们要用它来表示正确的月份时就需要加1。 | line_comment | zh-cn | package com.ater.common.utils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**有关预产期计算的算法
* @author 大师♂罗莊
*
*/
public class PregnancyHelp {
/**
* @param args
* @throws ParseException
*/
public static void main(String[] args) throws ParseException {
// 请输入您的最后一次来月经的时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdf.parse("2018-6-18");
Calendar d = Calendar.getInstance();
d.setTime(d1);
setValue(d);
getbornmanual(d);
getBorn("2018-6-21");
getCurrent("2018-6-21");
}
/**
* @param localCalendar1
* 末次月经时间
* @throws ParseException
*/
private static void setValue(Calendar localCalendar1) throws ParseException {
// 取今天时间
Calendar Calendartoday = Calendar.getInstance();
// 克隆一个保存下
Calendar Calendarborn = (Calendar) localCalendar1.clone();
// 取今天和末次月经时间相差多少天
long daysBetweennumber = daysBetween(localCalendar1.getTime(),
Calendartoday.getTime());
// 算出多少周
int WeekBetweennumber = (int) daysBetweennumber / 7;
// 零多少天
long i1 = (daysBetweennumber + 1) % 7;
// 电脑计算预产期,只需在末次月经第一天加上9个月零1周(280天)即可
Calendarborn.add(Calendar.DAY_OF_MONTH, 280);
// 计算预产期距离今天还有几天
long borndayBetween = -1
+ daysBetween(Calendartoday.getTime(), Calendarborn.getTime());
// 为输出年月日做准备
int bornyear = Calendarborn.get(Calendar.YEAR);
int bornmonth = 1 + Calendarborn.get(Calendar.MONTH);
// MONTH加1的原因: public static final int MONTH 指示月份的 get 和 set
// 的字段数字。这是一个特定于日历的值。在格里高利历和罗马儒略历中一年中的第一个月是 JANUARY,它为 0;
// 最后 <SUF>
int bornday = Calendarborn.get(Calendar.DAY_OF_MONTH);
System.out.println("您已经怀孕" + daysBetweennumber + "天");
String current = (WeekBetweennumber + "周" + i1 + "天");
System.out.println("怀孕周数" + current);
getMediMonthSpace(WeekBetweennumber);
System.out.println("怀孕月数(直接减去法)"
+ getMonthSpace(localCalendar1, Calendartoday) + "个月");
String born = (borndayBetween + "天");
System.out.println("距离宝宝出生还有" + born);
String borndayString = (String.valueOf(bornyear) + "年"
+ String.valueOf(bornmonth) + "月" + String.valueOf(bornday) + "日");
System.out.println("预产期为" + borndayString);
Calendarbornmanual(localCalendar1);
}
/**
* 计算方法:从末次月经第一天算起,月份减3,如不够时则加9,日数加7。
*
* @param cal
* 从末次月经
*/
static void Calendarbornmanual(Calendar cal) {
Calendar temp = (Calendar) cal.clone();
int month1 = temp.get(Calendar.MONTH) + 1;
if (month1 < 3) {
temp.add(Calendar.MONTH, 9);
} else {
temp.add(Calendar.MONTH, -3);
temp.add(Calendar.YEAR, 1);
}
temp.add(Calendar.DAY_OF_MONTH, 7);
System.out.println("人手工计算的预产期为");
outprint(temp);
}
//计算方法计算预产期
public static Date getbornmanual(Calendar cal) {
Calendar temp = (Calendar) cal.clone();
int month1 = temp.get(Calendar.MONTH) + 1;
if (month1 < 3) {
temp.add(Calendar.MONTH, 9);
} else {
temp.add(Calendar.MONTH, -3);
temp.add(Calendar.YEAR, 1);
}
temp.add(Calendar.DAY_OF_MONTH, 7);
System.out.println("人手工计算的预产期为");
outprint(temp);
return temp.getTime();
}
//获取怀孕周数
public static String getCurrent(String pregnancyDate) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(df.parse(pregnancyDate));
calendar.add(Calendar.MONTH, -9);// 月份减9
calendar.add(Calendar.DATE, -7);// 日期减15
calendar.getTime();
// 取今天时间
Calendar Calendartoday = Calendar.getInstance();
// 克隆一个保存下
Calendar Calendarborn = (Calendar) calendar.clone();
long daysBetweennumber = daysBetween( calendar.getTime(),Calendartoday.getTime());
// 算出多少周
int weekBetweennumber = (int) daysBetweennumber / 7;
int i1=(int) daysBetweennumber % 7;
System.out.println("您已经怀孕" + daysBetweennumber + "天");
String current = ("孕"+weekBetweennumber + "周" + i1 + "天");
System.out.println("怀孕周数" + current);
return current;
}
//获取预产期距离今天还有几天
public static long getBorn(String pregnancyDate ) throws ParseException {
// 取今天时间
Calendar Calendartoday = Calendar.getInstance();
// 克隆一个保存下
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(df.parse(pregnancyDate));
Calendar Calendarborn = (Calendar) calendar.clone();
// 计算预产期距离今天还有几天
long borndayBetween =
daysBetween(Calendartoday.getTime(), calendar.getTime());
return borndayBetween;
}
/**
* @param pregnancyDate
* 怀孕多少周
* 预产期减9个月15天 得到怀孕期
和当前日期相减
得到怀孕天数
除7 得到周数
* @throws ParseException
*/
public static int getWeek(String pregnancyDate ) throws ParseException {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(df.parse(pregnancyDate));
calendar.add(Calendar.MONTH, -9);// 月份减1
calendar.add(Calendar.DATE, -7);// 日期减1
calendar.getTime();
// 取今天时间
Calendar Calendartoday = Calendar.getInstance();
// 克隆一个保存下
Calendar Calendarborn = (Calendar) calendar.clone();
long daysBetweennumber = daysBetween( calendar.getTime(),Calendartoday.getTime());
// 算出多少周
int weekBetweennumber = (int) daysBetweennumber / 7;
System.out.println("周" + weekBetweennumber);
return weekBetweennumber;
}
/**
* 计算两个日期之间相差的天数 需要用calendar,因为Date返回的永远是UTC时间,也就是时区永远比我们晚8个小时。
*
* @param smdate
* 较小的时间
* @param bdate
* 较大的时间
* @return 相差天数
* @throws ParseException
*/
public static long daysBetween(Date smdate, Date bdate)
throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
smdate = sdf.parse(sdf.format(smdate));
bdate = sdf.parse(sdf.format(bdate));
Calendar cal = Calendar.getInstance();
cal.setTime(smdate);
long time1 = cal.getTimeInMillis();
cal.setTime(bdate);
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return between_days;
}
static void outprint(Calendar cal) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
// 打印
System.out.println(dateFormat.format(cal.getTime()));
}
/**
* 有人问我32w+(32周)怀孕几个月
*
* @param week
* 输入周数
*/
public static void getMediMonthSpace(int week) {
// 此算法同原昆明某三甲医院产科主任算法一致,所以为什么我的算法和她医生算出来的一致
int month = week * 7 / 30;// 周数算出月数,可以按28天或者30天算
int weekleave = week * 7 % 30;// 周数算出剩下的天数
// 也可以通过/7算出周数,大家自己去补充了
System.out.print("怀孕月数(计算法)" + month + "个月");
System.out.println(weekleave + "天");
}
/**
* 算两个日期差几个月,不能用Calendar.MONTH直接相减,否则2012年11月和2013年11月就是0
*
* @param scalendar
* 日期1
* @param calendar
* 日期2
* @return 两个日期差几个月
*/
public static int getMonthSpace(Calendar scalendar, Calendar calendar) {
int year1 = calendar.get(Calendar.YEAR);
int year2 = scalendar.get(Calendar.YEAR);
int month1 = calendar.get(Calendar.MONTH);
int month2 = scalendar.get(Calendar.MONTH);
int count = 0;
if (year1 == year2 && month1 > month2) {
count = month1 - month2;
} else if (year1 == year2 && month1 < month2) {
count = month2 - month1;
} else if (year1 > year2 && month1 > month2) {
count = (year1 - year2) * 12 + (month1 - month2);
} else if (year1 > year2 && month1 < month2) {
count = (year1 - year1) * 12 + (month2 - month1);
} else if (year1 < year2 && month1 > month2) {
count = (year2 - year1) * 12 + month1 - month2;
} else if (year1 < year2 && month1 < month2) {
count = (year2 - year1) * 12 + month2 - month1;
}
if (count < 0) {
count = Math.abs(count);
}
return count;
}
}
| false | 2,478 | 39 | 2,748 | 44 | 2,787 | 34 | 2,748 | 44 | 3,511 | 68 | false | false | false | false | false | true |
32588_1 | package exam.leetcode381周赛;
/**
* @Author CuiChengLong
* @Date 2024/1/21 11:03
* @Description
*/
public class t_2 {
public int[] countOfPairs(int n, int x, int y) {
int min = Math.min(x, y);
int max = Math.max(x, y);
x = min;
y = max;
int[] res = new int[n];
for (int i = 1; i <= n; i++) {
helpMe(i, n, res, x, y);
}
return res;
}
//每个节点到其他节点的最小路径
private void helpMe(int i, int n, int[] res, int x, int y) {
for (int j = i + 1; j <= n; j++) {
int temp = findMe(i, j, x, y);
res[temp - 1] += 2;
}
}
//i到j的最短路径 错误,笨蛋
private int findMe(int i, int j, int x, int y) {
if (x == y) return j - i;
if (i ==x && j == y) {
return 1;
}
if (i <= x && j >= y) {
int index1 = j - i;
int index2 = (x - i) + 1 + (j - y);
return Math.min(index2, index1);
} else {
int temp1 = Math.abs(x-j) + Math.abs(x - i);
int temp2 = Math.abs(y-j) + Math.abs(y - i);
int min = Math.min(temp2, temp1);
return Math.min(min, j - i);
}
}
public static void main(String[] args) {
t_2 test = new t_2();
test.countOfPairs(5, 1, 5);
}
public int[] countOfPairs2(int n, int x, int y) {
x--;
y--;
int[] ans = new int[n];
int[][] dis = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
dis[i][j] = Math.min(Math.abs(j - x) + Math.abs(i - y) + 1, Math.abs(j - y) + Math.abs(i - x) + 1);
dis[i][j] = Math.min(i - j, dis[i][j]);
ans[dis[i][j] - 1] += 2;
}
}
return ans;
}
//这么简单想不到
private int findMe2(int i, int j, int x, int y) {
int min = Math.min(Math.abs(j - x) + Math.abs(i - y) + 1, Math.abs(j - y) + Math.abs(i - x) + 1);
return Math.min(j - i, min);
}
}
| ccl125/ccl-leetcode | src/exam/leetcode381周赛/t_2.java | 750 | //每个节点到其他节点的最小路径 | line_comment | zh-cn | package exam.leetcode381周赛;
/**
* @Author CuiChengLong
* @Date 2024/1/21 11:03
* @Description
*/
public class t_2 {
public int[] countOfPairs(int n, int x, int y) {
int min = Math.min(x, y);
int max = Math.max(x, y);
x = min;
y = max;
int[] res = new int[n];
for (int i = 1; i <= n; i++) {
helpMe(i, n, res, x, y);
}
return res;
}
//每个 <SUF>
private void helpMe(int i, int n, int[] res, int x, int y) {
for (int j = i + 1; j <= n; j++) {
int temp = findMe(i, j, x, y);
res[temp - 1] += 2;
}
}
//i到j的最短路径 错误,笨蛋
private int findMe(int i, int j, int x, int y) {
if (x == y) return j - i;
if (i ==x && j == y) {
return 1;
}
if (i <= x && j >= y) {
int index1 = j - i;
int index2 = (x - i) + 1 + (j - y);
return Math.min(index2, index1);
} else {
int temp1 = Math.abs(x-j) + Math.abs(x - i);
int temp2 = Math.abs(y-j) + Math.abs(y - i);
int min = Math.min(temp2, temp1);
return Math.min(min, j - i);
}
}
public static void main(String[] args) {
t_2 test = new t_2();
test.countOfPairs(5, 1, 5);
}
public int[] countOfPairs2(int n, int x, int y) {
x--;
y--;
int[] ans = new int[n];
int[][] dis = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
dis[i][j] = Math.min(Math.abs(j - x) + Math.abs(i - y) + 1, Math.abs(j - y) + Math.abs(i - x) + 1);
dis[i][j] = Math.min(i - j, dis[i][j]);
ans[dis[i][j] - 1] += 2;
}
}
return ans;
}
//这么简单想不到
private int findMe2(int i, int j, int x, int y) {
int min = Math.min(Math.abs(j - x) + Math.abs(i - y) + 1, Math.abs(j - y) + Math.abs(i - x) + 1);
return Math.min(j - i, min);
}
}
| false | 681 | 9 | 750 | 9 | 797 | 9 | 750 | 9 | 851 | 17 | false | false | false | false | false | true |
38200_2 | package com.example.common.dict;
import com.example.common.IOUtil;
import com.example.dao.sql.BusinessRepository;
import com.example.dao.sql.CommunityRepository;
import com.example.dao.sql.ShopRepository;
import com.example.entity.Community;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* 字典文件生成工具,从mysql拿数据,生成词典
*/
@Component("mydict")
public class MydictImpl implements Mydict {
static String[] commonEndStrings = new String[]{"写字楼", "办公楼", "商铺", "公寓", "中心", "大厦", "花园", "小区"};
private Logger logger = Logger.getLogger(IOUtil.class);
@Autowired
private IOUtil ioUtil;
@Autowired
private ShopRepository shopRepository;
@Autowired
private BusinessRepository businessRepository;
@Autowired
private CommunityRepository communityRepository;
public static boolean isNumeric(String str) {
for (int i = str.length(); --i >= 0; ) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static int getFirstNumOffset(String str) {
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
return i;
}
}
return -1;
}
public static String getWithOutCommonEndName(String str) {
for (int i = 0; i < commonEndStrings.length; i++) {
int offset = str.indexOf(commonEndStrings[i]);
if (offset != -1) {
return str.substring(0, offset);
}
}
return str;
}
public static String[] splitByFirstNum(String str) {
int offset = getFirstNumOffset(str);
if (getFirstNumOffset(str) <= 0) {
return null;
} else {
return new String[]{str.substring(0, offset), str.substring(offset)};
}
}
public List<String> getDictWord() {
long count = communityRepository.count();
List<String> ls = new ArrayList<>(((int) count) * 2);
try (Stream<Community> stream = communityRepository.searchAll()) {
stream.forEach(shop -> {
String name = shop.getName();
String shortname = MydictImpl.getWithOutCommonEndName(name);
ls.add(name);
if (shortname.length() != name.length()) {
ls.add(shortname);
}
String[] subarrs = MydictImpl.splitByFirstNum(shop.getName());
if (subarrs == null) {
} else {
if (!Character.isDigit(subarrs[0].charAt(0))) {
System.out.println(subarrs[0].charAt(0));
ls.add(subarrs[0]);
ls.add(subarrs[1]);
}
}
});
} catch (Exception e) {
logger.warn("从数据库加载字典失败," + e);
}
return ls;
}
@Override
public Boolean saveDictToFile(List<String> dics, String path) {
return ioUtil.saveCollectionToTxt(dics, path);
}
//从本地文件路径获取
//如果没有则从数据库取
@Override
public List<String> LoadDictFromFile(String path) {
List<String> ls = ioUtil.readLineListWithLessMemory(path);
if (ls == null || ls.size() == 0) {
System.out.println("get dict begin ");
ls = getDictWord();
System.out.println("get dict end ");
saveDictToFile(ls, path);
System.out.println("save dict end");
return ls;
}
return ls;
}
@Override
public List<String> LoadDictFromFile() {
return this.LoadDictFromFile(this.getClass().getClassLoader().getResource("").getPath());
}
}
| cclient/spring-boot-es-jpa-proxy | src/main/java/com/example/common/dict/MydictImpl.java | 1,003 | //如果没有则从数据库取
| line_comment | zh-cn | package com.example.common.dict;
import com.example.common.IOUtil;
import com.example.dao.sql.BusinessRepository;
import com.example.dao.sql.CommunityRepository;
import com.example.dao.sql.ShopRepository;
import com.example.entity.Community;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* 字典文件生成工具,从mysql拿数据,生成词典
*/
@Component("mydict")
public class MydictImpl implements Mydict {
static String[] commonEndStrings = new String[]{"写字楼", "办公楼", "商铺", "公寓", "中心", "大厦", "花园", "小区"};
private Logger logger = Logger.getLogger(IOUtil.class);
@Autowired
private IOUtil ioUtil;
@Autowired
private ShopRepository shopRepository;
@Autowired
private BusinessRepository businessRepository;
@Autowired
private CommunityRepository communityRepository;
public static boolean isNumeric(String str) {
for (int i = str.length(); --i >= 0; ) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
public static int getFirstNumOffset(String str) {
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
return i;
}
}
return -1;
}
public static String getWithOutCommonEndName(String str) {
for (int i = 0; i < commonEndStrings.length; i++) {
int offset = str.indexOf(commonEndStrings[i]);
if (offset != -1) {
return str.substring(0, offset);
}
}
return str;
}
public static String[] splitByFirstNum(String str) {
int offset = getFirstNumOffset(str);
if (getFirstNumOffset(str) <= 0) {
return null;
} else {
return new String[]{str.substring(0, offset), str.substring(offset)};
}
}
public List<String> getDictWord() {
long count = communityRepository.count();
List<String> ls = new ArrayList<>(((int) count) * 2);
try (Stream<Community> stream = communityRepository.searchAll()) {
stream.forEach(shop -> {
String name = shop.getName();
String shortname = MydictImpl.getWithOutCommonEndName(name);
ls.add(name);
if (shortname.length() != name.length()) {
ls.add(shortname);
}
String[] subarrs = MydictImpl.splitByFirstNum(shop.getName());
if (subarrs == null) {
} else {
if (!Character.isDigit(subarrs[0].charAt(0))) {
System.out.println(subarrs[0].charAt(0));
ls.add(subarrs[0]);
ls.add(subarrs[1]);
}
}
});
} catch (Exception e) {
logger.warn("从数据库加载字典失败," + e);
}
return ls;
}
@Override
public Boolean saveDictToFile(List<String> dics, String path) {
return ioUtil.saveCollectionToTxt(dics, path);
}
//从本地文件路径获取
//如果 <SUF>
@Override
public List<String> LoadDictFromFile(String path) {
List<String> ls = ioUtil.readLineListWithLessMemory(path);
if (ls == null || ls.size() == 0) {
System.out.println("get dict begin ");
ls = getDictWord();
System.out.println("get dict end ");
saveDictToFile(ls, path);
System.out.println("save dict end");
return ls;
}
return ls;
}
@Override
public List<String> LoadDictFromFile() {
return this.LoadDictFromFile(this.getClass().getClassLoader().getResource("").getPath());
}
}
| false | 857 | 7 | 991 | 8 | 1,068 | 7 | 991 | 8 | 1,179 | 12 | false | false | false | false | false | true |
10045_3 | package com.wisedu.scc.love.activity.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wisedu.scc.love.R;
import com.wisedu.scc.love.sqlite.model.ChatRecord;
import com.wisedu.scc.love.utils.CommonUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainTabFragment extends Fragment {
private View view;
private PullToRefreshListView mPullRefreshListView;
private SimpleAdapter mAdapter;
private ArrayList<HashMap<String, Object>> itemsData;
public MainTabFragment() {
}
/**
* 在onCreate之后调用
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main, container, false);
mPullRefreshListView = (PullToRefreshListView)view.findViewById(R.id.messageList);
// 设置刷新模式
mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
// 设置列表内容
ListView actualListView = mPullRefreshListView.getRefreshableView();
//生成动态数组,并且转入数据
itemsData = getMessages();
mAdapter= new SimpleAdapter(MainTabFragment.this.getActivity(), //没什么解释
itemsData,//数据来源
R.layout.item_list_fragment_main,//XML实现
new String[]{"Avatar", "UserName", "Message", "Time", "Number"}, //动态数据KEY
new int[]{R.id.avatar, R.id.userName, R.id.message, R.id.time, R.id.number});
actualListView.setAdapter(mAdapter);
/*定义事件*/
mPullRefreshListView.setOnItemClickListener(new CustomOnItemClickListener());
mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// 异步获取消息任务
new GetMessagesTask().execute();
}
});
return view;
}
/**
* 自定义列表项单击事件
*/
private class CustomOnItemClickListener implements AdapterView.OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
CommonUtil.shortToast(MainTabFragment.this.getActivity(), "该用户是:".concat(item.get("UserName").toString()));
}
}
/**
* 自定义异步任务
*/
private class GetMessagesTask extends AsyncTask<Void, Void, String[]> {
/**
* 后台任务
* @param params
* @return
*/
@Override
protected String[] doInBackground(Void... params) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
}
return null;
}
/**
* 在doInBackground之后执行
* @param result
*/
@Override
protected void onPostExecute(String[] result) {
mAdapter.notifyDataSetChanged();
// 必须调用,不然会一直处于刷新状态
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
}
/**
* 获得聊天数据
* @return
*/
private ArrayList<HashMap<String, Object>> getMessages(){
//生成动态数组,并且转入数据
ArrayList<HashMap<String, Object>> data = new ArrayList<>();
for (int i = 0; i < 10; i++) {
HashMap<String, Object> map = new HashMap<>();
map.put("Avatar", R.drawable.avatar_default);//添加图像资源的ID
map.put("UserName", "婷子");
map.put("Message", "好想你,你在哪儿?");
map.put("Time", "17:10");
map.put("Number", i);
data.add(map);
}
return data;
}
}
| ccliu2015/love | app/src/main/java/com/wisedu/scc/love/activity/fragment/MainTabFragment.java | 1,071 | //生成动态数组,并且转入数据 | line_comment | zh-cn | package com.wisedu.scc.love.activity.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.wisedu.scc.love.R;
import com.wisedu.scc.love.sqlite.model.ChatRecord;
import com.wisedu.scc.love.utils.CommonUtil;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainTabFragment extends Fragment {
private View view;
private PullToRefreshListView mPullRefreshListView;
private SimpleAdapter mAdapter;
private ArrayList<HashMap<String, Object>> itemsData;
public MainTabFragment() {
}
/**
* 在onCreate之后调用
* @param inflater
* @param container
* @param savedInstanceState
* @return
*/
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main, container, false);
mPullRefreshListView = (PullToRefreshListView)view.findViewById(R.id.messageList);
// 设置刷新模式
mPullRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
// 设置列表内容
ListView actualListView = mPullRefreshListView.getRefreshableView();
//生成 <SUF>
itemsData = getMessages();
mAdapter= new SimpleAdapter(MainTabFragment.this.getActivity(), //没什么解释
itemsData,//数据来源
R.layout.item_list_fragment_main,//XML实现
new String[]{"Avatar", "UserName", "Message", "Time", "Number"}, //动态数据KEY
new int[]{R.id.avatar, R.id.userName, R.id.message, R.id.time, R.id.number});
actualListView.setAdapter(mAdapter);
/*定义事件*/
mPullRefreshListView.setOnItemClickListener(new CustomOnItemClickListener());
mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
// 异步获取消息任务
new GetMessagesTask().execute();
}
});
return view;
}
/**
* 自定义列表项单击事件
*/
private class CustomOnItemClickListener implements AdapterView.OnItemClickListener{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String, Object> item = (HashMap<String, Object>) parent.getItemAtPosition(position);
CommonUtil.shortToast(MainTabFragment.this.getActivity(), "该用户是:".concat(item.get("UserName").toString()));
}
}
/**
* 自定义异步任务
*/
private class GetMessagesTask extends AsyncTask<Void, Void, String[]> {
/**
* 后台任务
* @param params
* @return
*/
@Override
protected String[] doInBackground(Void... params) {
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
}
return null;
}
/**
* 在doInBackground之后执行
* @param result
*/
@Override
protected void onPostExecute(String[] result) {
mAdapter.notifyDataSetChanged();
// 必须调用,不然会一直处于刷新状态
mPullRefreshListView.onRefreshComplete();
super.onPostExecute(result);
}
}
/**
* 获得聊天数据
* @return
*/
private ArrayList<HashMap<String, Object>> getMessages(){
//生成动态数组,并且转入数据
ArrayList<HashMap<String, Object>> data = new ArrayList<>();
for (int i = 0; i < 10; i++) {
HashMap<String, Object> map = new HashMap<>();
map.put("Avatar", R.drawable.avatar_default);//添加图像资源的ID
map.put("UserName", "婷子");
map.put("Message", "好想你,你在哪儿?");
map.put("Time", "17:10");
map.put("Number", i);
data.add(map);
}
return data;
}
}
| false | 930 | 8 | 1,071 | 9 | 1,128 | 9 | 1,071 | 9 | 1,338 | 16 | false | false | false | false | false | true |
60605_8 | package main;
import bkfunc.AccountPage;
import bkfunc.GraphPage;
import bkfunc.TakeNote;
import bkfunc.ViewBook;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Pane mainPane = new Pane();
//按钮文字
Button takeNoteButton = new Button("立即\n记账");
Button manageBookButton = new Button("我的\n账本");
Button userButton = new Button("账户\n信息");
Button graphButton = new Button("统计\n图表");
//添加到板上
mainPane.getChildren().add(takeNoteButton);
mainPane.getChildren().add(manageBookButton);
mainPane.getChildren().add(userButton);
mainPane.getChildren().add(graphButton);
//按钮字体大小(按钮大小)
takeNoteButton.setFont(new Font(40));
manageBookButton.setFont(new Font(40));
userButton.setFont(new Font(40));
graphButton.setFont(new Font(40));
//按钮位置
takeNoteButton.setLayoutX(50);
takeNoteButton.setLayoutY(40);
manageBookButton.setLayoutX(220);
manageBookButton.setLayoutY(40);
userButton.setLayoutX(50);
userButton.setLayoutY(200);
graphButton.setLayoutX(220);
graphButton.setLayoutY(200);
//提示板
Stage NoticeStage = new Stage();
BorderPane noticePane = new BorderPane();
Scene noticeScene = new Scene(noticePane,222,90);
NoticeStage.setScene(noticeScene);
NoticeStage.setTitle("加载中...");
NoticeStage.getIcons().add(new Image("file:./images/loading.png"));
//子窗口实例化与按钮绑定
TakeNote takeNote = new TakeNote();
ViewBook viewBook = new ViewBook();
AccountPage accountPage = new AccountPage();
GraphPage graphPage = new GraphPage();
//立刻记账
takeNoteButton.setOnMouseClicked(e->{
primaryStage.hide();
takeNote.show();
});
takeNote.back.setOnMouseClicked(e->{
takeNote.primaryStage.hide();
primaryStage.show();
});
takeNote.primaryStage.setOnCloseRequest(e->{
primaryStage.show();
});
//我的账本
manageBookButton.setOnMouseClicked(e->{
primaryStage.hide();
NoticeStage.show();
viewBook.show();
NoticeStage.hide();
});
viewBook.primaryStage.setOnCloseRequest(e->{
primaryStage.show();
});
//账户信息
userButton.setOnMouseClicked(e->{
primaryStage.hide();
accountPage.show();
});
accountPage.primaryStage.setOnCloseRequest(e->{
primaryStage.show();
});
//统计图表
graphButton.setOnMouseClicked(e->{
primaryStage.hide();
graphPage.show();
});
graphPage.primaryStage.setOnCloseRequest(e->{
primaryStage.show();
});
StackPane root = new StackPane();
root.setStyle(
"-fx-background-image: url(" +
"'https://pic.52112.com/180710/JPG-180710_173/UZuAHiafUi_small.jpg'" +
"); " +
"-fx-background-size: cover;"
);
root.getChildren().add(mainPane);
Scene scene = new Scene(root,405,365);
primaryStage.setScene(scene);
primaryStage.setTitle("My Bookkeeping");
//图标
primaryStage.getIcons().add(new Image("file:./images/icon.png"));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| ccqstark/MyBookkeeping | src/main/Main.java | 989 | //账户信息 | line_comment | zh-cn | package main;
import bkfunc.AccountPage;
import bkfunc.GraphPage;
import bkfunc.TakeNote;
import bkfunc.ViewBook;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
Pane mainPane = new Pane();
//按钮文字
Button takeNoteButton = new Button("立即\n记账");
Button manageBookButton = new Button("我的\n账本");
Button userButton = new Button("账户\n信息");
Button graphButton = new Button("统计\n图表");
//添加到板上
mainPane.getChildren().add(takeNoteButton);
mainPane.getChildren().add(manageBookButton);
mainPane.getChildren().add(userButton);
mainPane.getChildren().add(graphButton);
//按钮字体大小(按钮大小)
takeNoteButton.setFont(new Font(40));
manageBookButton.setFont(new Font(40));
userButton.setFont(new Font(40));
graphButton.setFont(new Font(40));
//按钮位置
takeNoteButton.setLayoutX(50);
takeNoteButton.setLayoutY(40);
manageBookButton.setLayoutX(220);
manageBookButton.setLayoutY(40);
userButton.setLayoutX(50);
userButton.setLayoutY(200);
graphButton.setLayoutX(220);
graphButton.setLayoutY(200);
//提示板
Stage NoticeStage = new Stage();
BorderPane noticePane = new BorderPane();
Scene noticeScene = new Scene(noticePane,222,90);
NoticeStage.setScene(noticeScene);
NoticeStage.setTitle("加载中...");
NoticeStage.getIcons().add(new Image("file:./images/loading.png"));
//子窗口实例化与按钮绑定
TakeNote takeNote = new TakeNote();
ViewBook viewBook = new ViewBook();
AccountPage accountPage = new AccountPage();
GraphPage graphPage = new GraphPage();
//立刻记账
takeNoteButton.setOnMouseClicked(e->{
primaryStage.hide();
takeNote.show();
});
takeNote.back.setOnMouseClicked(e->{
takeNote.primaryStage.hide();
primaryStage.show();
});
takeNote.primaryStage.setOnCloseRequest(e->{
primaryStage.show();
});
//我的账本
manageBookButton.setOnMouseClicked(e->{
primaryStage.hide();
NoticeStage.show();
viewBook.show();
NoticeStage.hide();
});
viewBook.primaryStage.setOnCloseRequest(e->{
primaryStage.show();
});
//账户 <SUF>
userButton.setOnMouseClicked(e->{
primaryStage.hide();
accountPage.show();
});
accountPage.primaryStage.setOnCloseRequest(e->{
primaryStage.show();
});
//统计图表
graphButton.setOnMouseClicked(e->{
primaryStage.hide();
graphPage.show();
});
graphPage.primaryStage.setOnCloseRequest(e->{
primaryStage.show();
});
StackPane root = new StackPane();
root.setStyle(
"-fx-background-image: url(" +
"'https://pic.52112.com/180710/JPG-180710_173/UZuAHiafUi_small.jpg'" +
"); " +
"-fx-background-size: cover;"
);
root.getChildren().add(mainPane);
Scene scene = new Scene(root,405,365);
primaryStage.setScene(scene);
primaryStage.setTitle("My Bookkeeping");
//图标
primaryStage.getIcons().add(new Image("file:./images/icon.png"));
primaryStage.setResizable(false);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
| false | 839 | 3 | 989 | 3 | 1,046 | 3 | 989 | 3 | 1,211 | 7 | false | false | false | false | false | true |
27903_9 | package 字符串.No76最小覆盖子串;
/**
* 滑动窗口法
*/
public class Solution {
public String minWindow(String s, String t) {
// i为滑窗左边界,j为滑窗右边界
// needCnt变量方便我们快速判断当前滑窗是否符合要求
// start是答案字符串的起点下标,minLength是答案字符串的长度,也就是最小的长度
int i = 0, j = 0, minLength = Integer.MAX_VALUE, start = 0, needCnt = 0;
// 大写字母A的ASCII为65,小写z为122,最少需要58位才够用
// need数据记录还需要的字母数量
int[] need = new int[58];
// 统计t字符串中的我们所需的字母以及数量
for (int k = 0; k < t.length(); k++) {
need[t.charAt(k) - 'A']++;
needCnt++;
}
while (j < s.length()) {
// 先移动右边界,直到包含了所有的必要字母,也就是needCnt等于0
while (j < s.length() && needCnt > 0) {
if (need[s.charAt(j) - 'A'] > 0) {
// 如果是必要字母,那么needCnt要减1
needCnt--;
}
// 遇到的每一个字母need数组都要减1,右边界右移
need[s.charAt(j) - 'A']--;
j++;
}
// 然后移动左边界,直到遇到了第一个必要字母
while (i < j && need[s.charAt(i) - 'A'] < 0) {
need[s.charAt(i) - 'A']++;
i++;
}
// 这里必须要再判断下是否满足needCnt,因为上面循环的结束有可能是数组遍历完了
if (needCnt == 0 && j - i < minLength) {
// 遇到长度更小的要更新minLength和start
// 滑窗(当前子串)的长度的计算是 j - i (这里之所以不用+1是因为j的落脚点其实是最后一个必要字母后一位)
minLength = j - i;
start = i;
}
// 完成一个滑窗的判断后,为了进入下一个滑窗,左边界需要收缩一位
// i可能越界,这里需要多判断一次
if (i < s.length()) need[s.charAt(i) - 'A']++;
needCnt++;
i++;
}
// 最后用起点和最小子串长度截取答案子串
// 如果长度还是Integer.MAX_VALUE说不明找不到,返回""
return minLength == Integer.MAX_VALUE ? "" : s.substring(start, start + minLength);
}
}
| ccqstark/leetcode-java | src/字符串/No76最小覆盖子串/Solution.java | 680 | // 遇到的每一个字母need数组都要减1,右边界右移 | line_comment | zh-cn | package 字符串.No76最小覆盖子串;
/**
* 滑动窗口法
*/
public class Solution {
public String minWindow(String s, String t) {
// i为滑窗左边界,j为滑窗右边界
// needCnt变量方便我们快速判断当前滑窗是否符合要求
// start是答案字符串的起点下标,minLength是答案字符串的长度,也就是最小的长度
int i = 0, j = 0, minLength = Integer.MAX_VALUE, start = 0, needCnt = 0;
// 大写字母A的ASCII为65,小写z为122,最少需要58位才够用
// need数据记录还需要的字母数量
int[] need = new int[58];
// 统计t字符串中的我们所需的字母以及数量
for (int k = 0; k < t.length(); k++) {
need[t.charAt(k) - 'A']++;
needCnt++;
}
while (j < s.length()) {
// 先移动右边界,直到包含了所有的必要字母,也就是needCnt等于0
while (j < s.length() && needCnt > 0) {
if (need[s.charAt(j) - 'A'] > 0) {
// 如果是必要字母,那么needCnt要减1
needCnt--;
}
// 遇到 <SUF>
need[s.charAt(j) - 'A']--;
j++;
}
// 然后移动左边界,直到遇到了第一个必要字母
while (i < j && need[s.charAt(i) - 'A'] < 0) {
need[s.charAt(i) - 'A']++;
i++;
}
// 这里必须要再判断下是否满足needCnt,因为上面循环的结束有可能是数组遍历完了
if (needCnt == 0 && j - i < minLength) {
// 遇到长度更小的要更新minLength和start
// 滑窗(当前子串)的长度的计算是 j - i (这里之所以不用+1是因为j的落脚点其实是最后一个必要字母后一位)
minLength = j - i;
start = i;
}
// 完成一个滑窗的判断后,为了进入下一个滑窗,左边界需要收缩一位
// i可能越界,这里需要多判断一次
if (i < s.length()) need[s.charAt(i) - 'A']++;
needCnt++;
i++;
}
// 最后用起点和最小子串长度截取答案子串
// 如果长度还是Integer.MAX_VALUE说不明找不到,返回""
return minLength == Integer.MAX_VALUE ? "" : s.substring(start, start + minLength);
}
}
| false | 620 | 18 | 680 | 20 | 672 | 15 | 680 | 20 | 935 | 27 | false | false | false | false | false | true |
29903_8 | package game.ui;
import graphics.Canvas;
import android.graphics.Paint;
import static java.lang.Math.*;
import static util.MathUtil.*;
import util.BmpRes;
import game.entity.Player;
import game.item.*;
public abstract class UI{
private static final long serialVersionUID=1844677L;
//描述用户界面中的一个控件或容器
public static BmpRes item_frame=new BmpRes("UI/item_frame");
public static BmpRes selected_item_frame=new BmpRes("UI/selected_item_frame");
static BmpRes item_frame_left=new BmpRes("UI/item_frame_left");
static BmpRes selected_item_frame_left=new BmpRes("UI/selected_item_frame_left");
public static BmpRes
left_btn=new BmpRes("UI/left"),
right_btn=new BmpRes("UI/right"),
empty_btn=new BmpRes("UI/empty");
public static Player pl;
public static float H_div_W=1;
protected float x,y;
private game.block.BlockAt __block;
private CraftHelper __craft_helper;
private int bg_color=0;
//事件:得到焦点,此事件对静态控件无效
public void open(){}
//事件:每帧更新
public void update(){}
public final boolean press(float tx,float ty){
if(!exist())return false;
return onPress(tx-x,ty-y);
}
public final void draw(Canvas cv){
if(!exist())return;
cv.save();
cv.translate(x,y);
if(bg_color!=0)cv.drawRect(0,0,4,4,bg_color);
if(__block!=null)cv.drawBitmap(__block.block.getBmp(),0,0,4,4);
onDraw(cv);
cv.restore();
}
//设置4x4的背景色
public void setBgColor(int col){bg_color=col;}
public int getCraftType(){return 0;}
//事件:绘制
abstract protected void onDraw(Canvas cv);
//事件:按下,坐标相对于this的左上角
protected boolean onPress(float tx,float ty){return false;}
//存在性检查,如果不存在将不会被绘制,不能处理触摸事件,不存在的对话框会被关闭
public boolean exist(){
if(__block!=null)return pl.check(__block);
return true;
}
//事件:失去焦点,此事件对静态控件无效
public void close(){}
//设置4x4的背景方块
//并使用默认的依赖方块的存在性检验策略:方块仍存在,且离主角不远
public final UI setBlock(game.block.BlockAt ba){__block=ba;return this;}
public final UI setCraftHelper(CraftHelper ch){
__craft_helper=ch;
return this;
}
public final CraftHelper getCraftHelper(){return __craft_helper;}
//绘制进度条,画布,前景色,背景色,0和1间的进度,矩形的左、上、右、下
public static void drawProgressBar(Canvas cv,int color,int bg_color,float v,float left,float top,float right,float bottom){
v=left+(right-left)*max(0,min(v,1));
cv.drawRect(left,top,v,bottom,color);
cv.drawRect(v,top,right,bottom,bg_color);
}
}
| ccz181078/Blocks | src/game/ui/UI.java | 901 | //设置4x4的背景方块 | line_comment | zh-cn | package game.ui;
import graphics.Canvas;
import android.graphics.Paint;
import static java.lang.Math.*;
import static util.MathUtil.*;
import util.BmpRes;
import game.entity.Player;
import game.item.*;
public abstract class UI{
private static final long serialVersionUID=1844677L;
//描述用户界面中的一个控件或容器
public static BmpRes item_frame=new BmpRes("UI/item_frame");
public static BmpRes selected_item_frame=new BmpRes("UI/selected_item_frame");
static BmpRes item_frame_left=new BmpRes("UI/item_frame_left");
static BmpRes selected_item_frame_left=new BmpRes("UI/selected_item_frame_left");
public static BmpRes
left_btn=new BmpRes("UI/left"),
right_btn=new BmpRes("UI/right"),
empty_btn=new BmpRes("UI/empty");
public static Player pl;
public static float H_div_W=1;
protected float x,y;
private game.block.BlockAt __block;
private CraftHelper __craft_helper;
private int bg_color=0;
//事件:得到焦点,此事件对静态控件无效
public void open(){}
//事件:每帧更新
public void update(){}
public final boolean press(float tx,float ty){
if(!exist())return false;
return onPress(tx-x,ty-y);
}
public final void draw(Canvas cv){
if(!exist())return;
cv.save();
cv.translate(x,y);
if(bg_color!=0)cv.drawRect(0,0,4,4,bg_color);
if(__block!=null)cv.drawBitmap(__block.block.getBmp(),0,0,4,4);
onDraw(cv);
cv.restore();
}
//设置4x4的背景色
public void setBgColor(int col){bg_color=col;}
public int getCraftType(){return 0;}
//事件:绘制
abstract protected void onDraw(Canvas cv);
//事件:按下,坐标相对于this的左上角
protected boolean onPress(float tx,float ty){return false;}
//存在性检查,如果不存在将不会被绘制,不能处理触摸事件,不存在的对话框会被关闭
public boolean exist(){
if(__block!=null)return pl.check(__block);
return true;
}
//事件:失去焦点,此事件对静态控件无效
public void close(){}
//设置 <SUF>
//并使用默认的依赖方块的存在性检验策略:方块仍存在,且离主角不远
public final UI setBlock(game.block.BlockAt ba){__block=ba;return this;}
public final UI setCraftHelper(CraftHelper ch){
__craft_helper=ch;
return this;
}
public final CraftHelper getCraftHelper(){return __craft_helper;}
//绘制进度条,画布,前景色,背景色,0和1间的进度,矩形的左、上、右、下
public static void drawProgressBar(Canvas cv,int color,int bg_color,float v,float left,float top,float right,float bottom){
v=left+(right-left)*max(0,min(v,1));
cv.drawRect(left,top,v,bottom,color);
cv.drawRect(v,top,right,bottom,bg_color);
}
}
| false | 701 | 9 | 901 | 9 | 899 | 9 | 901 | 9 | 1,070 | 15 | false | false | false | false | false | true |
28285_3 | package cn.redcdn.hvs.im.column;
import android.content.ContentValues;
import android.database.Cursor;
import cn.redcdn.hvs.im.bean.ThreadsBean;
import cn.redcdn.log.CustomLog;
/**
* Desc
* Created by wangkai on 2017/2/24.
*/
public class ThreadsTable {
public static String TABLENAME = "t_threads";
public static final String THREADS_COLUMN_ID = "id";
public static final String THREADS_COLUMN_CREATETIME = "createTime";
public static final String THREADS_COLUMN_LASTTIME = "lastTime";
public static final String THREADS_COLUMN_TYPE = "type";
public static final String THREADS_COLUMN_RECIPIENTIDS = "recipientIds";
public static final String THREADS_COLUMN_EXTENDINFO = "extendInfo";
public static final String THREADS_COLUMN_TOP = "top"; // 是否置顶 0:不置顶,1:置顶
public static final String THREADS_COLUMN_RESERVERSTR1 = "reserverStr1"; // 是否免打扰 "0":打扰,"1":免打扰
public static final String THREADS_COLUMN_RESERVERSTR2 = "reserverStr2";
public static final int TOP_YES = 1;
public static final int TOP_NO = 0;
public static final String DISTRUB_YES = "0"; //"0":打扰
public static final String DISTRUB_NO = "1"; //"1":免打扰
public static final int TYPE_SINGLE_CHAT = 1;
public static final int TYPE_GROUP_CHAT = 2;
public static final int SAVE_CONTACT_YES = 1;
public static final int SAVE_CONTACT_NO = 0;
public static ContentValues makeContentValue(ThreadsBean bean) {
if (bean == null) {
return null;
}
ContentValues value = new ContentValues();
value.put(THREADS_COLUMN_ID, bean.getId());
value.put(THREADS_COLUMN_CREATETIME, bean.getCreateTime());
value.put(THREADS_COLUMN_LASTTIME, bean.getLastTime());
value.put(THREADS_COLUMN_TYPE, bean.getType());
value.put(THREADS_COLUMN_RECIPIENTIDS, bean.getRecipientIds());
value.put(THREADS_COLUMN_EXTENDINFO, bean.getExtendInfo());
value.put(THREADS_COLUMN_TOP, bean.getTop());
value.put(THREADS_COLUMN_RESERVERSTR1, bean.getReserverStr1());
value.put(THREADS_COLUMN_RESERVERSTR2, bean.getReserverStr2());
return value;
}
public static ThreadsBean pureCursor(Cursor cursor) {
if (cursor == null || cursor.isClosed()) {
return null;
}
ThreadsBean bean = new ThreadsBean();
try {
bean.setId(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_ID)));
bean.setCreateTime(cursor.getLong(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_CREATETIME)));
bean.setLastTime(cursor.getLong(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_LASTTIME)));
bean.setType(cursor.getInt(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_TYPE)));
bean.setRecipientIds(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_RECIPIENTIDS)));
bean.setExtendInfo(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_EXTENDINFO)));
bean.setTop(cursor.getInt(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_TOP)));
bean.setReserverStr1(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_RESERVERSTR1)));
bean.setReserverStr2(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_RESERVERSTR1)));
} catch (Exception e) {
CustomLog.e("ThreadsTable","Exception" + e.toString());
return null;
}
return bean;
}
}
| cdc0002829/demo | java/cn/redcdn/hvs/im/column/ThreadsTable.java | 946 | //"0":打扰 | line_comment | zh-cn | package cn.redcdn.hvs.im.column;
import android.content.ContentValues;
import android.database.Cursor;
import cn.redcdn.hvs.im.bean.ThreadsBean;
import cn.redcdn.log.CustomLog;
/**
* Desc
* Created by wangkai on 2017/2/24.
*/
public class ThreadsTable {
public static String TABLENAME = "t_threads";
public static final String THREADS_COLUMN_ID = "id";
public static final String THREADS_COLUMN_CREATETIME = "createTime";
public static final String THREADS_COLUMN_LASTTIME = "lastTime";
public static final String THREADS_COLUMN_TYPE = "type";
public static final String THREADS_COLUMN_RECIPIENTIDS = "recipientIds";
public static final String THREADS_COLUMN_EXTENDINFO = "extendInfo";
public static final String THREADS_COLUMN_TOP = "top"; // 是否置顶 0:不置顶,1:置顶
public static final String THREADS_COLUMN_RESERVERSTR1 = "reserverStr1"; // 是否免打扰 "0":打扰,"1":免打扰
public static final String THREADS_COLUMN_RESERVERSTR2 = "reserverStr2";
public static final int TOP_YES = 1;
public static final int TOP_NO = 0;
public static final String DISTRUB_YES = "0"; //"0 <SUF>
public static final String DISTRUB_NO = "1"; //"1":免打扰
public static final int TYPE_SINGLE_CHAT = 1;
public static final int TYPE_GROUP_CHAT = 2;
public static final int SAVE_CONTACT_YES = 1;
public static final int SAVE_CONTACT_NO = 0;
public static ContentValues makeContentValue(ThreadsBean bean) {
if (bean == null) {
return null;
}
ContentValues value = new ContentValues();
value.put(THREADS_COLUMN_ID, bean.getId());
value.put(THREADS_COLUMN_CREATETIME, bean.getCreateTime());
value.put(THREADS_COLUMN_LASTTIME, bean.getLastTime());
value.put(THREADS_COLUMN_TYPE, bean.getType());
value.put(THREADS_COLUMN_RECIPIENTIDS, bean.getRecipientIds());
value.put(THREADS_COLUMN_EXTENDINFO, bean.getExtendInfo());
value.put(THREADS_COLUMN_TOP, bean.getTop());
value.put(THREADS_COLUMN_RESERVERSTR1, bean.getReserverStr1());
value.put(THREADS_COLUMN_RESERVERSTR2, bean.getReserverStr2());
return value;
}
public static ThreadsBean pureCursor(Cursor cursor) {
if (cursor == null || cursor.isClosed()) {
return null;
}
ThreadsBean bean = new ThreadsBean();
try {
bean.setId(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_ID)));
bean.setCreateTime(cursor.getLong(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_CREATETIME)));
bean.setLastTime(cursor.getLong(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_LASTTIME)));
bean.setType(cursor.getInt(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_TYPE)));
bean.setRecipientIds(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_RECIPIENTIDS)));
bean.setExtendInfo(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_EXTENDINFO)));
bean.setTop(cursor.getInt(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_TOP)));
bean.setReserverStr1(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_RESERVERSTR1)));
bean.setReserverStr2(cursor.getString(cursor
.getColumnIndexOrThrow(THREADS_COLUMN_RESERVERSTR1)));
} catch (Exception e) {
CustomLog.e("ThreadsTable","Exception" + e.toString());
return null;
}
return bean;
}
}
| false | 817 | 5 | 946 | 8 | 978 | 5 | 946 | 8 | 1,212 | 9 | false | false | false | false | false | true |
2644_0 | // 项目暂未完全开源,如有需要可持续关注,谢谢 | cdfan/my-admin | MyAdmin/generator/src/main/java/com/generator/CodeGenerator.java | 18 | // 项目暂未完全开源,如有需要可持续关注,谢谢 | line_comment | zh-cn | // 项目 <SUF> | false | 14 | 14 | 18 | 18 | 14 | 14 | 18 | 18 | 31 | 31 | false | false | false | false | false | true |
15722_5 | import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* InitProject
* 运行命令: java Init (项目Code) (运行端口)
*
* @author JiYinchuan
* @since 1.1.0.211021
*/
public class Init {
/**
* 原始项目包名
*/
private static final String PROJECT_ORIGIN_PACKAGE_NAME = "pro.haichuang.framework.service.main";
/**
* 项目服务模块名称
*/
private static final String PROJECT_SERVICE_MODEL_NAME = "hc-service-main";
/**
* 系统换行符
*/
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static void main(String[] args) {
if (args.length != 2) {
throw new RuntimeException("参数配置错误, 正确运行为 [java Init 项目Code 运行端口]");
}
try {
// 项目原始Code
String originCodeName = args[0];
// 运行端口
String port = args[1];
if (originCodeName == null || originCodeName.isEmpty()) {
throw new RuntimeException("项目Code未配置, 执行命令为 [java Init 项目Code 运行端口]");
}
if (port == null || port.isEmpty()) {
throw new RuntimeException("项目运行端口未配置, 执行命令为 [java Init 项目Code 运行端口]");
}
for (int i = 0; i < port.length(); i++) {
if (!Character.isDigit(port.charAt(i))) {
throw new RuntimeException("项目运行端口配置错误");
}
}
// 服务模块对象
File serviceModelDirFile = new File(PROJECT_SERVICE_MODEL_NAME);
if (!serviceModelDirFile.exists()) {
throw new RuntimeException(String.format("[%s] 模块不存在", PROJECT_SERVICE_MODEL_NAME));
}
if (!serviceModelDirFile.isDirectory()) {
throw new RuntimeException(String.format("[%s] 必须为目录", PROJECT_SERVICE_MODEL_NAME));
}
try {
// 服务模块 [src/main] 目录
File mainDirFile = getChildDir(serviceModelDirFile, "src.main");
// 服务模块 [src/main/java] 目录
File javaDirFile = getChildDir(mainDirFile, "java");
// 服务模块核心包路径
File projectDirFile = getChildDir(javaDirFile, PROJECT_ORIGIN_PACKAGE_NAME);
// 服务模块 [src/test] 目录
File testDirFile = getChildDir(serviceModelDirFile, "src.test");
// 服务模块 [src/test/java] 目录
File javaTestDirFile = getChildDir(testDirFile, "java");
// 服务模块测试包路径
File projectTestDirFile = getChildDir(javaTestDirFile, PROJECT_ORIGIN_PACKAGE_NAME);
// 服务模块资源路径
File resourcesDirFile = getChildDir(mainDirFile, "resources");
// Mybatis-Xml存放目录
File resourcesMapperDirFile = getChildDir(resourcesDirFile, "pro.haichuang.framework.service.main");
// 服务模块 [pom.xml] 文件
File parentPomFile = new File("pom.xml");
File pomFile = new File(PROJECT_SERVICE_MODEL_NAME, "pom.xml");
if (!pomFile.exists() || !parentPomFile.exists()) {
throw new RuntimeException("[pom.xml] 不存在");
}
if (!pomFile.isFile() || !parentPomFile.exists()) {
throw new RuntimeException("[pom.xml] 必须为文件");
}
// 重命名项目核心文件信息
replaceCodeAndFlushWrite(projectDirFile.isDirectory(), projectDirFile, originCodeName, port);
// 重命名项目测试文件信息
replaceCodeAndFlushWrite(projectTestDirFile.isDirectory(), projectTestDirFile, originCodeName, port);
// 重命名项目包名
String projectNewPackageDirPath = getNewPackage(originCodeName).replaceAll("\\.", "/");
String projectOriginPackageDirPath = PROJECT_ORIGIN_PACKAGE_NAME.replaceAll("\\.", "/");
String projectDirNamePath = projectDirFile.getAbsolutePath().replaceAll("\\\\", "/");
boolean renameProjectDirResult = projectDirFile.renameTo(new File(projectDirNamePath.replace(projectOriginPackageDirPath, projectNewPackageDirPath)));
if (!renameProjectDirResult) {
throw new RuntimeException("重命名项目包名失败");
}
String projectTestDirNamePath = projectTestDirFile.getAbsolutePath().replaceAll("\\\\", "/");
boolean renameProjectTestDirResult = projectTestDirFile.renameTo(new File(projectTestDirNamePath.replace(projectOriginPackageDirPath, projectNewPackageDirPath)));
if (!renameProjectTestDirResult) {
throw new RuntimeException("重命名项目测试包名失败");
}
// 重命名资源文件信息
replaceCodeAndFlushWrite(resourcesDirFile.isDirectory() || (resourcesDirFile.isFile() && resourcesDirFile.getName().startsWith("application")),
resourcesDirFile, originCodeName, port);
// 重命名Mybatis-Xml文件存放目录名
File newResourcesMapperDirFile = new File(resourcesMapperDirFile.getCanonicalPath()
.replaceAll("\\\\", "/")
.replaceAll("pro/haichuang/framework/service/main", "pro/haichuang/framework/service/" + getProjectCode(originCodeName)));
if (!resourcesMapperDirFile.renameTo(newResourcesMapperDirFile)) {
throw new RuntimeException("重命名Mapper存放目录失败");
}
// 更改 [pom.xml] 文件 [Jar] 名称
replaceCodeAndFlushWrite(false, parentPomFile, originCodeName, port);
replaceCodeAndFlushWrite(false, pomFile, originCodeName, port);
} catch (Exception e) {
System.out.println("运行异常, 请联系管理员");
}
} catch (Exception e) {
System.out.println("运行异常, 请联系管理员");
}
}
/**
* 获取子目录
*
* @param parentFile 父目录File对象
* @param dirName 子目录名称
* @return 子目录
*/
private static File getChildDir(File parentFile, String dirName) {
File childDirFile = null;
try {
String[] dirNames = dirName.contains(".") ? dirName.split("\\.") : new String[]{dirName};
for (String tempDirName : dirNames) {
assert parentFile != null;
File[] tempDirFiles = parentFile.listFiles((dir, name) -> tempDirName.equals(name));
if (tempDirFiles != null) {
for (File file : tempDirFiles) {
if (file.isDirectory()) {
childDirFile = file;
}
}
}
parentFile = childDirFile;
}
} catch (Exception e) {
throw new RuntimeException("获取子目录失败, 请联系管理员");
}
return childDirFile;
}
/**
* 替换代号并重新写入
*
* @param isRecursion 是否需要递归
* @param file 文件
* @param originCodeName 项目原始Code
* @param port 项目端口
*/
private static void replaceCodeAndFlushWrite(boolean isRecursion, File file, String originCodeName, String port) {
if (isRecursion && file.isDirectory()) {
File[] childrenFiles = file.listFiles();
if (childrenFiles != null) {
for (File childrenFile : childrenFiles) {
replaceCodeAndFlushWrite(true, childrenFile, originCodeName, port);
}
}
} else if (file.isFile()) {
try (
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))
) {
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
if (line.contains(PROJECT_ORIGIN_PACKAGE_NAME)) {
line = line.replaceAll(PROJECT_ORIGIN_PACKAGE_NAME, getNewPackage(originCodeName));
}
if (line.contains("${hc.server.port}")) {
line = line.replaceAll("\\$\\{hc.server.port}", port);
}
if (line.contains("${hc.origin-code-name}")) {
line = line.replaceAll("\\$\\{hc.origin-code-name}", originCodeName);
}
if (line.contains("${hc.origin-lowercase-code-name}")) {
line = line.replaceAll("\\$\\{hc.origin-lowercase-code-name}", originCodeName.toLowerCase());
}
if (line.contains("${hc.project-code-name}")) {
line = line.replaceAll("\\$\\{hc.project-code-name}", getProjectCode(originCodeName));
}
if (line.contains("defaultJarFileName")) {
line = line.replaceAll("defaultJarFileName", originCodeName);
}
if (line.contains("projectartifactid")) {
line = line.replaceAll("projectartifactid", originCodeName.toLowerCase());
}
buffer.append(line.concat(LINE_SEPARATOR));
}
try (
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), true)
) {
writer.print(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取项目Code(首字母全小写+数字)
*
* @param originCodeName 项目原始Code
* @return 项目Code
*/
private static String getProjectCode(String originCodeName) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < originCodeName.length(); i++) {
char tempChar = originCodeName.charAt(i);
if (Character.isUpperCase(tempChar) || Character.isDigit(tempChar)) {
result.append(tempChar);
}
}
return result.toString().toLowerCase();
}
/**
* 获取新报名
*
* @param originCodeName 项目原始Code
* @return 新包名
*/
private static String getNewPackage(String originCodeName) {
return String.join(".", Arrays.copyOf(PROJECT_ORIGIN_PACKAGE_NAME.split("\\."), PROJECT_ORIGIN_PACKAGE_NAME.split("\\.").length - 1)).concat(".").concat(getProjectCode(originCodeName));
}
}
| cdhaichuang/haichuangframework | Init.java | 2,393 | // 运行端口 | line_comment | zh-cn | import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
/**
* InitProject
* 运行命令: java Init (项目Code) (运行端口)
*
* @author JiYinchuan
* @since 1.1.0.211021
*/
public class Init {
/**
* 原始项目包名
*/
private static final String PROJECT_ORIGIN_PACKAGE_NAME = "pro.haichuang.framework.service.main";
/**
* 项目服务模块名称
*/
private static final String PROJECT_SERVICE_MODEL_NAME = "hc-service-main";
/**
* 系统换行符
*/
private static final String LINE_SEPARATOR = System.getProperty("line.separator");
public static void main(String[] args) {
if (args.length != 2) {
throw new RuntimeException("参数配置错误, 正确运行为 [java Init 项目Code 运行端口]");
}
try {
// 项目原始Code
String originCodeName = args[0];
// 运行 <SUF>
String port = args[1];
if (originCodeName == null || originCodeName.isEmpty()) {
throw new RuntimeException("项目Code未配置, 执行命令为 [java Init 项目Code 运行端口]");
}
if (port == null || port.isEmpty()) {
throw new RuntimeException("项目运行端口未配置, 执行命令为 [java Init 项目Code 运行端口]");
}
for (int i = 0; i < port.length(); i++) {
if (!Character.isDigit(port.charAt(i))) {
throw new RuntimeException("项目运行端口配置错误");
}
}
// 服务模块对象
File serviceModelDirFile = new File(PROJECT_SERVICE_MODEL_NAME);
if (!serviceModelDirFile.exists()) {
throw new RuntimeException(String.format("[%s] 模块不存在", PROJECT_SERVICE_MODEL_NAME));
}
if (!serviceModelDirFile.isDirectory()) {
throw new RuntimeException(String.format("[%s] 必须为目录", PROJECT_SERVICE_MODEL_NAME));
}
try {
// 服务模块 [src/main] 目录
File mainDirFile = getChildDir(serviceModelDirFile, "src.main");
// 服务模块 [src/main/java] 目录
File javaDirFile = getChildDir(mainDirFile, "java");
// 服务模块核心包路径
File projectDirFile = getChildDir(javaDirFile, PROJECT_ORIGIN_PACKAGE_NAME);
// 服务模块 [src/test] 目录
File testDirFile = getChildDir(serviceModelDirFile, "src.test");
// 服务模块 [src/test/java] 目录
File javaTestDirFile = getChildDir(testDirFile, "java");
// 服务模块测试包路径
File projectTestDirFile = getChildDir(javaTestDirFile, PROJECT_ORIGIN_PACKAGE_NAME);
// 服务模块资源路径
File resourcesDirFile = getChildDir(mainDirFile, "resources");
// Mybatis-Xml存放目录
File resourcesMapperDirFile = getChildDir(resourcesDirFile, "pro.haichuang.framework.service.main");
// 服务模块 [pom.xml] 文件
File parentPomFile = new File("pom.xml");
File pomFile = new File(PROJECT_SERVICE_MODEL_NAME, "pom.xml");
if (!pomFile.exists() || !parentPomFile.exists()) {
throw new RuntimeException("[pom.xml] 不存在");
}
if (!pomFile.isFile() || !parentPomFile.exists()) {
throw new RuntimeException("[pom.xml] 必须为文件");
}
// 重命名项目核心文件信息
replaceCodeAndFlushWrite(projectDirFile.isDirectory(), projectDirFile, originCodeName, port);
// 重命名项目测试文件信息
replaceCodeAndFlushWrite(projectTestDirFile.isDirectory(), projectTestDirFile, originCodeName, port);
// 重命名项目包名
String projectNewPackageDirPath = getNewPackage(originCodeName).replaceAll("\\.", "/");
String projectOriginPackageDirPath = PROJECT_ORIGIN_PACKAGE_NAME.replaceAll("\\.", "/");
String projectDirNamePath = projectDirFile.getAbsolutePath().replaceAll("\\\\", "/");
boolean renameProjectDirResult = projectDirFile.renameTo(new File(projectDirNamePath.replace(projectOriginPackageDirPath, projectNewPackageDirPath)));
if (!renameProjectDirResult) {
throw new RuntimeException("重命名项目包名失败");
}
String projectTestDirNamePath = projectTestDirFile.getAbsolutePath().replaceAll("\\\\", "/");
boolean renameProjectTestDirResult = projectTestDirFile.renameTo(new File(projectTestDirNamePath.replace(projectOriginPackageDirPath, projectNewPackageDirPath)));
if (!renameProjectTestDirResult) {
throw new RuntimeException("重命名项目测试包名失败");
}
// 重命名资源文件信息
replaceCodeAndFlushWrite(resourcesDirFile.isDirectory() || (resourcesDirFile.isFile() && resourcesDirFile.getName().startsWith("application")),
resourcesDirFile, originCodeName, port);
// 重命名Mybatis-Xml文件存放目录名
File newResourcesMapperDirFile = new File(resourcesMapperDirFile.getCanonicalPath()
.replaceAll("\\\\", "/")
.replaceAll("pro/haichuang/framework/service/main", "pro/haichuang/framework/service/" + getProjectCode(originCodeName)));
if (!resourcesMapperDirFile.renameTo(newResourcesMapperDirFile)) {
throw new RuntimeException("重命名Mapper存放目录失败");
}
// 更改 [pom.xml] 文件 [Jar] 名称
replaceCodeAndFlushWrite(false, parentPomFile, originCodeName, port);
replaceCodeAndFlushWrite(false, pomFile, originCodeName, port);
} catch (Exception e) {
System.out.println("运行异常, 请联系管理员");
}
} catch (Exception e) {
System.out.println("运行异常, 请联系管理员");
}
}
/**
* 获取子目录
*
* @param parentFile 父目录File对象
* @param dirName 子目录名称
* @return 子目录
*/
private static File getChildDir(File parentFile, String dirName) {
File childDirFile = null;
try {
String[] dirNames = dirName.contains(".") ? dirName.split("\\.") : new String[]{dirName};
for (String tempDirName : dirNames) {
assert parentFile != null;
File[] tempDirFiles = parentFile.listFiles((dir, name) -> tempDirName.equals(name));
if (tempDirFiles != null) {
for (File file : tempDirFiles) {
if (file.isDirectory()) {
childDirFile = file;
}
}
}
parentFile = childDirFile;
}
} catch (Exception e) {
throw new RuntimeException("获取子目录失败, 请联系管理员");
}
return childDirFile;
}
/**
* 替换代号并重新写入
*
* @param isRecursion 是否需要递归
* @param file 文件
* @param originCodeName 项目原始Code
* @param port 项目端口
*/
private static void replaceCodeAndFlushWrite(boolean isRecursion, File file, String originCodeName, String port) {
if (isRecursion && file.isDirectory()) {
File[] childrenFiles = file.listFiles();
if (childrenFiles != null) {
for (File childrenFile : childrenFiles) {
replaceCodeAndFlushWrite(true, childrenFile, originCodeName, port);
}
}
} else if (file.isFile()) {
try (
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))
) {
StringBuffer buffer = new StringBuffer();
for (String line = reader.readLine(); line != null; line = reader.readLine()) {
if (line.contains(PROJECT_ORIGIN_PACKAGE_NAME)) {
line = line.replaceAll(PROJECT_ORIGIN_PACKAGE_NAME, getNewPackage(originCodeName));
}
if (line.contains("${hc.server.port}")) {
line = line.replaceAll("\\$\\{hc.server.port}", port);
}
if (line.contains("${hc.origin-code-name}")) {
line = line.replaceAll("\\$\\{hc.origin-code-name}", originCodeName);
}
if (line.contains("${hc.origin-lowercase-code-name}")) {
line = line.replaceAll("\\$\\{hc.origin-lowercase-code-name}", originCodeName.toLowerCase());
}
if (line.contains("${hc.project-code-name}")) {
line = line.replaceAll("\\$\\{hc.project-code-name}", getProjectCode(originCodeName));
}
if (line.contains("defaultJarFileName")) {
line = line.replaceAll("defaultJarFileName", originCodeName);
}
if (line.contains("projectartifactid")) {
line = line.replaceAll("projectartifactid", originCodeName.toLowerCase());
}
buffer.append(line.concat(LINE_SEPARATOR));
}
try (
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8), true)
) {
writer.print(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取项目Code(首字母全小写+数字)
*
* @param originCodeName 项目原始Code
* @return 项目Code
*/
private static String getProjectCode(String originCodeName) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < originCodeName.length(); i++) {
char tempChar = originCodeName.charAt(i);
if (Character.isUpperCase(tempChar) || Character.isDigit(tempChar)) {
result.append(tempChar);
}
}
return result.toString().toLowerCase();
}
/**
* 获取新报名
*
* @param originCodeName 项目原始Code
* @return 新包名
*/
private static String getNewPackage(String originCodeName) {
return String.join(".", Arrays.copyOf(PROJECT_ORIGIN_PACKAGE_NAME.split("\\."), PROJECT_ORIGIN_PACKAGE_NAME.split("\\.").length - 1)).concat(".").concat(getProjectCode(originCodeName));
}
}
| false | 2,224 | 6 | 2,393 | 4 | 2,556 | 4 | 2,393 | 4 | 3,115 | 8 | false | false | false | false | false | true |
27486_1 | package com.ucan.entity;
import java.io.Serializable;
import com.ucan.entity.page.PageParameter;
/**
* 用户-角色 实体类
*
* @author liming.cen
* @date 2022年12月23日 下午8:32:28
*/
public class UserRole implements Serializable {
private static final long serialVersionUID = -1445116664474354173L;
private String userId;
private String roleId;
/**
* 组织
*/
private Organization org;
/**
* 职位
*/
private Post post;
/**
* 角色
*/
private Role role;
/**
* 用户
*/
private User user;
private PageParameter page;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Organization getOrg() {
return org;
}
public void setOrg(Organization org) {
this.org = org;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public PageParameter getPage() {
return page;
}
public void setPage(PageParameter page) {
this.page = page;
}
}
| cenlm/springboot-ucan-admin | src/main/java/com/ucan/entity/UserRole.java | 432 | /**
* 组织
*/ | block_comment | zh-cn | package com.ucan.entity;
import java.io.Serializable;
import com.ucan.entity.page.PageParameter;
/**
* 用户-角色 实体类
*
* @author liming.cen
* @date 2022年12月23日 下午8:32:28
*/
public class UserRole implements Serializable {
private static final long serialVersionUID = -1445116664474354173L;
private String userId;
private String roleId;
/**
* 组织
<SUF>*/
private Organization org;
/**
* 职位
*/
private Post post;
/**
* 角色
*/
private Role role;
/**
* 用户
*/
private User user;
private PageParameter page;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public Organization getOrg() {
return org;
}
public void setOrg(Organization org) {
this.org = org;
}
public Post getPost() {
return post;
}
public void setPost(Post post) {
this.post = post;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public PageParameter getPage() {
return page;
}
public void setPage(PageParameter page) {
this.page = page;
}
}
| false | 370 | 9 | 432 | 7 | 466 | 9 | 432 | 7 | 533 | 12 | false | false | false | false | false | true |
39708_2 | /**
*
*/
package com.taobao.top.analysis.util;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 放入事件用于检测是否超时,先做成比较简化版的实现,后续可以扩展
* @author fangweng
* @email: fangweng@taobao.com
* 2011-12-5 下午1:37:00
*
*/
public abstract class TimeOutQueue<E extends TimeOutEvent>{
private static final Log logger = LogFactory.getLog(TimeOutQueue.class);
private PriorityBlockingQueue<E> taskEventPool;//等待状态变更的消息池
private TimeOutChecker timeOutChecker;//后台检查消息变更资源池的线程
private Semaphore poolIsEmpty = new Semaphore(1);//防止空循环检查消息变更资源池
//这三个用于超时事件队列检查
private ReentrantLock lock;
private Condition checkCondition;
private AtomicLong minTimeOutStamp;
public TimeOutQueue()
{
lock = new ReentrantLock();
checkCondition = lock.newCondition();
minTimeOutStamp = new AtomicLong(0);
taskEventPool = new PriorityBlockingQueue<E>(100);
timeOutChecker = new TimeOutChecker();
timeOutChecker.setDaemon(true);
timeOutChecker.start();
}
public void release()
{
clean();
if (timeOutChecker != null)
timeOutChecker.stopThread();
}
public void clean()
{
if (taskEventPool != null)
taskEventPool.clear();
minTimeOutStamp.set(0);
}
/**
* 用于后台检查状态变更消息池,当前只负责Timeout状态检查
* @author fangweng
* @email fangweng@taobao.com
* @date 2011-5-17
*
*/
class TimeOutChecker extends Thread
{
public TimeOutChecker()
{
super("TimeOutChecker-thread");
}
boolean isRunning = true;
public void run()
{
try
{
while(isRunning)
{
//checker没有竞争,所以这里还是可靠的,用于防止内部没有任何数据的空转
poolIsEmpty.acquire();
if (taskEventPool.isEmpty())
continue;
E node;
long restTime = 0;
while((node = taskEventPool.peek()) != null)
{
restTime = node.getEventCreateTime() + node.getMaxEventHoldTime() * 1000 - System.currentTimeMillis();
if (node.getEventCreateTime() != 0 && restTime <= 0)
{
taskEventPool.poll();
timeOutAction(node);
}
else
{
if (node.getEventCreateTime() == 0)
restTime = 5 * 60 * 1000;//如果剩下的都没有超时事件了,则给5分钟
break;
}
}
//cpu time interval ,预估一下一个最小超时到来的情况,防止多次循环
if (restTime > 10)
{
if (restTime > 5 * 60 * 1000)
{
if (logger.isInfoEnabled())
logger.info("restTime : " + restTime + " so large.");
restTime = 5 * 60 * 1000;
}
boolean flag = lock.tryLock();
try
{
if (flag)
checkCondition.await(restTime, TimeUnit.MILLISECONDS);
}
catch(InterruptedException ie)
{
//do nothing
}
catch(Exception ex)
{
logger.error(ex,ex);
}
finally
{
if (flag)
lock.unlock();
}
}
poolIsEmpty.release();
}
}
catch (InterruptedException e)
{
//do nothing
}
catch(Exception ex)
{
logger.error("TaskChecker end...",ex);
}
}
public void stopThread()
{
isRunning = false;
interrupt();
}
}
/**
* 当有新的事件加入状态变更等待队列,
* 判断最小的timeout是否发生改变,选择性唤醒checker
* @param node
*/
public void eventChainChange(E node)
{
if (node.getEventCreateTime() > 0 && (minTimeOutStamp.get() == 0 || node.getEventCreateTime() < minTimeOutStamp.get()))
{
//不做并发控制
minTimeOutStamp.set(node.getEventCreateTime());
boolean flag = lock.tryLock();
try
{
if (flag)
{
checkCondition.signalAll();
}
}
catch(Exception ex)
{
logger.error(ex,ex);
}
finally
{
if (flag)
lock.unlock();
}
}
}
public void clear() {
taskEventPool.clear();
if (poolIsEmpty.availablePermits() == 0)
poolIsEmpty.release();
}
public boolean contains(Object o) {
return taskEventPool.contains(o);
}
public boolean isEmpty() {
return taskEventPool.isEmpty();
}
public boolean remove(Object o) {
return taskEventPool.remove(o);
}
public int size() {
return taskEventPool.size();
}
public boolean add(E e) {
boolean result = taskEventPool.add(e);
if (result)
{
eventChainChange(e);
if (poolIsEmpty.availablePermits() == 0)
poolIsEmpty.release();
}
return result;
}
public boolean offer(E e) {
boolean result = taskEventPool.offer(e);
if (result)
{
eventChainChange(e);
if (poolIsEmpty.availablePermits() == 0)
poolIsEmpty.release();
}
return result;
}
public E peek() {
return taskEventPool.peek();
}
public E poll() {
return taskEventPool.poll();
}
//需要对timeout做一些反应
public abstract void timeOutAction(E event);
}
| cenwenchu/beatles | src/java/com/taobao/top/analysis/util/TimeOutQueue.java | 1,680 | //后台检查消息变更资源池的线程
| line_comment | zh-cn | /**
*
*/
package com.taobao.top.analysis.util;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* 放入事件用于检测是否超时,先做成比较简化版的实现,后续可以扩展
* @author fangweng
* @email: fangweng@taobao.com
* 2011-12-5 下午1:37:00
*
*/
public abstract class TimeOutQueue<E extends TimeOutEvent>{
private static final Log logger = LogFactory.getLog(TimeOutQueue.class);
private PriorityBlockingQueue<E> taskEventPool;//等待状态变更的消息池
private TimeOutChecker timeOutChecker;//后台 <SUF>
private Semaphore poolIsEmpty = new Semaphore(1);//防止空循环检查消息变更资源池
//这三个用于超时事件队列检查
private ReentrantLock lock;
private Condition checkCondition;
private AtomicLong minTimeOutStamp;
public TimeOutQueue()
{
lock = new ReentrantLock();
checkCondition = lock.newCondition();
minTimeOutStamp = new AtomicLong(0);
taskEventPool = new PriorityBlockingQueue<E>(100);
timeOutChecker = new TimeOutChecker();
timeOutChecker.setDaemon(true);
timeOutChecker.start();
}
public void release()
{
clean();
if (timeOutChecker != null)
timeOutChecker.stopThread();
}
public void clean()
{
if (taskEventPool != null)
taskEventPool.clear();
minTimeOutStamp.set(0);
}
/**
* 用于后台检查状态变更消息池,当前只负责Timeout状态检查
* @author fangweng
* @email fangweng@taobao.com
* @date 2011-5-17
*
*/
class TimeOutChecker extends Thread
{
public TimeOutChecker()
{
super("TimeOutChecker-thread");
}
boolean isRunning = true;
public void run()
{
try
{
while(isRunning)
{
//checker没有竞争,所以这里还是可靠的,用于防止内部没有任何数据的空转
poolIsEmpty.acquire();
if (taskEventPool.isEmpty())
continue;
E node;
long restTime = 0;
while((node = taskEventPool.peek()) != null)
{
restTime = node.getEventCreateTime() + node.getMaxEventHoldTime() * 1000 - System.currentTimeMillis();
if (node.getEventCreateTime() != 0 && restTime <= 0)
{
taskEventPool.poll();
timeOutAction(node);
}
else
{
if (node.getEventCreateTime() == 0)
restTime = 5 * 60 * 1000;//如果剩下的都没有超时事件了,则给5分钟
break;
}
}
//cpu time interval ,预估一下一个最小超时到来的情况,防止多次循环
if (restTime > 10)
{
if (restTime > 5 * 60 * 1000)
{
if (logger.isInfoEnabled())
logger.info("restTime : " + restTime + " so large.");
restTime = 5 * 60 * 1000;
}
boolean flag = lock.tryLock();
try
{
if (flag)
checkCondition.await(restTime, TimeUnit.MILLISECONDS);
}
catch(InterruptedException ie)
{
//do nothing
}
catch(Exception ex)
{
logger.error(ex,ex);
}
finally
{
if (flag)
lock.unlock();
}
}
poolIsEmpty.release();
}
}
catch (InterruptedException e)
{
//do nothing
}
catch(Exception ex)
{
logger.error("TaskChecker end...",ex);
}
}
public void stopThread()
{
isRunning = false;
interrupt();
}
}
/**
* 当有新的事件加入状态变更等待队列,
* 判断最小的timeout是否发生改变,选择性唤醒checker
* @param node
*/
public void eventChainChange(E node)
{
if (node.getEventCreateTime() > 0 && (minTimeOutStamp.get() == 0 || node.getEventCreateTime() < minTimeOutStamp.get()))
{
//不做并发控制
minTimeOutStamp.set(node.getEventCreateTime());
boolean flag = lock.tryLock();
try
{
if (flag)
{
checkCondition.signalAll();
}
}
catch(Exception ex)
{
logger.error(ex,ex);
}
finally
{
if (flag)
lock.unlock();
}
}
}
public void clear() {
taskEventPool.clear();
if (poolIsEmpty.availablePermits() == 0)
poolIsEmpty.release();
}
public boolean contains(Object o) {
return taskEventPool.contains(o);
}
public boolean isEmpty() {
return taskEventPool.isEmpty();
}
public boolean remove(Object o) {
return taskEventPool.remove(o);
}
public int size() {
return taskEventPool.size();
}
public boolean add(E e) {
boolean result = taskEventPool.add(e);
if (result)
{
eventChainChange(e);
if (poolIsEmpty.availablePermits() == 0)
poolIsEmpty.release();
}
return result;
}
public boolean offer(E e) {
boolean result = taskEventPool.offer(e);
if (result)
{
eventChainChange(e);
if (poolIsEmpty.availablePermits() == 0)
poolIsEmpty.release();
}
return result;
}
public E peek() {
return taskEventPool.peek();
}
public E poll() {
return taskEventPool.poll();
}
//需要对timeout做一些反应
public abstract void timeOutAction(E event);
}
| false | 1,431 | 11 | 1,660 | 11 | 1,698 | 10 | 1,660 | 11 | 2,508 | 20 | false | false | false | false | false | true |
37596_4 | package Client.Handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.nio.charset.Charset;
import java.util.Date;
/**
* @author zhanghongjie
* @date 2018/11/2
* @descrition
*/
public class FirstClientHandler extends ChannelInboundHandlerAdapter {
/**发送数据的方法*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(new Date() + ": 客户端写出数据");
//1、获取数据
ByteBuf buffer = getByteBuf(ctx);
//2、写数据
ctx.channel().writeAndFlush(buffer);
}
/**接受数据的方法*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
System.out.println(new Date() + " :客户端收到数据: " + byteBuf.toString(Charset.forName("utf-8")));
}
private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
//1、获取二进制抽象 ByteBuf
ByteBuf byteBuf = ctx.alloc().buffer();
//2、准备数据,指定字符串的字符集为utf-8
byte[] bytes = "你好,乔治!".getBytes(Charset.forName("utf-8"));
//3、填充数据到byteBuf
byteBuf.writeBytes(bytes);
return byteBuf;
}
}
| cerlaw/NettyPractice | src/Client/Handler/FirstClientHandler.java | 372 | /**接受数据的方法*/ | block_comment | zh-cn | package Client.Handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import java.nio.charset.Charset;
import java.util.Date;
/**
* @author zhanghongjie
* @date 2018/11/2
* @descrition
*/
public class FirstClientHandler extends ChannelInboundHandlerAdapter {
/**发送数据的方法*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println(new Date() + ": 客户端写出数据");
//1、获取数据
ByteBuf buffer = getByteBuf(ctx);
//2、写数据
ctx.channel().writeAndFlush(buffer);
}
/**接受数 <SUF>*/
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf byteBuf = (ByteBuf) msg;
System.out.println(new Date() + " :客户端收到数据: " + byteBuf.toString(Charset.forName("utf-8")));
}
private ByteBuf getByteBuf(ChannelHandlerContext ctx) {
//1、获取二进制抽象 ByteBuf
ByteBuf byteBuf = ctx.alloc().buffer();
//2、准备数据,指定字符串的字符集为utf-8
byte[] bytes = "你好,乔治!".getBytes(Charset.forName("utf-8"));
//3、填充数据到byteBuf
byteBuf.writeBytes(bytes);
return byteBuf;
}
}
| false | 326 | 5 | 372 | 5 | 378 | 5 | 372 | 5 | 483 | 11 | false | false | false | false | false | true |
31060_7 | package com.cfxyz.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
/*
* Oracle数据库脚本
DROP TABLE member PURGE ;
DROP SEQUENCE myseq ;
CREATE SEQUENCE myseq ;
CREATE TABLE member (
mid NUMBER,
name VARCHAR2(20),
birthday DATE DEFAULT SYSDATE ,
age NUMBER(3),
note CLOB,
CONSTRAINT pk_mid PRIMARY KEY(mid)
);
*/
public class TestJDBC {
private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl";
private static final String USER = "scott";
private static final String PASSWORD = "tiger";
public static void main(String[] args) throws Exception {
//第一步:加载数据库驱动程序,此时不需要实例化,因为会由容器自己负责管理
Class.forName(DBDRIVER);
//第二步:连接数据库
Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD);
System.out.println(conn);
//第三步:操作数据库
//数据更新:
Statement stmt = conn.createStatement();
String sql =" INSERT INTO member (mid, name, birthday, age, note) VALUES "
+ " (myseq.nextval, '张三', TO_DATE('1998-10-10', 'yyyy-mm-dd'), 17, '是个人') " ;
int len;
for(int x = 0; x < 30; x++) {
len = stmt.executeUpdate(sql) ; //执行更新
System.out.println("影响的数据行:" + len);
}
//数据修改:
sql ="UPDATE member SET name = '李四',birthday=SYSDATE, age=30 WHERE mid IN(3,5,7,9,11,13,15,17) " ;
len = stmt.executeUpdate(sql) ;
System.out.println("影响的数据行:" + len);
//数据删除:
sql ="DELETE FROM member WHERE mid IN(10, 20, 30)";
len = stmt.executeUpdate(sql) ;
System.out.println("影响的数据行:" + len);
//数据查询:
sql = "SELECT mid, name, birthday, age, note FROM member";
ResultSet rs = stmt.executeQuery(sql) ;
while(rs.next()) { //循环取出返回的每一行数据
int mid = rs.getInt("mid");
String name = rs.getString("name");
int age = rs.getInt("age");
Date birthday = rs.getDate("birthday");
String note = rs.getString("note");
System.out.println(mid + ", " + name + ", " + age + ", " + birthday + ", " + note);
}
//第四步:关闭数据库
rs.close(); //可选
stmt.close(); //可选
conn.close();
}
}
| cforth/codefarm | javademo/TestJDBC.java | 759 | //数据删除: | line_comment | zh-cn | package com.cfxyz.demo;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
/*
* Oracle数据库脚本
DROP TABLE member PURGE ;
DROP SEQUENCE myseq ;
CREATE SEQUENCE myseq ;
CREATE TABLE member (
mid NUMBER,
name VARCHAR2(20),
birthday DATE DEFAULT SYSDATE ,
age NUMBER(3),
note CLOB,
CONSTRAINT pk_mid PRIMARY KEY(mid)
);
*/
public class TestJDBC {
private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
private static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl";
private static final String USER = "scott";
private static final String PASSWORD = "tiger";
public static void main(String[] args) throws Exception {
//第一步:加载数据库驱动程序,此时不需要实例化,因为会由容器自己负责管理
Class.forName(DBDRIVER);
//第二步:连接数据库
Connection conn = DriverManager.getConnection(DBURL, USER, PASSWORD);
System.out.println(conn);
//第三步:操作数据库
//数据更新:
Statement stmt = conn.createStatement();
String sql =" INSERT INTO member (mid, name, birthday, age, note) VALUES "
+ " (myseq.nextval, '张三', TO_DATE('1998-10-10', 'yyyy-mm-dd'), 17, '是个人') " ;
int len;
for(int x = 0; x < 30; x++) {
len = stmt.executeUpdate(sql) ; //执行更新
System.out.println("影响的数据行:" + len);
}
//数据修改:
sql ="UPDATE member SET name = '李四',birthday=SYSDATE, age=30 WHERE mid IN(3,5,7,9,11,13,15,17) " ;
len = stmt.executeUpdate(sql) ;
System.out.println("影响的数据行:" + len);
//数据 <SUF>
sql ="DELETE FROM member WHERE mid IN(10, 20, 30)";
len = stmt.executeUpdate(sql) ;
System.out.println("影响的数据行:" + len);
//数据查询:
sql = "SELECT mid, name, birthday, age, note FROM member";
ResultSet rs = stmt.executeQuery(sql) ;
while(rs.next()) { //循环取出返回的每一行数据
int mid = rs.getInt("mid");
String name = rs.getString("name");
int age = rs.getInt("age");
Date birthday = rs.getDate("birthday");
String note = rs.getString("note");
System.out.println(mid + ", " + name + ", " + age + ", " + birthday + ", " + note);
}
//第四步:关闭数据库
rs.close(); //可选
stmt.close(); //可选
conn.close();
}
}
| false | 661 | 4 | 759 | 4 | 767 | 4 | 759 | 4 | 980 | 6 | false | false | false | false | false | true |
52970_0 | package com.app.cgb.moviepreview.entity;
import java.util.List;
public class EventList {
/**
* title : 该片你该了解的9件事
* list : ["《金刚狼3:殊死一战》是休·杰克曼最后一次饰演金刚狼,这个角色自第一部《X战警》以来已过去17年。","英文片名Logan是金刚狼作为普通人的名字,第三部老年金刚狼的能力不断退化,会增加更多\u201c人类\u201d的特性,和女儿的亲情戏也是一大看点,片名暗示了电影的主题,也暗示了狼叔的最终归属。","影片借鉴了漫威漫画《暮狼寻乡》的一些剧情,不过休·杰克曼说他出演本片的灵感更多来自电影《不可饶恕》。","本集导演詹姆斯·曼高德也导演了《金刚狼2》。这其实也是休·杰克曼与其合作的第三部电影,他们还合作过《穿越时空爱上你》。","詹姆斯·曼高德拍摄本片时借鉴了经典西部片《原野奇侠》,在片中也有X教授在赌场酒店里观看了这部影片的场景。","本片中老年版X教授帕特里克·斯图尔特也迎来告别演出。","为了找到人气角色劳拉(X-23)的扮演者,剧组搜遍了欧洲、南美、北美、加拿大,最后在西班牙马德里找到了达芙妮·基恩。","本片主要拍摄地在美国新奥尔良和路易斯安那州,取景地包括NASA的密乔零件装配厂、斯莱德尔市、路易斯安那11号高速公路和知名的51号公路。","《金刚狼3》在北美的电影分级是R级。"]
*/
private String title;
private List<String> list;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
| cgbgh/MoviesApp | app/src/main/java/com/app/cgb/moviepreview/entity/EventList.java | 651 | /**
* title : 该片你该了解的9件事
* list : ["《金刚狼3:殊死一战》是休·杰克曼最后一次饰演金刚狼,这个角色自第一部《X战警》以来已过去17年。","英文片名Logan是金刚狼作为普通人的名字,第三部老年金刚狼的能力不断退化,会增加更多\u201c人类\u201d的特性,和女儿的亲情戏也是一大看点,片名暗示了电影的主题,也暗示了狼叔的最终归属。","影片借鉴了漫威漫画《暮狼寻乡》的一些剧情,不过休·杰克曼说他出演本片的灵感更多来自电影《不可饶恕》。","本集导演詹姆斯·曼高德也导演了《金刚狼2》。这其实也是休·杰克曼与其合作的第三部电影,他们还合作过《穿越时空爱上你》。","詹姆斯·曼高德拍摄本片时借鉴了经典西部片《原野奇侠》,在片中也有X教授在赌场酒店里观看了这部影片的场景。","本片中老年版X教授帕特里克·斯图尔特也迎来告别演出。","为了找到人气角色劳拉(X-23)的扮演者,剧组搜遍了欧洲、南美、北美、加拿大,最后在西班牙马德里找到了达芙妮·基恩。","本片主要拍摄地在美国新奥尔良和路易斯安那州,取景地包括NASA的密乔零件装配厂、斯莱德尔市、路易斯安那11号高速公路和知名的51号公路。","《金刚狼3》在北美的电影分级是R级。"]
*/ | block_comment | zh-cn | package com.app.cgb.moviepreview.entity;
import java.util.List;
public class EventList {
/**
* tit <SUF>*/
private String title;
private List<String> list;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
}
| false | 474 | 380 | 651 | 535 | 521 | 395 | 651 | 535 | 856 | 719 | true | true | true | true | true | false |
27515_0 | package jianzhioffer;
import java.util.HashMap;
import java.util.Map;
/**
* 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
* https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/
*/
public class NumericString_LC20 {
/**
* 这题重新看了下,其实是编译原理的内容,有限状态自动机(DFA),确定每种状态能转移成什么,以及合法的结束状态;跟前缀树有点像,用状态转移的思想来做。
* 以下代码摘自中文力扣。
*/
static class Solution {
public boolean isNumber(String s) {
Map<State, Map<CharType, State>> transfer = new HashMap<State, Map<CharType, State>>();
Map<CharType, State> initialMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_SPACE, State.STATE_INITIAL);
put(CharType.CHAR_NUMBER, State.STATE_INTEGER);
put(CharType.CHAR_POINT, State.STATE_POINT_WITHOUT_INT);
put(CharType.CHAR_SIGN, State.STATE_INT_SIGN);
}};
transfer.put(State.STATE_INITIAL, initialMap);
Map<CharType, State> intSignMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_INTEGER);
put(CharType.CHAR_POINT, State.STATE_POINT_WITHOUT_INT);
}};
transfer.put(State.STATE_INT_SIGN, intSignMap);
Map<CharType, State> integerMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_INTEGER);
put(CharType.CHAR_EXP, State.STATE_EXP);
put(CharType.CHAR_POINT, State.STATE_POINT);
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_INTEGER, integerMap);
Map<CharType, State> pointMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_FRACTION);
put(CharType.CHAR_EXP, State.STATE_EXP);
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_POINT, pointMap);
Map<CharType, State> pointWithoutIntMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_FRACTION);
}};
transfer.put(State.STATE_POINT_WITHOUT_INT, pointWithoutIntMap);
Map<CharType, State> fractionMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_FRACTION);
put(CharType.CHAR_EXP, State.STATE_EXP);
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_FRACTION, fractionMap);
Map<CharType, State> expMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER);
put(CharType.CHAR_SIGN, State.STATE_EXP_SIGN);
}};
transfer.put(State.STATE_EXP, expMap);
Map<CharType, State> expSignMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER);
}};
transfer.put(State.STATE_EXP_SIGN, expSignMap);
Map<CharType, State> expNumberMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER);
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_EXP_NUMBER, expNumberMap);
Map<CharType, State> endMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_END, endMap);
int length = s.length();
State state = State.STATE_INITIAL;
for (int i = 0; i < length; i++) {
CharType type = toCharType(s.charAt(i));
if (!transfer.get(state).containsKey(type)) {
return false;
} else {
state = transfer.get(state).get(type);
}
}
return state == State.STATE_INTEGER || state == State.STATE_POINT || state == State.STATE_FRACTION || state == State.STATE_EXP_NUMBER || state == State.STATE_END;
}
public CharType toCharType(char ch) {
if (ch >= '0' && ch <= '9') {
return CharType.CHAR_NUMBER;
} else if (ch == 'e' || ch == 'E') {
return CharType.CHAR_EXP;
} else if (ch == '.') {
return CharType.CHAR_POINT;
} else if (ch == '+' || ch == '-') {
return CharType.CHAR_SIGN;
} else if (ch == ' ') {
return CharType.CHAR_SPACE;
} else {
return CharType.CHAR_ILLEGAL;
}
}
enum State {
STATE_INITIAL,
STATE_INT_SIGN,
STATE_INTEGER,
STATE_POINT,
STATE_POINT_WITHOUT_INT,
STATE_FRACTION,
STATE_EXP,
STATE_EXP_SIGN,
STATE_EXP_NUMBER,
STATE_END,
}
enum CharType {
CHAR_NUMBER,
CHAR_EXP,
CHAR_POINT,
CHAR_SIGN,
CHAR_SPACE,
CHAR_ILLEGAL,
}
}
//这题没意义,简直像业务里的胶水代码。以下摘自讨论区
// class Solution {
// public:
// bool isNumeric(char* str) {
// // 标记符号、小数点、e是否出现过
// bool sign = false, decimal = false, hasE = false;
// for (int i = 0; i < strlen(str); i++) {
// if (str[i] == 'e' || str[i] == 'E') {
// if (i == strlen(str)-1) return false; // e后面一定要接数字
// if (hasE) return false; // 不能同时存在两个e
// hasE = true;
// } else if (str[i] == '+' || str[i] == '-') {
// // 第二次出现+-符号,则必须紧接在e之后
// if (sign && str[i-1] != 'e' && str[i-1] != 'E') return false;
// // 第一次出现+-符号,且不是在字符串开头,则也必须紧接在e之后
// if (!sign && i > 0 && str[i-1] != 'e' && str[i-1] != 'E') return false;
// sign = true;
// } else if (str[i] == '.') {
// // e后面不能接小数点,小数点不能出现两次
// if (hasE || decimal) return false;
// decimal = true;
// } else if (str[i] < '0' || str[i] > '9') // 不合法字符
// return false;
// }
// return true;
// }
// };
////**以下未通过**
// public boolean isNumeric(char[] str) {
// int numberOfE = 0;
// int numberOfPoints = 0;
// if (str == null || str.length == 0) return false;
// if (str.length == 1 && (str[0] < '0' || str[0] > '9')) return false;
// for (int i = 0; i < str.length; i++) {
// //字符范围
// if ((str[i] < '0' || str[i] > '9') && str[i] != '+' && str[i] != '-' && str[i] != 'e' && str[i] != '.') return false;
// //e的限制
// if (str[i] == 'e') {
// if (i == str.length - 1 || i == 0 || numberOfE != 0) return false;
// numberOfE++;
// }
// //.的限制
// if (str[i] == '.') {
// if (i == str.length - 1 || i == 0 || numberOfPoints != 0) return false;
// numberOfPoints++;
// }
// //符号限制
// if (str[i] == '+' || str[i] == '-') {
// if (i != 0) {
// if (str[i - 1] != 'e' && str[i - 1] != 'E')
// return false;
// for (int j = i + i; j < str.length; j++) {
// if (str[j] > 'z' || str[i] < 'a') return false;
// }
// }
// }
// }
// return true;
// }
public static void main(String args[]) {
// new NumericString().isNumeric("123.45e+6".toCharArray());
}
}
| chaangliu/leetcode-training | jianzhioffer/NumericString_LC20.java | 2,335 | /**
* 请实现一个函数用来判断字符串是否表示数值(包括整数和小数)。例如,字符串"+100","5e2","-123","3.1416"和"-1E-16"都表示数值。 但是"12e","1a3.14","1.2.3","+-5"和"12e+4.3"都不是。
* https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/
*/ | block_comment | zh-cn | package jianzhioffer;
import java.util.HashMap;
import java.util.Map;
/**
* 请实现 <SUF>*/
public class NumericString_LC20 {
/**
* 这题重新看了下,其实是编译原理的内容,有限状态自动机(DFA),确定每种状态能转移成什么,以及合法的结束状态;跟前缀树有点像,用状态转移的思想来做。
* 以下代码摘自中文力扣。
*/
static class Solution {
public boolean isNumber(String s) {
Map<State, Map<CharType, State>> transfer = new HashMap<State, Map<CharType, State>>();
Map<CharType, State> initialMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_SPACE, State.STATE_INITIAL);
put(CharType.CHAR_NUMBER, State.STATE_INTEGER);
put(CharType.CHAR_POINT, State.STATE_POINT_WITHOUT_INT);
put(CharType.CHAR_SIGN, State.STATE_INT_SIGN);
}};
transfer.put(State.STATE_INITIAL, initialMap);
Map<CharType, State> intSignMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_INTEGER);
put(CharType.CHAR_POINT, State.STATE_POINT_WITHOUT_INT);
}};
transfer.put(State.STATE_INT_SIGN, intSignMap);
Map<CharType, State> integerMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_INTEGER);
put(CharType.CHAR_EXP, State.STATE_EXP);
put(CharType.CHAR_POINT, State.STATE_POINT);
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_INTEGER, integerMap);
Map<CharType, State> pointMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_FRACTION);
put(CharType.CHAR_EXP, State.STATE_EXP);
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_POINT, pointMap);
Map<CharType, State> pointWithoutIntMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_FRACTION);
}};
transfer.put(State.STATE_POINT_WITHOUT_INT, pointWithoutIntMap);
Map<CharType, State> fractionMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_FRACTION);
put(CharType.CHAR_EXP, State.STATE_EXP);
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_FRACTION, fractionMap);
Map<CharType, State> expMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER);
put(CharType.CHAR_SIGN, State.STATE_EXP_SIGN);
}};
transfer.put(State.STATE_EXP, expMap);
Map<CharType, State> expSignMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER);
}};
transfer.put(State.STATE_EXP_SIGN, expSignMap);
Map<CharType, State> expNumberMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_NUMBER, State.STATE_EXP_NUMBER);
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_EXP_NUMBER, expNumberMap);
Map<CharType, State> endMap = new HashMap<CharType, State>() {{
put(CharType.CHAR_SPACE, State.STATE_END);
}};
transfer.put(State.STATE_END, endMap);
int length = s.length();
State state = State.STATE_INITIAL;
for (int i = 0; i < length; i++) {
CharType type = toCharType(s.charAt(i));
if (!transfer.get(state).containsKey(type)) {
return false;
} else {
state = transfer.get(state).get(type);
}
}
return state == State.STATE_INTEGER || state == State.STATE_POINT || state == State.STATE_FRACTION || state == State.STATE_EXP_NUMBER || state == State.STATE_END;
}
public CharType toCharType(char ch) {
if (ch >= '0' && ch <= '9') {
return CharType.CHAR_NUMBER;
} else if (ch == 'e' || ch == 'E') {
return CharType.CHAR_EXP;
} else if (ch == '.') {
return CharType.CHAR_POINT;
} else if (ch == '+' || ch == '-') {
return CharType.CHAR_SIGN;
} else if (ch == ' ') {
return CharType.CHAR_SPACE;
} else {
return CharType.CHAR_ILLEGAL;
}
}
enum State {
STATE_INITIAL,
STATE_INT_SIGN,
STATE_INTEGER,
STATE_POINT,
STATE_POINT_WITHOUT_INT,
STATE_FRACTION,
STATE_EXP,
STATE_EXP_SIGN,
STATE_EXP_NUMBER,
STATE_END,
}
enum CharType {
CHAR_NUMBER,
CHAR_EXP,
CHAR_POINT,
CHAR_SIGN,
CHAR_SPACE,
CHAR_ILLEGAL,
}
}
//这题没意义,简直像业务里的胶水代码。以下摘自讨论区
// class Solution {
// public:
// bool isNumeric(char* str) {
// // 标记符号、小数点、e是否出现过
// bool sign = false, decimal = false, hasE = false;
// for (int i = 0; i < strlen(str); i++) {
// if (str[i] == 'e' || str[i] == 'E') {
// if (i == strlen(str)-1) return false; // e后面一定要接数字
// if (hasE) return false; // 不能同时存在两个e
// hasE = true;
// } else if (str[i] == '+' || str[i] == '-') {
// // 第二次出现+-符号,则必须紧接在e之后
// if (sign && str[i-1] != 'e' && str[i-1] != 'E') return false;
// // 第一次出现+-符号,且不是在字符串开头,则也必须紧接在e之后
// if (!sign && i > 0 && str[i-1] != 'e' && str[i-1] != 'E') return false;
// sign = true;
// } else if (str[i] == '.') {
// // e后面不能接小数点,小数点不能出现两次
// if (hasE || decimal) return false;
// decimal = true;
// } else if (str[i] < '0' || str[i] > '9') // 不合法字符
// return false;
// }
// return true;
// }
// };
////**以下未通过**
// public boolean isNumeric(char[] str) {
// int numberOfE = 0;
// int numberOfPoints = 0;
// if (str == null || str.length == 0) return false;
// if (str.length == 1 && (str[0] < '0' || str[0] > '9')) return false;
// for (int i = 0; i < str.length; i++) {
// //字符范围
// if ((str[i] < '0' || str[i] > '9') && str[i] != '+' && str[i] != '-' && str[i] != 'e' && str[i] != '.') return false;
// //e的限制
// if (str[i] == 'e') {
// if (i == str.length - 1 || i == 0 || numberOfE != 0) return false;
// numberOfE++;
// }
// //.的限制
// if (str[i] == '.') {
// if (i == str.length - 1 || i == 0 || numberOfPoints != 0) return false;
// numberOfPoints++;
// }
// //符号限制
// if (str[i] == '+' || str[i] == '-') {
// if (i != 0) {
// if (str[i - 1] != 'e' && str[i - 1] != 'E')
// return false;
// for (int j = i + i; j < str.length; j++) {
// if (str[j] > 'z' || str[i] < 'a') return false;
// }
// }
// }
// }
// return true;
// }
public static void main(String args[]) {
// new NumericString().isNumeric("123.45e+6".toCharArray());
}
}
| false | 2,005 | 119 | 2,335 | 131 | 2,400 | 123 | 2,335 | 131 | 2,753 | 163 | false | false | false | false | false | true |
19306_4 | /**
* <p>Copyright (c) 2014~, All rights reserved.<p>
* <p>This java file created by chainren,you can copy or used it to anywhere after his authorization.
* If you have any question,please contact chainren.Mail to:chainren@gmail.com.Thank's.<p>
*/
package org.weixin4j.msg;
import java.util.ArrayList;
import java.util.List;
import org.weixin4j.entity.WeixinConstants;
import org.weixin4j.entity.request.TextMessage;
import org.weixin4j.entity.response.Article;
import org.weixin4j.entity.response.ArticleMessage;
import org.weixin4j.entity.response.Image;
import org.weixin4j.entity.response.ImageMessage;
import org.weixin4j.entity.response.Music;
import org.weixin4j.entity.response.MusicMessage;
import org.weixin4j.entity.response.Video;
import org.weixin4j.entity.response.VideoMessage;
import org.weixin4j.entity.response.Voice;
import org.weixin4j.entity.response.VoiceMessage;
import com.thoughtworks.xstream.XStream;
/**
* <p>
* Description: xml消息生成工具,负责将微信接口实体数据生成符合微信接口报文标准的xml报文。
*
* <p>
* Company :
* <p>
* Create Date: 2014年6月10日
*
* @author chainren
* @version 1.0
* @since JDK1.7
*
*
*/
public class MessageBuilder {
/**
* <p>
* 对接口实体数据进行组装,生成符合微信接口的xml报文。
* <p>
* 该接口方法只能处理简单的接口实体,属性的为简单的数据类型(8种基本类型,String类型).
*
* @param obj
* 接口实体数据对象,由应用进行封装,
* @return 符合微信接口的xml报文。
*/
public static String buildSimpleXML(Object obj) {
XStream xs = UserDefinedXStream.createUserDefXStream();
xs.alias("xml", obj.getClass());
return xs.toXML(obj);
}
/**
*
* @param obj
* 实体对象
* @param subClz
* 实体中属性属于自定义属性的,指定该属性在xml中的标签名为类名,默认是类的全路径。
* @param subClzAlias
* 指定实体中自定义属性的节点名,顺序跟subClz对应
* @param toIgnoreClz
* 针对集合属性,在xml中忽略属性名标签
* @param toIgnoreTag
* 集合属性的属性名
* @return
*/
@SuppressWarnings("rawtypes")
public static String buildCustomXML(Object obj, Class[] subClz, String[] subClzAlias, Class[] toIgnoreClz,
String[] toIgnoreTag) {
XStream xs = UserDefinedXStream.createUserDefXStream();
xs.alias("xml", obj.getClass());
if (subClz != null && subClz.length > 0) {
if (subClzAlias != null) {
for (int i = 0; i < subClz.length; i++) {
xs.alias(subClzAlias[i], subClz[i]);
}
} else {
for (Class clz : subClz) {
xs.alias(clz.getSimpleName(), clz);
}
}
}
/** 针对实体中的集合属性,去除集合属性名称 **/
if (toIgnoreTag != null && toIgnoreTag.length > 0) {
for (int i = 0; i < toIgnoreTag.length; i++) {
xs.addImplicitCollection(toIgnoreClz[i], toIgnoreTag[i], toIgnoreClz[i].getSimpleName(), toIgnoreClz[i]);
}
}
return xs.toXML(obj);
}
public static void main(String[] args) {
TextMessage msg = new TextMessage("qinglv2007", "chainren", System.currentTimeMillis(), 1323423L,
"欢迎注册微信公众平台,这里有你想不到惊喜哦~");
System.out.println(buildSimpleXML(msg));
System.out.println("==========================回复文本消息xml格式===================================");
org.weixin4j.entity.response.TextMessage respTextMsg = new org.weixin4j.entity.response.TextMessage(
"rengui756", "itumei", System.currentTimeMillis(), WeixinConstants.MSG_TYPE_TEXT);
respTextMsg.setContent("回复的文本消息");
String respTextMsgXml = buildSimpleXML(respTextMsg);
System.out.println(respTextMsgXml);
System.out.println("==========================回复图片消息xml格式===================================");
ImageMessage respImageMsg = new ImageMessage("rengui756", "itumei", System.currentTimeMillis());
respImageMsg.setImage(new Image("xxxesdf732432"));
String respImageMsgXml = buildCustomXML(respImageMsg, new Class[] { Image.class }, null, null, null);
System.out.println(respImageMsgXml);
System.out.println("==========================回复语音消息xml格式===================================");
VoiceMessage respVoiceMsg = new VoiceMessage("rengui756", "itumei", System.currentTimeMillis());
respVoiceMsg.setVoice(new Voice("xdfs32391x"));
String respVoiceMsgXml = buildCustomXML(respVoiceMsg, new Class[] { Voice.class }, null, null, null);
System.out.println(respVoiceMsgXml);
System.out.println("==========================回复视频消息xml格式===================================");
VideoMessage respVideoMsg = new VideoMessage("rengui756", "itumei", System.currentTimeMillis());
respVideoMsg.setVideo(new Video("xd320nhds", "这是视频消息", "视频视频视频啊啊啊啊"));
String respVideoMsgXml = buildCustomXML(respVideoMsg, new Class[] { Voice.class }, null, null, null);
System.out.println(respVideoMsgXml);
System.out.println("==========================回复音乐消息xml格式===================================");
MusicMessage respMusicMsg = new MusicMessage("rengui756", "itumei", System.currentTimeMillis());
respMusicMsg.setMusic(new Music("音乐", "回复音乐消息", "http://kugou.com/music=mg.mp3",
"http://kugou.com/music=mgh.mp3", "xds232"));
String respMusicMsgXml = buildCustomXML(respMusicMsg, new Class[] { Voice.class }, null, null, null);
System.out.println(respMusicMsgXml);
System.out.println("==========================回复多图文消息xml格式===================================");
ArticleMessage respArticleMsg = new ArticleMessage("rengui756", "itumei", System.currentTimeMillis());
List<Article> articles = new ArrayList<Article>();
articles.add(new Article("文章1", "回复多图文第一篇", "http://pic/pic1.jpg", "http://article/article1"));
articles.add(new Article("文章2", "回复多图文第二篇", "http://pic/pic2.jpg", "http://article/article2"));
articles.add(new Article("文章3", "回复多图文第三篇", "http://pic/pic3.jpg", "http://article/article3"));
respArticleMsg.setArticles(articles);
respArticleMsg.setArticleCount(3);
String respArticleMsgXml = buildCustomXML(respArticleMsg, new Class[] { Article.class },
new String[] { "Item" }, null, null);
System.out.println(respArticleMsgXml);
}
}
| chainren/weixin4j | src/org/weixin4j/msg/MessageBuilder.java | 1,932 | /** 针对实体中的集合属性,去除集合属性名称 **/ | block_comment | zh-cn | /**
* <p>Copyright (c) 2014~, All rights reserved.<p>
* <p>This java file created by chainren,you can copy or used it to anywhere after his authorization.
* If you have any question,please contact chainren.Mail to:chainren@gmail.com.Thank's.<p>
*/
package org.weixin4j.msg;
import java.util.ArrayList;
import java.util.List;
import org.weixin4j.entity.WeixinConstants;
import org.weixin4j.entity.request.TextMessage;
import org.weixin4j.entity.response.Article;
import org.weixin4j.entity.response.ArticleMessage;
import org.weixin4j.entity.response.Image;
import org.weixin4j.entity.response.ImageMessage;
import org.weixin4j.entity.response.Music;
import org.weixin4j.entity.response.MusicMessage;
import org.weixin4j.entity.response.Video;
import org.weixin4j.entity.response.VideoMessage;
import org.weixin4j.entity.response.Voice;
import org.weixin4j.entity.response.VoiceMessage;
import com.thoughtworks.xstream.XStream;
/**
* <p>
* Description: xml消息生成工具,负责将微信接口实体数据生成符合微信接口报文标准的xml报文。
*
* <p>
* Company :
* <p>
* Create Date: 2014年6月10日
*
* @author chainren
* @version 1.0
* @since JDK1.7
*
*
*/
public class MessageBuilder {
/**
* <p>
* 对接口实体数据进行组装,生成符合微信接口的xml报文。
* <p>
* 该接口方法只能处理简单的接口实体,属性的为简单的数据类型(8种基本类型,String类型).
*
* @param obj
* 接口实体数据对象,由应用进行封装,
* @return 符合微信接口的xml报文。
*/
public static String buildSimpleXML(Object obj) {
XStream xs = UserDefinedXStream.createUserDefXStream();
xs.alias("xml", obj.getClass());
return xs.toXML(obj);
}
/**
*
* @param obj
* 实体对象
* @param subClz
* 实体中属性属于自定义属性的,指定该属性在xml中的标签名为类名,默认是类的全路径。
* @param subClzAlias
* 指定实体中自定义属性的节点名,顺序跟subClz对应
* @param toIgnoreClz
* 针对集合属性,在xml中忽略属性名标签
* @param toIgnoreTag
* 集合属性的属性名
* @return
*/
@SuppressWarnings("rawtypes")
public static String buildCustomXML(Object obj, Class[] subClz, String[] subClzAlias, Class[] toIgnoreClz,
String[] toIgnoreTag) {
XStream xs = UserDefinedXStream.createUserDefXStream();
xs.alias("xml", obj.getClass());
if (subClz != null && subClz.length > 0) {
if (subClzAlias != null) {
for (int i = 0; i < subClz.length; i++) {
xs.alias(subClzAlias[i], subClz[i]);
}
} else {
for (Class clz : subClz) {
xs.alias(clz.getSimpleName(), clz);
}
}
}
/** 针对实 <SUF>*/
if (toIgnoreTag != null && toIgnoreTag.length > 0) {
for (int i = 0; i < toIgnoreTag.length; i++) {
xs.addImplicitCollection(toIgnoreClz[i], toIgnoreTag[i], toIgnoreClz[i].getSimpleName(), toIgnoreClz[i]);
}
}
return xs.toXML(obj);
}
public static void main(String[] args) {
TextMessage msg = new TextMessage("qinglv2007", "chainren", System.currentTimeMillis(), 1323423L,
"欢迎注册微信公众平台,这里有你想不到惊喜哦~");
System.out.println(buildSimpleXML(msg));
System.out.println("==========================回复文本消息xml格式===================================");
org.weixin4j.entity.response.TextMessage respTextMsg = new org.weixin4j.entity.response.TextMessage(
"rengui756", "itumei", System.currentTimeMillis(), WeixinConstants.MSG_TYPE_TEXT);
respTextMsg.setContent("回复的文本消息");
String respTextMsgXml = buildSimpleXML(respTextMsg);
System.out.println(respTextMsgXml);
System.out.println("==========================回复图片消息xml格式===================================");
ImageMessage respImageMsg = new ImageMessage("rengui756", "itumei", System.currentTimeMillis());
respImageMsg.setImage(new Image("xxxesdf732432"));
String respImageMsgXml = buildCustomXML(respImageMsg, new Class[] { Image.class }, null, null, null);
System.out.println(respImageMsgXml);
System.out.println("==========================回复语音消息xml格式===================================");
VoiceMessage respVoiceMsg = new VoiceMessage("rengui756", "itumei", System.currentTimeMillis());
respVoiceMsg.setVoice(new Voice("xdfs32391x"));
String respVoiceMsgXml = buildCustomXML(respVoiceMsg, new Class[] { Voice.class }, null, null, null);
System.out.println(respVoiceMsgXml);
System.out.println("==========================回复视频消息xml格式===================================");
VideoMessage respVideoMsg = new VideoMessage("rengui756", "itumei", System.currentTimeMillis());
respVideoMsg.setVideo(new Video("xd320nhds", "这是视频消息", "视频视频视频啊啊啊啊"));
String respVideoMsgXml = buildCustomXML(respVideoMsg, new Class[] { Voice.class }, null, null, null);
System.out.println(respVideoMsgXml);
System.out.println("==========================回复音乐消息xml格式===================================");
MusicMessage respMusicMsg = new MusicMessage("rengui756", "itumei", System.currentTimeMillis());
respMusicMsg.setMusic(new Music("音乐", "回复音乐消息", "http://kugou.com/music=mg.mp3",
"http://kugou.com/music=mgh.mp3", "xds232"));
String respMusicMsgXml = buildCustomXML(respMusicMsg, new Class[] { Voice.class }, null, null, null);
System.out.println(respMusicMsgXml);
System.out.println("==========================回复多图文消息xml格式===================================");
ArticleMessage respArticleMsg = new ArticleMessage("rengui756", "itumei", System.currentTimeMillis());
List<Article> articles = new ArrayList<Article>();
articles.add(new Article("文章1", "回复多图文第一篇", "http://pic/pic1.jpg", "http://article/article1"));
articles.add(new Article("文章2", "回复多图文第二篇", "http://pic/pic2.jpg", "http://article/article2"));
articles.add(new Article("文章3", "回复多图文第三篇", "http://pic/pic3.jpg", "http://article/article3"));
respArticleMsg.setArticles(articles);
respArticleMsg.setArticleCount(3);
String respArticleMsgXml = buildCustomXML(respArticleMsg, new Class[] { Article.class },
new String[] { "Item" }, null, null);
System.out.println(respArticleMsgXml);
}
}
| false | 1,655 | 16 | 1,932 | 14 | 1,924 | 13 | 1,932 | 14 | 2,395 | 25 | false | false | false | false | false | true |
63423_9 | package cn.leanvision.common.util;
import android.content.Context;
/**
* @author lvshicheng
* @date 2015-1-23 11:32:37
* @description 主要用于设备类型的操作
*/
public class DeviceTypeUtil {
/**
* 控制面板类型 - 通用
*/
public static final String PANEL_TYPE_COMMON = "GENE";
/**
* 设备的状态
*/
public static final String DEV_STATUS_A002 = "A002";// 插控失联(灰) 默认失联
public static final String DEV_STATUS_A003 = "A003";// 插孔正常,设备功率小于某个值。(蓝)
public static final String DEV_STATUS_A004 = "A004";// 正常工作(绿)
public static final String DEV_STATUS_A005 = "A005";// 正常工作 与A002是相反状态
/**
* 红外类
*/
public static final String TYPE_KGHW = "KGHW";
/**
* 开关类
*/
public static final String TYPE_KG = "KG";
/**
* 电视机
*/
public static final String TYPE_KGTV = "KGTV";
/**
* 空气净化器
*/
public static final String TYPE_KGKJ = "KGKJ";
/**
* 红外热水器
*/
public static final String TYPE_KGHE = "KGHE";
/**
* 红外风扇
*/
public static final String TYPE_KGFA = "KGFA";
/**
* 通用红外类型
*/
public static final String TYPE_KGGE = "KGGE";
/**
* 电视机顶盒
*/
public static final String TYPE_KGST = "KGST";
/**
* 目前的红外设备名称
*/
private static final String[] HW_TYPENAME = new String[]{"空调", "电视", "遥控电风扇", "电视机顶盒", "遥控音箱", "DVD播放器", "空气净化器", "玩具"};
/**
* 通过设备名称获取器设备大类型
*/
public static String getBigTypeByTypeName(String typeName) {
String bigType = TYPE_KG; // 默认开关类
for (int i = 0; i < HW_TYPENAME.length; i++) {
if (HW_TYPENAME[i].equals(typeName)) {
bigType = TYPE_KGHW;
break;
}
}
return bigType;
}
/**
* @param statuesType : 设备状态类型 三种类型 - 正常,用电,失联
* @param devType : 设备类型,如电灯...
* @param bigType : 设备总的分类,暂时只分为两类 - 红外(KGHW)和非红外(KG)
* @description 更具设备类型获取相应的设备图像
*/
public static int getDeviceIcon(Context context, String statuesType, String devType, String bigType) {
String value = "mydevice_chazuo";
// 为了兼容以前版本
if (TYPE_KG.equals(bigType) || "1".equals(bigType)) {
bigType = TYPE_KG;
} else if (TYPE_KGHW.equals(bigType) || "2".equals(bigType)) {
bigType = TYPE_KGHW;
}
// mydevice_chazuo - mydevice_chazuo_n - mydevice_chazuo_unwork - mydevice_dianbingxiang_off
if (TYPE_KG.equals(bigType)) {
if ("台灯".equals(devType)) {
value = "mydevice_dengpao";
} else if ("插座".equals(devType)) {
value = "mydevice_chazuo";
} else if ("手机充电器".equals(devType)) {
value = "mydevice_chongdianqi";
} else if ("普通电风扇".equals(devType)) {
value = "mydevice_dianfengshan";
} else if ("普通洗衣机".equals(devType)) {
value = "mydevice_xiyiji";
} else if ("热水器".equals(devType)) {
value = "mydevice_reshuiqi";
} else if ("饮水机".equals(devType)) {
value = "mydevice_yinshuiji";
} else if ("冰箱".equals(devType)) {
value = "mydevice_dianbingxiang";
} else {
value = "mydevice_chazuo";
}
} else if (TYPE_KGHW.equals(bigType)) {
// 红外类显示布局
if ("空调".equals(devType)) {
value = "mydevice_kongtiao";
} else if ("遥控电风扇".equals(devType)) {
value = "mydevice_yaokongfengshan";
} else if ("遥控音箱".equals(devType)) {
value = "mydevice_yaokongyinxiang";
} else if ("电视机顶盒".equals(devType)) {
value = "mydevice_dianshihezi";
} else if ("DVD播放器".equals(devType)) {
value = "mydevice_bofangqi";
} else if ("空气净化器".equals(devType)) {
value = "mydevice_kongqijinghua";
} else if ("玩具".equals(devType)) {
value = "mydevice_wanju";
} else if ("电视".equals(devType)) {
value = "mydevice_dianshiji";
} else {
value = "mydevice_chazuo";
}
} else if (TYPE_KGKJ.equals(bigType)) {
value = "mydevice_kongqijinghua";
} else if (TYPE_KGHE.equals(bigType)) {
value = "mydevice_reshuiqi";
} else if (TYPE_KGFA.equals(bigType)) {
value = "mydevice_yaokongfengshan";
} else if (TYPE_KGGE.equals(bigType)) {
value = "mydevice_chazuo"; // 设置插座
} else if (TYPE_KGTV.equals(bigType)) {
value = "mydevice_dianshiji";
}else if(TYPE_KGST.equals(bigType)){
value = "mydevice_dianshihezi";
}
if (StringUtil.isNullOrEmpty(statuesType))
statuesType = DEV_STATUS_A002;
if (DEV_STATUS_A002.equals(statuesType))
// value = value + "_unwork";
value = value + "_off";
else if (DEV_STATUS_A003.equals(statuesType))
value = value + "_n";
return context.getResources().getIdentifier(value, "drawable", context.getPackageName());
}
}
| chakonger/Kongkong-Android | common/src/main/java/cn/leanvision/common/util/DeviceTypeUtil.java | 1,686 | /**
* 电视机
*/ | block_comment | zh-cn | package cn.leanvision.common.util;
import android.content.Context;
/**
* @author lvshicheng
* @date 2015-1-23 11:32:37
* @description 主要用于设备类型的操作
*/
public class DeviceTypeUtil {
/**
* 控制面板类型 - 通用
*/
public static final String PANEL_TYPE_COMMON = "GENE";
/**
* 设备的状态
*/
public static final String DEV_STATUS_A002 = "A002";// 插控失联(灰) 默认失联
public static final String DEV_STATUS_A003 = "A003";// 插孔正常,设备功率小于某个值。(蓝)
public static final String DEV_STATUS_A004 = "A004";// 正常工作(绿)
public static final String DEV_STATUS_A005 = "A005";// 正常工作 与A002是相反状态
/**
* 红外类
*/
public static final String TYPE_KGHW = "KGHW";
/**
* 开关类
*/
public static final String TYPE_KG = "KG";
/**
* 电视机 <SUF>*/
public static final String TYPE_KGTV = "KGTV";
/**
* 空气净化器
*/
public static final String TYPE_KGKJ = "KGKJ";
/**
* 红外热水器
*/
public static final String TYPE_KGHE = "KGHE";
/**
* 红外风扇
*/
public static final String TYPE_KGFA = "KGFA";
/**
* 通用红外类型
*/
public static final String TYPE_KGGE = "KGGE";
/**
* 电视机顶盒
*/
public static final String TYPE_KGST = "KGST";
/**
* 目前的红外设备名称
*/
private static final String[] HW_TYPENAME = new String[]{"空调", "电视", "遥控电风扇", "电视机顶盒", "遥控音箱", "DVD播放器", "空气净化器", "玩具"};
/**
* 通过设备名称获取器设备大类型
*/
public static String getBigTypeByTypeName(String typeName) {
String bigType = TYPE_KG; // 默认开关类
for (int i = 0; i < HW_TYPENAME.length; i++) {
if (HW_TYPENAME[i].equals(typeName)) {
bigType = TYPE_KGHW;
break;
}
}
return bigType;
}
/**
* @param statuesType : 设备状态类型 三种类型 - 正常,用电,失联
* @param devType : 设备类型,如电灯...
* @param bigType : 设备总的分类,暂时只分为两类 - 红外(KGHW)和非红外(KG)
* @description 更具设备类型获取相应的设备图像
*/
public static int getDeviceIcon(Context context, String statuesType, String devType, String bigType) {
String value = "mydevice_chazuo";
// 为了兼容以前版本
if (TYPE_KG.equals(bigType) || "1".equals(bigType)) {
bigType = TYPE_KG;
} else if (TYPE_KGHW.equals(bigType) || "2".equals(bigType)) {
bigType = TYPE_KGHW;
}
// mydevice_chazuo - mydevice_chazuo_n - mydevice_chazuo_unwork - mydevice_dianbingxiang_off
if (TYPE_KG.equals(bigType)) {
if ("台灯".equals(devType)) {
value = "mydevice_dengpao";
} else if ("插座".equals(devType)) {
value = "mydevice_chazuo";
} else if ("手机充电器".equals(devType)) {
value = "mydevice_chongdianqi";
} else if ("普通电风扇".equals(devType)) {
value = "mydevice_dianfengshan";
} else if ("普通洗衣机".equals(devType)) {
value = "mydevice_xiyiji";
} else if ("热水器".equals(devType)) {
value = "mydevice_reshuiqi";
} else if ("饮水机".equals(devType)) {
value = "mydevice_yinshuiji";
} else if ("冰箱".equals(devType)) {
value = "mydevice_dianbingxiang";
} else {
value = "mydevice_chazuo";
}
} else if (TYPE_KGHW.equals(bigType)) {
// 红外类显示布局
if ("空调".equals(devType)) {
value = "mydevice_kongtiao";
} else if ("遥控电风扇".equals(devType)) {
value = "mydevice_yaokongfengshan";
} else if ("遥控音箱".equals(devType)) {
value = "mydevice_yaokongyinxiang";
} else if ("电视机顶盒".equals(devType)) {
value = "mydevice_dianshihezi";
} else if ("DVD播放器".equals(devType)) {
value = "mydevice_bofangqi";
} else if ("空气净化器".equals(devType)) {
value = "mydevice_kongqijinghua";
} else if ("玩具".equals(devType)) {
value = "mydevice_wanju";
} else if ("电视".equals(devType)) {
value = "mydevice_dianshiji";
} else {
value = "mydevice_chazuo";
}
} else if (TYPE_KGKJ.equals(bigType)) {
value = "mydevice_kongqijinghua";
} else if (TYPE_KGHE.equals(bigType)) {
value = "mydevice_reshuiqi";
} else if (TYPE_KGFA.equals(bigType)) {
value = "mydevice_yaokongfengshan";
} else if (TYPE_KGGE.equals(bigType)) {
value = "mydevice_chazuo"; // 设置插座
} else if (TYPE_KGTV.equals(bigType)) {
value = "mydevice_dianshiji";
}else if(TYPE_KGST.equals(bigType)){
value = "mydevice_dianshihezi";
}
if (StringUtil.isNullOrEmpty(statuesType))
statuesType = DEV_STATUS_A002;
if (DEV_STATUS_A002.equals(statuesType))
// value = value + "_unwork";
value = value + "_off";
else if (DEV_STATUS_A003.equals(statuesType))
value = value + "_n";
return context.getResources().getIdentifier(value, "drawable", context.getPackageName());
}
}
| false | 1,504 | 8 | 1,684 | 9 | 1,712 | 9 | 1,684 | 9 | 2,091 | 11 | false | false | false | false | false | true |
18606_11 | package com.example.chenyu.shaketofresh;
import android.app.Fragment;
import android.app.Service;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Think on 2015/11/7.
*/
public class ListViewFragment extends Fragment implements SensorEventListener {
List<Map<String, Object>> mData = new ArrayList<Map<String, Object>>();
private String[] mListTitle = {"功能: ", "附带:", "姓名: ", "我的QQ:", "QQ学习群:", "邮箱:"};
private String[] mListStr = {"手机摇一摇震动刷新", "摇出我的二维码", "陈喻", "2657607916", "319010802", "2657607916@qq.com"};
// private String[] mListTitle = {"姓名: ", "昵称:", "年龄:", "胸围:","爱好: ", "性格:"};
// private String[] mListStr = {"陈彩凤", "小恐龙", "23", "快到D了", "喜欢脱老公的短裤","火爆生猛"};
private ListView mlistView = null;
private ListView lv;
private SimpleAdapter adapter;
private int i = 0;
private SensorManager mSensorManager;//定义sensor管理器
private Vibrator vibrator; //震动
private int m=2;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.listview_fragment, container, false);
mData = getmData();
lv = (ListView) view.findViewById(R.id.listview_fragment);
adapter = new SimpleAdapter(getActivity(), mData, R.layout.simple_list_item, new String[]{"title", "text"}, new int[]{R.id.text1, R.id.text2});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),"生日快乐",Toast.LENGTH_SHORT).show();
}
});
//获取传感器管理服务
mSensorManager = (SensorManager) getActivity().getSystemService(Service.SENSOR_SERVICE);
//震动
vibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);
return view;
}
@Override
public void onResume() {
super.onResume();
//加速度传感器 注册监听
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
//还有SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME等,
//根据不同应用,需要的反应速率不同,具体根据实际情况设定
SensorManager.SENSOR_DELAY_NORMAL);
}
public List<Map<String, Object>> getmData() {
for (int i = 0; i < mListTitle.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", mListTitle[i]);
map.put("text", mListStr[i]);
mData.add(map);
}
return mData;
}
//可以得到传感器实时测量出来的变化值
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
int sensorType = event.sensor.getType();
//values[0]:X轴,values[1]:Y轴,values[2]:Z轴
float[] values = event.values;
if (sensorType == Sensor.TYPE_ACCELEROMETER) {
/*因为一般正常情况下,任意轴数值最大就在9.8~10之间,只有在你突然摇动手机
*的时候,瞬时加速度才会突然增大或减少,所以,经过实际测试,只需监听任一轴的
* 加速度大于14的时候,改变你需要的设置就OK了
*/
if ((Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math.abs(values[2]) > 14)) {
//摇动手机后,设置button上显示的字为空
new GetDataTask().execute();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//当传感器精度改变时回调该方法,Do nothing.
}
private class GetDataTask extends AsyncTask<Void, Void, Map<String, Object>> {
@Override
protected Map<String, Object> doInBackground(Void... params) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "我是第--" + (++i) + "--个被摇出来的");
map.put("text", "");
// if(m%2==0){
// map.put("title", "老婆,生日快乐");
// map.put("text", "");
// m++;
// //摇动手机后,再伴随震动提示~~
// vibrator.vibrate(500);
// }else{
// map.put("title", "老婆,我爱你");
// map.put("text", "");
// //摇动手机后,再伴随震动提示~~
// vibrator.vibrate(500);
// m++;
// }
return map;
}
@Override
protected void onPostExecute(Map<String, Object> stringObjectMap) {
// super.onPostExecute(stringObjectMap);
mData.add(stringObjectMap);
adapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed. 如果没有下面的函数那么刷新将不会停
}
}
@Override
public void onStop() {
super.onStop();
//取消注册
mSensorManager.unregisterListener(this);
}
}
| changechenyu/ShakeToFresh | app/src/main/java/com/example/chenyu/shaketofresh/ListViewFragment.java | 1,628 | /*因为一般正常情况下,任意轴数值最大就在9.8~10之间,只有在你突然摇动手机
*的时候,瞬时加速度才会突然增大或减少,所以,经过实际测试,只需监听任一轴的
* 加速度大于14的时候,改变你需要的设置就OK了
*/ | block_comment | zh-cn | package com.example.chenyu.shaketofresh;
import android.app.Fragment;
import android.app.Service;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Think on 2015/11/7.
*/
public class ListViewFragment extends Fragment implements SensorEventListener {
List<Map<String, Object>> mData = new ArrayList<Map<String, Object>>();
private String[] mListTitle = {"功能: ", "附带:", "姓名: ", "我的QQ:", "QQ学习群:", "邮箱:"};
private String[] mListStr = {"手机摇一摇震动刷新", "摇出我的二维码", "陈喻", "2657607916", "319010802", "2657607916@qq.com"};
// private String[] mListTitle = {"姓名: ", "昵称:", "年龄:", "胸围:","爱好: ", "性格:"};
// private String[] mListStr = {"陈彩凤", "小恐龙", "23", "快到D了", "喜欢脱老公的短裤","火爆生猛"};
private ListView mlistView = null;
private ListView lv;
private SimpleAdapter adapter;
private int i = 0;
private SensorManager mSensorManager;//定义sensor管理器
private Vibrator vibrator; //震动
private int m=2;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.listview_fragment, container, false);
mData = getmData();
lv = (ListView) view.findViewById(R.id.listview_fragment);
adapter = new SimpleAdapter(getActivity(), mData, R.layout.simple_list_item, new String[]{"title", "text"}, new int[]{R.id.text1, R.id.text2});
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(),"生日快乐",Toast.LENGTH_SHORT).show();
}
});
//获取传感器管理服务
mSensorManager = (SensorManager) getActivity().getSystemService(Service.SENSOR_SERVICE);
//震动
vibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);
return view;
}
@Override
public void onResume() {
super.onResume();
//加速度传感器 注册监听
mSensorManager.registerListener(this,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
//还有SENSOR_DELAY_UI、SENSOR_DELAY_FASTEST、SENSOR_DELAY_GAME等,
//根据不同应用,需要的反应速率不同,具体根据实际情况设定
SensorManager.SENSOR_DELAY_NORMAL);
}
public List<Map<String, Object>> getmData() {
for (int i = 0; i < mListTitle.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", mListTitle[i]);
map.put("text", mListStr[i]);
mData.add(map);
}
return mData;
}
//可以得到传感器实时测量出来的变化值
@Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
int sensorType = event.sensor.getType();
//values[0]:X轴,values[1]:Y轴,values[2]:Z轴
float[] values = event.values;
if (sensorType == Sensor.TYPE_ACCELEROMETER) {
/*因为一 <SUF>*/
if ((Math.abs(values[0]) > 14 || Math.abs(values[1]) > 14 || Math.abs(values[2]) > 14)) {
//摇动手机后,设置button上显示的字为空
new GetDataTask().execute();
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
//当传感器精度改变时回调该方法,Do nothing.
}
private class GetDataTask extends AsyncTask<Void, Void, Map<String, Object>> {
@Override
protected Map<String, Object> doInBackground(Void... params) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "我是第--" + (++i) + "--个被摇出来的");
map.put("text", "");
// if(m%2==0){
// map.put("title", "老婆,生日快乐");
// map.put("text", "");
// m++;
// //摇动手机后,再伴随震动提示~~
// vibrator.vibrate(500);
// }else{
// map.put("title", "老婆,我爱你");
// map.put("text", "");
// //摇动手机后,再伴随震动提示~~
// vibrator.vibrate(500);
// m++;
// }
return map;
}
@Override
protected void onPostExecute(Map<String, Object> stringObjectMap) {
// super.onPostExecute(stringObjectMap);
mData.add(stringObjectMap);
adapter.notifyDataSetChanged();
// Call onRefreshComplete when the list has been refreshed. 如果没有下面的函数那么刷新将不会停
}
}
@Override
public void onStop() {
super.onStop();
//取消注册
mSensorManager.unregisterListener(this);
}
}
| false | 1,327 | 73 | 1,627 | 83 | 1,587 | 73 | 1,628 | 84 | 2,042 | 134 | false | false | false | false | false | true |
63352_2 | package ty.change.wsn.util;
public class Constants {
public static int NUM = 5;
public static final String NO = "N";
public static final String YES = "Y";
public static final String ENDDEVICE = "EndDevice";
public static final String ROUTER = "Router";
public static final String COORDINATOR = "Coordinator";
public static final String ACTIVITY = "ACTIVITY";
public static final String SLEEP = "SLEEP";
public static final String COORDINATOR_NETADDRESS = "0000";
public static String WSN_PATH = "wsn/";
// 虚拟机调试
public static String WSN_IP = "http://10.0.2.2:8080/";
// 手机调试,无限局域网
// public static String WSN_IP = "http://192.168.1.110:8080/";
public static String XMPP_IP = "";
// // 手机调试,无限局域网
// public static String WSN_IP = "http://192.168.3.163:8080/";
// 花生壳调试
// public static String WSN_IP = "http://hellowsn.vicp.cc/";
public static String SMART_HOME_TV = "电视";
public static final String NODE_Temperature = "温度";
public static final String NODE_Enagery = "能量";
// 查询服务器与串口通信的状态
public final static int COMMAND_CHECK_COMM_STATE = 0;
// 打开服务器与串口通信
public final static int COMMAND_COMM_OPEN = 1;
// 关闭服务器与串口通信
public final static int COMMAND_COMM_CLOSE = 2;
// 开灯
public final static int COMMAND_TURN_ON_LIGHT = 0;
// 关灯
public final static int COMMAND_TURN_OFF_LIGHT = 1;
// 温度设置
public final static int COMMAND_TEMP_SETTING = 2;
// 电压设置
public final static int COMMAND_VOLTAGE_SETTING = 3;
// 周期设置
public final static int COMMAND_CYCLE_SETTING = 4;
// 不报告
public final static int COMMAND_NODE_REPORT_SLEEP = 5;
public final static int COMMAND_AUTHORITY = 100;
// 查询服务器与串口通信的状态
public final static int SERIAL_COMM_STATE = 200;
public final static int ENDDEVICE_SELECTED = 0;
public final static int ROUTER_SELECTED = 1;
public final static int COORDINATOR_SELECTED = 2;
public static final String COMM_OPEN = "开启通信";
public static final String COMM_CLOSE = "关闭通信";
public static final String COMM_OPENED = "通信已经开启";
public static final String COMM_CLOSED = "通信已经终端";
public static final String COMMAND_WSN_STRUCT_REFRESH = "WSN_NT_REFRESH";
public static final String NODE_REPORT_STATE_SLEEP = "-1";
public static final String NODE_REPORT_CYCLE_SLOW = "60";
public static final String NODE_REPORT_CYCLE_NORMAL = "30";
public static final String NODE_REPORT_CYCLE_FREQUENCE = "10";
public static final String NODE_REPORT_STATE_UNABLE = "UNABLE";
public static final String LIGHT_STATE_ON = "ON";
public static final String LIGHT_STATE_OFF = "OFF";
public static final String RESULT = "RESULT";
public static final String REASON = "REASON";
// 推送有关
public static final String SHARED_PREFERENCE_NAME = "client_preferences";
// PREFERENCE KEYS
public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME";
public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME";
public static final String API_KEY = "API_KEY";
public static final String VERSION = "VERSION";
public static final String XMPP_HOST = "XMPP_HOST";
public static final String XMPP_PORT = "XMPP_PORT";
public static final String XMPP_USERNAME = "XMPP_USERNAME";
public static final String XMPP_PASSWORD = "XMPP_PASSWORD";
public static final String XMPP_EMAIL = "XMPP_EMAIL";
public static final String XMPP_AUTHORITY = "XMPP_AUTHORITY";
public static final String XMPP_LASTLOGIN_TIME = "XMPP_LASTLOGIN_TIME";
public static final String XMPP_REGISTER_TIME = "XMPP_REGISTER_TIME";
// public static final String USER_KEY = "USER_KEY";
public static final String DEVICE_ID = "DEVICE_ID";
public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID";
public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON";
public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED";
public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED";
public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED";
public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED";
// NOTIFICATION FIELDS
public static final String NOTIFICATION_ID = "NOTIFICATION_ID";
public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY";
public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE";
public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE";
public static final String NOTIFICATION_URI = "NOTIFICATION_URI";
public static final String NOTIFICATION_TIME = "NOTIFICATION_TIME";
// INTENT ACTIONS
public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION";
public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED";
public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED";
public static final String Connect_SUCCESS = "Connect_SUCCESS";
public static final String ZIGBEE_NODE = "ZIGBEE_NODE";
public static final String SELECTED_NODE = "SELECTED_NODE";
public static final String WSN_NOTI = "WSN_NOTI";
}
| changety/hellowsn | WSNMonitor_Android/src/ty/change/wsn/util/Constants.java | 1,590 | // 手机调试,无限局域网 | line_comment | zh-cn | package ty.change.wsn.util;
public class Constants {
public static int NUM = 5;
public static final String NO = "N";
public static final String YES = "Y";
public static final String ENDDEVICE = "EndDevice";
public static final String ROUTER = "Router";
public static final String COORDINATOR = "Coordinator";
public static final String ACTIVITY = "ACTIVITY";
public static final String SLEEP = "SLEEP";
public static final String COORDINATOR_NETADDRESS = "0000";
public static String WSN_PATH = "wsn/";
// 虚拟机调试
public static String WSN_IP = "http://10.0.2.2:8080/";
// 手机 <SUF>
// public static String WSN_IP = "http://192.168.1.110:8080/";
public static String XMPP_IP = "";
// // 手机调试,无限局域网
// public static String WSN_IP = "http://192.168.3.163:8080/";
// 花生壳调试
// public static String WSN_IP = "http://hellowsn.vicp.cc/";
public static String SMART_HOME_TV = "电视";
public static final String NODE_Temperature = "温度";
public static final String NODE_Enagery = "能量";
// 查询服务器与串口通信的状态
public final static int COMMAND_CHECK_COMM_STATE = 0;
// 打开服务器与串口通信
public final static int COMMAND_COMM_OPEN = 1;
// 关闭服务器与串口通信
public final static int COMMAND_COMM_CLOSE = 2;
// 开灯
public final static int COMMAND_TURN_ON_LIGHT = 0;
// 关灯
public final static int COMMAND_TURN_OFF_LIGHT = 1;
// 温度设置
public final static int COMMAND_TEMP_SETTING = 2;
// 电压设置
public final static int COMMAND_VOLTAGE_SETTING = 3;
// 周期设置
public final static int COMMAND_CYCLE_SETTING = 4;
// 不报告
public final static int COMMAND_NODE_REPORT_SLEEP = 5;
public final static int COMMAND_AUTHORITY = 100;
// 查询服务器与串口通信的状态
public final static int SERIAL_COMM_STATE = 200;
public final static int ENDDEVICE_SELECTED = 0;
public final static int ROUTER_SELECTED = 1;
public final static int COORDINATOR_SELECTED = 2;
public static final String COMM_OPEN = "开启通信";
public static final String COMM_CLOSE = "关闭通信";
public static final String COMM_OPENED = "通信已经开启";
public static final String COMM_CLOSED = "通信已经终端";
public static final String COMMAND_WSN_STRUCT_REFRESH = "WSN_NT_REFRESH";
public static final String NODE_REPORT_STATE_SLEEP = "-1";
public static final String NODE_REPORT_CYCLE_SLOW = "60";
public static final String NODE_REPORT_CYCLE_NORMAL = "30";
public static final String NODE_REPORT_CYCLE_FREQUENCE = "10";
public static final String NODE_REPORT_STATE_UNABLE = "UNABLE";
public static final String LIGHT_STATE_ON = "ON";
public static final String LIGHT_STATE_OFF = "OFF";
public static final String RESULT = "RESULT";
public static final String REASON = "REASON";
// 推送有关
public static final String SHARED_PREFERENCE_NAME = "client_preferences";
// PREFERENCE KEYS
public static final String CALLBACK_ACTIVITY_PACKAGE_NAME = "CALLBACK_ACTIVITY_PACKAGE_NAME";
public static final String CALLBACK_ACTIVITY_CLASS_NAME = "CALLBACK_ACTIVITY_CLASS_NAME";
public static final String API_KEY = "API_KEY";
public static final String VERSION = "VERSION";
public static final String XMPP_HOST = "XMPP_HOST";
public static final String XMPP_PORT = "XMPP_PORT";
public static final String XMPP_USERNAME = "XMPP_USERNAME";
public static final String XMPP_PASSWORD = "XMPP_PASSWORD";
public static final String XMPP_EMAIL = "XMPP_EMAIL";
public static final String XMPP_AUTHORITY = "XMPP_AUTHORITY";
public static final String XMPP_LASTLOGIN_TIME = "XMPP_LASTLOGIN_TIME";
public static final String XMPP_REGISTER_TIME = "XMPP_REGISTER_TIME";
// public static final String USER_KEY = "USER_KEY";
public static final String DEVICE_ID = "DEVICE_ID";
public static final String EMULATOR_DEVICE_ID = "EMULATOR_DEVICE_ID";
public static final String NOTIFICATION_ICON = "NOTIFICATION_ICON";
public static final String SETTINGS_NOTIFICATION_ENABLED = "SETTINGS_NOTIFICATION_ENABLED";
public static final String SETTINGS_SOUND_ENABLED = "SETTINGS_SOUND_ENABLED";
public static final String SETTINGS_VIBRATE_ENABLED = "SETTINGS_VIBRATE_ENABLED";
public static final String SETTINGS_TOAST_ENABLED = "SETTINGS_TOAST_ENABLED";
// NOTIFICATION FIELDS
public static final String NOTIFICATION_ID = "NOTIFICATION_ID";
public static final String NOTIFICATION_API_KEY = "NOTIFICATION_API_KEY";
public static final String NOTIFICATION_TITLE = "NOTIFICATION_TITLE";
public static final String NOTIFICATION_MESSAGE = "NOTIFICATION_MESSAGE";
public static final String NOTIFICATION_URI = "NOTIFICATION_URI";
public static final String NOTIFICATION_TIME = "NOTIFICATION_TIME";
// INTENT ACTIONS
public static final String ACTION_SHOW_NOTIFICATION = "org.androidpn.client.SHOW_NOTIFICATION";
public static final String ACTION_NOTIFICATION_CLICKED = "org.androidpn.client.NOTIFICATION_CLICKED";
public static final String ACTION_NOTIFICATION_CLEARED = "org.androidpn.client.NOTIFICATION_CLEARED";
public static final String Connect_SUCCESS = "Connect_SUCCESS";
public static final String ZIGBEE_NODE = "ZIGBEE_NODE";
public static final String SELECTED_NODE = "SELECTED_NODE";
public static final String WSN_NOTI = "WSN_NOTI";
}
| false | 1,232 | 10 | 1,590 | 10 | 1,521 | 8 | 1,590 | 10 | 2,032 | 14 | false | false | false | false | false | true |
20727_4 | package Medical.domain;
import Medical.framework.domain.BaseEntity;
/**
* 伤病申请表实体类
*
* @author zhengjianfeng
* @date 2018-12-12
*/
public class InjuryHandle extends BaseEntity {
/**
* 主键
*/
private String uid;
/**
* 姓名
*/
private String stuName;
/**
* 学生ID
*/
private String stuId;
/**
* 学生班级
*/
private String classes;
/**
* 医院
*/
private String medical;
/**
* 病情
*/
private String illness;
/**
* 医生ID
*/
private String docName;
/**
* 状态
*/
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
public String getMedical() {
return medical;
}
public void setMedical(String medical) {
this.medical = medical;
}
public String getIllness() {
return illness;
}
public void setIllness(String illness) {
this.illness = illness;
}
public String getDocName() {
return docName;
}
public void setDocName(String docName) {
this.docName = docName;
}
}
| changkimfung/MedicalApp | src/main/java/Medical/domain/InjuryHandle.java | 479 | /**
* 学生班级
*/ | block_comment | zh-cn | package Medical.domain;
import Medical.framework.domain.BaseEntity;
/**
* 伤病申请表实体类
*
* @author zhengjianfeng
* @date 2018-12-12
*/
public class InjuryHandle extends BaseEntity {
/**
* 主键
*/
private String uid;
/**
* 姓名
*/
private String stuName;
/**
* 学生ID
*/
private String stuId;
/**
* 学生班 <SUF>*/
private String classes;
/**
* 医院
*/
private String medical;
/**
* 病情
*/
private String illness;
/**
* 医生ID
*/
private String docName;
/**
* 状态
*/
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuId() {
return stuId;
}
public void setStuId(String stuId) {
this.stuId = stuId;
}
public String getClasses() {
return classes;
}
public void setClasses(String classes) {
this.classes = classes;
}
public String getMedical() {
return medical;
}
public void setMedical(String medical) {
this.medical = medical;
}
public String getIllness() {
return illness;
}
public void setIllness(String illness) {
this.illness = illness;
}
public String getDocName() {
return docName;
}
public void setDocName(String docName) {
this.docName = docName;
}
}
| false | 446 | 10 | 479 | 9 | 525 | 9 | 479 | 9 | 618 | 16 | false | false | false | false | false | true |
59801_1 | package 面试题;
/**
* @Description: 控制执行顺序demo
* @Author: changlu
* @Date: 3:37 PM
*/
public class ExecutionSequenceDemo {
public static void main(String[] args) {
Thread spring = new Thread(new SeasonThreadTask("春天"));
Thread summer = new Thread(new SeasonThreadTask("夏天"));
Thread autumn = new Thread(new SeasonThreadTask("秋天"));
try {
//夏天线程再启动
summer.start();
//主线程等待线程summer执行完,再往下执行
summer.join();
//春天线程先启动
spring.start();
//主线程等待线程spring执行完,再往下执行
spring.join();
//秋天线程最后启动
autumn.start();
//主线程等待线程autumn执行完,再往下执行
autumn.join();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class SeasonThreadTask implements Runnable{
private String name;
public SeasonThreadTask(String name){
this.name = name;
}
@Override
public void run() {
for (int i = 1; i <4; i++) {
System.out.println(this.name + "来了: " + i + "次");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} | changlua/JAVA-demos | JUC/src/main/java/面试题/ExecutionSequenceDemo.java | 349 | //夏天线程再启动
| line_comment | zh-cn | package 面试题;
/**
* @Description: 控制执行顺序demo
* @Author: changlu
* @Date: 3:37 PM
*/
public class ExecutionSequenceDemo {
public static void main(String[] args) {
Thread spring = new Thread(new SeasonThreadTask("春天"));
Thread summer = new Thread(new SeasonThreadTask("夏天"));
Thread autumn = new Thread(new SeasonThreadTask("秋天"));
try {
//夏天 <SUF>
summer.start();
//主线程等待线程summer执行完,再往下执行
summer.join();
//春天线程先启动
spring.start();
//主线程等待线程spring执行完,再往下执行
spring.join();
//秋天线程最后启动
autumn.start();
//主线程等待线程autumn执行完,再往下执行
autumn.join();
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
class SeasonThreadTask implements Runnable{
private String name;
public SeasonThreadTask(String name){
this.name = name;
}
@Override
public void run() {
for (int i = 1; i <4; i++) {
System.out.println(this.name + "来了: " + i + "次");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} | false | 307 | 7 | 346 | 8 | 355 | 6 | 346 | 8 | 437 | 11 | false | false | false | false | false | true |
61177_10 | package com.changlu.system.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.changlu.common.domain.BaseEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
import java.util.List;
/**
* 用户对象 sys_user
*
* @author ruoyi
*/
@TableName(value="sys_user")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SysUser extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 用户ID */
@TableId(value = "user_id",type = IdType.AUTO)
private Long userId;
/** 用户账号 */
private String userName;
/** 用户昵称 */
private String nickName;
/** 用户类型 */
private String userType;
/** 用户邮箱 */
private String email;
/** 手机号码 */
private String phonenumber;
/** 用户性别 */
private String sex;
/** 用户头像 */
private String avatar;
/** 密码 */
@JsonIgnore
private String password;
/** 帐号状态(0正常 1停用) */
private String status;
/** 删除标志(0代表存在 2代表删除) */
private String delFlag;
/** 最后登录IP */
private String loginIp;
/** 最后登录时间 */
private Date loginDate;
/** 角色对象 */
private List<SysRole> roles;
/** 角色ID */
private Long roleId;
/** 真实姓名 */
private String realName;
/** 个人描述 */
private String description;
/** 创建者 */
private String createBy;
/** 更新者 */
private String updateBy;
/** 备注 */
private String remark;
/** 个人照片 */
private String perImg;
//额外字段
/** 专业id */
private Long majorId;
/** 年纪id */
private Long gradeId;
/** 专业名称 */
private String majorName;
/** 年级名 */
private String gradeNum;
public SysUser(String username,String nickName, String password){
this.userName = username;
this.nickName = nickName;
this.password = password;
}
public static boolean isAdmin(Long userId)
{
return userId != null && 1L == userId;
}
public boolean isAdmin()
{
return isAdmin(this.userId);
}
}
| changlua/Studio-Vue | studio-system/src/main/java/com/changlu/system/pojo/SysUser.java | 609 | /** 帐号状态(0正常 1停用) */ | block_comment | zh-cn | package com.changlu.system.pojo;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.changlu.common.domain.BaseEntity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
import java.util.List;
/**
* 用户对象 sys_user
*
* @author ruoyi
*/
@TableName(value="sys_user")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SysUser extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 用户ID */
@TableId(value = "user_id",type = IdType.AUTO)
private Long userId;
/** 用户账号 */
private String userName;
/** 用户昵称 */
private String nickName;
/** 用户类型 */
private String userType;
/** 用户邮箱 */
private String email;
/** 手机号码 */
private String phonenumber;
/** 用户性别 */
private String sex;
/** 用户头像 */
private String avatar;
/** 密码 */
@JsonIgnore
private String password;
/** 帐号状 <SUF>*/
private String status;
/** 删除标志(0代表存在 2代表删除) */
private String delFlag;
/** 最后登录IP */
private String loginIp;
/** 最后登录时间 */
private Date loginDate;
/** 角色对象 */
private List<SysRole> roles;
/** 角色ID */
private Long roleId;
/** 真实姓名 */
private String realName;
/** 个人描述 */
private String description;
/** 创建者 */
private String createBy;
/** 更新者 */
private String updateBy;
/** 备注 */
private String remark;
/** 个人照片 */
private String perImg;
//额外字段
/** 专业id */
private Long majorId;
/** 年纪id */
private Long gradeId;
/** 专业名称 */
private String majorName;
/** 年级名 */
private String gradeNum;
public SysUser(String username,String nickName, String password){
this.userName = username;
this.nickName = nickName;
this.password = password;
}
public static boolean isAdmin(Long userId)
{
return userId != null && 1L == userId;
}
public boolean isAdmin()
{
return isAdmin(this.userId);
}
}
| false | 536 | 15 | 609 | 15 | 639 | 14 | 609 | 15 | 833 | 20 | false | false | false | false | false | true |
8291_2 | package org.mengyun.tcctransaction.dashboard.dto;
/**
* @Author huabao.fang
* @Date 2022/6/14 14:17
**/
public class DomainStoreDto {
private String domain;
// 最大重试次数
private int maxRetryCount;
// 恢复任务最大TPS
private int maxRecoveryRequestPerSecond;
// 告警手机号列表,多个以英文逗号分割
private String phoneNumbers;
// 告警类型: DING-钉钉, SMS-短信, PHONE-电话
private String alertType;
//告警阈值
private int threshold;
//达到重试上限的告警阈值
private int reachLimitThreshold;
// 告警间隔时间(单位为分钟) 避免频繁告警
private int intervalMinutes;
// 上次告警时间
private String lastAlertTime;
// 钉钉机器人地址
private String dingRobotUrl;
private String createTime;
private String lastUpdateTime;
private long version = 0L;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public int getMaxRetryCount() {
return maxRetryCount;
}
public void setMaxRetryCount(int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(String lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(String phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public String getAlertType() {
return alertType;
}
public void setAlertType(String alertType) {
this.alertType = alertType;
}
public int getThreshold() {
return threshold;
}
public void setThreshold(int threshold) {
this.threshold = threshold;
}
public int getReachLimitThreshold() {
return reachLimitThreshold;
}
public void setReachLimitThreshold(int reachLimitThreshold) {
this.reachLimitThreshold = reachLimitThreshold;
}
public int getIntervalMinutes() {
return intervalMinutes;
}
public void setIntervalMinutes(int intervalMinutes) {
this.intervalMinutes = intervalMinutes;
}
public String getDingRobotUrl() {
return dingRobotUrl;
}
public void setDingRobotUrl(String dingRobotUrl) {
this.dingRobotUrl = dingRobotUrl;
}
public String getLastAlertTime() {
return lastAlertTime;
}
public void setLastAlertTime(String lastAlertTime) {
this.lastAlertTime = lastAlertTime;
}
public int getMaxRecoveryRequestPerSecond() {
return maxRecoveryRequestPerSecond;
}
public void setMaxRecoveryRequestPerSecond(int maxRecoveryRequestPerSecond) {
this.maxRecoveryRequestPerSecond = maxRecoveryRequestPerSecond;
}
}
| changmingxie/tcc-transaction | tcc-transaction-core/src/main/java/org/mengyun/tcctransaction/dashboard/dto/DomainStoreDto.java | 770 | // 恢复任务最大TPS | line_comment | zh-cn | package org.mengyun.tcctransaction.dashboard.dto;
/**
* @Author huabao.fang
* @Date 2022/6/14 14:17
**/
public class DomainStoreDto {
private String domain;
// 最大重试次数
private int maxRetryCount;
// 恢复 <SUF>
private int maxRecoveryRequestPerSecond;
// 告警手机号列表,多个以英文逗号分割
private String phoneNumbers;
// 告警类型: DING-钉钉, SMS-短信, PHONE-电话
private String alertType;
//告警阈值
private int threshold;
//达到重试上限的告警阈值
private int reachLimitThreshold;
// 告警间隔时间(单位为分钟) 避免频繁告警
private int intervalMinutes;
// 上次告警时间
private String lastAlertTime;
// 钉钉机器人地址
private String dingRobotUrl;
private String createTime;
private String lastUpdateTime;
private long version = 0L;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public int getMaxRetryCount() {
return maxRetryCount;
}
public void setMaxRetryCount(int maxRetryCount) {
this.maxRetryCount = maxRetryCount;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getLastUpdateTime() {
return lastUpdateTime;
}
public void setLastUpdateTime(String lastUpdateTime) {
this.lastUpdateTime = lastUpdateTime;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getPhoneNumbers() {
return phoneNumbers;
}
public void setPhoneNumbers(String phoneNumbers) {
this.phoneNumbers = phoneNumbers;
}
public String getAlertType() {
return alertType;
}
public void setAlertType(String alertType) {
this.alertType = alertType;
}
public int getThreshold() {
return threshold;
}
public void setThreshold(int threshold) {
this.threshold = threshold;
}
public int getReachLimitThreshold() {
return reachLimitThreshold;
}
public void setReachLimitThreshold(int reachLimitThreshold) {
this.reachLimitThreshold = reachLimitThreshold;
}
public int getIntervalMinutes() {
return intervalMinutes;
}
public void setIntervalMinutes(int intervalMinutes) {
this.intervalMinutes = intervalMinutes;
}
public String getDingRobotUrl() {
return dingRobotUrl;
}
public void setDingRobotUrl(String dingRobotUrl) {
this.dingRobotUrl = dingRobotUrl;
}
public String getLastAlertTime() {
return lastAlertTime;
}
public void setLastAlertTime(String lastAlertTime) {
this.lastAlertTime = lastAlertTime;
}
public int getMaxRecoveryRequestPerSecond() {
return maxRecoveryRequestPerSecond;
}
public void setMaxRecoveryRequestPerSecond(int maxRecoveryRequestPerSecond) {
this.maxRecoveryRequestPerSecond = maxRecoveryRequestPerSecond;
}
}
| false | 741 | 9 | 770 | 8 | 837 | 6 | 770 | 8 | 1,033 | 12 | false | false | false | false | false | true |
63528_54 | package db;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Vector;
/**
* Created by 28713 on 2016/12/14.
*/
public class ConnectionPool {
private String jdbcDriver = ""; // 数据库驱动
private String dbUrl = ""; // 数据 URL
private String dbUsername = ""; // 数据库用户名
private String dbPassword = ""; // 数据库用户密码
private String testTable = ""; // 测试连接是否可用的测试表名,默认没有测试表
private int initialConnections = 5; // 连接池的初始大小
private int incrementalConnections = 5; // 连接池自动增加的大小
private int maxConnections = 50; // 连接池最大的大小
private Vector connections = null; // 存放连接池中数据库连接的向量 , 初始时为 null
// 它中存放的对象为 PooledConnection 型
ConnectionPool(String jdbcDriver, String dbUrl, String dbUsername,
String dbPassword) {
this.jdbcDriver = jdbcDriver;
this.dbUrl = dbUrl;
this.dbUsername = dbUsername;
this.dbPassword = dbPassword;
}
public int getInitialConnections() {
return this.initialConnections;
}
public void setInitialConnections(int initialConnections) {
this.initialConnections = initialConnections;
}
public int getIncrementalConnections() {
return this.incrementalConnections;
}
public void setIncrementalConnections(int incrementalConnections) {
this.incrementalConnections = incrementalConnections;
}
public int getMaxConnections() {
return this.maxConnections;
}
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
public String getTestTable() {
return this.testTable;
}
public void setTestTable(String testTable) {
this.testTable = testTable;
}
public synchronized void createPool() throws Exception {
// 确保连接池没有创建
// 假如连接池己经创建了,保存连接的向量 connections 不会为空
if (connections != null) {
return; // 假如己经创建,则返回
}
// 实例化 JDBC Driver 中指定的驱动类实例
Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance());
DriverManager.registerDriver(driver); // 注册 JDBC 驱动程序
// 创建保存连接的向量 , 初始时有 0 个元素
connections = new Vector();
// 根据 initialConnections 中设置的值,创建连接。
createConnections(this.initialConnections);
System.out.println("ConnectionPool creates successfully!");
}
private void createConnections(int numConnections) throws SQLException {
// 循环创建指定数目的数据库连接
for (int x = 0; x < numConnections; x++) {
// 是否连接池中的数据库连接的数量己经达到最大?最大值由类成员 maxConnections
// 指出,假如 maxConnections 为 0 或负数,表示连接数量没有限制。
// 假如连接数己经达到最大,即退出。
if (this.maxConnections > 0 &&
this.connections.size() >= this.maxConnections) {
break;
}
//add a new PooledConnection object to connections vector
// 增加一个连接到连接池中(向量 connections 中)
try {
connections.addElement(new PooledConnection(newConnection()));
} catch (SQLException e) {
System.out.println("Fail to create ConnectionPool!" + e.getMessage());
throw new SQLException();
}
System.out.println("Connection has be created!");
}
}
private Connection newConnection() throws SQLException {
// 创建一个数据库连接
Connection conn = DriverManager.getConnection(dbUrl, dbUsername,
dbPassword);
// 假如这是第一次创建数据库连接,即检查数据库,获得此数据库答应支持的
// 最大客户连接数目
//connections.size()==0 表示目前没有连接己被创建
if (connections.size() == 0) {
DatabaseMetaData metaData = conn.getMetaData();
int driverMaxConnections = metaData.getMaxConnections();
// 数据库返回的 driverMaxConnections 若为 0 ,表示此数据库没有最大
// 连接限制,或数据库的最大连接限制不知道
//driverMaxConnections 为返回的一个整数,表示此数据库答应客户连接的数目
// 假如连接池中设置的最大连接数量大于数据库答应的连接数目 , 则置连接池的最大
// 连接数目为数据库答应的最大数目
if (driverMaxConnections > 0 &&
this.maxConnections > driverMaxConnections) {
this.maxConnections = driverMaxConnections;
}
}
return conn; // 返回创建的新的数据库连接
}
public synchronized Connection getConnection() throws SQLException {
// 确保连接池己被创建
if (connections == null) {
return null; // 连接池还没创建,则返回 null
}
Connection conn = getFreeConnection(); // 获得一个可用的数据库连接
// 假如目前没有可以使用的连接,即所有的连接都在使用中
while (conn == null) {
// 等一会再试
wait(250);
conn = getFreeConnection(); // 重新再试,直到获得可用的连接,假如
//getFreeConnection() 返回的为 null
// 则表明创建一批连接后也不可获得可用连接
}
return conn; // 返回获得的可用的连接
}
private Connection getFreeConnection() throws SQLException {
// 从连接池中获得一个可用的数据库连接
Connection conn = findFreeConnection();
if (conn == null) {
// 假如目前连接池中没有可用的连接
// 创建一些连接
createConnections(incrementalConnections);
// 重新从池中查找是否有可用连接
conn = findFreeConnection();
if (conn == null) {
// 假如创建连接后仍获得不到可用的连接,则返回 null
return null;
}
}
return conn;
}
private Connection findFreeConnection() throws SQLException {
Connection conn = null;
PooledConnection pConn = null;
// 获得连接池向量中所有的对象
Enumeration enumerate = connections.elements();
// 遍历所有的对象,看是否有可用的连接
while (enumerate.hasMoreElements()) {
pConn = (PooledConnection) enumerate.nextElement();
if (!pConn.isBusy()) {
// 假如此对象不忙,则获得它的数据库连接并把它设为忙
conn = pConn.getConnection();
pConn.setBusy(true);
// 测试此连接是否可用
if (!testConnection(conn)) {
// 假如此连接不可再用了,则创建一个新的连接,
// 并替换此不可用的连接对象,假如创建失败,返回 null
try {
conn = newConnection();
} catch (SQLException e) {
System.out.println("Fail to create ConnectionPool!" + e.getMessage());
return null;
}
pConn.setConnection(conn);
}
break; // 己经找到一个可用的连接,退出
}
}
return conn; // 返回找到到的可用连接
}
private boolean testConnection(Connection conn) {
try {
// 判定测试表是否存在
if (testTable.equals("")) {
// 假如测试表为空,试着使用此连接的 setAutoCommit() 方法
// 来判定连接否可用(此方法只在部分数据库可用,假如不可用 ,
// 抛出异常)。注重:使用测试表的方法更可靠
conn.setAutoCommit(true);
} else { // 有测试表的时候使用测试表测试
//check if this connection is valid
Statement stmt = conn.createStatement();
stmt.execute("select count(*) from " + testTable);
}
} catch (SQLException e) {
// 上面抛出异常,此连接己不可用,关闭它,并返回 false;
closeConnection(conn);
return false;
}
// 连接可用,返回 true
return true;
}
public void returnConnection(Connection conn) {
// 确保连接池存在,假如连接没有创建(不存在),直接返回
if (connections == null) {
System.out.println("ConnectionPool is not existed.Can't return!");
return;
}
PooledConnection pConn = null;
Enumeration enumerate = connections.elements();
// 遍历连接池中的所有连接,找到这个要返回的连接对象
while (enumerate.hasMoreElements()) {
pConn = (PooledConnection) enumerate.nextElement();
// 先找到连接池中的要返回的连接对象
if (conn == pConn.getConnection()) {
// 找到了 , 设置此连接为空闲状态
pConn.setBusy(false);
break;
}
}
}
public synchronized void refreshConnections() throws SQLException {
// 确保连接池己创新存在
if (connections == null) {
System.out.println("ConnectionPool is not existed.Can't refresh!");
return;
}
PooledConnection pConn = null;
Enumeration enumerate = connections.elements();
while (enumerate.hasMoreElements()) {
// 获得一个连接对象
pConn = (PooledConnection) enumerate.nextElement();
// 假如对象忙则等 5 秒 ,5 秒后直接刷新
if (pConn.isBusy()) {
wait(5000); // 等 5 秒
}
// 关闭此连接,用一个新的连接代替它。
closeConnection(pConn.getConnection());
pConn.setConnection(newConnection());
pConn.setBusy(false);
}
}
public synchronized void closeConnectionPool() throws SQLException {
// 确保连接池存在,假如不存在,返回
if (connections == null) {
System.out.println("ConnectionPool is not existed.Can't close!");
return;
}
PooledConnection pConn = null;
Enumeration enumerate = connections.elements();
while (enumerate.hasMoreElements()) {
pConn = (PooledConnection) enumerate.nextElement();
// 假如忙,等 5 秒
if (pConn.isBusy()) {
wait(5000); // 等 5 秒
}
//5 秒后直接关闭它
closeConnection(pConn.getConnection());
// 从连接池向量中删除它
connections.removeElement(pConn);
}
// 置连接池为空
connections = null;
}
private void closeConnection(Connection conn) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("An error occur to close connection." + e.getMessage());
}
}
private void wait(int mSeconds) {
try {
Thread.sleep(mSeconds);
} catch (InterruptedException e) {
}
}
class PooledConnection {
Connection connection = null; // 数据库连接
boolean busy = false; // 此连接是否正在使用的标志,默认没有正在使用
// 构造函数,根据一个 Connection 构告一个 PooledConnection 对象
public PooledConnection(Connection connection) {
this.connection = connection;
}
// 返回此对象中的连接
public Connection getConnection() {
return connection;
}
// 设置此对象的,连接
public void setConnection(Connection connection) {
this.connection = connection;
}
// 获得对象连接是否忙
public boolean isBusy() {
return busy;
}
// 设置对象的连接正在忙
public void setBusy(boolean busy) {
this.busy = busy;
}
}
}
| changqing18/Shopping | src/db/ConnectionPool.java | 2,683 | // 己经找到一个可用的连接,退出 | line_comment | zh-cn | package db;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Vector;
/**
* Created by 28713 on 2016/12/14.
*/
public class ConnectionPool {
private String jdbcDriver = ""; // 数据库驱动
private String dbUrl = ""; // 数据 URL
private String dbUsername = ""; // 数据库用户名
private String dbPassword = ""; // 数据库用户密码
private String testTable = ""; // 测试连接是否可用的测试表名,默认没有测试表
private int initialConnections = 5; // 连接池的初始大小
private int incrementalConnections = 5; // 连接池自动增加的大小
private int maxConnections = 50; // 连接池最大的大小
private Vector connections = null; // 存放连接池中数据库连接的向量 , 初始时为 null
// 它中存放的对象为 PooledConnection 型
ConnectionPool(String jdbcDriver, String dbUrl, String dbUsername,
String dbPassword) {
this.jdbcDriver = jdbcDriver;
this.dbUrl = dbUrl;
this.dbUsername = dbUsername;
this.dbPassword = dbPassword;
}
public int getInitialConnections() {
return this.initialConnections;
}
public void setInitialConnections(int initialConnections) {
this.initialConnections = initialConnections;
}
public int getIncrementalConnections() {
return this.incrementalConnections;
}
public void setIncrementalConnections(int incrementalConnections) {
this.incrementalConnections = incrementalConnections;
}
public int getMaxConnections() {
return this.maxConnections;
}
public void setMaxConnections(int maxConnections) {
this.maxConnections = maxConnections;
}
public String getTestTable() {
return this.testTable;
}
public void setTestTable(String testTable) {
this.testTable = testTable;
}
public synchronized void createPool() throws Exception {
// 确保连接池没有创建
// 假如连接池己经创建了,保存连接的向量 connections 不会为空
if (connections != null) {
return; // 假如己经创建,则返回
}
// 实例化 JDBC Driver 中指定的驱动类实例
Driver driver = (Driver) (Class.forName(this.jdbcDriver).newInstance());
DriverManager.registerDriver(driver); // 注册 JDBC 驱动程序
// 创建保存连接的向量 , 初始时有 0 个元素
connections = new Vector();
// 根据 initialConnections 中设置的值,创建连接。
createConnections(this.initialConnections);
System.out.println("ConnectionPool creates successfully!");
}
private void createConnections(int numConnections) throws SQLException {
// 循环创建指定数目的数据库连接
for (int x = 0; x < numConnections; x++) {
// 是否连接池中的数据库连接的数量己经达到最大?最大值由类成员 maxConnections
// 指出,假如 maxConnections 为 0 或负数,表示连接数量没有限制。
// 假如连接数己经达到最大,即退出。
if (this.maxConnections > 0 &&
this.connections.size() >= this.maxConnections) {
break;
}
//add a new PooledConnection object to connections vector
// 增加一个连接到连接池中(向量 connections 中)
try {
connections.addElement(new PooledConnection(newConnection()));
} catch (SQLException e) {
System.out.println("Fail to create ConnectionPool!" + e.getMessage());
throw new SQLException();
}
System.out.println("Connection has be created!");
}
}
private Connection newConnection() throws SQLException {
// 创建一个数据库连接
Connection conn = DriverManager.getConnection(dbUrl, dbUsername,
dbPassword);
// 假如这是第一次创建数据库连接,即检查数据库,获得此数据库答应支持的
// 最大客户连接数目
//connections.size()==0 表示目前没有连接己被创建
if (connections.size() == 0) {
DatabaseMetaData metaData = conn.getMetaData();
int driverMaxConnections = metaData.getMaxConnections();
// 数据库返回的 driverMaxConnections 若为 0 ,表示此数据库没有最大
// 连接限制,或数据库的最大连接限制不知道
//driverMaxConnections 为返回的一个整数,表示此数据库答应客户连接的数目
// 假如连接池中设置的最大连接数量大于数据库答应的连接数目 , 则置连接池的最大
// 连接数目为数据库答应的最大数目
if (driverMaxConnections > 0 &&
this.maxConnections > driverMaxConnections) {
this.maxConnections = driverMaxConnections;
}
}
return conn; // 返回创建的新的数据库连接
}
public synchronized Connection getConnection() throws SQLException {
// 确保连接池己被创建
if (connections == null) {
return null; // 连接池还没创建,则返回 null
}
Connection conn = getFreeConnection(); // 获得一个可用的数据库连接
// 假如目前没有可以使用的连接,即所有的连接都在使用中
while (conn == null) {
// 等一会再试
wait(250);
conn = getFreeConnection(); // 重新再试,直到获得可用的连接,假如
//getFreeConnection() 返回的为 null
// 则表明创建一批连接后也不可获得可用连接
}
return conn; // 返回获得的可用的连接
}
private Connection getFreeConnection() throws SQLException {
// 从连接池中获得一个可用的数据库连接
Connection conn = findFreeConnection();
if (conn == null) {
// 假如目前连接池中没有可用的连接
// 创建一些连接
createConnections(incrementalConnections);
// 重新从池中查找是否有可用连接
conn = findFreeConnection();
if (conn == null) {
// 假如创建连接后仍获得不到可用的连接,则返回 null
return null;
}
}
return conn;
}
private Connection findFreeConnection() throws SQLException {
Connection conn = null;
PooledConnection pConn = null;
// 获得连接池向量中所有的对象
Enumeration enumerate = connections.elements();
// 遍历所有的对象,看是否有可用的连接
while (enumerate.hasMoreElements()) {
pConn = (PooledConnection) enumerate.nextElement();
if (!pConn.isBusy()) {
// 假如此对象不忙,则获得它的数据库连接并把它设为忙
conn = pConn.getConnection();
pConn.setBusy(true);
// 测试此连接是否可用
if (!testConnection(conn)) {
// 假如此连接不可再用了,则创建一个新的连接,
// 并替换此不可用的连接对象,假如创建失败,返回 null
try {
conn = newConnection();
} catch (SQLException e) {
System.out.println("Fail to create ConnectionPool!" + e.getMessage());
return null;
}
pConn.setConnection(conn);
}
break; // 己经 <SUF>
}
}
return conn; // 返回找到到的可用连接
}
private boolean testConnection(Connection conn) {
try {
// 判定测试表是否存在
if (testTable.equals("")) {
// 假如测试表为空,试着使用此连接的 setAutoCommit() 方法
// 来判定连接否可用(此方法只在部分数据库可用,假如不可用 ,
// 抛出异常)。注重:使用测试表的方法更可靠
conn.setAutoCommit(true);
} else { // 有测试表的时候使用测试表测试
//check if this connection is valid
Statement stmt = conn.createStatement();
stmt.execute("select count(*) from " + testTable);
}
} catch (SQLException e) {
// 上面抛出异常,此连接己不可用,关闭它,并返回 false;
closeConnection(conn);
return false;
}
// 连接可用,返回 true
return true;
}
public void returnConnection(Connection conn) {
// 确保连接池存在,假如连接没有创建(不存在),直接返回
if (connections == null) {
System.out.println("ConnectionPool is not existed.Can't return!");
return;
}
PooledConnection pConn = null;
Enumeration enumerate = connections.elements();
// 遍历连接池中的所有连接,找到这个要返回的连接对象
while (enumerate.hasMoreElements()) {
pConn = (PooledConnection) enumerate.nextElement();
// 先找到连接池中的要返回的连接对象
if (conn == pConn.getConnection()) {
// 找到了 , 设置此连接为空闲状态
pConn.setBusy(false);
break;
}
}
}
public synchronized void refreshConnections() throws SQLException {
// 确保连接池己创新存在
if (connections == null) {
System.out.println("ConnectionPool is not existed.Can't refresh!");
return;
}
PooledConnection pConn = null;
Enumeration enumerate = connections.elements();
while (enumerate.hasMoreElements()) {
// 获得一个连接对象
pConn = (PooledConnection) enumerate.nextElement();
// 假如对象忙则等 5 秒 ,5 秒后直接刷新
if (pConn.isBusy()) {
wait(5000); // 等 5 秒
}
// 关闭此连接,用一个新的连接代替它。
closeConnection(pConn.getConnection());
pConn.setConnection(newConnection());
pConn.setBusy(false);
}
}
public synchronized void closeConnectionPool() throws SQLException {
// 确保连接池存在,假如不存在,返回
if (connections == null) {
System.out.println("ConnectionPool is not existed.Can't close!");
return;
}
PooledConnection pConn = null;
Enumeration enumerate = connections.elements();
while (enumerate.hasMoreElements()) {
pConn = (PooledConnection) enumerate.nextElement();
// 假如忙,等 5 秒
if (pConn.isBusy()) {
wait(5000); // 等 5 秒
}
//5 秒后直接关闭它
closeConnection(pConn.getConnection());
// 从连接池向量中删除它
connections.removeElement(pConn);
}
// 置连接池为空
connections = null;
}
private void closeConnection(Connection conn) {
try {
conn.close();
} catch (SQLException e) {
System.out.println("An error occur to close connection." + e.getMessage());
}
}
private void wait(int mSeconds) {
try {
Thread.sleep(mSeconds);
} catch (InterruptedException e) {
}
}
class PooledConnection {
Connection connection = null; // 数据库连接
boolean busy = false; // 此连接是否正在使用的标志,默认没有正在使用
// 构造函数,根据一个 Connection 构告一个 PooledConnection 对象
public PooledConnection(Connection connection) {
this.connection = connection;
}
// 返回此对象中的连接
public Connection getConnection() {
return connection;
}
// 设置此对象的,连接
public void setConnection(Connection connection) {
this.connection = connection;
}
// 获得对象连接是否忙
public boolean isBusy() {
return busy;
}
// 设置对象的连接正在忙
public void setBusy(boolean busy) {
this.busy = busy;
}
}
}
| false | 2,612 | 11 | 2,683 | 11 | 2,837 | 11 | 2,683 | 11 | 3,783 | 22 | false | false | false | false | false | true |
22901_3 | package com.jsong.robostcode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
/**
* 如何处写出健壮的代码
*/
@Slf4j
public class RobostTest {
/**
* 入口
*
* @param args
*/
public static void main(String[] args) {
// 只有在异常情况下使用异常,这包含两方面内容
// 1. 如何处理识别异常情况并处理它
// 2. 是只在异常情况下使用异常流程,不要用异常来做业务逻辑控制
try {
boolean isCurrect = doSth();
} catch (Exception e) {
// 每一个 catch 块至少打印一条日志,说明异常情况或者说明为什么不处理。
log.error("doSth发生异常", e);
// 不要做控制业务流程处理 !
}
}
/**
* 业务逻辑
*
* @return
*/
public static boolean doSth() {
return true;
}
/**
* 抛出异常
*/
public static boolean doSthExcetion() throws Exception {
throw new Exception("error occur");
}
public void doSomething(String a, String b, String c) throws Exception {
if (a != null) {
doSth();
if (b != null) {
doSth();
if (c != null) {
doSth();
doSthExcetion();
}
}
}
}
/**
* 防御式编程,当输入不满足条件时,要尽早返回或主动报错。程
* 序/方法不应该因传入错误数据而被破坏,哪怕是其他由自己编写方法和程序产生的错误数据。
* 这种思想是 将可能出现的错误造成的影响控制在有限的范围内。
*
* @param a
* @param b
* @param c
* @throws Exception
*/
public void doSomethingClear(String a, String b, String c) throws Exception {
if (a == null) {
return ; //log some errorA
}
if (b == null) {
return ; //log some errorB
}
if (c == null) {
return ; //log some errorB
}
doSth();
doSthExcetion();
}
/**
* 使用断言的重要原则就是,断言不能有副作用,也绝不能把必须执行的代码放入断言
*
* @param dParam
* @return
*/
public boolean assertDemo(String dParam) {
Assert.isTrue(dParam.length() >1, ("参数验证失败-" + String.class.getSimpleName() +"验证失败:" + dParam));
doSth();
return true;
}
/**
* 其他的原则
*
* DRY (Don't Repeat Yourself)
* 系统中的每一部分,都必须有一个单一的、明确的、权威的代表。
*
* 我们要避免的是在改动时的一个逻辑的时候需要去修改十处,如果漏掉了任何一处就会造成 bug 甚至线上故障。
* 变更在软件开发中又是一个常态,而在一个到处是重复的系统中维护变更是非常艰难的。
*/
/**
* 没有文档比错误的文档更好
* - 读注释比读代码更容易,可怕的事情往往就这样发生;
* - 把注释放在更上层的复杂的复杂逻辑中。
* - 满篇的注释并不是好代码,也不是好习惯
*/
/**
* 选择优秀的库
*
* 官方包 > 开源组织(apache,eclipse, fsf, Linux,openstack)> 大公司 > 个人开发者
* 一、框架的功能性
* 二、团队协作能力
* 综合这两方面考虑,对要选择的框架做出评估,确定自己的目标框架
*/
/**
* 资源使用
*
* 管理资源:内存、事物、线程、文件、定时器,所有数量有限的事物都称为资源。遵循的模式:你分配、你使用、你回收。
*
*/
}
| changsong/jsong | src/main/java/com/jsong/robostcode/RobostTest.java | 1,006 | // 1. 如何处理识别异常情况并处理它 | line_comment | zh-cn | package com.jsong.robostcode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
/**
* 如何处写出健壮的代码
*/
@Slf4j
public class RobostTest {
/**
* 入口
*
* @param args
*/
public static void main(String[] args) {
// 只有在异常情况下使用异常,这包含两方面内容
// 1. <SUF>
// 2. 是只在异常情况下使用异常流程,不要用异常来做业务逻辑控制
try {
boolean isCurrect = doSth();
} catch (Exception e) {
// 每一个 catch 块至少打印一条日志,说明异常情况或者说明为什么不处理。
log.error("doSth发生异常", e);
// 不要做控制业务流程处理 !
}
}
/**
* 业务逻辑
*
* @return
*/
public static boolean doSth() {
return true;
}
/**
* 抛出异常
*/
public static boolean doSthExcetion() throws Exception {
throw new Exception("error occur");
}
public void doSomething(String a, String b, String c) throws Exception {
if (a != null) {
doSth();
if (b != null) {
doSth();
if (c != null) {
doSth();
doSthExcetion();
}
}
}
}
/**
* 防御式编程,当输入不满足条件时,要尽早返回或主动报错。程
* 序/方法不应该因传入错误数据而被破坏,哪怕是其他由自己编写方法和程序产生的错误数据。
* 这种思想是 将可能出现的错误造成的影响控制在有限的范围内。
*
* @param a
* @param b
* @param c
* @throws Exception
*/
public void doSomethingClear(String a, String b, String c) throws Exception {
if (a == null) {
return ; //log some errorA
}
if (b == null) {
return ; //log some errorB
}
if (c == null) {
return ; //log some errorB
}
doSth();
doSthExcetion();
}
/**
* 使用断言的重要原则就是,断言不能有副作用,也绝不能把必须执行的代码放入断言
*
* @param dParam
* @return
*/
public boolean assertDemo(String dParam) {
Assert.isTrue(dParam.length() >1, ("参数验证失败-" + String.class.getSimpleName() +"验证失败:" + dParam));
doSth();
return true;
}
/**
* 其他的原则
*
* DRY (Don't Repeat Yourself)
* 系统中的每一部分,都必须有一个单一的、明确的、权威的代表。
*
* 我们要避免的是在改动时的一个逻辑的时候需要去修改十处,如果漏掉了任何一处就会造成 bug 甚至线上故障。
* 变更在软件开发中又是一个常态,而在一个到处是重复的系统中维护变更是非常艰难的。
*/
/**
* 没有文档比错误的文档更好
* - 读注释比读代码更容易,可怕的事情往往就这样发生;
* - 把注释放在更上层的复杂的复杂逻辑中。
* - 满篇的注释并不是好代码,也不是好习惯
*/
/**
* 选择优秀的库
*
* 官方包 > 开源组织(apache,eclipse, fsf, Linux,openstack)> 大公司 > 个人开发者
* 一、框架的功能性
* 二、团队协作能力
* 综合这两方面考虑,对要选择的框架做出评估,确定自己的目标框架
*/
/**
* 资源使用
*
* 管理资源:内存、事物、线程、文件、定时器,所有数量有限的事物都称为资源。遵循的模式:你分配、你使用、你回收。
*
*/
}
| false | 952 | 13 | 1,006 | 13 | 1,012 | 12 | 1,006 | 13 | 1,547 | 29 | false | false | false | false | false | true |
63470_3 | package me.chanjar.pvp.bag;
import com.fasterxml.jackson.annotation.JsonIgnore;
import me.chanjar.pvp.equipment.model.Attribute;
import me.chanjar.pvp.equipment.model.Equipment;
import org.apache.commons.collections4.CollectionUtils;
import java.util.*;
import static java.util.stream.Collectors.toList;
/**
* 背包
*/
public class Bag {
/**
* 容量
*/
private int capacity;
/**
* 当前装备列表
*/
private final List<Equipment> currentEquipmentList;
/**
* 属性增强
*/
private Attribute enhancement = new Attribute();
/**
* 累计花费金币
*/
private int spentCoins;
/**
* 默认背包容量6
*/
public Bag() {
this(6);
}
public Bag(int capacity) {
this.capacity = capacity;
currentEquipmentList = new ArrayList<>(capacity);
}
/**
* 添加装备,不管容量、是否缺少下级装备
*
* @param equipment
*/
public void add(Equipment equipment) {
enhanceBy(equipment.getAttribute());
spentCoins += equipment.getPrice();
currentEquipmentList.add(equipment);
}
/**
* 买入装备
*
* @param equipment
* @return 容量满了、缺少下级装备、成功
*/
public BagAddResult buy(Equipment equipment) {
if (CollectionUtils.isEmpty(equipment.getDependsOn())) {
// 背包容量不足
if (currentEquipmentList.size() >= capacity) {
return BagAddResult.CAPACITY_OVERFLOW;
}
currentEquipmentList.add(equipment);
enhanceBy(equipment.getAttribute());
spentCoins += equipment.getPrice();
return BagAddResult.SUCCESS;
}
// 合成装备
List<String> dependsEquipmentIds = equipment.getDependsOn();
Set<Integer> dependsEquipmentIndices = new HashSet<>(dependsEquipmentIds.size());
for (int i = 0; i < dependsEquipmentIds.size(); i++) {
String dependsEquipmentId = dependsEquipmentIds.get(i);
int dependsEquipmentIndex = getEquipmentIndexOf(dependsEquipmentId, dependsEquipmentIndices);
if (dependsEquipmentIndex == -1) {
// 依赖的下级装备还没有
return BagAddResult.LACK_DEPEND_EQUIPMENT;
}
dependsEquipmentIndices.add(dependsEquipmentIndex);
}
// 如果当前背包物品数量 - 要被消耗掉的物品数量 依然>=背包容量,那就不能添加这个物品
if (currentEquipmentList.size() - dependsEquipmentIds.size() >= capacity) {
return BagAddResult.CAPACITY_OVERFLOW;
}
// 消耗装备
// 必须从最后往前删,如果这样0,1,把0删掉后,原来的1就会往前移,如果此时删掉1,实际上就是删掉原来的2
ArrayList<Integer> sortIds = new ArrayList<>(dependsEquipmentIndices);
Collections.sort(sortIds);
Collections.reverse(sortIds);
sortIds.forEach(i -> {
Equipment remove = currentEquipmentList.remove(i.intValue());
removeEnhance(remove.getAttribute());
});
// 添加装备
enhanceBy(equipment.getAttribute());
currentEquipmentList.add(equipment);
spentCoins += equipment.getPrice();
return BagAddResult.SUCCESS;
}
/**
* 卖出装备
*
* @param equipmentId
*/
public void sell(String equipmentId) {
int equipmentIndexOf = getEquipmentIndexOf(equipmentId, Collections.emptySet());
if (equipmentIndexOf == -1) {
return;
}
Equipment equipment = currentEquipmentList.remove(equipmentIndexOf);
spentCoins -= equipment.getSellPrice();
removeEnhance(equipment.getAttribute());
}
/**
* @param equipmentId
* @param excludeIndices 排除掉的下标结果
* @return
*/
private int getEquipmentIndexOf(String equipmentId, Set<Integer> excludeIndices) {
for (int i = 0; i < currentEquipmentList.size(); i++) {
Equipment equipment = currentEquipmentList.get(i);
if (equipment.getId().equals(equipmentId) && !excludeIndices.contains(Integer.valueOf(i))) {
return i;
}
}
return -1;
}
/**
* 获得装备列表
*
* @return
*/
@JsonIgnore
public List<Equipment> getCurrentEquipmentList() {
return currentEquipmentList;
}
public List<String> getCurrentEquipmentIds() {
return currentEquipmentList.stream().map(e -> e.getId()).collect(toList());
}
/**
* 被装备增强
*
* @param another
*/
private void enhanceBy(Attribute another) {
this.enhancement = enhancement.plus(another);
}
/**
* 消耗装备,原先的增强要被抵消
*
* @param another
*/
private void removeEnhance(Attribute another) {
this.enhancement = enhancement.minus(another);
}
/**
* 获得容量
*
* @return
*/
public int getCapacity() {
return capacity;
}
/**
* 获得累计花费金币
*
* @return
*/
public int getSpentCoins() {
return spentCoins;
}
public Attribute getEnhancement() {
return enhancement;
}
/**
* 清空背包,恢复原始状态
*/
public void reset() {
currentEquipmentList.clear();
enhancement = new Attribute();
spentCoins = 0;
}
}
| chanjarster/tencent-pvp-equipment-simulator | src/main/java/me/chanjar/pvp/bag/Bag.java | 1,320 | /**
* 属性增强
*/ | block_comment | zh-cn | package me.chanjar.pvp.bag;
import com.fasterxml.jackson.annotation.JsonIgnore;
import me.chanjar.pvp.equipment.model.Attribute;
import me.chanjar.pvp.equipment.model.Equipment;
import org.apache.commons.collections4.CollectionUtils;
import java.util.*;
import static java.util.stream.Collectors.toList;
/**
* 背包
*/
public class Bag {
/**
* 容量
*/
private int capacity;
/**
* 当前装备列表
*/
private final List<Equipment> currentEquipmentList;
/**
* 属性增 <SUF>*/
private Attribute enhancement = new Attribute();
/**
* 累计花费金币
*/
private int spentCoins;
/**
* 默认背包容量6
*/
public Bag() {
this(6);
}
public Bag(int capacity) {
this.capacity = capacity;
currentEquipmentList = new ArrayList<>(capacity);
}
/**
* 添加装备,不管容量、是否缺少下级装备
*
* @param equipment
*/
public void add(Equipment equipment) {
enhanceBy(equipment.getAttribute());
spentCoins += equipment.getPrice();
currentEquipmentList.add(equipment);
}
/**
* 买入装备
*
* @param equipment
* @return 容量满了、缺少下级装备、成功
*/
public BagAddResult buy(Equipment equipment) {
if (CollectionUtils.isEmpty(equipment.getDependsOn())) {
// 背包容量不足
if (currentEquipmentList.size() >= capacity) {
return BagAddResult.CAPACITY_OVERFLOW;
}
currentEquipmentList.add(equipment);
enhanceBy(equipment.getAttribute());
spentCoins += equipment.getPrice();
return BagAddResult.SUCCESS;
}
// 合成装备
List<String> dependsEquipmentIds = equipment.getDependsOn();
Set<Integer> dependsEquipmentIndices = new HashSet<>(dependsEquipmentIds.size());
for (int i = 0; i < dependsEquipmentIds.size(); i++) {
String dependsEquipmentId = dependsEquipmentIds.get(i);
int dependsEquipmentIndex = getEquipmentIndexOf(dependsEquipmentId, dependsEquipmentIndices);
if (dependsEquipmentIndex == -1) {
// 依赖的下级装备还没有
return BagAddResult.LACK_DEPEND_EQUIPMENT;
}
dependsEquipmentIndices.add(dependsEquipmentIndex);
}
// 如果当前背包物品数量 - 要被消耗掉的物品数量 依然>=背包容量,那就不能添加这个物品
if (currentEquipmentList.size() - dependsEquipmentIds.size() >= capacity) {
return BagAddResult.CAPACITY_OVERFLOW;
}
// 消耗装备
// 必须从最后往前删,如果这样0,1,把0删掉后,原来的1就会往前移,如果此时删掉1,实际上就是删掉原来的2
ArrayList<Integer> sortIds = new ArrayList<>(dependsEquipmentIndices);
Collections.sort(sortIds);
Collections.reverse(sortIds);
sortIds.forEach(i -> {
Equipment remove = currentEquipmentList.remove(i.intValue());
removeEnhance(remove.getAttribute());
});
// 添加装备
enhanceBy(equipment.getAttribute());
currentEquipmentList.add(equipment);
spentCoins += equipment.getPrice();
return BagAddResult.SUCCESS;
}
/**
* 卖出装备
*
* @param equipmentId
*/
public void sell(String equipmentId) {
int equipmentIndexOf = getEquipmentIndexOf(equipmentId, Collections.emptySet());
if (equipmentIndexOf == -1) {
return;
}
Equipment equipment = currentEquipmentList.remove(equipmentIndexOf);
spentCoins -= equipment.getSellPrice();
removeEnhance(equipment.getAttribute());
}
/**
* @param equipmentId
* @param excludeIndices 排除掉的下标结果
* @return
*/
private int getEquipmentIndexOf(String equipmentId, Set<Integer> excludeIndices) {
for (int i = 0; i < currentEquipmentList.size(); i++) {
Equipment equipment = currentEquipmentList.get(i);
if (equipment.getId().equals(equipmentId) && !excludeIndices.contains(Integer.valueOf(i))) {
return i;
}
}
return -1;
}
/**
* 获得装备列表
*
* @return
*/
@JsonIgnore
public List<Equipment> getCurrentEquipmentList() {
return currentEquipmentList;
}
public List<String> getCurrentEquipmentIds() {
return currentEquipmentList.stream().map(e -> e.getId()).collect(toList());
}
/**
* 被装备增强
*
* @param another
*/
private void enhanceBy(Attribute another) {
this.enhancement = enhancement.plus(another);
}
/**
* 消耗装备,原先的增强要被抵消
*
* @param another
*/
private void removeEnhance(Attribute another) {
this.enhancement = enhancement.minus(another);
}
/**
* 获得容量
*
* @return
*/
public int getCapacity() {
return capacity;
}
/**
* 获得累计花费金币
*
* @return
*/
public int getSpentCoins() {
return spentCoins;
}
public Attribute getEnhancement() {
return enhancement;
}
/**
* 清空背包,恢复原始状态
*/
public void reset() {
currentEquipmentList.clear();
enhancement = new Attribute();
spentCoins = 0;
}
}
| false | 1,200 | 9 | 1,320 | 8 | 1,388 | 9 | 1,320 | 8 | 1,869 | 16 | false | false | false | false | false | true |
35748_6 | package juejin.lc.leetCode;
public class CanWinNim {
/**
* 你和你的朋友,两个人一起玩 Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。
* 拿掉最后一块石头的人就是获胜者。你作为先手。
* <p>
* 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
* <p>
* 示例:
* <p>
* 输入: 4
* 输出: false
* 解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
* 因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
*
* @param n 石头数量
* @return 是否赢得比赛
*/
private boolean solution(int n) {
//让我们考虑一些小例子。显而易见的是,如果石头堆中只有一块、两块、或是三块石头,
// 那么在你的回合,你就可以把全部石子拿走,从而在游戏中取胜。而如果就像题目描述那样,
// 堆中恰好有四块石头,你就会失败。因为在这种情况下不管你取走多少石头,总会为你的对手留下几块,
// 使得他可以在游戏中打败你。因此,要想获胜,在你的回合中,必须避免石头堆中的石子数为 4 的情况。
//同样地,如果有五块、六块、或是七块石头,你可以控制自己拿取的石头数,总是恰好给你的对手留下四块石头,
// 使他输掉这场比赛。但是如果石头堆里有八块石头,你就不可避免地会输掉,
// 因为不管你从一堆石头中挑出一块、两块还是三块,你的对手都可以选择三块、两块或一块,
// 以确保在再一次轮到你的时候,你会面对四块石头。
//显然,它以相同的模式不断重复 n=4,8,12,16,,,,基本可以看出是 4 的倍数。
return (n % 4 != 0);
}
public static void main(String[] args) {
CanWinNim canWinNim = new CanWinNim();
int n = 100;
boolean result = canWinNim.solution(n);
System.out.println("result = " + result);
}
}
| chaoaiqi/study | java/src/juejin/lc/leetCode/CanWinNim.java | 674 | // 使他输掉这场比赛。但是如果石头堆里有八块石头,你就不可避免地会输掉, | line_comment | zh-cn | package juejin.lc.leetCode;
public class CanWinNim {
/**
* 你和你的朋友,两个人一起玩 Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。
* 拿掉最后一块石头的人就是获胜者。你作为先手。
* <p>
* 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
* <p>
* 示例:
* <p>
* 输入: 4
* 输出: false
* 解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
* 因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
*
* @param n 石头数量
* @return 是否赢得比赛
*/
private boolean solution(int n) {
//让我们考虑一些小例子。显而易见的是,如果石头堆中只有一块、两块、或是三块石头,
// 那么在你的回合,你就可以把全部石子拿走,从而在游戏中取胜。而如果就像题目描述那样,
// 堆中恰好有四块石头,你就会失败。因为在这种情况下不管你取走多少石头,总会为你的对手留下几块,
// 使得他可以在游戏中打败你。因此,要想获胜,在你的回合中,必须避免石头堆中的石子数为 4 的情况。
//同样地,如果有五块、六块、或是七块石头,你可以控制自己拿取的石头数,总是恰好给你的对手留下四块石头,
// 使他 <SUF>
// 因为不管你从一堆石头中挑出一块、两块还是三块,你的对手都可以选择三块、两块或一块,
// 以确保在再一次轮到你的时候,你会面对四块石头。
//显然,它以相同的模式不断重复 n=4,8,12,16,,,,基本可以看出是 4 的倍数。
return (n % 4 != 0);
}
public static void main(String[] args) {
CanWinNim canWinNim = new CanWinNim();
int n = 100;
boolean result = canWinNim.solution(n);
System.out.println("result = " + result);
}
}
| false | 572 | 24 | 674 | 32 | 595 | 25 | 674 | 32 | 1,007 | 52 | false | false | false | false | false | true |
33947_7 | package arrayPackage190124;
import org.omg.CORBA.PUBLIC_MEMBER;
public class Array190122N190123 {
String name;
int asset;
double reputation;
public static void main(String[] args) {
// 基本資料型別陣列,最普通的int一維陣列
int[] simplearray = new int[10]; // 建立新的array叫simplearray並有十個元素
// 物件參考變數陣列
Array190122N190123[] simplearray2 = new Array190122N190123[20];
// 使用大括號產生陣列並指定初值
int[] simplearray3 = { 1, 2, 3, 4, 5, 6, 7 };
String[] simplearray4 = { "Ricardo", "Tom", "Kevin", "Alexis" };
// length以取得陣列長度
// System.out.println(simplearray3.length);
// System.out.println(simplearray4.length);
// 更改元素的值
simplearray4[3] = "RicardoII";
// System.out.println(simplearray4[3]);
// 基本資料型別陣列
int number[] = new int[10];
number[0] = 100;
number[1] = 101;
number[2] = 102;
// System.out.println(number[2]);
// System.out.println(number[9]); //未給定值因此是null,也就是0
// 物件參考變數陣列:第一種方法
Array190122N190123[] complicatedarray = new Array190122N190123[10];
complicatedarray[0] = new Array190122N190123();
complicatedarray[0].name = "Ricardo";
complicatedarray[0].asset = 100000000;
// System.out.println(complicatedarray[0].name);
// 物件參考變數陣列:第二種方法
Array190122N190123 pointer = new Array190122N190123();
complicatedarray[1] = pointer;
pointer.name = "Richard";
pointer.asset = 100000000;
// System.out.println(pointer.asset);
// 最簡單的int二維陣列
int[][] tdarray = new int[5][4];
int[][] td2array = { { 1, 2, 3 }, { 4, 5, 6 } };
// System.out.println(td2array.length);
// System.out.println(td2array[1].length);
// System.out.println(td2array[1][0]);
// 再練習一次九九乘法表
for (int i = 0; i < 10;) {
for (int j = 0; j < 10; j++) {
// System.out.print(i + "X" + j + "=" + i*j + " ");
}
i++;
// System.out.println();
}
// 列印二維陣列
int[][] td3array = { { 1, 2, 3 }, { 4, 5, 6 } };
for (int i = 0; i < 2;) {
for (int j = 0; j < 3; j++) {
// System.out.print(td3array[i][j]);
}
// System.out.println();
i++;
}
// 列印二維陣列:注意第二列少一個元素
int[][] td4array = { { 7, 8, 9 }, { 10, 11 } };
for (int i = 0; i < td4array.length;) {
for (int j = 0; j < td4array[i].length; j++) {
// System.out.print(td4array[i][j]);
}
// System.out.println();
i++;
}
// lab: 產生一個簡單的int陣列
int[][] td5array = { { 1, 2, 3 }, { 4, 5, 6 } };
// lab: 利用迴圈計算總和
int sum = 0;
int[][] td6array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int i = 0; i < td6array.length;) {
for (int j = 0; j < td6array[i].length; j++) {
sum = sum + td6array[i][j];
}
i++;
}
// System.out.println(sum);
// 列印出陣列中的最大值及最小值
double[] td7array = { 1.1, 2.0, 1.2, 1.4, 0.5, 6.0 };
double max = 0;
double min = 99;
double average = 0;
for (int i = 0; i < td7array.length; i++) {
if (td7array[i] < min) {
min = td7array[i];
}
if (td7array[i] > max) {
max = td7array[i];
}
average = average + td7array[i];
}
average = average / td7array.length;
// System.out.println("最大值是" + max);
// System.out.println("最小值是" + min);
// System.out.println("平均值是" + average);
// lab: 做出四層聖誕樹
String[][] td8array = { { " * " }, { " *** " }, { " ***** " }, { " ******* " }, { "*********" },
{ " ||| " } };
for (int i = 0; i < td8array.length; i++) {
for (int j = 0; j < td8array[i].length; j++) {
// System.out.print(td8array[i][j]);
}
// System.out.println();
}
// 以下開始是1/24的練習
// 以下為來自(http://dic.vbird.tw/java/unit07.php)的練習題目
// 假設你要讓使用者輸入 X 與 Y 軸,然後透過以雙層迴圈的行為, 輸出一個矩形的星號圖示,該如何處理?
int x = 10;
int y = 10;
for (int i = 1; i < (x + 1); i++) {
for (int j = 1; j < (y + 1); j++) {
// System.out.print("*");
}
// System.out.println(i);
}
// 寫一個可以繪製出直角三角形,讓使用者輸入一個數值來處理喔!
int a = 10; // 直角三角形的層數
for (int i = 1; i < (a + 1); i++) { // 若未到達規定的層數,則迴圈必須繼續運行
for (int j = 1; j < (i + 1); j++) {
// 輸出*(該層"*"的數量,與當時的層數數目值相等。)
// System.out.print( "*" );
}
// System.out.println(i); //檢查用,檢查直角三角形的層數是否和指定的相符。
}
//終於要來挑戰聖誕樹了!!!!
int c = 10; //先指定聖誕樹的層數
for (int i = 1; i < (c + 1); i++) { //在聖誕樹還未達指定的層數時,不能停止運行。
for (int j = 1; j < (c - i + 1); j++) { //每一層聖誕樹的空白及*的總和,恰為層數-1,因此要不小於層數。
//先來印個空白吧
//System.out.print(" ");
}
//接下來來研究如何印出聖誕樹的"*"
for (int j = 1; j < (2 * i); j++) {
//System.out.print("*");
}
//System.out.println(i); //當然還是要來換個行,順便做個編號
} //好啦那我成功了!!!!!!!!
}
}
| chaoannricardo/StudyNotes | III_DataEngineer_BDSE10/1902_Java/JavaWorkspace/Practice/src/arrayPackage190124/Array190122N190123.java | 2,374 | // 更改元素的值
| line_comment | zh-cn | package arrayPackage190124;
import org.omg.CORBA.PUBLIC_MEMBER;
public class Array190122N190123 {
String name;
int asset;
double reputation;
public static void main(String[] args) {
// 基本資料型別陣列,最普通的int一維陣列
int[] simplearray = new int[10]; // 建立新的array叫simplearray並有十個元素
// 物件參考變數陣列
Array190122N190123[] simplearray2 = new Array190122N190123[20];
// 使用大括號產生陣列並指定初值
int[] simplearray3 = { 1, 2, 3, 4, 5, 6, 7 };
String[] simplearray4 = { "Ricardo", "Tom", "Kevin", "Alexis" };
// length以取得陣列長度
// System.out.println(simplearray3.length);
// System.out.println(simplearray4.length);
// 更改 <SUF>
simplearray4[3] = "RicardoII";
// System.out.println(simplearray4[3]);
// 基本資料型別陣列
int number[] = new int[10];
number[0] = 100;
number[1] = 101;
number[2] = 102;
// System.out.println(number[2]);
// System.out.println(number[9]); //未給定值因此是null,也就是0
// 物件參考變數陣列:第一種方法
Array190122N190123[] complicatedarray = new Array190122N190123[10];
complicatedarray[0] = new Array190122N190123();
complicatedarray[0].name = "Ricardo";
complicatedarray[0].asset = 100000000;
// System.out.println(complicatedarray[0].name);
// 物件參考變數陣列:第二種方法
Array190122N190123 pointer = new Array190122N190123();
complicatedarray[1] = pointer;
pointer.name = "Richard";
pointer.asset = 100000000;
// System.out.println(pointer.asset);
// 最簡單的int二維陣列
int[][] tdarray = new int[5][4];
int[][] td2array = { { 1, 2, 3 }, { 4, 5, 6 } };
// System.out.println(td2array.length);
// System.out.println(td2array[1].length);
// System.out.println(td2array[1][0]);
// 再練習一次九九乘法表
for (int i = 0; i < 10;) {
for (int j = 0; j < 10; j++) {
// System.out.print(i + "X" + j + "=" + i*j + " ");
}
i++;
// System.out.println();
}
// 列印二維陣列
int[][] td3array = { { 1, 2, 3 }, { 4, 5, 6 } };
for (int i = 0; i < 2;) {
for (int j = 0; j < 3; j++) {
// System.out.print(td3array[i][j]);
}
// System.out.println();
i++;
}
// 列印二維陣列:注意第二列少一個元素
int[][] td4array = { { 7, 8, 9 }, { 10, 11 } };
for (int i = 0; i < td4array.length;) {
for (int j = 0; j < td4array[i].length; j++) {
// System.out.print(td4array[i][j]);
}
// System.out.println();
i++;
}
// lab: 產生一個簡單的int陣列
int[][] td5array = { { 1, 2, 3 }, { 4, 5, 6 } };
// lab: 利用迴圈計算總和
int sum = 0;
int[][] td6array = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
for (int i = 0; i < td6array.length;) {
for (int j = 0; j < td6array[i].length; j++) {
sum = sum + td6array[i][j];
}
i++;
}
// System.out.println(sum);
// 列印出陣列中的最大值及最小值
double[] td7array = { 1.1, 2.0, 1.2, 1.4, 0.5, 6.0 };
double max = 0;
double min = 99;
double average = 0;
for (int i = 0; i < td7array.length; i++) {
if (td7array[i] < min) {
min = td7array[i];
}
if (td7array[i] > max) {
max = td7array[i];
}
average = average + td7array[i];
}
average = average / td7array.length;
// System.out.println("最大值是" + max);
// System.out.println("最小值是" + min);
// System.out.println("平均值是" + average);
// lab: 做出四層聖誕樹
String[][] td8array = { { " * " }, { " *** " }, { " ***** " }, { " ******* " }, { "*********" },
{ " ||| " } };
for (int i = 0; i < td8array.length; i++) {
for (int j = 0; j < td8array[i].length; j++) {
// System.out.print(td8array[i][j]);
}
// System.out.println();
}
// 以下開始是1/24的練習
// 以下為來自(http://dic.vbird.tw/java/unit07.php)的練習題目
// 假設你要讓使用者輸入 X 與 Y 軸,然後透過以雙層迴圈的行為, 輸出一個矩形的星號圖示,該如何處理?
int x = 10;
int y = 10;
for (int i = 1; i < (x + 1); i++) {
for (int j = 1; j < (y + 1); j++) {
// System.out.print("*");
}
// System.out.println(i);
}
// 寫一個可以繪製出直角三角形,讓使用者輸入一個數值來處理喔!
int a = 10; // 直角三角形的層數
for (int i = 1; i < (a + 1); i++) { // 若未到達規定的層數,則迴圈必須繼續運行
for (int j = 1; j < (i + 1); j++) {
// 輸出*(該層"*"的數量,與當時的層數數目值相等。)
// System.out.print( "*" );
}
// System.out.println(i); //檢查用,檢查直角三角形的層數是否和指定的相符。
}
//終於要來挑戰聖誕樹了!!!!
int c = 10; //先指定聖誕樹的層數
for (int i = 1; i < (c + 1); i++) { //在聖誕樹還未達指定的層數時,不能停止運行。
for (int j = 1; j < (c - i + 1); j++) { //每一層聖誕樹的空白及*的總和,恰為層數-1,因此要不小於層數。
//先來印個空白吧
//System.out.print(" ");
}
//接下來來研究如何印出聖誕樹的"*"
for (int j = 1; j < (2 * i); j++) {
//System.out.print("*");
}
//System.out.println(i); //當然還是要來換個行,順便做個編號
} //好啦那我成功了!!!!!!!!
}
}
| false | 2,082 | 7 | 2,371 | 6 | 2,167 | 6 | 2,371 | 6 | 2,923 | 9 | false | false | false | false | false | true |
25529_3 | package com.timeyang.config;
import com.timeyang.address.Address;
import com.timeyang.address.AddressRepository;
import com.timeyang.catalog.Catalog;
import com.timeyang.catalog.CatalogRepository;
import com.timeyang.inventory.Inventory;
import com.timeyang.inventory.InventoryRepository;
import com.timeyang.inventory.InventoryStatus;
import com.timeyang.product.Product;
import com.timeyang.product.ProductRepository;
import com.timeyang.shipment.Shipment;
import com.timeyang.shipment.ShipmentRepository;
import com.timeyang.shipment.ShipmentStatus;
import com.timeyang.warehouse.Warehouse;
import com.timeyang.warehouse.WarehouseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* 初始化数据库
*
* @author yangck
*/
@Service
@Profile("dev")
public class DatabaseInitializer {
@Autowired
private ProductRepository productRepository;
@Autowired
private ShipmentRepository shipmentRepository;
@Autowired
private WarehouseRepository warehouseRepository;
@Autowired
private AddressRepository addressRepository;
@Autowired
private CatalogRepository catalogRepository;
@Autowired
private InventoryRepository inventoryRepository;
@Autowired
private Neo4jConfiguration neo4jConfiguration;
public void populate() throws Exception {
// 删除所有边和节点
neo4jConfiguration.getSession().query("MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n, r;", new HashMap<>()).queryResults();
List<Product> products = Arrays.asList(
new Product("巴黎", "PD-00001", "<p>法国是欧洲浪漫的中心,它悠久历史、具有丰富文化内涵的名胜古迹及乡野风光吸引着世界各地的旅游者。风情万种的花都巴黎,美丽迷人的蓝色海岸,阿尔卑斯山的滑雪场等都是令人神往的旅游胜地 </p>", 9999.0),
new Product("马尔代夫", "PD-00002", "<p>马尔代夫位于斯里兰卡南方的海域里,被称为印度洋上人间最后的乐园。<strong>马尔代夫由露出水面及部分露出水面的大大小小千余个珊瑚岛组成。</strong><br>" +
"<em>马尔代夫 蜜月与爱人情陷天堂岛</em></p>", 29999.0),
new Product("印度尼西亚,巴厘岛", "PD-00003", "<p> 它是南太平洋最美丽的景点之一。居住在这里的热情人们让巴厘岛是如此的特别。从肉饼饭到火山,再到古朴的巴厘岛村落,巴厘岛一定是你终身难忘的旅程。</p>", 29999.0),
new Product("法国,普罗旺斯", "PD-00004", "<p>它已不再是一个单纯的地域名称,更代表了一种简单无忧、轻松慵懒的生活方式,一种宠辱不惊,看庭前花开花落;去留无意,望天上云卷云舒的闲适意境。<strong>如果旅行是为了摆脱生活的桎梏,普罗旺斯会让你忘掉一切。</strong></p>", 9999.0),
new Product("捷克共和国,布拉格", "PD-00005", "<p><em>布拉格是保存最完整的中世纪城市之一。</em>它一定是任何旅游名单上的必去之地。不要错过夜晚的城堡美景。城堡在灯光的映衬之下显得尤为壮观。</p>", 9999.0),
new Product("维多利亚瀑布", "PD-00006", "维多利亚瀑布,又称莫西奥图尼亚瀑布,位于非洲赞比西河中游,赞比亚与津巴布韦接壤处。宽1,700多米(5,500多英尺),最高处108米(355英尺),为世界著名瀑布奇观之一。<br/>维多利亚瀑布由‘魔鬼瀑布’、‘马蹄瀑布’、‘彩虹瀑布’、‘主瀑布’及‘东瀑布’共五道宽达百米的大瀑布组成<p><em>你站在瀑布边缘,看着瀑布一泻而下,发出如雷般的轰鸣,<strong>你无论如何大喊大叫,都听不到自己的声音,你的肾上腺素在体内涌动,你似乎体会到了临近死亡的感觉。</strong></em></p>", 13999.0),
new Product("泰姬陵", "PD-00007", "泰姬陵(印地语:ताज महल,乌尔都语:تاج محل\u200E),是位于印度北方邦阿格拉的一座用白色大理石建造的陵墓,是印度知名度最高的古迹之一。<p>它是<em>莫卧儿王朝第5代皇帝沙贾汗</em>为了<strong>纪念他的第二任妻子已故皇后姬蔓·芭奴而兴建的陵墓</strong>,竣工于1654年。泰姬陵被广泛认为是“印度穆斯林艺术的珍宝和世界遗产中被广泛赞美的杰作之一”</p>", 13999.0),
new Product("大堡礁", "PD-00008", "大堡礁(The Great Barrier Reef),是世界最大最长的珊瑚礁群,位于南半球,它纵贯于澳洲的东北沿海,北从托雷斯海峡,南到南回归线以南,绵延伸展共有2011公里,最宽处161公里。有2900个大小珊瑚礁岛,自然景观非常特殊。这里自然条件适宜,无大风大浪,成了多种鱼类的栖息地,而在那里不同的月份还能看到不同的水生珍稀动物,让游客大饱眼福。" +
"<p><em>在落潮时,部分的珊瑚礁露出水面形成珊瑚岛。在礁群与海岸之间是一条极方便的交通海路。<strong>风平浪静时,游船在此间通过,船下连绵不断的多彩、多形的珊瑚景色,就成为吸引世界各地游客来猎奇观赏的最佳海底奇观。</strong></em>大堡礁属热带气候,主要受南半球气流控制。</p>", 13999.0)
);
productRepository.save(products);
Catalog catalog = new Catalog(0L, "测试目录1");
catalog.getProducts().addAll(products);
catalogRepository.save(catalog);
Address warehouseAddress = new Address("中国", "云南", "丽江", "古城区", "street1", "street2", 000000);
Address shipToAddress = new Address("中国", "海南省", "三亚", "天涯区", "street1", "street2", 000001);
addressRepository.save(Arrays.asList(warehouseAddress, shipToAddress));
Warehouse warehouse = new Warehouse("测试仓库1");
warehouse.setAddress(warehouseAddress);
warehouse = warehouseRepository.save(warehouse);
Warehouse finalWarehouse = warehouse;
// 创建一个有着随机库存编号的库存集合。即为每个产品生成一个产品数量为1的库存,有着随机库存编号
Random random = new Random();
Set<Inventory> inventories = products.stream()
.map(product -> new Inventory(IntStream.range(0, 9).mapToObj(i -> Integer.toString(random.nextInt(9))).collect(Collectors.joining("")), product, finalWarehouse, InventoryStatus.IN_STOCK)).collect(Collectors.toSet());
inventoryRepository.save(inventories);
// 为每个产品生成10个额外库存。因为一个库存代表一个数量为1的产品,所以每个产品将有10个库存
for(int i = 0; i < 10; i++) {
inventoryRepository.save(products.stream().map(product -> new Inventory(IntStream.range(0, 9).mapToObj(x -> Integer.toString(random.nextInt(9))).collect(Collectors.joining("")), product, finalWarehouse, InventoryStatus.IN_STOCK)).collect(Collectors.toSet()));
}
Shipment shipment = new Shipment(inventories, shipToAddress, warehouse, ShipmentStatus.SHIPPED);
shipmentRepository.save(shipment);
}
}
| chaokunyang/microservices-event-sourcing | inventory-service/src/main/java/com/timeyang/config/DatabaseInitializer.java | 2,426 | // 为每个产品生成10个额外库存。因为一个库存代表一个数量为1的产品,所以每个产品将有10个库存 | line_comment | zh-cn | package com.timeyang.config;
import com.timeyang.address.Address;
import com.timeyang.address.AddressRepository;
import com.timeyang.catalog.Catalog;
import com.timeyang.catalog.CatalogRepository;
import com.timeyang.inventory.Inventory;
import com.timeyang.inventory.InventoryRepository;
import com.timeyang.inventory.InventoryStatus;
import com.timeyang.product.Product;
import com.timeyang.product.ProductRepository;
import com.timeyang.shipment.Shipment;
import com.timeyang.shipment.ShipmentRepository;
import com.timeyang.shipment.ShipmentStatus;
import com.timeyang.warehouse.Warehouse;
import com.timeyang.warehouse.WarehouseRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.data.neo4j.config.Neo4jConfiguration;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* 初始化数据库
*
* @author yangck
*/
@Service
@Profile("dev")
public class DatabaseInitializer {
@Autowired
private ProductRepository productRepository;
@Autowired
private ShipmentRepository shipmentRepository;
@Autowired
private WarehouseRepository warehouseRepository;
@Autowired
private AddressRepository addressRepository;
@Autowired
private CatalogRepository catalogRepository;
@Autowired
private InventoryRepository inventoryRepository;
@Autowired
private Neo4jConfiguration neo4jConfiguration;
public void populate() throws Exception {
// 删除所有边和节点
neo4jConfiguration.getSession().query("MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n, r;", new HashMap<>()).queryResults();
List<Product> products = Arrays.asList(
new Product("巴黎", "PD-00001", "<p>法国是欧洲浪漫的中心,它悠久历史、具有丰富文化内涵的名胜古迹及乡野风光吸引着世界各地的旅游者。风情万种的花都巴黎,美丽迷人的蓝色海岸,阿尔卑斯山的滑雪场等都是令人神往的旅游胜地 </p>", 9999.0),
new Product("马尔代夫", "PD-00002", "<p>马尔代夫位于斯里兰卡南方的海域里,被称为印度洋上人间最后的乐园。<strong>马尔代夫由露出水面及部分露出水面的大大小小千余个珊瑚岛组成。</strong><br>" +
"<em>马尔代夫 蜜月与爱人情陷天堂岛</em></p>", 29999.0),
new Product("印度尼西亚,巴厘岛", "PD-00003", "<p> 它是南太平洋最美丽的景点之一。居住在这里的热情人们让巴厘岛是如此的特别。从肉饼饭到火山,再到古朴的巴厘岛村落,巴厘岛一定是你终身难忘的旅程。</p>", 29999.0),
new Product("法国,普罗旺斯", "PD-00004", "<p>它已不再是一个单纯的地域名称,更代表了一种简单无忧、轻松慵懒的生活方式,一种宠辱不惊,看庭前花开花落;去留无意,望天上云卷云舒的闲适意境。<strong>如果旅行是为了摆脱生活的桎梏,普罗旺斯会让你忘掉一切。</strong></p>", 9999.0),
new Product("捷克共和国,布拉格", "PD-00005", "<p><em>布拉格是保存最完整的中世纪城市之一。</em>它一定是任何旅游名单上的必去之地。不要错过夜晚的城堡美景。城堡在灯光的映衬之下显得尤为壮观。</p>", 9999.0),
new Product("维多利亚瀑布", "PD-00006", "维多利亚瀑布,又称莫西奥图尼亚瀑布,位于非洲赞比西河中游,赞比亚与津巴布韦接壤处。宽1,700多米(5,500多英尺),最高处108米(355英尺),为世界著名瀑布奇观之一。<br/>维多利亚瀑布由‘魔鬼瀑布’、‘马蹄瀑布’、‘彩虹瀑布’、‘主瀑布’及‘东瀑布’共五道宽达百米的大瀑布组成<p><em>你站在瀑布边缘,看着瀑布一泻而下,发出如雷般的轰鸣,<strong>你无论如何大喊大叫,都听不到自己的声音,你的肾上腺素在体内涌动,你似乎体会到了临近死亡的感觉。</strong></em></p>", 13999.0),
new Product("泰姬陵", "PD-00007", "泰姬陵(印地语:ताज महल,乌尔都语:تاج محل\u200E),是位于印度北方邦阿格拉的一座用白色大理石建造的陵墓,是印度知名度最高的古迹之一。<p>它是<em>莫卧儿王朝第5代皇帝沙贾汗</em>为了<strong>纪念他的第二任妻子已故皇后姬蔓·芭奴而兴建的陵墓</strong>,竣工于1654年。泰姬陵被广泛认为是“印度穆斯林艺术的珍宝和世界遗产中被广泛赞美的杰作之一”</p>", 13999.0),
new Product("大堡礁", "PD-00008", "大堡礁(The Great Barrier Reef),是世界最大最长的珊瑚礁群,位于南半球,它纵贯于澳洲的东北沿海,北从托雷斯海峡,南到南回归线以南,绵延伸展共有2011公里,最宽处161公里。有2900个大小珊瑚礁岛,自然景观非常特殊。这里自然条件适宜,无大风大浪,成了多种鱼类的栖息地,而在那里不同的月份还能看到不同的水生珍稀动物,让游客大饱眼福。" +
"<p><em>在落潮时,部分的珊瑚礁露出水面形成珊瑚岛。在礁群与海岸之间是一条极方便的交通海路。<strong>风平浪静时,游船在此间通过,船下连绵不断的多彩、多形的珊瑚景色,就成为吸引世界各地游客来猎奇观赏的最佳海底奇观。</strong></em>大堡礁属热带气候,主要受南半球气流控制。</p>", 13999.0)
);
productRepository.save(products);
Catalog catalog = new Catalog(0L, "测试目录1");
catalog.getProducts().addAll(products);
catalogRepository.save(catalog);
Address warehouseAddress = new Address("中国", "云南", "丽江", "古城区", "street1", "street2", 000000);
Address shipToAddress = new Address("中国", "海南省", "三亚", "天涯区", "street1", "street2", 000001);
addressRepository.save(Arrays.asList(warehouseAddress, shipToAddress));
Warehouse warehouse = new Warehouse("测试仓库1");
warehouse.setAddress(warehouseAddress);
warehouse = warehouseRepository.save(warehouse);
Warehouse finalWarehouse = warehouse;
// 创建一个有着随机库存编号的库存集合。即为每个产品生成一个产品数量为1的库存,有着随机库存编号
Random random = new Random();
Set<Inventory> inventories = products.stream()
.map(product -> new Inventory(IntStream.range(0, 9).mapToObj(i -> Integer.toString(random.nextInt(9))).collect(Collectors.joining("")), product, finalWarehouse, InventoryStatus.IN_STOCK)).collect(Collectors.toSet());
inventoryRepository.save(inventories);
// 为每 <SUF>
for(int i = 0; i < 10; i++) {
inventoryRepository.save(products.stream().map(product -> new Inventory(IntStream.range(0, 9).mapToObj(x -> Integer.toString(random.nextInt(9))).collect(Collectors.joining("")), product, finalWarehouse, InventoryStatus.IN_STOCK)).collect(Collectors.toSet()));
}
Shipment shipment = new Shipment(inventories, shipToAddress, warehouse, ShipmentStatus.SHIPPED);
shipmentRepository.save(shipment);
}
}
| false | 1,822 | 31 | 2,426 | 35 | 1,997 | 30 | 2,426 | 35 | 3,152 | 56 | false | false | false | false | false | true |
50782_4 | package com.chaoxing.gsd.web;
import com.alibaba.fastjson.JSON;
import com.chaoxing.gsd.modules.service.RsService;
import com.chaoxing.gsd.service.DownloadIndexService;
import com.chaoxing.gsd.service.SearchESClusterService;
import com.chaoxing.gsd.service.SearchESIndexService;
import com.chaoxing.gsd.service.WebpageIndexService;
import com.chaoxing.gsd.utils.IDUtils;
import com.chaoxing.gsd.web.res.BaseRes;
import com.chaoxing.gsd.web.res.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import java.io.*;
import java.util.*;
import com.spreada.utils.chinese.*;
import com.chaoxing.gsd.modules.entity.Gis;
/**
* @author heyang
* @date 2018/08/27 describe:索引操作
*/
@Controller
@RequestMapping("/gsd")
public class SSPController {
@Autowired
private SearchESIndexService esService;
@Autowired
private RsService rsService;
@Autowired
private DownloadIndexService downloadIndexService;
@Autowired
private SearchESClusterService sec;
@Autowired
private WebpageIndexService webpageis;
// 文献message_types字段限制条件:BK=图书,JN=期刊,DT=学位论文,CP=会议论文,PAT=专利,ST=标准,NP=报纸,TR=科技成果,年鉴=YB,法律法规=LAR,信息咨询=INF,案例=CAS
@SuppressWarnings("unused")
private static String[] message_types = { "BK", "DT", "JN", "CP", "PAT", "ST", "NP", "TR", "YB", "LAR", "INF",
"CAS" };
// 用户保存网页document_type文档类型限制:webpage:邮件采集网页,literature文献
public static final List<String> DOCUMENT_TYPES = Arrays.asList(new String[] { "webpage", "literature" });
public static Logger logger = LoggerFactory.getLogger(SSPController.class);
/**
* @author heyang
* @param ${indexnames}
* 索引数组
* @param ${content}
* 搜索内容
* @param ${field}
* 检索字段
* @param ${pagesize}
* 每页记录数
* @param ${pagenum}
* 第几页从0开始 describe: 在指定多个索引库检索内容
*/
@POST
@RequestMapping("/search2")
@ResponseBody
public BaseResponse search2(@RequestParam(value = "indexnames") String[] indexNames,
@RequestParam(value = "content") String content, @RequestParam(value = "field") String field,
@RequestParam(value = "pagesize") Integer pageSize, @RequestParam(value = "pagenum") Integer pageNum) {
long begin1 = System.currentTimeMillis();
// 将内容转成简体
String trueSearch = content == null ? content : 简繁转换类.转换(content, 简繁转换类.目标.简体);
BaseResponse resp = new BaseResponse();
Map<String, Object> map = esService.search2(indexNames, trueSearch, field, pageSize, pageNum);
resp.setStatu(true);
resp.setData(map);
logger.info("search2 from es index: {} toast time:{} ", JSON.toJSONString(indexNames),
System.currentTimeMillis() - begin1);
return resp;
}
/**
* 在(七个哈佛库/7个索引)指定多个索引库查找聚类(String[] indexnames,String content,String field)
* 参数说明:indexnames索引库数组:textref_zhonghuajingdian,textref_kanripo,textref_ctext,textref_cbta,biogref_dnb,biogref_ddbc,biogref_cbdb
* content:搜索内容,field:检索字段,传空值,则在所有字段检索
* 返回的聚类名称包含:
* "gender","born_year","died_year","dynasty","jiguan","author","edition","collection","notes"
* @param indexNames
* @param content
* @param field
* @return
*/
@POST
@RequestMapping("/searchclusters2")
@ResponseBody
public BaseResponse searchClusters2(@RequestParam(value = "indexnames", required = true) String[] indexNames,
@RequestParam(value = "content", required = true) String content,
@RequestParam(value = "field", required = true) String field) {
long begin1 = System.currentTimeMillis();
BaseResponse resp = new BaseResponse();
Map<?, ?> map = sec.search2(indexNames, content, field);
resp.setStatu(true);
resp.setData(map);
logger.info("searchclusters2 from es index: {} toast time:{} ", JSON.toJSONString(indexNames),
System.currentTimeMillis() - begin1);
return resp;
}
/**
* @author heyang
* @param ${indexName}索引名称
* @param ${indexId}
* 文档id describe: 根据索引名称和文档id查询文档
*/
@PostMapping("/es/searchindexbyid")
@ResponseBody
public BaseResponse searchDocumentById(@RequestParam(name = "indexName") String indexName,
@RequestParam(name = "indexId") String documentId) {
long begin1 = System.currentTimeMillis();
BaseResponse resp = new BaseResponse();
try {
List<Map<String, Object>> result = esService.searchDocumentById(indexName, documentId);
resp.setStatu(true);
resp.setData(result);
} catch (Exception e) {
logger.info("searchindexbyid from es index: {} error:{} ", indexName, e);
resp = BaseRes.getErrorResponse();
}
logger.info("searchindexbyid from es index: {} toast time:{} ", indexName, System.currentTimeMillis() - begin1);
return resp;
}
/**
* @author heyang
* @param ${indexName}
* 索引名称 webpage
* @param ${documentIds}
* 文档id数组
* @param ${userId}
* 用户id describe:根据索引名称文档id数组删除文档
*/
@PostMapping("/es/deldocumentbyids")
@ResponseBody
public BaseResponse delDocumentById(@RequestParam(name = "indexName") String indexName,
@RequestParam(name = "documentIds") String[] documentIds,
@RequestParam(name = "userId", required = false) String userId) {
long begin1 = System.currentTimeMillis();
BaseResponse resp = new BaseResponse();
try {
for (String documentId : documentIds) {
esService.delDocumentById(indexName, documentId);
}
resp.setStatu(true);
} catch (Exception e) {
logger.info("deldocumentbyids from es indexName: {} error:{} ", indexName, e);
resp = BaseRes.getErrorResponse();
}
logger.info("deldocumentbyids from es indexName: {} toast time:{} ", indexName,
System.currentTimeMillis() - begin1);
return resp;
}
/**
* @author heyang
* @param webpageIds
* 网页id数组
* @param userId
* 用户id
* @param downloadType
* 导出格式:1(ris格式)/2(bib格式)只能输入1或者2 describe: 导出webpage索引
*/
@PostMapping("/es/downloadwebpage")
@ResponseBody
public void downLoadWebPage(@RequestParam(name = "webpageIds") String[] webpageIds,
@RequestParam(name = "userId") String userId, @RequestParam(name = "downloadType") int downloadType,
HttpServletResponse response, HttpServletRequest request) {
try {
if (downloadType != 1 && downloadType != 2) {
logger.warn("downloadType只能输入1或者2");
return;
}
List<Map<String, Object>> list = new ArrayList<>();
// 查询所有网页
for (String indexId : webpageIds) {
List<Map<String, Object>> result = esService.searchDocumentById("webpage", indexId);
if (result.size() != 0) {
Map<String, Object> map = result.get(0);
try {
list.add(map);
} catch (Exception e) {
logger.error("downLoadWebPage error:{}", e);
}
}
}
String token = IDUtils.maketoken();
String path = "";
if (downloadType == 1) {
path = "/" + token + ".ris";
} else if (downloadType == 2) {
path = "/" + token + ".bib";
}
String fileName = request.getServletContext().getRealPath(path);
File file = new File(fileName);
// 创建文件
if (!file.exists()) {
file.createNewFile();
}
// 写入,下载,删除
if (downloadType == 1) {
downloadIndexService.writeris(list, file);
} else if (downloadType == 2) {
downloadIndexService.writebib(list, file);
}
downLoad(response, fileName);
file.delete();
// 异步保存导出记录信息
toSaveExportLiteratureRecord(userId, webpageIds);
} catch (Exception e) {
logger.error("downLoadWebPage error io:{}", e);
}
}
/**
* 保存文献导出记录信息
*
* @param userId
* 用户id
* @param literatureId
* 文献id
*/
@Async("asyncServiceExecutor")
private void toSaveExportLiteratureRecord(String userId, String[] literatureId) {
rsService.toSaveExportLiteratureRecord(userId, literatureId);
}
/**
* @author heyang
* @param path
* 文件路径 describe: 下载文本文件
*/
public void downLoad(HttpServletResponse response, String path) throws IOException {
File file = new File(path);
response.setContentType("text/html;charset=utf-8");
FileReader reader = new FileReader(file);
// 写出(字符缓冲流,只能写文字不能写图片)
PrintWriter out = response.getWriter();
char buffer[] = new char[1024];
int len = 1024;
while ((len = reader.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
// 释放资源
reader.close();
out.flush();
out.close();
}
/**
* @author heyang
* @param ${indexName}
* 索引名称 sanfrancisco_picture describe: gis过滤
*/
@PostMapping("/es/gis")
@ResponseBody
public BaseResponse Gis(@RequestParam(name = "indexName") String indexName) {
long begin1 = System.currentTimeMillis();
BaseResponse resp = new BaseResponse();
try {
List<Gis> result = webpageis.Gis();
resp.setStatu(true);
resp.setData(result);
} catch (Exception e) {
logger.info("gis from es index: {} error:{} ", indexName, e);
resp = BaseRes.getErrorResponse();
}
logger.info("gis from es index: {} toast time:{} ", indexName, System.currentTimeMillis() - begin1);
return resp;
}
}
| chaoxing-gsd/GSD | GSD-open/src/main/java/com/chaoxing/gsd/web/SSPController.java | 2,990 | // 将内容转成简体 | line_comment | zh-cn | package com.chaoxing.gsd.web;
import com.alibaba.fastjson.JSON;
import com.chaoxing.gsd.modules.service.RsService;
import com.chaoxing.gsd.service.DownloadIndexService;
import com.chaoxing.gsd.service.SearchESClusterService;
import com.chaoxing.gsd.service.SearchESIndexService;
import com.chaoxing.gsd.service.WebpageIndexService;
import com.chaoxing.gsd.utils.IDUtils;
import com.chaoxing.gsd.web.res.BaseRes;
import com.chaoxing.gsd.web.res.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import java.io.*;
import java.util.*;
import com.spreada.utils.chinese.*;
import com.chaoxing.gsd.modules.entity.Gis;
/**
* @author heyang
* @date 2018/08/27 describe:索引操作
*/
@Controller
@RequestMapping("/gsd")
public class SSPController {
@Autowired
private SearchESIndexService esService;
@Autowired
private RsService rsService;
@Autowired
private DownloadIndexService downloadIndexService;
@Autowired
private SearchESClusterService sec;
@Autowired
private WebpageIndexService webpageis;
// 文献message_types字段限制条件:BK=图书,JN=期刊,DT=学位论文,CP=会议论文,PAT=专利,ST=标准,NP=报纸,TR=科技成果,年鉴=YB,法律法规=LAR,信息咨询=INF,案例=CAS
@SuppressWarnings("unused")
private static String[] message_types = { "BK", "DT", "JN", "CP", "PAT", "ST", "NP", "TR", "YB", "LAR", "INF",
"CAS" };
// 用户保存网页document_type文档类型限制:webpage:邮件采集网页,literature文献
public static final List<String> DOCUMENT_TYPES = Arrays.asList(new String[] { "webpage", "literature" });
public static Logger logger = LoggerFactory.getLogger(SSPController.class);
/**
* @author heyang
* @param ${indexnames}
* 索引数组
* @param ${content}
* 搜索内容
* @param ${field}
* 检索字段
* @param ${pagesize}
* 每页记录数
* @param ${pagenum}
* 第几页从0开始 describe: 在指定多个索引库检索内容
*/
@POST
@RequestMapping("/search2")
@ResponseBody
public BaseResponse search2(@RequestParam(value = "indexnames") String[] indexNames,
@RequestParam(value = "content") String content, @RequestParam(value = "field") String field,
@RequestParam(value = "pagesize") Integer pageSize, @RequestParam(value = "pagenum") Integer pageNum) {
long begin1 = System.currentTimeMillis();
// 将内 <SUF>
String trueSearch = content == null ? content : 简繁转换类.转换(content, 简繁转换类.目标.简体);
BaseResponse resp = new BaseResponse();
Map<String, Object> map = esService.search2(indexNames, trueSearch, field, pageSize, pageNum);
resp.setStatu(true);
resp.setData(map);
logger.info("search2 from es index: {} toast time:{} ", JSON.toJSONString(indexNames),
System.currentTimeMillis() - begin1);
return resp;
}
/**
* 在(七个哈佛库/7个索引)指定多个索引库查找聚类(String[] indexnames,String content,String field)
* 参数说明:indexnames索引库数组:textref_zhonghuajingdian,textref_kanripo,textref_ctext,textref_cbta,biogref_dnb,biogref_ddbc,biogref_cbdb
* content:搜索内容,field:检索字段,传空值,则在所有字段检索
* 返回的聚类名称包含:
* "gender","born_year","died_year","dynasty","jiguan","author","edition","collection","notes"
* @param indexNames
* @param content
* @param field
* @return
*/
@POST
@RequestMapping("/searchclusters2")
@ResponseBody
public BaseResponse searchClusters2(@RequestParam(value = "indexnames", required = true) String[] indexNames,
@RequestParam(value = "content", required = true) String content,
@RequestParam(value = "field", required = true) String field) {
long begin1 = System.currentTimeMillis();
BaseResponse resp = new BaseResponse();
Map<?, ?> map = sec.search2(indexNames, content, field);
resp.setStatu(true);
resp.setData(map);
logger.info("searchclusters2 from es index: {} toast time:{} ", JSON.toJSONString(indexNames),
System.currentTimeMillis() - begin1);
return resp;
}
/**
* @author heyang
* @param ${indexName}索引名称
* @param ${indexId}
* 文档id describe: 根据索引名称和文档id查询文档
*/
@PostMapping("/es/searchindexbyid")
@ResponseBody
public BaseResponse searchDocumentById(@RequestParam(name = "indexName") String indexName,
@RequestParam(name = "indexId") String documentId) {
long begin1 = System.currentTimeMillis();
BaseResponse resp = new BaseResponse();
try {
List<Map<String, Object>> result = esService.searchDocumentById(indexName, documentId);
resp.setStatu(true);
resp.setData(result);
} catch (Exception e) {
logger.info("searchindexbyid from es index: {} error:{} ", indexName, e);
resp = BaseRes.getErrorResponse();
}
logger.info("searchindexbyid from es index: {} toast time:{} ", indexName, System.currentTimeMillis() - begin1);
return resp;
}
/**
* @author heyang
* @param ${indexName}
* 索引名称 webpage
* @param ${documentIds}
* 文档id数组
* @param ${userId}
* 用户id describe:根据索引名称文档id数组删除文档
*/
@PostMapping("/es/deldocumentbyids")
@ResponseBody
public BaseResponse delDocumentById(@RequestParam(name = "indexName") String indexName,
@RequestParam(name = "documentIds") String[] documentIds,
@RequestParam(name = "userId", required = false) String userId) {
long begin1 = System.currentTimeMillis();
BaseResponse resp = new BaseResponse();
try {
for (String documentId : documentIds) {
esService.delDocumentById(indexName, documentId);
}
resp.setStatu(true);
} catch (Exception e) {
logger.info("deldocumentbyids from es indexName: {} error:{} ", indexName, e);
resp = BaseRes.getErrorResponse();
}
logger.info("deldocumentbyids from es indexName: {} toast time:{} ", indexName,
System.currentTimeMillis() - begin1);
return resp;
}
/**
* @author heyang
* @param webpageIds
* 网页id数组
* @param userId
* 用户id
* @param downloadType
* 导出格式:1(ris格式)/2(bib格式)只能输入1或者2 describe: 导出webpage索引
*/
@PostMapping("/es/downloadwebpage")
@ResponseBody
public void downLoadWebPage(@RequestParam(name = "webpageIds") String[] webpageIds,
@RequestParam(name = "userId") String userId, @RequestParam(name = "downloadType") int downloadType,
HttpServletResponse response, HttpServletRequest request) {
try {
if (downloadType != 1 && downloadType != 2) {
logger.warn("downloadType只能输入1或者2");
return;
}
List<Map<String, Object>> list = new ArrayList<>();
// 查询所有网页
for (String indexId : webpageIds) {
List<Map<String, Object>> result = esService.searchDocumentById("webpage", indexId);
if (result.size() != 0) {
Map<String, Object> map = result.get(0);
try {
list.add(map);
} catch (Exception e) {
logger.error("downLoadWebPage error:{}", e);
}
}
}
String token = IDUtils.maketoken();
String path = "";
if (downloadType == 1) {
path = "/" + token + ".ris";
} else if (downloadType == 2) {
path = "/" + token + ".bib";
}
String fileName = request.getServletContext().getRealPath(path);
File file = new File(fileName);
// 创建文件
if (!file.exists()) {
file.createNewFile();
}
// 写入,下载,删除
if (downloadType == 1) {
downloadIndexService.writeris(list, file);
} else if (downloadType == 2) {
downloadIndexService.writebib(list, file);
}
downLoad(response, fileName);
file.delete();
// 异步保存导出记录信息
toSaveExportLiteratureRecord(userId, webpageIds);
} catch (Exception e) {
logger.error("downLoadWebPage error io:{}", e);
}
}
/**
* 保存文献导出记录信息
*
* @param userId
* 用户id
* @param literatureId
* 文献id
*/
@Async("asyncServiceExecutor")
private void toSaveExportLiteratureRecord(String userId, String[] literatureId) {
rsService.toSaveExportLiteratureRecord(userId, literatureId);
}
/**
* @author heyang
* @param path
* 文件路径 describe: 下载文本文件
*/
public void downLoad(HttpServletResponse response, String path) throws IOException {
File file = new File(path);
response.setContentType("text/html;charset=utf-8");
FileReader reader = new FileReader(file);
// 写出(字符缓冲流,只能写文字不能写图片)
PrintWriter out = response.getWriter();
char buffer[] = new char[1024];
int len = 1024;
while ((len = reader.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
// 释放资源
reader.close();
out.flush();
out.close();
}
/**
* @author heyang
* @param ${indexName}
* 索引名称 sanfrancisco_picture describe: gis过滤
*/
@PostMapping("/es/gis")
@ResponseBody
public BaseResponse Gis(@RequestParam(name = "indexName") String indexName) {
long begin1 = System.currentTimeMillis();
BaseResponse resp = new BaseResponse();
try {
List<Gis> result = webpageis.Gis();
resp.setStatu(true);
resp.setData(result);
} catch (Exception e) {
logger.info("gis from es index: {} error:{} ", indexName, e);
resp = BaseRes.getErrorResponse();
}
logger.info("gis from es index: {} toast time:{} ", indexName, System.currentTimeMillis() - begin1);
return resp;
}
}
| false | 2,570 | 8 | 2,990 | 7 | 2,963 | 7 | 2,990 | 7 | 3,680 | 11 | false | false | false | false | false | true |
20975_16 | import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
/**
* 公司:http://192.168.3.41:8080/
* 家里:http://192.168.0.2:8080/
*/
@ServerEndpoint("/chatServer")
public class ChatServer {
//connect key为session的ID,value为此对象this
private static final HashMap<String, Object> connect = new HashMap<String, Object>();
//userMap key为session的ID,value为用户名
private static final HashMap<String, String> userMap = new HashMap<String, String>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//判断是否是第一次接收的消息
private boolean isFirst = true;
private String username;
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
connect.put(session.getId(), this);//获取Session,存入HashMap中
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
String usr = userMap.get(session.getId());
userMap.remove(session.getId());
connect.remove(session.getId());
System.out.println(usr + "退出!当前在线人数为" + connect.size());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
if (isFirst) {
this.username = message;
System.out.println("用户" + username + "上线,在线人数:" + connect.size());
userMap.put(session.getId(), username);
isFirst = false;
} else {
String[] msg = message.split("@", 2);//以@为分隔符把字符串分为xxx和xxx两部分,msg[0]表示发送至的用户名,all则表示发给所有人
if (msg[0].equals("all")) {
sendToAll(msg[1], session);
} else {
sendToUser(msg[0], msg[1], session);
}
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误" + error.getMessage());
error.printStackTrace();
}
/**
* 给所有人发送消息
*
* @param msg 发送的消息
* @param session
*/
private void sendToAll(String msg, Session session) {
String who;
//群发消息
for (String key : connect.keySet()) {
ChatServer client = (ChatServer) connect.get(key);
if (key.equalsIgnoreCase(userMap.get(key))) {
who = "自己对大家说 : ";
} else {
who = userMap.get(session.getId()) + "对大家说 :";
}
synchronized (client) {
try {
client.session.getBasicRemote().sendText(who + msg);
System.out.println(who + msg);
} catch (IOException e) {
connect.remove(client);
e.printStackTrace();
try {
client.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
/**
* 发送给指定用户
*
* @param user 用户名
* @param msg 发送的消息
* @param session
*/
private void sendToUser(String user, String msg, Session session) {
boolean you = false;//标记是否找到发送的用户
for (String key : userMap.keySet()) {
if (user.equalsIgnoreCase(userMap.get(key))) {
ChatServer client = (ChatServer) connect.get(key);
synchronized (client) {
try {
client.session.getBasicRemote().sendText(userMap.get(session.getId()) + "对你说:" + msg);
System.out.println(userMap.get(session.getId()) + "对你说:" + msg);
} catch (IOException e) {
connect.remove(client);
try {
client.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
you = true;//找到指定用户标记为true
break;
}
}
//you为true则在自己页面显示自己对xxx说xxx,否则显示系统:无此用户
if (you) {
try {
session.getBasicRemote().sendText("自己对" + user + "说:" + msg);
System.out.println("自己对" + user + "说:" + msg);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
System.out.println("系统:无此用户");
session.getBasicRemote().sendText("系统:无此用户");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| chaozhouzhang/demos | WebSocketDemo/server-java/WebSocketServer/Chat/src/ChatServer.java | 1,313 | //找到指定用户标记为true
| line_comment | zh-cn | import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
/**
* @ServerEndpoint 注解是一个类层次的注解,它的功能主要是将目前的类定义成一个websocket服务器端,
* 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
*/
/**
* 公司:http://192.168.3.41:8080/
* 家里:http://192.168.0.2:8080/
*/
@ServerEndpoint("/chatServer")
public class ChatServer {
//connect key为session的ID,value为此对象this
private static final HashMap<String, Object> connect = new HashMap<String, Object>();
//userMap key为session的ID,value为用户名
private static final HashMap<String, String> userMap = new HashMap<String, String>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//判断是否是第一次接收的消息
private boolean isFirst = true;
private String username;
/**
* 连接建立成功调用的方法
*
* @param session 可选的参数。session为与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
connect.put(session.getId(), this);//获取Session,存入HashMap中
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session) {
String usr = userMap.get(session.getId());
userMap.remove(session.getId());
connect.remove(session.getId());
System.out.println(usr + "退出!当前在线人数为" + connect.size());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
* @param session 可选的参数
*/
@OnMessage
public void onMessage(String message, Session session) {
if (isFirst) {
this.username = message;
System.out.println("用户" + username + "上线,在线人数:" + connect.size());
userMap.put(session.getId(), username);
isFirst = false;
} else {
String[] msg = message.split("@", 2);//以@为分隔符把字符串分为xxx和xxx两部分,msg[0]表示发送至的用户名,all则表示发给所有人
if (msg[0].equals("all")) {
sendToAll(msg[1], session);
} else {
sendToUser(msg[0], msg[1], session);
}
}
}
/**
* 发生错误时调用
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误" + error.getMessage());
error.printStackTrace();
}
/**
* 给所有人发送消息
*
* @param msg 发送的消息
* @param session
*/
private void sendToAll(String msg, Session session) {
String who;
//群发消息
for (String key : connect.keySet()) {
ChatServer client = (ChatServer) connect.get(key);
if (key.equalsIgnoreCase(userMap.get(key))) {
who = "自己对大家说 : ";
} else {
who = userMap.get(session.getId()) + "对大家说 :";
}
synchronized (client) {
try {
client.session.getBasicRemote().sendText(who + msg);
System.out.println(who + msg);
} catch (IOException e) {
connect.remove(client);
e.printStackTrace();
try {
client.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
/**
* 发送给指定用户
*
* @param user 用户名
* @param msg 发送的消息
* @param session
*/
private void sendToUser(String user, String msg, Session session) {
boolean you = false;//标记是否找到发送的用户
for (String key : userMap.keySet()) {
if (user.equalsIgnoreCase(userMap.get(key))) {
ChatServer client = (ChatServer) connect.get(key);
synchronized (client) {
try {
client.session.getBasicRemote().sendText(userMap.get(session.getId()) + "对你说:" + msg);
System.out.println(userMap.get(session.getId()) + "对你说:" + msg);
} catch (IOException e) {
connect.remove(client);
try {
client.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
you = true;//找到 <SUF>
break;
}
}
//you为true则在自己页面显示自己对xxx说xxx,否则显示系统:无此用户
if (you) {
try {
session.getBasicRemote().sendText("自己对" + user + "说:" + msg);
System.out.println("自己对" + user + "说:" + msg);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
System.out.println("系统:无此用户");
session.getBasicRemote().sendText("系统:无此用户");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| false | 1,212 | 8 | 1,308 | 8 | 1,407 | 8 | 1,308 | 8 | 1,731 | 14 | false | false | false | false | false | true |
39727_11 | package adm.bean;
public class Logger {
private String id; //记录事务日志的id
private String searchType; //搜索类型
private String types; //日志操作类型 发信 收信、登录、其它
private String title; //邮件主题
private String fmail; //发送者
private String tmail; //接收者
private String ftmail; //搜索帐号
private String time; //日志操作时间
private String times; //操作时间
private String timex; //操作时间
private String day; //搜索天数
private String state; //邮箱发送状态
private String userid; //用户id/管理员id
private String username; //用户名称/管理员名称
private String odata; //相关数据
private String ips; //登录ip
/*分页字段 -- Start*/
private int start ;
private int end ;
/*分页字段 -- End*/
private String domain;//域名
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFmail() {
return fmail;
}
public void setFmail(String fmail) {
this.fmail = fmail;
}
public String getTmail() {
return tmail;
}
public void setTmail(String tmail) {
this.tmail = tmail;
}
public String getFtmail() {
return ftmail;
}
public void setFtmail(String ftmail) {
this.ftmail = ftmail;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getTimes() {
return times;
}
public void setTimes(String times) {
this.times = times;
}
public String getTimex() {
return timex;
}
public void setTimex(String timex) {
this.timex = timex;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
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 getOdata() {
return odata;
}
public void setOdata(String odata) {
this.odata = odata;
}
public String getIps() {
return ips;
}
public void setIps(String ips) {
this.ips = ips;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
}
| chapin666/mail-ssm | mail/src/adm/bean/Logger.java | 1,002 | //邮箱发送状态
| line_comment | zh-cn | package adm.bean;
public class Logger {
private String id; //记录事务日志的id
private String searchType; //搜索类型
private String types; //日志操作类型 发信 收信、登录、其它
private String title; //邮件主题
private String fmail; //发送者
private String tmail; //接收者
private String ftmail; //搜索帐号
private String time; //日志操作时间
private String times; //操作时间
private String timex; //操作时间
private String day; //搜索天数
private String state; //邮箱 <SUF>
private String userid; //用户id/管理员id
private String username; //用户名称/管理员名称
private String odata; //相关数据
private String ips; //登录ip
/*分页字段 -- Start*/
private int start ;
private int end ;
/*分页字段 -- End*/
private String domain;//域名
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSearchType() {
return searchType;
}
public void setSearchType(String searchType) {
this.searchType = searchType;
}
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFmail() {
return fmail;
}
public void setFmail(String fmail) {
this.fmail = fmail;
}
public String getTmail() {
return tmail;
}
public void setTmail(String tmail) {
this.tmail = tmail;
}
public String getFtmail() {
return ftmail;
}
public void setFtmail(String ftmail) {
this.ftmail = ftmail;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getTimes() {
return times;
}
public void setTimes(String times) {
this.times = times;
}
public String getTimex() {
return timex;
}
public void setTimex(String timex) {
this.timex = timex;
}
public String getDay() {
return day;
}
public void setDay(String day) {
this.day = day;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
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 getOdata() {
return odata;
}
public void setOdata(String odata) {
this.odata = odata;
}
public String getIps() {
return ips;
}
public void setIps(String ips) {
this.ips = ips;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
}
| false | 780 | 5 | 1,002 | 5 | 1,014 | 5 | 1,002 | 5 | 1,148 | 12 | false | false | false | false | false | true |
35054_28 | package wang.imchao.plugin.alipay;
import android.text.TextUtils;
import com.alipay.sdk.app.PayTask;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class AliPayPlugin extends CordovaPlugin {
private static String TAG = "AliPayPlugin";
//商户PID
private String partner = "";
//商户收款账号
private String seller = "";
//商户私钥,pkcs8格式
private String privateKey = "";
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
partner = webView.getPreferences().getString("partner", "");
seller = webView.getPreferences().getString("seller", "");
privateKey = webView.getPreferences().getString("privatekey", "");
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
try {
JSONObject arguments = args.getJSONObject(0);
String tradeNo = arguments.getString("tradeNo");
String subject = arguments.getString("subject");
String body = arguments.getString("body");
String price = arguments.getString("price");
String notifyUrl = arguments.getString("notifyUrl");
this.pay(tradeNo, subject, body, price, notifyUrl, callbackContext);
} catch (JSONException e) {
callbackContext.error(new JSONObject());
e.printStackTrace();
return false;
}
return true;
}
public void pay(String tradeNo, String subject, String body, String price, String notifyUrl, final CallbackContext callbackContext) {
// 订单
String orderInfo = createRequestParameters(subject, body, price, tradeNo, notifyUrl);
// 对订单做RSA 签名
String sign = sign(orderInfo);
try {
// 仅需对sign 做URL编码
sign = URLEncoder.encode(sign, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 完整的符合支付宝参数规范的订单信息
final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
+ getSignType();
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
// 构造PayTask 对象
PayTask alipay = new PayTask(cordova.getActivity());
// 调用支付接口,获取支付结果
String result = alipay.pay(payInfo);
PayResult payResult = new PayResult(result);
if (TextUtils.equals(payResult.getResultStatus(), "9000")) {
callbackContext.success(payResult.toJson());
} else {
// 判断resultStatus 为非“9000”则代表可能支付失败
// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态)
if (TextUtils.equals(payResult.getResultStatus(), "8000")) {
callbackContext.success(payResult.toJson());
} else {
callbackContext.error(payResult.toJson());
}
}
}
});
}
/**
* create the order info. 创建订单信息
*/
public String createRequestParameters(String subject, String body, String price, String tradeNo, String notifyUrl) {
// 签约合作者身份ID
String orderInfo = "partner=" + "\"" + partner + "\"";
// 签约卖家支付宝账号
orderInfo += "&seller_id=" + "\"" + seller + "\"";
// 商户网站唯一订单号
orderInfo += "&out_trade_no=" + "\"" + tradeNo + "\"";
// 商品名称
orderInfo += "&subject=" + "\"" + subject + "\"";
// 商品详情
orderInfo += "&body=" + "\"" + body + "\"";
// 商品金额
orderInfo += "&total_fee=" + "\"" + price + "\"";
// 服务器异步通知页面路径
orderInfo += "¬ify_url=" + "\"" + notifyUrl
+ "\"";
// 服务接口名称, 固定值
orderInfo += "&service=\"mobile.securitypay.pay\"";
// 支付类型, 固定值
orderInfo += "&payment_type=\"1\"";
// 参数编码, 固定值
orderInfo += "&_input_charset=\"utf-8\"";
// 设置未付款交易的超时时间
// 默认30分钟,一旦超时,该笔交易就会自动被关闭。
// 取值范围:1m~15d。
// m-分钟,h-小时,d-天,1c-当天(无论交易何时创建,都在0点关闭)。
// 该参数数值不接受小数点,如1.5h,可转换为90m。
orderInfo += "&it_b_pay=\"30m\"";
// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";
// 支付宝处理完请求后,当前页面跳转到商户指定页面的路径,可空
orderInfo += "&return_url=\"m.alipay.com\"";
// 调用银行卡支付,需配置此参数,参与签名, 固定值 (需要签约《无线银行卡快捷支付》才能使用)
// orderInfo += "&paymethod=\"expressGateway\"";
return orderInfo;
}
/**
* sign the order info. 对订单信息进行签名
*
* @param content 待签名订单信息
*/
public String sign(String content) {
return SignUtils.sign(content, privateKey);
}
/**
* get the sign type we use. 获取签名方式
*/
public String getSignType() {
return "sign_type=\"RSA\"";
}
}
| charleyw/cordova-plugin-alipay | src/android/AliPayPlugin.java | 1,415 | // 支付宝处理完请求后,当前页面跳转到商户指定页面的路径,可空 | line_comment | zh-cn | package wang.imchao.plugin.alipay;
import android.text.TextUtils;
import com.alipay.sdk.app.PayTask;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
public class AliPayPlugin extends CordovaPlugin {
private static String TAG = "AliPayPlugin";
//商户PID
private String partner = "";
//商户收款账号
private String seller = "";
//商户私钥,pkcs8格式
private String privateKey = "";
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
partner = webView.getPreferences().getString("partner", "");
seller = webView.getPreferences().getString("seller", "");
privateKey = webView.getPreferences().getString("privatekey", "");
}
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {
try {
JSONObject arguments = args.getJSONObject(0);
String tradeNo = arguments.getString("tradeNo");
String subject = arguments.getString("subject");
String body = arguments.getString("body");
String price = arguments.getString("price");
String notifyUrl = arguments.getString("notifyUrl");
this.pay(tradeNo, subject, body, price, notifyUrl, callbackContext);
} catch (JSONException e) {
callbackContext.error(new JSONObject());
e.printStackTrace();
return false;
}
return true;
}
public void pay(String tradeNo, String subject, String body, String price, String notifyUrl, final CallbackContext callbackContext) {
// 订单
String orderInfo = createRequestParameters(subject, body, price, tradeNo, notifyUrl);
// 对订单做RSA 签名
String sign = sign(orderInfo);
try {
// 仅需对sign 做URL编码
sign = URLEncoder.encode(sign, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 完整的符合支付宝参数规范的订单信息
final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
+ getSignType();
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
// 构造PayTask 对象
PayTask alipay = new PayTask(cordova.getActivity());
// 调用支付接口,获取支付结果
String result = alipay.pay(payInfo);
PayResult payResult = new PayResult(result);
if (TextUtils.equals(payResult.getResultStatus(), "9000")) {
callbackContext.success(payResult.toJson());
} else {
// 判断resultStatus 为非“9000”则代表可能支付失败
// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认,最终交易是否成功以服务端异步通知为准(小概率状态)
if (TextUtils.equals(payResult.getResultStatus(), "8000")) {
callbackContext.success(payResult.toJson());
} else {
callbackContext.error(payResult.toJson());
}
}
}
});
}
/**
* create the order info. 创建订单信息
*/
public String createRequestParameters(String subject, String body, String price, String tradeNo, String notifyUrl) {
// 签约合作者身份ID
String orderInfo = "partner=" + "\"" + partner + "\"";
// 签约卖家支付宝账号
orderInfo += "&seller_id=" + "\"" + seller + "\"";
// 商户网站唯一订单号
orderInfo += "&out_trade_no=" + "\"" + tradeNo + "\"";
// 商品名称
orderInfo += "&subject=" + "\"" + subject + "\"";
// 商品详情
orderInfo += "&body=" + "\"" + body + "\"";
// 商品金额
orderInfo += "&total_fee=" + "\"" + price + "\"";
// 服务器异步通知页面路径
orderInfo += "¬ify_url=" + "\"" + notifyUrl
+ "\"";
// 服务接口名称, 固定值
orderInfo += "&service=\"mobile.securitypay.pay\"";
// 支付类型, 固定值
orderInfo += "&payment_type=\"1\"";
// 参数编码, 固定值
orderInfo += "&_input_charset=\"utf-8\"";
// 设置未付款交易的超时时间
// 默认30分钟,一旦超时,该笔交易就会自动被关闭。
// 取值范围:1m~15d。
// m-分钟,h-小时,d-天,1c-当天(无论交易何时创建,都在0点关闭)。
// 该参数数值不接受小数点,如1.5h,可转换为90m。
orderInfo += "&it_b_pay=\"30m\"";
// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";
// 支付 <SUF>
orderInfo += "&return_url=\"m.alipay.com\"";
// 调用银行卡支付,需配置此参数,参与签名, 固定值 (需要签约《无线银行卡快捷支付》才能使用)
// orderInfo += "&paymethod=\"expressGateway\"";
return orderInfo;
}
/**
* sign the order info. 对订单信息进行签名
*
* @param content 待签名订单信息
*/
public String sign(String content) {
return SignUtils.sign(content, privateKey);
}
/**
* get the sign type we use. 获取签名方式
*/
public String getSignType() {
return "sign_type=\"RSA\"";
}
}
| false | 1,328 | 23 | 1,415 | 22 | 1,473 | 20 | 1,415 | 22 | 1,999 | 35 | false | false | false | false | false | true |
58095_3 | package org.wanbang.study.allDesignMode.constructMode.proxyMode;
/**
* @description: 代理模式
* @author majiajian
* @date 2022/8/17 18:38
* @version 1.0
*/
/**
*
* 代理模式有点像⽼⼤和⼩弟,也有点像分销商。主要解决的是问题是为某些资源的访问、对象的类的易
* ⽤操作上提供⽅便使⽤的代理服务。⽽这种设计思想的模式经常会出现在我们的系统中,或者你⽤到过
* 的组件中,它们都提供给你⼀种⾮常简单易⽤的⽅式控制原本你需要编写很多代码的进⾏使⽤的服务
* 类。
*
* 类似这样的场景可以想到;
* 1. 你的数据库访问层⾯经常会提供⼀个较为基础的应⽤,以此来减少应⽤服务扩容时不⾄于数据库连
* 接数暴增。
* 2. 使⽤过的⼀些中间件例如;RPC框架,在拿到jar包对接⼝的描述后,中间件会在服务启动的时候⽣
* 成对应的代理类,当调⽤接⼝的时候,实际是通过代理类发出的socket信息进⾏通过。
* 3. 另外像我们常⽤的 MyBatis ,基本是定义接⼝但是不需要写实现类,就可以对 xml 或者⾃定义注
* 解⾥的 sql 语句进⾏增删改查操作。
*
*/
public class Doc {
/**
*
* 从测试结果可以看到,我们打印了SQL语句,这部分语句是从⾃定义注解中获取的; select
* userName from user where id = 100001 ,我们做了简单的适配。在mybatis框架中会交给
* SqlSession 的实现类进⾏逻辑处理返回操作数据库数据
* ⽽这⾥我们的测试结果是⼀个固定的,如果你愿意更加深⼊的研究可以尝试与数据库操作层进⾏关
* 联,让这个框架可以更加完善
*
*/
/**
*
* 关于这部分代理模式的讲解我们采⽤了开发⼀个关于 mybatis-spring 中间件中部分核⼼功能来
* 体现代理模式的强⼤之处,所以涉及到了⼀些关于代理类的创建以及spring中bean的注册这些知
* 识点,可能在平常的业务开发中都是很少⽤到的,但是在中间件开发中确实⾮常常⻅的操作。
* 代理模式除了开发中间件外还可以是对服务的包装,物联⽹组件等等,让复杂的各项服务变为轻量
* 级调⽤、缓存使⽤。你可以理解为你家⾥的电灯开关,我们不能操作220v电线的⼈⾁连接,但是
* 可以使⽤开关,避免触电。
* 代理模式的设计⽅式可以让代码更加整洁、⼲净易于维护,虽然在这部分开发中额外增加了很多类
* 也包括了⾃⼰处理bean的注册等,但是这样的中间件复⽤性极⾼也更加智能,可以⾮常⽅便的扩
* 展到各个服务应⽤中
*
*/
}
| chasesunshine/mjj-test-new-technology | demo-mybatis-plus2/src/main/java/org/wanbang/study/allDesignMode/constructMode/proxyMode/Doc.java | 903 | /**
*
* 关于这部分代理模式的讲解我们采⽤了开发⼀个关于 mybatis-spring 中间件中部分核⼼功能来
* 体现代理模式的强⼤之处,所以涉及到了⼀些关于代理类的创建以及spring中bean的注册这些知
* 识点,可能在平常的业务开发中都是很少⽤到的,但是在中间件开发中确实⾮常常⻅的操作。
* 代理模式除了开发中间件外还可以是对服务的包装,物联⽹组件等等,让复杂的各项服务变为轻量
* 级调⽤、缓存使⽤。你可以理解为你家⾥的电灯开关,我们不能操作220v电线的⼈⾁连接,但是
* 可以使⽤开关,避免触电。
* 代理模式的设计⽅式可以让代码更加整洁、⼲净易于维护,虽然在这部分开发中额外增加了很多类
* 也包括了⾃⼰处理bean的注册等,但是这样的中间件复⽤性极⾼也更加智能,可以⾮常⽅便的扩
* 展到各个服务应⽤中
*
*/ | block_comment | zh-cn | package org.wanbang.study.allDesignMode.constructMode.proxyMode;
/**
* @description: 代理模式
* @author majiajian
* @date 2022/8/17 18:38
* @version 1.0
*/
/**
*
* 代理模式有点像⽼⼤和⼩弟,也有点像分销商。主要解决的是问题是为某些资源的访问、对象的类的易
* ⽤操作上提供⽅便使⽤的代理服务。⽽这种设计思想的模式经常会出现在我们的系统中,或者你⽤到过
* 的组件中,它们都提供给你⼀种⾮常简单易⽤的⽅式控制原本你需要编写很多代码的进⾏使⽤的服务
* 类。
*
* 类似这样的场景可以想到;
* 1. 你的数据库访问层⾯经常会提供⼀个较为基础的应⽤,以此来减少应⽤服务扩容时不⾄于数据库连
* 接数暴增。
* 2. 使⽤过的⼀些中间件例如;RPC框架,在拿到jar包对接⼝的描述后,中间件会在服务启动的时候⽣
* 成对应的代理类,当调⽤接⼝的时候,实际是通过代理类发出的socket信息进⾏通过。
* 3. 另外像我们常⽤的 MyBatis ,基本是定义接⼝但是不需要写实现类,就可以对 xml 或者⾃定义注
* 解⾥的 sql 语句进⾏增删改查操作。
*
*/
public class Doc {
/**
*
* 从测试结果可以看到,我们打印了SQL语句,这部分语句是从⾃定义注解中获取的; select
* userName from user where id = 100001 ,我们做了简单的适配。在mybatis框架中会交给
* SqlSession 的实现类进⾏逻辑处理返回操作数据库数据
* ⽽这⾥我们的测试结果是⼀个固定的,如果你愿意更加深⼊的研究可以尝试与数据库操作层进⾏关
* 联,让这个框架可以更加完善
*
*/
/**
*
* 关于这 <SUF>*/
}
| false | 726 | 262 | 902 | 326 | 728 | 255 | 903 | 326 | 1,314 | 482 | false | false | false | false | false | true |
29391_18 | package com.youjiang.hualuo.utils;
import android.text.format.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* @author ChayChan
* @description: 关于时间的工具类
*/
public class TimeUtils {
public static final long ONE_MINUTE_MILLIONS = 60 * 1000;
public static final long ONE_HOUR_MILLIONS = 60 * ONE_MINUTE_MILLIONS;
public static SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
/**
* 得到剩余天数
*
* @param endTime 结束时间
* @return
*/
public static int getDayLast(String endTime) {
try {
long nowtime = new Date().getTime();
long lastTime = new SimpleDateFormat("yyyy-MM-dd").parse(endTime).getTime();
long distance = lastTime - nowtime;
if (distance <= 0) {
//如果是小于或等于0,则为0
return 0;
}
double rate = distance / (1.0f * 24 * 3600 * 1000);
int day = (int) (rate + 0.5f);
return day;
} catch (ParseException e) {
e.printStackTrace();
return -1;
}
}
/**
* 获取短时间格式
*
* @return
*/
public static String getShortTime(long millis) {
Date date = new Date(millis);
Date curDate = new Date();
String str = "";
long durTime = curDate.getTime() - date.getTime();
int dayStatus = calculateDayStatus(date, new Date());
if (durTime <= 10 * ONE_MINUTE_MILLIONS) {
str = "刚刚";
} else if (durTime < ONE_HOUR_MILLIONS) {
str = durTime / ONE_MINUTE_MILLIONS + "分钟前";
} else if (dayStatus == 0) {
str = durTime / ONE_HOUR_MILLIONS + "小时前";
} else if (dayStatus == -1) {
str = "昨天" + DateFormat.format("HH:mm", date);
} else if (isSameYear(date, curDate) && dayStatus < -1) {
str = DateFormat.format("MM-dd", date).toString();
} else {
str = DateFormat.format("yyyy-MM", date).toString();
}
return str;
}
/**
* 判断是否是同一年
* @param targetTime
* @param compareTime
* @return
*/
public static boolean isSameYear(Date targetTime, Date compareTime) {
Calendar tarCalendar = Calendar.getInstance();
tarCalendar.setTime(targetTime);
int tarYear = tarCalendar.get(Calendar.YEAR);
Calendar compareCalendar = Calendar.getInstance();
compareCalendar.setTime(compareTime);
int comYear = compareCalendar.get(Calendar.YEAR);
return tarYear == comYear;
}
/**
* 判断是否处于今天还是昨天,0表示今天,-1表示昨天,小于-1则是昨天以前
* @param targetTime
* @param compareTime
* @return
*/
public static int calculateDayStatus(Date targetTime, Date compareTime) {
Calendar tarCalendar = Calendar.getInstance();
tarCalendar.setTime(targetTime);
int tarDayOfYear = tarCalendar.get(Calendar.DAY_OF_YEAR);
Calendar compareCalendar = Calendar.getInstance();
compareCalendar.setTime(compareTime);
int comDayOfYear = compareCalendar.get(Calendar.DAY_OF_YEAR);
return tarDayOfYear - comDayOfYear;
}
/**
* 将秒数转换成00:00的字符串,如 118秒 -> 01:58
* @param time
* @return
*/
public static String secToTime(int time) {
String timeStr = null;
int hour = 0;
int minute = 0;
int second = 0;
if (time <= 0)
return "00:00";
else {
minute = time / 60;
if (minute < 60) {
second = time % 60;
timeStr = unitFormat(minute) + ":" + unitFormat(second);
} else {
hour = minute / 60;
if (hour > 99)
return "99:59:59";
minute = minute % 60;
second = time - hour * 3600 - minute * 60;
timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":"
+ unitFormat(second);
}
}
return timeStr;
}
public static String unitFormat(int i) {
String retStr = null;
if (i >= 0 && i < 10)
retStr = "0" + Integer.toString(i);
else
retStr = "" + i;
return retStr;
}
/**
* 获取当前月1号 返回格式yyyy-MM-dd (eg: 2007-06-01)
*
* @return
*/
public static String getMonthBegin() {
String yearMonth = new SimpleDateFormat(
"yyyy-MM").format(new Date());
return yearMonth + "-01";
}
/**
* 与当前时间对比
* @param time
* @return
*/
public static long compareTime(String time) {
long timeLong = 0;
long curTimeLong = 0;
try {
timeLong = sdf.parse(time).getTime();
curTimeLong = sdf.parse(getCurrentTimeString())
.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return curTimeLong - timeLong;// 当前时间减去传入的时间
}
/**
* 返回yyyy-MM-dd HH:mm:ss类型的时间字符串
*/
public static String getCurrentTimeString() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//
.format(new Date());
}
/**
* @param milliseconds 时间值
* @param isDetail 是否需要显示具体时间段 + 时分和星期 + 时分
* @return
*/
public static String getTimeShowString(long milliseconds,boolean isDetail) {
String dataString = "";
String timeStringBy24 = "";
Date currentTime = new Date(milliseconds);
Date today = new Date();
Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR_OF_DAY, 0);
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
Date todaybegin = todayStart.getTime();
Date yesterdaybegin = new Date(todaybegin.getTime() - 3600 * 24 * 1000);
Date preyesterday = new Date(
yesterdaybegin.getTime() - 3600 * 24 * 1000);
if (!currentTime.before(todaybegin)) {
dataString = "今天";
} else if (!currentTime.before(yesterdaybegin)) {
dataString = "昨天";
} else if (!currentTime.before(preyesterday)) {
dataString = "前天";
} else if (isSameWeekDates(currentTime, today)) {
dataString = getWeekOfDate(currentTime);
} else {
SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd",
Locale.getDefault());
dataString = dateformatter.format(currentTime);
}
SimpleDateFormat timeformatter24 = new SimpleDateFormat("HH:mm",
Locale.getDefault());
timeStringBy24 = timeformatter24.format(currentTime);
if (isDetail) {//显示具体的时间
//在聊天界面显示时间,如果是今天则显示当前时间段加上时和分 如上午 9:58
if (!currentTime.before(todaybegin)) {//如果是今天
return getTodayTimeBucket(currentTime);//根据时间段分为凌晨 上午 下午等
} else {
return dataString + " " + timeStringBy24;//如果是昨天 则是 昨天 9:58 如果是同在一个星期,前天之前的时间则显示 星期一 9:58
}
}else{
//在会话记录界面不需要展示很具体的时间
if (!currentTime.before(todaybegin)) {//如果是今天
return timeStringBy24;//直接返回时和分 如 9:58
}else{
return dataString;//如果不是今天,不需要展示时和分 如 昨天 前天 星期一
}
}
}
/**
* 判断两个日期是否在同一周
*
* @param date1
* @param date2
* @return
*/
public static boolean isSameWeekDates(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
if (0 == subYear) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2
.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2
.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2
.get(Calendar.WEEK_OF_YEAR))
return true;
}
return false;
}
/**
* 根据日期获得星期
*
* @param date
* @return
*/
public static String getWeekOfDate(Date date) {
String[] weekDaysName = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五",
"星期六" };
// String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" };
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return weekDaysName[intWeek];
}
/**
* 根据不同时间段,显示不同时间
*
* @param date
* @return
*/
public static String getTodayTimeBucket(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
SimpleDateFormat timeformatter0to11 = new SimpleDateFormat("KK:mm",
Locale.getDefault());
SimpleDateFormat timeformatter1to12 = new SimpleDateFormat("hh:mm",
Locale.getDefault());
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour >= 0 && hour < 5) {
return "凌晨 " + timeformatter0to11.format(date);
} else if (hour >= 5 && hour < 12) {
return "上午 " + timeformatter0to11.format(date);
} else if (hour >= 12 && hour < 18) {
return "下午 " + timeformatter1to12.format(date);
} else if (hour >= 18 && hour < 24) {
return "晚上 " + timeformatter1to12.format(date);
}
return "";
}
/**
* 获取当前时间 yyyy-MM-dd格式
*
* @return
*/
public static String getCurrentTimeYMD() {
return new SimpleDateFormat("yyyy-MM-dd")//
.format(new Date());
}
/**
* 将yyyy-MM-dd的字符串转换成Date对象
*/
public static Date getDateByYMD(String time) {
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
| chaychan/BlogFileResource | utils/TimeUtils.java | 2,915 | //如果是今天 | line_comment | zh-cn | package com.youjiang.hualuo.utils;
import android.text.format.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* @author ChayChan
* @description: 关于时间的工具类
*/
public class TimeUtils {
public static final long ONE_MINUTE_MILLIONS = 60 * 1000;
public static final long ONE_HOUR_MILLIONS = 60 * ONE_MINUTE_MILLIONS;
public static SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
/**
* 得到剩余天数
*
* @param endTime 结束时间
* @return
*/
public static int getDayLast(String endTime) {
try {
long nowtime = new Date().getTime();
long lastTime = new SimpleDateFormat("yyyy-MM-dd").parse(endTime).getTime();
long distance = lastTime - nowtime;
if (distance <= 0) {
//如果是小于或等于0,则为0
return 0;
}
double rate = distance / (1.0f * 24 * 3600 * 1000);
int day = (int) (rate + 0.5f);
return day;
} catch (ParseException e) {
e.printStackTrace();
return -1;
}
}
/**
* 获取短时间格式
*
* @return
*/
public static String getShortTime(long millis) {
Date date = new Date(millis);
Date curDate = new Date();
String str = "";
long durTime = curDate.getTime() - date.getTime();
int dayStatus = calculateDayStatus(date, new Date());
if (durTime <= 10 * ONE_MINUTE_MILLIONS) {
str = "刚刚";
} else if (durTime < ONE_HOUR_MILLIONS) {
str = durTime / ONE_MINUTE_MILLIONS + "分钟前";
} else if (dayStatus == 0) {
str = durTime / ONE_HOUR_MILLIONS + "小时前";
} else if (dayStatus == -1) {
str = "昨天" + DateFormat.format("HH:mm", date);
} else if (isSameYear(date, curDate) && dayStatus < -1) {
str = DateFormat.format("MM-dd", date).toString();
} else {
str = DateFormat.format("yyyy-MM", date).toString();
}
return str;
}
/**
* 判断是否是同一年
* @param targetTime
* @param compareTime
* @return
*/
public static boolean isSameYear(Date targetTime, Date compareTime) {
Calendar tarCalendar = Calendar.getInstance();
tarCalendar.setTime(targetTime);
int tarYear = tarCalendar.get(Calendar.YEAR);
Calendar compareCalendar = Calendar.getInstance();
compareCalendar.setTime(compareTime);
int comYear = compareCalendar.get(Calendar.YEAR);
return tarYear == comYear;
}
/**
* 判断是否处于今天还是昨天,0表示今天,-1表示昨天,小于-1则是昨天以前
* @param targetTime
* @param compareTime
* @return
*/
public static int calculateDayStatus(Date targetTime, Date compareTime) {
Calendar tarCalendar = Calendar.getInstance();
tarCalendar.setTime(targetTime);
int tarDayOfYear = tarCalendar.get(Calendar.DAY_OF_YEAR);
Calendar compareCalendar = Calendar.getInstance();
compareCalendar.setTime(compareTime);
int comDayOfYear = compareCalendar.get(Calendar.DAY_OF_YEAR);
return tarDayOfYear - comDayOfYear;
}
/**
* 将秒数转换成00:00的字符串,如 118秒 -> 01:58
* @param time
* @return
*/
public static String secToTime(int time) {
String timeStr = null;
int hour = 0;
int minute = 0;
int second = 0;
if (time <= 0)
return "00:00";
else {
minute = time / 60;
if (minute < 60) {
second = time % 60;
timeStr = unitFormat(minute) + ":" + unitFormat(second);
} else {
hour = minute / 60;
if (hour > 99)
return "99:59:59";
minute = minute % 60;
second = time - hour * 3600 - minute * 60;
timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":"
+ unitFormat(second);
}
}
return timeStr;
}
public static String unitFormat(int i) {
String retStr = null;
if (i >= 0 && i < 10)
retStr = "0" + Integer.toString(i);
else
retStr = "" + i;
return retStr;
}
/**
* 获取当前月1号 返回格式yyyy-MM-dd (eg: 2007-06-01)
*
* @return
*/
public static String getMonthBegin() {
String yearMonth = new SimpleDateFormat(
"yyyy-MM").format(new Date());
return yearMonth + "-01";
}
/**
* 与当前时间对比
* @param time
* @return
*/
public static long compareTime(String time) {
long timeLong = 0;
long curTimeLong = 0;
try {
timeLong = sdf.parse(time).getTime();
curTimeLong = sdf.parse(getCurrentTimeString())
.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
return curTimeLong - timeLong;// 当前时间减去传入的时间
}
/**
* 返回yyyy-MM-dd HH:mm:ss类型的时间字符串
*/
public static String getCurrentTimeString() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//
.format(new Date());
}
/**
* @param milliseconds 时间值
* @param isDetail 是否需要显示具体时间段 + 时分和星期 + 时分
* @return
*/
public static String getTimeShowString(long milliseconds,boolean isDetail) {
String dataString = "";
String timeStringBy24 = "";
Date currentTime = new Date(milliseconds);
Date today = new Date();
Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR_OF_DAY, 0);
todayStart.set(Calendar.MINUTE, 0);
todayStart.set(Calendar.SECOND, 0);
todayStart.set(Calendar.MILLISECOND, 0);
Date todaybegin = todayStart.getTime();
Date yesterdaybegin = new Date(todaybegin.getTime() - 3600 * 24 * 1000);
Date preyesterday = new Date(
yesterdaybegin.getTime() - 3600 * 24 * 1000);
if (!currentTime.before(todaybegin)) {
dataString = "今天";
} else if (!currentTime.before(yesterdaybegin)) {
dataString = "昨天";
} else if (!currentTime.before(preyesterday)) {
dataString = "前天";
} else if (isSameWeekDates(currentTime, today)) {
dataString = getWeekOfDate(currentTime);
} else {
SimpleDateFormat dateformatter = new SimpleDateFormat("yyyy-MM-dd",
Locale.getDefault());
dataString = dateformatter.format(currentTime);
}
SimpleDateFormat timeformatter24 = new SimpleDateFormat("HH:mm",
Locale.getDefault());
timeStringBy24 = timeformatter24.format(currentTime);
if (isDetail) {//显示具体的时间
//在聊天界面显示时间,如果是今天则显示当前时间段加上时和分 如上午 9:58
if (!currentTime.before(todaybegin)) {//如果是今天
return getTodayTimeBucket(currentTime);//根据时间段分为凌晨 上午 下午等
} else {
return dataString + " " + timeStringBy24;//如果是昨天 则是 昨天 9:58 如果是同在一个星期,前天之前的时间则显示 星期一 9:58
}
}else{
//在会话记录界面不需要展示很具体的时间
if (!currentTime.before(todaybegin)) {//如果 <SUF>
return timeStringBy24;//直接返回时和分 如 9:58
}else{
return dataString;//如果不是今天,不需要展示时和分 如 昨天 前天 星期一
}
}
}
/**
* 判断两个日期是否在同一周
*
* @param date1
* @param date2
* @return
*/
public static boolean isSameWeekDates(Date date1, Date date2) {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
int subYear = cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR);
if (0 == subYear) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2
.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (1 == subYear && 11 == cal2.get(Calendar.MONTH)) {
// 如果12月的最后一周横跨来年第一周的话则最后一周即算做来年的第一周
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2
.get(Calendar.WEEK_OF_YEAR))
return true;
} else if (-1 == subYear && 11 == cal1.get(Calendar.MONTH)) {
if (cal1.get(Calendar.WEEK_OF_YEAR) == cal2
.get(Calendar.WEEK_OF_YEAR))
return true;
}
return false;
}
/**
* 根据日期获得星期
*
* @param date
* @return
*/
public static String getWeekOfDate(Date date) {
String[] weekDaysName = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五",
"星期六" };
// String[] weekDaysCode = { "0", "1", "2", "3", "4", "5", "6" };
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int intWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
return weekDaysName[intWeek];
}
/**
* 根据不同时间段,显示不同时间
*
* @param date
* @return
*/
public static String getTodayTimeBucket(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
SimpleDateFormat timeformatter0to11 = new SimpleDateFormat("KK:mm",
Locale.getDefault());
SimpleDateFormat timeformatter1to12 = new SimpleDateFormat("hh:mm",
Locale.getDefault());
int hour = calendar.get(Calendar.HOUR_OF_DAY);
if (hour >= 0 && hour < 5) {
return "凌晨 " + timeformatter0to11.format(date);
} else if (hour >= 5 && hour < 12) {
return "上午 " + timeformatter0to11.format(date);
} else if (hour >= 12 && hour < 18) {
return "下午 " + timeformatter1to12.format(date);
} else if (hour >= 18 && hour < 24) {
return "晚上 " + timeformatter1to12.format(date);
}
return "";
}
/**
* 获取当前时间 yyyy-MM-dd格式
*
* @return
*/
public static String getCurrentTimeYMD() {
return new SimpleDateFormat("yyyy-MM-dd")//
.format(new Date());
}
/**
* 将yyyy-MM-dd的字符串转换成Date对象
*/
public static Date getDateByYMD(String time) {
Date date = null;
try {
date = new SimpleDateFormat("yyyy-MM-dd").parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
| false | 2,670 | 3 | 2,915 | 4 | 3,117 | 3 | 2,915 | 4 | 3,622 | 6 | false | false | false | false | false | true |
14745_1 | package com.chaychan.news.presenter;
import com.chaychan.news.model.entity.News;
import com.chaychan.news.model.entity.NewsData;
import com.chaychan.news.model.response.NewsResponse;
import com.chaychan.news.base.BasePresenter;
import com.chaychan.news.utils.ListUtils;
import com.chaychan.news.utils.PreUtils;
import com.chaychan.news.presenter.view.lNewsListView;
import com.google.gson.Gson;
import com.socks.library.KLog;
import java.util.ArrayList;
import java.util.List;
import rx.Subscriber;
/**
* @author ChayChan
* @description: 新闻列表的presenter
* @date 2017/6/18 10:04
*/
public class NewsListPresenter extends BasePresenter<lNewsListView> {
private long lastTime;
public NewsListPresenter(lNewsListView view) {
super(view);
}
public void getNewsList(String channelCode){
lastTime = PreUtils.getLong(channelCode,0);//读取对应频道下最后一次刷新的时间戳
if (lastTime == 0){
//如果为空,则是从来没有刷新过,使用当前时间戳
lastTime = System.currentTimeMillis() / 1000;
}
addSubscription(mApiService.getNewsList(channelCode,lastTime,System.currentTimeMillis()/1000), new Subscriber<NewsResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
KLog.e(e.getLocalizedMessage());
mView.onError();
}
@Override
public void onNext(NewsResponse response) {
lastTime = System.currentTimeMillis() / 1000;
PreUtils.putLong(channelCode,lastTime);//保存刷新的时间戳
List<NewsData> data = response.data;
List<News> newsList = new ArrayList<>();
if (!ListUtils.isEmpty(data)){
for (NewsData newsData : data) {
News news = new Gson().fromJson(newsData.content, News.class);
newsList.add(news);
}
}
KLog.e(newsList);
mView.onGetNewsListSuccess(newsList,response.tips.display_info);
}
});
}
}
| chaychan/TouTiao | app/src/main/java/com/chaychan/news/presenter/NewsListPresenter.java | 573 | //读取对应频道下最后一次刷新的时间戳 | line_comment | zh-cn | package com.chaychan.news.presenter;
import com.chaychan.news.model.entity.News;
import com.chaychan.news.model.entity.NewsData;
import com.chaychan.news.model.response.NewsResponse;
import com.chaychan.news.base.BasePresenter;
import com.chaychan.news.utils.ListUtils;
import com.chaychan.news.utils.PreUtils;
import com.chaychan.news.presenter.view.lNewsListView;
import com.google.gson.Gson;
import com.socks.library.KLog;
import java.util.ArrayList;
import java.util.List;
import rx.Subscriber;
/**
* @author ChayChan
* @description: 新闻列表的presenter
* @date 2017/6/18 10:04
*/
public class NewsListPresenter extends BasePresenter<lNewsListView> {
private long lastTime;
public NewsListPresenter(lNewsListView view) {
super(view);
}
public void getNewsList(String channelCode){
lastTime = PreUtils.getLong(channelCode,0);//读取 <SUF>
if (lastTime == 0){
//如果为空,则是从来没有刷新过,使用当前时间戳
lastTime = System.currentTimeMillis() / 1000;
}
addSubscription(mApiService.getNewsList(channelCode,lastTime,System.currentTimeMillis()/1000), new Subscriber<NewsResponse>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
KLog.e(e.getLocalizedMessage());
mView.onError();
}
@Override
public void onNext(NewsResponse response) {
lastTime = System.currentTimeMillis() / 1000;
PreUtils.putLong(channelCode,lastTime);//保存刷新的时间戳
List<NewsData> data = response.data;
List<News> newsList = new ArrayList<>();
if (!ListUtils.isEmpty(data)){
for (NewsData newsData : data) {
News news = new Gson().fromJson(newsData.content, News.class);
newsList.add(news);
}
}
KLog.e(newsList);
mView.onGetNewsListSuccess(newsList,response.tips.display_info);
}
});
}
}
| false | 465 | 10 | 573 | 13 | 583 | 11 | 573 | 13 | 692 | 26 | false | false | false | false | false | true |
22054_79 | package dp;
// 机器人达到指定位置方法数
//【题目】假设有排成一行的N个位置,记为1~N,N一定大于或等于2。
// 开始时机器人在其中的M位置上(M一定是1~N中的一个),机器人可以往左走或者往右走,如果机器人来到1位置,
// 那么下一步只能往右来到2位置;如果机器人来到N位置,那么下一步只能往左来到N-1位置。
// 规定机器人必须走K步,最终能来到P位置(P也一定是1~N中的一个)的方法有多少种。
// 给定四个参数N、M、K、P,返回方法数。
// 【举例】N=5,M=2,K=3,P=3上面的参数代表所有位置为 1 2 3 4 5。
// 机器人最开始在2位置上,必须经过3步,最后到达3位置。
// 走的方法只有如下3种:1)从2到1,从1到2,从2到32)从2到3,从3到2,从2到33)从2到3,从3到4,从4到3所以返回方法数3。
// N=3,M=1,K=3,P=3上面的参数代表所有位置为 1 2 3。
// 机器人最开始在1位置上,必须经过3步,最后到达3位置。怎么走也不可能,所以返回方法数 0。
public class C01_RobotWalk {
// public static int ways1(int N, int M, int K, int P) {
// // NOTE:参数无效直接返回0, 题目有保证有效,不用写
// if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
// return 0;
// }
// // 总共N个位置,从M点出发,还剩K步,返回最终能达到P的方法数
// return walk(N, M, K, P);
// }
// // N : 位置为1 ~ N,固定参数
// // cur : 当前在cur位置,可变参数
// // rest : 还剩res步没有走,可变参数
// // P : 最终目标位置是P,固定参数
// // 该函数的含义:只能在1~N这些位置上移动,当前在cur位置,走完rest步之后,停在P位置的方法数作为返回值返回
// public static int walk(int N, int cur, int rest, int P) {
// // 如果没有剩余步数了,当前的cur位置就是最后的位置
// // 如果最后的位置停在P上,那么之前做的移动是有效的
// // 如果最后的位置没在P上,那么之前做的移动是无效的
// if (rest == 0) {
// return cur == P ? 1 : 0;
// }
// // 如果还有rest步要走,而当前的cur位置在1位置上,那么当前这步只能从1走向2
// // 后续的过程就是,来到2位置上,还剩rest-1步要走
// if (cur == 1) {
// return walk(N, 2, rest - 1, P);
// }
// // 如果还有rest步要走,而当前的cur位置在N位置上,那么当前这步只能从N走向N-1
// // 后续的过程就是,来到N-1位置上,还剩rest-1步要走
// if (cur == N) {
// return walk(N, N - 1, rest - 1, P);
// }
// // 如果还有rest步要走,而当前的cur位置在中间位置上,那么当前这步可以走向左,也可以走向右
// // 走向左之后,后续的过程就是,来到cur-1位置上,还剩rest-1步要走
// // 走向右之后,后续的过程就是,来到cur+1位置上,还剩rest-1步要走
// // 走向左、走向右是截然不同的方法,所以总方法数要都算上
// return walk(N, cur + 1, rest - 1, P) + walk(N, cur - 1, rest - 1, P);
// }
// public static int ways2(int N, int M, int K, int P) {
// // 参数无效直接返回0
// if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
// return 0;
// }
// int[][] dp = new int[K + 1][N + 1];
// dp[0][P] = 1;
// for (int i = 1; i <= K; i++) {
// for (int j = 1; j <= N; j++) {
// if (j == 1) {
// dp[i][j] = dp[i - 1][2];
// } else if (j == N) {
// dp[i][j] = dp[i - 1][N - 1];
// } else {
// dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1];
// }
// }
// }
// return dp[K][M];
// }
// public static int ways4(int N, int M, int K, int P) {
// // 参数无效直接返回0
// if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
// return 0;
// }
// int[] dp = new int[N + 1];
// dp[P] = 1;
// for (int i = 1; i <= K; i++) {
// int leftUp = dp[1];// 左上角的值
// for (int j = 1; j <= N; j++) {
// int tmp = dp[j];
// if (j == 1) {
// dp[j] = dp[j + 1];
// } else if (j == N) {
// dp[j] = leftUp;
// } else {
// dp[j] = leftUp + dp[j + 1];
// }
// leftUp = tmp;
// }
// }
// return dp[M];
// }
// 暴力递归
public static int ways1(int N, int pos, int rest, int target) {
if (rest == 0) {
return pos == target ? 1 : 0;
}
if (pos == 1) {
return ways1(N, 2, rest - 1, target);
}
if (pos == N) {
return ways1(N, N - 1, rest - 1, target);
}
return ways1(N, pos - 1, rest - 1, target) + ways1(N, pos + 1, rest - 1, target);
}
// 记忆化搜索
public static int ways2(int N, int M, int K, int P) {
int[][] cache = new int[N + 1][K + 1];
for (int i = 0; i < N + 1; i++) {
for (int j = 0; j < K + 1; j++) {
cache[i][j] = -1;
}
}
// 边界条件题目有保证不越界
return process(N, M, K, P, cache);
}
private static int process(int N, int pos, int rest, int target, int[][] cache) {
if (cache[pos][rest] != -1) {
return cache[pos][rest];
}
if (rest == 0) {
cache[pos][rest] = pos == target ? 1 : 0;
} else if (pos == 1) {
cache[pos][rest] = process(N, 2, rest - 1, target, cache);
} else if (pos == N) {
cache[pos][rest] = process(N, N - 1, rest - 1, target, cache);
} else {
cache[pos][rest] = process(N, pos - 1, rest - 1, target, cache) + process(N, pos + 1, rest - 1, target, cache);
}
return cache[pos][rest];
}
// 严格表结构@1
public static int ways3(int N, int M, int K, int P) {
int[][] cache = new int[K + 1][N + 1];
cache[0][P] = 1;
for (int i = 1; i < cache.length; i++) {
for (int j = 1; j < cache[i].length; j++) {
if (j == 1) {
cache[i][j] = cache[i - 1][j + 1];
} else if (j == cache[i].length - 1) {
cache[i][j] = cache[i - 1][j - 1];
} else {
cache[i][j] = cache[i - 1][j - 1] + cache[i - 1][j + 1];
}
}
}
return cache[K][M];
}
// 严格表结构@2
// NOTE:每个各自只与上行的左侧格子和右侧格子有关,可以只缓存上一行的值和上一个左侧格子的值(因为算到当前格子时上行左侧的格子值已经被覆盖了)
public static int ways4(int N, int M, int K, int P) {
int[] cache = new int[N + 1];
int leftUpCache;
cache[P] = 1;
for (int i = 1; i < K + 1; i++) {
leftUpCache = cache[1];
for (int j = 1; j < cache.length; j++) {
int tem = cache[j];
if (j == 1) {
cache[j] = cache[j + 1];
} else if (j == cache.length - 1) {
cache[j] = leftUpCache;
} else {
cache[j] = leftUpCache + cache[j + 1];
}
leftUpCache = tem;
}
}
return cache[M];
}
public static void main(String[] args) {
System.out.println(ways1(7, 4, 9, 5));
System.out.println(ways2(7, 4, 9, 5));
System.out.println(ways3(7, 4, 9, 5));
System.out.println(ways4(7, 4, 9, 5));
}
}
| cheapCoder/zuoshen-algorithm | dp/C01_RobotWalk.java | 2,782 | // NOTE:每个各自只与上行的左侧格子和右侧格子有关,可以只缓存上一行的值和上一个左侧格子的值(因为算到当前格子时上行左侧的格子值已经被覆盖了) | line_comment | zh-cn | package dp;
// 机器人达到指定位置方法数
//【题目】假设有排成一行的N个位置,记为1~N,N一定大于或等于2。
// 开始时机器人在其中的M位置上(M一定是1~N中的一个),机器人可以往左走或者往右走,如果机器人来到1位置,
// 那么下一步只能往右来到2位置;如果机器人来到N位置,那么下一步只能往左来到N-1位置。
// 规定机器人必须走K步,最终能来到P位置(P也一定是1~N中的一个)的方法有多少种。
// 给定四个参数N、M、K、P,返回方法数。
// 【举例】N=5,M=2,K=3,P=3上面的参数代表所有位置为 1 2 3 4 5。
// 机器人最开始在2位置上,必须经过3步,最后到达3位置。
// 走的方法只有如下3种:1)从2到1,从1到2,从2到32)从2到3,从3到2,从2到33)从2到3,从3到4,从4到3所以返回方法数3。
// N=3,M=1,K=3,P=3上面的参数代表所有位置为 1 2 3。
// 机器人最开始在1位置上,必须经过3步,最后到达3位置。怎么走也不可能,所以返回方法数 0。
public class C01_RobotWalk {
// public static int ways1(int N, int M, int K, int P) {
// // NOTE:参数无效直接返回0, 题目有保证有效,不用写
// if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
// return 0;
// }
// // 总共N个位置,从M点出发,还剩K步,返回最终能达到P的方法数
// return walk(N, M, K, P);
// }
// // N : 位置为1 ~ N,固定参数
// // cur : 当前在cur位置,可变参数
// // rest : 还剩res步没有走,可变参数
// // P : 最终目标位置是P,固定参数
// // 该函数的含义:只能在1~N这些位置上移动,当前在cur位置,走完rest步之后,停在P位置的方法数作为返回值返回
// public static int walk(int N, int cur, int rest, int P) {
// // 如果没有剩余步数了,当前的cur位置就是最后的位置
// // 如果最后的位置停在P上,那么之前做的移动是有效的
// // 如果最后的位置没在P上,那么之前做的移动是无效的
// if (rest == 0) {
// return cur == P ? 1 : 0;
// }
// // 如果还有rest步要走,而当前的cur位置在1位置上,那么当前这步只能从1走向2
// // 后续的过程就是,来到2位置上,还剩rest-1步要走
// if (cur == 1) {
// return walk(N, 2, rest - 1, P);
// }
// // 如果还有rest步要走,而当前的cur位置在N位置上,那么当前这步只能从N走向N-1
// // 后续的过程就是,来到N-1位置上,还剩rest-1步要走
// if (cur == N) {
// return walk(N, N - 1, rest - 1, P);
// }
// // 如果还有rest步要走,而当前的cur位置在中间位置上,那么当前这步可以走向左,也可以走向右
// // 走向左之后,后续的过程就是,来到cur-1位置上,还剩rest-1步要走
// // 走向右之后,后续的过程就是,来到cur+1位置上,还剩rest-1步要走
// // 走向左、走向右是截然不同的方法,所以总方法数要都算上
// return walk(N, cur + 1, rest - 1, P) + walk(N, cur - 1, rest - 1, P);
// }
// public static int ways2(int N, int M, int K, int P) {
// // 参数无效直接返回0
// if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
// return 0;
// }
// int[][] dp = new int[K + 1][N + 1];
// dp[0][P] = 1;
// for (int i = 1; i <= K; i++) {
// for (int j = 1; j <= N; j++) {
// if (j == 1) {
// dp[i][j] = dp[i - 1][2];
// } else if (j == N) {
// dp[i][j] = dp[i - 1][N - 1];
// } else {
// dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1];
// }
// }
// }
// return dp[K][M];
// }
// public static int ways4(int N, int M, int K, int P) {
// // 参数无效直接返回0
// if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
// return 0;
// }
// int[] dp = new int[N + 1];
// dp[P] = 1;
// for (int i = 1; i <= K; i++) {
// int leftUp = dp[1];// 左上角的值
// for (int j = 1; j <= N; j++) {
// int tmp = dp[j];
// if (j == 1) {
// dp[j] = dp[j + 1];
// } else if (j == N) {
// dp[j] = leftUp;
// } else {
// dp[j] = leftUp + dp[j + 1];
// }
// leftUp = tmp;
// }
// }
// return dp[M];
// }
// 暴力递归
public static int ways1(int N, int pos, int rest, int target) {
if (rest == 0) {
return pos == target ? 1 : 0;
}
if (pos == 1) {
return ways1(N, 2, rest - 1, target);
}
if (pos == N) {
return ways1(N, N - 1, rest - 1, target);
}
return ways1(N, pos - 1, rest - 1, target) + ways1(N, pos + 1, rest - 1, target);
}
// 记忆化搜索
public static int ways2(int N, int M, int K, int P) {
int[][] cache = new int[N + 1][K + 1];
for (int i = 0; i < N + 1; i++) {
for (int j = 0; j < K + 1; j++) {
cache[i][j] = -1;
}
}
// 边界条件题目有保证不越界
return process(N, M, K, P, cache);
}
private static int process(int N, int pos, int rest, int target, int[][] cache) {
if (cache[pos][rest] != -1) {
return cache[pos][rest];
}
if (rest == 0) {
cache[pos][rest] = pos == target ? 1 : 0;
} else if (pos == 1) {
cache[pos][rest] = process(N, 2, rest - 1, target, cache);
} else if (pos == N) {
cache[pos][rest] = process(N, N - 1, rest - 1, target, cache);
} else {
cache[pos][rest] = process(N, pos - 1, rest - 1, target, cache) + process(N, pos + 1, rest - 1, target, cache);
}
return cache[pos][rest];
}
// 严格表结构@1
public static int ways3(int N, int M, int K, int P) {
int[][] cache = new int[K + 1][N + 1];
cache[0][P] = 1;
for (int i = 1; i < cache.length; i++) {
for (int j = 1; j < cache[i].length; j++) {
if (j == 1) {
cache[i][j] = cache[i - 1][j + 1];
} else if (j == cache[i].length - 1) {
cache[i][j] = cache[i - 1][j - 1];
} else {
cache[i][j] = cache[i - 1][j - 1] + cache[i - 1][j + 1];
}
}
}
return cache[K][M];
}
// 严格表结构@2
// NO <SUF>
public static int ways4(int N, int M, int K, int P) {
int[] cache = new int[N + 1];
int leftUpCache;
cache[P] = 1;
for (int i = 1; i < K + 1; i++) {
leftUpCache = cache[1];
for (int j = 1; j < cache.length; j++) {
int tem = cache[j];
if (j == 1) {
cache[j] = cache[j + 1];
} else if (j == cache.length - 1) {
cache[j] = leftUpCache;
} else {
cache[j] = leftUpCache + cache[j + 1];
}
leftUpCache = tem;
}
}
return cache[M];
}
public static void main(String[] args) {
System.out.println(ways1(7, 4, 9, 5));
System.out.println(ways2(7, 4, 9, 5));
System.out.println(ways3(7, 4, 9, 5));
System.out.println(ways4(7, 4, 9, 5));
}
}
| false | 2,484 | 54 | 2,782 | 59 | 2,669 | 46 | 2,782 | 59 | 3,343 | 86 | false | false | false | false | false | true |
48785_5 | package com.xiangxue.ch02;
import java.util.LinkedList;
import java.util.List;
/**
*/
public class StopWorld {
/*不停往list中填充数据 业务线程*/
public static class FillListThread extends Thread{
List<byte[]> list = new LinkedList<>();
//模拟业务不断填充数据局
@Override
public void run() {
try {
while(true){
if(list.size()*512/1024/1024>=990){ //数据达到一定,进行清理
list.clear();
System.out.println("list is clear");
}
byte[] bl;
for(int i=0;i<100;i++){
bl = new byte[512]; //填充数据
list.add(bl); //填充数据
}
Thread.sleep(1);
}
} catch (Exception e) {
}
}
}
/*每100ms定时打印*/
public static class TimerThread extends Thread{
public final static long startTime = System.currentTimeMillis();
@Override
public void run() {
try {
while(true){
long t = System.currentTimeMillis()-startTime;
System.out.println(t/1000+"."+t%1000); //每个一段时间打印一下业务执行时间
Thread.sleep(100); //0.1秒 0.1 -0.2 -0.3
}
} catch (Exception e) {
}
}
}
public static void main(String[] args) {
FillListThread myThread = new FillListThread(); //业务线程
TimerThread timerThread = new TimerThread(); //打印时间线程(0.1秒打印一次)
myThread.start();
timerThread.start();
}
}
| checkming/AndroidAdvancedNotes | Java/ch02/ch02/StopWorld.java | 427 | /*每100ms定时打印*/ | block_comment | zh-cn | package com.xiangxue.ch02;
import java.util.LinkedList;
import java.util.List;
/**
*/
public class StopWorld {
/*不停往list中填充数据 业务线程*/
public static class FillListThread extends Thread{
List<byte[]> list = new LinkedList<>();
//模拟业务不断填充数据局
@Override
public void run() {
try {
while(true){
if(list.size()*512/1024/1024>=990){ //数据达到一定,进行清理
list.clear();
System.out.println("list is clear");
}
byte[] bl;
for(int i=0;i<100;i++){
bl = new byte[512]; //填充数据
list.add(bl); //填充数据
}
Thread.sleep(1);
}
} catch (Exception e) {
}
}
}
/*每10 <SUF>*/
public static class TimerThread extends Thread{
public final static long startTime = System.currentTimeMillis();
@Override
public void run() {
try {
while(true){
long t = System.currentTimeMillis()-startTime;
System.out.println(t/1000+"."+t%1000); //每个一段时间打印一下业务执行时间
Thread.sleep(100); //0.1秒 0.1 -0.2 -0.3
}
} catch (Exception e) {
}
}
}
public static void main(String[] args) {
FillListThread myThread = new FillListThread(); //业务线程
TimerThread timerThread = new TimerThread(); //打印时间线程(0.1秒打印一次)
myThread.start();
timerThread.start();
}
}
| false | 389 | 9 | 427 | 9 | 456 | 9 | 427 | 9 | 567 | 13 | false | false | false | false | false | true |
33797_0 | package algorithm.dp;
/**
* 动态规划
* 爬楼梯问题展示了如何通过子问题分解来求解原问题的。实际上,子问题分解是一种通用的算法思路,在分治、动态规划、回溯中的侧重点不同。
* 1.分治算法递归地将原问题划分为多个相互独立的子问题,直至最小子问题,并在回溯中合并子问题的解,最终得到原问题的解。
* <p>
* 2.动态规划也对问题进行递归分解,但与分治算法的主要区别是,动态规划中的子问题是相互依赖的,在分解过程中会出现许多重叠子问题。
* <p>
* 3.回溯算法在尝试和回退中穷举所有可能的解,并通过剪枝避免不必要的搜索分支。原问题的解由一系列决策步骤构成,我们可以将每个决策步骤之前的子序列看作一个子问题。
* <p>
* 实际上,动态规划常用来求解最优化问题,它们不仅包含重叠子问题,还具有另外两大特性:最优子结构、无后效性。
* <p>
* 最优子结构: 原问题的最优解是从子问题的最优解构建得来的。
* 无后效性: 给定一个确定的状 * 无后效性: 给定一个确定的状态,它的未来发展只与当前状态有关,而与过去经历的所有状态无关。
态,它的未来发展只与当前状态有关,而与过去经历的所有状态无关。
*
* 关键点:
* 1.状态转移方程+目标因素+DP定义
* 2. 虽然求的是目标容量cap,其实是计算了0->cap所有容量最大价值
* 3. 换个问法,转换成计算0->cap所有目标极值,并通过i/j 进行二维填表来辅助理解(类似回溯公式)
* 4. 注意边界条件(边界和状态转移方程是配套的)
*
* @author: east
* @date: 2024/1/10
*/
public class Dp {
}
| cheedonghu/JavaDemo | src/algorithm/dp/Dp.java | 569 | /**
* 动态规划
* 爬楼梯问题展示了如何通过子问题分解来求解原问题的。实际上,子问题分解是一种通用的算法思路,在分治、动态规划、回溯中的侧重点不同。
* 1.分治算法递归地将原问题划分为多个相互独立的子问题,直至最小子问题,并在回溯中合并子问题的解,最终得到原问题的解。
* <p>
* 2.动态规划也对问题进行递归分解,但与分治算法的主要区别是,动态规划中的子问题是相互依赖的,在分解过程中会出现许多重叠子问题。
* <p>
* 3.回溯算法在尝试和回退中穷举所有可能的解,并通过剪枝避免不必要的搜索分支。原问题的解由一系列决策步骤构成,我们可以将每个决策步骤之前的子序列看作一个子问题。
* <p>
* 实际上,动态规划常用来求解最优化问题,它们不仅包含重叠子问题,还具有另外两大特性:最优子结构、无后效性。
* <p>
* 最优子结构: 原问题的最优解是从子问题的最优解构建得来的。
* 无后效性: 给定一个确定的状 * 无后效性: 给定一个确定的状态,它的未来发展只与当前状态有关,而与过去经历的所有状态无关。
态,它的未来发展只与当前状态有关,而与过去经历的所有状态无关。
*
* 关键点:
* 1.状态转移方程+目标因素+DP定义
* 2. 虽然求的是目标容量cap,其实是计算了0->cap所有容量最大价值
* 3. 换个问法,转换成计算0->cap所有目标极值,并通过i/j 进行二维填表来辅助理解(类似回溯公式)
* 4. 注意边界条件(边界和状态转移方程是配套的)
*
* @author: east
* @date: 2024/1/10
*/ | block_comment | zh-cn | package algorithm.dp;
/**
* 动态规 <SUF>*/
public class Dp {
}
| false | 464 | 454 | 569 | 552 | 475 | 461 | 569 | 552 | 827 | 809 | true | true | true | true | true | false |
16207_4 | package com.gis.wx.model;
public class WechatUser{
private String openid; //用户的唯一标识
private String nickname;//用户昵称
private Integer sex;// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
private String province;//用户个人资料填写的省份
private String city;//普通用户个人资料填写的城市
private String country;// 国家,如中国为CN
private String headimgurl; // 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
private String[] privilege;// 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
private String unionid;// 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。详见:获取用户个人信息(UnionID机制)
private String access_token;
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeadimgurl() {
return headimgurl;
}
public void setHeadimgurl(String headimgurl) {
this.headimgurl = headimgurl;
}
public String[] getPrivilege() {
return privilege;
}
public void setPrivilege(String[] privilege) {
this.privilege = privilege;
}
public String getUnionid() {
return unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
}
| chen1218chen/Angular | src/com/gis/wx/model/WechatUser.java | 702 | //普通用户个人资料填写的城市 | line_comment | zh-cn | package com.gis.wx.model;
public class WechatUser{
private String openid; //用户的唯一标识
private String nickname;//用户昵称
private Integer sex;// 用户的性别,值为1时是男性,值为2时是女性,值为0时是未知
private String province;//用户个人资料填写的省份
private String city;//普通 <SUF>
private String country;// 国家,如中国为CN
private String headimgurl; // 用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空。若用户更换头像,原有头像URL将失效。
private String[] privilege;// 用户特权信息,json 数组,如微信沃卡用户为(chinaunicom)
private String unionid;// 只有在用户将公众号绑定到微信开放平台帐号后,才会出现该字段。详见:获取用户个人信息(UnionID机制)
private String access_token;
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public Integer getSex() {
return sex;
}
public void setSex(Integer sex) {
this.sex = sex;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getHeadimgurl() {
return headimgurl;
}
public void setHeadimgurl(String headimgurl) {
this.headimgurl = headimgurl;
}
public String[] getPrivilege() {
return privilege;
}
public void setPrivilege(String[] privilege) {
this.privilege = privilege;
}
public String getUnionid() {
return unionid;
}
public void setUnionid(String unionid) {
this.unionid = unionid;
}
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
}
| false | 570 | 8 | 702 | 11 | 704 | 9 | 702 | 11 | 872 | 21 | false | false | false | false | false | true |
30990_5 | /*
* Copyright (C) 2010 The MobileSecurePay Project
* All right reserved.
* author: shiqun.shi@alipay.com
*
* 提示:如何获取安全校验码和合作身份者id
* 1.用您的签约支付宝账号登录支付宝网站(www.alipay.com)
* 2.点击“商家服务”(https://b.alipay.com/order/myorder.htm)
* 3.点击“查询合作者身份(pid)”、“查询安全校验码(key)”
*/
package com.vapps.alipay;
//
// 请参考 Android平台安全支付服务(msp)应用开发接口(4.2 RSA算法签名)部分,并使用压缩包中的openssl RSA密钥生成工具,生成一套RSA公私钥。
// 这里签名时,只需要使用生成的RSA私钥。
// Note: 为安全起见,使用RSA私钥进行签名的操作过程,应该尽量放到商家服务器端去进行。
public final class Keys {
//合作身份者id,以2088开头的16位纯数字
public static final String PARTNER = "";
//收款支付宝账号
public static final String SELLER = "";
//商户私钥,自助生成 pkcs8格式
public static final String RSA_PRIVATE = "";
//支付宝默认公钥 ,请勿修改
public static final String PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
}
| chen4342024/cordova-plugin-alipay | src/android/Keys.java | 498 | //收款支付宝账号 | line_comment | zh-cn | /*
* Copyright (C) 2010 The MobileSecurePay Project
* All right reserved.
* author: shiqun.shi@alipay.com
*
* 提示:如何获取安全校验码和合作身份者id
* 1.用您的签约支付宝账号登录支付宝网站(www.alipay.com)
* 2.点击“商家服务”(https://b.alipay.com/order/myorder.htm)
* 3.点击“查询合作者身份(pid)”、“查询安全校验码(key)”
*/
package com.vapps.alipay;
//
// 请参考 Android平台安全支付服务(msp)应用开发接口(4.2 RSA算法签名)部分,并使用压缩包中的openssl RSA密钥生成工具,生成一套RSA公私钥。
// 这里签名时,只需要使用生成的RSA私钥。
// Note: 为安全起见,使用RSA私钥进行签名的操作过程,应该尽量放到商家服务器端去进行。
public final class Keys {
//合作身份者id,以2088开头的16位纯数字
public static final String PARTNER = "";
//收款 <SUF>
public static final String SELLER = "";
//商户私钥,自助生成 pkcs8格式
public static final String RSA_PRIVATE = "";
//支付宝默认公钥 ,请勿修改
public static final String PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
}
| false | 454 | 4 | 498 | 6 | 463 | 5 | 498 | 6 | 688 | 12 | false | false | false | false | false | true |
7587_2 | package com.feiqu.web.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSON;
import com.feiqu.common.base.BaseResult;
import com.feiqu.common.enums.MsgEnum;
import com.feiqu.common.enums.ResultEnum;
import com.feiqu.common.enums.TopicTypeEnum;
import com.feiqu.common.enums.YesNoEnum;
import com.feiqu.framwork.constant.CommonConstant;
import com.feiqu.framwork.util.CommonUtils;
import com.feiqu.framwork.util.HttpClientUtil;
import com.feiqu.framwork.web.base.BaseController;
import com.feiqu.system.model.*;
import com.feiqu.system.pojo.cache.FqUserCache;
import com.feiqu.system.pojo.response.DetailCommentResponse;
import com.feiqu.system.pojo.response.wangyi.NewsResponse;
import com.feiqu.system.service.CMessageService;
import com.feiqu.system.service.FqNewsService;
import com.feiqu.system.service.FqUserService;
import com.feiqu.system.service.GeneralCommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Stopwatch;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* FqNewscontroller
* Created by cwd on 2018/11/14.
*/
@Controller
@RequestMapping("/fqNews")
public class FqNewsController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(FqNewsController.class);
@Autowired
private FqNewsService fqNewsService;
@Autowired
private GeneralCommentService commentService;
@Autowired
private FqUserService fqUserService;
@Autowired
private CMessageService messageService;
/**
* 跳转到FqNews首页
*/
@RequestMapping("")
public String index(@RequestParam(defaultValue = "desc") String order, Model model,
@RequestParam(defaultValue = "1") Integer pageIndex) {
PageHelper.startPage(pageIndex,20);
FqNewsExample fqNewsExample = new FqNewsExample();
fqNewsExample.setOrderByClause("gmt_create "+order);
List<FqNews> fqNews = fqNewsService.selectByExample(fqNewsExample);
model.addAttribute("fqNews",fqNews);
PageInfo page = new PageInfo(fqNews);
model.addAttribute("pageIndex",pageIndex);
model.addAttribute("pageSize",20);//文章放多点好,感觉,要不然老是需要翻页
model.addAttribute("count",page.getTotal());
return "/news/index";
}
/**
* 添加FqNews页面
*/
@RequestMapping("/fqNews_add")
public String fqNews_add() {
return "/system/FqNews/add";
}
/**
* ajax添加FqNews
*/
@ResponseBody
@RequestMapping("/add")
public Object add(FqNews fqNews) {
BaseResult result = new BaseResult();
fqNewsService.insert(fqNews);
return result;
}
/**
* ajax删除FqNews
*/
@ResponseBody
@RequestMapping("/delete")
public Object delete(@RequestParam Integer fqNewsId) {
BaseResult result = new BaseResult();
fqNewsService.deleteByPrimaryKey(fqNewsId);
return result;
}
/**
* 更新FqNews页面
*/
@RequestMapping("/edit/{fqNewsId}")
public Object fqNewsEdit(@PathVariable Integer fqNewsId, Model model) {
FqNews fqNews = fqNewsService.selectByPrimaryKey(fqNewsId);
model.addAttribute("fqNews", fqNews);
return "/system/FqNews/edit";
}
/**
* 更新FqNews页面
*/
@RequestMapping("/detail/{fqNewsId}")
public String detail(@PathVariable Long fqNewsId, Model model) {
FqNews fqNews = fqNewsService.selectByPrimaryKey(fqNewsId);
if(fqNews == null){
return "/404";
}
model.addAttribute("fqNews", fqNews);
GeneralCommentExample commentExample = new GeneralCommentExample();
commentExample.setOrderByClause("create_time desc");
commentExample.createCriteria().andTopicIdEqualTo(fqNewsId.intValue()).andDelFlagEqualTo(YesNoEnum.NO.getValue()).andTopicTypeEqualTo(TopicTypeEnum.NEWS_TYPE.getValue());
List<DetailCommentResponse> commentList = commentService.selectUserByExample(commentExample);
model.addAttribute("commentList",commentList);
FqNewsExample fqNewsExample = new FqNewsExample();
fqNewsExample.createCriteria().andSourceEqualTo(fqNews.getSource()).andIdNotEqualTo(fqNewsId);
PageHelper.startPage(1,CommonConstant.DEAULT_PAGE_SIZE,false);
List<FqNews> fqNewsSame = fqNewsService.selectByExample(fqNewsExample);
model.addAttribute("sameSource",fqNewsSame);
return "/news/detail";
}
/**
* ajax更新FqNews
*/
@ResponseBody
@RequestMapping("/edit")
public Object edit(FqNews fqNews) {
BaseResult result = new BaseResult();
fqNewsService.updateByPrimaryKey(fqNews);
return result;
}
/**
* 查询FqNews首页
*/
@RequestMapping("list")
@ResponseBody
public Object list(@RequestParam(defaultValue = "0") Integer index, @RequestParam(defaultValue = "10") Integer size) {
BaseResult result = new BaseResult();
PageHelper.startPage(index, size);
FqNewsExample example = new FqNewsExample();
example.setOrderByClause("create_time desc");
List<FqNews> list = fqNewsService.selectByExample(example);
PageInfo page = new PageInfo(list);
result.setData(page);
return result;
}
@ResponseBody
@RequestMapping(value = "comment",method = RequestMethod.POST)
public Object articleReply(GeneralComment comment){
logger.info("newsReply:"+JSON.toJSONString(comment));
BaseResult result = new BaseResult();
try {
FqUserCache user = getCurrentUser();
if(user == null){
result.setResult(ResultEnum.USER_NOT_LOGIN);
return result;
}
FqNews fqNews = fqNewsService.selectByPrimaryKey(comment.getTopicId().longValue());
if(fqNews == null){
result.setResult(ResultEnum.FAIL);
return result;
}
if(StringUtils.isBlank(comment.getContent())){
result.setResult(ResultEnum.PARAM_NULL);
result.setMessage("评论内容不能为空");
return result;
}
Date now = new Date();
comment.setCreateTime(now);
comment.setTopicType(TopicTypeEnum.NEWS_TYPE.getValue());
comment.setDelFlag(YesNoEnum.NO.getValue());
commentService.insert(comment);
List<String> aiteNames = CommonUtils.findAiteNicknames(comment.getContent());
if(aiteNames.size() > 0){
for(String aiteNickname : aiteNames){
FqUserExample example = new FqUserExample();
example.createCriteria().andNicknameEqualTo(aiteNickname);
FqUser aiteUser = fqUserService.selectFirstByExample(example);
if(aiteUser != null){
if(!aiteUser.getId().equals(user.getId())){
CMessage message = new CMessage();
message.setPostUserId(-1);
message.setCreateTime(now);
message.setDelFlag(YesNoEnum.NO.getValue());
message.setReceivedUserId(aiteUser.getId());
message.setType(MsgEnum.OFFICIAL_MSG.getValue());
message.setContent("系统消息通知:<a class=\"c-fly-link\" href=\""+ CommonConstant.DOMAIN_URL+"/u/"+user.getId()+"/peopleIndex\" target=\"_blank\">"+user.getNickname()+" </a> " +
"在<a class=\"c-fly-link\" href=\"" + CommonConstant.DOMAIN_URL + "/fqNews/" + comment.getTopicId() +"\" target=\"_blank\">此新闻</a>中回复了你 -"+ DateUtil.formatDateTime(now));
messageService.insert(message);
}
}
}
}
result.setData(comment);
} catch (Exception e) {
logger.error("新闻评论出错",e);
result.setResult(ResultEnum.FAIL);
}
return result;
}
/**
* 查询FqNews首页
*/
@RequestMapping("collect")
@ResponseBody
public Object collect(@RequestParam(required = false) Integer loop) {
BaseResult baseResult = new BaseResult();
Stopwatch stopwatch = Stopwatch.createStarted();
String result = null;
int loopSize = 10,loopCount = 10,loopIndex = 0;
if(loop != null){
loopCount = loop;
}
String url = "https://3g.163.com/touch/reconstruct/article/list/BBM54PGAwangning/";
String suffix = "-10.html";
try {
Date now = new Date();
while (loopIndex < loopCount){
String realUrl = url + loopSize*loopIndex+suffix;
result = HttpClientUtil.getWebPage(realUrl);
int index = result.indexOf(":");
result = result.substring(index + 1, result.lastIndexOf("]") + 1);
Console.log(result);
List<NewsResponse> newsResponseList = JSON.parseArray(result, NewsResponse.class);
for (NewsResponse newsResponse : newsResponseList) {
if(newsResponse.getCommentCount() < 1000){
continue;
}
if(StringUtils.isEmpty(newsResponse.getUrl())){
continue;
}
String result2 = HttpClientUtil.getWebPage(newsResponse.getUrl());
result2 = result2.substring(result2.indexOf("<article"), result2.lastIndexOf("</article>") + 10);
result2 = result2.substring(0, result2.lastIndexOf("<div class=\"footer\">"));
result2 += "</article>";
result2 = result2.replaceAll("data-src","src");
FqNews fqNews = new FqNews(newsResponse);
fqNews.setGmtCreate(now);
fqNews.setCommentCount(0);
fqNews.setContent(result2);
fqNewsService.insert(fqNews);
}
loopIndex++;
}
} catch (IOException e) {
e.printStackTrace();
}
stopwatch.stop();
long seconds = stopwatch.elapsed(TimeUnit.SECONDS);
logger.info("新闻更新完毕,耗时{}秒",seconds);
return baseResult;
}
} | chen87548081/feiqu-opensource | feiqu-front/src/main/java/com/feiqu/web/controller/FqNewsController.java | 2,610 | //文章放多点好,感觉,要不然老是需要翻页 | line_comment | zh-cn | package com.feiqu.web.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Console;
import com.alibaba.fastjson.JSON;
import com.feiqu.common.base.BaseResult;
import com.feiqu.common.enums.MsgEnum;
import com.feiqu.common.enums.ResultEnum;
import com.feiqu.common.enums.TopicTypeEnum;
import com.feiqu.common.enums.YesNoEnum;
import com.feiqu.framwork.constant.CommonConstant;
import com.feiqu.framwork.util.CommonUtils;
import com.feiqu.framwork.util.HttpClientUtil;
import com.feiqu.framwork.web.base.BaseController;
import com.feiqu.system.model.*;
import com.feiqu.system.pojo.cache.FqUserCache;
import com.feiqu.system.pojo.response.DetailCommentResponse;
import com.feiqu.system.pojo.response.wangyi.NewsResponse;
import com.feiqu.system.service.CMessageService;
import com.feiqu.system.service.FqNewsService;
import com.feiqu.system.service.FqUserService;
import com.feiqu.system.service.GeneralCommentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Stopwatch;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* FqNewscontroller
* Created by cwd on 2018/11/14.
*/
@Controller
@RequestMapping("/fqNews")
public class FqNewsController extends BaseController {
private static Logger logger = LoggerFactory.getLogger(FqNewsController.class);
@Autowired
private FqNewsService fqNewsService;
@Autowired
private GeneralCommentService commentService;
@Autowired
private FqUserService fqUserService;
@Autowired
private CMessageService messageService;
/**
* 跳转到FqNews首页
*/
@RequestMapping("")
public String index(@RequestParam(defaultValue = "desc") String order, Model model,
@RequestParam(defaultValue = "1") Integer pageIndex) {
PageHelper.startPage(pageIndex,20);
FqNewsExample fqNewsExample = new FqNewsExample();
fqNewsExample.setOrderByClause("gmt_create "+order);
List<FqNews> fqNews = fqNewsService.selectByExample(fqNewsExample);
model.addAttribute("fqNews",fqNews);
PageInfo page = new PageInfo(fqNews);
model.addAttribute("pageIndex",pageIndex);
model.addAttribute("pageSize",20);//文章 <SUF>
model.addAttribute("count",page.getTotal());
return "/news/index";
}
/**
* 添加FqNews页面
*/
@RequestMapping("/fqNews_add")
public String fqNews_add() {
return "/system/FqNews/add";
}
/**
* ajax添加FqNews
*/
@ResponseBody
@RequestMapping("/add")
public Object add(FqNews fqNews) {
BaseResult result = new BaseResult();
fqNewsService.insert(fqNews);
return result;
}
/**
* ajax删除FqNews
*/
@ResponseBody
@RequestMapping("/delete")
public Object delete(@RequestParam Integer fqNewsId) {
BaseResult result = new BaseResult();
fqNewsService.deleteByPrimaryKey(fqNewsId);
return result;
}
/**
* 更新FqNews页面
*/
@RequestMapping("/edit/{fqNewsId}")
public Object fqNewsEdit(@PathVariable Integer fqNewsId, Model model) {
FqNews fqNews = fqNewsService.selectByPrimaryKey(fqNewsId);
model.addAttribute("fqNews", fqNews);
return "/system/FqNews/edit";
}
/**
* 更新FqNews页面
*/
@RequestMapping("/detail/{fqNewsId}")
public String detail(@PathVariable Long fqNewsId, Model model) {
FqNews fqNews = fqNewsService.selectByPrimaryKey(fqNewsId);
if(fqNews == null){
return "/404";
}
model.addAttribute("fqNews", fqNews);
GeneralCommentExample commentExample = new GeneralCommentExample();
commentExample.setOrderByClause("create_time desc");
commentExample.createCriteria().andTopicIdEqualTo(fqNewsId.intValue()).andDelFlagEqualTo(YesNoEnum.NO.getValue()).andTopicTypeEqualTo(TopicTypeEnum.NEWS_TYPE.getValue());
List<DetailCommentResponse> commentList = commentService.selectUserByExample(commentExample);
model.addAttribute("commentList",commentList);
FqNewsExample fqNewsExample = new FqNewsExample();
fqNewsExample.createCriteria().andSourceEqualTo(fqNews.getSource()).andIdNotEqualTo(fqNewsId);
PageHelper.startPage(1,CommonConstant.DEAULT_PAGE_SIZE,false);
List<FqNews> fqNewsSame = fqNewsService.selectByExample(fqNewsExample);
model.addAttribute("sameSource",fqNewsSame);
return "/news/detail";
}
/**
* ajax更新FqNews
*/
@ResponseBody
@RequestMapping("/edit")
public Object edit(FqNews fqNews) {
BaseResult result = new BaseResult();
fqNewsService.updateByPrimaryKey(fqNews);
return result;
}
/**
* 查询FqNews首页
*/
@RequestMapping("list")
@ResponseBody
public Object list(@RequestParam(defaultValue = "0") Integer index, @RequestParam(defaultValue = "10") Integer size) {
BaseResult result = new BaseResult();
PageHelper.startPage(index, size);
FqNewsExample example = new FqNewsExample();
example.setOrderByClause("create_time desc");
List<FqNews> list = fqNewsService.selectByExample(example);
PageInfo page = new PageInfo(list);
result.setData(page);
return result;
}
@ResponseBody
@RequestMapping(value = "comment",method = RequestMethod.POST)
public Object articleReply(GeneralComment comment){
logger.info("newsReply:"+JSON.toJSONString(comment));
BaseResult result = new BaseResult();
try {
FqUserCache user = getCurrentUser();
if(user == null){
result.setResult(ResultEnum.USER_NOT_LOGIN);
return result;
}
FqNews fqNews = fqNewsService.selectByPrimaryKey(comment.getTopicId().longValue());
if(fqNews == null){
result.setResult(ResultEnum.FAIL);
return result;
}
if(StringUtils.isBlank(comment.getContent())){
result.setResult(ResultEnum.PARAM_NULL);
result.setMessage("评论内容不能为空");
return result;
}
Date now = new Date();
comment.setCreateTime(now);
comment.setTopicType(TopicTypeEnum.NEWS_TYPE.getValue());
comment.setDelFlag(YesNoEnum.NO.getValue());
commentService.insert(comment);
List<String> aiteNames = CommonUtils.findAiteNicknames(comment.getContent());
if(aiteNames.size() > 0){
for(String aiteNickname : aiteNames){
FqUserExample example = new FqUserExample();
example.createCriteria().andNicknameEqualTo(aiteNickname);
FqUser aiteUser = fqUserService.selectFirstByExample(example);
if(aiteUser != null){
if(!aiteUser.getId().equals(user.getId())){
CMessage message = new CMessage();
message.setPostUserId(-1);
message.setCreateTime(now);
message.setDelFlag(YesNoEnum.NO.getValue());
message.setReceivedUserId(aiteUser.getId());
message.setType(MsgEnum.OFFICIAL_MSG.getValue());
message.setContent("系统消息通知:<a class=\"c-fly-link\" href=\""+ CommonConstant.DOMAIN_URL+"/u/"+user.getId()+"/peopleIndex\" target=\"_blank\">"+user.getNickname()+" </a> " +
"在<a class=\"c-fly-link\" href=\"" + CommonConstant.DOMAIN_URL + "/fqNews/" + comment.getTopicId() +"\" target=\"_blank\">此新闻</a>中回复了你 -"+ DateUtil.formatDateTime(now));
messageService.insert(message);
}
}
}
}
result.setData(comment);
} catch (Exception e) {
logger.error("新闻评论出错",e);
result.setResult(ResultEnum.FAIL);
}
return result;
}
/**
* 查询FqNews首页
*/
@RequestMapping("collect")
@ResponseBody
public Object collect(@RequestParam(required = false) Integer loop) {
BaseResult baseResult = new BaseResult();
Stopwatch stopwatch = Stopwatch.createStarted();
String result = null;
int loopSize = 10,loopCount = 10,loopIndex = 0;
if(loop != null){
loopCount = loop;
}
String url = "https://3g.163.com/touch/reconstruct/article/list/BBM54PGAwangning/";
String suffix = "-10.html";
try {
Date now = new Date();
while (loopIndex < loopCount){
String realUrl = url + loopSize*loopIndex+suffix;
result = HttpClientUtil.getWebPage(realUrl);
int index = result.indexOf(":");
result = result.substring(index + 1, result.lastIndexOf("]") + 1);
Console.log(result);
List<NewsResponse> newsResponseList = JSON.parseArray(result, NewsResponse.class);
for (NewsResponse newsResponse : newsResponseList) {
if(newsResponse.getCommentCount() < 1000){
continue;
}
if(StringUtils.isEmpty(newsResponse.getUrl())){
continue;
}
String result2 = HttpClientUtil.getWebPage(newsResponse.getUrl());
result2 = result2.substring(result2.indexOf("<article"), result2.lastIndexOf("</article>") + 10);
result2 = result2.substring(0, result2.lastIndexOf("<div class=\"footer\">"));
result2 += "</article>";
result2 = result2.replaceAll("data-src","src");
FqNews fqNews = new FqNews(newsResponse);
fqNews.setGmtCreate(now);
fqNews.setCommentCount(0);
fqNews.setContent(result2);
fqNewsService.insert(fqNews);
}
loopIndex++;
}
} catch (IOException e) {
e.printStackTrace();
}
stopwatch.stop();
long seconds = stopwatch.elapsed(TimeUnit.SECONDS);
logger.info("新闻更新完毕,耗时{}秒",seconds);
return baseResult;
}
} | false | 2,233 | 15 | 2,610 | 18 | 2,740 | 15 | 2,610 | 18 | 3,193 | 26 | false | false | false | false | false | true |
51648_0 | package Builder;
public class Director {
private Builder builder;
public Director (Builder builder){
this.builder=builder;
}
public void construct(){ //编写文档
builder.makeTitle("Greeting");
builder.makeString("白天");
builder.makeItems(new String[]{"早上好","下午好"});
builder.makeString("夜晚");
builder.makeItems(new String[]{"晚上好","晚安","再见"});
builder.close();
}
}
| chenbihao/Design-Patterns | 图解设计模式版(过时废弃/src/Builder/Director.java | 130 | //编写文档 | line_comment | zh-cn | package Builder;
public class Director {
private Builder builder;
public Director (Builder builder){
this.builder=builder;
}
public void construct(){ //编写 <SUF>
builder.makeTitle("Greeting");
builder.makeString("白天");
builder.makeItems(new String[]{"早上好","下午好"});
builder.makeString("夜晚");
builder.makeItems(new String[]{"晚上好","晚安","再见"});
builder.close();
}
}
| false | 91 | 3 | 130 | 3 | 115 | 3 | 130 | 3 | 154 | 7 | false | false | false | false | false | true |
61369_1 | package com.hz.cds.prisoner.ws.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.hz.db.service.IQueryService;
@Service
public class PrisonerWsUtil {
final Logger logger = LoggerFactory.getLogger(PrisonerWsUtil.class);
@Resource
private IQueryService queryService;
/**用于存放已释放罪犯编号信息的List,已释放的罪犯信息不需要更新 */
public List<String> notInPrisonList = null;
/**用于存放在监罪犯编号信息的map,对已在监的罪犯信息进行更新 */
public List<String> inPrisonList = null;
/**用于存放部门信息的MAP**/
public HashMap<String,String> drptMap = null;
/**
* 获取数据库中所有罪犯的编号及在监状态,对其分类(放入对应的List中)
* @param cusNumber
*/
public void queryPrisonerList(String cusNumber){
notInPrisonList = new ArrayList<String>();
inPrisonList = new ArrayList<String>();
List<Map<String,Object>> rtnList=new ArrayList<Map<String,Object>>();
List<Object> parasList=new ArrayList<Object>();
parasList.add(cusNumber);
try {
rtnList= queryService.query("select_prisoner_no_list","0",parasList);
//遍历查询结果
for(Map<String,Object> row:rtnList){
String prisonerId = row.get("pbd_other_id").toString();
String status = row.get("pbd_stts_indc").toString();
if(status.equals("0")){
//离监(已释放)罪犯
notInPrisonList.add(prisonerId);
}else{
inPrisonList.add(prisonerId);
}
}
logger.info("初始化已释放和在监罪犯编号集合...完成");
} catch (Exception e) {
logger.error("初始化已释放和在监罪犯编号集合...异常",e);
}
}
/**
* 根据key返回对应的值
* @param child
* @param key
* @return
*/
public String getValue(Element child,String key){
return child.element(key).getTextTrim();
}
/**
* 初始化部门信息(应对罪犯改造系统与本系统部门编号不一致的情况)
* @param cusNumber
*/
public void getPrisnerDrpt(String cusNumber){
drptMap = new HashMap<String,String>();
List<Map<String,Object>> rtnList=new ArrayList<Map<String,Object>>();
List<Object> parasList=new ArrayList<Object>();
parasList.add(cusNumber);
try {
rtnList = queryService.query("select_dept_info_ws","0",parasList);
//遍历查询结果
for(Map<String,Object> row:rtnList){
String dprtmntid = row.get("odd_id").toString();
String drptmntName = row.get("odd_name").toString();
drptMap.put(drptmntName, dprtmntid);
}
logger.info("初始化部门信息...完成");
} catch (Exception e) {
logger.error("初始化部门信息...异常",e);
}
}
}
| chendaiming/Develop | HzPrisoner/src/com/hz/cds/prisoner/ws/util/PrisonerWsUtil.java | 921 | /**用于存放在监罪犯编号信息的map,对已在监的罪犯信息进行更新 */ | block_comment | zh-cn | package com.hz.cds.prisoner.ws.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.hz.db.service.IQueryService;
@Service
public class PrisonerWsUtil {
final Logger logger = LoggerFactory.getLogger(PrisonerWsUtil.class);
@Resource
private IQueryService queryService;
/**用于存放已释放罪犯编号信息的List,已释放的罪犯信息不需要更新 */
public List<String> notInPrisonList = null;
/**用于存 <SUF>*/
public List<String> inPrisonList = null;
/**用于存放部门信息的MAP**/
public HashMap<String,String> drptMap = null;
/**
* 获取数据库中所有罪犯的编号及在监状态,对其分类(放入对应的List中)
* @param cusNumber
*/
public void queryPrisonerList(String cusNumber){
notInPrisonList = new ArrayList<String>();
inPrisonList = new ArrayList<String>();
List<Map<String,Object>> rtnList=new ArrayList<Map<String,Object>>();
List<Object> parasList=new ArrayList<Object>();
parasList.add(cusNumber);
try {
rtnList= queryService.query("select_prisoner_no_list","0",parasList);
//遍历查询结果
for(Map<String,Object> row:rtnList){
String prisonerId = row.get("pbd_other_id").toString();
String status = row.get("pbd_stts_indc").toString();
if(status.equals("0")){
//离监(已释放)罪犯
notInPrisonList.add(prisonerId);
}else{
inPrisonList.add(prisonerId);
}
}
logger.info("初始化已释放和在监罪犯编号集合...完成");
} catch (Exception e) {
logger.error("初始化已释放和在监罪犯编号集合...异常",e);
}
}
/**
* 根据key返回对应的值
* @param child
* @param key
* @return
*/
public String getValue(Element child,String key){
return child.element(key).getTextTrim();
}
/**
* 初始化部门信息(应对罪犯改造系统与本系统部门编号不一致的情况)
* @param cusNumber
*/
public void getPrisnerDrpt(String cusNumber){
drptMap = new HashMap<String,String>();
List<Map<String,Object>> rtnList=new ArrayList<Map<String,Object>>();
List<Object> parasList=new ArrayList<Object>();
parasList.add(cusNumber);
try {
rtnList = queryService.query("select_dept_info_ws","0",parasList);
//遍历查询结果
for(Map<String,Object> row:rtnList){
String dprtmntid = row.get("odd_id").toString();
String drptmntName = row.get("odd_name").toString();
drptMap.put(drptmntName, dprtmntid);
}
logger.info("初始化部门信息...完成");
} catch (Exception e) {
logger.error("初始化部门信息...异常",e);
}
}
}
| false | 743 | 23 | 921 | 28 | 892 | 23 | 921 | 28 | 1,193 | 43 | false | false | false | false | false | true |
43109_0 | package benKeBiYeSheJi;
import commonTool.Input_xls_Data;
public class Read_Data {
Input_xls_Data id = new Input_xls_Data();
String path, sheetName, colName;//读取路径
int[] yueFen;//总的时段长度
int[] yueTianShu;//各月天数
int[] yueFaDianShiChang;//水电站机组月运行时数(h)
double[] yueRuKuJingLiuLiang;//月入库径流量(m³)
public Read_Data() {
//狮子滩入库径流量
path = "F:\\本科毕业设计(2018))\\狮子滩水库信息\\狮子滩月入库径流量.xls";
sheetName = "Sheet1";
//参与调度的总月份数
colName = "月份";
yueFen = id.getColumnDatasInt(path, sheetName, colName);
//参与调度的各月份天数
colName = "月天数(d)";
yueTianShu = id.getColumnDatasInt(path, sheetName, colName);
//参与调度的各月机组运行时段数
colName = "水电站机组月运行时数(h)";
yueFaDianShiChang = id.getColumnDatasInt(path, sheetName, colName);
//狮子滩各月入库径流量
colName = "月入库径流量(m³)";
yueRuKuJingLiuLiang = id.getColumnDatasDouble(path, sheetName, colName);
}
//读取数据
public int[] read_YueFen() {
return yueFen;
}
public int[] read_YueTianShu() {
return yueTianShu;
}
public int[] read_YueFaDianShiChang() {
return yueFaDianShiChang;
}
public double[] read_YueRuKuJingLiuLiang() {
return yueRuKuJingLiuLiang;
}
/**
* 由各月入库径流、天数,计算出各月入库月平均流量
* @return
*/
public double[] get_YueRuKuPingJunLiuLiang() {
double[] yueRuKuJingLiuLiang = read_YueRuKuJingLiuLiang();
int[] yueTianShu = read_YueTianShu();
double[] yueRuKuPingJunLiuLiang = new double[yueRuKuJingLiuLiang.length];
for(int i = 0; i < yueRuKuJingLiuLiang.length; i ++){
yueRuKuPingJunLiuLiang[i] = yueRuKuJingLiuLiang[i] /
(yueTianShu[i] * 24 * 3600);
}
return yueRuKuPingJunLiuLiang;
}
// //测试
// public static void main(String[] args) {
// Read_Data rd = new Read_Data();
// int[] yueTianShu = rd.read_YueTianShu();
// for(int i : yueTianShu){
//// System.out.println(i);
// }
// double[] arr = rd.get_YueRuKuPingJunLiuLiang();
// for(double d : arr){
// System.out.println(d);
// }
// }
}
| chendamowang/POA- | Read_Data.java | 946 | //读取路径
| line_comment | zh-cn | package benKeBiYeSheJi;
import commonTool.Input_xls_Data;
public class Read_Data {
Input_xls_Data id = new Input_xls_Data();
String path, sheetName, colName;//读取 <SUF>
int[] yueFen;//总的时段长度
int[] yueTianShu;//各月天数
int[] yueFaDianShiChang;//水电站机组月运行时数(h)
double[] yueRuKuJingLiuLiang;//月入库径流量(m³)
public Read_Data() {
//狮子滩入库径流量
path = "F:\\本科毕业设计(2018))\\狮子滩水库信息\\狮子滩月入库径流量.xls";
sheetName = "Sheet1";
//参与调度的总月份数
colName = "月份";
yueFen = id.getColumnDatasInt(path, sheetName, colName);
//参与调度的各月份天数
colName = "月天数(d)";
yueTianShu = id.getColumnDatasInt(path, sheetName, colName);
//参与调度的各月机组运行时段数
colName = "水电站机组月运行时数(h)";
yueFaDianShiChang = id.getColumnDatasInt(path, sheetName, colName);
//狮子滩各月入库径流量
colName = "月入库径流量(m³)";
yueRuKuJingLiuLiang = id.getColumnDatasDouble(path, sheetName, colName);
}
//读取数据
public int[] read_YueFen() {
return yueFen;
}
public int[] read_YueTianShu() {
return yueTianShu;
}
public int[] read_YueFaDianShiChang() {
return yueFaDianShiChang;
}
public double[] read_YueRuKuJingLiuLiang() {
return yueRuKuJingLiuLiang;
}
/**
* 由各月入库径流、天数,计算出各月入库月平均流量
* @return
*/
public double[] get_YueRuKuPingJunLiuLiang() {
double[] yueRuKuJingLiuLiang = read_YueRuKuJingLiuLiang();
int[] yueTianShu = read_YueTianShu();
double[] yueRuKuPingJunLiuLiang = new double[yueRuKuJingLiuLiang.length];
for(int i = 0; i < yueRuKuJingLiuLiang.length; i ++){
yueRuKuPingJunLiuLiang[i] = yueRuKuJingLiuLiang[i] /
(yueTianShu[i] * 24 * 3600);
}
return yueRuKuPingJunLiuLiang;
}
// //测试
// public static void main(String[] args) {
// Read_Data rd = new Read_Data();
// int[] yueTianShu = rd.read_YueTianShu();
// for(int i : yueTianShu){
//// System.out.println(i);
// }
// double[] arr = rd.get_YueRuKuPingJunLiuLiang();
// for(double d : arr){
// System.out.println(d);
// }
// }
}
| false | 795 | 5 | 934 | 4 | 808 | 4 | 934 | 4 | 1,095 | 10 | false | false | false | false | false | true |
62315_21 | package com.dwtedx.qq.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.dwtedx.tst.R;
public class DropdownListView extends ListView implements OnScrollListener {
private static final String TAG = "listview";
private final static int RELEASE_To_REFRESH = 0;
private final static int PULL_To_REFRESH = 1;
private final static int REFRESHING = 2;
private final static int DONE = 3;
private final static int LOADING = 4;
// 实际的padding的距离与界面上偏移距离的比例
private final static int RATIO = 3;
private LayoutInflater inflater;
private FrameLayout fl;
private LinearLayout headView;
// private View line;
private ProgressBar progressBar;
// private RotateAnimation animation;
// private RotateAnimation reverseAnimation;
// 用于保证startY的值在一个完整的touch事件中只被记录一次
private boolean isRecored;
private int headContentWidth;
private int headContentHeight;
private int startY;
private int firstItemIndex;
private int state;
private boolean isBack;
private OnRefreshListenerHeader refreshListenerHeader;
private boolean isRefreshableHeader;
public DropdownListView(Context context) {
super(context);
init(context);
}
public DropdownListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
setCacheColorHint(context.getResources().getColor(R.color.transparent));
inflater = LayoutInflater.from(context);
fl = (FrameLayout)inflater.inflate(R.layout.dropdown_lv_head, null);
headView = (LinearLayout) fl.findViewById(R.id.drop_down_head);
progressBar = (ProgressBar) fl.findViewById(R.id.loading);
measureView(headView);
headContentHeight = headView.getMeasuredHeight();
headContentWidth = headView.getMeasuredWidth();
headView.setPadding(0, -1 * headContentHeight, 0, 0);
headView.invalidate();
Log.v("size", "width:" + headContentWidth + " height:"
+ headContentHeight);
addHeaderView(fl, null, false);
// addHeaderView(headView, null, false);
setOnScrollListener(this);
state = DONE;
isRefreshableHeader = false;
}
public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2,
int arg3) {
firstItemIndex = firstVisiableItem;
}
public void onScrollStateChanged(AbsListView arg0, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// 判断滚动到底部
}
}
public boolean onTouchEvent(MotionEvent event) {
if (isRefreshableHeader) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (firstItemIndex == 0 && !isRecored) {
isRecored = true;
startY = (int) event.getY();
Log.v(TAG, "在down时候记录当前位置‘");
}
break;
case MotionEvent.ACTION_UP:
if (state != REFRESHING && state != LOADING) {
if (state == DONE) {
// 什么都不做
}
if (state == PULL_To_REFRESH) {
state = DONE;
changeHeaderViewByState();
Log.v(TAG, "由下拉刷新状态,到done状态");
}
if (state == RELEASE_To_REFRESH) {
state = REFRESHING;
changeHeaderViewByState();
// recoverLine();
onRefresh();
Log.v(TAG, "由松开刷新状态,到done状态");
}
}
isRecored = false;
isBack = false;
break;
case MotionEvent.ACTION_MOVE:
int tempY = (int) event.getY();
if (!isRecored && firstItemIndex == 0) {
Log.v(TAG, "在move时候记录下位置");
isRecored = true;
startY = tempY;
}
if (state != REFRESHING && isRecored && state != LOADING) {
// 保证在设置padding的过程中,当前的位置一直是在head,否则如果当列表超出屏幕的话,当在上推的时候,列表会同时进行滚动
// 可以松手去刷新了
if (state == RELEASE_To_REFRESH) {
setSelection(0);
// 往上推了,推到了屏幕足够掩盖head的程度,但是还没有推到全部掩盖的地步
if (((tempY - startY) / RATIO < headContentHeight)
&& (tempY - startY) > 0) {
state = PULL_To_REFRESH;
changeHeaderViewByState();
Log.v(TAG, "由松开刷新状态转变到下拉刷新状态");
}
// 一下子推到顶了
else if (tempY - startY <= 0) {
state = DONE;
changeHeaderViewByState();
Log.v(TAG, "由松开刷新状态转变到done状态");
}
// 往下拉了,或者还没有上推到屏幕顶部掩盖head的地步
else {
// 不用进行特别的操作,只用更新paddingTop的值就行了
}
}
// 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态
if (state == PULL_To_REFRESH) {
setSelection(0);
// 下拉到可以进入RELEASE_TO_REFRESH的状态
if ((tempY - startY) / RATIO >= headContentHeight) {
state = RELEASE_To_REFRESH;
isBack = true;
changeHeaderViewByState();
Log.v(TAG, "由done或者下拉刷新状态转变到松开刷新");
}
// 上推到顶了
else if (tempY - startY <= 0) {
state = DONE;
changeHeaderViewByState();
Log.v(TAG, "由DOne或者下拉刷新状态转变到done状态");
}
}
// done状态下
if (state == DONE) {
if (tempY - startY > 0) {
state = PULL_To_REFRESH;
changeHeaderViewByState();
}
}
// 更新headView的size
if (state == PULL_To_REFRESH) {
headView.setPadding(0, -1 * headContentHeight
+ (tempY - startY) / RATIO, 0, 0);
}
// 更新headView的paddingTop
if (state == RELEASE_To_REFRESH) {
headView.setPadding(0, (tempY - startY) / RATIO
- headContentHeight, 0, 0);
}
}
break;
}
}
return super.onTouchEvent(event);
}
// 当状态改变时候,调用该方法,以更新界面
private void changeHeaderViewByState() {
switch (state) {
case RELEASE_To_REFRESH:
progressBar.setVisibility(View.VISIBLE);
Log.v(TAG, "当前状态,松开刷新");
break;
case PULL_To_REFRESH:
progressBar.setVisibility(View.VISIBLE);
// 是由RELEASE_To_REFRESH状态转变来的
if (isBack) {
isBack = false;
} else {
}
Log.v(TAG, "当前状态,下拉刷新");
break;
case REFRESHING:
headView.setPadding(0, 0, 0, 0);
progressBar.setVisibility(View.VISIBLE);
Log.v(TAG, "当前状态,正在刷新...");
break;
case DONE:
headView.setPadding(0, -1 * headContentHeight, 0, 0);
progressBar.setVisibility(View.GONE);
Log.v(TAG, "当前状态,done");
break;
}
}
public void setOnRefreshListenerHead(
OnRefreshListenerHeader refreshListenerHeader) {
this.refreshListenerHeader = refreshListenerHeader;
isRefreshableHeader = true;
}
public interface OnRefreshListenerHeader {
public void onRefresh();
}
public interface OnRefreshListenerFooter {
public void onRefresh();
}
public void onRefreshCompleteHeader() {
state = DONE;
changeHeaderViewByState();
}
private void onRefresh() {
if (refreshListenerHeader != null) {
refreshListenerHeader.onRefresh();
}
}
// 此方法直接照搬自网络上的一个下拉刷新的demo,此处是“估计”headView的width以及height
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
}
}
| chendd/QQChat | src/com/dwtedx/qq/view/DropdownListView.java | 2,578 | // 当状态改变时候,调用该方法,以更新界面
| line_comment | zh-cn | package com.dwtedx.qq.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import com.dwtedx.tst.R;
public class DropdownListView extends ListView implements OnScrollListener {
private static final String TAG = "listview";
private final static int RELEASE_To_REFRESH = 0;
private final static int PULL_To_REFRESH = 1;
private final static int REFRESHING = 2;
private final static int DONE = 3;
private final static int LOADING = 4;
// 实际的padding的距离与界面上偏移距离的比例
private final static int RATIO = 3;
private LayoutInflater inflater;
private FrameLayout fl;
private LinearLayout headView;
// private View line;
private ProgressBar progressBar;
// private RotateAnimation animation;
// private RotateAnimation reverseAnimation;
// 用于保证startY的值在一个完整的touch事件中只被记录一次
private boolean isRecored;
private int headContentWidth;
private int headContentHeight;
private int startY;
private int firstItemIndex;
private int state;
private boolean isBack;
private OnRefreshListenerHeader refreshListenerHeader;
private boolean isRefreshableHeader;
public DropdownListView(Context context) {
super(context);
init(context);
}
public DropdownListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
setCacheColorHint(context.getResources().getColor(R.color.transparent));
inflater = LayoutInflater.from(context);
fl = (FrameLayout)inflater.inflate(R.layout.dropdown_lv_head, null);
headView = (LinearLayout) fl.findViewById(R.id.drop_down_head);
progressBar = (ProgressBar) fl.findViewById(R.id.loading);
measureView(headView);
headContentHeight = headView.getMeasuredHeight();
headContentWidth = headView.getMeasuredWidth();
headView.setPadding(0, -1 * headContentHeight, 0, 0);
headView.invalidate();
Log.v("size", "width:" + headContentWidth + " height:"
+ headContentHeight);
addHeaderView(fl, null, false);
// addHeaderView(headView, null, false);
setOnScrollListener(this);
state = DONE;
isRefreshableHeader = false;
}
public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2,
int arg3) {
firstItemIndex = firstVisiableItem;
}
public void onScrollStateChanged(AbsListView arg0, int scrollState) {
if (scrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// 判断滚动到底部
}
}
public boolean onTouchEvent(MotionEvent event) {
if (isRefreshableHeader) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (firstItemIndex == 0 && !isRecored) {
isRecored = true;
startY = (int) event.getY();
Log.v(TAG, "在down时候记录当前位置‘");
}
break;
case MotionEvent.ACTION_UP:
if (state != REFRESHING && state != LOADING) {
if (state == DONE) {
// 什么都不做
}
if (state == PULL_To_REFRESH) {
state = DONE;
changeHeaderViewByState();
Log.v(TAG, "由下拉刷新状态,到done状态");
}
if (state == RELEASE_To_REFRESH) {
state = REFRESHING;
changeHeaderViewByState();
// recoverLine();
onRefresh();
Log.v(TAG, "由松开刷新状态,到done状态");
}
}
isRecored = false;
isBack = false;
break;
case MotionEvent.ACTION_MOVE:
int tempY = (int) event.getY();
if (!isRecored && firstItemIndex == 0) {
Log.v(TAG, "在move时候记录下位置");
isRecored = true;
startY = tempY;
}
if (state != REFRESHING && isRecored && state != LOADING) {
// 保证在设置padding的过程中,当前的位置一直是在head,否则如果当列表超出屏幕的话,当在上推的时候,列表会同时进行滚动
// 可以松手去刷新了
if (state == RELEASE_To_REFRESH) {
setSelection(0);
// 往上推了,推到了屏幕足够掩盖head的程度,但是还没有推到全部掩盖的地步
if (((tempY - startY) / RATIO < headContentHeight)
&& (tempY - startY) > 0) {
state = PULL_To_REFRESH;
changeHeaderViewByState();
Log.v(TAG, "由松开刷新状态转变到下拉刷新状态");
}
// 一下子推到顶了
else if (tempY - startY <= 0) {
state = DONE;
changeHeaderViewByState();
Log.v(TAG, "由松开刷新状态转变到done状态");
}
// 往下拉了,或者还没有上推到屏幕顶部掩盖head的地步
else {
// 不用进行特别的操作,只用更新paddingTop的值就行了
}
}
// 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态
if (state == PULL_To_REFRESH) {
setSelection(0);
// 下拉到可以进入RELEASE_TO_REFRESH的状态
if ((tempY - startY) / RATIO >= headContentHeight) {
state = RELEASE_To_REFRESH;
isBack = true;
changeHeaderViewByState();
Log.v(TAG, "由done或者下拉刷新状态转变到松开刷新");
}
// 上推到顶了
else if (tempY - startY <= 0) {
state = DONE;
changeHeaderViewByState();
Log.v(TAG, "由DOne或者下拉刷新状态转变到done状态");
}
}
// done状态下
if (state == DONE) {
if (tempY - startY > 0) {
state = PULL_To_REFRESH;
changeHeaderViewByState();
}
}
// 更新headView的size
if (state == PULL_To_REFRESH) {
headView.setPadding(0, -1 * headContentHeight
+ (tempY - startY) / RATIO, 0, 0);
}
// 更新headView的paddingTop
if (state == RELEASE_To_REFRESH) {
headView.setPadding(0, (tempY - startY) / RATIO
- headContentHeight, 0, 0);
}
}
break;
}
}
return super.onTouchEvent(event);
}
// 当状 <SUF>
private void changeHeaderViewByState() {
switch (state) {
case RELEASE_To_REFRESH:
progressBar.setVisibility(View.VISIBLE);
Log.v(TAG, "当前状态,松开刷新");
break;
case PULL_To_REFRESH:
progressBar.setVisibility(View.VISIBLE);
// 是由RELEASE_To_REFRESH状态转变来的
if (isBack) {
isBack = false;
} else {
}
Log.v(TAG, "当前状态,下拉刷新");
break;
case REFRESHING:
headView.setPadding(0, 0, 0, 0);
progressBar.setVisibility(View.VISIBLE);
Log.v(TAG, "当前状态,正在刷新...");
break;
case DONE:
headView.setPadding(0, -1 * headContentHeight, 0, 0);
progressBar.setVisibility(View.GONE);
Log.v(TAG, "当前状态,done");
break;
}
}
public void setOnRefreshListenerHead(
OnRefreshListenerHeader refreshListenerHeader) {
this.refreshListenerHeader = refreshListenerHeader;
isRefreshableHeader = true;
}
public interface OnRefreshListenerHeader {
public void onRefresh();
}
public interface OnRefreshListenerFooter {
public void onRefresh();
}
public void onRefreshCompleteHeader() {
state = DONE;
changeHeaderViewByState();
}
private void onRefresh() {
if (refreshListenerHeader != null) {
refreshListenerHeader.onRefresh();
}
}
// 此方法直接照搬自网络上的一个下拉刷新的demo,此处是“估计”headView的width以及height
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
public void setAdapter(BaseAdapter adapter) {
super.setAdapter(adapter);
}
}
| false | 2,080 | 15 | 2,554 | 14 | 2,423 | 14 | 2,552 | 14 | 3,578 | 22 | false | false | false | false | false | true |
45549_11 | /*
There are n coins in a line. Two players take turns to take one or two
coins from right side until there are no more coins left. The player who
take the last coin wins.
*/
/*
Could you please decide the first play will win or lose?
Example
n = 1, return true.
n = 2, return true.
n = 3, return false.
n = 4, return true.
n = 5, return true.
Challenge
O(n) time and O(1) memory
*/
//////////////////////////////////////
// DP Drawing search tree bottom up //
//////////////////////////////////////
public class Solution {
// int[] dp; we can put it in here in case it goes too deep
public boolean firstWillWin(int n) {
int[] dp = new int[n + 1];
return MemorySearch(n, dp);
}
private boolean MemorySearch(int n, int[] dp) {
if (dp[n] != 0)
if (dp[n] == 1)
return false;
else /* dp[n] == 2 */
return true;
if (n <= 0) dp[n] = 1;
else if (n == 1) dp[n] = 2;
else if (n == 2) dp[n] = 2;
else if (n == 3) dp[n] = 1;
else
/* Take care of these index by drawing the search tree*/
if ((MemorySearch(n - 2, dp) && MemorySearch(n - 3, dp)) ||
MemorySearch(n - 3, dp) && MemorySearch(n - 4, dp)) {
dp[n] = 2;
} else {
dp[n] = 1;
}
}
}
/////////////////////////////
// Memory Search top down // StackOverflow
/////////////////////////////
public class Solution {
public boolean firstWillWin(int n) {
boolean []dp = new boolean[n+1];
boolean []flag = new boolean[n+1];
return MemorySearch(n, dp, flag);
}
boolean MemorySearch(int i, boolean []dp, boolean []flag) {
if(flag[i] == true) {
return dp[i];
}
if(i == 0) {
dp[i] = false;
} else if(i == 1) {
dp[i] = true;
} else if(i == 2) {
dp[i] = true;
} else { /* Too deep */
/* dp[i] 现在还剩i个硬币,现在当前取硬币的人最后输赢状况 */
dp[i] = !MemorySearch(i-1, dp, flag) || !MemorySearch(i-2, dp,
flag);
}
flag[i] = true;
return dp[i];
}
}
/////////////////
// DP top down // Not easy to come up
/////////////////
public class Solution {
public boolean firstWillWin(int n) {
/* Base case / Init */
if (n == 0)
return false;
else if (n == 1)
return true;
else if (n == 2)
return true;
/* dp[i] 现在还剩i个硬币,现在当前取硬币的人最后输赢状况 */
boolean []dp = new boolean[n+1];
dp[0] = false;
dp[1] = true;
dp[2] = true;
for (int i = 3; i <= n; i++)
dp[i] = !dp[i - 1] || !dp[i - 2];
return dp[n];
}
}
| chendddong/LintCode | 394. Coins in a Line.java | 860 | /* dp[i] 现在还剩i个硬币,现在当前取硬币的人最后输赢状况 */ | block_comment | zh-cn | /*
There are n coins in a line. Two players take turns to take one or two
coins from right side until there are no more coins left. The player who
take the last coin wins.
*/
/*
Could you please decide the first play will win or lose?
Example
n = 1, return true.
n = 2, return true.
n = 3, return false.
n = 4, return true.
n = 5, return true.
Challenge
O(n) time and O(1) memory
*/
//////////////////////////////////////
// DP Drawing search tree bottom up //
//////////////////////////////////////
public class Solution {
// int[] dp; we can put it in here in case it goes too deep
public boolean firstWillWin(int n) {
int[] dp = new int[n + 1];
return MemorySearch(n, dp);
}
private boolean MemorySearch(int n, int[] dp) {
if (dp[n] != 0)
if (dp[n] == 1)
return false;
else /* dp[n] == 2 */
return true;
if (n <= 0) dp[n] = 1;
else if (n == 1) dp[n] = 2;
else if (n == 2) dp[n] = 2;
else if (n == 3) dp[n] = 1;
else
/* Take care of these index by drawing the search tree*/
if ((MemorySearch(n - 2, dp) && MemorySearch(n - 3, dp)) ||
MemorySearch(n - 3, dp) && MemorySearch(n - 4, dp)) {
dp[n] = 2;
} else {
dp[n] = 1;
}
}
}
/////////////////////////////
// Memory Search top down // StackOverflow
/////////////////////////////
public class Solution {
public boolean firstWillWin(int n) {
boolean []dp = new boolean[n+1];
boolean []flag = new boolean[n+1];
return MemorySearch(n, dp, flag);
}
boolean MemorySearch(int i, boolean []dp, boolean []flag) {
if(flag[i] == true) {
return dp[i];
}
if(i == 0) {
dp[i] = false;
} else if(i == 1) {
dp[i] = true;
} else if(i == 2) {
dp[i] = true;
} else { /* Too deep */
/* dp[i] 现在还剩i个硬币,现在当前取硬币的人最后输赢状况 */
dp[i] = !MemorySearch(i-1, dp, flag) || !MemorySearch(i-2, dp,
flag);
}
flag[i] = true;
return dp[i];
}
}
/////////////////
// DP top down // Not easy to come up
/////////////////
public class Solution {
public boolean firstWillWin(int n) {
/* Base case / Init */
if (n == 0)
return false;
else if (n == 1)
return true;
else if (n == 2)
return true;
/* dp[ <SUF>*/
boolean []dp = new boolean[n+1];
dp[0] = false;
dp[1] = true;
dp[2] = true;
for (int i = 3; i <= n; i++)
dp[i] = !dp[i - 1] || !dp[i - 2];
return dp[n];
}
}
| false | 804 | 26 | 860 | 28 | 933 | 25 | 860 | 28 | 1,035 | 46 | false | false | false | false | false | true |
49942_2 | package lol.chendong.data.meizhi;
import com.orhanobut.logger.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* 作者:陈东 — www.renwey.com
* 日期:2016/12/23 - 14:04
* 注释:
*/
public class MeizhiData {
public static final String 最热 = "hot/";
public static final String 推荐 = "best/";
public static final String 最新 = "";
public static final String 性感 = "xinggan/";
public static final String 日本 = "japan/";
public static final String 台湾 = "taiwan/";
public static final String 清纯妹纸 = "mm/";
public static final String 搜索 = "search/";
public static final String 自拍 = "zipai";
private static MeizhiData ourInstance = new MeizhiData();
int detalPage; //详情页面数量
private int timeout = 1000 * 10; //超时时间
private MeizhiBean bean = new MeizhiBean();
private MeizhiData() {
headerMap.put("Referer","http://www.mzitu.com/");
headerMap.put("Domain-Name","mei_zi_tu_domain_name");
}
public static MeizhiData getData() {
return ourInstance;
}
Map<String ,String > headerMap = new HashMap<>();
/**
* 获取浏览图列表
*
* @param type
* @param page
* @return
*/
public Observable<List<MeizhiBean>> getRoughPicList(final String type, final int page) {
Observable<List<MeizhiBean>> meizhiOb = Observable.create(new Observable.OnSubscribe<List<MeizhiBean>>() {
@Override
public void call(Subscriber<? super List<MeizhiBean>> subscriber) {
List<MeizhiBean> meizhiBeanList = new ArrayList<>();
try {
Document doc = Jsoup.connect("http://www.mzitu.com/" + type + "page/" + page)
.header("Referer","http://www.mzitu.com/")
.header("Domain-Name","mei_zi_tu_domain_name")
.get();
Logger.d("http://www.mzitu.com/" + type + "page/" + page);
Element content = doc.getElementById("pins");
Elements dataList = content.getElementsByTag("li");
for (Element data : dataList) {
MeizhiBean mbean = new MeizhiBean();
mbean.setTime(data.getElementsByClass("time").text());
mbean.setView(data.getElementsByClass("view").text());
Element link = data.select("a").first();//查找第一个a元素
mbean.setUrl(link.attr("href"));
Element img = link.getElementsByTag("img").first();
mbean.setTitle(img.attr("alt"));
MeizhiBean.MeiZhiImage mimg = new MeizhiBean.MeiZhiImage();
mimg.setWidth(Integer.parseInt(img.attr("width")));
mimg.setHeight(Integer.parseInt(img.attr("height")));
mimg.setImgUrl(img.attr("data-original"));
mbean.setImage(mimg);
meizhiBeanList.add(mbean);
}
subscriber.onNext(meizhiBeanList);
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
}
});
return meizhiOb
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread());
}
/**
* 搜索妹子
*
* @param search
* @param page
* @return
*/
public Observable<List<MeizhiBean>> getSearchMeizhiList(final String search, final int page) {
return getRoughPicList(搜索 + search + "/", page);
}
private void isAgain(MeizhiBean meizhiBean) {
if (!meizhiBean.getUrl().equals(bean.getUrl())) {
bean = meizhiBean;
detalPage = getDetailPage(meizhiBean.getUrl());
}
}
/**
* 获取详情(高清)
* 为了防止频繁请求被服务器拒绝,控制每次获取5张,再次传入相同值获取接下来五张
*
* @param meizhiBean
* @param p minPage = 1
* @return
*/
public Observable<List<MeizhiBean>> getDetailMeizhiList(final MeizhiBean meizhiBean, final int p) {
Observable<List<MeizhiBean>> meizhiOb = Observable.create(new Observable.OnSubscribe<List<MeizhiBean>>() {
@Override
public void call(Subscriber<? super List<MeizhiBean>> subscriber) {
isAgain(meizhiBean);
try {
int page = p - 1;
if (5 * page >= detalPage) {
subscriber.onError(new NullPointerException("没有更多的数据了"));
} else {
List<MeizhiBean> meizhiBeanList = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
MeizhiBean mbean = new MeizhiBean(bean);
Document doc = Jsoup.connect(bean.getUrl() + "/" + (i + 5 * page))
.headers(headerMap)
.get();
Element img = doc.getElementsByClass("main-image").first();
Element dataa = img.getElementsByTag("a").first();
Element data = dataa.getElementsByTag("img").first();
mbean.getImage().setImgUrl(data.attr("src"));
meizhiBeanList.add(mbean);
}
subscriber.onNext(meizhiBeanList);
subscriber.onCompleted();
}
} catch (IOException e) {
subscriber.onError(e);
}
}
});
return meizhiOb
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread());
}
/**
* 获取详情页的页数
*
* @param url
* @return
*/
private int getDetailPage(String url) {
try {
Document doc = Jsoup.connect(url)
.headers(headerMap)
.get();
Element link = doc.getElementsByClass("pagenavi").first();
Element resultLinks = link.getElementsByClass("dots").first();
Element page = resultLinks.nextElementSibling();
return Integer.parseInt(page.text());
} catch (IOException e) {
e.printStackTrace();
return 1;
}
}
/**
* 获取自拍的页数
*
* @return
*/
private int getSharePage() {
try {
Document doc = Jsoup.connect("http://www.mzitu.com/share").get();
Element link = doc.getElementsByClass("pagenavi-cm").first().getElementsByClass("page-numbers current").first();
return Integer.parseInt(link.text());
} catch (IOException e) {
e.printStackTrace();
return 1;
}
}
/**
* 自拍
*
* @param page
* @return
*/
public Observable<List<MeizhiBean>> getSharelMeizhiList(final int page) {
Logger.d("获取自拍");
Observable<List<MeizhiBean>> meizhiOb = Observable.create(new Observable.OnSubscribe<List<MeizhiBean>>() {
@Override
public void call(Subscriber<? super List<MeizhiBean>> subscriber) {
List<MeizhiBean> meizhiBeanList = new ArrayList<>();
int maxPage = getSharePage() + 1;
if (page > maxPage) {
subscriber.onNext(meizhiBeanList);
} else {
try {
Document doc = Jsoup.connect("http://www.mzitu.com/share/comment-page-" + (maxPage - page) + "#comments")
.headers(headerMap)
.get();
Element link = doc.getElementById("comments");
Elements dataList = link.getElementsByTag("li");
for (Element data : dataList) {
Element img = data.getElementsByTag("img").first();
MeizhiBean meizhiBean = new MeizhiBean();
meizhiBean.setTime(data.getElementsByTag("a").first().text());
meizhiBean.setImage(new MeizhiBean.MeiZhiImage(img.attr("src")));
meizhiBeanList.add(meizhiBean);
}
subscriber.onNext(meizhiBeanList);
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
}
}
});
return meizhiOb
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread());
}
/**
* 获取每日更新
*
* @return
*/
public Observable<List<MeizhiBean>> getAllMeizhiList() {
Observable<List<MeizhiBean>> meizhiOb = Observable.create(new Observable.OnSubscribe<List<MeizhiBean>>() {
@Override
public void call(Subscriber<? super List<MeizhiBean>> subscriber) {
List<MeizhiBean> meizhiBeanList = new ArrayList<>();
try {
Document doc = Jsoup.connect("http://www.mzitu.com/all")
.headers(headerMap)
.get();
Elements link = doc.getElementsByClass("archives");
for (Element data : link) {
for (Element d : data.getElementsByTag("a")) {
MeizhiBean meizhiBean = new MeizhiBean();
meizhiBean.setUrl(d.attr("href"));
meizhiBean.setTitle(d.text());
meizhiBeanList.add(meizhiBean);
}
}
subscriber.onNext(meizhiBeanList);
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
}
});
return meizhiOb
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread());
}
}
| chendongde310/OTAKU | data/src/main/java/lol/chendong/data/meizhi/MeizhiData.java | 2,479 | //超时时间 | line_comment | zh-cn | package lol.chendong.data.meizhi;
import com.orhanobut.logger.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* 作者:陈东 — www.renwey.com
* 日期:2016/12/23 - 14:04
* 注释:
*/
public class MeizhiData {
public static final String 最热 = "hot/";
public static final String 推荐 = "best/";
public static final String 最新 = "";
public static final String 性感 = "xinggan/";
public static final String 日本 = "japan/";
public static final String 台湾 = "taiwan/";
public static final String 清纯妹纸 = "mm/";
public static final String 搜索 = "search/";
public static final String 自拍 = "zipai";
private static MeizhiData ourInstance = new MeizhiData();
int detalPage; //详情页面数量
private int timeout = 1000 * 10; //超时 <SUF>
private MeizhiBean bean = new MeizhiBean();
private MeizhiData() {
headerMap.put("Referer","http://www.mzitu.com/");
headerMap.put("Domain-Name","mei_zi_tu_domain_name");
}
public static MeizhiData getData() {
return ourInstance;
}
Map<String ,String > headerMap = new HashMap<>();
/**
* 获取浏览图列表
*
* @param type
* @param page
* @return
*/
public Observable<List<MeizhiBean>> getRoughPicList(final String type, final int page) {
Observable<List<MeizhiBean>> meizhiOb = Observable.create(new Observable.OnSubscribe<List<MeizhiBean>>() {
@Override
public void call(Subscriber<? super List<MeizhiBean>> subscriber) {
List<MeizhiBean> meizhiBeanList = new ArrayList<>();
try {
Document doc = Jsoup.connect("http://www.mzitu.com/" + type + "page/" + page)
.header("Referer","http://www.mzitu.com/")
.header("Domain-Name","mei_zi_tu_domain_name")
.get();
Logger.d("http://www.mzitu.com/" + type + "page/" + page);
Element content = doc.getElementById("pins");
Elements dataList = content.getElementsByTag("li");
for (Element data : dataList) {
MeizhiBean mbean = new MeizhiBean();
mbean.setTime(data.getElementsByClass("time").text());
mbean.setView(data.getElementsByClass("view").text());
Element link = data.select("a").first();//查找第一个a元素
mbean.setUrl(link.attr("href"));
Element img = link.getElementsByTag("img").first();
mbean.setTitle(img.attr("alt"));
MeizhiBean.MeiZhiImage mimg = new MeizhiBean.MeiZhiImage();
mimg.setWidth(Integer.parseInt(img.attr("width")));
mimg.setHeight(Integer.parseInt(img.attr("height")));
mimg.setImgUrl(img.attr("data-original"));
mbean.setImage(mimg);
meizhiBeanList.add(mbean);
}
subscriber.onNext(meizhiBeanList);
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
}
});
return meizhiOb
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread());
}
/**
* 搜索妹子
*
* @param search
* @param page
* @return
*/
public Observable<List<MeizhiBean>> getSearchMeizhiList(final String search, final int page) {
return getRoughPicList(搜索 + search + "/", page);
}
private void isAgain(MeizhiBean meizhiBean) {
if (!meizhiBean.getUrl().equals(bean.getUrl())) {
bean = meizhiBean;
detalPage = getDetailPage(meizhiBean.getUrl());
}
}
/**
* 获取详情(高清)
* 为了防止频繁请求被服务器拒绝,控制每次获取5张,再次传入相同值获取接下来五张
*
* @param meizhiBean
* @param p minPage = 1
* @return
*/
public Observable<List<MeizhiBean>> getDetailMeizhiList(final MeizhiBean meizhiBean, final int p) {
Observable<List<MeizhiBean>> meizhiOb = Observable.create(new Observable.OnSubscribe<List<MeizhiBean>>() {
@Override
public void call(Subscriber<? super List<MeizhiBean>> subscriber) {
isAgain(meizhiBean);
try {
int page = p - 1;
if (5 * page >= detalPage) {
subscriber.onError(new NullPointerException("没有更多的数据了"));
} else {
List<MeizhiBean> meizhiBeanList = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
MeizhiBean mbean = new MeizhiBean(bean);
Document doc = Jsoup.connect(bean.getUrl() + "/" + (i + 5 * page))
.headers(headerMap)
.get();
Element img = doc.getElementsByClass("main-image").first();
Element dataa = img.getElementsByTag("a").first();
Element data = dataa.getElementsByTag("img").first();
mbean.getImage().setImgUrl(data.attr("src"));
meizhiBeanList.add(mbean);
}
subscriber.onNext(meizhiBeanList);
subscriber.onCompleted();
}
} catch (IOException e) {
subscriber.onError(e);
}
}
});
return meizhiOb
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread());
}
/**
* 获取详情页的页数
*
* @param url
* @return
*/
private int getDetailPage(String url) {
try {
Document doc = Jsoup.connect(url)
.headers(headerMap)
.get();
Element link = doc.getElementsByClass("pagenavi").first();
Element resultLinks = link.getElementsByClass("dots").first();
Element page = resultLinks.nextElementSibling();
return Integer.parseInt(page.text());
} catch (IOException e) {
e.printStackTrace();
return 1;
}
}
/**
* 获取自拍的页数
*
* @return
*/
private int getSharePage() {
try {
Document doc = Jsoup.connect("http://www.mzitu.com/share").get();
Element link = doc.getElementsByClass("pagenavi-cm").first().getElementsByClass("page-numbers current").first();
return Integer.parseInt(link.text());
} catch (IOException e) {
e.printStackTrace();
return 1;
}
}
/**
* 自拍
*
* @param page
* @return
*/
public Observable<List<MeizhiBean>> getSharelMeizhiList(final int page) {
Logger.d("获取自拍");
Observable<List<MeizhiBean>> meizhiOb = Observable.create(new Observable.OnSubscribe<List<MeizhiBean>>() {
@Override
public void call(Subscriber<? super List<MeizhiBean>> subscriber) {
List<MeizhiBean> meizhiBeanList = new ArrayList<>();
int maxPage = getSharePage() + 1;
if (page > maxPage) {
subscriber.onNext(meizhiBeanList);
} else {
try {
Document doc = Jsoup.connect("http://www.mzitu.com/share/comment-page-" + (maxPage - page) + "#comments")
.headers(headerMap)
.get();
Element link = doc.getElementById("comments");
Elements dataList = link.getElementsByTag("li");
for (Element data : dataList) {
Element img = data.getElementsByTag("img").first();
MeizhiBean meizhiBean = new MeizhiBean();
meizhiBean.setTime(data.getElementsByTag("a").first().text());
meizhiBean.setImage(new MeizhiBean.MeiZhiImage(img.attr("src")));
meizhiBeanList.add(meizhiBean);
}
subscriber.onNext(meizhiBeanList);
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
}
}
});
return meizhiOb
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread());
}
/**
* 获取每日更新
*
* @return
*/
public Observable<List<MeizhiBean>> getAllMeizhiList() {
Observable<List<MeizhiBean>> meizhiOb = Observable.create(new Observable.OnSubscribe<List<MeizhiBean>>() {
@Override
public void call(Subscriber<? super List<MeizhiBean>> subscriber) {
List<MeizhiBean> meizhiBeanList = new ArrayList<>();
try {
Document doc = Jsoup.connect("http://www.mzitu.com/all")
.headers(headerMap)
.get();
Elements link = doc.getElementsByClass("archives");
for (Element data : link) {
for (Element d : data.getElementsByTag("a")) {
MeizhiBean meizhiBean = new MeizhiBean();
meizhiBean.setUrl(d.attr("href"));
meizhiBean.setTitle(d.text());
meizhiBeanList.add(meizhiBean);
}
}
subscriber.onNext(meizhiBeanList);
subscriber.onCompleted();
} catch (IOException e) {
subscriber.onError(e);
}
}
});
return meizhiOb
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.newThread());
}
}
| false | 2,223 | 4 | 2,479 | 3 | 2,642 | 3 | 2,479 | 3 | 3,078 | 5 | false | false | false | false | false | true |
20073_22 |
/**
* Created by 0048104325 on 2017/7/14.
* desc : 正则相关常量
*/
public interface RegexConstants {
/**
* 正则:手机号(简单)
*/
String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$";
/**
* 正则:手机号(精确)
* <p>移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188</p>
* <p>联通:130、131、132、145、155、156、171、175、176、185、186</p>
* <p>电信:133、153、173、177、180、181、189</p>
* <p>全球星:1349</p>
* <p>虚拟运营商:170</p>
*/
String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,1,3,5-8])|(18[0-9])|(147))\\d{8}$";
/**
* 正则:电话号码
*/
String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";
/**
* 正则:身份证号码15位
*/
String REGEX_ID_CARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
/**
* 正则:身份证号码18位
*/
String REGEX_ID_CARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$";
/**
* 正则:邮箱
*/
String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
/**
* 正则:URL
*/
String REGEX_URL = "[a-zA-z]+://[^\\s]*";
/**
* 正则:汉字
*/
String REGEX_ZH = "^[\\u4e00-\\u9fa5]+$";
/**
* 正则:用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位
*/
String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$";
/**
* 正则:yyyy-MM-dd格式的日期校验,已考虑平闰年
*/
String REGEX_DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
/**
* 正则:IP地址
*/
String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
///////////////////////////////////////////////////////////////////////////
// 以下摘自http://tool.oschina.net/regex
///////////////////////////////////////////////////////////////////////////
/**
* 正则:双字节字符(包括汉字在内)
*/
String REGEX_DOUBLE_BYTE_CHAR = "[^\\x00-\\xff]";
/**
* 正则:空白行
*/
String REGEX_BLANK_LINE = "\\n\\s*\\r";
/**
* 正则:QQ号
*/
String REGEX_TENCENT_NUM = "[1-9][0-9]{4,}";
/**
* 正则:中国邮政编码
*/
String REGEX_ZIP_CODE = "[1-9]\\d{5}(?!\\d)";
/**
* 正则:正整数
*/
String REGEX_POSITIVE_INTEGER = "^[1-9]\\d*$";
/**
* 正则:负整数
*/
String REGEX_NEGATIVE_INTEGER = "^-[1-9]\\d*$";
/**
* 正则:整数
*/
String REGEX_INTEGER = "^-?[1-9]\\d*$";
/**
* 正则:非负整数(正整数 + 0)
*/
String REGEX_NOT_NEGATIVE_INTEGER = "^[1-9]\\d*|0$";
/**
* 正则:非正整数(负整数 + 0)
*/
String REGEX_NOT_POSITIVE_INTEGER = "^-[1-9]\\d*|0$";
/**
* 正则:正浮点数
*/
String REGEX_POSITIVE_FLOAT = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$";
/**
* 正则:负浮点数
*/
String REGEX_NEGATIVE_FLOAT = "^-[1-9]\\d*\\.\\d*|-0\\.\\d*[1-9]\\d*$";
/**
* 正则:车牌号码
*/
String REGEX_CAR_ID = "\\d{5}$|[A-Z]{1}\\d{4}|\\d{1}[A-Z]{1}\\d{3}|[A-Z]{2}\\d{3}$";
}
| cheng2016/AndroidUtil | util/RegexConstants.java | 1,582 | /**
* 正则:非正整数(负整数 + 0)
*/ | block_comment | zh-cn |
/**
* Created by 0048104325 on 2017/7/14.
* desc : 正则相关常量
*/
public interface RegexConstants {
/**
* 正则:手机号(简单)
*/
String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$";
/**
* 正则:手机号(精确)
* <p>移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188</p>
* <p>联通:130、131、132、145、155、156、171、175、176、185、186</p>
* <p>电信:133、153、173、177、180、181、189</p>
* <p>全球星:1349</p>
* <p>虚拟运营商:170</p>
*/
String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,1,3,5-8])|(18[0-9])|(147))\\d{8}$";
/**
* 正则:电话号码
*/
String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";
/**
* 正则:身份证号码15位
*/
String REGEX_ID_CARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
/**
* 正则:身份证号码18位
*/
String REGEX_ID_CARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$";
/**
* 正则:邮箱
*/
String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
/**
* 正则:URL
*/
String REGEX_URL = "[a-zA-z]+://[^\\s]*";
/**
* 正则:汉字
*/
String REGEX_ZH = "^[\\u4e00-\\u9fa5]+$";
/**
* 正则:用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位
*/
String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$";
/**
* 正则:yyyy-MM-dd格式的日期校验,已考虑平闰年
*/
String REGEX_DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
/**
* 正则:IP地址
*/
String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
///////////////////////////////////////////////////////////////////////////
// 以下摘自http://tool.oschina.net/regex
///////////////////////////////////////////////////////////////////////////
/**
* 正则:双字节字符(包括汉字在内)
*/
String REGEX_DOUBLE_BYTE_CHAR = "[^\\x00-\\xff]";
/**
* 正则:空白行
*/
String REGEX_BLANK_LINE = "\\n\\s*\\r";
/**
* 正则:QQ号
*/
String REGEX_TENCENT_NUM = "[1-9][0-9]{4,}";
/**
* 正则:中国邮政编码
*/
String REGEX_ZIP_CODE = "[1-9]\\d{5}(?!\\d)";
/**
* 正则:正整数
*/
String REGEX_POSITIVE_INTEGER = "^[1-9]\\d*$";
/**
* 正则:负整数
*/
String REGEX_NEGATIVE_INTEGER = "^-[1-9]\\d*$";
/**
* 正则:整数
*/
String REGEX_INTEGER = "^-?[1-9]\\d*$";
/**
* 正则:非负整数(正整数 + 0)
*/
String REGEX_NOT_NEGATIVE_INTEGER = "^[1-9]\\d*|0$";
/**
* 正则: <SUF>*/
String REGEX_NOT_POSITIVE_INTEGER = "^-[1-9]\\d*|0$";
/**
* 正则:正浮点数
*/
String REGEX_POSITIVE_FLOAT = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$";
/**
* 正则:负浮点数
*/
String REGEX_NEGATIVE_FLOAT = "^-[1-9]\\d*\\.\\d*|-0\\.\\d*[1-9]\\d*$";
/**
* 正则:车牌号码
*/
String REGEX_CAR_ID = "\\d{5}$|[A-Z]{1}\\d{4}|\\d{1}[A-Z]{1}\\d{3}|[A-Z]{2}\\d{3}$";
}
| false | 1,523 | 21 | 1,582 | 19 | 1,630 | 20 | 1,582 | 19 | 1,942 | 29 | false | false | false | false | false | true |
31254_3 | package newtouch.cn.downmenu.fragment;
/**
* @创建者 Administrator
* @创建时间 2016/4/11 10:39
* @描述 ${TODO}
* @更新者 $Author$
* @更新时间 $Date$
* @更新描述 ${TODO}
*/
public class AddressFragemnt extends BaseFragment {
String catalogues[][] = new String[][]{
new String[]{"全部美食", "本帮江浙菜", "川菜", "粤菜", "湘菜", "东北菜", "台湾菜", "新疆/清真", "素菜", "火锅", "自助餐", "小吃快餐", "日本", "韩国料理",
"东南亚菜", "西餐", "面包甜点", "其他"},
new String[]{"全部休闲娱乐", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部购物", "综合商场", "服饰鞋包", "运动户外", "珠宝饰品", "化妆品", "数码家电", "亲子购物", "家居建材"
, "书店", "书店", "眼镜店", "特色集市", "更多购物场所", "食品茶酒", "超市/便利店", "药店"},
new String[]{"全部休闲娱乐", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全", "咖啡厅", "酒吧", "茶馆", "KTV", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部", "咖啡厅", "酒吧", "茶馆", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部休", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部休闲", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部休闲娱", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏"},
new String[]{"全部休闲娱乐", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部休闲aaa", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏"},
};
String catalogues1[] = new String[]{"全部频道", "美食", "休闲娱乐", "购物", "酒店", "丽人", "运动健身", "结婚", "亲子", "爱车", "生活服务"};
/**--------------------------------加载数据------------------------------**/
@Override
protected String[][] setCatalogues2() {
//开线程异步加载数据
return catalogues;
}
@Override
protected String[] setCatalogues1() {
return catalogues1;
}
/**--------------------------------设置页面------------------------------**/
}
| chengcnaplex/DownMenu | app/src/main/java/newtouch/cn/downmenu/fragment/AddressFragemnt.java | 1,396 | /**--------------------------------设置页面------------------------------**/ | block_comment | zh-cn | package newtouch.cn.downmenu.fragment;
/**
* @创建者 Administrator
* @创建时间 2016/4/11 10:39
* @描述 ${TODO}
* @更新者 $Author$
* @更新时间 $Date$
* @更新描述 ${TODO}
*/
public class AddressFragemnt extends BaseFragment {
String catalogues[][] = new String[][]{
new String[]{"全部美食", "本帮江浙菜", "川菜", "粤菜", "湘菜", "东北菜", "台湾菜", "新疆/清真", "素菜", "火锅", "自助餐", "小吃快餐", "日本", "韩国料理",
"东南亚菜", "西餐", "面包甜点", "其他"},
new String[]{"全部休闲娱乐", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部购物", "综合商场", "服饰鞋包", "运动户外", "珠宝饰品", "化妆品", "数码家电", "亲子购物", "家居建材"
, "书店", "书店", "眼镜店", "特色集市", "更多购物场所", "食品茶酒", "超市/便利店", "药店"},
new String[]{"全部休闲娱乐", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全", "咖啡厅", "酒吧", "茶馆", "KTV", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部", "咖啡厅", "酒吧", "茶馆", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部休", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部休闲", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部休闲娱", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏"},
new String[]{"全部休闲娱乐", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏", "更多休闲娱乐"},
new String[]{"全部休闲aaa", "咖啡厅", "酒吧", "茶馆", "KTV", "电影院", "游乐游艺", "公园", "景点/郊游", "洗浴", "足浴按摩", "文化艺术",
"DIY手工坊", "桌球馆", "桌面游戏"},
};
String catalogues1[] = new String[]{"全部频道", "美食", "休闲娱乐", "购物", "酒店", "丽人", "运动健身", "结婚", "亲子", "爱车", "生活服务"};
/**--------------------------------加载数据------------------------------**/
@Override
protected String[][] setCatalogues2() {
//开线程异步加载数据
return catalogues;
}
@Override
protected String[] setCatalogues1() {
return catalogues1;
}
/**--- <SUF>*/
}
| false | 989 | 7 | 1,396 | 6 | 1,062 | 8 | 1,396 | 6 | 1,917 | 12 | false | false | false | false | false | true |
5798_4 | /*
* Copyright 2018-present yangguo@outlook.com
*
* 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 info.yangguo.waf;
import com.google.common.collect.Lists;
import info.yangguo.waf.config.ContextHolder;
import info.yangguo.waf.model.ForwardConfig;
import info.yangguo.waf.model.WeightedRoundRobinScheduling;
import info.yangguo.waf.request.*;
import info.yangguo.waf.response.HttpResponseFilter;
import info.yangguo.waf.util.ResponseUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.*;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.littleshoot.proxy.HttpFiltersAdapter;
import org.littleshoot.proxy.impl.ClientToProxyConnection;
import org.littleshoot.proxy.impl.ProxyConnection;
import org.littleshoot.proxy.impl.ProxyToServerConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
/**
* @author:杨果
* @date:2017/4/17 下午2:12
* <p>
* Description:
*/
public class HttpFilterAdapterImpl extends HttpFiltersAdapter {
private static Logger logger = LoggerFactory.getLogger(HttpFilterAdapterImpl.class);
public HttpFilterAdapterImpl(HttpRequest originalRequest, ChannelHandlerContext ctx) {
super(originalRequest, ctx);
}
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
//放到里面主要是为了线程安全,由于一条链路不断的情况下,多个请求过来都在一个ClientToProxy线程中,但是对于Filter来说确实多线程处理的,
//不放在里面就会报对List操作的操作异常。
List<RequestFilter> requestFilters = Lists.newArrayList();
//注意顺序
requestFilters.add(new RewriteFilter());
requestFilters.add(new RedirectFilter());
requestFilters.add(new SecurityFilter());
requestFilters.add(new TranslateFilter());
HttpResponse response = null;
for (RequestFilter filter : requestFilters) {
try {
response = filter.doFilter(originalRequest, httpObject);
} catch (Exception e) {
logger.warn("request client to proxy failed", e);
response = ResponseUtil.createResponse(HttpResponseStatus.BAD_GATEWAY, originalRequest, null);
}
if (response != null) {
break;
}
}
return response;
}
@Override
public void proxyToServerResolutionSucceeded(String serverHostAndPort,
InetSocketAddress resolvedRemoteAddress) {
if (resolvedRemoteAddress == null) {
//在使用 Channel 写数据之前,建议使用 isWritable() 方法来判断一下当前 ChannelOutboundBuffer 里的写缓存水位,防止 OOM 发生。不过实践下来,正常的通信过程不太会 OOM,但当网络环境不好,同时传输报文很大时,确实会出现限流的情况。
if (ctx.channel().isWritable()) {
ctx.writeAndFlush(ResponseUtil.createResponse(HttpResponseStatus.BAD_GATEWAY, originalRequest, null));
}
}
}
/**
* <b>Important:</b>:这个只能用在HTTP1.1上
* 浏览器->Nginx->Waf->Tomcat,如果Nginx->Waf是Http1.0,那么Waf->Tomcat之间的链路会自动关闭,而关闭之时,Waf有可能还没有将报文返回给Nginx,所以
* Nginx上会有大量的<b>upstream prematurely closed connection while reading upstream</b>异常!这样设计的前提是,waf->server的链接关闭只有两种情况
* <p>
* 1. idle超时关闭。
* <p>
* 2. 异常关闭,例如大文件上传超过tomcat中程序允许上传的最大值,并且tomcat未设置maxswallow时,从而导致tomcat发送RST。
* <p>
* 代理链接的是两个或多个使用相同协议的应用程序,此处的相同非常重要,所以中间最少别随意跟换协议!!
*/
@Override
public void proxyToServerRequestSending() {
ClientToProxyConnection clientToProxyConnection = (ClientToProxyConnection) ctx.handler();
ProxyConnection proxyConnection = clientToProxyConnection.getProxyToServerConnection();
logger.debug("client channel:{}-{}", clientToProxyConnection.getChannel().localAddress().toString(), clientToProxyConnection.getChannel().remoteAddress().toString());
logger.debug("server channel:{}-{}", proxyConnection.getChannel().localAddress().toString(), proxyConnection.getChannel().remoteAddress().toString());
proxyConnection.getChannel().closeFuture().addListener(new GenericFutureListener() {
@Override
public void operationComplete(Future future) {
if (clientToProxyConnection.getChannel().isActive()) {
logger.debug("channel:{}-{} will be closed", clientToProxyConnection.getChannel().localAddress().toString(), clientToProxyConnection.getChannel().remoteAddress().toString());
clientToProxyConnection.getChannel().close();
} else {
logger.debug("channel:{}-{} has been closed", clientToProxyConnection.getChannel().localAddress().toString(), clientToProxyConnection.getChannel().remoteAddress().toString());
}
}
});
}
@Override
public HttpObject proxyToClientResponse(HttpObject httpObject) {
HttpResponseFilter httpResponseFilter = new HttpResponseFilter();
if (httpObject instanceof HttpResponse) {
try {
httpResponseFilter.doFilter(originalRequest, (HttpResponse) httpObject, ContextHolder.getClusterService());
} catch (Exception e) {
logger.error("response filter failed", e.getCause());
}
}
return httpObject;
}
@Override
public void proxyToServerConnectionFailed() {
if ("on".equals(Constant.wafConfs.get("waf.lb"))) {
try {
ClientToProxyConnection clientToProxyConnection = (ClientToProxyConnection) ctx.handler();
ProxyToServerConnection proxyToServerConnection = clientToProxyConnection.getProxyToServerConnection();
String serverHostAndPort = proxyToServerConnection.getServerHostAndPort().replace(":", "_");
String remoteHostName = proxyToServerConnection.getRemoteAddress().getAddress().getHostAddress();
int remoteHostPort = proxyToServerConnection.getRemoteAddress().getPort();
WeightedRoundRobinScheduling weightedRoundRobinScheduling = ContextHolder.getClusterService().getUpstreamConfig().get(serverHostAndPort);
weightedRoundRobinScheduling.getUnhealthilyServerConfigs().add(weightedRoundRobinScheduling.getServersMap().get(remoteHostName + "_" + remoteHostPort));
weightedRoundRobinScheduling.getHealthilyServerConfigs().remove(weightedRoundRobinScheduling.getServersMap().get(remoteHostName + "_" + remoteHostPort));
} catch (Exception e) {
logger.error("connection of proxy->server is failed", e);
}
}
}
@Override
public void proxyToServerConnectionSucceeded(final ChannelHandlerContext serverCtx) {
Map<String, ForwardConfig> forwardConfigMap = ContextHolder.getClusterService().getTranslateConfigs();
//forward的时候牵涉到协议转换,所以必须要是FullHttpRequest,所以我们必须要使用aggregator
if (!forwardConfigMap.containsKey(originalRequest.headers().getAsString(WafHttpHeaderNames.X_WAF_ROUTE))) {
ChannelPipeline pipeline = serverCtx.pipeline();
//当没有修改getMaximumResponseBufferSizeInBytes中buffer默认的大小时,下面两个handler是不存在的
if (pipeline.get("inflater") != null) {
pipeline.remove("inflater");
}
if (pipeline.get("aggregator") != null) {
pipeline.remove("aggregator");
}
}
super.proxyToServerConnectionSucceeded(serverCtx);
}
}
| chengdedeng/waf | src/main/java/info/yangguo/waf/HttpFilterAdapterImpl.java | 1,945 | //注意顺序 | line_comment | zh-cn | /*
* Copyright 2018-present yangguo@outlook.com
*
* 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 info.yangguo.waf;
import com.google.common.collect.Lists;
import info.yangguo.waf.config.ContextHolder;
import info.yangguo.waf.model.ForwardConfig;
import info.yangguo.waf.model.WeightedRoundRobinScheduling;
import info.yangguo.waf.request.*;
import info.yangguo.waf.response.HttpResponseFilter;
import info.yangguo.waf.util.ResponseUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.*;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import org.littleshoot.proxy.HttpFiltersAdapter;
import org.littleshoot.proxy.impl.ClientToProxyConnection;
import org.littleshoot.proxy.impl.ProxyConnection;
import org.littleshoot.proxy.impl.ProxyToServerConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.Map;
/**
* @author:杨果
* @date:2017/4/17 下午2:12
* <p>
* Description:
*/
public class HttpFilterAdapterImpl extends HttpFiltersAdapter {
private static Logger logger = LoggerFactory.getLogger(HttpFilterAdapterImpl.class);
public HttpFilterAdapterImpl(HttpRequest originalRequest, ChannelHandlerContext ctx) {
super(originalRequest, ctx);
}
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
//放到里面主要是为了线程安全,由于一条链路不断的情况下,多个请求过来都在一个ClientToProxy线程中,但是对于Filter来说确实多线程处理的,
//不放在里面就会报对List操作的操作异常。
List<RequestFilter> requestFilters = Lists.newArrayList();
//注意 <SUF>
requestFilters.add(new RewriteFilter());
requestFilters.add(new RedirectFilter());
requestFilters.add(new SecurityFilter());
requestFilters.add(new TranslateFilter());
HttpResponse response = null;
for (RequestFilter filter : requestFilters) {
try {
response = filter.doFilter(originalRequest, httpObject);
} catch (Exception e) {
logger.warn("request client to proxy failed", e);
response = ResponseUtil.createResponse(HttpResponseStatus.BAD_GATEWAY, originalRequest, null);
}
if (response != null) {
break;
}
}
return response;
}
@Override
public void proxyToServerResolutionSucceeded(String serverHostAndPort,
InetSocketAddress resolvedRemoteAddress) {
if (resolvedRemoteAddress == null) {
//在使用 Channel 写数据之前,建议使用 isWritable() 方法来判断一下当前 ChannelOutboundBuffer 里的写缓存水位,防止 OOM 发生。不过实践下来,正常的通信过程不太会 OOM,但当网络环境不好,同时传输报文很大时,确实会出现限流的情况。
if (ctx.channel().isWritable()) {
ctx.writeAndFlush(ResponseUtil.createResponse(HttpResponseStatus.BAD_GATEWAY, originalRequest, null));
}
}
}
/**
* <b>Important:</b>:这个只能用在HTTP1.1上
* 浏览器->Nginx->Waf->Tomcat,如果Nginx->Waf是Http1.0,那么Waf->Tomcat之间的链路会自动关闭,而关闭之时,Waf有可能还没有将报文返回给Nginx,所以
* Nginx上会有大量的<b>upstream prematurely closed connection while reading upstream</b>异常!这样设计的前提是,waf->server的链接关闭只有两种情况
* <p>
* 1. idle超时关闭。
* <p>
* 2. 异常关闭,例如大文件上传超过tomcat中程序允许上传的最大值,并且tomcat未设置maxswallow时,从而导致tomcat发送RST。
* <p>
* 代理链接的是两个或多个使用相同协议的应用程序,此处的相同非常重要,所以中间最少别随意跟换协议!!
*/
@Override
public void proxyToServerRequestSending() {
ClientToProxyConnection clientToProxyConnection = (ClientToProxyConnection) ctx.handler();
ProxyConnection proxyConnection = clientToProxyConnection.getProxyToServerConnection();
logger.debug("client channel:{}-{}", clientToProxyConnection.getChannel().localAddress().toString(), clientToProxyConnection.getChannel().remoteAddress().toString());
logger.debug("server channel:{}-{}", proxyConnection.getChannel().localAddress().toString(), proxyConnection.getChannel().remoteAddress().toString());
proxyConnection.getChannel().closeFuture().addListener(new GenericFutureListener() {
@Override
public void operationComplete(Future future) {
if (clientToProxyConnection.getChannel().isActive()) {
logger.debug("channel:{}-{} will be closed", clientToProxyConnection.getChannel().localAddress().toString(), clientToProxyConnection.getChannel().remoteAddress().toString());
clientToProxyConnection.getChannel().close();
} else {
logger.debug("channel:{}-{} has been closed", clientToProxyConnection.getChannel().localAddress().toString(), clientToProxyConnection.getChannel().remoteAddress().toString());
}
}
});
}
@Override
public HttpObject proxyToClientResponse(HttpObject httpObject) {
HttpResponseFilter httpResponseFilter = new HttpResponseFilter();
if (httpObject instanceof HttpResponse) {
try {
httpResponseFilter.doFilter(originalRequest, (HttpResponse) httpObject, ContextHolder.getClusterService());
} catch (Exception e) {
logger.error("response filter failed", e.getCause());
}
}
return httpObject;
}
@Override
public void proxyToServerConnectionFailed() {
if ("on".equals(Constant.wafConfs.get("waf.lb"))) {
try {
ClientToProxyConnection clientToProxyConnection = (ClientToProxyConnection) ctx.handler();
ProxyToServerConnection proxyToServerConnection = clientToProxyConnection.getProxyToServerConnection();
String serverHostAndPort = proxyToServerConnection.getServerHostAndPort().replace(":", "_");
String remoteHostName = proxyToServerConnection.getRemoteAddress().getAddress().getHostAddress();
int remoteHostPort = proxyToServerConnection.getRemoteAddress().getPort();
WeightedRoundRobinScheduling weightedRoundRobinScheduling = ContextHolder.getClusterService().getUpstreamConfig().get(serverHostAndPort);
weightedRoundRobinScheduling.getUnhealthilyServerConfigs().add(weightedRoundRobinScheduling.getServersMap().get(remoteHostName + "_" + remoteHostPort));
weightedRoundRobinScheduling.getHealthilyServerConfigs().remove(weightedRoundRobinScheduling.getServersMap().get(remoteHostName + "_" + remoteHostPort));
} catch (Exception e) {
logger.error("connection of proxy->server is failed", e);
}
}
}
@Override
public void proxyToServerConnectionSucceeded(final ChannelHandlerContext serverCtx) {
Map<String, ForwardConfig> forwardConfigMap = ContextHolder.getClusterService().getTranslateConfigs();
//forward的时候牵涉到协议转换,所以必须要是FullHttpRequest,所以我们必须要使用aggregator
if (!forwardConfigMap.containsKey(originalRequest.headers().getAsString(WafHttpHeaderNames.X_WAF_ROUTE))) {
ChannelPipeline pipeline = serverCtx.pipeline();
//当没有修改getMaximumResponseBufferSizeInBytes中buffer默认的大小时,下面两个handler是不存在的
if (pipeline.get("inflater") != null) {
pipeline.remove("inflater");
}
if (pipeline.get("aggregator") != null) {
pipeline.remove("aggregator");
}
}
super.proxyToServerConnectionSucceeded(serverCtx);
}
}
| false | 1,760 | 3 | 1,945 | 3 | 1,985 | 3 | 1,945 | 3 | 2,513 | 7 | false | false | false | false | false | true |
63113_2 | import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class L464_Can_I_Win {
/*
1 <= maxChoosableInteger <= 20
0 <= desiredTotal <= 300
*/
Map<Integer, Boolean> map = new HashMap<>();
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
if (desiredTotal <= 0)
return true;
int sum = (maxChoosableInteger + 1) * maxChoosableInteger / 2;
if (sum < desiredTotal)
return false;
boolean[] selected = new boolean[maxChoosableInteger + 1];
return helper(desiredTotal, selected);
}
/*
表示基于desiredTotal和selected的状态,当前用户是否能赢
回溯搜索,遍历selected数组,分别尝试每一个数字,看当前是否可以赢
*/
public boolean helper(int desiredTotal, boolean[] selected) {
if (desiredTotal <= 0)
return false;
int symbol = format(selected);
if (map.containsKey(symbol)) {
return map.get(symbol);
}
int size = selected.length;
for (int i = 1; i < size; i++) {
if (!selected[i]) {
selected[i] = true;
if (!helper(desiredTotal - i, selected)) {
selected[i] = false;
map.put(symbol, true);
return true;
}
selected[i] = false;
}
}
map.put(symbol, false);
return false;
}
/*
将数组二进制化
1-5,选择1和3
则00101
*/
public int format(boolean[] selected) {
int symbol = 0;
for (boolean select : selected) {
symbol <<= 1;
if (select) {
symbol |= 1;
}
}
return symbol;
}
public boolean canIWin2(int maxChoosableInteger, int desiredTotal) {
if (desiredTotal <= 0) {
return true;
}
if ((maxChoosableInteger * (maxChoosableInteger + 1)) / 2 < desiredTotal) {
return false; // Sum of all numbers is less than desiredTotal
}
return canIWin(0, maxChoosableInteger, desiredTotal, new Boolean[1 << maxChoosableInteger]);
}
private boolean canIWin(int usedNumbers, int mXN, int total, Boolean[] memo) {
if (memo[usedNumbers] != null) {
return memo[usedNumbers];
}
for (int i = 1; i <= mXN; i++) {
int currentMask = 1 << (i - 1);
if ((usedNumbers & currentMask) == 0) { // Number i not used
if (i >= total
|| !canIWin(usedNumbers | currentMask, mXN, total - i, memo)) {
memo[usedNumbers] = true;
return true;
}
}
}
memo[usedNumbers] = false;
return false;
}
/*
超时,应该是Arrays.toString(state)导致
*/
public boolean canIWin3(int maxChoosableInteger, int desiredTotal) {
if (desiredTotal <= 0) {
return true;
}
if ((1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal) {
return false;
}
int[] state = new int[maxChoosableInteger + 1];
Map<String, Boolean> map = new HashMap<>();
return helper(maxChoosableInteger, desiredTotal, state, map);
}
private boolean helper(int maxChoosableInteger, int desiredTotal, int[] state, Map<String, Boolean> map) {
String curtState = Arrays.toString(state);
if (map.containsKey(curtState)) {
return map.get(curtState);
}
for (int i = 1; i < state.length; i++) {
if (state[i] == 1) {
continue;
}
state[i] = 1;
if (desiredTotal - i <= 0 || !helper(maxChoosableInteger, desiredTotal - i, state, map)) {
map.put(curtState, true);
state[i] = 0;
return true;
}
state[i] = 0;
}
map.put(curtState, false);
return false;
}
public static void main(String[] args) {
L464_Can_I_Win s = new L464_Can_I_Win();
long sysDate1 = System.currentTimeMillis();
int maxChoosableInteger = 10;
int desiredTotal = 11;
boolean res = s.canIWin(maxChoosableInteger, desiredTotal);
System.out.println(res);
long sysDate2 = System.currentTimeMillis();
System.out.println("\ntime ");
System.out.print(sysDate2 - sysDate1);
}
} | chenglingli/LeetCodeSolution | src/L464_Can_I_Win.java | 1,160 | /*
将数组二进制化
1-5,选择1和3
则00101
*/ | block_comment | zh-cn | import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
public class L464_Can_I_Win {
/*
1 <= maxChoosableInteger <= 20
0 <= desiredTotal <= 300
*/
Map<Integer, Boolean> map = new HashMap<>();
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
if (desiredTotal <= 0)
return true;
int sum = (maxChoosableInteger + 1) * maxChoosableInteger / 2;
if (sum < desiredTotal)
return false;
boolean[] selected = new boolean[maxChoosableInteger + 1];
return helper(desiredTotal, selected);
}
/*
表示基于desiredTotal和selected的状态,当前用户是否能赢
回溯搜索,遍历selected数组,分别尝试每一个数字,看当前是否可以赢
*/
public boolean helper(int desiredTotal, boolean[] selected) {
if (desiredTotal <= 0)
return false;
int symbol = format(selected);
if (map.containsKey(symbol)) {
return map.get(symbol);
}
int size = selected.length;
for (int i = 1; i < size; i++) {
if (!selected[i]) {
selected[i] = true;
if (!helper(desiredTotal - i, selected)) {
selected[i] = false;
map.put(symbol, true);
return true;
}
selected[i] = false;
}
}
map.put(symbol, false);
return false;
}
/*
将数组 <SUF>*/
public int format(boolean[] selected) {
int symbol = 0;
for (boolean select : selected) {
symbol <<= 1;
if (select) {
symbol |= 1;
}
}
return symbol;
}
public boolean canIWin2(int maxChoosableInteger, int desiredTotal) {
if (desiredTotal <= 0) {
return true;
}
if ((maxChoosableInteger * (maxChoosableInteger + 1)) / 2 < desiredTotal) {
return false; // Sum of all numbers is less than desiredTotal
}
return canIWin(0, maxChoosableInteger, desiredTotal, new Boolean[1 << maxChoosableInteger]);
}
private boolean canIWin(int usedNumbers, int mXN, int total, Boolean[] memo) {
if (memo[usedNumbers] != null) {
return memo[usedNumbers];
}
for (int i = 1; i <= mXN; i++) {
int currentMask = 1 << (i - 1);
if ((usedNumbers & currentMask) == 0) { // Number i not used
if (i >= total
|| !canIWin(usedNumbers | currentMask, mXN, total - i, memo)) {
memo[usedNumbers] = true;
return true;
}
}
}
memo[usedNumbers] = false;
return false;
}
/*
超时,应该是Arrays.toString(state)导致
*/
public boolean canIWin3(int maxChoosableInteger, int desiredTotal) {
if (desiredTotal <= 0) {
return true;
}
if ((1 + maxChoosableInteger) * maxChoosableInteger / 2 < desiredTotal) {
return false;
}
int[] state = new int[maxChoosableInteger + 1];
Map<String, Boolean> map = new HashMap<>();
return helper(maxChoosableInteger, desiredTotal, state, map);
}
private boolean helper(int maxChoosableInteger, int desiredTotal, int[] state, Map<String, Boolean> map) {
String curtState = Arrays.toString(state);
if (map.containsKey(curtState)) {
return map.get(curtState);
}
for (int i = 1; i < state.length; i++) {
if (state[i] == 1) {
continue;
}
state[i] = 1;
if (desiredTotal - i <= 0 || !helper(maxChoosableInteger, desiredTotal - i, state, map)) {
map.put(curtState, true);
state[i] = 0;
return true;
}
state[i] = 0;
}
map.put(curtState, false);
return false;
}
public static void main(String[] args) {
L464_Can_I_Win s = new L464_Can_I_Win();
long sysDate1 = System.currentTimeMillis();
int maxChoosableInteger = 10;
int desiredTotal = 11;
boolean res = s.canIWin(maxChoosableInteger, desiredTotal);
System.out.println(res);
long sysDate2 = System.currentTimeMillis();
System.out.println("\ntime ");
System.out.print(sysDate2 - sysDate1);
}
} | false | 1,124 | 32 | 1,160 | 26 | 1,296 | 29 | 1,160 | 26 | 1,413 | 34 | false | false | false | false | false | true |
56336_8 | package com.spring.common.utils;
/**
* @Author 施成
* @Date 2018/2/11
* @time 0:50
* @Describe:
*/
public class Constants {
public static class ResponseCode {
public static final int success = 0;
public static final int error = 1;
}
public static class Regular {
public static final String onlineUser = "onlineUser";
}
public static class isAdmin{
public static final int isRoleAdmin= 0;
public static final int notRolwAdmin =1;
}
public static class DateTimeFilter{
public static final Integer count= null;
public static final Integer today = -1;
public static final Integer week = -7;
public static final Integer month = -30;
public static final Integer sixMonth = -180;
public static final Integer year = -365;
}
//设置HR部门ID常量
public static String DEPT_HR_ID = "126108720Q29700F";
//判断新插入的用户信息是否为管理员账户
public static boolean IS_USER_ADMIN = true;
public static boolean NOT_USER_ADMIN = false;
//设置信息的状态 0-异常 1-正常
public static Integer IS_STATUS = 1;
public static Integer NOT_STATUS = 0;
//设置普通员工的UUID常量
public static String ROLE_STAFF = "126304SL3U29700A";
public static class AttendConstants{
/**
* 中午十二点,判定上下午
*/
public static final Integer NOON_HOUR = 12;
public static final Integer NOON_MINUTE = 00;
/**
* 早晚上班时间判定
*/
public static final Integer MORNING_HOUR = 9;
public static final Integer MORNING_MINUTE = 00;
public static final Integer EVENING_HOUR = 17;
public static final Integer EVENING_MINUTE = 00;
/**
* 缺勤一整天
*/
public static final Integer ABSENCE_DAY = 480;
/**
* 考勤状态
*/
public static final Integer ATTEND_STATUS_ABNORMAL = 0; //异常
public static final Integer ATTEND_STATUS_NORMAL = 1; //正常
}
}
| chengshi2017/RBACAdmin | src/main/java/com/spring/common/utils/Constants.java | 563 | /**
* 考勤状态
*/ | block_comment | zh-cn | package com.spring.common.utils;
/**
* @Author 施成
* @Date 2018/2/11
* @time 0:50
* @Describe:
*/
public class Constants {
public static class ResponseCode {
public static final int success = 0;
public static final int error = 1;
}
public static class Regular {
public static final String onlineUser = "onlineUser";
}
public static class isAdmin{
public static final int isRoleAdmin= 0;
public static final int notRolwAdmin =1;
}
public static class DateTimeFilter{
public static final Integer count= null;
public static final Integer today = -1;
public static final Integer week = -7;
public static final Integer month = -30;
public static final Integer sixMonth = -180;
public static final Integer year = -365;
}
//设置HR部门ID常量
public static String DEPT_HR_ID = "126108720Q29700F";
//判断新插入的用户信息是否为管理员账户
public static boolean IS_USER_ADMIN = true;
public static boolean NOT_USER_ADMIN = false;
//设置信息的状态 0-异常 1-正常
public static Integer IS_STATUS = 1;
public static Integer NOT_STATUS = 0;
//设置普通员工的UUID常量
public static String ROLE_STAFF = "126304SL3U29700A";
public static class AttendConstants{
/**
* 中午十二点,判定上下午
*/
public static final Integer NOON_HOUR = 12;
public static final Integer NOON_MINUTE = 00;
/**
* 早晚上班时间判定
*/
public static final Integer MORNING_HOUR = 9;
public static final Integer MORNING_MINUTE = 00;
public static final Integer EVENING_HOUR = 17;
public static final Integer EVENING_MINUTE = 00;
/**
* 缺勤一整天
*/
public static final Integer ABSENCE_DAY = 480;
/**
* 考勤状 <SUF>*/
public static final Integer ATTEND_STATUS_ABNORMAL = 0; //异常
public static final Integer ATTEND_STATUS_NORMAL = 1; //正常
}
}
| false | 533 | 11 | 563 | 10 | 587 | 10 | 563 | 10 | 709 | 16 | false | false | false | false | false | true |
47591_0 | package com.cheng.sample;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.cheng.channel.Channel;
import com.cheng.channel.ChannelView;
import com.cheng.channel.ViewHolder;
import com.cheng.channel.adapter.BaseStyleAdapter;
import com.cheng.channel.adapter.ChannelListenerAdapter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
public class CustomChannelActivity extends AppCompatActivity {
private String TAG = "CustomChannelActivity:";
private ChannelView channelView;
private LinkedHashMap<String, List<Channel>> data = new LinkedHashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_channel);
channelView = findViewById(R.id.channelView);
init();
}
private void init() {
String[] myChannel = {"要闻", "视频", "新时代", "娱乐", "体育", "军事", "NBA", "国际", "科技", "财经", "汽车", "电影", "游戏", "独家", "房产",
"图片", "时尚", "呼和浩特"};
String[] recommendChannel1 = {"综艺", "美食", "育儿", "冰雪", "必读", "政法网事", "都市",
"NFL", "韩流"};
String[] recommendChannel2 = {"问答", "文化", "佛学", "股票", "动漫", "理财", "情感", "职场", "旅游"};
String[] recommendChannel3 = {"家居", "电竞", "数码", "星座", "教育", "美容", "电视剧",
"搏击", "健康"};
List<Channel> myChannelList = new ArrayList<>();
List<Channel> recommendChannelList1 = new ArrayList<>();
List<Channel> recommendChannelList2 = new ArrayList<>();
List<Channel> recommendChannelList3 = new ArrayList<>();
for (int i = 0; i < myChannel.length; i++) {
String aMyChannel = myChannel[i];
Channel channel;
if (i > 2 && i < 6) {
//可设置频道归属板块(channelBelong),当前设置此频道归属于第二板块,当删除该频道时该频道将回到第二板块
channel = new Channel(aMyChannel, 2, i);
} else if (i > 7 && i < 10) {
//可设置频道归属板块(channelBelong),当前设置此频道归属于第三板块,当删除该频道时该频道将回到第三板块中
channel = new Channel(aMyChannel, 3, i);
} else {
channel = new Channel(aMyChannel, (Object) i);
}
myChannelList.add(channel);
}
for (String aMyChannel : recommendChannel1) {
Channel channel = new Channel(aMyChannel);
recommendChannelList1.add(channel);
}
for (String aMyChannel : recommendChannel2) {
Channel channel = new Channel(aMyChannel);
recommendChannelList2.add(channel);
}
for (String aMyChannel : recommendChannel3) {
Channel channel = new Channel(aMyChannel);
recommendChannelList3.add(channel);
}
data.put("我的频道", myChannelList);
data.put("推荐频道", recommendChannelList1);
data.put("国内", recommendChannelList2);
data.put("国外", recommendChannelList3);
channelView.setChannelFixedCount(3);
channelView.setInsertRecommendPosition(6);
channelView.setStyleAdapter(new MyAdapter());
channelView.setOnChannelListener(new ChannelListenerAdapter() {
@Override
public void channelItemClick(int position, Channel channel) {
Log.i(TAG, position + ".." + channel);
}
@Override
public void channelEditStateItemClick(int position, Channel channel) {
Log.i(TAG + "EditState:", position + ".." + channel);
}
@Override
public void channelEditFinish(List<Channel> channelList) {
Log.i(TAG, channelList.toString());
Log.i(TAG, channelView.isChange() + "");
Log.i(TAG, channelView.getOtherChannel().toString());
}
@Override
public void channelEditStart() {
Log.i(TAG, "channelEditStart");
}
});
}
class MyAdapter extends BaseStyleAdapter<MyAdapter.MyViewHolder> {
@Override
public MyViewHolder createStyleView(ViewGroup parent, String channelName) {
View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_custom_channel, null);
MyViewHolder customViewHolder = new MyViewHolder(inflate);
customViewHolder.tv.setText(channelName);
return customViewHolder;
}
@Override
public LinkedHashMap<String, List<Channel>> getChannelData() {
return data;
}
@Override
public void setNormalStyle(MyViewHolder viewHolder) {
viewHolder.tv.setBackgroundResource(R.drawable.bg_channel_custom_normal);
viewHolder.iv.setVisibility(View.INVISIBLE);
}
@Override
public void setFixedStyle(MyViewHolder viewHolder) {
viewHolder.tv.setTextColor(Color.parseColor("#1E87FF"));
viewHolder.tv.setBackgroundResource(R.drawable.bg_channel_custom_fixed);
}
@Override
public void setEditStyle(MyViewHolder viewHolder) {
viewHolder.tv.setBackgroundResource(R.drawable.bg_channel_custom_edit);
viewHolder.iv.setVisibility(View.VISIBLE);
}
@Override
public void setFocusedStyle(MyViewHolder viewHolder) {
viewHolder.tv.setBackgroundResource(R.drawable.bg_channel_custom_focused);
}
class MyViewHolder extends ViewHolder {
TextView tv;
ImageView iv;
public MyViewHolder(View itemView) {
super(itemView);
tv = itemView.findViewById(R.id.tv_channel);
iv = itemView.findViewById(R.id.iv_delete);
}
}
}
}
| chengzhicao/ChannelView | app/src/main/java/com/cheng/sample/CustomChannelActivity.java | 1,512 | //可设置频道归属板块(channelBelong),当前设置此频道归属于第二板块,当删除该频道时该频道将回到第二板块 | line_comment | zh-cn | package com.cheng.sample;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.cheng.channel.Channel;
import com.cheng.channel.ChannelView;
import com.cheng.channel.ViewHolder;
import com.cheng.channel.adapter.BaseStyleAdapter;
import com.cheng.channel.adapter.ChannelListenerAdapter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
public class CustomChannelActivity extends AppCompatActivity {
private String TAG = "CustomChannelActivity:";
private ChannelView channelView;
private LinkedHashMap<String, List<Channel>> data = new LinkedHashMap<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_channel);
channelView = findViewById(R.id.channelView);
init();
}
private void init() {
String[] myChannel = {"要闻", "视频", "新时代", "娱乐", "体育", "军事", "NBA", "国际", "科技", "财经", "汽车", "电影", "游戏", "独家", "房产",
"图片", "时尚", "呼和浩特"};
String[] recommendChannel1 = {"综艺", "美食", "育儿", "冰雪", "必读", "政法网事", "都市",
"NFL", "韩流"};
String[] recommendChannel2 = {"问答", "文化", "佛学", "股票", "动漫", "理财", "情感", "职场", "旅游"};
String[] recommendChannel3 = {"家居", "电竞", "数码", "星座", "教育", "美容", "电视剧",
"搏击", "健康"};
List<Channel> myChannelList = new ArrayList<>();
List<Channel> recommendChannelList1 = new ArrayList<>();
List<Channel> recommendChannelList2 = new ArrayList<>();
List<Channel> recommendChannelList3 = new ArrayList<>();
for (int i = 0; i < myChannel.length; i++) {
String aMyChannel = myChannel[i];
Channel channel;
if (i > 2 && i < 6) {
//可设 <SUF>
channel = new Channel(aMyChannel, 2, i);
} else if (i > 7 && i < 10) {
//可设置频道归属板块(channelBelong),当前设置此频道归属于第三板块,当删除该频道时该频道将回到第三板块中
channel = new Channel(aMyChannel, 3, i);
} else {
channel = new Channel(aMyChannel, (Object) i);
}
myChannelList.add(channel);
}
for (String aMyChannel : recommendChannel1) {
Channel channel = new Channel(aMyChannel);
recommendChannelList1.add(channel);
}
for (String aMyChannel : recommendChannel2) {
Channel channel = new Channel(aMyChannel);
recommendChannelList2.add(channel);
}
for (String aMyChannel : recommendChannel3) {
Channel channel = new Channel(aMyChannel);
recommendChannelList3.add(channel);
}
data.put("我的频道", myChannelList);
data.put("推荐频道", recommendChannelList1);
data.put("国内", recommendChannelList2);
data.put("国外", recommendChannelList3);
channelView.setChannelFixedCount(3);
channelView.setInsertRecommendPosition(6);
channelView.setStyleAdapter(new MyAdapter());
channelView.setOnChannelListener(new ChannelListenerAdapter() {
@Override
public void channelItemClick(int position, Channel channel) {
Log.i(TAG, position + ".." + channel);
}
@Override
public void channelEditStateItemClick(int position, Channel channel) {
Log.i(TAG + "EditState:", position + ".." + channel);
}
@Override
public void channelEditFinish(List<Channel> channelList) {
Log.i(TAG, channelList.toString());
Log.i(TAG, channelView.isChange() + "");
Log.i(TAG, channelView.getOtherChannel().toString());
}
@Override
public void channelEditStart() {
Log.i(TAG, "channelEditStart");
}
});
}
class MyAdapter extends BaseStyleAdapter<MyAdapter.MyViewHolder> {
@Override
public MyViewHolder createStyleView(ViewGroup parent, String channelName) {
View inflate = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_custom_channel, null);
MyViewHolder customViewHolder = new MyViewHolder(inflate);
customViewHolder.tv.setText(channelName);
return customViewHolder;
}
@Override
public LinkedHashMap<String, List<Channel>> getChannelData() {
return data;
}
@Override
public void setNormalStyle(MyViewHolder viewHolder) {
viewHolder.tv.setBackgroundResource(R.drawable.bg_channel_custom_normal);
viewHolder.iv.setVisibility(View.INVISIBLE);
}
@Override
public void setFixedStyle(MyViewHolder viewHolder) {
viewHolder.tv.setTextColor(Color.parseColor("#1E87FF"));
viewHolder.tv.setBackgroundResource(R.drawable.bg_channel_custom_fixed);
}
@Override
public void setEditStyle(MyViewHolder viewHolder) {
viewHolder.tv.setBackgroundResource(R.drawable.bg_channel_custom_edit);
viewHolder.iv.setVisibility(View.VISIBLE);
}
@Override
public void setFocusedStyle(MyViewHolder viewHolder) {
viewHolder.tv.setBackgroundResource(R.drawable.bg_channel_custom_focused);
}
class MyViewHolder extends ViewHolder {
TextView tv;
ImageView iv;
public MyViewHolder(View itemView) {
super(itemView);
tv = itemView.findViewById(R.id.tv_channel);
iv = itemView.findViewById(R.id.iv_delete);
}
}
}
}
| false | 1,234 | 30 | 1,512 | 41 | 1,550 | 32 | 1,512 | 41 | 1,837 | 72 | false | false | false | false | false | true |
57646_0 | package design_mode.prototype_pattern;
//奖状类
public class Citation implements Cloneable {
private Student student;
public void setStudent(Student student) {
this.student = student;
}
public Student getStudent() {
return student;
}
public void show() {
System.out.println(student.name+ "同学:在2020学年第一学期中表现优秀,被评为三好学生。特发此状!");
}
@Override
public Citation clone() throws CloneNotSupportedException {
Citation citation= (Citation) super.clone();
citation.student= student.clone();
return citation;
}
} | chenhao19981227/Daily_Code | design_mode/prototype_pattern/Citation.java | 160 | //奖状类 | line_comment | zh-cn | package design_mode.prototype_pattern;
//奖状 <SUF>
public class Citation implements Cloneable {
private Student student;
public void setStudent(Student student) {
this.student = student;
}
public Student getStudent() {
return student;
}
public void show() {
System.out.println(student.name+ "同学:在2020学年第一学期中表现优秀,被评为三好学生。特发此状!");
}
@Override
public Citation clone() throws CloneNotSupportedException {
Citation citation= (Citation) super.clone();
citation.student= student.clone();
return citation;
}
} | false | 132 | 4 | 160 | 4 | 162 | 4 | 160 | 4 | 190 | 6 | false | false | false | false | false | true |
12185_0 | package cn.hncu.pubs;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CharacterFilter implements Filter{
private String charset;
//黑名单
private Set<String> set = new HashSet<String>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
charset = filterConfig.getInitParameter("charset");
//到数据库中把黑名单加载进来,这里简单模拟一下
//set.add("127.0.0.1");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(charset);
//以下演示黑名单过滤技术
String ip = request.getRemoteAddr();;//获得客户端的IP
if(set.contains(ip)){
HttpServletResponse resp = (HttpServletResponse) response;
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().println("你已被列入黑名单!");
}else{//放行
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
| chenhaoxiang/Java | myAutoLoginWeb/src/cn/hncu/pubs/CharacterFilter.java | 377 | //黑名单 | line_comment | zh-cn | package cn.hncu.pubs;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CharacterFilter implements Filter{
private String charset;
//黑名 <SUF>
private Set<String> set = new HashSet<String>();
@Override
public void init(FilterConfig filterConfig) throws ServletException {
charset = filterConfig.getInitParameter("charset");
//到数据库中把黑名单加载进来,这里简单模拟一下
//set.add("127.0.0.1");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(charset);
//以下演示黑名单过滤技术
String ip = request.getRemoteAddr();;//获得客户端的IP
if(set.contains(ip)){
HttpServletResponse resp = (HttpServletResponse) response;
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().println("你已被列入黑名单!");
}else{//放行
chain.doFilter(request, response);
}
}
@Override
public void destroy() {
}
}
| false | 287 | 2 | 377 | 4 | 370 | 3 | 377 | 4 | 462 | 6 | false | false | false | false | false | true |
12920_4 | package cn.chenhaoxiang.controller;
import cn.chenhaoxiang.converter.OrderForm2OrderDTOConverter;
import cn.chenhaoxiang.dto.OrderDTO;
import cn.chenhaoxiang.enums.ResultEnum;
import cn.chenhaoxiang.exception.SellException;
import cn.chenhaoxiang.form.OrderForm;
import cn.chenhaoxiang.service.BuyerService;
import cn.chenhaoxiang.service.OrderService;
import cn.chenhaoxiang.utils.ResultVOUtil;
import cn.chenhaoxiang.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: 陈浩翔.
* Date: 2018/1/16.
* Time: 下午 7:24.
* Explain:
*/
@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class BuyerOrderController {
@Autowired
private OrderService orderService;
@Autowired
private BuyerService buyerService;
//创建订单
@PostMapping("/create")
public ResultVO<Map<String,String>> create(@Valid OrderForm orderForm,
BindingResult bindingResult){
if(bindingResult.hasErrors()){//表单校验,必须带上@Valid参数,然后必须有BindingResult参数
log.error("[创建订单] 参数不正确,orderForm={}",orderForm);
throw new SellException(ResultEnum.PARAM_ERROR.getCode()
,bindingResult.getFieldError().getDefaultMessage());
//bindingResult.getFieldError().getDefaultMessage()获取的是OrderForm实体中属性上NotEmpty注解的message值
}
OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
log.error("[创建订单] 购物车不能为空");
throw new SellException(ResultEnum.CART_EMPTY);
}
OrderDTO createResult = orderService.create(orderDTO);
Map<String,String> map = new HashMap<>();
map.put("orderId",createResult.getOrderId());
return ResultVOUtil.success(map);
}
//订单列表
@GetMapping("/list")
public ResultVO<List<OrderDTO>> list(@RequestParam("openid") String openid,
@RequestParam(value = "page",defaultValue = "0") Integer page,
@RequestParam(value = "size",defaultValue = "10") Integer size){
if(StringUtils.isEmpty(openid)){
log.error("[查询订单列表] openid为空");
throw new SellException(ResultEnum.PARAM_ERROR);
}
PageRequest pageRequest = new PageRequest(page,size);
Page<OrderDTO> orderDTOPage = orderService.findList(openid,pageRequest);
//约束一:时间需要返回时间戳,秒为单位的
//第一种方法 - 转存Date -> Long.不可取,麻烦
//第二种 请见Date2LongSerializer类
//约束二:为null的属性不返回到前端, 也就是类转json 属性为NULL的不参加序列化
//第一种方法,到类上使用JsonInclude(JsonInclude.Include.NON_NULL)注解
//但是对象很多的时候,每个类去加的话,有些麻烦。
//第二种方法:全局配置 spring: jackson: default-property-inclusion: non_null
// orderDTOPage.getTotalElements();//总行数
// orderDTOPage.getTotalPages();//总页数
return ResultVOUtil.success(orderDTOPage.getContent());
}
//订单详情
@GetMapping("/detail")
public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid,
@RequestParam("orderId") String orderId){
if(StringUtils.isEmpty(openid)||StringUtils.isEmpty(orderId)){
log.error("[查询订单详情] openid为空或orderId为空");
throw new SellException(ResultEnum.PARAM_ERROR);
}
OrderDTO orderDTO =buyerService.findOrderOne(openid,orderId);
return ResultVOUtil.success(orderDTO);
}
//取消订单
@PostMapping("/cancel")
public ResultVO cancel(@RequestParam("openid") String openid,
@RequestParam("orderId") String orderId){
if(StringUtils.isEmpty(openid)||StringUtils.isEmpty(orderId)){
log.error("[查询订单详情] openid为空或orderId为空");
throw new SellException(ResultEnum.PARAM_ERROR);
}
buyerService.cancelOrder(openid, orderId);
return ResultVOUtil.success();
}
}
| chenhaoxiang/WeChatOrderSystem | sell/src/main/java/cn/chenhaoxiang/controller/BuyerOrderController.java | 1,165 | //订单列表 | line_comment | zh-cn | package cn.chenhaoxiang.controller;
import cn.chenhaoxiang.converter.OrderForm2OrderDTOConverter;
import cn.chenhaoxiang.dto.OrderDTO;
import cn.chenhaoxiang.enums.ResultEnum;
import cn.chenhaoxiang.exception.SellException;
import cn.chenhaoxiang.form.OrderForm;
import cn.chenhaoxiang.service.BuyerService;
import cn.chenhaoxiang.service.OrderService;
import cn.chenhaoxiang.utils.ResultVOUtil;
import cn.chenhaoxiang.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created with IntelliJ IDEA.
* User: 陈浩翔.
* Date: 2018/1/16.
* Time: 下午 7:24.
* Explain:
*/
@RestController
@RequestMapping("/buyer/order")
@Slf4j
public class BuyerOrderController {
@Autowired
private OrderService orderService;
@Autowired
private BuyerService buyerService;
//创建订单
@PostMapping("/create")
public ResultVO<Map<String,String>> create(@Valid OrderForm orderForm,
BindingResult bindingResult){
if(bindingResult.hasErrors()){//表单校验,必须带上@Valid参数,然后必须有BindingResult参数
log.error("[创建订单] 参数不正确,orderForm={}",orderForm);
throw new SellException(ResultEnum.PARAM_ERROR.getCode()
,bindingResult.getFieldError().getDefaultMessage());
//bindingResult.getFieldError().getDefaultMessage()获取的是OrderForm实体中属性上NotEmpty注解的message值
}
OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
log.error("[创建订单] 购物车不能为空");
throw new SellException(ResultEnum.CART_EMPTY);
}
OrderDTO createResult = orderService.create(orderDTO);
Map<String,String> map = new HashMap<>();
map.put("orderId",createResult.getOrderId());
return ResultVOUtil.success(map);
}
//订单 <SUF>
@GetMapping("/list")
public ResultVO<List<OrderDTO>> list(@RequestParam("openid") String openid,
@RequestParam(value = "page",defaultValue = "0") Integer page,
@RequestParam(value = "size",defaultValue = "10") Integer size){
if(StringUtils.isEmpty(openid)){
log.error("[查询订单列表] openid为空");
throw new SellException(ResultEnum.PARAM_ERROR);
}
PageRequest pageRequest = new PageRequest(page,size);
Page<OrderDTO> orderDTOPage = orderService.findList(openid,pageRequest);
//约束一:时间需要返回时间戳,秒为单位的
//第一种方法 - 转存Date -> Long.不可取,麻烦
//第二种 请见Date2LongSerializer类
//约束二:为null的属性不返回到前端, 也就是类转json 属性为NULL的不参加序列化
//第一种方法,到类上使用JsonInclude(JsonInclude.Include.NON_NULL)注解
//但是对象很多的时候,每个类去加的话,有些麻烦。
//第二种方法:全局配置 spring: jackson: default-property-inclusion: non_null
// orderDTOPage.getTotalElements();//总行数
// orderDTOPage.getTotalPages();//总页数
return ResultVOUtil.success(orderDTOPage.getContent());
}
//订单详情
@GetMapping("/detail")
public ResultVO<OrderDTO> detail(@RequestParam("openid") String openid,
@RequestParam("orderId") String orderId){
if(StringUtils.isEmpty(openid)||StringUtils.isEmpty(orderId)){
log.error("[查询订单详情] openid为空或orderId为空");
throw new SellException(ResultEnum.PARAM_ERROR);
}
OrderDTO orderDTO =buyerService.findOrderOne(openid,orderId);
return ResultVOUtil.success(orderDTO);
}
//取消订单
@PostMapping("/cancel")
public ResultVO cancel(@RequestParam("openid") String openid,
@RequestParam("orderId") String orderId){
if(StringUtils.isEmpty(openid)||StringUtils.isEmpty(orderId)){
log.error("[查询订单详情] openid为空或orderId为空");
throw new SellException(ResultEnum.PARAM_ERROR);
}
buyerService.cancelOrder(openid, orderId);
return ResultVOUtil.success();
}
}
| false | 987 | 3 | 1,165 | 3 | 1,194 | 3 | 1,165 | 3 | 1,522 | 7 | false | false | false | false | false | true |
57206_4 | package jimo.care.care_note.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jimo.care.care_note.bean.*;
import jimo.care.care_note.info.Message;
import jimo.care.care_note.info.user.UserSettingStatus;
import jimo.care.care_note.service.impl.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* <p>
* SettingController前端控制器
* </p>
*
* @author JIMO
* @since 2022-08-13
*/
@RestController
public class SettingController {
@Resource
ModuleServiceImpl moduleService;
@Resource
LogServiceImpl logService;
@Resource
RelationServiceImpl relationService;
@Resource
UserServiceImpl userService;
@Resource
SettingServiceImpl settingService;
/***
* @param request
* @return 获取全部关怀对象的信息
*/
@PostMapping("/user/setting")
public Message getModules(HttpServletRequest request) {
Map<String, List<Setting>> map = new HashMap<>();
try {
User careUser = getCareUser(request);
List<Setting> onSetting = new ArrayList<>();
List<Setting> stopSetting =new ArrayList<>();
relationService.AdminGetRelations(null,Wrappers.<Relation>query().select("s_id","m_id").eq("u_id",careUser.getId())).getRecords()
.forEach(r-> settingInfo(onSetting,stopSetting,r));
map.put("onSetting",onSetting);
map.put("stopSetting",stopSetting);
} catch (Exception e) {
e.printStackTrace();
return new Message(500, "error", null);
}
return new Message(200, "ok", map);
}
@PostMapping("/user/setting/delete/{id}")
public Message deleteSetting(@PathVariable("id")Integer id){
boolean b = settingService.deleteBySID(id);
return new Message(b?200:500,b?"删除成功!刷新页面生效!":"系统异常,请重试!",null);
}
/***
* @param request
* @return 用于判断这是修改或是创建!并传入参数。
*/
@PostMapping("/user/setting/get")
public Message getSetting(HttpServletRequest request) {
Object sID = request.getSession().getAttribute("setting");
User careUser = getCareUser(request);
List<CareModule> list =new ArrayList<>();
moduleService.UserGetModules(null,careUser.getId()).getRecords()
.forEach(m->list.add(m));
if (sID == null) {
Setting setting = new Setting();
setting.setModules(list);
return new Message(200, "欢迎创建对象!", setting);
} else {
Relation relation = relationService.getRelation((int) sID);
Setting setting = settingService.UserGetSetting((int) sID);
setting.setModuleId(relation.getMId());
setting.setModules(list);
return new Message(201, "谨慎修改对象!", setting);
}
}
@PostMapping("/user/setting/post")
public Message postSetting(Setting setting, HttpServletRequest request) {
Object sID = request.getSession().getAttribute("setting");
if (sID == null) {
boolean b = settingService.insert(setting)&&relationService.insert(new Relation(getCareUser(request).getId(),setting.getId(),setting.getModuleId()));
return new Message(b ? 200 : 500, b ? "创建成功!" : "创建失败,请重试!", null);
} else {
setting.setId((int)sID);
Relation relation = relationService.getRelation((int) sID);
relation.setMId(setting.getModuleId());
boolean b=settingService.updateBySIF(setting)&&relationService.updateByRID(relation);
return new Message(b ? 200 : 500, b ? "修改成功!" : "修改失败,请重试!", null);
}
}
/***
* @param request 传入HttpServiceRequest
* @return 取出session中的CareUser信息
*/
private User getCareUser(HttpServletRequest request) {
return (User) request.getSession().getAttribute("CareUser");
}
/***
* 根据业务需求进行筛选处理
*/
private void settingInfo(List<Setting> onSetting, List<Setting> stopSetting,Relation relation) {
Setting setting = settingService.UserGetSetting(relation.getSId());
if (setting.getStatus()>=0&&setting.getStatus()<8){
setting.setVisit(logService.getCount(Wrappers.<Log>query().eq("s_id",relation.getSId())));
setting.setModuleName(moduleService.getModule(relation.getMId()).getName());
if (setting.getStatus()!=0){
setting.setStatusName(auto(setting.getStatus()));
onSetting.add(setting);
}else {
setting.setStatusName("服务已暂停");
stopSetting.add(setting);
}
}
}
/***
* @param s 将标识信息转化为可见的信息!
* @return
*/
private String auto(Integer s) {
switch (s) {
case 0:
return "服务已暂停";
case 1:
return "早安服务";
case 2:
return "午安服务";
case 3:
return "早安-午安服务";
case 4:
return "晚安服务";
case 5:
return "早安-晚安服务";
case 6:
return "午安-晚安服务";
case 7:
return "全天服务";
}
return null;
}
/***
* @param s 将可见的信息转化为内部标识!
* @return
*/
private String autoF(String s) {
return Objects.equals(s,"系统自动智能语句!")||Objects.equals(s,"")||Objects.equals(s,null) ? UserSettingStatus.AUTO : s;
}
}
| chenjimo/Care_Note | src/main/java/jimo/care/care_note/controller/SettingController.java | 1,478 | /***
* 根据业务需求进行筛选处理
*/ | block_comment | zh-cn | package jimo.care.care_note.controller;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import jimo.care.care_note.bean.*;
import jimo.care.care_note.info.Message;
import jimo.care.care_note.info.user.UserSettingStatus;
import jimo.care.care_note.service.impl.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* <p>
* SettingController前端控制器
* </p>
*
* @author JIMO
* @since 2022-08-13
*/
@RestController
public class SettingController {
@Resource
ModuleServiceImpl moduleService;
@Resource
LogServiceImpl logService;
@Resource
RelationServiceImpl relationService;
@Resource
UserServiceImpl userService;
@Resource
SettingServiceImpl settingService;
/***
* @param request
* @return 获取全部关怀对象的信息
*/
@PostMapping("/user/setting")
public Message getModules(HttpServletRequest request) {
Map<String, List<Setting>> map = new HashMap<>();
try {
User careUser = getCareUser(request);
List<Setting> onSetting = new ArrayList<>();
List<Setting> stopSetting =new ArrayList<>();
relationService.AdminGetRelations(null,Wrappers.<Relation>query().select("s_id","m_id").eq("u_id",careUser.getId())).getRecords()
.forEach(r-> settingInfo(onSetting,stopSetting,r));
map.put("onSetting",onSetting);
map.put("stopSetting",stopSetting);
} catch (Exception e) {
e.printStackTrace();
return new Message(500, "error", null);
}
return new Message(200, "ok", map);
}
@PostMapping("/user/setting/delete/{id}")
public Message deleteSetting(@PathVariable("id")Integer id){
boolean b = settingService.deleteBySID(id);
return new Message(b?200:500,b?"删除成功!刷新页面生效!":"系统异常,请重试!",null);
}
/***
* @param request
* @return 用于判断这是修改或是创建!并传入参数。
*/
@PostMapping("/user/setting/get")
public Message getSetting(HttpServletRequest request) {
Object sID = request.getSession().getAttribute("setting");
User careUser = getCareUser(request);
List<CareModule> list =new ArrayList<>();
moduleService.UserGetModules(null,careUser.getId()).getRecords()
.forEach(m->list.add(m));
if (sID == null) {
Setting setting = new Setting();
setting.setModules(list);
return new Message(200, "欢迎创建对象!", setting);
} else {
Relation relation = relationService.getRelation((int) sID);
Setting setting = settingService.UserGetSetting((int) sID);
setting.setModuleId(relation.getMId());
setting.setModules(list);
return new Message(201, "谨慎修改对象!", setting);
}
}
@PostMapping("/user/setting/post")
public Message postSetting(Setting setting, HttpServletRequest request) {
Object sID = request.getSession().getAttribute("setting");
if (sID == null) {
boolean b = settingService.insert(setting)&&relationService.insert(new Relation(getCareUser(request).getId(),setting.getId(),setting.getModuleId()));
return new Message(b ? 200 : 500, b ? "创建成功!" : "创建失败,请重试!", null);
} else {
setting.setId((int)sID);
Relation relation = relationService.getRelation((int) sID);
relation.setMId(setting.getModuleId());
boolean b=settingService.updateBySIF(setting)&&relationService.updateByRID(relation);
return new Message(b ? 200 : 500, b ? "修改成功!" : "修改失败,请重试!", null);
}
}
/***
* @param request 传入HttpServiceRequest
* @return 取出session中的CareUser信息
*/
private User getCareUser(HttpServletRequest request) {
return (User) request.getSession().getAttribute("CareUser");
}
/***
* 根据业 <SUF>*/
private void settingInfo(List<Setting> onSetting, List<Setting> stopSetting,Relation relation) {
Setting setting = settingService.UserGetSetting(relation.getSId());
if (setting.getStatus()>=0&&setting.getStatus()<8){
setting.setVisit(logService.getCount(Wrappers.<Log>query().eq("s_id",relation.getSId())));
setting.setModuleName(moduleService.getModule(relation.getMId()).getName());
if (setting.getStatus()!=0){
setting.setStatusName(auto(setting.getStatus()));
onSetting.add(setting);
}else {
setting.setStatusName("服务已暂停");
stopSetting.add(setting);
}
}
}
/***
* @param s 将标识信息转化为可见的信息!
* @return
*/
private String auto(Integer s) {
switch (s) {
case 0:
return "服务已暂停";
case 1:
return "早安服务";
case 2:
return "午安服务";
case 3:
return "早安-午安服务";
case 4:
return "晚安服务";
case 5:
return "早安-晚安服务";
case 6:
return "午安-晚安服务";
case 7:
return "全天服务";
}
return null;
}
/***
* @param s 将可见的信息转化为内部标识!
* @return
*/
private String autoF(String s) {
return Objects.equals(s,"系统自动智能语句!")||Objects.equals(s,"")||Objects.equals(s,null) ? UserSettingStatus.AUTO : s;
}
}
| false | 1,309 | 15 | 1,478 | 13 | 1,580 | 13 | 1,478 | 13 | 1,823 | 23 | false | false | false | false | false | true |
51555_0 | package com.example.rap_1.manager;
import com.example.rap_1.create.Adj_human;
import com.example.rap_1.create.Character;
import com.example.rap_1.create.Country_1;
import com.example.rap_1.create.Space;
import com.example.rap_1.create.V;
public class Tag_1_manager {
public static String getTag_1(){
String countryName_1 = Country_1.getCountryName();//芬兰
String adj = Adj_human.getAdj();//无聊
String character = Character.getCharacter();//王子
String v = V.getV();//游荡
String countryName_2 = Country_1.getCountryName();//几内亚
String space = Space.getSpace();//购物中心
String ture_1=countryName_1+adj+character+v+countryName_2+space;
return ture_1;
}
}
| chenjingru111/rap_1 | app/src/main/java/com/example/rap_1/manager/Tag_1_manager.java | 228 | //几内亚 | line_comment | zh-cn | package com.example.rap_1.manager;
import com.example.rap_1.create.Adj_human;
import com.example.rap_1.create.Character;
import com.example.rap_1.create.Country_1;
import com.example.rap_1.create.Space;
import com.example.rap_1.create.V;
public class Tag_1_manager {
public static String getTag_1(){
String countryName_1 = Country_1.getCountryName();//芬兰
String adj = Adj_human.getAdj();//无聊
String character = Character.getCharacter();//王子
String v = V.getV();//游荡
String countryName_2 = Country_1.getCountryName();//几内 <SUF>
String space = Space.getSpace();//购物中心
String ture_1=countryName_1+adj+character+v+countryName_2+space;
return ture_1;
}
}
| false | 189 | 4 | 228 | 4 | 226 | 4 | 228 | 4 | 260 | 8 | false | false | false | false | false | true |
24046_13 | package com.chenjjia.算法.LeetCode;
import java.util.*;
/**
* Author: chenjunjia
* Date: 2022/11/17 13:01
* WeChat: China_JoJo_
* Blog: https://juejin.cn/user/1856417285289304/posts
* Github: https://github.com/chenjjiaa
*/
public class A93_复原IP地址 {
// List<String> ans = new ArrayList<>();
// public List<String> restoreIpAddresses1(String s) {
// if (s == null || s.length() == 0) {
// return ans;
// }
// backtracking(s, 0, 0);
// return ans;
// }
//
// public void backtracking(String s, int startIndex, int pointCount) {
// if (pointCount == 3) {
// if (isValid(s, startIndex, s.length()))
// ans.add(new String(s));
// return;
// }
// for (int i = startIndex; i < s.length(); i++) {
// // 判断切割区间是否合法,这里已经相当于是剪枝了
// if (isValid(s, startIndex, i+1)) {
// s = s.substring(0, startIndex + 1) + "," + s.substring(startIndex); // 加个逗号
//// pointCount += 1; // 加了逗号,count + 1
// // 因为从当前位置切割,加上了逗号,所以要i+2,pointCount的回溯可以在这里的入参完成
// backtracking(s, i+2, pointCount+1);
//// pointCount -= 1;
// s = s.substring(0, startIndex + 1) + s.substring(startIndex + 2);
// }
// }
// }
//=============================================================
List<String> path = new ArrayList<>();
List<String> resultList = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12 || s.length() < 4 || s == null)
return resultList;
backtrack(s, 0);
return resultList;
}
/**
这题切割,就是要考虑子串的处理,子串的验证,和子串的拼接
跟着评论区老哥的代码敲的
bug:回溯函数的 base case 条件写错了
startIndex == 4 改成 path.size() == 4
*/
private void backtrack(String s, int startIndex) {
if (path.size() == 4 && startIndex != s.length()) return;
if (path.size() == 4 && startIndex == s.length()){
resultList.add(String.join(".", path)); // 这个join函数用时2ms,手动StringBuilder的话就是1ms
return;
}
for(int i = startIndex; i < s.length() && i < startIndex + 3; i++){
String sub = s.substring(startIndex, i + 1);
if(Integer.parseInt(sub) <= 255){ // 这个验证阶段真的是妙极了!直接在循环中验证,而且很简洁
if(sub.length() > 1 && s.charAt(startIndex) == '0'){
return;
}
path.add(sub);
backtrack(s, i + 1);
path.remove(path.size() - 1);
}else{
return;
}
}
}
//=============================================================
/**
* 左闭右开区间
*/
public boolean isValid(String s, int start, int end) {
if (s.length() > 1) {
if (s.length() > 3)
return false;
if (s.charAt(start) == '0')
return false;
}
StringBuffer stringBuffer = new StringBuffer("");
for (; start < end; start++) {
stringBuffer.append(s.charAt(start));
}
return Integer.parseInt(stringBuffer.toString()) <= 255;
}
}
| chenjjiaa/Algorithm | src/com/chenjjia/算法/LeetCode/A93_复原IP地址.java | 1,034 | // // 判断切割区间是否合法,这里已经相当于是剪枝了
| line_comment | zh-cn | package com.chenjjia.算法.LeetCode;
import java.util.*;
/**
* Author: chenjunjia
* Date: 2022/11/17 13:01
* WeChat: China_JoJo_
* Blog: https://juejin.cn/user/1856417285289304/posts
* Github: https://github.com/chenjjiaa
*/
public class A93_复原IP地址 {
// List<String> ans = new ArrayList<>();
// public List<String> restoreIpAddresses1(String s) {
// if (s == null || s.length() == 0) {
// return ans;
// }
// backtracking(s, 0, 0);
// return ans;
// }
//
// public void backtracking(String s, int startIndex, int pointCount) {
// if (pointCount == 3) {
// if (isValid(s, startIndex, s.length()))
// ans.add(new String(s));
// return;
// }
// for (int i = startIndex; i < s.length(); i++) {
// // 判断 <SUF>
// if (isValid(s, startIndex, i+1)) {
// s = s.substring(0, startIndex + 1) + "," + s.substring(startIndex); // 加个逗号
//// pointCount += 1; // 加了逗号,count + 1
// // 因为从当前位置切割,加上了逗号,所以要i+2,pointCount的回溯可以在这里的入参完成
// backtracking(s, i+2, pointCount+1);
//// pointCount -= 1;
// s = s.substring(0, startIndex + 1) + s.substring(startIndex + 2);
// }
// }
// }
//=============================================================
List<String> path = new ArrayList<>();
List<String> resultList = new ArrayList<>();
public List<String> restoreIpAddresses(String s) {
if (s.length() > 12 || s.length() < 4 || s == null)
return resultList;
backtrack(s, 0);
return resultList;
}
/**
这题切割,就是要考虑子串的处理,子串的验证,和子串的拼接
跟着评论区老哥的代码敲的
bug:回溯函数的 base case 条件写错了
startIndex == 4 改成 path.size() == 4
*/
private void backtrack(String s, int startIndex) {
if (path.size() == 4 && startIndex != s.length()) return;
if (path.size() == 4 && startIndex == s.length()){
resultList.add(String.join(".", path)); // 这个join函数用时2ms,手动StringBuilder的话就是1ms
return;
}
for(int i = startIndex; i < s.length() && i < startIndex + 3; i++){
String sub = s.substring(startIndex, i + 1);
if(Integer.parseInt(sub) <= 255){ // 这个验证阶段真的是妙极了!直接在循环中验证,而且很简洁
if(sub.length() > 1 && s.charAt(startIndex) == '0'){
return;
}
path.add(sub);
backtrack(s, i + 1);
path.remove(path.size() - 1);
}else{
return;
}
}
}
//=============================================================
/**
* 左闭右开区间
*/
public boolean isValid(String s, int start, int end) {
if (s.length() > 1) {
if (s.length() > 3)
return false;
if (s.charAt(start) == '0')
return false;
}
StringBuffer stringBuffer = new StringBuffer("");
for (; start < end; start++) {
stringBuffer.append(s.charAt(start));
}
return Integer.parseInt(stringBuffer.toString()) <= 255;
}
}
| false | 888 | 18 | 1,006 | 24 | 1,015 | 17 | 1,006 | 24 | 1,210 | 33 | false | false | false | false | false | true |
43559_16 | package cn.aidou.Entry;
import org.apache.log4j.Logger;
/**
* 程序有哪些不足 多线程怎样对任务管理的比较好?效率会高一些? 一个线程负责一个对象,一个对象拥有1把锁,当锁中的对象出现故障的时候有监听器自行断电,
* 终止线程,进而抛出异常给开发人员,当线程与任务链接状况很好的情况下(需要有很好的监听
* 排错机制),每个需要访问任务的线程拥有对象任务的一把锁,实现了线程对任务的互斥管理, 方便了责任的划分。
* @author aidou
*/
public class EntryClass
{
/**
* [数据流处理]
* 源:以流的形式到达处理器
* execute 符合特定业务流程的中间处理过程
* 目标:将任务结果输出到指定地方
* [监控运行状态层面]
* 在运行过程中加入log4j日志处理,把每一关健步骤都监控起来---log4j
* 由运行状态各项参数将过程及结果动态展现出来---类似ganglia
* [引入的第三方服务]
* 1.flume系统日志收集系统
* 2.kafka消息队列
* 3.zookeeper分布式应用程序协调服务
* 4.流处理引擎 spark streaming or JStorm
* 5.hdfs存储数据/mapreduce计算数据
* @param args
*/
//args 输入参数按照:driver url username password 顺序输入
private static Logger logger = Logger.getLogger(EntryClass.class);
public static void main(String[] args) throws Exception
{
/********************************************************/
/**
* 开源框架集成情况:
* a.将开源任务调度框架集成进来
* b.kafka消息队列的源码阅读与集成
* c.流处理技术应用到项目当中
* d.hdfs分布式文件系统存储数据以及mapreduce过程
* f.flume项目的集成情况
* g.zookeeper
*
* #############阅读源码与学习源码以及应用情况
* #############积累算法和整个架构的思想
*/
/********************************************************/
/**
* 1.输入流的产生
*/
/**
* 2.输入流格式化切分
*/
/**
* 3.任务调度容器处理爬虫作业--------------------------开源框架
*/
/***********************初始化基础运行环境开始***********************/
/**
* #.1管理器初始化数据库运行环境
*/
Manager sm = new Manager(args);
/**
* #.2初始化线程池环境
*/
sm.initWorkSpace();
/**
* #.3初始化爬虫群的各项参数
*/
sm.initMember(10, 4);
/***********************初始化基础运行环境结束***********************/
/**
* 4.执行爬虫任务!
*/
sm.executeWork();
/**
* #############JVM+爬虫的心跳机制+分布式缓存机制+任务的负载均衡策略
*/
/**
* #############scala+python+并发编程学习+大数据技术源码学习
*/
/**********************借鉴************************/
//时间触发基于内存的处理引擎,符合条件的开仓处理。和database不同
//实时风险控制 跟踪
//开仓模式识别
/************************************************/
}
}
| chenkai1100/SpiderFrame | src/cn/aidou/Entry/EntryClass.java | 809 | //时间触发基于内存的处理引擎,符合条件的开仓处理。和database不同 | line_comment | zh-cn | package cn.aidou.Entry;
import org.apache.log4j.Logger;
/**
* 程序有哪些不足 多线程怎样对任务管理的比较好?效率会高一些? 一个线程负责一个对象,一个对象拥有1把锁,当锁中的对象出现故障的时候有监听器自行断电,
* 终止线程,进而抛出异常给开发人员,当线程与任务链接状况很好的情况下(需要有很好的监听
* 排错机制),每个需要访问任务的线程拥有对象任务的一把锁,实现了线程对任务的互斥管理, 方便了责任的划分。
* @author aidou
*/
public class EntryClass
{
/**
* [数据流处理]
* 源:以流的形式到达处理器
* execute 符合特定业务流程的中间处理过程
* 目标:将任务结果输出到指定地方
* [监控运行状态层面]
* 在运行过程中加入log4j日志处理,把每一关健步骤都监控起来---log4j
* 由运行状态各项参数将过程及结果动态展现出来---类似ganglia
* [引入的第三方服务]
* 1.flume系统日志收集系统
* 2.kafka消息队列
* 3.zookeeper分布式应用程序协调服务
* 4.流处理引擎 spark streaming or JStorm
* 5.hdfs存储数据/mapreduce计算数据
* @param args
*/
//args 输入参数按照:driver url username password 顺序输入
private static Logger logger = Logger.getLogger(EntryClass.class);
public static void main(String[] args) throws Exception
{
/********************************************************/
/**
* 开源框架集成情况:
* a.将开源任务调度框架集成进来
* b.kafka消息队列的源码阅读与集成
* c.流处理技术应用到项目当中
* d.hdfs分布式文件系统存储数据以及mapreduce过程
* f.flume项目的集成情况
* g.zookeeper
*
* #############阅读源码与学习源码以及应用情况
* #############积累算法和整个架构的思想
*/
/********************************************************/
/**
* 1.输入流的产生
*/
/**
* 2.输入流格式化切分
*/
/**
* 3.任务调度容器处理爬虫作业--------------------------开源框架
*/
/***********************初始化基础运行环境开始***********************/
/**
* #.1管理器初始化数据库运行环境
*/
Manager sm = new Manager(args);
/**
* #.2初始化线程池环境
*/
sm.initWorkSpace();
/**
* #.3初始化爬虫群的各项参数
*/
sm.initMember(10, 4);
/***********************初始化基础运行环境结束***********************/
/**
* 4.执行爬虫任务!
*/
sm.executeWork();
/**
* #############JVM+爬虫的心跳机制+分布式缓存机制+任务的负载均衡策略
*/
/**
* #############scala+python+并发编程学习+大数据技术源码学习
*/
/**********************借鉴************************/
//时间 <SUF>
//实时风险控制 跟踪
//开仓模式识别
/************************************************/
}
}
| false | 759 | 18 | 809 | 21 | 826 | 19 | 809 | 21 | 1,338 | 35 | false | false | false | false | false | true |
61595_1 | package com.itheima.a22;
import com.itheima.a04.Bean2;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
/*
目标: 如何获取方法参数名, 注意把 a22 目录添加至模块的类路径
1. a22 不在 src 是避免 idea 自动编译它下面的类
2. spring boot 在编译时会加 -parameters
3. 大部分 IDE 编译时都会加 -g
*/
public class A22 {
public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException {
// 1. 反射获取参数名
Method foo = Bean2.class.getMethod("foo", String.class, int.class);
/*for (Parameter parameter : foo.getParameters()) {
System.out.println(parameter.getName());
}*/
// 2. 基于 LocalVariableTable 本地变量表
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = discoverer.getParameterNames(foo);
System.out.println(Arrays.toString(parameterNames));
/*
学到了什么
a. 如果编译时添加了 -parameters 可以生成参数表, 反射时就可以拿到参数名
b. 如果编译时添加了 -g 可以生成调试信息, 但分为两种情况
1. 普通类, 会包含局部变量表, 用 asm 可以拿到参数名
2. 接口, 不会包含局部变量表, 无法获得参数名 (这也是 MyBatis 在实现 Mapper 接口时为何要提供 @Param 注解来辅助获得参数名)
*/
}
}
| chenlinSir/spring5-code-study | show/src/main/java/com/itheima/a22/A22.java | 429 | // 1. 反射获取参数名 | line_comment | zh-cn | package com.itheima.a22;
import com.itheima.a04.Bean2;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.StandardReflectionParameterNameDiscoverer;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
/*
目标: 如何获取方法参数名, 注意把 a22 目录添加至模块的类路径
1. a22 不在 src 是避免 idea 自动编译它下面的类
2. spring boot 在编译时会加 -parameters
3. 大部分 IDE 编译时都会加 -g
*/
public class A22 {
public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException {
// 1. <SUF>
Method foo = Bean2.class.getMethod("foo", String.class, int.class);
/*for (Parameter parameter : foo.getParameters()) {
System.out.println(parameter.getName());
}*/
// 2. 基于 LocalVariableTable 本地变量表
LocalVariableTableParameterNameDiscoverer discoverer = new LocalVariableTableParameterNameDiscoverer();
String[] parameterNames = discoverer.getParameterNames(foo);
System.out.println(Arrays.toString(parameterNames));
/*
学到了什么
a. 如果编译时添加了 -parameters 可以生成参数表, 反射时就可以拿到参数名
b. 如果编译时添加了 -g 可以生成调试信息, 但分为两种情况
1. 普通类, 会包含局部变量表, 用 asm 可以拿到参数名
2. 接口, 不会包含局部变量表, 无法获得参数名 (这也是 MyBatis 在实现 Mapper 接口时为何要提供 @Param 注解来辅助获得参数名)
*/
}
}
| false | 409 | 10 | 429 | 10 | 422 | 9 | 429 | 10 | 596 | 14 | false | false | false | false | false | true |
17739_4 | package ndArray;
/*
Lab class 的主要作用是存放一些实验中的功能。有一些功能未必有 paper 的支持,因此使用应当谨慎。
*/
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class Lab {
public Lab() {}
public static double sharpness(int[][][] img, double T1, double T2, String mode) {
mode = mode.toLowerCase();
if (!( mode.equals("chw1") || mode.equals("cwh1") || mode.equals("hwc1") || mode.equals("whc1") ||
mode.equals("chw255") || mode.equals("cwh255") || mode.equals("hwc255") || mode.equals("whc255") )) {
throw new IllegalArgumentException("Illegal Mode. Please choose the mode from: chw1, cwh1, hwc1, whc1, " +
"chw255, cwh255, hwc255, whc255.");
}
double[][][] img_d = NdUtils.cast(img); // 改变格式到 double
if (!mode.substring(0,1).equals("c")) {
img_d = NdUtils.transpose(img_d, new int[]{2, 0, 1}); // 转置
}
if (mode.substring(3,4).equals("2")) {
NdMath.elementwiseDivide(img_d, 255); // 归一化
}
return sharpness(img_d, T1, T2, "chw1");
}
// 推荐 T1 = 0.2, T2 = 0.1
public static double sharpness(double[][][] img_d, double T1, double T2, String mode) {
mode = mode.toLowerCase();
if (!( mode.equals("chw1") || mode.equals("cwh1") || mode.equals("hwc1") || mode.equals("whc1") ||
mode.equals("chw255") || mode.equals("cwh255") || mode.equals("hwc255") || mode.equals("whc255") )) {
throw new IllegalArgumentException("Illegal Mode. Please choose the mode from: chw1, cwh1, hwc1, whc1, " +
"chw255, cwh255, hwc255, whc255.");
}
if (!mode.substring(0,1).equals("c")) {
img_d = NdUtils.transpose(img_d, new int[]{2, 0, 1}); // 转置
}
if (mode.substring(3,4).equals("2")) {
NdMath.elementwiseDivide(img_d, 255); // 归一化
}
// 使用 Laplacian 做卷积
double[][][] lap_result = new double[][][]{
NdMath.convolve(img_d[0], Filters.laplacian2d3_nine()),
NdMath.convolve(img_d[1], Filters.laplacian2d3_nine()),
NdMath.convolve(img_d[2], Filters.laplacian2d3_nine()),
};
NdMath.ndAbs(lap_result); // 绝对值
double[][] lap_result_ = NdMath.reduce(lap_result); // 各 channel 的平均
ArrayList<Double> lap_values = NdUtils.flatten(lap_result_);
double[] thresholds = new double[]{T1, T2};
double[] percentages = new double[2];
for (int i = 0; i < 2; i++) {
double percentage = 0;
for (double d : lap_values) {
if (d>thresholds[i]) percentage+=1;
}
percentage /= lap_values.size();
percentages[i] = percentage;
}
return percentages[0]/percentages[1];
}
private static double aligness_legacy(double[][] img_) {
ArrayList<double[][]> sobels = Filters.sobel2d(3);
double[][] sobelx = NdMath.convolve(img_, sobels.get(0));
NdMath.ndAbs(sobelx);
double[][] sobely = NdMath.convolve(img_, sobels.get(1));
NdMath.ndAbs(sobely);
double result = 0;
for (int i = 0; i < sobelx.length; i++) {
for (int j = 0; j < sobelx[0].length; j++) {
result += Math.max(sobelx[i][j], sobely[i][j]);
}
}
return result;
}
public static double straighten_legacy(int[][][] img_, String mode) {
int w = 0;
int h = 0;
switch (mode) {
case "chw":
w = img_[0][0].length;
h = img_[0].length;
break;
case "cwh":
w = img_[0].length;
h = img_[0][0].length;
break;
case "hwc":
w = img_[0].length;
h = img_.length;
break;
case "whc":
w = img_.length;
h = img_[0].length;
break;
default:
throw new IllegalArgumentException("Illegal Mode. Please choose the mode from: chw, cwh, hwc, whc.");
}
double side_length = 128;
double ratio = 2*side_length/(w+h);
int newWidth = Math.max(3, (int)(w*ratio)); // 因为 sobel filter 边长是 3
int newHeight = Math.max(3, (int)(h*ratio));
BufferedImage bi = NdImageIO.convert(img_, mode);
bi = NdImagePro.resize(bi, newWidth, newHeight);
int[][][] img = NdImageIO.convert(bi, "cwh");
double[][] img_bw = NdMath.reduce(NdUtils.cast(img));
double[] gaps = new double[]{30,10,3.3,1.1};
double[] best_angle = new double[]{0, aligness_legacy(img_bw)};
for (double gap : gaps) {
double base_angle = best_angle[0];
for (double delta : new double[]{-gap, gap}) {
double angle = base_angle+delta;
BufferedImage bi_ = NdImagePro.rotate(bi, angle);
img = NdImageIO.convert(bi_, "cwh");
img_bw = NdMath.reduce(NdUtils.cast(img));
double _aligness = aligness_legacy(img_bw);
if (_aligness>best_angle[1]) {
best_angle = new double[]{angle, _aligness};
}
}
}
return best_angle[0];
}
}
| chenmingxiang110/J4darrays | src/ndArray/Lab.java | 1,653 | // 归一化 | line_comment | zh-cn | package ndArray;
/*
Lab class 的主要作用是存放一些实验中的功能。有一些功能未必有 paper 的支持,因此使用应当谨慎。
*/
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class Lab {
public Lab() {}
public static double sharpness(int[][][] img, double T1, double T2, String mode) {
mode = mode.toLowerCase();
if (!( mode.equals("chw1") || mode.equals("cwh1") || mode.equals("hwc1") || mode.equals("whc1") ||
mode.equals("chw255") || mode.equals("cwh255") || mode.equals("hwc255") || mode.equals("whc255") )) {
throw new IllegalArgumentException("Illegal Mode. Please choose the mode from: chw1, cwh1, hwc1, whc1, " +
"chw255, cwh255, hwc255, whc255.");
}
double[][][] img_d = NdUtils.cast(img); // 改变格式到 double
if (!mode.substring(0,1).equals("c")) {
img_d = NdUtils.transpose(img_d, new int[]{2, 0, 1}); // 转置
}
if (mode.substring(3,4).equals("2")) {
NdMath.elementwiseDivide(img_d, 255); // 归一化
}
return sharpness(img_d, T1, T2, "chw1");
}
// 推荐 T1 = 0.2, T2 = 0.1
public static double sharpness(double[][][] img_d, double T1, double T2, String mode) {
mode = mode.toLowerCase();
if (!( mode.equals("chw1") || mode.equals("cwh1") || mode.equals("hwc1") || mode.equals("whc1") ||
mode.equals("chw255") || mode.equals("cwh255") || mode.equals("hwc255") || mode.equals("whc255") )) {
throw new IllegalArgumentException("Illegal Mode. Please choose the mode from: chw1, cwh1, hwc1, whc1, " +
"chw255, cwh255, hwc255, whc255.");
}
if (!mode.substring(0,1).equals("c")) {
img_d = NdUtils.transpose(img_d, new int[]{2, 0, 1}); // 转置
}
if (mode.substring(3,4).equals("2")) {
NdMath.elementwiseDivide(img_d, 255); // 归一 <SUF>
}
// 使用 Laplacian 做卷积
double[][][] lap_result = new double[][][]{
NdMath.convolve(img_d[0], Filters.laplacian2d3_nine()),
NdMath.convolve(img_d[1], Filters.laplacian2d3_nine()),
NdMath.convolve(img_d[2], Filters.laplacian2d3_nine()),
};
NdMath.ndAbs(lap_result); // 绝对值
double[][] lap_result_ = NdMath.reduce(lap_result); // 各 channel 的平均
ArrayList<Double> lap_values = NdUtils.flatten(lap_result_);
double[] thresholds = new double[]{T1, T2};
double[] percentages = new double[2];
for (int i = 0; i < 2; i++) {
double percentage = 0;
for (double d : lap_values) {
if (d>thresholds[i]) percentage+=1;
}
percentage /= lap_values.size();
percentages[i] = percentage;
}
return percentages[0]/percentages[1];
}
private static double aligness_legacy(double[][] img_) {
ArrayList<double[][]> sobels = Filters.sobel2d(3);
double[][] sobelx = NdMath.convolve(img_, sobels.get(0));
NdMath.ndAbs(sobelx);
double[][] sobely = NdMath.convolve(img_, sobels.get(1));
NdMath.ndAbs(sobely);
double result = 0;
for (int i = 0; i < sobelx.length; i++) {
for (int j = 0; j < sobelx[0].length; j++) {
result += Math.max(sobelx[i][j], sobely[i][j]);
}
}
return result;
}
public static double straighten_legacy(int[][][] img_, String mode) {
int w = 0;
int h = 0;
switch (mode) {
case "chw":
w = img_[0][0].length;
h = img_[0].length;
break;
case "cwh":
w = img_[0].length;
h = img_[0][0].length;
break;
case "hwc":
w = img_[0].length;
h = img_.length;
break;
case "whc":
w = img_.length;
h = img_[0].length;
break;
default:
throw new IllegalArgumentException("Illegal Mode. Please choose the mode from: chw, cwh, hwc, whc.");
}
double side_length = 128;
double ratio = 2*side_length/(w+h);
int newWidth = Math.max(3, (int)(w*ratio)); // 因为 sobel filter 边长是 3
int newHeight = Math.max(3, (int)(h*ratio));
BufferedImage bi = NdImageIO.convert(img_, mode);
bi = NdImagePro.resize(bi, newWidth, newHeight);
int[][][] img = NdImageIO.convert(bi, "cwh");
double[][] img_bw = NdMath.reduce(NdUtils.cast(img));
double[] gaps = new double[]{30,10,3.3,1.1};
double[] best_angle = new double[]{0, aligness_legacy(img_bw)};
for (double gap : gaps) {
double base_angle = best_angle[0];
for (double delta : new double[]{-gap, gap}) {
double angle = base_angle+delta;
BufferedImage bi_ = NdImagePro.rotate(bi, angle);
img = NdImageIO.convert(bi_, "cwh");
img_bw = NdMath.reduce(NdUtils.cast(img));
double _aligness = aligness_legacy(img_bw);
if (_aligness>best_angle[1]) {
best_angle = new double[]{angle, _aligness};
}
}
}
return best_angle[0];
}
}
| false | 1,483 | 5 | 1,653 | 5 | 1,698 | 5 | 1,653 | 5 | 1,906 | 7 | false | false | false | false | false | true |
46801_3 | package cn.allbs.enums;
import cn.allbs.utils.IntervalUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* aqi 划分
*
* @author ChenQi
*/
@Getter
@AllArgsConstructor
public enum AqiLevelEnum {
/**
* 空气质量指数及相关信息
*/
I(1, 0D, 50D, "优", "绿色", "{\"R\":0,\"G\":228,\"B\":0}", "{\"C\":40,\"M\":0,\"Y\":100,\"K\":0}", "空气质量令人满意,基本无空气污染", "各类人群可正常活动"),
II(2, 51D, 100D, "良", "黄色", "{\"R\":255,\"G\":255,\"B\":0}", "{\"C\":0,\"M\":0,\"Y\":100,\"K\":0}", "空气质量可接受,但某些污染物可能对极少数异常敏感人群监控有较弱影响", "极少数异常敏感人群应减少户外活动"),
III(3, 101D, 150D, "轻度污染", "橙色", "{\"R\":255,\"G\":126,\"B\":0}", "{\"C\":0,\"M\":52,\"Y\":100,\"K\":0}", "易感人群症状有轻度加剧,健康人群出现刺激症状", "儿童、老年人及心脏病、呼吸系统疾病患者应减少长时间、高强度的户外锻炼"),
IV(4, 151D, 200D, "中度污染", "红色", "{\"R\":255,\"G\":0,\"B\":0}", "{\"C\":0,\"M\":100,\"Y\":100,\"K\":0}", "进一步加剧易感人群症状,可能对健康人群心脏、呼吸系统有影响", "儿童、老年人及心脏病、呼吸系统疾病患者应避免长时间、高强度的户外锻炼,一般人群适宜减少户外运动"),
V(5, 201D, 300D, "重度污染", "紫色", "{\"R\":153,\"G\":0,\"B\":76}", "{\"C\":10,\"M\":100,\"Y\":40,\"K\":30}", "心脏病和肺病患者症状显著加剧,运动耐受力降低,健康人群普遍出现症状", "儿童、老年人和心脏病、肺病患者应停留在室内,停止户外活动,一般人群减少户外活动"),
VI(6, 301D, null, "严重污染", "褐红色", "{\"R\":126,\"G\":0,\"B\":35}", "{\"C\":30,\"M\":100,\"Y\":100,\"K\":30}", "健康人群运动耐受力降低,有明显强烈症状,提前出现某些疾病", "儿童、老年人和病人应当停留在室内,避免体力消耗,一般人群应避免户外活动");
/**
* 空气质量等级
*/
private final Integer airLevel;
/**
* 区间最小值
*/
private final Double min;
/**
* 区间最大值
*/
private final Double max;
/**
* 空气质量指数类别
*/
private final String airGrade;
/**
* 代表颜色
*/
private final String behalfColor;
/**
* 电脑屏幕显示色彩
*/
private final String rgb;
/**
* 印刷色彩模式
*/
private final String cmyk;
/**
* 对健康的影响情况
*/
private final String healthEffect;
/**
* 建议措施
*/
private final String suggestions;
/**
* 根据aqi数值判断aqi等级及相关信息
*
* @param aqi aqi数值
* @return aqi相关信息
*/
public static AqiLevelEnum getLevelInfoByAqi(int aqi) {
AqiLevelEnum[] aqiLevelEnums = AqiLevelEnum.values();
for (AqiLevelEnum aqiLevelEnum : aqiLevelEnums) {
if (IntervalUtil.checkInAllCloseInterval(aqiLevelEnum.getMin(), aqiLevelEnum.getMax(), (double) aqi)) {
return aqiLevelEnum;
}
}
return null;
}
}
| chenqi92/allbs-model | src/main/java/cn/allbs/enums/AqiLevelEnum.java | 1,161 | /**
* 区间最小值
*/ | block_comment | zh-cn | package cn.allbs.enums;
import cn.allbs.utils.IntervalUtil;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* aqi 划分
*
* @author ChenQi
*/
@Getter
@AllArgsConstructor
public enum AqiLevelEnum {
/**
* 空气质量指数及相关信息
*/
I(1, 0D, 50D, "优", "绿色", "{\"R\":0,\"G\":228,\"B\":0}", "{\"C\":40,\"M\":0,\"Y\":100,\"K\":0}", "空气质量令人满意,基本无空气污染", "各类人群可正常活动"),
II(2, 51D, 100D, "良", "黄色", "{\"R\":255,\"G\":255,\"B\":0}", "{\"C\":0,\"M\":0,\"Y\":100,\"K\":0}", "空气质量可接受,但某些污染物可能对极少数异常敏感人群监控有较弱影响", "极少数异常敏感人群应减少户外活动"),
III(3, 101D, 150D, "轻度污染", "橙色", "{\"R\":255,\"G\":126,\"B\":0}", "{\"C\":0,\"M\":52,\"Y\":100,\"K\":0}", "易感人群症状有轻度加剧,健康人群出现刺激症状", "儿童、老年人及心脏病、呼吸系统疾病患者应减少长时间、高强度的户外锻炼"),
IV(4, 151D, 200D, "中度污染", "红色", "{\"R\":255,\"G\":0,\"B\":0}", "{\"C\":0,\"M\":100,\"Y\":100,\"K\":0}", "进一步加剧易感人群症状,可能对健康人群心脏、呼吸系统有影响", "儿童、老年人及心脏病、呼吸系统疾病患者应避免长时间、高强度的户外锻炼,一般人群适宜减少户外运动"),
V(5, 201D, 300D, "重度污染", "紫色", "{\"R\":153,\"G\":0,\"B\":76}", "{\"C\":10,\"M\":100,\"Y\":40,\"K\":30}", "心脏病和肺病患者症状显著加剧,运动耐受力降低,健康人群普遍出现症状", "儿童、老年人和心脏病、肺病患者应停留在室内,停止户外活动,一般人群减少户外活动"),
VI(6, 301D, null, "严重污染", "褐红色", "{\"R\":126,\"G\":0,\"B\":35}", "{\"C\":30,\"M\":100,\"Y\":100,\"K\":30}", "健康人群运动耐受力降低,有明显强烈症状,提前出现某些疾病", "儿童、老年人和病人应当停留在室内,避免体力消耗,一般人群应避免户外活动");
/**
* 空气质量等级
*/
private final Integer airLevel;
/**
* 区间最 <SUF>*/
private final Double min;
/**
* 区间最大值
*/
private final Double max;
/**
* 空气质量指数类别
*/
private final String airGrade;
/**
* 代表颜色
*/
private final String behalfColor;
/**
* 电脑屏幕显示色彩
*/
private final String rgb;
/**
* 印刷色彩模式
*/
private final String cmyk;
/**
* 对健康的影响情况
*/
private final String healthEffect;
/**
* 建议措施
*/
private final String suggestions;
/**
* 根据aqi数值判断aqi等级及相关信息
*
* @param aqi aqi数值
* @return aqi相关信息
*/
public static AqiLevelEnum getLevelInfoByAqi(int aqi) {
AqiLevelEnum[] aqiLevelEnums = AqiLevelEnum.values();
for (AqiLevelEnum aqiLevelEnum : aqiLevelEnums) {
if (IntervalUtil.checkInAllCloseInterval(aqiLevelEnum.getMin(), aqiLevelEnum.getMax(), (double) aqi)) {
return aqiLevelEnum;
}
}
return null;
}
}
| false | 947 | 11 | 1,157 | 10 | 1,053 | 11 | 1,161 | 10 | 1,623 | 13 | false | false | false | false | false | true |
25003_1 | package com.lyc.wwyt.enums;
import com.lyc.wwyt.config.check.CodeEnum;
/**
* 开停车大检修类型
*
* @author ChenQi
* @date 2023/5/23
*/
public enum PlanTypeEnum implements CodeEnum {
/**
* 开车
*/
RUN("开车", "1"),
/**
* 停车
*/
STOP("停车", "2"),
/**
* 检修
*/
CHECK("检修", "3");
private final String code;
private final String value;
PlanTypeEnum(String code, String value) {
this.code = code;
this.value = value;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getValue() {
return this.value;
}
}
| chenqi92/jt-wwyt | src/main/java/com/lyc/wwyt/enums/PlanTypeEnum.java | 206 | /**
* 开车
*/ | block_comment | zh-cn | package com.lyc.wwyt.enums;
import com.lyc.wwyt.config.check.CodeEnum;
/**
* 开停车大检修类型
*
* @author ChenQi
* @date 2023/5/23
*/
public enum PlanTypeEnum implements CodeEnum {
/**
* 开车
<SUF>*/
RUN("开车", "1"),
/**
* 停车
*/
STOP("停车", "2"),
/**
* 检修
*/
CHECK("检修", "3");
private final String code;
private final String value;
PlanTypeEnum(String code, String value) {
this.code = code;
this.value = value;
}
@Override
public String getCode() {
return this.code;
}
@Override
public String getValue() {
return this.value;
}
}
| false | 185 | 8 | 206 | 8 | 223 | 9 | 206 | 8 | 270 | 12 | false | false | false | false | false | true |
41705_6 | package tankwar;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import barrier.Grass;
import barrier.Home;
import barrier.Metal;
import barrier.Wall;
import barrier.Water;
import tankwar.Tank.Direction;
/**
* 坦克大战的子弹类
* @author chenruiying
*
*/
public class Missle implements Runnable{
/** x位置*/
private int x;
/** y位置*/
private int y;
/** 速度*/
private int speed;
/** 方向*/
private Direction dir;
private boolean live = true;//0存活 1死亡
/** 尺寸*/
public int SIZE;
private boolean self;//0我方 1敌方
private ArrayList<Tank> allTanks;
private ArrayList<Explode> explodes;
private final ArrayList<Wall> walls;
private final ArrayList<Metal> metals;
private final ArrayList<Water> waters;
private final ArrayList<Grass> grasses;
private final Home home;
/** 火力*/
private int power;
private ImageIcon enemymissleIcon1;//敌人子弹图片1
private ImageIcon mymissIcon1;//我方子弹图片1
private ImageIcon enemymissleIcon2;//敌人子弹图片2
private ImageIcon mymissIcon2;//我方子弹图片2
private ImageIcon enemymissleIcon3;//敌人子弹图片3
private ImageIcon mymissIcon3;//我方子弹图片3
/**
* 子弹类主方法
* @param x 位置x
* @param y 位置y
* @param tank 坦克
* @param allTanks 全部坦克
* @param walls 普通墙
* @param metals 金属墙
* @param waters 水
* @param grasses 草
* @param home 家
* @param explodes 爆炸
* @param missles 子弹
*/
public Missle(int x, int y, Tank tank, ArrayList<Tank> allTanks, ArrayList<Wall> walls, ArrayList<Metal> metals, ArrayList<Water> waters,ArrayList<Grass> grasses , Home home, ArrayList<Explode>explodes, ArrayList<Missle> missles)
{
this.allTanks = allTanks;
this.walls = walls;
this.metals = metals;
this.waters = waters;
this.grasses = grasses;
this.home = home;
this.explodes = explodes;
this.self = tank.isSelf();
this.power = tank.getPower();
SIZE = power;
this.x = x + 22;
this.y = y + 30;
this.dir = tank.getDir();
speed = 10;
}
/*
* 子弹的运动方法
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while((x >- 10 && x < TankWar.GAME_WIDTH && y >- 10 && y < TankWar.GAME_HEIGHT && live)) {
switch (dir) {
case U:
y -= speed;
break;
case R:
x += speed;
break;
case D:
y += speed;
break;
case L:
x -= speed;
break;
}
for (int i = 0; i < walls.size(); i++) {
if(x > walls.get(i).getX() && x < walls.get(i).getX() + 60 && y > walls.get(i).getY() && y < walls.get(i).getY() + 60) {
walls.get(i).setHp(walls.get(i).getHp() - power);
if(self) {
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\hit.wav").start();
}
if(walls.get(i).getHp() <= 0) {
Explode temp = new Explode(walls.get(i).getX(), walls.get(i).getY());
new Thread(temp).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\explode.wav").start();
explodes.add(temp);
walls.remove(i);
}
this.live = false;
}
}
if(x > home.getX() && x < home.getX() + 60 && y > home.getY() && y < home.getY() + 60) {
home.setHp(home.getHp() - power);
if(home.getHp() <= 0) {
Explode temp=new Explode(home.getX(), home.getY());
Explode temp1=new Explode(home.getX() + 60, home.getY());
Explode temp2=new Explode(home.getX() - 60, home.getY());
Explode temp3=new Explode(home.getX(), home.getY() - 60);
new Thread(temp).start();
new Thread(temp1).start();
new Thread(temp2).start();
new Thread(temp3).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\blast.wav").start();
explodes.add(temp);
explodes.add(temp1);
explodes.add(temp2);
explodes.add(temp3);
home.setFace(new ImageIcon("images/destory.gif").getImage());
home.setLive(false);
}
this.live = false;
}
for (int i = 0; i < metals.size(); i++) {
if(x > metals.get(i).getX() && x < metals.get(i).getX() + 60 && y > metals.get(i).getY() && y < metals.get(i).getY() + 60)
{
this.live = false;
}
}
if(self) {
for (int i = 2; i < allTanks.size(); i++) {
if((x > allTanks.get(i).getX() && x < allTanks.get(i).getX() + Tank.SIZE && y>allTanks.get(i).getY() && y < allTanks.get(i).getY() + Tank.SIZE)) {
allTanks.get(i).setHp(allTanks.get(i).getHp() - power);
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\hit.wav").start();
if(allTanks.get(i).getHp()<=0) {
Explode temp = new Explode(allTanks.get(i).getX(), allTanks.get(i).getY());
new Thread(temp).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\blast.wav").start();
explodes.add(temp);
TankWar.SCORE += 100;
try{
allTanks.remove(i);
} catch (Exception e) {}
}
this.live = false;
}
}
} else {
try {
if(x > allTanks.get(0).getX() && x < allTanks.get(0).getX() + Tank.SIZE && y > allTanks.get(0).getY() && y < allTanks.get(0).getY() + Tank.SIZE) {
allTanks.get(0).setHp(allTanks.get(0).getHp() - power);
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\hit.wav").start();
if(allTanks.get(0).getHp() <= 0) {
Explode temp = new Explode(allTanks.get(0).getX(), allTanks.get(0).getY());
new Thread(temp).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\blast.wav").start();
explodes.add(temp);
allTanks.get(0).setLive(false);
}
this.live = false;
}
} catch(Exception e){}
try {
if(x > allTanks.get(1).getX() && x < allTanks.get(1).getX() + Tank.SIZE && y > allTanks.get(1).getY() && y < allTanks.get(1).getY() + Tank.SIZE) {
allTanks.get(1).setHp(allTanks.get(1).getHp() - power);
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\hit.wav").start();
if(allTanks.get(1).getHp() <= 0) {
Explode temp = new Explode(allTanks.get(1).getX(), allTanks.get(1).getY());
new Thread(temp).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\blast.wav").start();
explodes.add(temp);
allTanks.get(1).setLive(false);
}
this.live = false;
}
} catch(Exception e){}
}
try {Thread.sleep(30);
} catch (InterruptedException e) {}
}
this.live = false;
}
public void setLive(boolean live) {
this.live = live;
}
public boolean isLive() {
return live;
}
/**
* 画出子弹的方法
* @param g 画笔
*/
public void drawMissle(Graphics g)
{
enemymissleIcon1 = new ImageIcon(Missle.class.getResource("/img/enemymissle_1.gif"));
mymissIcon1 = new ImageIcon(Missle.class.getResource("/img/tankmissle_1.gif"));
enemymissleIcon2 = new ImageIcon(Missle.class.getResource("/img/enemymissle_2.gif"));
mymissIcon2 = new ImageIcon(Missle.class.getResource("/img/tankmissle_2.gif"));
enemymissleIcon3 = new ImageIcon(Missle.class.getResource("/img/enemymissle_3.gif"));
mymissIcon3 = new ImageIcon(Missle.class.getResource("/img/tankmissle_3.gif"));
if(!self) {
if(SIZE >= 10 && SIZE <= 14) {
g.drawImage(enemymissleIcon2.getImage(), x, y, null);
} else if (SIZE >= 16 && SIZE <= 20) {
g.drawImage(enemymissleIcon1.getImage(), x, y, null);
} else {
g.drawImage(enemymissleIcon3.getImage(), x, y, null);
}
} else {
if(SIZE >= 10 && SIZE <= 14) {
g.drawImage(mymissIcon2.getImage(), x, y, null);
} else if (SIZE >= 16 && SIZE <= 20) {
g.drawImage(mymissIcon1.getImage(), x, y, null);
} else {
g.drawImage(mymissIcon3.getImage(), x, y, null);
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
| chenruiyingry/TankWar_Double | src/tankwar/Missle.java | 2,879 | /** 尺寸*/ | block_comment | zh-cn | package tankwar;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import barrier.Grass;
import barrier.Home;
import barrier.Metal;
import barrier.Wall;
import barrier.Water;
import tankwar.Tank.Direction;
/**
* 坦克大战的子弹类
* @author chenruiying
*
*/
public class Missle implements Runnable{
/** x位置*/
private int x;
/** y位置*/
private int y;
/** 速度*/
private int speed;
/** 方向*/
private Direction dir;
private boolean live = true;//0存活 1死亡
/** 尺寸* <SUF>*/
public int SIZE;
private boolean self;//0我方 1敌方
private ArrayList<Tank> allTanks;
private ArrayList<Explode> explodes;
private final ArrayList<Wall> walls;
private final ArrayList<Metal> metals;
private final ArrayList<Water> waters;
private final ArrayList<Grass> grasses;
private final Home home;
/** 火力*/
private int power;
private ImageIcon enemymissleIcon1;//敌人子弹图片1
private ImageIcon mymissIcon1;//我方子弹图片1
private ImageIcon enemymissleIcon2;//敌人子弹图片2
private ImageIcon mymissIcon2;//我方子弹图片2
private ImageIcon enemymissleIcon3;//敌人子弹图片3
private ImageIcon mymissIcon3;//我方子弹图片3
/**
* 子弹类主方法
* @param x 位置x
* @param y 位置y
* @param tank 坦克
* @param allTanks 全部坦克
* @param walls 普通墙
* @param metals 金属墙
* @param waters 水
* @param grasses 草
* @param home 家
* @param explodes 爆炸
* @param missles 子弹
*/
public Missle(int x, int y, Tank tank, ArrayList<Tank> allTanks, ArrayList<Wall> walls, ArrayList<Metal> metals, ArrayList<Water> waters,ArrayList<Grass> grasses , Home home, ArrayList<Explode>explodes, ArrayList<Missle> missles)
{
this.allTanks = allTanks;
this.walls = walls;
this.metals = metals;
this.waters = waters;
this.grasses = grasses;
this.home = home;
this.explodes = explodes;
this.self = tank.isSelf();
this.power = tank.getPower();
SIZE = power;
this.x = x + 22;
this.y = y + 30;
this.dir = tank.getDir();
speed = 10;
}
/*
* 子弹的运动方法
* @see java.lang.Runnable#run()
*/
@Override
public void run() {
while((x >- 10 && x < TankWar.GAME_WIDTH && y >- 10 && y < TankWar.GAME_HEIGHT && live)) {
switch (dir) {
case U:
y -= speed;
break;
case R:
x += speed;
break;
case D:
y += speed;
break;
case L:
x -= speed;
break;
}
for (int i = 0; i < walls.size(); i++) {
if(x > walls.get(i).getX() && x < walls.get(i).getX() + 60 && y > walls.get(i).getY() && y < walls.get(i).getY() + 60) {
walls.get(i).setHp(walls.get(i).getHp() - power);
if(self) {
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\hit.wav").start();
}
if(walls.get(i).getHp() <= 0) {
Explode temp = new Explode(walls.get(i).getX(), walls.get(i).getY());
new Thread(temp).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\explode.wav").start();
explodes.add(temp);
walls.remove(i);
}
this.live = false;
}
}
if(x > home.getX() && x < home.getX() + 60 && y > home.getY() && y < home.getY() + 60) {
home.setHp(home.getHp() - power);
if(home.getHp() <= 0) {
Explode temp=new Explode(home.getX(), home.getY());
Explode temp1=new Explode(home.getX() + 60, home.getY());
Explode temp2=new Explode(home.getX() - 60, home.getY());
Explode temp3=new Explode(home.getX(), home.getY() - 60);
new Thread(temp).start();
new Thread(temp1).start();
new Thread(temp2).start();
new Thread(temp3).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\blast.wav").start();
explodes.add(temp);
explodes.add(temp1);
explodes.add(temp2);
explodes.add(temp3);
home.setFace(new ImageIcon("images/destory.gif").getImage());
home.setLive(false);
}
this.live = false;
}
for (int i = 0; i < metals.size(); i++) {
if(x > metals.get(i).getX() && x < metals.get(i).getX() + 60 && y > metals.get(i).getY() && y < metals.get(i).getY() + 60)
{
this.live = false;
}
}
if(self) {
for (int i = 2; i < allTanks.size(); i++) {
if((x > allTanks.get(i).getX() && x < allTanks.get(i).getX() + Tank.SIZE && y>allTanks.get(i).getY() && y < allTanks.get(i).getY() + Tank.SIZE)) {
allTanks.get(i).setHp(allTanks.get(i).getHp() - power);
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\hit.wav").start();
if(allTanks.get(i).getHp()<=0) {
Explode temp = new Explode(allTanks.get(i).getX(), allTanks.get(i).getY());
new Thread(temp).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\blast.wav").start();
explodes.add(temp);
TankWar.SCORE += 100;
try{
allTanks.remove(i);
} catch (Exception e) {}
}
this.live = false;
}
}
} else {
try {
if(x > allTanks.get(0).getX() && x < allTanks.get(0).getX() + Tank.SIZE && y > allTanks.get(0).getY() && y < allTanks.get(0).getY() + Tank.SIZE) {
allTanks.get(0).setHp(allTanks.get(0).getHp() - power);
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\hit.wav").start();
if(allTanks.get(0).getHp() <= 0) {
Explode temp = new Explode(allTanks.get(0).getX(), allTanks.get(0).getY());
new Thread(temp).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\blast.wav").start();
explodes.add(temp);
allTanks.get(0).setLive(false);
}
this.live = false;
}
} catch(Exception e){}
try {
if(x > allTanks.get(1).getX() && x < allTanks.get(1).getX() + Tank.SIZE && y > allTanks.get(1).getY() && y < allTanks.get(1).getY() + Tank.SIZE) {
allTanks.get(1).setHp(allTanks.get(1).getHp() - power);
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\hit.wav").start();
if(allTanks.get(1).getHp() <= 0) {
Explode temp = new Explode(allTanks.get(1).getX(), allTanks.get(1).getY());
new Thread(temp).start();
new Audio("E:\\workspace\\MyTankWar2.0\\src\\music\\blast.wav").start();
explodes.add(temp);
allTanks.get(1).setLive(false);
}
this.live = false;
}
} catch(Exception e){}
}
try {Thread.sleep(30);
} catch (InterruptedException e) {}
}
this.live = false;
}
public void setLive(boolean live) {
this.live = live;
}
public boolean isLive() {
return live;
}
/**
* 画出子弹的方法
* @param g 画笔
*/
public void drawMissle(Graphics g)
{
enemymissleIcon1 = new ImageIcon(Missle.class.getResource("/img/enemymissle_1.gif"));
mymissIcon1 = new ImageIcon(Missle.class.getResource("/img/tankmissle_1.gif"));
enemymissleIcon2 = new ImageIcon(Missle.class.getResource("/img/enemymissle_2.gif"));
mymissIcon2 = new ImageIcon(Missle.class.getResource("/img/tankmissle_2.gif"));
enemymissleIcon3 = new ImageIcon(Missle.class.getResource("/img/enemymissle_3.gif"));
mymissIcon3 = new ImageIcon(Missle.class.getResource("/img/tankmissle_3.gif"));
if(!self) {
if(SIZE >= 10 && SIZE <= 14) {
g.drawImage(enemymissleIcon2.getImage(), x, y, null);
} else if (SIZE >= 16 && SIZE <= 20) {
g.drawImage(enemymissleIcon1.getImage(), x, y, null);
} else {
g.drawImage(enemymissleIcon3.getImage(), x, y, null);
}
} else {
if(SIZE >= 10 && SIZE <= 14) {
g.drawImage(mymissIcon2.getImage(), x, y, null);
} else if (SIZE >= 16 && SIZE <= 20) {
g.drawImage(mymissIcon1.getImage(), x, y, null);
} else {
g.drawImage(mymissIcon3.getImage(), x, y, null);
}
}
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
| false | 2,437 | 5 | 2,879 | 7 | 2,776 | 3 | 2,879 | 7 | 3,643 | 9 | false | false | false | false | false | true |
53059_1 | package com.csx.util;
import java.util.Date;
import java.util.Random;
/**
* 打分工具类
* Created by csx on 2016/10/2.
*/
public class ScoreUtil {
//获取问题的分值
public static double getScoreQuestion(long qViews, int qAnswers, long qScore, long aScores, Date date_ask, Date date_active){
Random random=new Random();
qViews+=2;
// System.out.println("qViews:"+qViews+"--qAnswers:"+qAnswers+"--qScore:"+qScore+"--aScores:"+aScores);
Date dateNow=new Date();
double qAge=(dateNow.getTime()-date_ask.getTime())/3600000;
qAge=Math.round(qAge);
double qUpdated=(dateNow.getTime()-date_active.getTime())/3600000;
qUpdated=Math.round(qUpdated);
double dividend=Math.log10(qViews)*4+(qAnswers*qScore)/5+aScores;
// System.out.println("分子:"+dividend);
double divisor=Math.pow(((qAge+1)-(qAge-qUpdated)/2),1.5);
// System.out.println("分母:"+divisor);
return dividend/divisor;
}
//获取评论的分值,使用基于威尔逊区间的算法,此算法也在reddit评论上使用
public static double getScoreComment(long like,long dislike){
long n=like+dislike;
if(n==0){
return 0;
}
double z=1.0;
double phat=(double)like/n;
return (phat+z*z/(2*n)-z*Math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n);
}
}
| chensongxian/wenda | src/main/java/com/csx/util/ScoreUtil.java | 465 | //获取问题的分值 | line_comment | zh-cn | package com.csx.util;
import java.util.Date;
import java.util.Random;
/**
* 打分工具类
* Created by csx on 2016/10/2.
*/
public class ScoreUtil {
//获取 <SUF>
public static double getScoreQuestion(long qViews, int qAnswers, long qScore, long aScores, Date date_ask, Date date_active){
Random random=new Random();
qViews+=2;
// System.out.println("qViews:"+qViews+"--qAnswers:"+qAnswers+"--qScore:"+qScore+"--aScores:"+aScores);
Date dateNow=new Date();
double qAge=(dateNow.getTime()-date_ask.getTime())/3600000;
qAge=Math.round(qAge);
double qUpdated=(dateNow.getTime()-date_active.getTime())/3600000;
qUpdated=Math.round(qUpdated);
double dividend=Math.log10(qViews)*4+(qAnswers*qScore)/5+aScores;
// System.out.println("分子:"+dividend);
double divisor=Math.pow(((qAge+1)-(qAge-qUpdated)/2),1.5);
// System.out.println("分母:"+divisor);
return dividend/divisor;
}
//获取评论的分值,使用基于威尔逊区间的算法,此算法也在reddit评论上使用
public static double getScoreComment(long like,long dislike){
long n=like+dislike;
if(n==0){
return 0;
}
double z=1.0;
double phat=(double)like/n;
return (phat+z*z/(2*n)-z*Math.sqrt((phat*(1-phat)+z*z/(4*n))/n))/(1+z*z/n);
}
}
| false | 384 | 6 | 465 | 6 | 460 | 5 | 465 | 6 | 555 | 8 | false | false | false | false | false | true |
30720_10 | package com.JUtils.base;
import java.util.regex.Pattern;
/**
* --15位身份证号码:第7、8位为出生年份(两位数),第9、10位为出生月份,第11、12位代表出生日期,第15位代表性别,奇数为男,偶数为女。
* --18位身份证号码
* :第7、8、9、10位为出生年份(四位数),第11、第12位为出生月份,第13、14位代表出生日期,第17位代表性别,奇数为男,偶数为女。
*
* @Author:chenssy
* @date:2016年6月1日 下午12:29:41
*
*/
public class IdcardValidator {
/**
* 省,直辖市代码表: { 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",
* 21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",
* 33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",
* 42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",
* 51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",
* 63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}
*/
// 每位加权因子
private static int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
/**
* 验证身份证是否合法
*
* @author : chenssy
* @date : 2016年6月1日 下午12:30:03
*
* @param idcard
* @return
*/
@SuppressWarnings("static-access")
public boolean isValidatedAllIdcard(String idcard) {
return this.isValidate18Idcard(idcard);
}
/**
*
<p>
* 判断18位身份证的合法性
* </p>
* 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。
* 排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。
* <p>
* 顺序码: 表示在同一地址码所标识的区域范围内,对同年、同月、同 日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配 给女性。
* </p>
* <p>
* 1.前1、2位数字表示:所在省份的代码; 2.第3、4位数字表示:所在城市的代码; 3.第5、6位数字表示:所在区县的代码;
* 4.第7~14位数字表示:出生年、月、日; 5.第15、16位数字表示:所在地的派出所的代码;
* 6.第17位数字表示性别:奇数表示男性,偶数表示女性;
* 7.第18位数字是校检码:也有的说是个人信息码,一般是随计算机的随机产生,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示。
* </p>
* <p>
* 第十八位数字(校验码)的计算方法为: 1.将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4
* 2 1 6 3 7 9 10 5 8 4 2
* </p>
* <p>
* 2.将这17位数字和系数相乘的结果相加。
* </p>
* <p>
* 3.用加出来和除以11,看余数是多少?
* </p>
* 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3
* 2。
* <p>
* 5.通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2。
* </p>
*
* @author : chenssy
* @date : 2016年6月1日 下午12:31:10
*
* @param idcard
* 待验证的身份证
* @return
*/
public static boolean isValidate18Idcard(String idcard) {
// 非18位为假
if (idcard.length() != 18) {
return false;
}
// 获取前17位
String idcard17 = idcard.substring(0, 17);
// 获取第18位
String idcard18Code = idcard.substring(17, 18);
char c[] = null;
String checkCode = "";
// 是否都为数字
if (isDigital(idcard17)) {
c = idcard17.toCharArray();
} else {
return false;
}
if (null != c) {
int bit[] = new int[idcard17.length()];
bit = converCharToInt(c);
int sum17 = 0;
sum17 = getPowerSum(bit);
// 将和值与11取模得到余数进行校验码判断
checkCode = getCheckCodeBySum(sum17);
if (null == checkCode) {
return false;
}
// 将身份证的第18位与算出来的校码进行匹配,不相等就为假
if (!idcard18Code.equalsIgnoreCase(checkCode)) {
return false;
}
}
return true;
}
/**
* 18位身份证号码的基本数字和位数验校
*
* @author : chenssy
* @date : 2016年6月1日 下午12:31:49
*
* @param idcard
* 待验证的身份证
* @return
*/
public static boolean is18Idcard(String idcard) {
return Pattern.matches("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([\\d|x|X]{1})$", idcard);
}
/**
* 数字验证
*
* @author : chenssy
* @date : 2016年6月1日 下午12:32:18
*
* @param str
* @return
*/
private static boolean isDigital(String str) {
return str == null || "".equals(str) ? false : str.matches("^[0-9]*$");
}
/**
* 将身份证的每位和对应位的加权因子相乘之后,再得到和值
*
* @author : chenssy
* @date : 2016年6月1日 下午12:32:34
*
* @param bit
* @return
*/
private static int getPowerSum(int[] bit) {
int sum = 0;
if (power.length != bit.length) {
return sum;
}
for (int i = 0; i < bit.length; i++) {
for (int j = 0; j < power.length; j++) {
if (i == j) {
sum = sum + bit[i] * power[j];
}
}
}
return sum;
}
/**
* 将和值与11取模得到余数进行校验码判断
*
* @author : chenssy
* @date : 2016年6月1日 下午12:32:51
*
* @param sum17
* @return
*/
private static String getCheckCodeBySum(int sum17) {
String checkCode = null;
switch (sum17 % 11) {
case 10:
checkCode = "2";
break;
case 9:
checkCode = "3";
break;
case 8:
checkCode = "4";
break;
case 7:
checkCode = "5";
break;
case 6:
checkCode = "6";
break;
case 5:
checkCode = "7";
break;
case 4:
checkCode = "8";
break;
case 3:
checkCode = "9";
break;
case 2:
checkCode = "x";
break;
case 1:
checkCode = "0";
break;
case 0:
checkCode = "1";
break;
}
return checkCode;
}
/**
* 将字符数组转为整型数组
*
* @author : chenssy
* @date : 2016年6月1日 下午12:33:22
*
* @param c
* @return
* @throws NumberFormatException
*/
private static int[] converCharToInt(char[] c) throws NumberFormatException {
int[] a = new int[c.length];
int k = 0;
for (char temp : c) {
a[k++] = Integer.parseInt(String.valueOf(temp));
}
return a;
}
/**
*
* @param idno
* @return 身份证信息中代表性别的数值
*/
public static int getUserSex(String idno) {
String sex="1";
if(idno!=null){
if(idno.length()>15){
sex = idno.substring(16, 17);
}
}
return Integer.parseInt(sex) % 2==0 ? 0:1;
}
}
| chenssy89/jutils | src/main/java/com/JUtils/base/IdcardValidator.java | 2,770 | // 将身份证的第18位与算出来的校码进行匹配,不相等就为假 | line_comment | zh-cn | package com.JUtils.base;
import java.util.regex.Pattern;
/**
* --15位身份证号码:第7、8位为出生年份(两位数),第9、10位为出生月份,第11、12位代表出生日期,第15位代表性别,奇数为男,偶数为女。
* --18位身份证号码
* :第7、8、9、10位为出生年份(四位数),第11、第12位为出生月份,第13、14位代表出生日期,第17位代表性别,奇数为男,偶数为女。
*
* @Author:chenssy
* @date:2016年6月1日 下午12:29:41
*
*/
public class IdcardValidator {
/**
* 省,直辖市代码表: { 11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",
* 21:"辽宁",22:"吉林",23:"黑龙江",31:"上海",32:"江苏",
* 33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",
* 42:"湖北",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",
* 51:"四川",52:"贵州",53:"云南",54:"西藏",61:"陕西",62:"甘肃",
* 63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外"}
*/
// 每位加权因子
private static int power[] = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 };
/**
* 验证身份证是否合法
*
* @author : chenssy
* @date : 2016年6月1日 下午12:30:03
*
* @param idcard
* @return
*/
@SuppressWarnings("static-access")
public boolean isValidatedAllIdcard(String idcard) {
return this.isValidate18Idcard(idcard);
}
/**
*
<p>
* 判断18位身份证的合法性
* </p>
* 根据〖中华人民共和国国家标准GB11643-1999〗中有关公民身份号码的规定,公民身份号码是特征组合码,由十七位数字本体码和一位数字校验码组成。
* 排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码。
* <p>
* 顺序码: 表示在同一地址码所标识的区域范围内,对同年、同月、同 日出生的人编定的顺序号,顺序码的奇数分配给男性,偶数分配 给女性。
* </p>
* <p>
* 1.前1、2位数字表示:所在省份的代码; 2.第3、4位数字表示:所在城市的代码; 3.第5、6位数字表示:所在区县的代码;
* 4.第7~14位数字表示:出生年、月、日; 5.第15、16位数字表示:所在地的派出所的代码;
* 6.第17位数字表示性别:奇数表示男性,偶数表示女性;
* 7.第18位数字是校检码:也有的说是个人信息码,一般是随计算机的随机产生,用来检验身份证的正确性。校检码可以是0~9的数字,有时也用x表示。
* </p>
* <p>
* 第十八位数字(校验码)的计算方法为: 1.将前面的身份证号码17位数分别乘以不同的系数。从第一位到第十七位的系数分别为:7 9 10 5 8 4
* 2 1 6 3 7 9 10 5 8 4 2
* </p>
* <p>
* 2.将这17位数字和系数相乘的结果相加。
* </p>
* <p>
* 3.用加出来和除以11,看余数是多少?
* </p>
* 4.余数只可能有0 1 2 3 4 5 6 7 8 9 10这11个数字。其分别对应的最后一位身份证的号码为1 0 X 9 8 7 6 5 4 3
* 2。
* <p>
* 5.通过上面得知如果余数是2,就会在身份证的第18位数字上出现罗马数字的Ⅹ。如果余数是10,身份证的最后一位号码就是2。
* </p>
*
* @author : chenssy
* @date : 2016年6月1日 下午12:31:10
*
* @param idcard
* 待验证的身份证
* @return
*/
public static boolean isValidate18Idcard(String idcard) {
// 非18位为假
if (idcard.length() != 18) {
return false;
}
// 获取前17位
String idcard17 = idcard.substring(0, 17);
// 获取第18位
String idcard18Code = idcard.substring(17, 18);
char c[] = null;
String checkCode = "";
// 是否都为数字
if (isDigital(idcard17)) {
c = idcard17.toCharArray();
} else {
return false;
}
if (null != c) {
int bit[] = new int[idcard17.length()];
bit = converCharToInt(c);
int sum17 = 0;
sum17 = getPowerSum(bit);
// 将和值与11取模得到余数进行校验码判断
checkCode = getCheckCodeBySum(sum17);
if (null == checkCode) {
return false;
}
// 将身 <SUF>
if (!idcard18Code.equalsIgnoreCase(checkCode)) {
return false;
}
}
return true;
}
/**
* 18位身份证号码的基本数字和位数验校
*
* @author : chenssy
* @date : 2016年6月1日 下午12:31:49
*
* @param idcard
* 待验证的身份证
* @return
*/
public static boolean is18Idcard(String idcard) {
return Pattern.matches("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([\\d|x|X]{1})$", idcard);
}
/**
* 数字验证
*
* @author : chenssy
* @date : 2016年6月1日 下午12:32:18
*
* @param str
* @return
*/
private static boolean isDigital(String str) {
return str == null || "".equals(str) ? false : str.matches("^[0-9]*$");
}
/**
* 将身份证的每位和对应位的加权因子相乘之后,再得到和值
*
* @author : chenssy
* @date : 2016年6月1日 下午12:32:34
*
* @param bit
* @return
*/
private static int getPowerSum(int[] bit) {
int sum = 0;
if (power.length != bit.length) {
return sum;
}
for (int i = 0; i < bit.length; i++) {
for (int j = 0; j < power.length; j++) {
if (i == j) {
sum = sum + bit[i] * power[j];
}
}
}
return sum;
}
/**
* 将和值与11取模得到余数进行校验码判断
*
* @author : chenssy
* @date : 2016年6月1日 下午12:32:51
*
* @param sum17
* @return
*/
private static String getCheckCodeBySum(int sum17) {
String checkCode = null;
switch (sum17 % 11) {
case 10:
checkCode = "2";
break;
case 9:
checkCode = "3";
break;
case 8:
checkCode = "4";
break;
case 7:
checkCode = "5";
break;
case 6:
checkCode = "6";
break;
case 5:
checkCode = "7";
break;
case 4:
checkCode = "8";
break;
case 3:
checkCode = "9";
break;
case 2:
checkCode = "x";
break;
case 1:
checkCode = "0";
break;
case 0:
checkCode = "1";
break;
}
return checkCode;
}
/**
* 将字符数组转为整型数组
*
* @author : chenssy
* @date : 2016年6月1日 下午12:33:22
*
* @param c
* @return
* @throws NumberFormatException
*/
private static int[] converCharToInt(char[] c) throws NumberFormatException {
int[] a = new int[c.length];
int k = 0;
for (char temp : c) {
a[k++] = Integer.parseInt(String.valueOf(temp));
}
return a;
}
/**
*
* @param idno
* @return 身份证信息中代表性别的数值
*/
public static int getUserSex(String idno) {
String sex="1";
if(idno!=null){
if(idno.length()>15){
sex = idno.substring(16, 17);
}
}
return Integer.parseInt(sex) % 2==0 ? 0:1;
}
}
| false | 2,507 | 23 | 2,768 | 24 | 2,711 | 21 | 2,770 | 24 | 3,509 | 37 | false | false | false | false | false | true |
55539_0 | package com.chen.dayaction.designpattern.template9;
import com.chen.dayaction.designpattern.template9.beverage.Coffee;
import com.chen.dayaction.designpattern.template9.beverage.CoffeeBeverage;
import com.chen.dayaction.designpattern.template9.beverage.Tea;
/**
* 泡茶与咖啡案例:
* 茶和咖啡的冲泡方式非常相似:
* 冲咖啡:1)把水煮沸2)用沸水冲泡咖啡3)把咖啡倒进杯子4)加糖和牛奶
* 冲泡茶:1)把水煮沸2)用沸水浸泡茶叶3)把茶倒进杯子4)加柠檬
* 封装算法。两种饮料的冲泡方法是基本相同的,只是一些步骤需要不同的实现。所以我们泛化了冲泡方法,把它放在基类。
* 一些步骤依赖子类进行,咖啡因饮料基类了解和控制冲泡方法的步骤,亲自执行步骤1和步骤3,依赖具体子类实现来完成步骤2和步骤4.
* */
public class CoffeeBeverageDemo {
public static void main(String[] args) {
CoffeeBeverage tea = new Tea();
tea.prepareRecipe();
CoffeeBeverage coffee = new Coffee();
coffee.prepareRecipe();
}
}
| chentian114/100-dayaction | designpattern-1/src/main/java/com/chen/dayaction/designpattern/template9/CoffeeBeverageDemo.java | 375 | /**
* 泡茶与咖啡案例:
* 茶和咖啡的冲泡方式非常相似:
* 冲咖啡:1)把水煮沸2)用沸水冲泡咖啡3)把咖啡倒进杯子4)加糖和牛奶
* 冲泡茶:1)把水煮沸2)用沸水浸泡茶叶3)把茶倒进杯子4)加柠檬
* 封装算法。两种饮料的冲泡方法是基本相同的,只是一些步骤需要不同的实现。所以我们泛化了冲泡方法,把它放在基类。
* 一些步骤依赖子类进行,咖啡因饮料基类了解和控制冲泡方法的步骤,亲自执行步骤1和步骤3,依赖具体子类实现来完成步骤2和步骤4.
* */ | block_comment | zh-cn | package com.chen.dayaction.designpattern.template9;
import com.chen.dayaction.designpattern.template9.beverage.Coffee;
import com.chen.dayaction.designpattern.template9.beverage.CoffeeBeverage;
import com.chen.dayaction.designpattern.template9.beverage.Tea;
/**
* 泡茶与 <SUF>*/
public class CoffeeBeverageDemo {
public static void main(String[] args) {
CoffeeBeverage tea = new Tea();
tea.prepareRecipe();
CoffeeBeverage coffee = new Coffee();
coffee.prepareRecipe();
}
}
| false | 282 | 169 | 375 | 233 | 311 | 174 | 375 | 233 | 543 | 381 | false | false | false | false | false | true |
58555_2 | /**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package me.ctf.lm.util;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.List;
/**
* 分页工具类
*
* @author Mark sunlightcs@gmail.com
*/
public class PageUtils implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 总记录数
*/
private int totalCount;
/**
* 每页记录数
*/
private int pageSize;
/**
* 总页数
*/
private int totalPage;
/**
* 当前页数
*/
private int currPage;
/**
* 列表数据
*/
private List<?> list;
/**
* 分页
* @param list 列表数据
* @param totalCount 总记录数
* @param pageSize 每页记录数
* @param currPage 当前页数
*/
public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
}
/**
* 分页
*/
public PageUtils(IPage<?> page) {
this.list = page.getRecords();
this.totalCount = (int)page.getTotal();
this.pageSize = (int)page.getSize();
this.currPage = (int)page.getCurrent();
this.totalPage = (int)page.getPages();
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
| chentiefeng/lite-monitor | src/main/java/me/ctf/lm/util/PageUtils.java | 663 | /**
* 总记录数
*/ | block_comment | zh-cn | /**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package me.ctf.lm.util;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.List;
/**
* 分页工具类
*
* @author Mark sunlightcs@gmail.com
*/
public class PageUtils implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 总记录 <SUF>*/
private int totalCount;
/**
* 每页记录数
*/
private int pageSize;
/**
* 总页数
*/
private int totalPage;
/**
* 当前页数
*/
private int currPage;
/**
* 列表数据
*/
private List<?> list;
/**
* 分页
* @param list 列表数据
* @param totalCount 总记录数
* @param pageSize 每页记录数
* @param currPage 当前页数
*/
public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
}
/**
* 分页
*/
public PageUtils(IPage<?> page) {
this.list = page.getRecords();
this.totalCount = (int)page.getTotal();
this.pageSize = (int)page.getSize();
this.currPage = (int)page.getCurrent();
this.totalPage = (int)page.getPages();
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
| false | 535 | 10 | 663 | 9 | 653 | 10 | 663 | 9 | 783 | 14 | false | false | false | false | false | true |
31684_6 | package weizheTest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Semaphore;
public class Ticket {
private int ticketNum;// 票数
private String time;
private String start,end;
Semaphore semaphore = new Semaphore(1);//信号量
public Ticket(int ticketNum,String time,String start,String end) {
this.ticketNum = ticketNum;
this.time = time;
this.start = start;
this.end = end;
}
// 取票,票数减一
public void getTicket(String name) throws InterruptedException {
semaphore.acquire(); //P操作
if (ticketNum >= 1) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println("--------------------------------------");
System.out.println(time+"--"+start+" 开往 "+end+"的班车");
System.out.println(name + " 买票成功,号码=" + ticketNum+" 购票时间"+df.format(new Date()));
this.subTicketNum();
System.out.println("当前还有 "+semaphore.getQueueLength()+"人在等待买票 ");
// System.out.println("--------------------------------------");
} else {// 票数为0
System.out.println("--------------------------------------");
System.out.println("票已经售完 " + name + " 没有买到票");
System.out.println("--------------------------------------");
}
semaphore.release(); //V操作
}
public void subTicketNum() {
if (this.ticketNum > 0)
this.ticketNum = this.ticketNum - 1;
}
public int getTicketNum() {
return ticketNum;
}
public String getStart() {
return start;
}
public String getEnd() {
return end;
}
}
| chenweizhe/weizheTest | src/weizheTest/Ticket.java | 457 | // 票数为0
| line_comment | zh-cn | package weizheTest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Semaphore;
public class Ticket {
private int ticketNum;// 票数
private String time;
private String start,end;
Semaphore semaphore = new Semaphore(1);//信号量
public Ticket(int ticketNum,String time,String start,String end) {
this.ticketNum = ticketNum;
this.time = time;
this.start = start;
this.end = end;
}
// 取票,票数减一
public void getTicket(String name) throws InterruptedException {
semaphore.acquire(); //P操作
if (ticketNum >= 1) {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println("--------------------------------------");
System.out.println(time+"--"+start+" 开往 "+end+"的班车");
System.out.println(name + " 买票成功,号码=" + ticketNum+" 购票时间"+df.format(new Date()));
this.subTicketNum();
System.out.println("当前还有 "+semaphore.getQueueLength()+"人在等待买票 ");
// System.out.println("--------------------------------------");
} else {// 票数 <SUF>
System.out.println("--------------------------------------");
System.out.println("票已经售完 " + name + " 没有买到票");
System.out.println("--------------------------------------");
}
semaphore.release(); //V操作
}
public void subTicketNum() {
if (this.ticketNum > 0)
this.ticketNum = this.ticketNum - 1;
}
public int getTicketNum() {
return ticketNum;
}
public String getStart() {
return start;
}
public String getEnd() {
return end;
}
}
| false | 383 | 8 | 455 | 7 | 482 | 7 | 455 | 7 | 584 | 9 | false | false | false | false | false | true |
18867_0 | package other;
/**
* @Author: Wenhang Chen
* @Description:你和你的朋友,两个人一起玩 Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。
* <p>
* 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
* 示例:
* <p>
* 输入: 4
* 输出: false
* 解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
* 因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
* @Date: Created in 12:08 12/7/2019
* @Modified by:
*/
public class NimGame {
public boolean canWinNim(int n) {
// a % (2^n) 等价于 a & (2^n - 1)
return (n & 3) != 0;
}
}
| chenwenhang/AlgorithmPractice | src/other/NimGame.java | 313 | /**
* @Author: Wenhang Chen
* @Description:你和你的朋友,两个人一起玩 Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。
* <p>
* 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
* 示例:
* <p>
* 输入: 4
* 输出: false
* 解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛;
* 因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。
* @Date: Created in 12:08 12/7/2019
* @Modified by:
*/ | block_comment | zh-cn | package other;
/**
* @Au <SUF>*/
public class NimGame {
public boolean canWinNim(int n) {
// a % (2^n) 等价于 a & (2^n - 1)
return (n & 3) != 0;
}
}
| false | 267 | 208 | 313 | 249 | 267 | 202 | 313 | 249 | 446 | 353 | false | false | false | false | false | true |
57043_6 | //一道做过挺多次的题了?以至于第一眼看过去还是会想用一个array来存访问过的字符
public class Solution {
/**
* @param s: a string
* @return: an integer
*/
public int lengthOfLongestSubstring(String s) {
// write your code here
int result = 0, leftIndex = 0;
if (s == null || s.length() == 0) return result;
// ASCII一共256个?256个应该够了。。。
int[] alphabetCount = new int[256];
char[] charArray = s.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char currChar = charArray[i];
if (alphabetCount[currChar] == 0) {
alphabetCount[currChar]++;
} else {
result = result < (i - leftIndex) ? (i - leftIndex) : result;
while (charArray[leftIndex] != currChar) {
alphabetCount[charArray[leftIndex]]--;
leftIndex++;
}
leftIndex++;
}
}
// 最后还要再判断一下,老是忘记这里所以不能一次过。。。
result = result < (s.length() - leftIndex) ? (s.length() - leftIndex) : result;
return result;
}
}
//一道滑动窗口的经典题
//视频里讲的解法:和不看视频自己写的思路一样,但是while loop写的更明智。也不需要跳出for循环后再判断一遍了
//我的方法是for循环rightIndex, 视频是for循环leftIndex, 显然后者更明智,注意如何合并while循环条件
public class Solution {
/**
* @param s: a string
* @return: an integer
*/
public int lengthOfLongestSubstring(String s) {
// write your code here
int result = 0;
if (s == null || s.length() == 0) return result;
char[] charArray = s.toCharArray();
int[] alphabetCount = new int[256];
int leftIndex = 0, rightIndex = 0;
for (; leftIndex < charArray.length; leftIndex++) {
while (rightIndex < charArray.length && alphabetCount[charArray[rightIndex]] == 0) {
alphabetCount[charArray[rightIndex]]++;
rightIndex++;
result = result < (rightIndex - leftIndex) ? (rightIndex - leftIndex) : result;
}
alphabetCount[charArray[leftIndex]] = 0;
}
return result;
}
}
| chenxi1103/Coding-Practice | 2019/2019-06-23/sliding window/384. Longest Substring Without Repeating Characters.java | 609 | //视频里讲的解法:和不看视频自己写的思路一样,但是while loop写的更明智。也不需要跳出for循环后再判断一遍了 | line_comment | zh-cn | //一道做过挺多次的题了?以至于第一眼看过去还是会想用一个array来存访问过的字符
public class Solution {
/**
* @param s: a string
* @return: an integer
*/
public int lengthOfLongestSubstring(String s) {
// write your code here
int result = 0, leftIndex = 0;
if (s == null || s.length() == 0) return result;
// ASCII一共256个?256个应该够了。。。
int[] alphabetCount = new int[256];
char[] charArray = s.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char currChar = charArray[i];
if (alphabetCount[currChar] == 0) {
alphabetCount[currChar]++;
} else {
result = result < (i - leftIndex) ? (i - leftIndex) : result;
while (charArray[leftIndex] != currChar) {
alphabetCount[charArray[leftIndex]]--;
leftIndex++;
}
leftIndex++;
}
}
// 最后还要再判断一下,老是忘记这里所以不能一次过。。。
result = result < (s.length() - leftIndex) ? (s.length() - leftIndex) : result;
return result;
}
}
//一道滑动窗口的经典题
//视频 <SUF>
//我的方法是for循环rightIndex, 视频是for循环leftIndex, 显然后者更明智,注意如何合并while循环条件
public class Solution {
/**
* @param s: a string
* @return: an integer
*/
public int lengthOfLongestSubstring(String s) {
// write your code here
int result = 0;
if (s == null || s.length() == 0) return result;
char[] charArray = s.toCharArray();
int[] alphabetCount = new int[256];
int leftIndex = 0, rightIndex = 0;
for (; leftIndex < charArray.length; leftIndex++) {
while (rightIndex < charArray.length && alphabetCount[charArray[rightIndex]] == 0) {
alphabetCount[charArray[rightIndex]]++;
rightIndex++;
result = result < (rightIndex - leftIndex) ? (rightIndex - leftIndex) : result;
}
alphabetCount[charArray[leftIndex]] = 0;
}
return result;
}
}
| false | 569 | 33 | 609 | 40 | 636 | 35 | 609 | 40 | 760 | 67 | false | false | false | false | false | true |
61139_2 | package com.cxp.jboa.dao;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import com.cxp.jboa.entity.Mails;
public interface MailsMapper {
//分页查询收到的邮件
List<Mails> listMails(Map<String, Object> map);
//得到邮件总个数
int getTotalCount(Map<String, Object> map);
int deleteByPrimaryKey(BigDecimal id);
//写邮件
int insert(Mails record);
int insertSelective(Mails record);
//查询邮件详细信息
Mails selectById(BigDecimal id);
//删除邮件到垃圾箱
int delToGarage(Mails record);
//得到垃圾邮件
List<Mails> getMailGarage();
//还原邮件
int garageBack(Mails mails);
//彻底删除邮件
int garageDel(Mails mails);
int updateByPrimaryKey(Mails record);
} | chenxiaopan/jboa | src/main/java/com/cxp/jboa/dao/MailsMapper.java | 248 | //写邮件 | line_comment | zh-cn | package com.cxp.jboa.dao;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import com.cxp.jboa.entity.Mails;
public interface MailsMapper {
//分页查询收到的邮件
List<Mails> listMails(Map<String, Object> map);
//得到邮件总个数
int getTotalCount(Map<String, Object> map);
int deleteByPrimaryKey(BigDecimal id);
//写邮 <SUF>
int insert(Mails record);
int insertSelective(Mails record);
//查询邮件详细信息
Mails selectById(BigDecimal id);
//删除邮件到垃圾箱
int delToGarage(Mails record);
//得到垃圾邮件
List<Mails> getMailGarage();
//还原邮件
int garageBack(Mails mails);
//彻底删除邮件
int garageDel(Mails mails);
int updateByPrimaryKey(Mails record);
} | false | 195 | 3 | 248 | 3 | 234 | 3 | 248 | 3 | 336 | 6 | false | false | false | false | false | true |
58912_2 | package com.bocweb.fly.locatecenterhorizontalview;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import com.bocweb.fly.locatecenterhorizontalview.view.LocateCenterHorizontalView;
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 fly on 2018/4/4.
*/
public class MainActivity extends AppCompatActivity {
LocateCenterHorizontalView zhouText;
RecyclerView zhouImage;
List<ContinentModel> list;
IndexZhouTextAdapter zhouTextAdapter;
IndexZhouImageAdapter zhouImageAdapter;
int circle = 250;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
EventBus.getDefault().register(this);
zhouImage = findViewById(R.id.zhouImage);
zhouText = findViewById(R.id.zhouText);
initData();
initZhouText();
zhouImage.setHasFixedSize(true);
zhouImage.setLayoutManager(new LinearLayoutManager(this));
zhouImageAdapter = new IndexZhouImageAdapter(this, list);
zhouImage.setAdapter(zhouImageAdapter);
zhouImage.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (move) {
move = false;
LinearLayoutManager layoutManager = (LinearLayoutManager) zhouImage.getLayoutManager();
int n = mIndex - layoutManager.findFirstVisibleItemPosition();
if (0 <= n && n < zhouImage.getChildCount()) {
//获取要置顶的项顶部离RecyclerView顶部的距离
int top = zhouImage.getChildAt(n).getTop();
//最后的移动
zhouImage.scrollBy(0, top);
}
}
}
});
}
private void initZhouText() {
zhouText.setHasFixedSize(true);
zhouText.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
zhouTextAdapter = new IndexZhouTextAdapter(this, list, circle);
zhouText.setAdapter(zhouTextAdapter);
zhouText.setOnSelectedPositionChangedListener(new LocateCenterHorizontalView.OnSelectedPositionChangedListener() {
@Override
public void selectedPositionChanged(int pos) {
if (zhouTextAdapter.getData().size() > 0) {
int i = pos % zhouTextAdapter.getData().size();
// zhouImage.smoothScrollToPosition(i)
moveToPosition(i);
}
}
});
}
boolean move = false;
int mIndex = 0;
private void moveToPosition(int n) {
mIndex = n;
//先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
LinearLayoutManager layoutManager = (LinearLayoutManager) zhouImage.getLayoutManager();
int firstItem = layoutManager.findFirstVisibleItemPosition();
int lastItem = layoutManager.findLastVisibleItemPosition();
//然后区分情况
if (n <= firstItem) {
//当要置顶的项在当前显示的第一个项的前面时
zhouImage.smoothScrollToPosition(n);
} else if (n <= lastItem) {
//当要置顶的项已经在屏幕上显示时
int top = zhouImage.getChildAt(n - firstItem).getTop();
zhouImage.scrollBy(0, top);
} else {
//当要置顶的项在当前显示的最后一项的后面时
zhouImage.scrollToPosition(n);
//这里这个变量是用在RecyclerView滚动监听里面的
move = true;
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(ZhouTextClickEvent e) {
zhouText.moveToPosition(e.position);
}
private void initData() {
list = new ArrayList<>();
list.add(new ContinentModel(0, "亚洲", "1"));
list.add(new ContinentModel(1, "欧洲", "2"));
list.add(new ContinentModel(2, "大洋洲", "3"));
list.add(new ContinentModel(3, "非洲", "4"));
list.add(new ContinentModel(4, "南美洲", "5"));
list.add(new ContinentModel(5, "北美洲", "6"));
list.add(new ContinentModel(6, "南极洲", "7"));
}
}
| chenxinfei/LocateCenterHorizontalView | app/src/main/java/com/bocweb/fly/locatecenterhorizontalview/MainActivity.java | 1,175 | //最后的移动 | line_comment | zh-cn | package com.bocweb.fly.locatecenterhorizontalview;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.ImageView;
import com.bocweb.fly.locatecenterhorizontalview.view.LocateCenterHorizontalView;
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 fly on 2018/4/4.
*/
public class MainActivity extends AppCompatActivity {
LocateCenterHorizontalView zhouText;
RecyclerView zhouImage;
List<ContinentModel> list;
IndexZhouTextAdapter zhouTextAdapter;
IndexZhouImageAdapter zhouImageAdapter;
int circle = 250;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
EventBus.getDefault().register(this);
zhouImage = findViewById(R.id.zhouImage);
zhouText = findViewById(R.id.zhouText);
initData();
initZhouText();
zhouImage.setHasFixedSize(true);
zhouImage.setLayoutManager(new LinearLayoutManager(this));
zhouImageAdapter = new IndexZhouImageAdapter(this, list);
zhouImage.setAdapter(zhouImageAdapter);
zhouImage.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (move) {
move = false;
LinearLayoutManager layoutManager = (LinearLayoutManager) zhouImage.getLayoutManager();
int n = mIndex - layoutManager.findFirstVisibleItemPosition();
if (0 <= n && n < zhouImage.getChildCount()) {
//获取要置顶的项顶部离RecyclerView顶部的距离
int top = zhouImage.getChildAt(n).getTop();
//最后 <SUF>
zhouImage.scrollBy(0, top);
}
}
}
});
}
private void initZhouText() {
zhouText.setHasFixedSize(true);
zhouText.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false));
zhouTextAdapter = new IndexZhouTextAdapter(this, list, circle);
zhouText.setAdapter(zhouTextAdapter);
zhouText.setOnSelectedPositionChangedListener(new LocateCenterHorizontalView.OnSelectedPositionChangedListener() {
@Override
public void selectedPositionChanged(int pos) {
if (zhouTextAdapter.getData().size() > 0) {
int i = pos % zhouTextAdapter.getData().size();
// zhouImage.smoothScrollToPosition(i)
moveToPosition(i);
}
}
});
}
boolean move = false;
int mIndex = 0;
private void moveToPosition(int n) {
mIndex = n;
//先从RecyclerView的LayoutManager中获取第一项和最后一项的Position
LinearLayoutManager layoutManager = (LinearLayoutManager) zhouImage.getLayoutManager();
int firstItem = layoutManager.findFirstVisibleItemPosition();
int lastItem = layoutManager.findLastVisibleItemPosition();
//然后区分情况
if (n <= firstItem) {
//当要置顶的项在当前显示的第一个项的前面时
zhouImage.smoothScrollToPosition(n);
} else if (n <= lastItem) {
//当要置顶的项已经在屏幕上显示时
int top = zhouImage.getChildAt(n - firstItem).getTop();
zhouImage.scrollBy(0, top);
} else {
//当要置顶的项在当前显示的最后一项的后面时
zhouImage.scrollToPosition(n);
//这里这个变量是用在RecyclerView滚动监听里面的
move = true;
}
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(ZhouTextClickEvent e) {
zhouText.moveToPosition(e.position);
}
private void initData() {
list = new ArrayList<>();
list.add(new ContinentModel(0, "亚洲", "1"));
list.add(new ContinentModel(1, "欧洲", "2"));
list.add(new ContinentModel(2, "大洋洲", "3"));
list.add(new ContinentModel(3, "非洲", "4"));
list.add(new ContinentModel(4, "南美洲", "5"));
list.add(new ContinentModel(5, "北美洲", "6"));
list.add(new ContinentModel(6, "南极洲", "7"));
}
}
| false | 989 | 4 | 1,175 | 4 | 1,174 | 3 | 1,175 | 4 | 1,399 | 6 | false | false | false | false | false | true |
19716_24 | package com.briup.environment.gui;
import java.awt.*;
import java.util.List;
import com.briup.environment.bean.MaxMinAvg;
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.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;
/**
* @Author: cxx
* 生成报表类
* @Date: 2018/6/13 8:56
*/
public class BarChartServlet {
//构造函数,初始化面板
public BarChartServlet(List<MaxMinAvg> list,int day){
//获取数据
CategoryDataset dataset = getDataset(list);
String title="";
if (list.size()==1) {
title=day+"号数据统计";
}else {
title=day+"号所有数据统计";
}
//创建图形实体对象
JFreeChart chart=ChartFactory.createBarChart3D(//工厂模式
title, //图形的标题
"", //目录轴的显示标签(X轴)
"值", //数据轴的显示标签(Y轴)
dataset, //数据集
PlotOrientation.VERTICAL, //垂直显示图形
true, //是否生成图样
true, //是否生成提示工具
false);//是否生成URL链接
CategoryPlot plot=chart.getCategoryPlot();//获取图形区域对象
BarRenderer3D renderer = new BarRenderer3D();//3D属性修改
//设置网格竖线颜色
plot.setDomainGridlinePaint(Color.blue);
plot.setDomainGridlinesVisible(true);
//设置网格横线颜色
plot.setRangeGridlinePaint(Color.blue);
plot.setRangeGridlinesVisible(true);
//图片背景色
plot.setBackgroundPaint(Color.LIGHT_GRAY);
plot.setOutlineVisible(true);
//图边框颜色
plot.setOutlinePaint(Color.magenta);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelPaint(Color.black);//设置数值颜色,默认黑色
renderer.setBaseItemLabelFont(new Font("微软雅黑",Font.PLAIN,13));
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER));
renderer.setItemLabelAnchorOffset(15);
plot.setRenderer(renderer);
//------------------------------------------获取X轴
CategoryAxis domainAxis=plot.getDomainAxis();
domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14));//设置X轴的标题的字体
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,15));//设置X轴坐标上的字体
domainAxis.setTickLabelsVisible(true);//X轴的标题文字是否显示
//-----------------------------------------获取Y轴
ValueAxis rangeAxis=plot.getRangeAxis();
rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15));//设置Y轴坐标上的标题字体
//设置图样的文字样式
chart.getLegend().setItemFont(new Font("黑体",Font.BOLD ,15));
//设置图形的标题
chart.getTitle().setFont(new Font("宋体",Font.BOLD ,20));
frame1 =new ChartPanel(chart,true);//将已经画好的图形报表存放到面板中
}
//用于获取数据
private static CategoryDataset getDataset(List<MaxMinAvg> list){
DefaultCategoryDataset dataset=new DefaultCategoryDataset();//创建数据集对象
//往数据集对象中添加数据(实际应用中是从数据库,Excel文件或者文本文件中获取数据,这里为了方便起见将数据直接给出)
System.out.println("============"+list.size());
String msg="";
if (list.size()==1){
switch (list.get(0).getType()){
case 1:msg="温度";break;
case 2:msg="湿度";break;
case 3:msg="光照强度";break;
default:msg="二氧化碳";break;
}
dataset.addValue(list.get(0).getMin(),"最小值",msg);//数据值,X轴,Y轴
dataset.addValue(list.get(0).getMax(),"最大值",msg);
dataset.addValue(list.get(0).getAvg(),"平均值",msg);
}else if (list.size()==4){
for (MaxMinAvg value : list) {
switch (value.getType()){
case 1:msg="温度";break;
case 2:msg="湿度";break;
case 3:msg="光照强度";break;
default:msg="二氧化碳";break;
}
dataset.addValue(value.getMin(),"最小值",msg);
dataset.addValue(value.getMax(),"最大值",msg);
dataset.addValue(value.getAvg(),"平均值",msg);
}
}
return dataset;
}
//构建容器面板,用于存放已经画好的图形报表
private ChartPanel frame1;
//在构造方法中将图形报表初始化
//构建一个方法,用于获取存放了图形的面板(封装:隐藏具体实现)
public ChartPanel getChartPanel(){
return frame1;
}
}
| chenxingxing6/EMDC | src/main/java/com/briup/environment/gui/BarChartServlet.java | 1,422 | //-----------------------------------------获取Y轴
| line_comment | zh-cn | package com.briup.environment.gui;
import java.awt.*;
import java.util.List;
import com.briup.environment.bean.MaxMinAvg;
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.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;
/**
* @Author: cxx
* 生成报表类
* @Date: 2018/6/13 8:56
*/
public class BarChartServlet {
//构造函数,初始化面板
public BarChartServlet(List<MaxMinAvg> list,int day){
//获取数据
CategoryDataset dataset = getDataset(list);
String title="";
if (list.size()==1) {
title=day+"号数据统计";
}else {
title=day+"号所有数据统计";
}
//创建图形实体对象
JFreeChart chart=ChartFactory.createBarChart3D(//工厂模式
title, //图形的标题
"", //目录轴的显示标签(X轴)
"值", //数据轴的显示标签(Y轴)
dataset, //数据集
PlotOrientation.VERTICAL, //垂直显示图形
true, //是否生成图样
true, //是否生成提示工具
false);//是否生成URL链接
CategoryPlot plot=chart.getCategoryPlot();//获取图形区域对象
BarRenderer3D renderer = new BarRenderer3D();//3D属性修改
//设置网格竖线颜色
plot.setDomainGridlinePaint(Color.blue);
plot.setDomainGridlinesVisible(true);
//设置网格横线颜色
plot.setRangeGridlinePaint(Color.blue);
plot.setRangeGridlinesVisible(true);
//图片背景色
plot.setBackgroundPaint(Color.LIGHT_GRAY);
plot.setOutlineVisible(true);
//图边框颜色
plot.setOutlinePaint(Color.magenta);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelPaint(Color.black);//设置数值颜色,默认黑色
renderer.setBaseItemLabelFont(new Font("微软雅黑",Font.PLAIN,13));
renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.CENTER));
renderer.setItemLabelAnchorOffset(15);
plot.setRenderer(renderer);
//------------------------------------------获取X轴
CategoryAxis domainAxis=plot.getDomainAxis();
domainAxis.setLabelFont(new Font("黑体",Font.BOLD,14));//设置X轴的标题的字体
domainAxis.setTickLabelFont(new Font("宋体",Font.BOLD,15));//设置X轴坐标上的字体
domainAxis.setTickLabelsVisible(true);//X轴的标题文字是否显示
//-- <SUF>
ValueAxis rangeAxis=plot.getRangeAxis();
rangeAxis.setLabelFont(new Font("黑体",Font.BOLD,15));//设置Y轴坐标上的标题字体
//设置图样的文字样式
chart.getLegend().setItemFont(new Font("黑体",Font.BOLD ,15));
//设置图形的标题
chart.getTitle().setFont(new Font("宋体",Font.BOLD ,20));
frame1 =new ChartPanel(chart,true);//将已经画好的图形报表存放到面板中
}
//用于获取数据
private static CategoryDataset getDataset(List<MaxMinAvg> list){
DefaultCategoryDataset dataset=new DefaultCategoryDataset();//创建数据集对象
//往数据集对象中添加数据(实际应用中是从数据库,Excel文件或者文本文件中获取数据,这里为了方便起见将数据直接给出)
System.out.println("============"+list.size());
String msg="";
if (list.size()==1){
switch (list.get(0).getType()){
case 1:msg="温度";break;
case 2:msg="湿度";break;
case 3:msg="光照强度";break;
default:msg="二氧化碳";break;
}
dataset.addValue(list.get(0).getMin(),"最小值",msg);//数据值,X轴,Y轴
dataset.addValue(list.get(0).getMax(),"最大值",msg);
dataset.addValue(list.get(0).getAvg(),"平均值",msg);
}else if (list.size()==4){
for (MaxMinAvg value : list) {
switch (value.getType()){
case 1:msg="温度";break;
case 2:msg="湿度";break;
case 3:msg="光照强度";break;
default:msg="二氧化碳";break;
}
dataset.addValue(value.getMin(),"最小值",msg);
dataset.addValue(value.getMax(),"最大值",msg);
dataset.addValue(value.getAvg(),"平均值",msg);
}
}
return dataset;
}
//构建容器面板,用于存放已经画好的图形报表
private ChartPanel frame1;
//在构造方法中将图形报表初始化
//构建一个方法,用于获取存放了图形的面板(封装:隐藏具体实现)
public ChartPanel getChartPanel(){
return frame1;
}
}
| false | 1,193 | 6 | 1,404 | 7 | 1,422 | 8 | 1,404 | 7 | 1,843 | 12 | false | false | false | false | false | true |
58543_7 | package com.peace.pms.util;
/**
* 授权展示方式
* @Author: cxx
* @Date: 2018/3/1 15:45
*/
public enum Display {
DEFAULT("default"), //适用:sina ————默认的授权页面,适用于web浏览器。
PAGE("page"), //适用:人人,百度 ————全屏形式的授权页面(默认),适用于web应用。
IFRAME("iframe"), //适用:人人
POPUP("popup"), //适用:人人,百度 ————弹框形式的授权页面,适用于桌面软件应用和web应用。
TOUCH("touch"), //适用:人人 ————人人智能移动终端,最小尺寸(320px*480px)
MOBILE("mobile"), //适用:人人,百度,sina,qq ————人人不支持js的移动终端,最小尺寸(480*800px),百度智能机。
TV("tv"), //适用:百度 ————电视等超大显示屏使用的授权页面。
PAD("pad"), //适用:百度 ————IPad/Android等智能平板电脑使用的授权页面。
CLIENT("client"), //适用:sina ————客户端版本授权页面,适用于PC桌面应用。
APPONWEIBO("apponweibo"),//适用:sina ————默认的站内应用授权页,授权后不返回access_token,只刷新站内应用父框架。
WAP("wap"); //适用:sina ————wap版授权页面,适用于非智能手机。
Display(String type) {
this.type = type;
}
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| chenxingxing6/pms | src/main/java/com/peace/pms/util/Display.java | 479 | //适用:百度 ————电视等超大显示屏使用的授权页面。
| line_comment | zh-cn | package com.peace.pms.util;
/**
* 授权展示方式
* @Author: cxx
* @Date: 2018/3/1 15:45
*/
public enum Display {
DEFAULT("default"), //适用:sina ————默认的授权页面,适用于web浏览器。
PAGE("page"), //适用:人人,百度 ————全屏形式的授权页面(默认),适用于web应用。
IFRAME("iframe"), //适用:人人
POPUP("popup"), //适用:人人,百度 ————弹框形式的授权页面,适用于桌面软件应用和web应用。
TOUCH("touch"), //适用:人人 ————人人智能移动终端,最小尺寸(320px*480px)
MOBILE("mobile"), //适用:人人,百度,sina,qq ————人人不支持js的移动终端,最小尺寸(480*800px),百度智能机。
TV("tv"), //适用 <SUF>
PAD("pad"), //适用:百度 ————IPad/Android等智能平板电脑使用的授权页面。
CLIENT("client"), //适用:sina ————客户端版本授权页面,适用于PC桌面应用。
APPONWEIBO("apponweibo"),//适用:sina ————默认的站内应用授权页,授权后不返回access_token,只刷新站内应用父框架。
WAP("wap"); //适用:sina ————wap版授权页面,适用于非智能手机。
Display(String type) {
this.type = type;
}
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| false | 413 | 17 | 478 | 22 | 417 | 17 | 478 | 22 | 702 | 37 | false | false | false | false | false | true |
31764_7 | package com.demo.txtest;
/**
* User: lanxinghua
* Date: 2019/10/19 15:03
* Desc:
*/
public interface ITxService {
/**
* 总结:1和2,外围无事务,哪个方法报错,哪个回滚
* 1、外围无事务有异常,里面有两个添加方法,可以添加成功
*/
void notxException_required_required();
/**
* 2、外围无事务无异常,里面有两个添加方法,其中一个事务方法内部异常,导致回滚
*/
void notx_required_requiredException();
/**
* 3、外围有事务且有异常,里面有两个添加方法,不论外围有异常,还是其他方法有异常,全都回滚
*/
void txException_required_required();
/**
* 4、外围有事务且有异常,不回滚
*/
void txException_requiredNew_requiredNew();
/**
* 5、外围有事务且有异常,里面有两个添加方法,requiredNewException的进行回滚
*/
void txException_requiredNew_requiredNewException();
/**
* 6、外围有事务且有异常,里面有两个添加方法,外部插入成功,内部回滚
*/
void txException_required_requiredExceptionTry();
/**
* 7.在一个类里面:没事务方法A调有事务方法B,B的事务会被忽略调
*/
void notx_notxMethod_txMethodException();
void notx_notxMethod_txMethodException1();
}
| chenxingxing6/sourcecode | study-transcation/src/main/java/com/demo/txtest/ITxService.java | 379 | /**
* 7.在一个类里面:没事务方法A调有事务方法B,B的事务会被忽略调
*/ | block_comment | zh-cn | package com.demo.txtest;
/**
* User: lanxinghua
* Date: 2019/10/19 15:03
* Desc:
*/
public interface ITxService {
/**
* 总结:1和2,外围无事务,哪个方法报错,哪个回滚
* 1、外围无事务有异常,里面有两个添加方法,可以添加成功
*/
void notxException_required_required();
/**
* 2、外围无事务无异常,里面有两个添加方法,其中一个事务方法内部异常,导致回滚
*/
void notx_required_requiredException();
/**
* 3、外围有事务且有异常,里面有两个添加方法,不论外围有异常,还是其他方法有异常,全都回滚
*/
void txException_required_required();
/**
* 4、外围有事务且有异常,不回滚
*/
void txException_requiredNew_requiredNew();
/**
* 5、外围有事务且有异常,里面有两个添加方法,requiredNewException的进行回滚
*/
void txException_requiredNew_requiredNewException();
/**
* 6、外围有事务且有异常,里面有两个添加方法,外部插入成功,内部回滚
*/
void txException_required_requiredExceptionTry();
/**
* 7.在 <SUF>*/
void notx_notxMethod_txMethodException();
void notx_notxMethod_txMethodException1();
}
| false | 341 | 29 | 379 | 31 | 394 | 30 | 379 | 31 | 552 | 44 | false | false | false | false | false | true |
58845_1 | package com.moment.login.interceptor;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
//这个拦截器只拦截动作发生之前
public class LoginHandlerInterceptor implements HandlerInterceptor{
//进行日志管理记录
private Logger logger = LoggerFactory.getLogger(this.getClass());
//这里是进行了spring的属性注入
private List<String> allowUris;
public void setAllowUris(List<String> allowUris) {
this.allowUris = allowUris;
}
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
//这里涉及到两个登陆角色,管理员和用户,因此这里的拦截器也要相应去识别管理员和用户的登陆
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
logger.debug("LoginStateHandlerInterceptor preHandle");
HttpServletRequest httpReq=(HttpServletRequest)request;
HttpServletResponse httpRes=(HttpServletResponse)response;
if(httpReq.getSession().getAttribute("user")!=null){//已经登录
logger.debug("用户已经登录");
return true;
}else if(httpReq.getSession().getAttribute("admin")!=null){
logger.debug("管理员已经登录");
return true;
}else{//没有登录
String uri=httpReq.getRequestURI();
if(isAllowURI(uri)){//本身登录模块不需要 拦截
return true;
}else{
//返回登录页
httpRes.sendRedirect(httpReq.getContextPath()+"/user/login.action");
return false;
}
}
}
/**
* 判断是否不需要拦截的URI
* @param uri
* @return
*/
private boolean isAllowURI(String uri){
if(allowUris!=null){
for(String str : allowUris){
if(uri.indexOf(str)>-1){
return true;
}
}
}
return false;
}
}
| chenyang1999/MyComputerCollegeCourses | java/moment/src/main/java/com/moment/login/interceptor/LoginHandlerInterceptor.java | 621 | //进行日志管理记录 | line_comment | zh-cn | package com.moment.login.interceptor;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
//这个拦截器只拦截动作发生之前
public class LoginHandlerInterceptor implements HandlerInterceptor{
//进行 <SUF>
private Logger logger = LoggerFactory.getLogger(this.getClass());
//这里是进行了spring的属性注入
private List<String> allowUris;
public void setAllowUris(List<String> allowUris) {
this.allowUris = allowUris;
}
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
//这里涉及到两个登陆角色,管理员和用户,因此这里的拦截器也要相应去识别管理员和用户的登陆
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
logger.debug("LoginStateHandlerInterceptor preHandle");
HttpServletRequest httpReq=(HttpServletRequest)request;
HttpServletResponse httpRes=(HttpServletResponse)response;
if(httpReq.getSession().getAttribute("user")!=null){//已经登录
logger.debug("用户已经登录");
return true;
}else if(httpReq.getSession().getAttribute("admin")!=null){
logger.debug("管理员已经登录");
return true;
}else{//没有登录
String uri=httpReq.getRequestURI();
if(isAllowURI(uri)){//本身登录模块不需要 拦截
return true;
}else{
//返回登录页
httpRes.sendRedirect(httpReq.getContextPath()+"/user/login.action");
return false;
}
}
}
/**
* 判断是否不需要拦截的URI
* @param uri
* @return
*/
private boolean isAllowURI(String uri){
if(allowUris!=null){
for(String str : allowUris){
if(uri.indexOf(str)>-1){
return true;
}
}
}
return false;
}
}
| false | 497 | 6 | 621 | 5 | 612 | 5 | 621 | 5 | 825 | 9 | false | false | false | false | false | true |
66494_2 | package com.codechen.scaffold.core.util;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author:Java陈序员
* @date 2023-07-10 10:25
* @description ip 工具类
*/
public class IpUtil {
private static final String UNKNOWN = "unknown";
private static final String HEADER_FORWARDED = "x-forwarded-for";
private static final String HEADER_PROXY = "Proxy-Client-IP";
private static final String HEADER_WL_PROXY = "WL-Proxy-Client-IP";
private static final String HEADER_HTTP = "HTTP_CLIENT_IP";
private static final String HEADER_HTTP_FORWARDED = "HTTP_X_FORWARDED_FOR";
private static final String LOCAL_IP = "127.0.0.1";
private static final String LOCAL_HOST = "localhost";
private static Searcher searcher;
/**
* 获取 IP 地址
*
* Host:获取客户端(client)的真实域名和端口号
* X-Real-IP:获取客户端真实 IP 地址
* X-Forwarded-For:也是获取客户端真实 IP 地址,如果有多层代理时会获取客户端真实 IP 及每层代理服务器的 IP 地址
* X-Forwarded-Proto:获取客户端的真实协议(如 http、https)
* getRemoteAddr()用于获取没有代理服务器情况下用户的 IP 地址2
* 1.当用户的请求经过一个代理服务器后到达最终服务器,此时在最终服务器端通过getRemoteAddr()只能得到代理服务器的 IP 地址,通过在代理服务器中配置proxy_set_header X-Real-IP $remote_addr,最终的服务器可以通过X-Real-IP获取用户的真实 IP 地址。
* 2.当用户的请求经过多个代理服务器后到达最终服务器时,配置proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for后可通过X-Forwarded-For获取用户真实 IP 地址(请求通过第一台 nginx时:X-Forwarded-For = X-Real-IP = 用户真实 IP 地址;请求通过第二台 nginx 时:X-Forwarded-For = 用户真实 IP 地址, X-Real-IP = 上一台 nginx 的 IP 地址 )。
* 3.获取客户端的IP地址不仅可以通过proxy_set_header X-real-ip $remote_addr;获取,也可以通过proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;获取。
*
* @param request
* @return
*/
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader(HEADER_FORWARDED);
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader(HEADER_PROXY);
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader(HEADER_WL_PROXY);
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader(HEADER_HTTP);
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader(HEADER_HTTP_FORWARDED);
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 本机访问
if (LOCAL_IP.equalsIgnoreCase(ip) || LOCAL_HOST.equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
// 根据网卡取本机配置的 IP
try {
InetAddress localHost = InetAddress.getLocalHost();
ip = localHost.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
// 对于通过多个代理的情况,第一个 IP 为客户端真实 IP,多个 IP 按照','分割
if (ip != null && ip.length() > 15) {
if (ip.indexOf(",") > 15) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}
/**
* 获取 mac 地址
*
* @return
* @throws Exception
*/
public static String getMacAddress() throws Exception {
// 获取 mac 地址
byte[] hardwareAddress = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
// 将 mac 地址转成字符串
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < hardwareAddress.length; i++) {
if (i != 0) {
stringBuilder.append("-");
}
// hardwareAddress[i] & 0xFF 是为了把 byte 转化为正整数
String s = Integer.toHexString(hardwareAddress[i] & 0xFF);
stringBuilder.append(s.length() == 1 ? 0 + s : s);
}
return stringBuilder.toString().trim().toUpperCase();
}
/**
* 判断是否为合法 IP
* @return
*/
public static boolean checkIp(String ipAddress) {
String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
Pattern pattern = Pattern.compile(ip);
Matcher matcher = pattern.matcher(ipAddress);
return matcher.matches();
}
/**
* 在服务启动时,将 ip2region 加载到内存中
*/
@PostConstruct
private static void initIp2Region() {
try {
InputStream inputStream = new ClassPathResource("/ipdb/ip2region.xdb").getInputStream();
byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
searcher = Searcher.newWithBuffer(bytes);
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* 获取 ip 所属地址
*
* @param ip ip
* @return
*/
public static String getIpRegion(String ip) {
boolean isIp = checkIp(ip);
if (isIp) {
initIp2Region();
try {
String searchIpInfo = searcher.search(ip);
// searchIpInfo 的数据格式: 国家|区域|省份|城市|ISP
// 192.168.31.160 0|0|0|内网IP|内网IP
// 47.52.236.180 中国|0|香港|0|阿里云
// 220.248.12.158 中国|0|上海|上海市|联通
// 164.114.53.60 美国|0|华盛顿|0|0
String[] splitIpInfo = searchIpInfo.split("\\|");
if (splitIpInfo.length > 0) {
if ("中国".equals(splitIpInfo[0])) {
// 国内属地返回省份
return splitIpInfo[2];
} else if ("0".equals(splitIpInfo[0])) {
if ("内网IP".equals(splitIpInfo[4])) {
// 内网 IP
return splitIpInfo[4];
} else {
return "";
}
} else {
// 国外属地返回国家
return splitIpInfo[0];
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
} else {
throw new IllegalArgumentException("非法的IP地址");
}
}
}
| chenyl8848/springboot-dev-scaffold | src/main/java/com/codechen/scaffold/core/util/IpUtil.java | 1,921 | // 本机访问 | line_comment | zh-cn | package com.codechen.scaffold.core.util;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.FileCopyUtils;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author:Java陈序员
* @date 2023-07-10 10:25
* @description ip 工具类
*/
public class IpUtil {
private static final String UNKNOWN = "unknown";
private static final String HEADER_FORWARDED = "x-forwarded-for";
private static final String HEADER_PROXY = "Proxy-Client-IP";
private static final String HEADER_WL_PROXY = "WL-Proxy-Client-IP";
private static final String HEADER_HTTP = "HTTP_CLIENT_IP";
private static final String HEADER_HTTP_FORWARDED = "HTTP_X_FORWARDED_FOR";
private static final String LOCAL_IP = "127.0.0.1";
private static final String LOCAL_HOST = "localhost";
private static Searcher searcher;
/**
* 获取 IP 地址
*
* Host:获取客户端(client)的真实域名和端口号
* X-Real-IP:获取客户端真实 IP 地址
* X-Forwarded-For:也是获取客户端真实 IP 地址,如果有多层代理时会获取客户端真实 IP 及每层代理服务器的 IP 地址
* X-Forwarded-Proto:获取客户端的真实协议(如 http、https)
* getRemoteAddr()用于获取没有代理服务器情况下用户的 IP 地址2
* 1.当用户的请求经过一个代理服务器后到达最终服务器,此时在最终服务器端通过getRemoteAddr()只能得到代理服务器的 IP 地址,通过在代理服务器中配置proxy_set_header X-Real-IP $remote_addr,最终的服务器可以通过X-Real-IP获取用户的真实 IP 地址。
* 2.当用户的请求经过多个代理服务器后到达最终服务器时,配置proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for后可通过X-Forwarded-For获取用户真实 IP 地址(请求通过第一台 nginx时:X-Forwarded-For = X-Real-IP = 用户真实 IP 地址;请求通过第二台 nginx 时:X-Forwarded-For = 用户真实 IP 地址, X-Real-IP = 上一台 nginx 的 IP 地址 )。
* 3.获取客户端的IP地址不仅可以通过proxy_set_header X-real-ip $remote_addr;获取,也可以通过proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;获取。
*
* @param request
* @return
*/
public String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader(HEADER_FORWARDED);
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader(HEADER_PROXY);
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader(HEADER_WL_PROXY);
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader(HEADER_HTTP);
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getHeader(HEADER_HTTP_FORWARDED);
}
if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
// 本机 <SUF>
if (LOCAL_IP.equalsIgnoreCase(ip) || LOCAL_HOST.equalsIgnoreCase(ip) || "0:0:0:0:0:0:0:1".equalsIgnoreCase(ip)) {
// 根据网卡取本机配置的 IP
try {
InetAddress localHost = InetAddress.getLocalHost();
ip = localHost.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
// 对于通过多个代理的情况,第一个 IP 为客户端真实 IP,多个 IP 按照','分割
if (ip != null && ip.length() > 15) {
if (ip.indexOf(",") > 15) {
ip = ip.substring(0, ip.indexOf(","));
}
}
return ip;
}
/**
* 获取 mac 地址
*
* @return
* @throws Exception
*/
public static String getMacAddress() throws Exception {
// 获取 mac 地址
byte[] hardwareAddress = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()).getHardwareAddress();
// 将 mac 地址转成字符串
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < hardwareAddress.length; i++) {
if (i != 0) {
stringBuilder.append("-");
}
// hardwareAddress[i] & 0xFF 是为了把 byte 转化为正整数
String s = Integer.toHexString(hardwareAddress[i] & 0xFF);
stringBuilder.append(s.length() == 1 ? 0 + s : s);
}
return stringBuilder.toString().trim().toUpperCase();
}
/**
* 判断是否为合法 IP
* @return
*/
public static boolean checkIp(String ipAddress) {
String ip = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
Pattern pattern = Pattern.compile(ip);
Matcher matcher = pattern.matcher(ipAddress);
return matcher.matches();
}
/**
* 在服务启动时,将 ip2region 加载到内存中
*/
@PostConstruct
private static void initIp2Region() {
try {
InputStream inputStream = new ClassPathResource("/ipdb/ip2region.xdb").getInputStream();
byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
searcher = Searcher.newWithBuffer(bytes);
} catch (Exception exception) {
exception.printStackTrace();
}
}
/**
* 获取 ip 所属地址
*
* @param ip ip
* @return
*/
public static String getIpRegion(String ip) {
boolean isIp = checkIp(ip);
if (isIp) {
initIp2Region();
try {
String searchIpInfo = searcher.search(ip);
// searchIpInfo 的数据格式: 国家|区域|省份|城市|ISP
// 192.168.31.160 0|0|0|内网IP|内网IP
// 47.52.236.180 中国|0|香港|0|阿里云
// 220.248.12.158 中国|0|上海|上海市|联通
// 164.114.53.60 美国|0|华盛顿|0|0
String[] splitIpInfo = searchIpInfo.split("\\|");
if (splitIpInfo.length > 0) {
if ("中国".equals(splitIpInfo[0])) {
// 国内属地返回省份
return splitIpInfo[2];
} else if ("0".equals(splitIpInfo[0])) {
if ("内网IP".equals(splitIpInfo[4])) {
// 内网 IP
return splitIpInfo[4];
} else {
return "";
}
} else {
// 国外属地返回国家
return splitIpInfo[0];
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
} else {
throw new IllegalArgumentException("非法的IP地址");
}
}
}
| false | 1,772 | 5 | 1,921 | 4 | 1,991 | 4 | 1,921 | 4 | 2,522 | 8 | false | false | false | false | false | true |
27733_7 | package T_3_国王挖金矿问题;
public class Solution {
static int GOLDS = 5; //金矿数量
static int PEOPLES = 100; //总人数
public static void main(String[] args) {
int[] peopleNeed = new int[]{77, 22, 29, 50, 99};//每座金矿需要的人数
int[] goldGet = new int[]{92, 22, 87, 36, 90};//每座金矿能够得到的金子数量
//记录当剩下 people个人和 剩下前golds个金矿时,能够得到的最大的金子,当为-1值表示未知
int[][] maxGold = new int[PEOPLES +1][GOLDS ];
initData(maxGold);
System.out.println(getMaxGold(PEOPLES, GOLDS-1, peopleNeed, goldGet, maxGold));
}
public static int getMaxGold(int people, int goldNum, int[] peopleNeed, int[] goldGet, int[][] maxGold) {
int getGold = 0; //记录当有people个人,前goldNum个金矿时,得到的金子
if (maxGold[people][goldNum] != -1) { //如果之前有记录,就直接取出来
getGold = maxGold[people][goldNum];
} else if (goldNum == 1) { //最后一个金矿
if (people >= peopleNeed[goldNum]) {
getGold = goldGet[goldNum];
} else {
getGold = 0;
}
} else if (people >= peopleNeed[goldNum]) {
getGold = Math.max(
getMaxGold(people - peopleNeed[goldNum],
goldNum - 1, peopleNeed, goldGet, maxGold)
,
getMaxGold(people, goldNum - 1, peopleNeed, goldGet, maxGold));
} else {
getGold = getMaxGold(people, goldNum - 1, peopleNeed, goldGet, maxGold);
maxGold[people][goldNum] = getGold;
}
return getGold;
}
public static void initData(int[][] maxGold) {
for (int i = 0; i < maxGold.length; i++) {
for (int j = 0; j < maxGold[0].length; j++) {
maxGold[i][j] = -1;
}
}
}
}
| chenyongda2018/DataStructure-Algorithm | 算法分析与设计/T_3_国王挖金矿问题/Solution.java | 582 | //最后一个金矿 | line_comment | zh-cn | package T_3_国王挖金矿问题;
public class Solution {
static int GOLDS = 5; //金矿数量
static int PEOPLES = 100; //总人数
public static void main(String[] args) {
int[] peopleNeed = new int[]{77, 22, 29, 50, 99};//每座金矿需要的人数
int[] goldGet = new int[]{92, 22, 87, 36, 90};//每座金矿能够得到的金子数量
//记录当剩下 people个人和 剩下前golds个金矿时,能够得到的最大的金子,当为-1值表示未知
int[][] maxGold = new int[PEOPLES +1][GOLDS ];
initData(maxGold);
System.out.println(getMaxGold(PEOPLES, GOLDS-1, peopleNeed, goldGet, maxGold));
}
public static int getMaxGold(int people, int goldNum, int[] peopleNeed, int[] goldGet, int[][] maxGold) {
int getGold = 0; //记录当有people个人,前goldNum个金矿时,得到的金子
if (maxGold[people][goldNum] != -1) { //如果之前有记录,就直接取出来
getGold = maxGold[people][goldNum];
} else if (goldNum == 1) { //最后 <SUF>
if (people >= peopleNeed[goldNum]) {
getGold = goldGet[goldNum];
} else {
getGold = 0;
}
} else if (people >= peopleNeed[goldNum]) {
getGold = Math.max(
getMaxGold(people - peopleNeed[goldNum],
goldNum - 1, peopleNeed, goldGet, maxGold)
,
getMaxGold(people, goldNum - 1, peopleNeed, goldGet, maxGold));
} else {
getGold = getMaxGold(people, goldNum - 1, peopleNeed, goldGet, maxGold);
maxGold[people][goldNum] = getGold;
}
return getGold;
}
public static void initData(int[][] maxGold) {
for (int i = 0; i < maxGold.length; i++) {
for (int j = 0; j < maxGold[0].length; j++) {
maxGold[i][j] = -1;
}
}
}
}
| false | 559 | 4 | 582 | 6 | 593 | 4 | 582 | 6 | 726 | 9 | false | false | false | false | false | true |
58666_5 | package com.zhbit.entity;
import java.util.Vector;
import com.zhbit.excetion.DataBaseException;
import com.zhbit.excetion.PasswordNotMatchException;
import com.zhbit.excetion.QueryResultIsNullException;
import com.zhbit.excetion.UpdateDataException;
import com.zhbit.excetion.UpdateSuccessException;
import com.zhbit.form.UpdatePassWordForm;
import com.zhbit.form.UpdatePersonalInfoForm;
/**
*
* @author chenyueling
*
*/
public interface StudentService {
//********************查询快递信息******************//
//*******************查询保修信息********************//
//********************查询阿姨信息*********************//
//**********************查询宿舍信息*******************//
//*********************个人信息***********************//
public void initPersonalInfo(Student student) throws DataBaseException,
QueryResultIsNullException;
/**
* 个人密码修改
* @param updatepassWordForm
* @throws PasswordNotMatchException
* @throws DataBaseException
* @throws UpdateSuccessException
*/
public void PasswordUpdate(UpdatePassWordForm updatepassWordForm) throws PasswordNotMatchException, DataBaseException, UpdateSuccessException;
public void UpdatePersonalInfo(UpdatePersonalInfoForm updatePersonalInfoForm) throws UpdateDataException, DataBaseException;
/**
* 查询学生个人详细的快递信息
* @return
* @throws DataBaseException
* @throws QueryResultIsNullException
*/
public Vector<Object> getPersonalExpressInfo(String StuId) throws DataBaseException,QueryResultIsNullException;
/**
*快递信息消息弹出宽显示的快递信息
* @return
* @throws DataBaseException
* @throws QueryResultIsNullException
*/
public Vector<Object> showPersonalExpressInfo(String StuId) throws DataBaseException,QueryResultIsNullException;
/**
* 查询学生个人夜归记录
* @param StuId
* @return
* @throws DataBaseException
* @throws QueryResultIsNullException
*/
public Vector<Object> getPersonalCurfewInfo(String StuId)throws DataBaseException,QueryResultIsNullException;
/**
* 查询自己所在宿舍报修信息
* @return
* @throws DataBaseException
* @throws QueryResultIsNullException
*/
public Vector<Object> getMaintainceRecord(String RoomId)throws DataBaseException,QueryResultIsNullException;
public Vector<Object> getItem() throws DataBaseException;
public boolean insertItemMa(String id, String dormId2, String roomId2, String bedNum2, String itemId, String rmark) throws DataBaseException;
public boolean updateExpressTransceiver(int record, String data) throws DataBaseException;
}
| chenyueling/Dormitory_Management_System | src/com/zhbit/entity/StudentService.java | 658 | //*********************个人信息***********************// | line_comment | zh-cn | package com.zhbit.entity;
import java.util.Vector;
import com.zhbit.excetion.DataBaseException;
import com.zhbit.excetion.PasswordNotMatchException;
import com.zhbit.excetion.QueryResultIsNullException;
import com.zhbit.excetion.UpdateDataException;
import com.zhbit.excetion.UpdateSuccessException;
import com.zhbit.form.UpdatePassWordForm;
import com.zhbit.form.UpdatePersonalInfoForm;
/**
*
* @author chenyueling
*
*/
public interface StudentService {
//********************查询快递信息******************//
//*******************查询保修信息********************//
//********************查询阿姨信息*********************//
//**********************查询宿舍信息*******************//
//*********************个人 <SUF>
public void initPersonalInfo(Student student) throws DataBaseException,
QueryResultIsNullException;
/**
* 个人密码修改
* @param updatepassWordForm
* @throws PasswordNotMatchException
* @throws DataBaseException
* @throws UpdateSuccessException
*/
public void PasswordUpdate(UpdatePassWordForm updatepassWordForm) throws PasswordNotMatchException, DataBaseException, UpdateSuccessException;
public void UpdatePersonalInfo(UpdatePersonalInfoForm updatePersonalInfoForm) throws UpdateDataException, DataBaseException;
/**
* 查询学生个人详细的快递信息
* @return
* @throws DataBaseException
* @throws QueryResultIsNullException
*/
public Vector<Object> getPersonalExpressInfo(String StuId) throws DataBaseException,QueryResultIsNullException;
/**
*快递信息消息弹出宽显示的快递信息
* @return
* @throws DataBaseException
* @throws QueryResultIsNullException
*/
public Vector<Object> showPersonalExpressInfo(String StuId) throws DataBaseException,QueryResultIsNullException;
/**
* 查询学生个人夜归记录
* @param StuId
* @return
* @throws DataBaseException
* @throws QueryResultIsNullException
*/
public Vector<Object> getPersonalCurfewInfo(String StuId)throws DataBaseException,QueryResultIsNullException;
/**
* 查询自己所在宿舍报修信息
* @return
* @throws DataBaseException
* @throws QueryResultIsNullException
*/
public Vector<Object> getMaintainceRecord(String RoomId)throws DataBaseException,QueryResultIsNullException;
public Vector<Object> getItem() throws DataBaseException;
public boolean insertItemMa(String id, String dormId2, String roomId2, String bedNum2, String itemId, String rmark) throws DataBaseException;
public boolean updateExpressTransceiver(int record, String data) throws DataBaseException;
}
| false | 565 | 7 | 658 | 8 | 670 | 8 | 658 | 8 | 847 | 12 | false | false | false | false | false | true |
24961_5 | import javax.swing.table.TableRowSorter;
import java.util.ArrayList;
import java.util.List;
public class blackWhiteChess {
private int cols; //行
private int rows; //列
private int[][] grid;
private int checkPoint;
public blackWhiteChess() {
}
public blackWhiteChess(int[][] grid) {
cols = grid.length;
rows = grid[0].length;
this.grid = grid;
checkPoint = 0; // 1则黑棋下,旁边要有2;0则白棋下,旁边要有1
}
public int checkPoint() {
checkPoint = checkPoint + 1;
return (checkPoint % 2);
}
public List check() {
List res = new ArrayList(2);
//TODO
/*现在有了三个方法:
1.判断所选的position是否为0
2.判断 mypostion 是否在 other 附近
3.判断 mypostion 是否在 other 横竖撇捺位置
*/
for (int col = 0; col < cols; col++) {
for (int row = 0; row < rows; row++) {
int[] position = new int[]{col,row};
if (validPlace(position) && ifNearOtherChess(position) && whetherOtherSide(position)) {
res.add(new int[]{col,row});
}
}
}
return res;
}
private boolean validPlace(int[] position) {
int col = position[0];
int row = position[1];
return grid[col][row] == 0;
}
// 判断 mypostion 四周是否又有与其不同的值
public boolean ifNearOtherChess(int[] position) {
//other 是一个x,y
int pcol = position[0];
int prow = position[1];
for (int col = -1; col <= 1; col +=1) {
for (int row = -1; row <= 1; row +=1) {
if (col == 0 && row == 0) {
continue;
}
int newCol = pcol + col;
int newRow = prow + row;
if (newCol >= 0 && newCol <cols && newRow>=0 && newRow <rows) {
int surroundNum = grid[newCol][newRow];
if (surroundNum != 0 && surroundNum == (checkPoint + 1)) {
return true;
}
}
}
}
return false;
}
// 判断 棋盘中 横竖撇捺方向 是否有 与 poistion 相同的值
public boolean whetherOtherSide(int[] position) {
int pcol = position[0];
int prow = position[1];
if (grid[pcol][prow] != 0) {
return false;
}
for (int col = 0; col < cols; col++) {
for (int row = 0; row < rows; row++) {
if (col == pcol || row == prow || (col - pcol) == (row - prow) || (col - pcol) == -(row - prow)) {
int otherNum = grid[col][row];
// checkpoint 为 0 时,白棋下,要 = 2,checkpoint 为1时,要=1,黑棋下
if (checkPoint == 0) {
if (otherNum != 0 && otherNum == (checkPoint + 2)) {
return true;
}
} else {
if (otherNum != 0 && otherNum == checkPoint) {
return true;
}
}
}
}
}
return false;
}
}
| chenyuxiang0425/cs61b_sp19 | blackWhiteChess/src/blackWhiteChess.java | 862 | // 判断 棋盘中 横竖撇捺方向 是否有 与 poistion 相同的值 | line_comment | zh-cn | import javax.swing.table.TableRowSorter;
import java.util.ArrayList;
import java.util.List;
public class blackWhiteChess {
private int cols; //行
private int rows; //列
private int[][] grid;
private int checkPoint;
public blackWhiteChess() {
}
public blackWhiteChess(int[][] grid) {
cols = grid.length;
rows = grid[0].length;
this.grid = grid;
checkPoint = 0; // 1则黑棋下,旁边要有2;0则白棋下,旁边要有1
}
public int checkPoint() {
checkPoint = checkPoint + 1;
return (checkPoint % 2);
}
public List check() {
List res = new ArrayList(2);
//TODO
/*现在有了三个方法:
1.判断所选的position是否为0
2.判断 mypostion 是否在 other 附近
3.判断 mypostion 是否在 other 横竖撇捺位置
*/
for (int col = 0; col < cols; col++) {
for (int row = 0; row < rows; row++) {
int[] position = new int[]{col,row};
if (validPlace(position) && ifNearOtherChess(position) && whetherOtherSide(position)) {
res.add(new int[]{col,row});
}
}
}
return res;
}
private boolean validPlace(int[] position) {
int col = position[0];
int row = position[1];
return grid[col][row] == 0;
}
// 判断 mypostion 四周是否又有与其不同的值
public boolean ifNearOtherChess(int[] position) {
//other 是一个x,y
int pcol = position[0];
int prow = position[1];
for (int col = -1; col <= 1; col +=1) {
for (int row = -1; row <= 1; row +=1) {
if (col == 0 && row == 0) {
continue;
}
int newCol = pcol + col;
int newRow = prow + row;
if (newCol >= 0 && newCol <cols && newRow>=0 && newRow <rows) {
int surroundNum = grid[newCol][newRow];
if (surroundNum != 0 && surroundNum == (checkPoint + 1)) {
return true;
}
}
}
}
return false;
}
// 判断 <SUF>
public boolean whetherOtherSide(int[] position) {
int pcol = position[0];
int prow = position[1];
if (grid[pcol][prow] != 0) {
return false;
}
for (int col = 0; col < cols; col++) {
for (int row = 0; row < rows; row++) {
if (col == pcol || row == prow || (col - pcol) == (row - prow) || (col - pcol) == -(row - prow)) {
int otherNum = grid[col][row];
// checkpoint 为 0 时,白棋下,要 = 2,checkpoint 为1时,要=1,黑棋下
if (checkPoint == 0) {
if (otherNum != 0 && otherNum == (checkPoint + 2)) {
return true;
}
} else {
if (otherNum != 0 && otherNum == checkPoint) {
return true;
}
}
}
}
}
return false;
}
}
| false | 823 | 28 | 862 | 26 | 909 | 19 | 862 | 26 | 1,045 | 41 | false | false | false | false | false | true |
59033_0 | package learn.ch12_interface;
/**
* 父类
*/
public class PriHogwarts {
public void study(){
System.out.println("理论+实战+高薪就业");
}
}
| chenzhiyou/HogwartsJavaTest | src/main/java/learn/ch12_interface/PriHogwarts.java | 57 | /**
* 父类
*/ | block_comment | zh-cn | package learn.ch12_interface;
/**
* 父类
<SUF>*/
public class PriHogwarts {
public void study(){
System.out.println("理论+实战+高薪就业");
}
}
| false | 43 | 8 | 57 | 8 | 52 | 7 | 57 | 8 | 67 | 10 | false | false | false | false | false | true |
15358_0 | package git;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n请选择操作:");
System.out.println("1. 加密");
System.out.println("2. 解密");
System.out.println("3. 退出");
String option = scanner.nextLine();
switch (option) {
case "1":
jiami(scanner);
break;
case "2":
jiemi(scanner);
break;
case "3":
System.out.println("退出程序。");
return;
default:
System.out.println("无效的选项,请重新输入。");
}
}
}
private static void jiami(Scanner scanner) {
System.out.println("请输入要加密的密码:");
String password = scanner.nextLine();
System.out.println("请选择加密方式");
System.out.println("1. 偏移加密");
System.out.println("2. 调换加密");
System.out.println("3. 反转加密");
String option = scanner.nextLine();
switch (option) {
case "1":
jiamiPassword(password);
break;
case "2":
jiamiPassword2(password);
break;
case "3":
jiamiPassword3(password);
break;
default:
System.out.println("无效的选项,请重新输入。");
}
System.out.println("加密后的密码: " + jiamiPassword(password));
}
private static String jiamiPassword(String password) {
StringBuilder jiamiPassword = new StringBuilder();
for (int i = 0; i <password.length(); i++) {
char c = password.charAt(i);
int ascii = (int) c;
int pianyi = 3;
int newAscii = ascii + i + pianyi;
char newChar = (char) newAscii;
jiamiPassword.append(newChar);
}
return jiamiPassword.toString();
}
private static String jiamiPassword3(String password) {
StringBuilder jiamiPassword = new StringBuilder();
for (int i = password.length(); i >= 0; i--) {
char c = password.charAt(i);
char newChar = c;
jiamiPassword.append(newChar);
}
return jiamiPassword.toString();
}
private static String jiamiPassword2(String password) {
String jiamiPassword = new String();
String c = String.valueOf(password.charAt(0));
//valufOf()方法是将其他类型的数据转换成String类型,在这里的作用是将字符转换成字符串
String c1 = String.valueOf(password.charAt(password.length()));
jiamiPassword=c1+password.substring(1,password.length()-1)+c;
return jiamiPassword.toString();
}
private static void jiemi(Scanner scanner) {
System.out.println("请输入要解密的密码:");
String jiamiPassword = scanner.nextLine();
String jiemiPassword = jiemiPassword(jiamiPassword);
System.out.println("解密后的密码: " + jiemiPassword);
}
private static String jiemiPassword(String jiamiPassword) {
StringBuilder jiemiPassword = new StringBuilder();
for (int i = 0; i < jiamiPassword.length(); i++) {
char c = jiamiPassword.charAt(i);
int ascii = ((int) c)-3-i;
char newChar = (char) ascii;
jiemiPassword.append(newChar);
}
return jiemiPassword.toString();
}
} | chenztnull/GitTest | demo.java | 886 | //valufOf()方法是将其他类型的数据转换成String类型,在这里的作用是将字符转换成字符串 | line_comment | zh-cn | package git;
import java.util.Scanner;
public class demo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("\n请选择操作:");
System.out.println("1. 加密");
System.out.println("2. 解密");
System.out.println("3. 退出");
String option = scanner.nextLine();
switch (option) {
case "1":
jiami(scanner);
break;
case "2":
jiemi(scanner);
break;
case "3":
System.out.println("退出程序。");
return;
default:
System.out.println("无效的选项,请重新输入。");
}
}
}
private static void jiami(Scanner scanner) {
System.out.println("请输入要加密的密码:");
String password = scanner.nextLine();
System.out.println("请选择加密方式");
System.out.println("1. 偏移加密");
System.out.println("2. 调换加密");
System.out.println("3. 反转加密");
String option = scanner.nextLine();
switch (option) {
case "1":
jiamiPassword(password);
break;
case "2":
jiamiPassword2(password);
break;
case "3":
jiamiPassword3(password);
break;
default:
System.out.println("无效的选项,请重新输入。");
}
System.out.println("加密后的密码: " + jiamiPassword(password));
}
private static String jiamiPassword(String password) {
StringBuilder jiamiPassword = new StringBuilder();
for (int i = 0; i <password.length(); i++) {
char c = password.charAt(i);
int ascii = (int) c;
int pianyi = 3;
int newAscii = ascii + i + pianyi;
char newChar = (char) newAscii;
jiamiPassword.append(newChar);
}
return jiamiPassword.toString();
}
private static String jiamiPassword3(String password) {
StringBuilder jiamiPassword = new StringBuilder();
for (int i = password.length(); i >= 0; i--) {
char c = password.charAt(i);
char newChar = c;
jiamiPassword.append(newChar);
}
return jiamiPassword.toString();
}
private static String jiamiPassword2(String password) {
String jiamiPassword = new String();
String c = String.valueOf(password.charAt(0));
//va <SUF>
String c1 = String.valueOf(password.charAt(password.length()));
jiamiPassword=c1+password.substring(1,password.length()-1)+c;
return jiamiPassword.toString();
}
private static void jiemi(Scanner scanner) {
System.out.println("请输入要解密的密码:");
String jiamiPassword = scanner.nextLine();
String jiemiPassword = jiemiPassword(jiamiPassword);
System.out.println("解密后的密码: " + jiemiPassword);
}
private static String jiemiPassword(String jiamiPassword) {
StringBuilder jiemiPassword = new StringBuilder();
for (int i = 0; i < jiamiPassword.length(); i++) {
char c = jiamiPassword.charAt(i);
int ascii = ((int) c)-3-i;
char newChar = (char) ascii;
jiemiPassword.append(newChar);
}
return jiemiPassword.toString();
}
} | false | 840 | 24 | 886 | 26 | 1,012 | 22 | 886 | 26 | 1,132 | 39 | false | false | false | false | false | true |
27495_7 | package com.hotent.core.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import com.hotent.core.util.AppUtil;
import com.hotent.platform.dao.system.SysUserDao;
import com.hotent.platform.model.system.SysUser;
import com.hotent.platform.service.system.SysUserService;
/**
* 任务执行人
* @author ray
*
*/
public class TaskExecutor implements Serializable {
/**
* 默认不抽取。
*/
public static final int EXACT_NOEXACT=0;
/**
* 抽取用户
*/
public static final int EXACT_EXACT_USER=1;
/**
* 二级抽取,这个适用于会签任务,
* 就是角色先不抽取,到具体任务时,在进行人员抽取。
*/
public static final int EXACT_EXACT_SECOND=2;
/**
* 用户分组,这个适用于会签任务。
* 比如某个用户规则选出人员来后,将人员进行分组。
*
*/
public static final int EXACT_USER_GROUP=3;
/**
*
*/
private static final long serialVersionUID = 10001L;
/**
* 把任务直接授权给一个或多个用户
*/
public static final String USER_TYPE_USER="user";
/**
* 把任务直接授权给一个或多个组织
*/
public static final String USER_TYPE_ORG="org";
/**
* 把任务直接授权给一个或多个角色
*/
public static final String USER_TYPE_ROLE="role";
/**
* 把任务直接授权给一个或多个岗位
*/
public static final String USER_TYPE_POS="pos";
/**
* 用户分组。
*/
public static final String USER_TYPE_USERGROUP="group";
/**
* 执行人的类型为。
* type:
* user,用户
* org,组织
* role,角色
* pos,岗位
*/
private String type="user";
//如果type==user 则需要求出每个用户的主组织
public String mainOrgName;
/**
* 执行者ID
*/
private String executeId="";
/**
* 执行人name。
*/
private String executor="";
/**
* 抽取类型。
* 0:默认不抽取。
* 1:抽取
* 2:二级抽取
* 3:用户分组
*/
private int exactType=0;
public TaskExecutor(){}
/**
* 构造函数
* @param executeId 用户ID
*/
public TaskExecutor(String executeId){
Long userId = Long.parseLong(executeId);
SysUserService sysUserService = (SysUserService)AppUtil.getBean(SysUserService.class);
SysUser sysUser = sysUserService.getById(userId);
this.executeId = executeId;
this.executor = sysUser.getFullname();
}
/**
* 构造函数
* @param type 人员类型(user,pos,org,role)
* @param executeId 对应的id
* @param name 对应的名称
*/
public TaskExecutor(String type,String executeId,String name){
this.type=type;
this.executeId=executeId;
this.executor=name;
if(USER_TYPE_USERGROUP.equalsIgnoreCase(type)){
this.exactType=EXACT_USER_GROUP;
}
}
/**
* 获取任务用户。
* @param executeId
* @return
*/
public static TaskExecutor getTaskUser(String executeId,String name){
return new TaskExecutor(USER_TYPE_USER,executeId,name);
}
/**
* 获取组织执行人。
* @param executeId
* @return
*/
public static TaskExecutor getTaskOrg(String executeId,String name){
return new TaskExecutor(USER_TYPE_ORG,executeId, name);
}
/**
* 获取角色任务。
* @param executeId
* @return
*/
public static TaskExecutor getTaskRole(String executeId,String name){
return new TaskExecutor(USER_TYPE_ROLE,executeId,name);
}
/**
* 获取岗位。
* @param executeId
* @return
*/
public static TaskExecutor getTaskPos(String executeId,String name){
return new TaskExecutor(USER_TYPE_POS,executeId,name);
}
/**
* 获取用户分组。
* @param executeId
* @param name
* @return
*/
public static TaskExecutor getTaskUserGroup(String executeId,String name){
TaskExecutor ex= new TaskExecutor(USER_TYPE_USERGROUP,executeId,name);
ex.setExactType(EXACT_USER_GROUP);
return ex;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getExecuteId() {
return executeId;
}
public void setExecuteId(String executeId) {
this.executeId = executeId;
}
public String getExecutor() {
return executor;
}
public void setExecutor(String executor) {
this.executor = executor;
}
public int getExactType() {
return exactType;
}
public void setExactType(int exactType) {
this.exactType = exactType;
}
@Override
public boolean equals(Object obj){
if(! (obj instanceof TaskExecutor)){
return false;
}
TaskExecutor tmp=(TaskExecutor)obj;
if(this.type.equals(tmp.getType()) && this.executeId.equals(tmp.getExecuteId())){
return true;
}
return false;
}
@Override
public int hashCode(){
String tmp=this.type +this.executeId;
return tmp.hashCode();
}
public Set<SysUser> getSysUser() throws UnsatisfiedDependencyException{
Set<SysUser> sysUsers = new HashSet<SysUser>();
if(AppUtil.getContext()==null){
throw new UnsatisfiedDependencyException("Convert Executor to SysUser dependency ApplicationContext", "applicationContext", "", "Convert Executor to SysUser dependency ApplicationContext");
}
if(USER_TYPE_USER.equals(type)){
SysUserService sysUserService = (SysUserService) AppUtil.getBean(SysUserService.class);
SysUser sysUser = sysUserService.getById(Long.valueOf(executeId));
sysUsers.add(sysUser);
}else if(USER_TYPE_ORG.equals(type)){
SysUserDao sysUserDao = (SysUserDao) AppUtil.getBean(SysUserDao.class);
List<SysUser> users = sysUserDao.getByOrgId(Long.valueOf(executeId));
sysUsers.addAll(users);
}else if(USER_TYPE_POS.equals(type)){
SysUserDao sysUserDao = (SysUserDao) AppUtil.getBean(SysUserDao.class);
List<SysUser> users = sysUserDao.getByPosId(Long.valueOf(executeId));
sysUsers.addAll(users);
}else if(USER_TYPE_ROLE.equals(type)){
SysUserDao sysUserDao = (SysUserDao) AppUtil.getBean(SysUserDao.class);
List<SysUser> users = sysUserDao.getByRoleId(Long.valueOf(executeId));
sysUsers.addAll(users);
}
return sysUsers;
}
public String getMainOrgName() {
return mainOrgName;
}
public void setMainOrgName(String mainOrgName) {
this.mainOrgName = mainOrgName;
}
}
| cheong15/SysRoomManager | src/com/hotent/core/model/TaskExecutor.java | 1,927 | /**
* 把任务直接授权给一个或多个角色
*/ | block_comment | zh-cn | package com.hotent.core.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.UnsatisfiedDependencyException;
import com.hotent.core.util.AppUtil;
import com.hotent.platform.dao.system.SysUserDao;
import com.hotent.platform.model.system.SysUser;
import com.hotent.platform.service.system.SysUserService;
/**
* 任务执行人
* @author ray
*
*/
public class TaskExecutor implements Serializable {
/**
* 默认不抽取。
*/
public static final int EXACT_NOEXACT=0;
/**
* 抽取用户
*/
public static final int EXACT_EXACT_USER=1;
/**
* 二级抽取,这个适用于会签任务,
* 就是角色先不抽取,到具体任务时,在进行人员抽取。
*/
public static final int EXACT_EXACT_SECOND=2;
/**
* 用户分组,这个适用于会签任务。
* 比如某个用户规则选出人员来后,将人员进行分组。
*
*/
public static final int EXACT_USER_GROUP=3;
/**
*
*/
private static final long serialVersionUID = 10001L;
/**
* 把任务直接授权给一个或多个用户
*/
public static final String USER_TYPE_USER="user";
/**
* 把任务直接授权给一个或多个组织
*/
public static final String USER_TYPE_ORG="org";
/**
* 把任务 <SUF>*/
public static final String USER_TYPE_ROLE="role";
/**
* 把任务直接授权给一个或多个岗位
*/
public static final String USER_TYPE_POS="pos";
/**
* 用户分组。
*/
public static final String USER_TYPE_USERGROUP="group";
/**
* 执行人的类型为。
* type:
* user,用户
* org,组织
* role,角色
* pos,岗位
*/
private String type="user";
//如果type==user 则需要求出每个用户的主组织
public String mainOrgName;
/**
* 执行者ID
*/
private String executeId="";
/**
* 执行人name。
*/
private String executor="";
/**
* 抽取类型。
* 0:默认不抽取。
* 1:抽取
* 2:二级抽取
* 3:用户分组
*/
private int exactType=0;
public TaskExecutor(){}
/**
* 构造函数
* @param executeId 用户ID
*/
public TaskExecutor(String executeId){
Long userId = Long.parseLong(executeId);
SysUserService sysUserService = (SysUserService)AppUtil.getBean(SysUserService.class);
SysUser sysUser = sysUserService.getById(userId);
this.executeId = executeId;
this.executor = sysUser.getFullname();
}
/**
* 构造函数
* @param type 人员类型(user,pos,org,role)
* @param executeId 对应的id
* @param name 对应的名称
*/
public TaskExecutor(String type,String executeId,String name){
this.type=type;
this.executeId=executeId;
this.executor=name;
if(USER_TYPE_USERGROUP.equalsIgnoreCase(type)){
this.exactType=EXACT_USER_GROUP;
}
}
/**
* 获取任务用户。
* @param executeId
* @return
*/
public static TaskExecutor getTaskUser(String executeId,String name){
return new TaskExecutor(USER_TYPE_USER,executeId,name);
}
/**
* 获取组织执行人。
* @param executeId
* @return
*/
public static TaskExecutor getTaskOrg(String executeId,String name){
return new TaskExecutor(USER_TYPE_ORG,executeId, name);
}
/**
* 获取角色任务。
* @param executeId
* @return
*/
public static TaskExecutor getTaskRole(String executeId,String name){
return new TaskExecutor(USER_TYPE_ROLE,executeId,name);
}
/**
* 获取岗位。
* @param executeId
* @return
*/
public static TaskExecutor getTaskPos(String executeId,String name){
return new TaskExecutor(USER_TYPE_POS,executeId,name);
}
/**
* 获取用户分组。
* @param executeId
* @param name
* @return
*/
public static TaskExecutor getTaskUserGroup(String executeId,String name){
TaskExecutor ex= new TaskExecutor(USER_TYPE_USERGROUP,executeId,name);
ex.setExactType(EXACT_USER_GROUP);
return ex;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getExecuteId() {
return executeId;
}
public void setExecuteId(String executeId) {
this.executeId = executeId;
}
public String getExecutor() {
return executor;
}
public void setExecutor(String executor) {
this.executor = executor;
}
public int getExactType() {
return exactType;
}
public void setExactType(int exactType) {
this.exactType = exactType;
}
@Override
public boolean equals(Object obj){
if(! (obj instanceof TaskExecutor)){
return false;
}
TaskExecutor tmp=(TaskExecutor)obj;
if(this.type.equals(tmp.getType()) && this.executeId.equals(tmp.getExecuteId())){
return true;
}
return false;
}
@Override
public int hashCode(){
String tmp=this.type +this.executeId;
return tmp.hashCode();
}
public Set<SysUser> getSysUser() throws UnsatisfiedDependencyException{
Set<SysUser> sysUsers = new HashSet<SysUser>();
if(AppUtil.getContext()==null){
throw new UnsatisfiedDependencyException("Convert Executor to SysUser dependency ApplicationContext", "applicationContext", "", "Convert Executor to SysUser dependency ApplicationContext");
}
if(USER_TYPE_USER.equals(type)){
SysUserService sysUserService = (SysUserService) AppUtil.getBean(SysUserService.class);
SysUser sysUser = sysUserService.getById(Long.valueOf(executeId));
sysUsers.add(sysUser);
}else if(USER_TYPE_ORG.equals(type)){
SysUserDao sysUserDao = (SysUserDao) AppUtil.getBean(SysUserDao.class);
List<SysUser> users = sysUserDao.getByOrgId(Long.valueOf(executeId));
sysUsers.addAll(users);
}else if(USER_TYPE_POS.equals(type)){
SysUserDao sysUserDao = (SysUserDao) AppUtil.getBean(SysUserDao.class);
List<SysUser> users = sysUserDao.getByPosId(Long.valueOf(executeId));
sysUsers.addAll(users);
}else if(USER_TYPE_ROLE.equals(type)){
SysUserDao sysUserDao = (SysUserDao) AppUtil.getBean(SysUserDao.class);
List<SysUser> users = sysUserDao.getByRoleId(Long.valueOf(executeId));
sysUsers.addAll(users);
}
return sysUsers;
}
public String getMainOrgName() {
return mainOrgName;
}
public void setMainOrgName(String mainOrgName) {
this.mainOrgName = mainOrgName;
}
}
| false | 1,601 | 16 | 1,927 | 15 | 1,972 | 16 | 1,927 | 15 | 2,448 | 29 | false | false | false | false | false | true |
26019_3 | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Java函数式编程(三):列表的转化
*
* @author Ethan
* @date 2015/12/3 0003 10:25
*/
public class Demo03 {
public static void main(String[] args) {
//需求:将列表中的名字转化成全大写的
//创建一个不可变的名字的列表
final List<String> friends = Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");
//生成另一个全部大写的列表
final List<String> uppercaseNames = new ArrayList<>();
for (String name : friends) {
uppercaseNames.add(name.toUpperCase());
}
//改进1--虽然用了内部迭代器,但扔新建了一个列表,继续改进...
final List<String> uppercaseNames2 = new ArrayList<>();
friends.forEach(name -> uppercaseNames2.add(name.toUpperCase()));
System.out.println("-------------Stream的map过滤简化-------------");
//改进2---Stream类的map方法
/*map方法很适合把一个输入集合转化成一个新的输出集合。*/
friends.stream()
.map(name -> name.toUpperCase())
.filter(name -> name.endsWith("E"))
.forEach(name -> System.out.println(name));
System.out.println("----------------方法引用再简化-------------------");
friends.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
System.out.println("------------输出各个名字的长度------------");
friends.stream()
.map(String::length)
.forEach(System.out::println);
/*
* 什么时候应该使用方法引用?
* 当使用Java编程的时候,通常我们用lambda表达式的时候要比方法引用多得多。但这并不意味着方法引用不重要或者没啥用处。当lambda
* 表达式非常简短的时候,它是一个很好的替代方案,它直接调用了实例方法或者静态方法。
* 也就是说,如果lambda表达式只是传递了一下参数给方法调用的话,我们应该改用方法引用。
* 像这样的lambda表达式,有点像Tom Smykowski在电影上班一条虫中讲的那样,
* 它的工作就是"从客户那把需求拿给软件工程师"。
* 因为这个,我把这种重构成方法引用的模式叫做上班一条虫模式。
* 除了简洁外,使用方法引用,方法名字本身的含义和作用可以更好的体现出来。
* 使用方法引用背后,编译器起到了很关键的作用。方法引用的目标对象和参数都会从这个生成的方法里传进来的参数那推导出来。
* 这才使得你可以使用方法引用写出比使用lambda表达式更简洁的代码。
* 不过,如果参数在传递给方法之前或者调用结果在返回之后要被修改的话,这种便利的写法我们就用不了了。
* */
}
}
| cherish2008/Java1.8 | src/Demo03.java | 730 | //生成另一个全部大写的列表 | line_comment | zh-cn | import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Java函数式编程(三):列表的转化
*
* @author Ethan
* @date 2015/12/3 0003 10:25
*/
public class Demo03 {
public static void main(String[] args) {
//需求:将列表中的名字转化成全大写的
//创建一个不可变的名字的列表
final List<String> friends = Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");
//生成 <SUF>
final List<String> uppercaseNames = new ArrayList<>();
for (String name : friends) {
uppercaseNames.add(name.toUpperCase());
}
//改进1--虽然用了内部迭代器,但扔新建了一个列表,继续改进...
final List<String> uppercaseNames2 = new ArrayList<>();
friends.forEach(name -> uppercaseNames2.add(name.toUpperCase()));
System.out.println("-------------Stream的map过滤简化-------------");
//改进2---Stream类的map方法
/*map方法很适合把一个输入集合转化成一个新的输出集合。*/
friends.stream()
.map(name -> name.toUpperCase())
.filter(name -> name.endsWith("E"))
.forEach(name -> System.out.println(name));
System.out.println("----------------方法引用再简化-------------------");
friends.stream()
.map(String::toUpperCase)
.forEach(System.out::println);
System.out.println("------------输出各个名字的长度------------");
friends.stream()
.map(String::length)
.forEach(System.out::println);
/*
* 什么时候应该使用方法引用?
* 当使用Java编程的时候,通常我们用lambda表达式的时候要比方法引用多得多。但这并不意味着方法引用不重要或者没啥用处。当lambda
* 表达式非常简短的时候,它是一个很好的替代方案,它直接调用了实例方法或者静态方法。
* 也就是说,如果lambda表达式只是传递了一下参数给方法调用的话,我们应该改用方法引用。
* 像这样的lambda表达式,有点像Tom Smykowski在电影上班一条虫中讲的那样,
* 它的工作就是"从客户那把需求拿给软件工程师"。
* 因为这个,我把这种重构成方法引用的模式叫做上班一条虫模式。
* 除了简洁外,使用方法引用,方法名字本身的含义和作用可以更好的体现出来。
* 使用方法引用背后,编译器起到了很关键的作用。方法引用的目标对象和参数都会从这个生成的方法里传进来的参数那推导出来。
* 这才使得你可以使用方法引用写出比使用lambda表达式更简洁的代码。
* 不过,如果参数在传递给方法之前或者调用结果在返回之后要被修改的话,这种便利的写法我们就用不了了。
* */
}
}
| false | 630 | 7 | 730 | 9 | 708 | 7 | 730 | 9 | 1,062 | 15 | false | false | false | false | false | true |
64199_1 | package com.cherry.leetcode.offer;
import java.util.ArrayDeque;
/**
* @Author: Cherry
* @Date: 2021/3/27
* @Desc: Issue64
* <p>
* 求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
*/
public class Issue64 {
public int sumNums(int n) {
boolean x = n > 1 && (n += sumNums(n - 1)) > 0;
return n;
}
public static void main(String[] args) {
System.out.println(sum(20) - 1);
}
public int test() {
int x1 = 3;
int y1 = 3;
int xk = 0;
int yk = 0;
int x2 = 0;
int y2 = 0;
int i = 1;
while (x2 != 3 && y2 != 3) {
String ship = i % 2 == 1 ? "船从左到右" : "";
System.out.printf("第%d次,%s,左岸商人%d仆人%d,->>船上商人%d仆人%d,右岸商人%d仆人%d", ship, i, x1, y1, xk, yk, x2, y2);
}
return -1;
}
public static double sum(int i) {
if (i == 0) {
return 1;
}
return sum(i - 1) * 1.075 + 1;
}
// 邻接矩阵表示无向图
private int data[][] = {
{0, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 0, 0},
{1, 0, 0, 0, 0, 1},
{1, 1, 0, 0, 1, 0},
{0, 0, 0, 1, 0, 0},
{0, 0, 1, 0, 0, 0}
};
private int indexX = 0;
private int indexY = 0;
public void findPath(int maxDepth, int start, int end) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
dfs(maxDepth, queue, start, end);
}
public void dfs(int maxDepth, ArrayDeque<Integer> queue, int start, int end) {
if (data[indexX][indexY] == 1 && queue.contains(indexX)) {
if (queue.size() <= maxDepth) {
if (queue.getFirst() == start && queue.getLast() == end) {
// 输出结果集
System.out.println(queue);
queue.removeLast();
dfs(maxDepth, queue, start, end);
} else {
queue.add(indexX);
}
} else {
// 回溯
queue.removeLast();
indexX--;
indexY++;
dfs(maxDepth, queue, start, end);
}
}
indexY++;
}
public void init(int size, String[] graph) {
}
}
| cherryEmpire/spring-all-fun | leetcode-problemset/src/main/java/com/cherry/leetcode/offer/Issue64.java | 798 | // 邻接矩阵表示无向图 | line_comment | zh-cn | package com.cherry.leetcode.offer;
import java.util.ArrayDeque;
/**
* @Author: Cherry
* @Date: 2021/3/27
* @Desc: Issue64
* <p>
* 求 1+2+...+n ,要求不能使用乘除法、for、while、if、else、switch、case等关键字及条件判断语句(A?B:C)。
*/
public class Issue64 {
public int sumNums(int n) {
boolean x = n > 1 && (n += sumNums(n - 1)) > 0;
return n;
}
public static void main(String[] args) {
System.out.println(sum(20) - 1);
}
public int test() {
int x1 = 3;
int y1 = 3;
int xk = 0;
int yk = 0;
int x2 = 0;
int y2 = 0;
int i = 1;
while (x2 != 3 && y2 != 3) {
String ship = i % 2 == 1 ? "船从左到右" : "";
System.out.printf("第%d次,%s,左岸商人%d仆人%d,->>船上商人%d仆人%d,右岸商人%d仆人%d", ship, i, x1, y1, xk, yk, x2, y2);
}
return -1;
}
public static double sum(int i) {
if (i == 0) {
return 1;
}
return sum(i - 1) * 1.075 + 1;
}
// 邻接 <SUF>
private int data[][] = {
{0, 1, 1, 1, 0, 0},
{1, 0, 0, 1, 0, 0},
{1, 0, 0, 0, 0, 1},
{1, 1, 0, 0, 1, 0},
{0, 0, 0, 1, 0, 0},
{0, 0, 1, 0, 0, 0}
};
private int indexX = 0;
private int indexY = 0;
public void findPath(int maxDepth, int start, int end) {
ArrayDeque<Integer> queue = new ArrayDeque<>();
dfs(maxDepth, queue, start, end);
}
public void dfs(int maxDepth, ArrayDeque<Integer> queue, int start, int end) {
if (data[indexX][indexY] == 1 && queue.contains(indexX)) {
if (queue.size() <= maxDepth) {
if (queue.getFirst() == start && queue.getLast() == end) {
// 输出结果集
System.out.println(queue);
queue.removeLast();
dfs(maxDepth, queue, start, end);
} else {
queue.add(indexX);
}
} else {
// 回溯
queue.removeLast();
indexX--;
indexY++;
dfs(maxDepth, queue, start, end);
}
}
indexY++;
}
public void init(int size, String[] graph) {
}
}
| false | 736 | 10 | 798 | 10 | 839 | 9 | 798 | 10 | 934 | 17 | false | false | false | false | false | true |
8131_4 | /*
In the "100 game," two players take turns adding, to a running total, any integer from 1..10.
The player who first causes the running total to reach or exceed 100 wins.
What if we change the game so that players cannot re-use integers?
For example, two players might take turns drawing from a common pool of numbers of 1..15
without replacement until they reach a total >= 100.
Given an integer maxChoosableInteger and another integer desiredTotal,
determine if the first player to move can force a win, assuming both players play optimally.
You can always assume that maxChoosableInteger will not be larger than 20 and desiredTotal will not be larger than 300.
Example
Input:
maxChoosableInteger = 10
desiredTotal = 11
Output:
false
Explanation:
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
*/
/**
* Approach: Game Theory (Using Recursion + Memory Search)
* 这道题目属于博弈论的类型,其实质是一个求 Permutations 的过程。
* 在取数的过程中,安装取的顺序,我们总共有 maxChoosableInteger! 种方案,即 1~maxChoosableInteger 的全排列。
* 但是枚举 maxChoosableInteger! 种方案明显超过了能承受的时间复杂度。
* 原因在于我们进行了大量重复的不必要计算。
*
* 分析题目,我们发现,只要当前状态已经确定,那么结果也就确定了。
* 即只要游戏还没结束,我们并不关心如何来到当前状态。如:玩家取了 1,3 和 3,1 结果是相同的。
* 因此我们可以采用记忆化搜索的方法将已经计算过的状态保存下来,从而达到优化时间复杂度的目的。
*
* 递归过程中,我们关心的状态有:当前所能取到的最大值(这个是不变的);当前所取到值之和;以及那些数已经被取过了
* 这里我们稍微进行了 两点 空间复杂度上的优化:
* 1. 使用 dp[] 来记录计算出来的结果。因为其只有 3 中状态,所以我们使用 byte 就够了,开 int[] 浪费了。
* 2. 使用一个 int 来记录哪些数被取过。因为 maxChoosableInteger 不会超过 20,而 int 有 32 位,完全够用了。
* 这个做法非常常见,包括大家所熟悉的 BitMap 也使用到了这个做法。
*
* 时间复杂度:O(2^n)
*
* 参考资料:https://www.youtube.com/watch?v=GNZIAbf0gT0
*/
class Solution {
byte[] dp; // 0: unknow, 1: can win, -1: can't win
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
int sum = maxChoosableInteger * (maxChoosableInteger + 1) >> 1;
// 取出所有的数都凑不出 desiredTotal,肯定输
if (desiredTotal > sum) {
return false;
}
// 可取的最大值直接 >= 期望值,先手必赢
if (desiredTotal <= maxChoosableInteger) {
return true;
}
// dp[]的 index 就表示了其中一种方案.(思想与利用 二进制 计算subset相同)
dp = new byte[1 << maxChoosableInteger];
return canIWinHelper(maxChoosableInteger, desiredTotal, 0);
}
private boolean canIWinHelper(int maxChoosableInteger, int desiredTotal, int state) {
// if the previous player make desiredTotal <= 0, it means he can win, then the current player lose.
if (desiredTotal <= 0) {
dp[state] = -1;
return false;
}
// if the current state has been calculated before, return the result directly
if (dp[state] != 0) {
return dp[state] == 1;
}
for (int i = 0; i < maxChoosableInteger; i++) {
// if number i is used, skip it
if (((state >> i) & 1) > 0) {
continue;
}
// the next player can't win, them the current player can win
if (!canIWinHelper(maxChoosableInteger, desiredTotal - (i + 1), state | (1 << i))) {
dp[state] = 1;
return true;
}
}
dp[state] = -1;
return false;
}
} | cherryljr/LeetCode | Can I Win.java | 1,217 | // 可取的最大值直接 >= 期望值,先手必赢
| line_comment | zh-cn | /*
In the "100 game," two players take turns adding, to a running total, any integer from 1..10.
The player who first causes the running total to reach or exceed 100 wins.
What if we change the game so that players cannot re-use integers?
For example, two players might take turns drawing from a common pool of numbers of 1..15
without replacement until they reach a total >= 100.
Given an integer maxChoosableInteger and another integer desiredTotal,
determine if the first player to move can force a win, assuming both players play optimally.
You can always assume that maxChoosableInteger will not be larger than 20 and desiredTotal will not be larger than 300.
Example
Input:
maxChoosableInteger = 10
desiredTotal = 11
Output:
false
Explanation:
No matter which integer the first player choose, the first player will lose.
The first player can choose an integer from 1 up to 10.
If the first player choose 1, the second player can only choose integers from 2 up to 10.
The second player will win by choosing 10 and get a total = 11, which is >= desiredTotal.
Same with other integers chosen by the first player, the second player will always win.
*/
/**
* Approach: Game Theory (Using Recursion + Memory Search)
* 这道题目属于博弈论的类型,其实质是一个求 Permutations 的过程。
* 在取数的过程中,安装取的顺序,我们总共有 maxChoosableInteger! 种方案,即 1~maxChoosableInteger 的全排列。
* 但是枚举 maxChoosableInteger! 种方案明显超过了能承受的时间复杂度。
* 原因在于我们进行了大量重复的不必要计算。
*
* 分析题目,我们发现,只要当前状态已经确定,那么结果也就确定了。
* 即只要游戏还没结束,我们并不关心如何来到当前状态。如:玩家取了 1,3 和 3,1 结果是相同的。
* 因此我们可以采用记忆化搜索的方法将已经计算过的状态保存下来,从而达到优化时间复杂度的目的。
*
* 递归过程中,我们关心的状态有:当前所能取到的最大值(这个是不变的);当前所取到值之和;以及那些数已经被取过了
* 这里我们稍微进行了 两点 空间复杂度上的优化:
* 1. 使用 dp[] 来记录计算出来的结果。因为其只有 3 中状态,所以我们使用 byte 就够了,开 int[] 浪费了。
* 2. 使用一个 int 来记录哪些数被取过。因为 maxChoosableInteger 不会超过 20,而 int 有 32 位,完全够用了。
* 这个做法非常常见,包括大家所熟悉的 BitMap 也使用到了这个做法。
*
* 时间复杂度:O(2^n)
*
* 参考资料:https://www.youtube.com/watch?v=GNZIAbf0gT0
*/
class Solution {
byte[] dp; // 0: unknow, 1: can win, -1: can't win
public boolean canIWin(int maxChoosableInteger, int desiredTotal) {
int sum = maxChoosableInteger * (maxChoosableInteger + 1) >> 1;
// 取出所有的数都凑不出 desiredTotal,肯定输
if (desiredTotal > sum) {
return false;
}
// 可取 <SUF>
if (desiredTotal <= maxChoosableInteger) {
return true;
}
// dp[]的 index 就表示了其中一种方案.(思想与利用 二进制 计算subset相同)
dp = new byte[1 << maxChoosableInteger];
return canIWinHelper(maxChoosableInteger, desiredTotal, 0);
}
private boolean canIWinHelper(int maxChoosableInteger, int desiredTotal, int state) {
// if the previous player make desiredTotal <= 0, it means he can win, then the current player lose.
if (desiredTotal <= 0) {
dp[state] = -1;
return false;
}
// if the current state has been calculated before, return the result directly
if (dp[state] != 0) {
return dp[state] == 1;
}
for (int i = 0; i < maxChoosableInteger; i++) {
// if number i is used, skip it
if (((state >> i) & 1) > 0) {
continue;
}
// the next player can't win, them the current player can win
if (!canIWinHelper(maxChoosableInteger, desiredTotal - (i + 1), state | (1 << i))) {
dp[state] = 1;
return true;
}
}
dp[state] = -1;
return false;
}
} | false | 1,116 | 17 | 1,201 | 19 | 1,167 | 16 | 1,201 | 19 | 1,496 | 23 | false | false | false | false | false | true |
29177_14 | /*
Description
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present.
When the cache reached its CAPACITY, it should invalidate the least recently used item before inserting a new item.
Example
Tags
Linked List Uber Zenefits Google
*/
/**
* Approach 1: HashMap + DoubleLinkedList
* 这类题目纯粹考察的是我们的 Coding 能力。
* 只需要分析好这个数据结构需要实现的 逻辑功能,并处理好各种情况下的 Case,就能够解决题目。
*
* 为了实现 LRU,首先我们需要准备一个 HashMap 来存储 key 与对应的信息 value。
* 其次,各个节点具有优先级(最新被调用的优先级最高),并且我们需要 频繁地 对其进行修改。
* 那么最合适的毫无疑问就是 链表了。并且我们还需要在队列的两端都能够进行操作,
* 因此我们需要设计一个 双向链表。具备 head, tail 指针,数据从 尾部 插入(tail节点优先级最高)
*
* 接下来我们来考虑,HashMap 和 链表的节点 中应该存放哪些信息。
* 对与 HashMap 而言,key毫无疑问就是我们插入的 key 了,但是 value 就直接是对应的 value 吗?
* 并不是,因为对于 链表 而言,查询一个 key 需要花费 O(n) 的时间代价,
* 但是我们使用了 HashMap 因此可以将查询的时间复杂度降低到 O(1),那么为什么不在 value 中放入链表的 Node 呢?
* 这样就能够使我们可以通过 map 查询到 key 对应的 node 之后,直接对 双向链表 进行操作,从而省去遍历链表的时间。
* 对于 Node 而言,我们需要放入的信息有:value, prePointer, nextPointer 以及 key.
* 放入 key 的原因是考虑到了 removeHead() 这个函数,当 LRU 的大小到达 CAPACITY 时,
* 如果继续插入元素,我们将移除 优先级最低 的节点,也就是我们的 head 节点。
* 这个时候如果 Node 中含有 key 这个信息的话,我们可以直接通过 Node 获得 key,从而对 map 也进行相应的 remove 操作。
*
* 具体实现请参考代码以及注释。
*/
public class LRUCache {
private Map<Integer, Node> map;
private DoubleLinkedList list;
public final int CAPACITY;
/*
* @param capacity: An integer
*/public LRUCache(int capacity) {
// do intialization if necessary
this.map = new HashMap<>();
this.list = new DoubleLinkedList();
this.CAPACITY = capacity;
}
/*
* @param key: An integer
* @return: An integer
*/
public int get(int key) {
if (map.containsKey(key)) {
Node node = map.get(key);
// 因为发生 get 操作,将对应的节点移动到链表末尾(优先级置为最高)
list.moveNodeToTail(node);
return node.value;
}
return -1;
}
/*
* @param key: An integer
* @param value: An integer
* @return: nothing
*/
public void set(int key, int value) {
if (!map.containsKey(key)) {
// 若不包含该元素,则在 map 和 list 中插入数据
Node newNode = new Node(key, value);
list.add(newNode);
map.put(key, newNode);
if (map.size() > CAPACITY) {
// 如果本次插入导致了map的大小 大于 LRU.CAPACITY,则移除优先级最低的节点
removeMostUnusedNode();
}
} else {
// 更新节点值,同时将对应的节点优先级置为最高
Node node = map.get(key);
node.value = value;
list.moveNodeToTail(node);
}
}
private void removeMostUnusedNode() {
// 分别从 list 和 map 中移除对应的元素
Node removedNode = this.list.removeHead();
map.remove(removedNode.key);
}
private class Node {
int key;
int value;
Node pre, next;
public Node(int key, int value) {
this.key = key;
this.value = value;
this.pre = null;
this.next = null;
}
}
private class DoubleLinkedList {
private Node head; // 头结点(优先级最低)
private Node tail; // 尾节点(优先级最高)
public DoubleLinkedList() {
this.head = null;
this.tail = null;
}
public void add(Node node) {
if (node == null) {
return;
}
if (head == null) {
head = node;
tail = node;
} else {
tail.next = node;
node.pre = tail;
tail = node;
}
}
public void moveNodeToTail(Node node) {
if (node == tail) {
// 如果本身就是尾节点,则无需移动
return;
}
if (node == head) {
// 如果要移动到末尾的是头节点,则需要将头结点向后移动一位(移除原来的头结点)
head = head.next;
head.pre = null;
} else {
// 如果要移除的节点位于 链表中间,则连接该节点两端的节点
node.pre.next = node.next;
node.next.pre = node.pre;
}
// 将该节点连接在 原来的tail 之后,然后更新 tail 节点
tail.next = node;
node.pre = tail;
node.next = null;
tail = node;
}
public Node removeHead() {
if (head == null) {
return null;
}
Node removedNode = head;
if (head == tail) {
// 只有一个节点,直接删除即可
head = null;
tail = null;
} else {
// 删除头节点
head = removedNode.next;
head.pre = null;
removedNode.next = null;
}
return removedNode;
}
}
}
/**
* Approach 2: Using LinkedHashMap
* This is the laziest implementation using Java’s LinkedHashMap.
*
* Several points to mention:
* In the constructor, the third boolean parameter specifies the ordering mode.
* If we set it to true, it will be in access order.
* (https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#LinkedHashMap-int-float-boolean-)
* By overriding removeEldestEntry in this way, we do not need to take care of it ourselves.
* It will automatically remove the least recent one when the size of map exceeds the specified capacity.
* (https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#removeEldestEntry-java.util.Map.Entry-)
*/
public class LRUCache {
private LinkedHashMap<Integer, Integer> map;
private final int CAPACITY;
/*
* @param capacity: An integer
*/
public LRUCache(int capacity) {
// do intialization if necessary
this.CAPACITY = capacity;
// The map will be in access order
map = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true){
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > CAPACITY;
}
};
}
/*
* @param key: An integer
* @return: An integer
*/
public int get(int key) {
return map.getOrDefault(key, -1);
}
/*
* @param key: An integer
* @param value: An integer
* @return: nothing
*/
public void set(int key, int value) {
map.put(key, value);
}
}
/**
* LRU Cache Template (Using Generics)
*/
public class LRU {
public static class Node<K, V> {
public K key;
public V value;
public Node<K, V> pre;
public Node<K, V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
this.pre = null;
this.next = null;
}
}
public static class DoubleLinkedList<K, V> {
private Node<K, V> head;
private Node<K, V> tail;
public DoubleLinkedList() {
this.head = null;
this.tail = null;
}
public void addNode(Node<K, V> newNode) {
if (newNode == null) {
return;
}
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.pre = tail;
tail = newNode;
}
}
public void moveNodeToTail(Node<K, V> node) {
if (tail == node) {
return;
}
if (head == node) {
head = node.next;
head.pre = null;
} else {
node.pre.next = node.next;
node.next.pre = node.pre;
}
tail.next = node;
node.pre = tail;
node.next = null;
tail = node;
}
public Node<K, V> removeHead() {
if (head == null) {
return null;
}
Node<K, V> removedNode = head;
if (head == tail) {
head = null;
tail = null;
} else {
head = removedNode.next;
head.pre = null;
removedNode.next = null;
}
return removedNode;
}
}
public static class LRUCache<K, V> {
private HashMap<K, Node<K, V>> map;
private DoubleLinkedList<K, V> list;
private final int CAPACITY;
public LRUCache(int capacity) {
// do intialization
if (capacity < 1) {
throw new RuntimeException("should be more than 0.");
}
map = new HashMap<>();
list = new DoubleLinkedList<>();
this.CAPACITY = capacity;
}
public V get(K key) {
if (map.containsKey(key)) {
Node<K, V> node = map.get(key);
list.moveNodeToTail(node);
return node.value;
}
return null;
}
public void set(K key, V value) {
if (map.containsKey(key)) {
Node<K, V> node = map.get(key);
node.value = value;
list.moveNodeToTail(node);
} else {
Node<K, V> newNode = new Node<>(key, value);
map.put(key, newNode);
list.addNode(newNode);
if (map.size() > CAPACITY) {
removeMostUnusedCache();
}
}
}
private void removeMostUnusedCache() {
Node<K, V> removedNode = list.removeHead();
map.remove(removedNode.key);
}
}
public static void main(String[] args) {
LRUCache<String, Integer> testCache = new LRUCache<>(3);
testCache.set("A", 1);
testCache.set("B", 2);
testCache.set("C", 3);
System.out.println(testCache.get("B"));
System.out.println(testCache.get("A"));
testCache.set("D", 4);
System.out.println(testCache.get("D"));
System.out.println(testCache.get("C"));
}
} | cherryljr/LintCode | LRU Cache.java | 2,816 | // 如果要移动到末尾的是头节点,则需要将头结点向后移动一位(移除原来的头结点)
| line_comment | zh-cn | /*
Description
Design and implement a data structure for Least Recently Used (LRU) cache.
It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present.
When the cache reached its CAPACITY, it should invalidate the least recently used item before inserting a new item.
Example
Tags
Linked List Uber Zenefits Google
*/
/**
* Approach 1: HashMap + DoubleLinkedList
* 这类题目纯粹考察的是我们的 Coding 能力。
* 只需要分析好这个数据结构需要实现的 逻辑功能,并处理好各种情况下的 Case,就能够解决题目。
*
* 为了实现 LRU,首先我们需要准备一个 HashMap 来存储 key 与对应的信息 value。
* 其次,各个节点具有优先级(最新被调用的优先级最高),并且我们需要 频繁地 对其进行修改。
* 那么最合适的毫无疑问就是 链表了。并且我们还需要在队列的两端都能够进行操作,
* 因此我们需要设计一个 双向链表。具备 head, tail 指针,数据从 尾部 插入(tail节点优先级最高)
*
* 接下来我们来考虑,HashMap 和 链表的节点 中应该存放哪些信息。
* 对与 HashMap 而言,key毫无疑问就是我们插入的 key 了,但是 value 就直接是对应的 value 吗?
* 并不是,因为对于 链表 而言,查询一个 key 需要花费 O(n) 的时间代价,
* 但是我们使用了 HashMap 因此可以将查询的时间复杂度降低到 O(1),那么为什么不在 value 中放入链表的 Node 呢?
* 这样就能够使我们可以通过 map 查询到 key 对应的 node 之后,直接对 双向链表 进行操作,从而省去遍历链表的时间。
* 对于 Node 而言,我们需要放入的信息有:value, prePointer, nextPointer 以及 key.
* 放入 key 的原因是考虑到了 removeHead() 这个函数,当 LRU 的大小到达 CAPACITY 时,
* 如果继续插入元素,我们将移除 优先级最低 的节点,也就是我们的 head 节点。
* 这个时候如果 Node 中含有 key 这个信息的话,我们可以直接通过 Node 获得 key,从而对 map 也进行相应的 remove 操作。
*
* 具体实现请参考代码以及注释。
*/
public class LRUCache {
private Map<Integer, Node> map;
private DoubleLinkedList list;
public final int CAPACITY;
/*
* @param capacity: An integer
*/public LRUCache(int capacity) {
// do intialization if necessary
this.map = new HashMap<>();
this.list = new DoubleLinkedList();
this.CAPACITY = capacity;
}
/*
* @param key: An integer
* @return: An integer
*/
public int get(int key) {
if (map.containsKey(key)) {
Node node = map.get(key);
// 因为发生 get 操作,将对应的节点移动到链表末尾(优先级置为最高)
list.moveNodeToTail(node);
return node.value;
}
return -1;
}
/*
* @param key: An integer
* @param value: An integer
* @return: nothing
*/
public void set(int key, int value) {
if (!map.containsKey(key)) {
// 若不包含该元素,则在 map 和 list 中插入数据
Node newNode = new Node(key, value);
list.add(newNode);
map.put(key, newNode);
if (map.size() > CAPACITY) {
// 如果本次插入导致了map的大小 大于 LRU.CAPACITY,则移除优先级最低的节点
removeMostUnusedNode();
}
} else {
// 更新节点值,同时将对应的节点优先级置为最高
Node node = map.get(key);
node.value = value;
list.moveNodeToTail(node);
}
}
private void removeMostUnusedNode() {
// 分别从 list 和 map 中移除对应的元素
Node removedNode = this.list.removeHead();
map.remove(removedNode.key);
}
private class Node {
int key;
int value;
Node pre, next;
public Node(int key, int value) {
this.key = key;
this.value = value;
this.pre = null;
this.next = null;
}
}
private class DoubleLinkedList {
private Node head; // 头结点(优先级最低)
private Node tail; // 尾节点(优先级最高)
public DoubleLinkedList() {
this.head = null;
this.tail = null;
}
public void add(Node node) {
if (node == null) {
return;
}
if (head == null) {
head = node;
tail = node;
} else {
tail.next = node;
node.pre = tail;
tail = node;
}
}
public void moveNodeToTail(Node node) {
if (node == tail) {
// 如果本身就是尾节点,则无需移动
return;
}
if (node == head) {
// 如果 <SUF>
head = head.next;
head.pre = null;
} else {
// 如果要移除的节点位于 链表中间,则连接该节点两端的节点
node.pre.next = node.next;
node.next.pre = node.pre;
}
// 将该节点连接在 原来的tail 之后,然后更新 tail 节点
tail.next = node;
node.pre = tail;
node.next = null;
tail = node;
}
public Node removeHead() {
if (head == null) {
return null;
}
Node removedNode = head;
if (head == tail) {
// 只有一个节点,直接删除即可
head = null;
tail = null;
} else {
// 删除头节点
head = removedNode.next;
head.pre = null;
removedNode.next = null;
}
return removedNode;
}
}
}
/**
* Approach 2: Using LinkedHashMap
* This is the laziest implementation using Java’s LinkedHashMap.
*
* Several points to mention:
* In the constructor, the third boolean parameter specifies the ordering mode.
* If we set it to true, it will be in access order.
* (https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#LinkedHashMap-int-float-boolean-)
* By overriding removeEldestEntry in this way, we do not need to take care of it ourselves.
* It will automatically remove the least recent one when the size of map exceeds the specified capacity.
* (https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html#removeEldestEntry-java.util.Map.Entry-)
*/
public class LRUCache {
private LinkedHashMap<Integer, Integer> map;
private final int CAPACITY;
/*
* @param capacity: An integer
*/
public LRUCache(int capacity) {
// do intialization if necessary
this.CAPACITY = capacity;
// The map will be in access order
map = new LinkedHashMap<Integer, Integer>(capacity, 0.75f, true){
protected boolean removeEldestEntry(Map.Entry eldest) {
return size() > CAPACITY;
}
};
}
/*
* @param key: An integer
* @return: An integer
*/
public int get(int key) {
return map.getOrDefault(key, -1);
}
/*
* @param key: An integer
* @param value: An integer
* @return: nothing
*/
public void set(int key, int value) {
map.put(key, value);
}
}
/**
* LRU Cache Template (Using Generics)
*/
public class LRU {
public static class Node<K, V> {
public K key;
public V value;
public Node<K, V> pre;
public Node<K, V> next;
public Node(K key, V value) {
this.key = key;
this.value = value;
this.pre = null;
this.next = null;
}
}
public static class DoubleLinkedList<K, V> {
private Node<K, V> head;
private Node<K, V> tail;
public DoubleLinkedList() {
this.head = null;
this.tail = null;
}
public void addNode(Node<K, V> newNode) {
if (newNode == null) {
return;
}
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.pre = tail;
tail = newNode;
}
}
public void moveNodeToTail(Node<K, V> node) {
if (tail == node) {
return;
}
if (head == node) {
head = node.next;
head.pre = null;
} else {
node.pre.next = node.next;
node.next.pre = node.pre;
}
tail.next = node;
node.pre = tail;
node.next = null;
tail = node;
}
public Node<K, V> removeHead() {
if (head == null) {
return null;
}
Node<K, V> removedNode = head;
if (head == tail) {
head = null;
tail = null;
} else {
head = removedNode.next;
head.pre = null;
removedNode.next = null;
}
return removedNode;
}
}
public static class LRUCache<K, V> {
private HashMap<K, Node<K, V>> map;
private DoubleLinkedList<K, V> list;
private final int CAPACITY;
public LRUCache(int capacity) {
// do intialization
if (capacity < 1) {
throw new RuntimeException("should be more than 0.");
}
map = new HashMap<>();
list = new DoubleLinkedList<>();
this.CAPACITY = capacity;
}
public V get(K key) {
if (map.containsKey(key)) {
Node<K, V> node = map.get(key);
list.moveNodeToTail(node);
return node.value;
}
return null;
}
public void set(K key, V value) {
if (map.containsKey(key)) {
Node<K, V> node = map.get(key);
node.value = value;
list.moveNodeToTail(node);
} else {
Node<K, V> newNode = new Node<>(key, value);
map.put(key, newNode);
list.addNode(newNode);
if (map.size() > CAPACITY) {
removeMostUnusedCache();
}
}
}
private void removeMostUnusedCache() {
Node<K, V> removedNode = list.removeHead();
map.remove(removedNode.key);
}
}
public static void main(String[] args) {
LRUCache<String, Integer> testCache = new LRUCache<>(3);
testCache.set("A", 1);
testCache.set("B", 2);
testCache.set("C", 3);
System.out.println(testCache.get("B"));
System.out.println(testCache.get("A"));
testCache.set("D", 4);
System.out.println(testCache.get("D"));
System.out.println(testCache.get("C"));
}
} | false | 2,582 | 28 | 2,804 | 29 | 2,952 | 29 | 2,804 | 29 | 3,656 | 42 | false | false | false | false | false | true |
58198_8 | /*
时间限制:1秒
空间限制:32768K
大家一定玩过“推箱子”这个经典的游戏。具体规则就是在一个N*M的地图上,有1个玩家、1个箱子、1个目的地以及若干障碍,其余是空地。
玩家可以往上下左右4个方向移动,但是不能移动出地图或者移动到障碍里去。如果往这个方向移动推到了箱子,箱子也会按这个方向移动一格,
当然,箱子也不能被推出地图或推到障碍里。当箱子被推到目的地以后,游戏目标达成。现在告诉你游戏开始是初始的地图布局,
请你求出玩家最少需要移动多少步才能够将游戏目标达成。
输入描述:
每个测试输入包含1个测试用例
第一行输入两个数字N,M表示地图的大小。其中0<N,M<=8。
接下来有N行,每行包含M个字符表示该行地图。其中 . 表示空地、X表示玩家、*表示箱子、#表示障碍、@表示目的地。
每个地图必定包含1个玩家、1个箱子、1个目的地。
输出描述:
输出一个数字表示玩家最少需要移动多少步才能将游戏目标达成。当无论如何达成不了的时候,输出-1。
示例1
输入
4 4
....
..*@
....
.X..
6 6
...#..
......
#*##..
..##.#
..X...
.@#...
输出
3
11
*/
/**
* Approach 1: BFS
* 这道题目一开始把它想得太复杂了。觉得需要不断地去分析箱子和人的相对位置,然后看怎么推,能不能推。
* 然而在写代码的过程中我们可以发现非常重要的一点:
* 箱子的移动方向和人的移动方向是一致的。因此我们只需要对人的移动进行分析即可。
* 在加入了箱子这个因素之后,人的移动结果对于箱子有两种情况:
* 1. 人的下一步移动到了箱子上(人和箱子重合了),此时意味着箱子可以被推动,
* 并且推动的方向与人的移动方向一致。然后我们再根据箱子的位置判断本次移动是否合法。
* 2. 人的下一步并没有移动到箱子上,此时与普通情况下的 BFS 没有任何差别。
* 只需要判断是否会走到障碍物上或者出界即可。
* 为了在 BFS 过程中记录下状态信息,防止陷入死循环,我们需要一个 四维数组visited。
* 分别记录 人的位置信息(x, y) 和 箱子的位置信息(bx, by)
*
* 时间复杂度:O(n^2)
* 空间复杂度:O(n^4)
*/
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int N = sc.nextInt(), M = sc.nextInt();
char[][] maze = new char[N][M];
for (int i = 0; i < N; i++) {
maze[i] = sc.next().toCharArray();
}
System.out.println(minDistance(maze));
}
sc.close();
}
private static int minDistance(char[][] maze) {
int rows = maze.length, cols = maze[0].length;
int startX = 0, startY = 0, startBX = 0, startBY = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] == 'X') {
startX = i;
startY = j;
} else if (maze[i][j] == '*') {
startBX = i;
startBY = j;
}
}
}
Queue<State> queue = new LinkedList<>();
boolean[][][][] visited = new boolean[rows][cols][rows][cols];
queue.offer(new State(startX, startY, startBX, startBY));
visited[startX][startY][startBX][startBY] = true;
final int[][] DIRS = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int step = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
State curr = queue.poll();
if (maze[curr.bx][curr.by] == '@') {
return step;
}
for (int[] dir : DIRS) {
int nextX = curr.x + dir[0];
int nextY = curr.y + dir[1];
int nextBX = curr.bx;
int nextBY = curr.by;
// 人的下一步遇到障碍物或者走出界直接continue
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || maze[nextX][nextY] == '#') {
continue;
}
// 人的下一步位置与箱子重合,说明人的本次移动可以推动箱子,方向与人移动的方向相同
if (nextX == curr.bx && nextY == curr.by) {
nextBX = curr.bx + dir[0];
nextBY = curr.by + dir[1];
// 不能把箱子推出界或者推到障碍物中去
if (nextBX < 0 || nextBX >= rows || nextBY < 0 || nextBY >= cols || maze[nextBX][nextBY] == '#') {
continue;
}
}
// 如果当前状态还没记录过
if (!visited[nextX][nextY][nextBX][nextBY]) {
queue.offer(new State(nextX, nextY, nextBX, nextBY));
visited[nextX][nextY][nextBX][nextBY] = true;
}
}
}
step++;
}
return -1;
}
static class State {
int x, y;
int bx, by;
public State(int x, int y, int bx, int by) {
this.x = x;
this.y = y;
this.bx = bx;
this.by = by;
}
}
}
/**
* Approach 2: BFS (Record the route)
* 考虑到 Approach 1 中只给出了最佳步数,并没有给出最佳的走法(路径)。
* 但反正都是 BFS 跑一边,把路径记录下来不也挺好的吗?(万一什么时候用到了呢)
* 因此这边提供一个记录路径的做法。
*
* 代码几乎没有修改,只是在 State 中增加了一个 前向指针 prev. 用来指向上一步的状态信息。
* 然后记录下每一步的走法。最后遍历一遍链表,将他们存储下来即可。
*/
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int N = sc.nextInt(), M = sc.nextInt();
char[][] maze = new char[N][M];
for (int i = 0; i < N; i++) {
maze[i] = sc.next().toCharArray();
}
System.out.println(minDistance(maze).size() - 1);
}
sc.close();
}
private static List<State> minDistance(char[][] maze) {
int rows = maze.length, cols = maze[0].length;
int startX = 0, startY = 0, startBX = 0, startBY = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] == 'X') {
startX = i;
startY = j;
} else if (maze[i][j] == '*') {
startBX = i;
startBY = j;
}
}
}
Queue<State> queue = new LinkedList<>();
boolean[][][][] visited = new boolean[rows][cols][rows][cols];
queue.offer(new State(startX, startY, startBX, startBY, null));
visited[startX][startY][startBX][startBY] = true;
State end = null;
final int[][] DIRS = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
while (!queue.isEmpty()) {
State curr = queue.poll();
if (maze[curr.bx][curr.by] == '@') {
end = curr;
break;
}
for (int[] dir : DIRS) {
int nextX = curr.x + dir[0];
int nextY = curr.y + dir[1];
int nextBX = curr.bx;
int nextBY = curr.by;
// 人的下一步遇到障碍物或者走出界直接continue
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || maze[nextX][nextY] == '#') {
continue;
}
// 人的下一步位置与箱子重合,说明人的本次移动可以推动箱子,方向与人移动的方向相同
if (nextX == curr.bx && nextY == curr.by) {
nextBX = curr.bx + dir[0];
nextBY = curr.by + dir[1];
// 不能把箱子推出界或者推到障碍物中去
if (nextBX < 0 || nextBX >= rows || nextBY < 0 || nextBY >= cols || maze[nextBX][nextBY] == '#') {
continue;
}
}
// 如果当前状态还没记录过
if (!visited[nextX][nextY][nextBX][nextBY]) {
queue.offer(new State(nextX, nextY, nextBX, nextBY, curr));
visited[nextX][nextY][nextBX][nextBY] = true;
}
}
}
// 路径结果
List<State> rst = new LinkedList<>();
while (end != null) {
rst.add(0, end);
end = end.prev;
}
return rst;
}
static class State {
int x, y;
int bx, by;
State prev; // 指向前一个状态信息
public State(int x, int y, int bx, int by, State prev) {
this.x = x;
this.y = y;
this.bx = bx;
this.by = by;
this.prev = prev;
}
}
}
| cherryljr/NowCoder | 网易_推箱子.java | 2,668 | // 人的下一步位置与箱子重合,说明人的本次移动可以推动箱子,方向与人移动的方向相同 | line_comment | zh-cn | /*
时间限制:1秒
空间限制:32768K
大家一定玩过“推箱子”这个经典的游戏。具体规则就是在一个N*M的地图上,有1个玩家、1个箱子、1个目的地以及若干障碍,其余是空地。
玩家可以往上下左右4个方向移动,但是不能移动出地图或者移动到障碍里去。如果往这个方向移动推到了箱子,箱子也会按这个方向移动一格,
当然,箱子也不能被推出地图或推到障碍里。当箱子被推到目的地以后,游戏目标达成。现在告诉你游戏开始是初始的地图布局,
请你求出玩家最少需要移动多少步才能够将游戏目标达成。
输入描述:
每个测试输入包含1个测试用例
第一行输入两个数字N,M表示地图的大小。其中0<N,M<=8。
接下来有N行,每行包含M个字符表示该行地图。其中 . 表示空地、X表示玩家、*表示箱子、#表示障碍、@表示目的地。
每个地图必定包含1个玩家、1个箱子、1个目的地。
输出描述:
输出一个数字表示玩家最少需要移动多少步才能将游戏目标达成。当无论如何达成不了的时候,输出-1。
示例1
输入
4 4
....
..*@
....
.X..
6 6
...#..
......
#*##..
..##.#
..X...
.@#...
输出
3
11
*/
/**
* Approach 1: BFS
* 这道题目一开始把它想得太复杂了。觉得需要不断地去分析箱子和人的相对位置,然后看怎么推,能不能推。
* 然而在写代码的过程中我们可以发现非常重要的一点:
* 箱子的移动方向和人的移动方向是一致的。因此我们只需要对人的移动进行分析即可。
* 在加入了箱子这个因素之后,人的移动结果对于箱子有两种情况:
* 1. 人的下一步移动到了箱子上(人和箱子重合了),此时意味着箱子可以被推动,
* 并且推动的方向与人的移动方向一致。然后我们再根据箱子的位置判断本次移动是否合法。
* 2. 人的下一步并没有移动到箱子上,此时与普通情况下的 BFS 没有任何差别。
* 只需要判断是否会走到障碍物上或者出界即可。
* 为了在 BFS 过程中记录下状态信息,防止陷入死循环,我们需要一个 四维数组visited。
* 分别记录 人的位置信息(x, y) 和 箱子的位置信息(bx, by)
*
* 时间复杂度:O(n^2)
* 空间复杂度:O(n^4)
*/
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int N = sc.nextInt(), M = sc.nextInt();
char[][] maze = new char[N][M];
for (int i = 0; i < N; i++) {
maze[i] = sc.next().toCharArray();
}
System.out.println(minDistance(maze));
}
sc.close();
}
private static int minDistance(char[][] maze) {
int rows = maze.length, cols = maze[0].length;
int startX = 0, startY = 0, startBX = 0, startBY = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] == 'X') {
startX = i;
startY = j;
} else if (maze[i][j] == '*') {
startBX = i;
startBY = j;
}
}
}
Queue<State> queue = new LinkedList<>();
boolean[][][][] visited = new boolean[rows][cols][rows][cols];
queue.offer(new State(startX, startY, startBX, startBY));
visited[startX][startY][startBX][startBY] = true;
final int[][] DIRS = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
int step = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
State curr = queue.poll();
if (maze[curr.bx][curr.by] == '@') {
return step;
}
for (int[] dir : DIRS) {
int nextX = curr.x + dir[0];
int nextY = curr.y + dir[1];
int nextBX = curr.bx;
int nextBY = curr.by;
// 人的下一步遇到障碍物或者走出界直接continue
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || maze[nextX][nextY] == '#') {
continue;
}
// 人的下一步位置与箱子重合,说明人的本次移动可以推动箱子,方向与人移动的方向相同
if (nextX == curr.bx && nextY == curr.by) {
nextBX = curr.bx + dir[0];
nextBY = curr.by + dir[1];
// 不能把箱子推出界或者推到障碍物中去
if (nextBX < 0 || nextBX >= rows || nextBY < 0 || nextBY >= cols || maze[nextBX][nextBY] == '#') {
continue;
}
}
// 如果当前状态还没记录过
if (!visited[nextX][nextY][nextBX][nextBY]) {
queue.offer(new State(nextX, nextY, nextBX, nextBY));
visited[nextX][nextY][nextBX][nextBY] = true;
}
}
}
step++;
}
return -1;
}
static class State {
int x, y;
int bx, by;
public State(int x, int y, int bx, int by) {
this.x = x;
this.y = y;
this.bx = bx;
this.by = by;
}
}
}
/**
* Approach 2: BFS (Record the route)
* 考虑到 Approach 1 中只给出了最佳步数,并没有给出最佳的走法(路径)。
* 但反正都是 BFS 跑一边,把路径记录下来不也挺好的吗?(万一什么时候用到了呢)
* 因此这边提供一个记录路径的做法。
*
* 代码几乎没有修改,只是在 State 中增加了一个 前向指针 prev. 用来指向上一步的状态信息。
* 然后记录下每一步的走法。最后遍历一遍链表,将他们存储下来即可。
*/
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int N = sc.nextInt(), M = sc.nextInt();
char[][] maze = new char[N][M];
for (int i = 0; i < N; i++) {
maze[i] = sc.next().toCharArray();
}
System.out.println(minDistance(maze).size() - 1);
}
sc.close();
}
private static List<State> minDistance(char[][] maze) {
int rows = maze.length, cols = maze[0].length;
int startX = 0, startY = 0, startBX = 0, startBY = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (maze[i][j] == 'X') {
startX = i;
startY = j;
} else if (maze[i][j] == '*') {
startBX = i;
startBY = j;
}
}
}
Queue<State> queue = new LinkedList<>();
boolean[][][][] visited = new boolean[rows][cols][rows][cols];
queue.offer(new State(startX, startY, startBX, startBY, null));
visited[startX][startY][startBX][startBY] = true;
State end = null;
final int[][] DIRS = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
while (!queue.isEmpty()) {
State curr = queue.poll();
if (maze[curr.bx][curr.by] == '@') {
end = curr;
break;
}
for (int[] dir : DIRS) {
int nextX = curr.x + dir[0];
int nextY = curr.y + dir[1];
int nextBX = curr.bx;
int nextBY = curr.by;
// 人的下一步遇到障碍物或者走出界直接continue
if (nextX < 0 || nextX >= rows || nextY < 0 || nextY >= cols || maze[nextX][nextY] == '#') {
continue;
}
// 人的 <SUF>
if (nextX == curr.bx && nextY == curr.by) {
nextBX = curr.bx + dir[0];
nextBY = curr.by + dir[1];
// 不能把箱子推出界或者推到障碍物中去
if (nextBX < 0 || nextBX >= rows || nextBY < 0 || nextBY >= cols || maze[nextBX][nextBY] == '#') {
continue;
}
}
// 如果当前状态还没记录过
if (!visited[nextX][nextY][nextBX][nextBY]) {
queue.offer(new State(nextX, nextY, nextBX, nextBY, curr));
visited[nextX][nextY][nextBX][nextBY] = true;
}
}
}
// 路径结果
List<State> rst = new LinkedList<>();
while (end != null) {
rst.add(0, end);
end = end.prev;
}
return rst;
}
static class State {
int x, y;
int bx, by;
State prev; // 指向前一个状态信息
public State(int x, int y, int bx, int by, State prev) {
this.x = x;
this.y = y;
this.bx = bx;
this.by = by;
this.prev = prev;
}
}
}
| false | 2,327 | 24 | 2,668 | 30 | 2,614 | 26 | 2,668 | 30 | 3,576 | 49 | false | false | false | false | false | true |
58526_2 | // copy from https://bbs.pediy.com/thread-250714.htm
// copyright @ newx
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.MessageDigest;
import java.util.HashMap;
public class GetDBKey {
public static void main(String[] args) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("CompatibleInfo.cfg"));
Object DL = in.readObject();
HashMap hashWithOutFormat = (HashMap) DL;
String s = String.valueOf(hashWithOutFormat.get(Integer.valueOf(258))); // 取手机的IMEI
System.out.println("IMEI:"+s);
ObjectInputStream in1 = new ObjectInputStream(new FileInputStream("systemInfo.cfg"));
Object DJ = in1.readObject();
HashMap hashWithOutFormat1 = (HashMap) DJ;
String t = String.valueOf(hashWithOutFormat1.get(Integer.valueOf(1))); // 取微信的uin
System.out.println("uin:"+t);
s = s + t; //合并到一个字符串
s = encode(s); // MD5
System.out.println("密码是 : " + s.substring(0, 7));
in.close();
in1.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String encode(String content)
{
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(content.getBytes());
return getEncode32(digest);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private static String getEncode32(MessageDigest digest)
{
StringBuilder builder = new StringBuilder();
for (byte b : digest.digest())
{
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString(b & 0xf));
}
return builder.toString();
}
}
| chg-hou/EnMicroMsg.db-Password-Cracker | tools/GetDBKey.java | 486 | // 取手机的IMEI | line_comment | zh-cn | // copy from https://bbs.pediy.com/thread-250714.htm
// copyright @ newx
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.security.MessageDigest;
import java.util.HashMap;
public class GetDBKey {
public static void main(String[] args) {
try {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("CompatibleInfo.cfg"));
Object DL = in.readObject();
HashMap hashWithOutFormat = (HashMap) DL;
String s = String.valueOf(hashWithOutFormat.get(Integer.valueOf(258))); // 取手 <SUF>
System.out.println("IMEI:"+s);
ObjectInputStream in1 = new ObjectInputStream(new FileInputStream("systemInfo.cfg"));
Object DJ = in1.readObject();
HashMap hashWithOutFormat1 = (HashMap) DJ;
String t = String.valueOf(hashWithOutFormat1.get(Integer.valueOf(1))); // 取微信的uin
System.out.println("uin:"+t);
s = s + t; //合并到一个字符串
s = encode(s); // MD5
System.out.println("密码是 : " + s.substring(0, 7));
in.close();
in1.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static String encode(String content)
{
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(content.getBytes());
return getEncode32(digest);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
private static String getEncode32(MessageDigest digest)
{
StringBuilder builder = new StringBuilder();
for (byte b : digest.digest())
{
builder.append(Integer.toHexString((b >> 4) & 0xf));
builder.append(Integer.toHexString(b & 0xf));
}
return builder.toString();
}
}
| false | 415 | 7 | 486 | 7 | 518 | 6 | 486 | 7 | 565 | 8 | false | false | false | false | false | true |
21295_12 | package 映射;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
public class _01_Two_Sum {
public static int[] twoSum(int[] nums, int target) {
// 這個方法不行喔
// HashMap<Integer, Integer> map = new HashMap<>();
// for (int i = 0; i < nums.length; i++) {
// map.put(nums[i],i);
// }
//map 在[3,3]時候 會只剩下{{3,1}}
// for (Integer key : map.keySet()){
// int other = target - key;
//所以這個一定不會成立 !map.get(key).equals(map.get(other))
// if (map.containsKey(other) && !map.get(key).equals(map.get(other))){
// return new int[]{map.get(key),map.get(other)};
// }
// }
// return new int[]{-1,-1};
//所以一定要用下面的方法
int n = nums.length;
HashMap<Integer, Integer> index = new HashMap<>();
// 构造一个哈希表:元素映射到相应的索引
for (int i = 0; i < n; i++)
index.put(nums[i], i);//一樣會是index 在[3,3]時候 會只剩下{{3,1}}
for (int i = 0; i < n; i++) {
//但是永遠都是從第一個開始遍歷 所以一定會跟map中被覆蓋的參數不一樣的下標
int other = target - nums[i];
// 如果 other 存在且不是 nums[i] 本身 這個才會成立 index.get(other) != i
if (index.containsKey(other) && index.get(other) != i)
return new int[]{i, index.get(other)};
}
return new int[]{-1, -1};
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[]{3, 3}, 6)));
}
}
| chianglianglin/jackson_Data_Structure | 00_leetcode/src/映射/_01_Two_Sum.java | 555 | // 构造一个哈希表:元素映射到相应的索引 | line_comment | zh-cn | package 映射;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.HashMap;
public class _01_Two_Sum {
public static int[] twoSum(int[] nums, int target) {
// 這個方法不行喔
// HashMap<Integer, Integer> map = new HashMap<>();
// for (int i = 0; i < nums.length; i++) {
// map.put(nums[i],i);
// }
//map 在[3,3]時候 會只剩下{{3,1}}
// for (Integer key : map.keySet()){
// int other = target - key;
//所以這個一定不會成立 !map.get(key).equals(map.get(other))
// if (map.containsKey(other) && !map.get(key).equals(map.get(other))){
// return new int[]{map.get(key),map.get(other)};
// }
// }
// return new int[]{-1,-1};
//所以一定要用下面的方法
int n = nums.length;
HashMap<Integer, Integer> index = new HashMap<>();
// 构造 <SUF>
for (int i = 0; i < n; i++)
index.put(nums[i], i);//一樣會是index 在[3,3]時候 會只剩下{{3,1}}
for (int i = 0; i < n; i++) {
//但是永遠都是從第一個開始遍歷 所以一定會跟map中被覆蓋的參數不一樣的下標
int other = target - nums[i];
// 如果 other 存在且不是 nums[i] 本身 這個才會成立 index.get(other) != i
if (index.containsKey(other) && index.get(other) != i)
return new int[]{i, index.get(other)};
}
return new int[]{-1, -1};
}
public static void main(String[] args) {
System.out.println(Arrays.toString(twoSum(new int[]{3, 3}, 6)));
}
}
| false | 448 | 16 | 555 | 14 | 514 | 12 | 555 | 14 | 670 | 26 | false | false | false | false | false | true |
9360_1 | package instruction;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
public class MethodHandlerTest {
static class MyPrinter {
public void println(String msg) {
System.out.println(msg);
}
}
private static void test(Object obj) throws Throwable {
// 描述方法的返回值,参数类型
MethodType methodType = MethodType.methodType(void.class, String.class);
// 在指定类中查找符合给定的方法名称、方法返回值、参数类型的方法
// 因为调用的是成员方法,成员方法都有一个隐含参数,也就是方法的调用者,通过 bingTo 传递过去
MethodHandle methodHandle = MethodHandles.lookup()
.findVirtual(obj.getClass(), "println", methodType)
.bindTo(obj);
// 通过 MethodHandler 调用方法
methodHandle.invokeExact("chiclaim");
}
private static void test2(Object obj) throws Throwable {
Class clazz = obj.getClass();
Method method = clazz.getDeclaredMethod("println", String.class);
method.invoke(obj, "chiclaim");
}
public static void main(String[] args) throws Throwable {
test(System.out); // PrintStream
test(new MyPrinter()); // MyPrinter
System.out.println();
test2(System.out); // PrintStream
test2(new MyPrinter()); // MyPrinter
}
}
| chiclaim/AndroidAll | language-java/jvm/jvm-sample/src/instruction/MethodHandlerTest.java | 353 | // 在指定类中查找符合给定的方法名称、方法返回值、参数类型的方法 | line_comment | zh-cn | package instruction;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;
public class MethodHandlerTest {
static class MyPrinter {
public void println(String msg) {
System.out.println(msg);
}
}
private static void test(Object obj) throws Throwable {
// 描述方法的返回值,参数类型
MethodType methodType = MethodType.methodType(void.class, String.class);
// 在指 <SUF>
// 因为调用的是成员方法,成员方法都有一个隐含参数,也就是方法的调用者,通过 bingTo 传递过去
MethodHandle methodHandle = MethodHandles.lookup()
.findVirtual(obj.getClass(), "println", methodType)
.bindTo(obj);
// 通过 MethodHandler 调用方法
methodHandle.invokeExact("chiclaim");
}
private static void test2(Object obj) throws Throwable {
Class clazz = obj.getClass();
Method method = clazz.getDeclaredMethod("println", String.class);
method.invoke(obj, "chiclaim");
}
public static void main(String[] args) throws Throwable {
test(System.out); // PrintStream
test(new MyPrinter()); // MyPrinter
System.out.println();
test2(System.out); // PrintStream
test2(new MyPrinter()); // MyPrinter
}
}
| false | 313 | 19 | 353 | 19 | 366 | 18 | 353 | 19 | 461 | 34 | false | false | false | false | false | true |
29025_1 | package tutorials.lesson27;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 滥用 Checked Exception
*
* @author kumushuoshuo
* @github https://github.com/chiclaim/
*/
public class JavaAbusedCheckedException {
// 抛出长长的异常列表
void case1() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
FileNotFoundException, ClassNotFoundException {
ThrowsTest.test1();
ThrowsTest.test2();
ThrowsTest.test3();
ThrowsTest.test4();
}
// 为了避免长长的异常列表,可能会这样做:
void case2() throws Throwable {
ThrowsTest.test1();
ThrowsTest.test2();
ThrowsTest.test3();
ThrowsTest.test4();
}
// 如果不对外抛出异常,可能会直接 try...catch 异常,避免
void case3() {
try {
ThrowsTest.test1();
ThrowsTest.test2();
ThrowsTest.test3();
ThrowsTest.test4();
} catch (Throwable t) {
t.printStackTrace();
}
}
// 我们知道不会抛出异常,但是也不得不 try...catch
// ByteArrayInputStream
void test4() {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
} | chiclaim/KotlinTutorials | kotlin-in-action/src/main/java/tutorials/lesson27/JavaAbusedCheckedException.java | 370 | // 抛出长长的异常列表 | line_comment | zh-cn | package tutorials.lesson27;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 滥用 Checked Exception
*
* @author kumushuoshuo
* @github https://github.com/chiclaim/
*/
public class JavaAbusedCheckedException {
// 抛出 <SUF>
void case1() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException,
FileNotFoundException, ClassNotFoundException {
ThrowsTest.test1();
ThrowsTest.test2();
ThrowsTest.test3();
ThrowsTest.test4();
}
// 为了避免长长的异常列表,可能会这样做:
void case2() throws Throwable {
ThrowsTest.test1();
ThrowsTest.test2();
ThrowsTest.test3();
ThrowsTest.test4();
}
// 如果不对外抛出异常,可能会直接 try...catch 异常,避免
void case3() {
try {
ThrowsTest.test1();
ThrowsTest.test2();
ThrowsTest.test3();
ThrowsTest.test4();
} catch (Throwable t) {
t.printStackTrace();
}
}
// 我们知道不会抛出异常,但是也不得不 try...catch
// ByteArrayInputStream
void test4() {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
} | false | 317 | 8 | 370 | 10 | 390 | 8 | 370 | 10 | 501 | 15 | false | false | false | false | false | true |
30010_2 | package exception;
/**
* https://juejin.cn/post/6844903446185951240
* https://zhuanlan.zhihu.com/p/143282333
* {try}-with-resources关键点
* 1. 由带资源的try语句管理的资源必须是实现了AutoCloseable接口的类的对象
* 2. 在try代码中声明的资源被隐式声明为final
* 3. 通过使用分号分隔每个声明可以管理多个资源
*/
public class TryWithResource {
public static void main(String[] args) {
try (Connection conn = new Connection()) {
conn.sendData();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/** 配合try-with-resource,资源必须实现AutoClosable接口。该接口的实现类需要重写close方法
* Closeable 和 AutoCloseable
* AutoCloseable 是 Java 7 新增的接口,Closeable 早就有了. 二者的关系是 Closeable extends AutoCloseable, 二者都仅包含一个 close() 方法, 那么为什么 Java 7 还要新增 AutoCloseable 接口呢?
* Closeable 在 java.io 包下, 主要用于 IO 相关的资源的关闭, 其 close() 方法定义了抛出 IOException 异常, 其实现类实现 close() 方法时, 不允许抛出除 IOException、 RuntimeException 外其他类型的异常.
* AutoCloseable 位于 java.lang 包下, 使用更广泛, 其 close() 方法定义是 void close() throws Exception, 就是它的实现类的 close() 方法对异常抛出是没有限制的。
*/
class Connection implements AutoCloseable {
/**
* 由于一次只能抛出一个异常,所以在最上层看到的是最后一个抛出的异常——也就是close方法抛出的MyException,而sendData抛出的Exception被忽略了。这就是所谓的异常屏蔽。
* 由于异常信息的丢失,异常屏蔽可能会导致某些bug变得极其难以发现,从Java 1.7开始,Throwable类新增了 addSuppressed 方法,支持将一个异常附加到另一个异常身上,从而避免异常屏蔽。
*/
public void sendData() throws Exception {
System.out.println("正在发送数据");
throw new Exception("doSomething exception");
}
@Override
public void close() throws Exception {
System.out.println("正在关闭连接");
throw new Exception("close exception");
}
}
| china-bear/Java_Learning | code/basic/src/main/java/exception/TryWithResource.java | 590 | /**
* 由于一次只能抛出一个异常,所以在最上层看到的是最后一个抛出的异常——也就是close方法抛出的MyException,而sendData抛出的Exception被忽略了。这就是所谓的异常屏蔽。
* 由于异常信息的丢失,异常屏蔽可能会导致某些bug变得极其难以发现,从Java 1.7开始,Throwable类新增了 addSuppressed 方法,支持将一个异常附加到另一个异常身上,从而避免异常屏蔽。
*/ | block_comment | zh-cn | package exception;
/**
* https://juejin.cn/post/6844903446185951240
* https://zhuanlan.zhihu.com/p/143282333
* {try}-with-resources关键点
* 1. 由带资源的try语句管理的资源必须是实现了AutoCloseable接口的类的对象
* 2. 在try代码中声明的资源被隐式声明为final
* 3. 通过使用分号分隔每个声明可以管理多个资源
*/
public class TryWithResource {
public static void main(String[] args) {
try (Connection conn = new Connection()) {
conn.sendData();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/** 配合try-with-resource,资源必须实现AutoClosable接口。该接口的实现类需要重写close方法
* Closeable 和 AutoCloseable
* AutoCloseable 是 Java 7 新增的接口,Closeable 早就有了. 二者的关系是 Closeable extends AutoCloseable, 二者都仅包含一个 close() 方法, 那么为什么 Java 7 还要新增 AutoCloseable 接口呢?
* Closeable 在 java.io 包下, 主要用于 IO 相关的资源的关闭, 其 close() 方法定义了抛出 IOException 异常, 其实现类实现 close() 方法时, 不允许抛出除 IOException、 RuntimeException 外其他类型的异常.
* AutoCloseable 位于 java.lang 包下, 使用更广泛, 其 close() 方法定义是 void close() throws Exception, 就是它的实现类的 close() 方法对异常抛出是没有限制的。
*/
class Connection implements AutoCloseable {
/**
* 由于一 <SUF>*/
public void sendData() throws Exception {
System.out.println("正在发送数据");
throw new Exception("doSomething exception");
}
@Override
public void close() throws Exception {
System.out.println("正在关闭连接");
throw new Exception("close exception");
}
}
| false | 550 | 102 | 590 | 123 | 561 | 100 | 590 | 123 | 888 | 226 | false | false | false | false | false | true |
57832_19 | /**
*
* GFW.Press
* Copyright (C) 2016 chinashiyu ( chinashiyu@gfw.press ; http://gfw.press )
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
**/
package press.gfw;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.crypto.SecretKey;
import javax.net.ServerSocketFactory;
import org.json.simple.JSONObject;
/**
*
* GFW.Press服务器
*
* @author chinashiyu ( chinashiyu@gfw.press ; http://gfw.press )
*
*/
public class Server extends Thread {
public static void main(String[] args) throws IOException {
Server server = new Server();
server.service();
}
private File lockFile = null;
private String proxyHost = "127.0.0.1"; // 默认为本机地址
private int proxyPort = 3128; // 默认为HTTP代理标准端口
private int listenPort = 0;
private String password = null;
private SecretKey key = null;
private Encrypt encrypt = null;
private boolean kill = false;
private Config config = null;
private ServerSocket serverSocket = null;
/**
* 构造方法,主线程
*/
public Server() {
lockFile = new File("server.lock");
config = new Config();
loadConfig(); // 获取配置参数
}
/**
* 构造方法,用户线程
*
* @param proxyHost
* @param proxyPort
* @param listenPort
* @param password
*/
public Server(String proxyHost, int proxyPort, int listenPort, String password) {
super();
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.listenPort = listenPort;
this.password = password;
encrypt = new Encrypt();
if (encrypt.isPassword(this.password)) {
key = encrypt.getPasswordKey(this.password);
}
}
/**
* 构造方法,用户线程
*
* @param proxyHost
* @param proxyPort
* @param listenPort
* @param password
*/
public Server(String proxyHost, int proxyPort, String listenPort, String password) {
this(proxyHost, proxyPort, (listenPort != null && (listenPort = listenPort.trim()).matches("\\d+")) ? Integer.valueOf(listenPort) : 0, password);
}
/**
* 暂停
*
* @param m
*/
private void _sleep(long m) {
try {
sleep(m);
} catch (InterruptedException ie) {
}
}
/**
* 获取密码
*
* @return
*/
public synchronized String getPassword() {
return password;
}
/**
* @return the kill
*/
public synchronized boolean isKill() {
return kill;
}
public synchronized void kill() {
kill = true;
if (serverSocket != null && !serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException ex) {
}
serverSocket = null;
}
}
/**
* 获取配置参数
*/
private void loadConfig() {
JSONObject json = config.getServerConfig();
if (json != null) {
String _proxyHost = (String) json.get("ProxyHost");
proxyHost = (_proxyHost == null || (_proxyHost = _proxyHost.trim()).length() == 0) ? proxyHost : _proxyHost;
String _proxyPort = (String) json.get("ProxyPort");
proxyPort = (_proxyPort == null || !(_proxyPort = _proxyPort.trim()).matches("\\d+")) ? proxyPort : Integer.valueOf(_proxyPort);
}
}
/**
* 打印信息
*
* @param o
*/
private void log(Object o) {
String time = (new Timestamp(System.currentTimeMillis())).toString().substring(0, 19);
System.out.println("[" + time + "] " + o.toString());
}
/**
* 用户线程
*/
@Override
@SuppressWarnings("preview")
public void run() {
// log("监听端口:" + listenPort);
if (encrypt == null || listenPort < 1024 || listenPort > 65536) {
kill = true;
log("监听端口:" + listenPort + " 线程参数不符合条件,线程结束。");
return;
}
try {
serverSocket = ServerSocketFactory.getDefault().createServerSocket(listenPort);
} catch (IOException ex) {
kill = true;
log("监听端口:" + listenPort + " 线程启动时出错,线程结束。");
return;
}
while (!kill) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
if (kill) {
break;
}
if (serverSocket != null && !serverSocket.isClosed()) {
log("监听端口:" + listenPort + " 线程运行时出错,暂停3秒钟后重试。");
_sleep(3000L);
continue;
} else {
log("监听端口:" + listenPort + " 线程运行时出错,线程结束。");
break;
}
}
ServerThread serverThread = new ServerThread(clientSocket, proxyHost, proxyPort, key);
// startVirtualThread(serverThread);
serverThread.start();
}
kill = true;
if (serverSocket != null && !serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException ex) {
}
serverSocket = null;
}
}
/**
* 主线程
*/
@SuppressWarnings("preview")
public void service() {
if (System.currentTimeMillis() - lockFile.lastModified() < 30 * 1000L) {
log("服务器已经在运行中");
log("如果确定没有运行,请删除 " + lockFile.getAbsolutePath() + "文件,重新启动");
return;
}
try {
lockFile.createNewFile();
} catch (IOException ioe) {
}
lockFile.deleteOnExit();
log("GFW.Press服务器开始运行......");
log("代理主机:" + proxyHost);
log("代理端口:" + proxyPort);
Hashtable<String, String> users = null; // 用户
Hashtable<String, Server> threads = new Hashtable<>(); // 用户线程
while (true) {
lockFile.setLastModified(System.currentTimeMillis());
users = config.getUser(); // 获取用户列表
if (users == null || users.size() == 0) {
_sleep(10 * 1000L); // 暂停10秒
continue;
}
Enumeration<String> threadPorts = threads.keys(); // 用户线程的所有端口
while (threadPorts.hasMoreElements()) { // 删除用户及修改密码处理
String threadPort = threadPorts.nextElement();
String userPassword = users.remove(threadPort);
if (userPassword == null) { // 用户已删除
threads.remove(threadPort).kill();
log("删除用户,端口:" + threadPort);
} else {
Server thread = threads.get(threadPort);
if (!userPassword.equals(thread.getPassword())) { // 用户改密码
log("修改密码,端口:" + threadPort);
threads.remove(threadPort);
thread.kill();
thread = new Server(proxyHost, proxyPort, threadPort, userPassword);
threads.put(threadPort, thread);
// startVirtualThread(thread);
thread.start();
}
}
}
Enumeration<String> userPorts = users.keys();
while (userPorts.hasMoreElements()) { // 新用户
String userPort = userPorts.nextElement();
Server thread = new Server(proxyHost, proxyPort, userPort, users.get(userPort));
threads.put(userPort, thread);
// startVirtualThread(thread);
thread.start();
}
users.clear();
_sleep(20 * 1000L); // 暂停20秒
}
}
}
| chinashiyu/gfw.press | src/press/gfw/Server.java | 2,244 | // 暂停10秒 | line_comment | zh-cn | /**
*
* GFW.Press
* Copyright (C) 2016 chinashiyu ( chinashiyu@gfw.press ; http://gfw.press )
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
**/
package press.gfw;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Timestamp;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.crypto.SecretKey;
import javax.net.ServerSocketFactory;
import org.json.simple.JSONObject;
/**
*
* GFW.Press服务器
*
* @author chinashiyu ( chinashiyu@gfw.press ; http://gfw.press )
*
*/
public class Server extends Thread {
public static void main(String[] args) throws IOException {
Server server = new Server();
server.service();
}
private File lockFile = null;
private String proxyHost = "127.0.0.1"; // 默认为本机地址
private int proxyPort = 3128; // 默认为HTTP代理标准端口
private int listenPort = 0;
private String password = null;
private SecretKey key = null;
private Encrypt encrypt = null;
private boolean kill = false;
private Config config = null;
private ServerSocket serverSocket = null;
/**
* 构造方法,主线程
*/
public Server() {
lockFile = new File("server.lock");
config = new Config();
loadConfig(); // 获取配置参数
}
/**
* 构造方法,用户线程
*
* @param proxyHost
* @param proxyPort
* @param listenPort
* @param password
*/
public Server(String proxyHost, int proxyPort, int listenPort, String password) {
super();
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
this.listenPort = listenPort;
this.password = password;
encrypt = new Encrypt();
if (encrypt.isPassword(this.password)) {
key = encrypt.getPasswordKey(this.password);
}
}
/**
* 构造方法,用户线程
*
* @param proxyHost
* @param proxyPort
* @param listenPort
* @param password
*/
public Server(String proxyHost, int proxyPort, String listenPort, String password) {
this(proxyHost, proxyPort, (listenPort != null && (listenPort = listenPort.trim()).matches("\\d+")) ? Integer.valueOf(listenPort) : 0, password);
}
/**
* 暂停
*
* @param m
*/
private void _sleep(long m) {
try {
sleep(m);
} catch (InterruptedException ie) {
}
}
/**
* 获取密码
*
* @return
*/
public synchronized String getPassword() {
return password;
}
/**
* @return the kill
*/
public synchronized boolean isKill() {
return kill;
}
public synchronized void kill() {
kill = true;
if (serverSocket != null && !serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException ex) {
}
serverSocket = null;
}
}
/**
* 获取配置参数
*/
private void loadConfig() {
JSONObject json = config.getServerConfig();
if (json != null) {
String _proxyHost = (String) json.get("ProxyHost");
proxyHost = (_proxyHost == null || (_proxyHost = _proxyHost.trim()).length() == 0) ? proxyHost : _proxyHost;
String _proxyPort = (String) json.get("ProxyPort");
proxyPort = (_proxyPort == null || !(_proxyPort = _proxyPort.trim()).matches("\\d+")) ? proxyPort : Integer.valueOf(_proxyPort);
}
}
/**
* 打印信息
*
* @param o
*/
private void log(Object o) {
String time = (new Timestamp(System.currentTimeMillis())).toString().substring(0, 19);
System.out.println("[" + time + "] " + o.toString());
}
/**
* 用户线程
*/
@Override
@SuppressWarnings("preview")
public void run() {
// log("监听端口:" + listenPort);
if (encrypt == null || listenPort < 1024 || listenPort > 65536) {
kill = true;
log("监听端口:" + listenPort + " 线程参数不符合条件,线程结束。");
return;
}
try {
serverSocket = ServerSocketFactory.getDefault().createServerSocket(listenPort);
} catch (IOException ex) {
kill = true;
log("监听端口:" + listenPort + " 线程启动时出错,线程结束。");
return;
}
while (!kill) {
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException ex) {
if (kill) {
break;
}
if (serverSocket != null && !serverSocket.isClosed()) {
log("监听端口:" + listenPort + " 线程运行时出错,暂停3秒钟后重试。");
_sleep(3000L);
continue;
} else {
log("监听端口:" + listenPort + " 线程运行时出错,线程结束。");
break;
}
}
ServerThread serverThread = new ServerThread(clientSocket, proxyHost, proxyPort, key);
// startVirtualThread(serverThread);
serverThread.start();
}
kill = true;
if (serverSocket != null && !serverSocket.isClosed()) {
try {
serverSocket.close();
} catch (IOException ex) {
}
serverSocket = null;
}
}
/**
* 主线程
*/
@SuppressWarnings("preview")
public void service() {
if (System.currentTimeMillis() - lockFile.lastModified() < 30 * 1000L) {
log("服务器已经在运行中");
log("如果确定没有运行,请删除 " + lockFile.getAbsolutePath() + "文件,重新启动");
return;
}
try {
lockFile.createNewFile();
} catch (IOException ioe) {
}
lockFile.deleteOnExit();
log("GFW.Press服务器开始运行......");
log("代理主机:" + proxyHost);
log("代理端口:" + proxyPort);
Hashtable<String, String> users = null; // 用户
Hashtable<String, Server> threads = new Hashtable<>(); // 用户线程
while (true) {
lockFile.setLastModified(System.currentTimeMillis());
users = config.getUser(); // 获取用户列表
if (users == null || users.size() == 0) {
_sleep(10 * 1000L); // 暂停 <SUF>
continue;
}
Enumeration<String> threadPorts = threads.keys(); // 用户线程的所有端口
while (threadPorts.hasMoreElements()) { // 删除用户及修改密码处理
String threadPort = threadPorts.nextElement();
String userPassword = users.remove(threadPort);
if (userPassword == null) { // 用户已删除
threads.remove(threadPort).kill();
log("删除用户,端口:" + threadPort);
} else {
Server thread = threads.get(threadPort);
if (!userPassword.equals(thread.getPassword())) { // 用户改密码
log("修改密码,端口:" + threadPort);
threads.remove(threadPort);
thread.kill();
thread = new Server(proxyHost, proxyPort, threadPort, userPassword);
threads.put(threadPort, thread);
// startVirtualThread(thread);
thread.start();
}
}
}
Enumeration<String> userPorts = users.keys();
while (userPorts.hasMoreElements()) { // 新用户
String userPort = userPorts.nextElement();
Server thread = new Server(proxyHost, proxyPort, userPort, users.get(userPort));
threads.put(userPort, thread);
// startVirtualThread(thread);
thread.start();
}
users.clear();
_sleep(20 * 1000L); // 暂停20秒
}
}
}
| false | 1,993 | 8 | 2,244 | 8 | 2,246 | 6 | 2,244 | 8 | 3,037 | 13 | false | false | false | false | false | true |